Compare commits

..

183 Commits

Author SHA1 Message Date
bc114b6ae0 Merge remote-tracking branch 'origin/Subscription_Plan' into Purchase_Invoice_Management 2025-12-16 11:06:57 +05:30
92a09bfcf0 Handle Date range in Expense Widget on dashboard
Link Project to detail page in Attendance Report Widget
2025-12-15 11:45:43 +05:30
4f9fa1b7c2 Add link to he project from Attendance details widget 2025-12-15 11:08:27 +05:30
34d5ce9ef9 missing request demo links 2025-12-14 17:22:21 +05:30
476fb49e07 adjust sidebar logo size and position from left border 2025-12-14 17:03:12 +05:30
7143af1e1e format DPR page 2025-12-14 16:49:06 +05:30
a477090cb8 Add missing images 2025-12-14 16:07:46 +05:30
f1a5f72db7 modified landing page hero images 2025-12-14 13:27:50 +05:30
e8886577d8 Correction in weidget. 2025-12-13 16:36:47 +05:30
e10a6ff14c Change the design of subscription page. 2025-12-13 14:51:17 +05:30
a309d13247 Correction in teams, projectinfra and daily task for dropdown. 2025-12-13 11:51:16 +05:30
fa694d8361 Correction in Attendance page. 2025-12-13 11:37:53 +05:30
a9bbd75d6c Correction in name of Project by status to Attendance by Project 2025-12-13 11:26:50 +05:30
3ff80ee032 Sorting in Subscription page. 2025-12-13 11:20:16 +05:30
e695807e77 Adding 2025-12-13 11:18:45 +05:30
630c11985d Correction in Subscription page. 2025-12-13 11:18:11 +05:30
d68cb9e664 Merge branch 'main' of https://git.marcoaiot.com/admin/marco.pms.web into Subscription_Plan 2025-12-13 09:59:35 +05:30
caeece0660 Merge branch 'main' of https://git.marcoaiot.com/admin/marco.pms.web into Purchase_Invoice_Management 2025-12-13 09:57:19 +05:30
44f3d8783d Adding additional fields in landing subscription cards. 2025-12-13 09:54:02 +05:30
3a8c1745f4 Removing dropdown logic all the places wehre dropdown is added. 2025-12-12 19:07:55 +05:30
deba5dfa01 Adding View functionality in Add challan. 2025-12-12 18:11:38 +05:30
bb743d2bb0 Adding Submit functionality in tenant. 2025-12-12 17:27:37 +05:30
6f9eeadc22 fixed project list paginantion 2025-12-12 16:22:55 +05:30
6099dd2ea5 fixed logo label on side bar 2025-12-12 15:25:21 +05:30
7b1b360c78 added missing view_all_employee permissions 2025-12-12 10:31:36 +05:30
cdaf642eba added zoom in - out using mouse wheel 2025-12-11 16:01:11 +05:30
b31195c5a1 Adding sorting in Project display. 2025-12-11 11:04:29 +05:30
9daeffd90e Adding formatcurrecny at hover effect at Expense Breakdown. 2025-12-11 10:54:24 +05:30
ab34ea63fa Merge branch 'Purchase_Invoice_Management' of https://git.marcoaiot.com/admin/marco.pms.web into Purchase_Invoice_Management 2025-12-11 10:39:36 +05:30
17ef307ff2 Adding MyJobs at the place of all jobs in service Jobs. 2025-12-11 10:39:32 +05:30
ae9ef7938d fixed : Project created permission for service 2025-12-11 10:37:39 +05:30
e755faecdc fixed: added array guards in mergedServices to stop iterable error 2025-12-11 10:25:45 +05:30
23660379c9 fixed 'ProjectwiseTeamCount' path inside dashboard 2025-12-11 09:51:01 +05:30
2bf5e9a13f Merge branch 'Encrypted_Reponse' into Purchase_Invoice_Management 2025-12-11 09:40:09 +05:30
3413806670 Merge branch 'Encrypted_Reponse' into Purchase_Invoice_Management 2025-12-11 09:39:51 +05:30
8033fdb7e7 selected default current selected service - create task 2025-12-10 16:52:52 +05:30
b62fc82a9c Merge branch 'Purchase_Invoice_Management' of https://git.marcoaiot.com/admin/marco.pms.web into Purchase_Invoice_Management 2025-12-10 16:33:04 +05:30
4253ed71eb modified ui base on suggestion 2025-12-10 16:32:59 +05:30
01fc302011 Merge pull request 'Adding_Chips_DailyTask :- Adding Chips in Daily task report.' (#538) from Adding_Chips_DailyTask into Purchase_Invoice_Management
Reviewed-on: #538
merged
2025-12-10 11:01:16 +00:00
d56aefde02 Adding sizing in manageemployee. 2025-12-10 11:01:16 +00:00
c71fe3a45e Adding dates chips in document. 2025-12-10 11:01:16 +00:00
0f43c877c4 Adding Date picker chips in Expense and 2025-12-10 11:01:16 +00:00
153ffcdc3e Adding w-100 at doument filter panel. 2025-12-10 11:01:16 +00:00
e31e4cfc31 Adding Filter chips at Tenant. 2025-12-10 11:01:16 +00:00
8216bf1f2d Correction in Infra Project Card view. 2025-12-10 11:01:16 +00:00
6b9d7c56bc Adding filter chips in daily Progress Report. 2025-12-10 11:01:16 +00:00
07ba95e533 removed console warning 2025-12-10 12:40:30 +05:30
c1ae9ee55e changed footer 2025-12-10 12:26:43 +05:30
117d82769a Merge branch 'Purchase_Invoice_Management' of https://git.marcoaiot.com/admin/marco.pms.web into dpr-report 2025-12-10 12:16:11 +05:30
35f1aa8c13 hide attendance project wise overview project having selected 2025-12-10 12:12:12 +05:30
cd1ae64753 added attandace poject wise overview 2025-12-10 12:09:53 +05:30
363a9c5feb Merge branch 'Purchase_Invoice_Management' of https://git.marcoaiot.com/admin/marco.pms.web into Purchase_Invoice_Management 2025-12-10 10:32:00 +05:30
69148331f5 added partially proejctwise attendace 2025-12-10 10:31:54 +05:30
1bbc338b9b Merge pull request 'Adding Dashboard a Jobs Weidget.' (#537) from Jobs_Weidget into Purchase_Invoice_Management
Reviewed-on: #537
merged
2025-12-10 05:00:21 +00:00
bc0540a0b7 Adding Dashboard a Jobs Weidget. 2025-12-10 10:27:07 +05:30
65158b9368 added encryption 2025-12-09 16:37:13 +05:30
4a47b1d0fa removed console and added none option for groupping for Expense list 2025-12-09 14:26:18 +05:30
0643d3d0e1 Merge branch 'Purchase_Invoice_Management' of https://git.marcoaiot.com/admin/marco.pms.web into Purchase_Invoice_Management 2025-12-09 12:40:03 +05:30
3a1aac8834 Updation at Projects Completion Status when nothing is zero nothing is show. 2025-12-08 18:13:17 +05:30
8e49d4dc8b added new class for pageView heigt 2025-12-08 16:24:03 +05:30
e10bb10c20 display properly each document 2025-12-08 14:10:00 +05:30
cd9c6d2365 removed color for collection action butttons 2025-12-08 11:43:58 +05:30
0a82297396 fixed updated or archived - service jobs msg 2025-12-08 11:37:14 +05:30
07ab3314f3 Removing Console.log at ViewBranchdetails. 2025-12-08 10:31:54 +05:30
e6a6c8c9e8 Updation in ViewBranchdetails. 2025-12-08 10:03:09 +05:30
3d90eebd44 Increasing the size of plannedwork. 2025-12-06 17:14:07 +05:30
d5582400b0 Changes in EditActivity Modal. 2025-12-06 17:10:36 +05:30
8b3ca8d57a Merge pull request 'Adding_dropdown :- Adding custome dropdown across all the modal.' (#533) from Adding_dropdown into Purchase_Invoice_Management
Reviewed-on: #533
merged
2025-12-06 11:30:46 +00:00
7eb2274584 Resolving Error in EditActivitymodal. 2025-12-06 16:57:14 +05:30
5a8a8c4676 Merge branch 'Purchase_Invoice_Management' of https://git.marcoaiot.com/admin/marco.pms.web into Adding_dropdown 2025-12-06 16:54:54 +05:30
d9c3964983 Merge pull request 'Add Pending Actions toggle near search box in Expense.' (#530) from Adding_Toggle_Button into Purchase_Invoice_Management
Reviewed-on: #530
merged
2025-12-06 11:18:15 +00:00
50e33b7b39 Add Pending Actions toggle near search box in Expense. 2025-12-06 11:18:15 +00:00
d6a8040977 Merge pull request 'Attendance in Employee Profile Should Display Project-Wise' (#531) from Kartik_Enhancement_918 into Purchase_Invoice_Management
Reviewed-on: #531
Merged
2025-12-06 11:14:50 +00:00
95813c5869 Planned Work now accepts values with up to 2 decimal places. 2025-12-06 11:14:50 +00:00
88dc11793c Attendance in Employee Profile Should Display Project-Wise 2025-12-06 11:14:50 +00:00
ca3cc590d2 Merge pull request 'Branch_Detail_View :- Adding details view in jobs.' (#532) from Branch_Detail_View into Purchase_Invoice_Management
Reviewed-on: #532
merged
2025-12-06 11:13:10 +00:00
1e151a8b10 Adding Cursor pointer for view branch in jobs. 2025-12-06 11:13:10 +00:00
946e0b2883 Showing details view in Branches. 2025-12-06 11:13:10 +00:00
baa17ab0cf fixed visile dropdown issue inside master page 2025-12-06 16:42:10 +05:30
7de27cc335 Correction in Master Page. 2025-12-06 16:35:02 +05:30
3c3468f8f9 Correction in EmpProfile. 2025-12-06 16:00:07 +05:30
c4a46cbe80 Merge branch 'Purchase_Invoice_Management' of https://git.marcoaiot.com/admin/marco.pms.web into Adding_dropdown 2025-12-06 15:08:54 +05:30
c83e7eb75f Adding dropdown in Edit Task. 2025-12-06 15:07:18 +05:30
72b533226a Adding dropdown across all places. 2025-12-06 14:49:23 +05:30
48ff718da4 Correction in directory managecontact. 2025-12-06 13:00:35 +05:30
654e34ebfa Adding Dropdown in all places. 2025-12-06 12:58:43 +05:30
c7e72946ea added mission hook 2025-12-06 11:58:09 +05:30
19c8975e8f added margin bottom for selectField 2025-12-06 11:30:32 +05:30
1f64cf65f9 Merge branch 'Adding_dropdown' of https://git.marcoaiot.com/admin/marco.pms.web into Adding_dropdown 2025-12-06 11:12:35 +05:30
29cebedfad fixed selectfield ui 2025-12-06 11:12:25 +05:30
a1680c709a Adding dropdown in Daily task. 2025-12-06 10:22:24 +05:30
0e75a3e1c9 Adding Dropdown in Employee. 2025-12-06 10:11:58 +05:30
cdf9bbbe48 added padding to better space 2025-12-06 09:48:15 +05:30
94fbeef5d1 added skeleton 2025-12-05 19:32:23 +05:30
88053d1286 added optional chain for handle error 2025-12-05 18:55:23 +05:30
96bcdffdca added optional chain for n=menu 2025-12-05 18:45:19 +05:30
23a7a56e32 added collection overview widget 2025-12-05 18:24:23 +05:30
dbf4f5e9c8 Adding New dropdown in across all modules. 2025-12-05 17:57:08 +05:30
7df9d47f07 Adding dropdown in directory. 2025-12-05 15:40:38 +05:30
8f6d877548 removed scrolling inside job - status logs 2025-12-05 12:05:55 +05:30
7930876b7d Merge pull request 'Adding time line in Jobs Status.' (#527) from Implementing_TimeLine into Purchase_Invoice_Management
Reviewed-on: #52
merged
2025-12-05 06:23:55 +00:00
b8f2607b45 Adding Workdone label. 2025-12-05 06:23:55 +00:00
47752e5e35 Adding time line in Jobs Status. 2025-12-05 06:23:55 +00:00
25bb7d1f58 allow view pdf file 2025-12-05 11:38:54 +05:30
427d728efc Merge pull request 'Adding Tabs in attendancepage just like View Jobs.' (#529) from Attendance_Tabs into Purchase_Invoice_Management
Reviewed-on: #529
Merged
2025-12-05 04:49:16 +00:00
65043732d3 Adding Tabs in attendancepage just like View Jobs. 2025-12-05 04:49:16 +00:00
6a0feacb1b Merge branch 'main' of https://git.marcoaiot.com/admin/marco.pms.web into Purchase_Invoice_Management 2025-12-04 17:38:32 +05:30
949126d790 Adding height in ServiceProjectTeamlist. 2025-12-04 15:20:08 +05:30
f9d66d73b0 changed sequnce of project nave 2025-12-04 13:44:23 +05:30
0dbfc1f87a hide time 2025-12-04 13:09:29 +05:30
49c07606aa Adding Acknowledge number and date in View Purchase. 2025-12-04 11:32:58 +05:30
865928c1cb correct right path 2025-12-03 16:58:42 +05:30
06882e557e fixed- added right path 2025-12-03 16:54:48 +05:30
581447ecb6 addd field inside view Purchase - 2025-12-03 16:44:21 +05:30
2392a96eb8 added new column proform amount 2025-12-03 16:02:36 +05:30
8a3228c0c1 added pagination inside infra list 2025-12-03 15:27:12 +05:30
d615f6ca8a added required start tick on field base proforma and base amount 2025-12-03 14:53:14 +05:30
48f8d4aedb Merge branch 'Purchase_Invoice_Management' of https://git.marcoaiot.com/admin/marco.pms.web into Purchase_Invoice_Management 2025-12-03 13:55:43 +05:30
258bd82b54 handle proforma to base , Tax, amount condition 2025-12-03 13:55:39 +05:30
ef38ac4cdb added page-min-h in directorycontectlist. 2025-12-03 12:34:21 +05:30
8dfc8e4336 Merge pull request 'Adding ImageGallery Chips.' (#517) from Image_Gallery_FilterChips into Purchase_Invoice_Management
Reviewed-on: #517
merged
2025-12-03 06:55:13 +00:00
25b334a83c restriction before choosing project for gallery filter api calling an removed unused code 2025-12-03 06:55:13 +00:00
a8c10a0a9a UI updation in Collection. 2025-12-03 06:55:13 +00:00
4a66dad07a UI updation in Organization. 2025-12-03 06:55:13 +00:00
21c2a5cf7d Adding ImageGallery Chips. 2025-12-03 06:55:13 +00:00
83bd99549a Merge pull request 'Finance_Export_Functionality :- Implementing Export Functionality in Finance Module.' (#522) from Finance_Export_Functionality into Purchase_Invoice_Management
Reviewed-on: #522
Merged
2025-12-03 06:45:30 +00:00
8fc49ab4a7 Merge branch 'Purchase_Invoice_Management' of https://git.marcoaiot.com/admin/marco.pms.web into Finance_Export_Functionality 2025-12-03 12:14:41 +05:30
7fc058565b changed component, follow standard naming 2025-12-03 12:12:19 +05:30
d9947daf83 changed component, follow standard naming 2025-12-03 12:09:35 +05:30
36f5edf4f5 UI updation in all popups. 2025-12-03 11:42:44 +05:30
9cd1d932b1 added preview image inside challan, remove restric of payment date 2025-12-03 11:33:23 +05:30
214a416deb UI updation in Create and Update Service and Infra projects. 2025-12-03 11:30:41 +05:30
3e3ff189c9 changed class to className 2025-12-03 10:10:36 +05:30
06ac8099ed Merge branch 'Purchase_Invoice_Management' of https://git.marcoaiot.com/admin/marco.pms.web into Finance_Export_Functionality 2025-12-03 09:55:57 +05:30
917e7f3ccc Adding api for Finance for Export. 2025-12-03 09:53:41 +05:30
927b1840b4 Merge pull request 'Correction in HoverPopup at Jobs View panel.' (#525) from Jobs_Side_Panel into Purchase_Invoice_Management
Reviewed-on: #525
Merged
2025-12-03 04:18:02 +00:00
8dbdd230af Adding HoverPopup effect. 2025-12-03 04:18:02 +00:00
57bbcd4b45 Correction in HoverPopup. 2025-12-03 04:18:02 +00:00
c3720df294 removed invalid border for tittle 2025-12-02 17:32:27 +05:30
a747880a77 fixed value of sume value 2025-12-02 17:27:55 +05:30
3bfe108dab removed all required condition 2025-12-02 17:23:03 +05:30
aa2e732ff4 added merged payment and delete 2025-12-02 10:58:38 +05:30
76d99d6a14 merged purchase_payment 2025-12-02 09:49:56 +05:30
444ffa9696 Merge pull request 'At the time of Update in Purchase Automatically hit the sumit without click.' (#526) from Purchase_Invoice_Update into Purchase_Invoice_Management
Reviewed-on: #526
merged
2025-12-02 04:13:53 +00:00
03fb5f7bc3 Merge branch 'Purchase_Invoice_Management' of https://git.marcoaiot.com/admin/marco.pms.web into Finance_Export_Functionality 2025-12-01 15:16:51 +05:30
4b0ac5b6db Correction in Purchase List table-responsive. 2025-12-01 15:15:05 +05:30
311c74587a Adding Delete and Restore functionality in Purchase Invoice 2025-12-01 15:03:13 +05:30
ef3312523f added payment 2025-12-01 12:32:46 +05:30
35b3384dac At the time of Update in Purchase Automatically hit the sumit without click. 2025-12-01 11:39:34 +05:30
194b032870 fixed attachment issue. using added documentId 2025-12-01 10:26:54 +05:30
0482bfe191 Merge pull request 'Adding Upload functionlaiy in ManagePurchase.' (#524) from Multiple_File_Uploader into Purchase_Invoice_Management
Reviewed-on: #524
Merged
2025-12-01 04:13:29 +00:00
6fa2cc4ef0 fixed attachment remove and update operation 2025-11-29 13:27:07 +05:30
cb9d263730 Adding activetab to 0 2025-11-29 09:36:13 +05:30
f0d21b14a2 added attachement in invoice 2025-11-28 20:49:47 +05:30
9ce47a9232 Adding Upload functionlaiy in ManagePurchase. 2025-11-28 18:01:42 +05:30
5818b84760 chaange sequence of dashbord widgets 2025-11-28 12:36:23 +05:30
f9a0098adb Merge pull request 'Services_Bugs :- UI changes of Purchase Modal.' (#523) from Services_Bugs into Purchase_Invoice_Management
Reviewed-on: #523
Merged
2025-11-28 06:42:44 +00:00
cb00bd4f35 centered spinner inside purchase list 2025-11-28 11:37:53 +05:30
aec6930e11 fixed challan attachmenet 2025-11-28 11:35:59 +05:30
44e1e16d19 fixed challan list attchament icon 2025-11-28 11:24:41 +05:30
76826f8cee Merge branch 'Purchase_Invoice_Management' of https://git.marcoaiot.com/admin/marco.pms.web into Purchase_Invoice_Management 2025-11-28 11:20:49 +05:30
09428b1ff1 change JobComment btn label - 'send' to 'Submit' 2025-11-28 11:20:45 +05:30
9eae0b2cd1 Correction in App routes. 2025-11-27 18:01:07 +05:30
a791007561 Merge branch 'Purchase_Invoice_Management' of https://git.marcoaiot.com/admin/marco.pms.web into Finance_Export_Functionality 2025-11-27 17:57:56 +05:30
af95009c1f Adding Export functionality in Expense. 2025-11-27 17:49:38 +05:30
a31d5d5015 Adding Export functionality in Payment Request. 2025-11-27 17:41:49 +05:30
b5fb48104c Adding Export functionality in Recurring Expense. 2025-11-27 17:23:13 +05:30
359a787bdb Merge branch 'Issues_Nov_4W' of https://git.marcoaiot.com/admin/marco.pms.web into Finance_Export_Functionality 2025-11-27 10:40:45 +05:30
7e4a8157bf Change the UI for Employee and Directory and adding export functionality. 2025-11-27 10:40:10 +05:30
3072354ed2 Adding Export Functionality in Advance Payment and adding spinner on it. 2025-11-27 10:16:25 +05:30
f8963ef476 Merge pull request 'At Assigned Employee when selecting a Job role it change according to master now show correct data.' (#520) from Assigned_Employee_Job_Role into main
Reviewed-on: #520
merged
2025-11-26 12:20:28 +00:00
7b1ad80d78 Increase the gap for Advance Payment rows. 2025-11-26 16:56:01 +05:30
833cb98dd3 Change the Name of AdvancePayment Component. 2025-11-26 16:51:01 +05:30
e8f6298f93 Clicking on Contact Name in Notes Should Redirect to That Contact’s Detail Page in Directory (Web) 2025-11-26 12:35:21 +05:30
da13e40fd5 Service title and group text appear too bold in Masters → Services 2025-11-26 11:12:53 +05:30
9c02a4a925 Increase the size of date picker in OrganizationInfo at tenant and Page is not Refresh at Create form. 2025-11-26 10:49:57 +05:30
c975e54331 Logs Tab Action Redirects Back to Page 1 Automatically 2025-11-26 10:33:04 +05:30
2109a5f1f1 “Create Job” Popup Should Close Automatically After Job Creation. 2025-11-26 10:12:58 +05:30
9ad3b8726c At Assigned Employee when selecting a Job role it change according to master now show correct data. 2025-11-25 18:09:32 +05:30
b348117f05 added Total employee present figure 2025-11-25 09:50:39 +05:30
1157643916 added report data by project and date wise 2025-11-24 16:08:45 +05:30
37212e489e splitted code and added server data 2025-11-22 16:38:39 +05:30
b2c0388412 dpr report wireframe 2025-11-22 13:14:57 +05:30
202 changed files with 10683 additions and 5326 deletions

7
package-lock.json generated
View File

@ -18,6 +18,7 @@
"apexcharts": "^4.5.0", "apexcharts": "^4.5.0",
"axios": "^1.7.9", "axios": "^1.7.9",
"axios-retry": "^4.5.0", "axios-retry": "^4.5.0",
"crypto-js": "^4.2.0",
"date-fns": "^4.1.0", "date-fns": "^4.1.0",
"dotenv": "^16.4.7", "dotenv": "^16.4.7",
"dotenv-webpack": "^8.1.0", "dotenv-webpack": "^8.1.0",
@ -2414,6 +2415,12 @@
"node": ">= 8" "node": ">= 8"
} }
}, },
"node_modules/crypto-js": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz",
"integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
"license": "MIT"
},
"node_modules/csstype": { "node_modules/csstype": {
"version": "3.1.3", "version": "3.1.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",

View File

@ -21,6 +21,7 @@
"apexcharts": "^4.5.0", "apexcharts": "^4.5.0",
"axios": "^1.7.9", "axios": "^1.7.9",
"axios-retry": "^4.5.0", "axios-retry": "^4.5.0",
"crypto-js": "^4.2.0",
"date-fns": "^4.1.0", "date-fns": "^4.1.0",
"dotenv": "^16.4.7", "dotenv": "^16.4.7",
"dotenv-webpack": "^8.1.0", "dotenv-webpack": "^8.1.0",

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 500 KiB

After

Width:  |  Height:  |  Size: 52 KiB

BIN
public/img/hero/bg-011.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 500 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 201 KiB

After

Width:  |  Height:  |  Size: 201 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 MiB

After

Width:  |  Height:  |  Size: 1.8 MiB

View File

@ -20,14 +20,21 @@ import { SpinnerLoader } from "../common/Loader";
const usePagination = (data, itemsPerPage) => { const usePagination = (data, itemsPerPage) => {
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const maxPage = Math.ceil(data.length / itemsPerPage); // const maxPage = Math.ceil(data.length / itemsPerPage);
const maxPage = Math.max(1, Math.ceil(data.length / itemsPerPage));
const currentItems = useMemo(() => { const currentItems = useMemo(() => {
const startIndex = (currentPage - 1) * itemsPerPage; const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage; const endIndex = startIndex + itemsPerPage;
return data.slice(startIndex, endIndex); return data.slice(startIndex, endIndex);
}, [data, currentPage, itemsPerPage]); }, [data, currentPage, itemsPerPage]);
const paginate = useCallback((pageNumber) => setCurrentPage(pageNumber), []); // const paginate = useCallback((pageNumber) => setCurrentPage(pageNumber), []);
const paginate = useCallback((pageNumber) => {
// keep page within 1..maxPage
const p = Math.max(1, Math.min(pageNumber, maxPage));
setCurrentPage(p);
}, [maxPage]);
const resetPage = useCallback(() => setCurrentPage(1), []); const resetPage = useCallback(() => setCurrentPage(1), []);
return { return {
@ -36,6 +43,7 @@ const usePagination = (data, itemsPerPage) => {
currentItems, currentItems,
paginate, paginate,
resetPage, resetPage,
setCurrentPage,
}; };
}; };
@ -125,9 +133,16 @@ const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => {
resetPage, resetPage,
} = usePagination(filteredSearchData, 20); } = usePagination(filteredSearchData, 20);
// useEffect(() => {
// resetPage();
// }, [filteredSearchData]);
useEffect(() => { useEffect(() => {
resetPage(); if (currentPage > totalPages) {
}, [filteredSearchData]); paginate(totalPages || 1);
}
// NOTE: do NOT force reset to page 1 here keep the same page if still valid
}, [filteredSearchData, totalPages, currentPage, paginate]);
const handler = useCallback( const handler = useCallback(
(msg) => { (msg) => {
@ -144,10 +159,9 @@ const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => {
record.id === msg.response.id ? { ...record, ...msg.response } : record record.id === msg.response.id ? { ...record, ...msg.response } : record
); );
}); });
resetPage();
} }
}, },
[selectedProject, dateRange, resetPage] [selectedProject, dateRange]
); );
useEffect(() => { useEffect(() => {
@ -214,7 +228,7 @@ const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => {
{isLoading ? ( {isLoading ? (
<div <div
className="d-flex justify-content-center align-items-center" className="d-flex justify-content-center align-items-center"
style={{ minHeight: "50vh" }} style={{ minHeight: "50vh" }}
> >
<SpinnerLoader /> <SpinnerLoader />
</div> </div>

View File

@ -1,233 +1,108 @@
import React from 'react'
import Avatar from "../common/Avatar"; // <-- ADD THIS
import { useExpenseAllTransactionsList } from '../../hooks/useExpense';
import { useNavigate } from 'react-router-dom';
import { formatFigure } from '../../utils/appUtils';
import { SpinnerLoader } from '../common/Loader';
import React, { useEffect, useMemo } from "react"; const AdvancePaymentList = ({ searchString }) => {
import { useExpenseAllTransactionsList, useExpenseTransactions } from "../../hooks/useExpense";
import Error from "../common/Error";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import Loader, { SpinnerLoader } from "../common/Loader";
import { useForm, useFormContext } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { employee } from "../../data/masters";
import { useAdvancePaymentContext } from "../../pages/AdvancePayment/AdvancePaymentPage";
import { formatFigure } from "../../utils/appUtils";
const AdvancePaymentList = ({ employeeId, searchString }) => { const { data, isError, isLoading, error } =
const { setBalance } = useAdvancePaymentContext(); useExpenseAllTransactionsList(searchString);
const { data, isError, isLoading, error, isFetching } =
useExpenseTransactions(employeeId, { enabled: !!employeeId });
const records = Array.isArray(data) ? data : [];
let currentBalance = 0; const rows = data || [];
const rowsWithBalance = records.map((r) => { const navigate = useNavigate();
const isCredit = r.amount > 0;
const credit = isCredit ? r.amount : 0;
const debit = !isCredit ? Math.abs(r.amount) : 0;
currentBalance += credit - debit;
return {
id: r.id,
description: r.title || "-",
projectName: r.project?.name || "-",
createdAt: r.createdAt,
credit,
debit,
financeUId: r.financeUId,
balance: currentBalance,
};
});
useEffect(() => { const columns = [
if (!employeeId) { {
setBalance(null); key: "employee",
return; label: "Employee Name",
align: "text-start",
customRender: (r) => (
<div className="d-flex align-items-center gap-2" onClick={() => navigate(`/advance-payment/${r.id}`)}
style={{ cursor: "pointer" }}>
<Avatar firstName={r.firstName} lastName={r.lastName} />
<span className="fw-medium">
{r.firstName} {r.lastName}
</span>
</div>
),
},
{
key: "jobRoleName",
label: "Job Role",
align: "text-start",
customRender: (r) => (
<span className="fw-semibold">
{r.jobRoleName}
</span>
),
},
{
key: "balanceAmount",
label: "Balance (₹)",
align: "text-end",
customRender: (r) => (
<span className="fw-semibold fs-6">
{formatFigure(r.balanceAmount, {
// type: "currency",
currency: "INR",
})}
</span>
),
},
];
if (isLoading) {
return (
<div className="d-flex justify-content-center align-items-center py-4" style={{ height: "300px" }}>
<SpinnerLoader />
</div>
);
} }
if (rowsWithBalance.length > 0) { if (isError) return <p className="text-center py-4 text-danger">{error.message}</p>;
setBalance(rowsWithBalance[rowsWithBalance.length - 1].balance);
} else {
setBalance(0);
}
}, [employeeId, data, setBalance]);
if (!employeeId) {
return ( return (
<div <div className="card-datatable" id="payment-request-table">
className="d-flex justify-content-center align-items-center" <div className="mx-2">
style={{ height: "200px" }} <table className="table border-top dataTable text-nowrap align-middle">
> <thead>
<p className="text-muted m-0">Please select an employee</p> <tr>
</div> {columns.map((col) => (
); <th key={col.key} className={`sorting ${col.align}`}>
} {col.label}
</th>
))}
</tr>
</thead>
if (isLoading || isFetching) { <tbody>
return ( {rows.length > 0 ? (
<div rows.map((row) => (
className="d-flex justify-content-center align-items-center" <tr key={row.id} className="align-middle" style={{ height: "50px" }}>
style={{ height: "200px" }} {columns.map((col) => (
> <td key={col.key} className={`d-table-cell ${col.align} py-3`}>
<SpinnerLoader /> {col.customRender
</div> ? col.customRender(row)
); : col.getValue(row)}
} </td>
))}
if (isError) { </tr>
return ( ))
<div className="text-center py-3"> ) : (
{error?.status === 404 <tr>
? "No advance payment transactions found." <td colSpan={columns.length} className="text-center border-0 py-3">
: <Error error={error} />} No Employees Found
</div> </td>
); </tr>
} )}
const columns = [ </tbody>
{ </table>
key: "date", </div>
label: ( </div>
<> )
Date }
</>
),
align: "text-start",
},
{ key: "description", label: "Description", align: "text-start" },
{
key: "credit",
label: (
<>
Credit <i className="bx bx-rupee text-success"></i>
</>
),
align: "text-end",
},
{
key: "debit",
label: (
<>
Debit <i className="bx bx-rupee text-danger"></i>
</>
),
align: "text-end",
},
{
key: "balance",
label: (
<>
Balance <i className="bi bi-currency-rupee text-primary"></i>
</>
),
align: "text-end fw-bold",
},
];
// Handle empty records
if (rowsWithBalance.length === 0) {
return (
<div className="text-center text-muted py-3">
No advance payment records found.
</div>
);
}
const DecideCreditOrDebit = ({ financeUId }) => {
if (!financeUId) return null;
const prefix = financeUId?.substring(0, 2).toUpperCase();
if (prefix === "PR") return <span className="text-success">+</span>;
if (prefix === "EX") return <span className="text-danger">-</span>;
return null;
};
return (
<div className="table-responsive">
<table className="table align-middle">
<thead className="table_header_border">
<tr>
{columns.map((col) => (
<th key={col.key} className={col.align}>
{col.label}
</th>
))}
</tr>
</thead>
<tbody>
{Array.isArray(data) && data.length > 0 ? (
data.map((row) => (
<tr key={row.id}>
{columns.map((col) => (
<td key={col.key} className={`${col.align} p-2`}>
{col.key === "credit" ? (
row.amount > 0 ? (
<span>{row.amount.toLocaleString("en-IN")}</span>
) : (
"-"
)
) : col.key === "debit" ? (
row.amount < 0 ? (
<span>
{Math.abs(row.amount).toLocaleString("en-IN")}
</span>
) : (
"-"
)
) : col.key === "balance" ? (
<div className="d-flex align-items-center justify-content-end">
{/* <DecideCreditOrDebit financeUId={row?.financeUId} /> */}
<span className="mx-2">
{formatFigure(row.currentBalance)}
</span>
</div>
) : col.key === "date" ? (
<small className="text-muted px-1">
{formatUTCToLocalTime(row.paidAt)}
</small>
) : (
<div className="d-flex flex-column text-start gap-1 py-1">
<small className="fw-semibold text-dark">
{row.project?.name || "-"}
</small>
<small>{row.title || "-"}</small>
</div>
)}
</td>
))}
</tr>
))
) : (
<tr>
<td
colSpan={columns.length}
className="text-center text-muted py-3"
>
No advance payment records found.
</td>
</tr>
)}
</tbody>
<tfoot className=" fw-bold">
<tr className="tr-group text-dark py-2">
<td className="text-start">
{" "}
<div className="d-flex align-items-center px-1 py-2">
Final Balance
</div>
</td>
<td className="text-end" colSpan="4">
<div className="d-flex align-items-center justify-content-end px-1 py-2">
{currentBalance.toLocaleString("en-IN", {
style: "currency",
currency: "INR",
})}
</div>
</td>
</tr>
</tfoot>
</table>
</div>
);
};
export default AdvancePaymentList; export default AdvancePaymentList;

View File

@ -1,100 +0,0 @@
import React from 'react'
import Avatar from "../../components/common/Avatar"; // <-- ADD THIS
import { useExpenseAllTransactionsList } from '../../hooks/useExpense';
import { useNavigate } from 'react-router-dom';
import { formatFigure } from '../../utils/appUtils';
const AdvancePaymentList1 = ({ searchString }) => {
const { data, isError, isLoading, error } =
useExpenseAllTransactionsList(searchString);
const rows = data || [];
const navigate = useNavigate();
const columns = [
{
key: "employee",
label: "Employee Name",
align: "text-start",
customRender: (r) => (
<div className="d-flex align-items-center gap-2" onClick={() => navigate(`/advance-payment/${r.id}`)}
style={{ cursor: "pointer" }}>
<Avatar firstName={r.firstName} lastName={r.lastName} />
<span className="fw-medium">
{r.firstName} {r.lastName}
</span>
</div>
),
},
{
key: "jobRoleName",
label: "Job Role",
align: "text-start",
customRender: (r) => (
<span className="fw-semibold">
{r.jobRoleName}
</span>
),
},
{
key: "balanceAmount",
label: "Balance (₹)",
align: "text-end",
customRender: (r) => (
<span className="fw-semibold fs-6">
{formatFigure(r.balanceAmount, {
// type: "currency",
currency: "INR",
})}
</span>
),
},
];
if (isLoading) return <p className="text-center py-4">Loading...</p>;
if (isError) return <p className="text-center py-4 text-danger">{error.message}</p>;
return (
<div className="card-datatable" id="payment-request-table">
<div className="mx-2">
<table className="table border-top dataTable text-nowrap align-middle">
<thead>
<tr>
{columns.map((col) => (
<th key={col.key} className={`sorting ${col.align}`}>
{col.label}
</th>
))}
</tr>
</thead>
<tbody>
{rows.length > 0 ? (
rows.map((row) => (
<tr key={row.id} className="align-middle" style={{ height: "40px" }}>
{columns.map((col) => (
<td key={col.key} className={`d-table-cell ${col.align} py-3`}>
{col.customRender
? col.customRender(row)
: col.getValue(row)}
</td>
))}
</tr>
))
) : (
<tr>
<td colSpan={columns.length} className="text-center border-0 py-3">
No Employees Found
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
)
}
export default AdvancePaymentList1;

View File

@ -0,0 +1,233 @@
import React, { useEffect, useMemo } from "react";
import { useExpenseAllTransactionsList, useExpenseTransactions } from "../../hooks/useExpense";
import Error from "../common/Error";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import Loader, { SpinnerLoader } from "../common/Loader";
import { useForm, useFormContext } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { employee } from "../../data/masters";
import { useAdvancePaymentContext } from "../../pages/AdvancePayment/AdvancePaymentPageDetails";
import { formatFigure } from "../../utils/appUtils";
const AdvancePaymentListDetails = ({ employeeId, searchString,tableRef }) => {
const { setBalance } = useAdvancePaymentContext();
const { data, isError, isLoading, error, isFetching } =
useExpenseTransactions(employeeId, { enabled: !!employeeId });
const records = Array.isArray(data) ? data : [];
let currentBalance = 0;
const rowsWithBalance = records.map((r) => {
const isCredit = r.amount > 0;
const credit = isCredit ? r.amount : 0;
const debit = !isCredit ? Math.abs(r.amount) : 0;
currentBalance += credit - debit;
return {
id: r.id,
description: r.title || "-",
projectName: r.project?.name || "-",
createdAt: r.createdAt,
credit,
debit,
financeUId: r.financeUId,
balance: currentBalance,
};
});
useEffect(() => {
if (!employeeId) {
setBalance(null);
return;
}
if (rowsWithBalance.length > 0) {
setBalance(rowsWithBalance[rowsWithBalance.length - 1].balance);
} else {
setBalance(0);
}
}, [employeeId, data, setBalance]);
if (!employeeId) {
return (
<div
className="d-flex justify-content-center align-items-center"
style={{ height: "200px" }}
>
<p className="text-muted m-0">Please select an employee</p>
</div>
);
}
if (isLoading || isFetching) {
return (
<div
className="d-flex justify-content-center align-items-center"
style={{ height: "200px" }}
>
<SpinnerLoader />
</div>
);
}
if (isError) {
return (
<div className="text-center py-3">
{error?.status === 404
? "No advance payment transactions found."
: <Error error={error} />}
</div>
);
}
const columns = [
{
key: "date",
label: (
<>
Date
</>
),
align: "text-start",
},
{ key: "description", label: "Description", align: "text-start" },
{
key: "credit",
label: (
<>
Credit <i className="bx bx-rupee text-success"></i>
</>
),
align: "text-end",
},
{
key: "debit",
label: (
<>
Debit <i className="bx bx-rupee text-danger"></i>
</>
),
align: "text-end",
},
{
key: "balance",
label: (
<>
Balance <i className="bi bi-currency-rupee text-primary"></i>
</>
),
align: "text-end fw-bold",
},
];
// Handle empty records
if (rowsWithBalance.length === 0) {
return (
<div className="text-center text-muted py-3">
No advance payment records found.
</div>
);
}
const DecideCreditOrDebit = ({ financeUId }) => {
if (!financeUId) return null;
const prefix = financeUId?.substring(0, 2).toUpperCase();
if (prefix === "PR") return <span className="text-success">+</span>;
if (prefix === "EX") return <span className="text-danger">-</span>;
return null;
};
return (
<div className="table-responsive">
<table className="table align-middle" ref={tableRef}>
<thead className="table_header_border">
<tr>
{columns.map((col) => (
<th key={col.key} className={col.align}>
{col.label}
</th>
))}
</tr>
</thead>
<tbody>
{Array.isArray(data) && data.length > 0 ? (
data.map((row) => (
<tr key={row.id}>
{columns.map((col) => (
<td key={col.key} className={`${col.align} p-2`}>
{col.key === "credit" ? (
row.amount > 0 ? (
<span>{row.amount.toLocaleString("en-IN")}</span>
) : (
"-"
)
) : col.key === "debit" ? (
row.amount < 0 ? (
<span>
{Math.abs(row.amount).toLocaleString("en-IN")}
</span>
) : (
"-"
)
) : col.key === "balance" ? (
<div className="d-flex align-items-center justify-content-end">
{/* <DecideCreditOrDebit financeUId={row?.financeUId} /> */}
<span className="mx-2">
{formatFigure(row.currentBalance)}
</span>
</div>
) : col.key === "date" ? (
<small className="text-muted px-1">
{formatUTCToLocalTime(row.paidAt)}
</small>
) : (
<div className="d-flex flex-column text-start gap-1 py-1">
<small className="fw-semibold text-dark">
{row.project?.name || "-"}
</small>
<small>{row.title || "-"}</small>
</div>
)}
</td>
))}
</tr>
))
) : (
<tr>
<td
colSpan={columns.length}
className="text-center text-muted py-3"
>
No advance payment records found.
</td>
</tr>
)}
</tbody>
<tfoot className=" fw-bold">
<tr className="tr-group text-dark py-2">
<td className="text-start">
{" "}
<div className="d-flex align-items-center px-1 py-2">
Final Balance
</div>
</td>
<td className="text-end" colSpan="4">
<div className="d-flex align-items-center justify-content-end px-1 py-2">
{currentBalance.toLocaleString("en-IN", {
style: "currency",
currency: "INR",
})}
</div>
</td>
</tr>
</tfoot>
</table>
</div>
);
};
export default AdvancePaymentListDetails;

View File

@ -0,0 +1,76 @@
import moment from "moment";
import { exportToCSV, exportToExcel, exportToPDF, printTable } from "../../utils/tableExportUtils";
const handleAdvancePaymentExport = (type, data, tableRef) => {
if (!data || data.length === 0) return;
let currentBalance = 0;
const exportData = data.map((item) => {
const credit = item.amount > 0 ? item.amount : 0;
const debit = item.amount < 0 ? Math.abs(item.amount) : 0;
currentBalance += credit - debit;
return {
Date: item.createdAt ? moment(item.createdAt).format("DD-MMM-YYYY") : "",
Description: item.title || "-", // used only for CSV/Excel
Project: item.project?.name || "-",
Credit: credit || "",
Debit: debit || "",
"Finance ID": item.financeUId || "-",
Balance: currentBalance,
};
});
// Final row
exportData.push({
Date: "",
Description: "Final Balance",
Project: "",
Credit: "",
Debit: "",
"Finance ID": "",
Balance: currentBalance,
});
switch (type) {
case "csv":
exportToCSV(exportData, "advance-payments");
break;
case "excel":
exportToExcel(exportData, "advance-payments");
break;
case "pdf":
// Create a copy of data ONLY for PDF (without Description)
const pdfData = exportData.map((row, index) => {
// Detect final row
const isFinal = index === exportData.length - 1;
return {
Date: isFinal ? "" : row.Date,
Project: isFinal ? "Final Balance" : row.Project,
Credit: row.Credit,
Debit: row.Debit,
"Finance ID": row["Finance ID"],
Balance: row.Balance,
};
});
exportToPDF(
pdfData,
"advance-payments",
["Date", "Project", "Credit", "Debit", "Finance ID", "Balance"]
);
break;
case "print":
if (tableRef?.current) printTable(tableRef.current);
break;
default:
break;
}
};
export default handleAdvancePaymentExport;

View File

@ -42,7 +42,12 @@ const HorizontalBarChart = ({
categories.length === seriesData.length; categories.length === seriesData.length;
if (!hasValidData) { if (!hasValidData) {
return <div className="text-center text-gray-500">No data to display</div>; return <div
className="d-flex justify-content-center align-items-center text-muted"
style={{ height: "300px" }}
>
No data found
</div>
} }
// Combine seriesData and categories, then sort in descending order // Combine seriesData and categories, then sort in descending order
const combined = seriesData.map((value, index) => ({ const combined = seriesData.map((value, index) => ({

View File

@ -0,0 +1,95 @@
import React, { useMemo } from "react";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
const TaskReportFilterChips = ({ filter, filterData, removeFilterChip, clearFilter }) => {
const data = filterData?.data || filterData || {};
const filterChips = useMemo(() => {
const chips = [];
const addGroup = (ids, list, label, key) => {
if (!ids || ids.length === 0) return;
const items = ids.map((id) => ({
id,
name: list?.find((i) => i.id === id)?.name || id,
}));
chips.push({ key, label, items });
};
// Building
addGroup(filter?.buildingIds, data?.buildings, "Building", "buildingIds");
// Floor
addGroup(filter?.floorIds, data?.floors, "Floor", "floorIds");
// Activities
addGroup(filter?.activityIds, data?.activities, "Activity", "activityIds");
// Date Range Chips
if (filter?.dateFrom || filter?.dateTo) {
chips.push({
key: "date",
label: "Date Range",
items: [
{
id: "date-range",
name: `${filter?.dateFrom ? formatUTCToLocalTime(filter.dateFrom) : ""}
${filter?.dateTo ? " to " + formatUTCToLocalTime(filter.dateTo) : ""}`,
},
],
});
}
return chips;
}, [filter, filterData]);
if (!filterChips.length) return null;
return (
<div className="d-flex flex-wrap align-items-center gap-2 mt-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>
{/* If date chip → remove whole date range */}
{chipGroup.key === "date" ? (
<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={() => clearFilter()}
/>
) : (
<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 TaskReportFilterChips;

View File

@ -1,4 +1,4 @@
import React, { useState } from "react"; import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from "react";
import { useCurrentService } from "../../hooks/useProjects"; import { useCurrentService } from "../../hooks/useProjects";
import { useSelectedProject } from "../../slices/apiDataManager"; import { useSelectedProject } from "../../slices/apiDataManager";
import { FormProvider, useForm } from "react-hook-form"; import { FormProvider, useForm } from "react-hook-form";
@ -11,8 +11,9 @@ import { DateRangePicker1 } from "../common/DateRangePicker";
import SelectMultiple from "../common/SelectMultiple"; import SelectMultiple from "../common/SelectMultiple";
import { localToUtc } from "../../utils/appUtils"; import { localToUtc } from "../../utils/appUtils";
import { useTaskFilter } from "../../hooks/useTasks"; import { useTaskFilter } from "../../hooks/useTasks";
import { set } from "date-fns";
const TaskReportFilterPanel = ({ handleFilter }) => { const TaskReportFilterPanel = forwardRef(({ handleFilter, setFilterdata, clearFilter }, ref) => {
const [resetKey, setResetKey] = useState(0); const [resetKey, setResetKey] = useState(0);
const selectedProject = useSelectedProject(); const selectedProject = useSelectedProject();
const selectedService = useCurrentService(); const selectedService = useCurrentService();
@ -23,10 +24,42 @@ const TaskReportFilterPanel = ({ handleFilter }) => {
defaultValues: TaskReportDefaultValue, defaultValues: TaskReportDefaultValue,
}); });
const dynamicDefaultFilter = useMemo(() => {
return {
...TaskReportDefaultValue,
buildingIds: TaskReportDefaultValue.buildingIds || [],
floorIds: TaskReportDefaultValue.floorIds || [],
activityIds: TaskReportDefaultValue.activityIds || [],
dateFrom: TaskReportDefaultValue.dateFrom,
dateTo: TaskReportDefaultValue.dateTo,
};
}, [selectedProject]);
useImperativeHandle(ref, () => ({
resetFieldValue: (name, value) => {
// Reset specific field
if (value !== undefined) {
setValue(name, value);
} else {
// Fix: Use TaskReportDefaultValue or get current values before setting new ones
// reset({ ...methods.getValues(), [name]: TaskReportDefaultValue[name] }); // Updated to use TaskReportDefaultValue
setValue(name, TaskReportDefaultValue[name]);
}
},
getValues: methods.getValues,
onClear: onClear, // 💡 EXPOSE THE ONCLEAR FUNCTION
}));
useEffect(() => {
if (data && setFilterdata) {
setFilterdata(data);
}
}, [data, setFilterdata]);
const { const {
register, register,
reset, reset,
handleSubmit, handleSubmit,
setValue,
formState: { errors }, formState: { errors },
} = methods; } = methods;
const closePanel = () => { const closePanel = () => {
@ -52,7 +85,7 @@ const TaskReportFilterPanel = ({ handleFilter }) => {
<div className="mb-3 w-100"> <div className="mb-3 w-100">
<label className="fw-semibold">Choose Date Range:</label> <label className="fw-semibold">Choose Date Range:</label>
<DateRangePicker1 <DateRangePicker1
className="w-100" className="w-100"
placeholder="DD-MM-YYYY To DD-MM-YYYY" placeholder="DD-MM-YYYY To DD-MM-YYYY"
startField="dateFrom" startField="dateFrom"
endField="dateTo" endField="dateTo"
@ -105,6 +138,6 @@ const TaskReportFilterPanel = ({ handleFilter }) => {
</form> </form>
</FormProvider> </FormProvider>
); );
}; });
export default TaskReportFilterPanel; export default TaskReportFilterPanel;

View File

@ -17,8 +17,9 @@ import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import Pagination from "../common/Pagination"; import Pagination from "../common/Pagination";
import { TaskReportListSkeleton } from "./TaskRepprtListSkeleton"; import { TaskReportListSkeleton } from "./TaskRepprtListSkeleton";
import HoverPopup from "../common/HoverPopup"; import HoverPopup from "../common/HoverPopup";
import TaskReportFilterChips from "./TaskReportFilterChips";
const TaskReportList = () => { const TaskReportList = ({ filter, filterData, removeFilterChip, clearFilter }) => {
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const [filters, setFilters] = useState({ const [filters, setFilters] = useState({
selectedBuilding: "", selectedBuilding: "",
@ -29,7 +30,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: contextFilter } = useDailyProgrssContext();
const selectedProject = useSelectedProject(); const selectedProject = useSelectedProject();
const { projectNames } = useProjectName(); const { projectNames } = useProjectName();
@ -37,7 +38,7 @@ const TaskReportList = () => {
selectedProject, selectedProject,
ITEMS_PER_PAGE, ITEMS_PER_PAGE,
currentPage, currentPage,
service, filter service, contextFilter
); );
const ProgrssReportColumn = [ const ProgrssReportColumn = [
@ -147,13 +148,13 @@ const TaskReportList = () => {
data-bs-placement="left" data-bs-placement="left"
data-bs-html="true" data-bs-html="true"
data-bs-content={` data-bs-content={`
<div class="border border-secondary rounded custom-popover p-2 px-3"> <div className="border border-secondary rounded custom-popover p-2 px-3">
${task.teamMembers ${task.teamMembers
.map( .map(
(m) => ` (m) => `
<div class="d-flex align-items-center gap-2 mb-2"> <div className="d-flex align-items-center gap-2 mb-2">
<div class="avatar avatar-xs"> <div className="avatar avatar-xs">
<span class="avatar-initial rounded-circle bg-label-primary"> <span className="avatar-initial rounded-circle bg-label-primary">
${m?.firstName?.charAt(0) || ""}${m?.lastName?.charAt(0) || "" ${m?.firstName?.charAt(0) || ""}${m?.lastName?.charAt(0) || ""
} }
</span> </span>
@ -193,124 +194,135 @@ const TaskReportList = () => {
if (isError) return <div>Loading....</div>; if (isError) return <div>Loading....</div>;
return ( return (
<div> <div>
<div className="mt-2 table-responsive text-nowrap">
<table className="table">
<thead>
<tr>
<th className="text-start">Activity</th>
<th>
<span>
Total Pending{" "}
<HoverPopup
id="total_pending_task"
title="Total Pending Task"
content={
<div className="text-wrap" style={{ maxWidth: "200px" }}>
This shows the total pending tasks for each activity on that date.
</div>
}
>
<i className="bx bx-xs ms-1 bx-info-circle cursor-pointer"></i>
</HoverPopup>
</span>
</th>
<th> <div className="main-content">
<span> <div className="col-12 mb-2 mt-2 px-4">
Reported/Planned{" "} <TaskReportFilterChips
<HoverPopup filter={filter}
id="reportes_and_planned_task" filterData={filterData}
title="Reported and Planned Task" removeFilterChip={removeFilterChip}
content={ clearFilter={clearFilter}
<div className="text-wrap" style={{ maxWidth: "200px" }}> />
This shows the reported versus planned tasks for each activity on that date. </div>
</div> <div className="mt-2 table-responsive text-nowrap">
} <table className="table">
> <thead>
<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>
</tr> Total Pending{" "}
)} <HoverPopup
id="total_pending_task"
title="Total Pending Task"
content={
<div className="text-wrap" style={{ minWidth: "200px" }}>
This shows the total pending tasks for each activity on that date.
</div>
}
>
<i className="bx bx-xs ms-1 bx-info-circle cursor-pointer"></i>
</HoverPopup>
</span>
</th>
{groupedTasks.map(({ date, tasks }) => ( <th>
<React.Fragment key={date}> <span>
<tr className="table-row-header text-start"> Reported/Planned{" "}
<td colSpan={6}> <HoverPopup
<strong>{formatUTCToLocalTime(date)}</strong> id="reportes_and_planned_task"
title="Reported and Planned Task"
content={
<div className="text-wrap" style={{ maxWidth: "200px" }}>
This shows the reported versus planned tasks for each activity on that date.
</div>
}
>
<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>
<td colSpan={6} className="text-center align-middle" style={{ height: "200px", borderBottom: "none" }}>
No reports available
</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"}
</div>
<div className="text-sm py-2">
{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>
</tr>
))}
</React.Fragment>
))}
</tbody>
</table>
</div> </div>
{ {
data?.data?.length > 0 && ( data?.data?.length > 0 && (
<Pagination <Pagination
currentPage={currentPage} currentPage={currentPage}
totalPages={data.totalPages} totalPages={data.totalPages}
onPageChange={paginate} onPageChange={paginate}
/> />
) )
} }
</div >
</div > </div >
); );
}; };

View File

@ -31,7 +31,7 @@ const selectedProjectId = useSelectedProject()
<div className="card-header mb-1 pb-0"> <div className="card-header mb-1 pb-0">
<div className="d-flex flex-wrap justify-content-between align-items-center"> <div className="d-flex flex-wrap justify-content-between align-items-center">
<div className="card-title mb-0 text-start"> <div className="card-title mb-0 text-start">
<h5 className="mb-1">Attendance</h5> <h5 class="card-title m-0 me-2">Attendance</h5>
<p className="card-subtitle">Daily Attendance Data</p> <p className="card-subtitle">Daily Attendance Data</p>
</div> </div>

View File

@ -10,7 +10,7 @@ const formatDate = (dateStr) => {
const date = new Date(dateStr); const date = new Date(dateStr);
return date.toLocaleDateString("en-GB", { return date.toLocaleDateString("en-GB", {
day: "2-digit", day: "2-digit",
month: "long", month: "short",
}); });
}; };
@ -104,7 +104,7 @@ const AttendanceOverview = () => {
{/* Header */} {/* Header */}
<div className="d-flex mt-2 justify-content-between align-items-center mb-3"> <div className="d-flex mt-2 justify-content-between align-items-center mb-3">
<div className="card-title mb-0 text-start"> <div className="card-title mb-0 text-start">
<h5 className="mb-1 fw-bold">Attendance Overview</h5> <h5 className="mb-1 fw-semibold">Attendance Overview</h5>
<p className="card-subtitle">Role-wise present count</p> <p className="card-subtitle">Role-wise present count</p>
</div> </div>
<div className="d-flex gap-2"> <div className="d-flex gap-2">

View File

@ -0,0 +1,344 @@
import React from "react";
import Chart from "react-apexcharts";
import { useGetCollectionOverview } from "../../hooks/useDashboard_Data";
import { formatFigure } from "../../utils/appUtils";
const CollectionOverview = ({ data, isLoading }) => {
const borderColor = "#ddd";
const labelColor = "#6c757d";
// Extract bucket values
const labels = ["030 Days", "3060 Days", "6090 Days", "90+ Days"];
const amounts = [
data.bucket0To30Amount,
data.bucket30To60Amount,
data.bucket60To90Amount,
data.bucket90PlusAmount,
];
// Colors (Zoho-style distributed)
const colors = ["#7367F0", "#00cfe8", "#28c76f", "#ea5455"];
const options = {
chart: {
type: "bar",
height: 260,
toolbar: { show: false },
},
plotOptions: {
bar: {
horizontal: true,
barHeight: "65%",
distributed: true,
borderRadius: 8,
startingShape: "rounded",
},
},
colors: colors,
grid: {
borderColor: borderColor,
strokeDashArray: 6,
padding: { top: -10, bottom: -10 },
xaxis: { lines: { show: true } },
},
dataLabels: {
enabled: true,
formatter: (_, opts) => labels[opts.dataPointIndex],
style: {
colors: ["#fff"],
fontSize: "13px",
fontWeight: 500,
},
offsetX: 0,
},
xaxis: {
categories: amounts.map((a) => a),
labels: {
style: { colors: labelColor, fontSize: "12px" },
formatter: (val) => `${val.toLocaleString()}`,
},
},
yaxis: {
labels: {
style: {
colors: labelColor,
fontSize: "13px",
},
formatter: () => "", // hide duplicate labels
},
},
tooltip: {
custom: ({ series, seriesIndex, dataPointIndex }) => {
return `
<div className="px-2 py-1">
<strong>${labels[dataPointIndex]}</strong><br>
${series[seriesIndex][dataPointIndex].toLocaleString()}
</div>
`;
},
},
legend: { show: false },
};
const series = [
{
name: "Amount",
data: amounts,
},
];
return (
<div>
<Chart options={options} series={series} type="bar" height={260} />
</div>
);
};
export default CollectionOverview;
export const TopicBarChart = ({ data,isLoading }) => {
const data1 = {
totalDueAmount: 213590,
totalCollectedAmount: 5000,
totalValue: 218590,
pendingPercentage: 97.71,
collectedPercentage: 2.29,
bucket0To30Invoices: 10,
bucket30To60Invoices: 4,
bucket60To90Invoices: 2,
bucket90PlusInvoices: 1,
bucket0To30Amount: 2130,
bucket30To60Amount: 2003,
bucket60To90Amount: 4500,
bucket90PlusAmount: 8800,
topClientBalance: 55300,
topClient: {
id: "4e3a6d31-c640-40f7-8d67-6c109fcdb9ea",
name: "Marco Secure Solutions Ltd.",
email: "admin@marcoaiot.com",
contactPerson: "Admin",
address:
"2nd Floor, Fullora Building, Tejas CHS, behind Kothrud Stand, Tejas Society, Dahanukar Colony, Kothrud, Pune, Maharashtra 411038",
gstNumber: null,
contactNumber: "123456789",
sprid: 5400,
},
};
const borderColor = "#ddd";
const labelColor = "#6c757d";
// COLORS
const config = {
colors: {
b0: "#7367F0",
b30: "#00cfe8",
b60: "#28c76f",
b90: "#ea5455",
},
};
// NEW LABELS (BUCKETS)
const chartLabels = ["030 Days", "3060 Days", "6090 Days", "90+ Days"];
// NEW VALUES (BUCKET AMOUNT)
const chartValues = [
data.bucket0To30Amount,
data.bucket30To60Amount,
data.bucket60To90Amount,
data.bucket90PlusAmount,
];
const options = {
chart: {
height: 300,
type: "bar",
toolbar: { show: false },
},
plotOptions: {
bar: {
horizontal: true,
barHeight: "40%",
distributed: true,
startingShape: "rounded",
borderRadius: 7,
},
},
grid: {
strokeDashArray: 10,
borderColor,
xaxis: { lines: { show: true } },
yaxis: { lines: { show: false } },
padding: { top: -35, bottom: -12 },
},
colors: [
config.colors.b0,
config.colors.b30,
config.colors.b60,
config.colors.b90,
],
labels: chartLabels,
fill: { opacity: 1 },
dataLabels: {
enabled: true,
style: {
colors: ["#fff"],
fontWeight: 400,
fontSize: "13px",
fontFamily: "Public Sans",
},
formatter: (_, opts) => chartLabels[opts.dataPointIndex],
},
xaxis: {
categories: chartValues.map((x) => formatFigure(x, { type: "currency" })),
axisBorder: { show: false },
axisTicks: { show: false },
labels: {
style: {
colors: labelColor,
fontFamily: "Public Sans",
fontSize: "13px",
},
formatter: (val) => `${Number(val).toLocaleString()}`,
},
},
yaxis: {
labels: {
style: {
colors: labelColor,
fontFamily: "Public Sans",
fontSize: "13px",
},
},
},
tooltip: {
enabled: true,
custom: ({ series, seriesIndex, dataPointIndex }) => {
return `
<div className="px-3 py-2">
<span>${series[seriesIndex][
dataPointIndex
].toLocaleString()}</span>
</div>
`;
},
},
legend: { show: false },
};
const series = [
{
data: chartValues,
},
];
return (
<div className="row p-2">
<div className="col-md-8">
<div className="card-header d-flex align-items-center justify-content-between">
<h5 className="card-title m-0 me-2">Collection Overview</h5>
</div>
<div className="w-100 d-flex align-items-center text-start px-6">
<p className="text-secondary fs-6 m-0">Due Amount</p>
<span className="ms-2 fs-5">
{formatFigure(data.totalDueAmount, { type: "currency" })}
</span>
<p className="text-secondary fs-6 m-0 ms-1">Collected Amount</p>
<span className="ms-2 fs-5">
{formatFigure(data.totalCollectedAmount, { type: "currency" })}
</span>
</div>
<Chart options={options} series={series} type="bar" height={300} />
</div>
<div className="col-md-4 d-flex flex-column gap-2">
<div className="card-header d-flex align-items-end justify-content-between"></div>
<div className="p-1 m-1 text-start">
<small className="fw-medium">Overdue Days</small>
</div>
{/* 030 Days */}
<div
className="p-1 rounded-3 text-start mx-1"
style={{
background: "var(--bs-primary-bg-subtle)",
borderLeft: "4px solid var(--bs-primary)",
minWidth: "170px",
}}
>
<h5 className="fw-bold mb-0">
{formatFigure(data.bucket0To30Amount, { type: "currency" })}
</h5>
<p className="text-secondary mb-0 small">030 Days</p>
</div>
{/* 3060 Days */}
<div
className="p-1 rounded-3 text-start mx-1"
style={{
background: "var(--bs-info-bg-subtle)",
borderLeft: "4px solid var(--bs-info)",
minWidth: "170px",
}}
>
<h5 className="fw-bold mb-0">
{formatFigure(data.bucket30To60Amount, { type: "currency" })}
</h5>
<p className="text-secondary mb-0 small">3060 Days</p>
</div>
{/* 6090 Days */}
<div
className="p-1 rounded-3 text-start mx-1"
style={{
background: "var(--bs-warning-bg-subtle)",
borderLeft: "4px solid var(--bs-warning)",
minWidth: "170px",
}}
>
<h5 className="fw-bold mb-0">
{formatFigure(data.bucket60To90Amount, { type: "currency" })}
</h5>
<p className="text-secondary mb-0 small">6090 Days</p>
</div>
{/* 90+ Days */}
<div
className="p-1 rounded-3 text-start mx-1"
style={{
background: "var(--bs-danger-bg-subtle)",
borderLeft: "4px solid var(--bs-danger)",
minWidth: "170px",
}}
>
<h5 className="fw-bold mb-0">
{formatFigure(data.bucket90PlusAmount, { type: "currency" })}
</h5>
<p className="text-secondary mb-0 small">90+ Days</p>
</div>
</div>
</div>
);
};

View File

@ -0,0 +1,40 @@
const SkeletonLine = ({ height = 20, width = "100%", className = "" }) => (
<div
className={`skeleton mb-2 ${className}`}
style={{ height, width }}
></div>
);
export const CollectionOverviewSkeleton = () => {
return (
<div className="card row p-1">
{/* LEFT SIDE */}
<div className="col-8">
<div className="">
{/* Header */}
<div className="d-flex align-items-center justify-content-between mb-3">
<SkeletonLine height={24} width="180px" />
</div>
{/* Due & Collected summary */}
<div className="d-flex align-items-center text-start px-6 mb-3">
<SkeletonLine height={16} width="100px" className="me-2" />
<SkeletonLine height={20} width="120px" className="me-2" />
<SkeletonLine height={16} width="120px" className="ms-2 me-2" />
<SkeletonLine height={20} width="120px" />
</div>
{/* Chart Skeleton */}
<SkeletonLine height={250} width="100%" className="mt-2" />
</div>
</div>
</div>
);
};

View File

@ -1,10 +1,11 @@
import React from "react"; import React from "react";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { import {
useDashboardProjectsCardData, useDashboardProjectsCardData,
useDashboardTeamsCardData, useDashboardTeamsCardData,
useDashboardTasksCardData, useDashboardTasksCardData,
useAttendanceOverviewData useAttendanceOverviewData,
useGetCollectionOverview,
} from "../../hooks/useDashboard_Data"; } from "../../hooks/useDashboard_Data";
import Projects from "./Projects"; import Projects from "./Projects";
@ -19,76 +20,106 @@ import ExpenseByProject from "./ExpenseByProject";
import ProjectStatistics from "../Project/ProjectStatistics"; import ProjectStatistics from "../Project/ProjectStatistics";
import ServiceJobs from "./ServiceJobs"; import ServiceJobs from "./ServiceJobs";
import { useHasUserPermission } from "../../hooks/useHasUserPermission"; import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { REGULARIZE_ATTENDANCE, SELF_ATTENDANCE, TEAM_ATTENDANCE } from "../../utils/constants"; import {
REGULARIZE_ATTENDANCE,
SELF_ATTENDANCE,
TEAM_ATTENDANCE,
} from "../../utils/constants";
import CollectionOverview, { TopicBarChart } from "./CollectionOverview";
import { CollectionOverviewSkeleton } from "./CollectionOverviewSkeleton";
import ProjectWiseTeamCount from "./ProjectWiseTeamCount";
const Dashboard = () => { const Dashboard = () => {
// Get the selected project ID from Redux store
const projectId = useSelector((store) => store.localVariables.projectId);
const isAllProjectsSelected = projectId === null;
const canRegularize = useHasUserPermission(REGULARIZE_ATTENDANCE);
const canTeamAttendance = useHasUserPermission(TEAM_ATTENDANCE);
const canSelfAttendance = useHasUserPermission(SELF_ATTENDANCE);
// Get the selected project ID from Redux store const { data, isLoading, isError } = useGetCollectionOverview();
const projectId = useSelector((store) => store.localVariables.projectId); return (
const isAllProjectsSelected = projectId === null; <div className="container-fluid mt-5">
const canRegularize = useHasUserPermission(REGULARIZE_ATTENDANCE); <div className="row gy-4">
const canTeamAttendance = useHasUserPermission(TEAM_ATTENDANCE); {isAllProjectsSelected && (
const canSelfAttendance = useHasUserPermission(SELF_ATTENDANCE); <div className="col-sm-6 col-lg-6">
<Projects />
</div>
)}
<div
return ( className={`${!isAllProjectsSelected ? "col-sm-6 col-lg-6" : "col-sm-6 col-lg-6"
<div className="container-fluid mt-5"> }`}
<div className="row gy-4"> >
{isAllProjectsSelected && ( <Teams />
<div className="col-sm-6 col-lg-4">
<Projects />
</div>
)}
<div className={`${!isAllProjectsSelected ? "col-sm-6 col-lg-6" : "col-sm-6 col-lg-4"}`}>
<Teams />
</div>
<div className={`${!isAllProjectsSelected ? "col-sm-6 col-lg-6" : "col-sm-6 col-lg-4"}`}>
<TasksCard />
</div>
{isAllProjectsSelected && (
<div className="col-xxl-6 col-lg-6">
<ProjectCompletionChart />
</div>
)}
<div className="col-xxl-6 col-lg-6">
<ProjectProgressChart />
</div>
{!isAllProjectsSelected && (canRegularize || canTeamAttendance || canSelfAttendance) && (
<div className="col-12 col-md-6 mb-sm-0 mb-4">
<AttendanceOverview />
</div>
)}
{!isAllProjectsSelected && (
<div className="col-xxl-4 col-lg-4">
<div className="card h-100">
<ProjectStatistics />
</div>
</div>
)}
<div className="col-12 col-xl-4 col-md-6">
<div className="card ">
<ExpenseStatus />
</div>
</div>
<div className="col-12 col-xl-8">
<div className="card h-100">
<ExpenseAnalysis />
</div>
</div>
<div className="col-12 col-md-6">
<ExpenseByProject />
</div>
{/* <div className="col-12 col-md-12">
<ServiceJobs />
</div> */}
</div>
</div> </div>
);
{!isAllProjectsSelected && ( <div
className={`${!isAllProjectsSelected ? "col-sm-6 col-lg-6" : "col-sm-6 col-lg-6"
}`}
>
<TasksCard />
</div>)}
<div className="col-12 col-xl-4 col-md-6">
<div className="card ">
<ExpenseStatus />
</div>
</div>
<div className="col-12 col-xl-8">
<div className="card h-100">
<ExpenseAnalysis />
</div>
</div>
<div className="col-12 col-md-6">
<ExpenseByProject />
</div>
{isAllProjectsSelected && (
<div className="col-xxl-6 col-lg-6">
<ProjectCompletionChart />
</div>
)}
<div className="col-xxl-6 col-lg-6">
<ProjectProgressChart />
</div>
{!isAllProjectsSelected &&
(canRegularize || canTeamAttendance || canSelfAttendance) && (
<div className="col-12 col-md-6 mb-sm-0 mb-4">
<AttendanceOverview />
</div>
)}
{isAllProjectsSelected && <div className="col-12 col-md-6 mb-sm-0 mb-4">
<ProjectWiseTeamCount />
</div>}
{!isAllProjectsSelected && (
<div className="col-xxl-4 col-lg-4">
<div className="card h-100">
<ProjectStatistics />
</div>
</div>
)}
{isAllProjectsSelected && (
<div className="col-12 col-md-4 mb-sm-0 mb-4">
<ServiceJobs />
</div>
)}
<div className="col-md-8">
{isLoading ? (
<CollectionOverviewSkeleton />
) : (
data && (
<div className="card">
<TopicBarChart data={data} />
</div>
)
)}
</div>
</div>
</div>
);
}; };
export default Dashboard; export default Dashboard;

View File

@ -52,6 +52,18 @@ const ExpenseAnalysis = () => {
legend: { show: false }, legend: { show: false },
dataLabels: { enabled: true, formatter: (val) => `${val.toFixed(0)}%` }, dataLabels: { enabled: true, formatter: (val) => `${val.toFixed(0)}%` },
colors: flatColors, colors: flatColors,
tooltip: {
y: {
formatter: function (value) {
return formatCurrency(value);
},
},
x: {
formatter: function (label) {
return label;
},
},
},
plotOptions: { plotOptions: {
pie: { pie: {
donut: { donut: {
@ -88,7 +100,7 @@ const ExpenseAnalysis = () => {
<div className="text-end text-sm-end"> <div className="text-end text-sm-end">
<FormProvider {...methods}> <FormProvider {...methods}>
<DateRangePicker1 /> <DateRangePicker1 pastDays="30" />
</FormProvider> </FormProvider>
</div> </div>
</div> </div>
@ -140,7 +152,9 @@ const ExpenseAnalysis = () => {
className="col-6" className="col-6"
key={idx} key={idx}
style={{ style={{
borderLeft: `3px solid ${flatColors[idx % flatColors.length]}`, borderLeft: `3px solid ${
flatColors[idx % flatColors.length]
}`,
}} }}
> >
<div className="d-flex flex-column text-start"> <div className="d-flex flex-column text-start">
@ -165,7 +179,6 @@ const ExpenseAnalysis = () => {
</span> </span>
</div> </div>
</div> </div>
))} ))}
</div> </div>
</div> </div>

View File

@ -92,45 +92,40 @@ const ExpenseByProject = () => {
<div className="card shadow-sm h-100 rounded "> <div className="card shadow-sm h-100 rounded ">
{/* Header */} {/* Header */}
<div className="card-header"> <div className="card-header">
<div className="d-flex justify-content-between align-items-center mb-1 mt-1"> <div className="d-block justify-content-between align-items-center mb-1 mt-1">
<div className="text-start"> <div className="text-start">
<h5 className="mb-1 me-6 card-title">Monthly Expense -</h5> <h5 className="mb-1 me-6 card-title">Monthly Expense </h5>
<p className="card-subtitle m-0">{projectName}</p> <div className="row w-100">
</div> <div className="col-6"> <p className="card-subtitle m-0">{projectName}</p></div>
<div className="btn-group mb-5 ms-n8"> <div className="col-6 d-flex justify-content-between align-items-center px-0">
<button
className="btn btn-sm dropdown-toggle fs-5"
type="button"
data-bs-toggle="dropdown" <select
aria-expanded="false" className="form-select form-select-sm ms-auto mt-sm-0"
value={selectedType}
onChange={(e) => setSelectedType(e.target.value)}
disabled={typeLoading}
style={{ maxWidth: "200px" }}
> >
{viewMode} <option value="">All Categories</option>
</button> {expenseCategories?.map((type) => (
<ul className="dropdown-menu dropdown-menu-end "> <option key={type.id} value={type.id}>
<li> {type.name}
<button </option>
className="dropdown-item" ))}
onClick={() => { </select>
setViewMode("Category");
setSelectedType(""); </div>
}}
>
Category
</button>
</li> </div>
<li>
<button
className="dropdown-item"
onClick={() => {
setViewMode("Project");
setSelectedType("");
}}
>
Project
</button>
</li>
</ul>
</div> </div>
</div> </div>
{/* Range Buttons + Expense Dropdown */} {/* Range Buttons + Expense Dropdown */}
@ -148,22 +143,7 @@ const ExpenseByProject = () => {
{item} {item}
</button> </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>
{expenseCategories?.map((type) => (
<option key={type.id} value={type.id}>
{type.name}
</option>
))}
</select>
)}
</div> </div>
</div> </div>

View File

@ -12,14 +12,17 @@ const ProjectCompletionChart = () => {
isError, isError,
error, error,
} = useProjectCompletionStatus(); } = useProjectCompletionStatus();
const projectNames = projects?.map((p) => p.name) || []; const filteredProjects = projects?.filter((p) => p.completedWork > 0) || [];
const projectProgress =
projects?.map((p) => { const projectNames = filteredProjects.map((p) => p.name);
const completed = p.completedWork || 0;
const planned = p.plannedWork || 1; const projectProgress = filteredProjects.map((p) => {
const percent = planned ? (completed / planned) * 100 : 0; const completed = p.completedWork || 0;
return Math.min(Math.round(percent), 100); const planned = p.plannedWork || 1;
}) || []; const percent = planned ? (completed / planned) * 100 : 0;
return Math.min(parseFloat(percent.toFixed(2)), 100); // limit to 2 decimals
});
return ( return (
<div className="card h-100"> <div className="card h-100">

View File

@ -1,6 +1,6 @@
import React, { useState } from "react"; import React, { useState } from "react";
import LineChart from "../Charts/LineChart"; import LineChart from "../Charts/LineChart";
import { useProjects } from "../../hooks/useProjects"; import { useProjectName } from "../../hooks/useProjects";
import { useDashboard_Data } from "../../hooks/useDashboard_Data"; import { useDashboard_Data } from "../../hooks/useDashboard_Data";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
@ -11,7 +11,7 @@ const ProjectProgressChart = ({
const selectedProject = useSelector( const selectedProject = useSelector(
(store) => store.localVariables.projectId (store) => store.localVariables.projectId
); );
const { projects } = useProjects(); const { projectNames } = useProjectName();
const [range, setRange] = useState(DefaultRange); const [range, setRange] = useState(DefaultRange);
const [showAllEmployees, setShowAllEmployees] = useState(false); const [showAllEmployees, setShowAllEmployees] = useState(false);
@ -79,7 +79,9 @@ const ProjectProgressChart = ({
}) })
); );
const selectedProjectData = projects?.find((p) => p.id === selectedProject); const selectedProjectData = projectNames?.find(
(p) => p.id === selectedProject
);
const selectedProjectName = selectedProjectData?.shortName?.trim() const selectedProjectName = selectedProjectData?.shortName?.trim()
? selectedProjectData.shortName ? selectedProjectData.shortName
: selectedProjectData?.name; : selectedProjectData?.name;
@ -90,7 +92,7 @@ const ProjectProgressChart = ({
<div className="d-flex flex-wrap justify-content-between align-items-start mb-2"> <div className="d-flex flex-wrap justify-content-between align-items-start mb-2">
{/* Left: Title */} {/* Left: Title */}
<div className="card-title text-start"> <div className="card-title text-start">
<h5 className="mb-1 fw-bold">Project Progress</h5> <h5 className="mb-1 fw-semibold">Project Progress</h5>
<p className="card-subtitle">Progress Overview by Project</p> <p className="card-subtitle">Progress Overview by Project</p>
</div> </div>
</div> </div>

View File

@ -0,0 +1,112 @@
import React from "react";
import { useProjectName } from "../../hooks/useProjects";
import { BUCKET_BG_CLASSES } from "../../utils/constants";
import { useAttendaceProjectWiseOveriew } from "../../hooks/useDashboard_Data";
import { AppColors, localToUtc } from "../../utils/appUtils";
import DatePicker from "../common/DatePicker";
import { useAppForm, useAppWatch } from "../../hooks/appHooks/useAppForm";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { setProjectId } from "../../slices/localVariablesSlice";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
const ProjectWiseTeamCount = () => {
const dispatch = useDispatch();
const navigate = useNavigate();
const { control } = useAppForm({
resolver: zodResolver(
z.object({
date: z.string().optional(),
})
),
defaultValues: {
date: new Date().toISOString().slice(0, 10),
},
});
const goToProject = (projectId) => () => {
dispatch(setProjectId(projectId));
navigate(`/projects/details`);
};
const selectedDate = useAppWatch({ control, name: "date" });
const { data, isLoading, isFetching, isError, error } =
useAttendaceProjectWiseOveriew(localToUtc(selectedDate));
const percent = (teamCount, attendanceCount) => {
return teamCount > 0 ? Math.round((attendanceCount / teamCount) * 100) : 0;
};
return (
<div className="card h-100 p-3">
{/* Header */}
<div className="d-flex justify-content-between text-start mb-2">
<h5 className="card-title m-0 me-2">Attendance by Project</h5>
<DatePicker name="date" control={control} maxDate={new Date()} />
</div>
{/* Only show spinner for new data, not full component */}
{isFetching && !isLoading && (
<div className="small text-end text-muted">Updating</div>
)}
{/* Table */}
<div className="table-container">
<table className="table table-borderless mb-0">
<thead className="table-header">
<tr>
<th style={{ width: 200 }} className="text-start">
Project
</th>
<th style={{ width: 100 }}>Team Size</th>
<th style={{ width: 80 }} className="text-start">
Logged In
</th>
{/* <th>Percentage</th> */}
</tr>
</thead>
</table>
<div
className="table-body-scroll overflow-auto pe-1"
style={{ maxHeight: "60vh" }}
>
<table className="table table-borderless mb-0">
<tbody>
{(data ?? []).map((item, index) => (
<tr key={item.projectId || index}>
<td style={{ width: 200 }}>
<div
className="d-flex align-items-center text-wrap my-2 text-start"
style={{ width: "180px" }}
>
<a
onClick={goToProject(item.projectId)}
className="text-heading text-truncate cursor-pointer"
>
{" "}
<span className="text-heading">{item.projectName}</span>
</a>
</div>
</td>
<td className="text-center" style={{ width: 80 }}>
{item.teamCount}
</td>
<td className="text-center" style={{ width: 80 }}>
{item.attendanceCount}
</td>
{/* <td>{percent(item.teamCount, item.attendanceCount)}%</td> */}
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
);
};
export default ProjectWiseTeamCount;

View File

@ -1,234 +1,185 @@
import React from "react"; import React, { useEffect, useRef, useState } from "react";
import { useParams } from "react-router-dom";
import { useJobsProgression } from "../../hooks/useDashboard_Data";
import { SpinnerLoader } from "../common/Loader";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import { useServiceProject } from "../../hooks/useServiceProject";
const ServiceJobs = () => { const ServiceJobs = () => {
const { projectId } = useParams();
const { data, isLoading, isError } = useJobsProgression(projectId);
const jobs = data || {};
const { data: projectData, isLoading: projectLoading } =
useServiceProject(projectId);
const [activeTab, setActiveTab] = useState("tab-new");
// 👇 prevents re-running auto logic after first load
const hasInitializedTab = useRef(false);
const tabMapping = [
{ id: "tab-new", label: "My Jobs", key: "myJobs" },
{ id: "tab-shipping", label: "In Progress", key: "inProgressJobs" },
{ id: "tab-preparing", label: "Assigned", key: "assignedJobs" },
];
/* ---------- INITIAL TAB SELECTION ONLY ---------- */
useEffect(() => {
if (hasInitializedTab.current || !jobs) return;
if (jobs.myJobs?.length > 0) {
setActiveTab("tab-new");
} else if (jobs.inProgressJobs?.length > 0) {
setActiveTab("tab-shipping");
} else {
setActiveTab("tab-preparing");
}
hasInitializedTab.current = true;
}, [jobs]);
return ( return (
<div className="col-xxl-4 col-lg-6"> <div>
<div className="card h-100"> <div className="card page-min-h">
{/* Header */}
<div className="card-header d-flex justify-content-between"> <div className="card-header d-flex justify-content-between">
<div className="card-title mb-0 text-start"> <div className="card-title mb-0 text-start">
<h5 className="mb-1">Service Jobs</h5> <h5 className="mb-1 fw-bold">Service Jobs</h5>
<p className="card-subtitle">All Projects</p> <p className="card-subtitle">
{projectLoading
? "Loading..."
: projectData?.name || "All Projects"}
</p>
</div> </div>
</div> </div>
<div className="card-body p-0"> <div className="card-body p-0">
<div className="nav-align-top"> <div className="nav-align-top">
{/* Tabs */} {/* Tabs */}
<ul className="nav nav-tabs nav-fill rounded-0 timeline-indicator-advanced" role="tablist"> <ul className="nav nav-tabs nav-fill rounded-0 timeline-indicator-advanced">
<li className="nav-item"> {tabMapping.map((tab) => (
<button className="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-new"> <li className="nav-item" key={tab.id}>
My Jobs <button
</button> type="button"
</li> className={`nav-link ${
<li className="nav-item"> activeTab === tab.id ? "active" : ""
<button className="nav-link" data-bs-toggle="tab" data-bs-target="#tab-preparing"> }`}
Assigned onClick={() => setActiveTab(tab.id)}
</button> >
</li> {tab.label}
<li className="nav-item"> </button>
<button className="nav-link" data-bs-toggle="tab" data-bs-target="#tab-shipping"> </li>
In Progress ))}
</button>
</li>
</ul> </ul>
{/* Tab Content */} {/* Content */}
<div className="tab-content border-0 mx-1 text-start"> <div className="tab-content border-0 mx-1 text-start">
{isLoading && (
<div
className="text-center"
style={{
height: "250px",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<SpinnerLoader />
</div>
)}
{/* ---------------------- NEW TAB ---------------------- */} {isError && (
<div className="tab-pane fade show active" id="tab-new"> <p
{/* Entry 1 */} className="text-center"
<ul className="timeline mb-0"> style={{
<li className="timeline-item ps-6 border-left-dashed"> height: "250px",
<span className="timeline-indicator-advanced timeline-indicator-success border-0 shadow-none"> display: "flex",
<i className="bx bx-check-circle"></i> justifyContent: "center",
</span> alignItems: "center",
<div className="timeline-event ps-1"> margin: 0,
<div className="timeline-header"> }}
<small className="text-success text-uppercase">Sender</small> >
</div> No data found
<h6 className="my-50">Myrtle Ullrich</h6> </p>
<p className="text-body mb-0">101 Boulder, California(CA), 95959</p> )}
{!isLoading &&
!isError &&
tabMapping.map((tab) => {
const list = jobs[tab.key] || [];
return (
<div
key={tab.id}
className={`tab-pane fade ${
activeTab === tab.id ? "show active" : ""
}`}
>
{list.length === 0 ? (
<p
className="text-center"
style={{
height: "250px",
display: "flex",
justifyContent: "center",
alignItems: "center",
margin: 0,
}}
>
No jobs found
</p>
) : (
<div className="job-scroll-wrapper">
{list.map((job, index) => (
<React.Fragment key={index}>
<ul className="timeline mb-0">
<li className="timeline-item ps-6 border-left-dashed">
<span className="timeline-indicator-advanced timeline-indicator-success border-0 shadow-none">
<i className="bx bx-check-circle"></i>
</span>
<div className="timeline-event ps-1">
<small className="text-success text-uppercase">
Assigned By
</small>
<h6 className="my-50">{job.assignedBy}</h6>
<p className="text-body mb-0">
{formatUTCToLocalTime(job.assignedAt)}
</p>
</div>
</li>
<li className="timeline-item ps-6 border-transparent">
<span className="timeline-indicator-advanced timeline-indicator-primary border-0 shadow-none">
<i className="bx bx-map"></i>
</span>
<div className="timeline-event ps-1">
<small className="text-primary text-uppercase">
Project
</small>
<h6 className="my-50">{job.project}</h6>
<p className="text-body mb-0">
{job.title}
</p>
</div>
</li>
</ul>
{index < list.length - 1 && (
<div className="border-1 border-light border-top border-dashed my-4"></div>
)}
</React.Fragment>
))}
</div>
)}
</div> </div>
</li> );
<li className="timeline-item ps-6 border-transparent"> })}
<span className="timeline-indicator-advanced timeline-indicator-primary border-0 shadow-none">
<i className="bx bx-map"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-primary text-uppercase">Receiver</small>
</div>
<h6 className="my-50">Barry Schowalter</h6>
<p className="text-body mb-0">939 Orange, California(CA), 92118</p>
</div>
</li>
</ul>
<div className="border-1 border-light border-top border-dashed my-4"></div>
{/* Entry 2 */}
<ul className="timeline mb-0">
<li className="timeline-item ps-6 border-left-dashed">
<span className="timeline-indicator-advanced timeline-indicator-success border-0 shadow-none">
<i className="bx bx-check-circle"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-success text-uppercase">Sender</small>
</div>
<h6 className="my-50">Veronica Herman</h6>
<p className="text-body mb-0">162 Windsor, California(CA), 95492</p>
</div>
</li>
<li className="timeline-item ps-6 border-transparent">
<span className="timeline-indicator-advanced timeline-indicator-primary border-0 shadow-none">
<i className="bx bx-map"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-primary text-uppercase">Receiver</small>
</div>
<h6 className="my-50">Helen Jacobs</h6>
<p className="text-body mb-0">487 Sunset, California(CA), 94043</p>
</div>
</li>
</ul>
</div>
{/* ---------------------- PREPARING TAB ---------------------- */}
<div className="tab-pane fade" id="tab-preparing">
{/* Entry 1 */}
<ul className="timeline mb-0">
<li className="timeline-item ps-6 border-left-dashed">
<span className="timeline-indicator-advanced timeline-indicator-warning border-0 shadow-none">
<i className="bx bx-time-five"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-warning text-uppercase">Sender</small>
</div>
<h6 className="my-50">Oliver Grant</h6>
<p className="text-body mb-0">220 Pine St, California(CA), 95765</p>
</div>
</li>
<li className="timeline-item ps-6 border-transparent">
<span className="timeline-indicator-advanced timeline-indicator-primary border-0 shadow-none">
<i className="bx bx-map"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-primary text-uppercase">Receiver</small>
</div>
<h6 className="my-50">Samantha Lee</h6>
<p className="text-body mb-0">744 Bay Area, California(CA), 94016</p>
</div>
</li>
</ul>
<div className="border-1 border-light border-top border-dashed my-4"></div>
{/* Entry 2 */}
<ul className="timeline mb-0">
<li className="timeline-item ps-6 border-left-dashed">
<span className="timeline-indicator-advanced timeline-indicator-warning border-0 shadow-none">
<i className="bx bx-time-five"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-warning text-uppercase">Sender</small>
</div>
<h6 className="my-50">Marcus Howard</h6>
<p className="text-body mb-0">58 Avenue, California(CA), 95376</p>
</div>
</li>
<li className="timeline-item ps-6 border-transparent">
<span className="timeline-indicator-advanced timeline-indicator-primary border-0 shadow-none">
<i className="bx bx-map"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-primary text-uppercase">Receiver</small>
</div>
<h6 className="my-50">Daniel Foster</h6>
<p className="text-body mb-0">312 Marina, California(CA), 94109</p>
</div>
</li>
</ul>
</div>
{/* ---------------------- SHIPPING TAB ---------------------- */}
<div className="tab-pane fade" id="tab-shipping">
{/* Entry 1 */}
<ul className="timeline mb-0">
<li className="timeline-item ps-6 border-left-dashed">
<span className="timeline-indicator-advanced timeline-indicator-info border-0 shadow-none">
<i className="bx bx-package"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-info text-uppercase">Sender</small>
</div>
<h6 className="my-50">James Carter</h6>
<p className="text-body mb-0">441 Market St, California(CA), 94111</p>
</div>
</li>
<li className="timeline-item ps-6 border-transparent">
<span className="timeline-indicator-advanced timeline-indicator-primary border-0 shadow-none">
<i className="bx bx-map"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-primary text-uppercase">Receiver</small>
</div>
<h6 className="my-50">Linda Moore</h6>
<p className="text-body mb-0">990 Willow Road, California(CA), 94025</p>
</div>
</li>
</ul>
<div className="border-1 border-light border-top border-dashed my-4"></div>
{/* Entry 2 */}
<ul className="timeline mb-0">
<li className="timeline-item ps-6 border-left-dashed">
<span className="timeline-indicator-advanced timeline-indicator-info border-0 shadow-none">
<i className="bx bx-package"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-info text-uppercase">Sender</small>
</div>
<h6 className="my-50">Sarah Bennett</h6>
<p className="text-body mb-0">882 Canyon Rd, California(CA), 94704</p>
</div>
</li>
<li className="timeline-item ps-6 border-transparent">
<span className="timeline-indicator-advanced timeline-indicator-primary border-0 shadow-none">
<i className="bx bx-map"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-primary text-uppercase">Receiver</small>
</div>
<h6 className="my-50">George Simmons</h6>
<p className="text-body mb-0">19 Palm St, California(CA), 93001</p>
</div>
</li>
</ul>
</div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
); );

View File

@ -43,7 +43,7 @@ const BucketForm = ({ selectedBucket, mode, onSubmit, onCancel, isPending }) =>
Name Name
</Label> </Label>
<input <input
className="form-control form-control-sm" className="form-control"
{...register("name")} {...register("name")}
/> />
{errors.name && ( {errors.name && (
@ -51,12 +51,12 @@ const BucketForm = ({ selectedBucket, mode, onSubmit, onCancel, isPending }) =>
)} )}
</div> </div>
<div className="mb-3"> <div className="my-3">
<Label htmlFor="description" className="text-start" required> <Label htmlFor="description" className="text-start" required>
Description Description
</Label> </Label>
<textarea <textarea
className="form-control form-control-sm" className="form-control"
{...register("description")} {...register("description")}
rows="3" rows="3"
/> />

View File

@ -14,7 +14,7 @@ const BucketList = ({ buckets, loading, searchTerm, onEdit, onDelete }) => {
if (!loading && sorted.length === 0) return <div>No buckets found</div>; if (!loading && sorted.length === 0) return <div>No buckets found</div>;
return ( return (
<div className="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-3 pt-3 px-2 px-sm-0"> <div className="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-3 pt-3 px-2 px-sm-0 text-start">
{sorted.map((bucket) => ( {sorted.map((bucket) => (
<div className="col" key={bucket.id}> <div className="col" key={bucket.id}>
<div className="card h-100"> <div className="card h-100">

View File

@ -40,7 +40,7 @@ const CardViewContact = ({
className="card text-start border-1" className="card text-start border-1"
style={{ background: `${!IsActive ? "#f8f6f6" : ""}` }} style={{ background: `${!IsActive ? "#f8f6f6" : ""}` }}
> >
<div className="card-body px-1 py-2 pb-0"> <div className="card-body px-1 py-2 pb-0">
<div className="d-flex justify-content-between"> <div className="d-flex justify-content-between">
<div <div
className={`d-flex align-items-center ${ className={`d-flex align-items-center ${
@ -61,7 +61,7 @@ const CardViewContact = ({
(contact?.name || "").trim().split(" ")[1]?.charAt(0) || "" (contact?.name || "").trim().split(" ")[1]?.charAt(0) || ""
} }
/>{" "} />{" "}
<span className="text-heading fs-6 ms-2"> {contact?.name}</span> <span className="text-heading fs-6 ms-2 mt-n1"> {contact?.name}</span>
</div> </div>
<div> <div>
{IsActive && ( {IsActive && (

View File

@ -99,7 +99,7 @@ const ListViewContact = ({ data, Pagination }) => {
/> />
<div className="card "> <div className="card ">
<div <div
className="card-datatable table-responsive" className="card-datatable table-responsive page-min-h"
id="horizontal-example" id="horizontal-example"
> >
<div className="dataTables_wrapper no-footer mx-5 pb-2"> <div className="dataTables_wrapper no-footer mx-5 pb-2">
@ -120,8 +120,8 @@ const ListViewContact = ({ data, Pagination }) => {
{Array.isArray(data) && data.length > 0 ? ( {Array.isArray(data) && data.length > 0 ? (
data.map((row, i) => ( data.map((row, i) => (
<tr <tr
key={i} key={i}
style={{ background: `${!showActive ? "#f8f6f6" : ""}` }} style={{height: "50px", background: `${!showActive ? "#f8f6f6" : ""}` }}
> >
{contactList.map((col) => ( {contactList.map((col) => (
<td key={col.key} className={col.align}> <td key={col.key} className={col.align}>

View File

@ -45,7 +45,7 @@ const ManageBucket1 = () => {
return ( return (
<div className="container m-0 p-0" style={{ minHeight: "00px" }}> <div className="container m-0 p-0" style={{ minHeight: "00px" }}>
<div className="d-flex justify-content-center"> <div className="d-flex justify-content-center">
<p className="fs-5 fw-semibold m-0">Manage Buckets</p> <h5 className="m-0">Manage Buckets</h5>
</div> </div>
{action ? ( {action ? (

View File

@ -19,6 +19,9 @@ import SelectMultiple from "../common/SelectMultiple";
import { ContactSchema, defaultContactValue } from "./DirectorySchema"; import { ContactSchema, defaultContactValue } from "./DirectorySchema";
import InputSuggestions from "../common/InputSuggestion"; import InputSuggestions from "../common/InputSuggestion";
import Label from "../common/Label"; import Label from "../common/Label";
import { AppFormController } from "../../hooks/appHooks/useAppForm";
import SelectField from "../common/Forms/SelectField";
import { BUCKET_BG_CLASSES } from "../../utils/constants";
const ManageContact = ({ contactId, closeModal }) => { const ManageContact = ({ contactId, closeModal }) => {
// fetch master data // fetch master data
@ -194,7 +197,7 @@ const ManageContact = ({ contactId, closeModal }) => {
Name Name
</Label> </Label>
<input <input
className="form-control form-control-sm" className="form-control "
{...register("name")} {...register("name")}
/> />
{errors.name && ( {errors.name && (
@ -210,6 +213,7 @@ const ManageContact = ({ contactId, closeModal }) => {
value={watch("organization") || ""} value={watch("organization") || ""}
onChange={(val) => setValue("organization", val, { shouldValidate: true })} onChange={(val) => setValue("organization", val, { shouldValidate: true })}
error={errors.organization?.message} error={errors.organization?.message}
size="md"
/> />
</div> </div>
@ -222,7 +226,7 @@ const ManageContact = ({ contactId, closeModal }) => {
Designation Designation
</Label> </Label>
<input <input
className="form-control form-control-sm" className="form-control "
{...register("designation")} {...register("designation")}
onChange={handleDesignationChange} onChange={handleDesignationChange}
/> />
@ -257,7 +261,7 @@ const ManageContact = ({ contactId, closeModal }) => {
</div> </div>
{/* Emails + Phones */} {/* Emails + Phones */}
<div className="row mt-1"> <div className="row mt-3">
<div className="col-md-6"> <div className="col-md-6">
{emailFields.map((field, index) => ( {emailFields.map((field, index) => (
<div <div
@ -265,22 +269,39 @@ const ManageContact = ({ contactId, closeModal }) => {
className="row d-flex align-items-center mb-1" className="row d-flex align-items-center mb-1"
> >
<div className="col-5 text-start"> <div className="col-5 text-start">
<label className="form-label">Label</label> <AppFormController
<select name={`contactEmails.${index}.label`}
className="form-select form-select-sm" control={control}
{...register(`contactEmails.${index}.label`)} render={({ field }) => (
> <SelectField
<option value="Work">Work</option> label="Label"
<option value="Personal">Personal</option> options={[
<option value="Other">Other</option> { id: "Work", name: "Work" },
</select> { id: "Personal", name: "Personal" },
{ id: "Other", name: "Other" }
]}
placeholder="Choose a Label"
required
labelKey="name"
valueKeyKey="id"
value={field.value}
onChange={field.onChange}
className="m-0"
/>
)}
/>
{errors.contactEmails?.[index]?.label && (
<small className="danger-text">
{errors.contactEmails[index].label.message}
</small>
)}
</div> </div>
<div className="col-7 text-start"> <div className="col-7 text-start mt-n3">
<label className="form-label">Email</label> <label className="form-label">Email</label>
<div className="d-flex align-items-center"> <div className="d-flex align-items-center">
<input <input
type="email" type="email"
className="form-control form-control-sm" className="form-control "
{...register(`contactEmails.${index}.emailAddress`)} {...register(`contactEmails.${index}.emailAddress`)}
placeholder="email@example.com" placeholder="email@example.com"
/> />
@ -308,27 +329,43 @@ const ManageContact = ({ contactId, closeModal }) => {
<div className="col-md-6"> <div className="col-md-6">
{phoneFields.map((field, index) => ( {phoneFields.map((field, index) => (
<div <div key={field.id} className="row d-flex align-items-center mb-2">
key={field.id}
className="row d-flex align-items-center mb-2"
>
<div className="col-5 text-start"> <div className="col-5 text-start">
<label className="form-label">Label</label> <AppFormController
<select name={`contactPhones.${index}.label`}
className="form-select form-select-sm" control={control}
{...register(`contactPhones.${index}.label`)} render={({ field }) => (
> <SelectField
<option value="Office">Office</option> label="Label"
<option value="Personal">Personal</option> options={[
<option value="Business">Business</option> { id: "Office", name: "Office" },
</select> { id: "Personal", name: "Personal" },
{ id: "Business", name: "Business" }
]}
placeholder="Choose a Label"
required
labelKey="name"
valueKeyKey="id"
value={field.value}
onChange={field.onChange}
className="m-0"
/>
)}
/>
{errors.contactPhones?.[index]?.label && (
<small className="danger-text">
{errors.contactPhones[index].label.message}
</small>
)}
</div> </div>
<div className="col-7 text-start">
<div className="col-7 text-start mt-n3">
<label className="form-label">Phone</label> <label className="form-label">Phone</label>
<div className="d-flex align-items-center"> <div className="d-flex align-items-center">
<input <input
type="text" type="text"
className="form-control form-control-sm" className="form-control "
{...register(`contactPhones.${index}.phoneNumber`)} {...register(`contactPhones.${index}.phoneNumber`)}
placeholder="9876543210" placeholder="9876543210"
/> />
@ -350,42 +387,43 @@ const ManageContact = ({ contactId, closeModal }) => {
</small> </small>
)} )}
</div> </div>
</div> </div>
))} ))}
</div> </div>
</div> </div>
{/* Category + Projects */} {/* Category + Projects */}
<div className="row my-1"> <div className="row">
<div className="col-md-6 text-start"> <div className="col-md-6 text-start">
<label className="form-label">Category</label> <AppFormController
<select name="contactCategoryId"
className="form-select form-select-sm" control={control}
{...register("contactCategoryId")} rules={{ required: "Category is required" }}
> render={({ field }) => (
{contactCategoryLoading && !contactCategory ? ( <SelectField
<option disabled value=""> label="Category"
Loading... required
</option> options={contactCategory ?? []}
) : ( placeholder="Select Category"
<> labelKey="name"
<option disabled value=""> valueKeyKey="id"
Select Category value={field.value}
</option> onChange={field.onChange}
{contactCategory?.map((cate) => ( isLoading={contactCategoryLoading && !contactCategory}
<option key={cate.id} value={cate.id}> className="m-0"
{cate.name} />
</option>
))}
</>
)} )}
</select> />
{errors.contactCategoryId && ( {errors.contactCategoryId && (
<small className="danger-text"> <small className="danger-text">
{errors.contactCategoryId.message} {errors.contactCategoryId.message}
</small> </small>
)} )}
</div> </div>
<div className="col-12 col-md-6 text-start"> <div className="col-12 col-md-6 text-start">
<SelectMultiple <SelectMultiple
name="projectIds" name="projectIds"
@ -402,13 +440,14 @@ const ManageContact = ({ contactId, closeModal }) => {
</div> </div>
{/* Tags */} {/* Tags */}
<div className="col-12 text-start"> <div className="col-12 text-start mt-3">
<TagInput <TagInput
name="tags" name="tags"
label="Tags" label="Tags"
options={contactTags} options={contactTags}
isRequired={true} isRequired={true}
placeholder="Enter Tag" placeholder="Enter Tag"
size="sm"
/> />
{errors.tags && ( {errors.tags && (
<small className="danger-text">{errors.tags.message}</small> <small className="danger-text">{errors.tags.message}</small>
@ -417,16 +456,26 @@ const ManageContact = ({ contactId, closeModal }) => {
{/* Buckets */} {/* Buckets */}
<div className="row"> <div className="row">
<div className="col-md-12 mt-1 text-start"> <div className="col-md-12 mt-3 text-start">
<label className="form-label ">Select Bucket</label> <Label className="form-label mb-2" required>Select Bucket</Label>
<ul className="d-flex flex-wrap px-1 list-unstyled mb-0">
<div
className="d-flex flex-wrap gap-3 p-1"
style={{
maxHeight: "200px",
overflowY: "auto",
}}
>
{bucketsLoaging && <p>Loading...</p>} {bucketsLoaging && <p>Loading...</p>}
{buckets?.map((item) => (
<li {buckets?.map((item, index) => (
<div
key={item.id} key={item.id}
className="list-inline-item flex-shrink-0 me-6 mb-1" className={`card p-2 shadow-sm flex-shrink-0 ${BUCKET_BG_CLASSES[index % BUCKET_BG_CLASSES.length]}`}
onClick={() => handleCheckboxChange(item.id)}
> >
<div className="form-check">
<div className="form-check m-0">
<input <input
type="checkbox" type="checkbox"
className="form-check-input" className="form-check-input"
@ -434,16 +483,17 @@ const ManageContact = ({ contactId, closeModal }) => {
checked={watchBucketIds.includes(item.id)} checked={watchBucketIds.includes(item.id)}
onChange={() => handleCheckboxChange(item.id)} onChange={() => handleCheckboxChange(item.id)}
/> />
<label <label className="form-check-label ms-0" htmlFor={`item-${item.id}`}>
className="form-check-label"
htmlFor={`item-${item.id}`}
>
{item.name} {item.name}
</label> </label>
</div> </div>
</li> </div>
))} ))}
</ul>
</div>
</div>
<div className="text-start mt-3 mb-3">
{errors.bucketIds && ( {errors.bucketIds && (
<small className="danger-text">{errors.bucketIds.message}</small> <small className="danger-text">{errors.bucketIds.message}</small>
)} )}
@ -454,15 +504,15 @@ const ManageContact = ({ contactId, closeModal }) => {
<div className="col-12 text-start"> <div className="col-12 text-start">
<label className="form-label">Address</label> <label className="form-label">Address</label>
<textarea <textarea
className="form-control form-control-sm" className="form-control "
rows="2" rows="2"
{...register("address")} {...register("address")}
/> />
</div> </div>
<div className="col-12 text-start"> <div className="col-12 text-start mt-3">
<label className="form-label">Description</label> <label className="form-label">Description</label>
<textarea <textarea
className="form-control form-control-sm" className="form-control "
rows="2" rows="2"
{...register("description")} {...register("description")}
/> />

View File

@ -9,6 +9,7 @@ import ConfirmModal from "../common/ConfirmModal"; // Make sure path is correct
import "../common/TextEditor/Editor.css"; import "../common/TextEditor/Editor.css";
import GlobalModel from "../common/GlobalModel"; import GlobalModel from "../common/GlobalModel";
import { useActiveInActiveNote, useUpdateNote } from "../../hooks/useDirectory"; import { useActiveInActiveNote, useUpdateNote } from "../../hooks/useDirectory";
import { useDirectoryContext } from "../../pages/Directory/DirectoryPage";
const NoteCardDirectoryEditable = ({ const NoteCardDirectoryEditable = ({
noteItem, noteItem,
@ -22,14 +23,14 @@ const NoteCardDirectoryEditable = ({
const [isDeleting, setIsDeleting] = useState(false); const [isDeleting, setIsDeleting] = useState(false);
const [isRestoring, setIsRestoring] = useState(false); const [isRestoring, setIsRestoring] = useState(false);
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false); const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const [open_contact, setOpen_contact] = useState(null);
const [isOpenModalNote, setIsOpenModalNote] = useState(false);
const { mutate: UpdateNote, isPending: isUpatingNote } = useUpdateNote(() => const { mutate: UpdateNote, isPending: isUpatingNote } = useUpdateNote(() =>
setEditing(false) setEditing(false)
); );
const { mutate: ActiveInactive, isPending: isUpdatingStatus } = const { mutate: ActiveInactive, isPending: isUpdatingStatus } =
useActiveInActiveNote(() => setIsDeleteModalOpen(false)); useActiveInActiveNote(() => setIsDeleteModalOpen(false));
const { setContactOpen } = useDirectoryContext();
const handleUpdateNote = async () => { const handleUpdateNote = async () => {
const payload = { const payload = {
@ -45,12 +46,6 @@ const NoteCardDirectoryEditable = ({
ActiveInactive({ noteId: noteItem.id, noteStatus: !noteItem.isActive }); ActiveInactive({ noteId: noteItem.id, noteStatus: !noteItem.isActive });
}; };
const contactProfile = (contactId) => {
DirectoryRepository.GetContactProfile(contactId).then((res) => {
setOpen_contact(res?.data);
setIsOpenModalNote(true);
});
};
const handleRestore = async () => { const handleRestore = async () => {
try { try {
@ -88,7 +83,9 @@ const NoteCardDirectoryEditable = ({
<div> <div>
<div <div
className="d-flex ms-3 align-middle cursor-pointer" className="d-flex ms-3 align-middle cursor-pointer"
onClick={() => contactProfile(noteItem.contactId)} onClick={() =>
setContactOpen({ contact: { id: noteItem.contactId }, Open: true })
}
> >
<span> <span>
<span className="fw-bold "> {noteItem?.contactName} </span>{" "} <span className="fw-bold "> {noteItem?.contactName} </span>{" "}
@ -97,6 +94,7 @@ const NoteCardDirectoryEditable = ({
</span> </span>
</span> </span>
</div> </div>
<div className="d-flex ms-0 align-middle"></div> <div className="d-flex ms-0 align-middle"></div>
<div className="d-flex ms-3 mt-2"> <div className="d-flex ms-3 mt-2">
<span className="text-muted"> <span className="text-muted">

View File

@ -59,12 +59,18 @@ const DocumentFilterPanel = forwardRef(
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
resetFieldValue: (name, value) => { resetFieldValue: (name, value) => {
if (value !== undefined) { if (value !== undefined) {
setValue(name, value); setValue(name, value, { shouldValidate: true, shouldDirty: true });
} else { } else {
reset({ ...methods.getValues(), [name]: DocumentFilterDefaultValues[name] }); reset({ ...methods.getValues(), [name]: DocumentFilterDefaultValues[name] });
} }
if ((name === "startDate" || name === "endDate") && value === null) {
setTimeout(() => {
setResetKey((prev) => prev + 1);
}, 0);
}
}, },
getValues: methods.getValues, // optional, to read current filter state getValues: methods.getValues,
})); }));
//changes //changes
@ -141,6 +147,7 @@ const DocumentFilterPanel = forwardRef(
defaultRange={false} defaultRange={false}
resetSignal={resetKey} resetSignal={resetKey}
maxDate={new Date()} maxDate={new Date()}
className="w-100"
/> />
</div> </div>

View File

@ -124,26 +124,27 @@ const Documents = ({ Document_Entity, Entity }) => {
const updatedFilters = { ...filters }; const updatedFilters = { ...filters };
if (Array.isArray(updatedFilters[key])) { if (Array.isArray(updatedFilters[key])) {
updatedFilters[key] = updatedFilters[key].filter((v) => v !== id); updatedFilters[key] = updatedFilters[key].filter((v) => v !== id);
updatedRef.current?.resetFieldValue(key,updatedFilters[key]); updatedRef.current?.resetFieldValue(key, updatedFilters[key]);
} }
else if (key === "dateRange") { else if (key === "dateRange") {
updatedFilters.startDate = null; updatedFilters.startDate = null;
updatedFilters.endDate = null; updatedFilters.endDate = null;
updatedRef.current?.resetFieldValue("startDate",null); // These calls correctly tell the DocumentFilterPanel to update its form state:
updatedRef.current?.resetFieldValue("endDate",null); updatedRef.current?.resetFieldValue("startDate", null);
updatedRef.current?.resetFieldValue("endDate", null);
} }
else { else {
updatedFilters[key] = null; updatedFilters[key] = null;
} }
setFilter(updatedFilters); setFilter(updatedFilters);
return updatedFilters; return updatedFilters;
}; };
return ( return (
<DocumentContext.Provider value={contextValues}> <DocumentContext.Provider value={contextValues}>
<div className="mt-2"> <div className="mt-2">
<div className="card page-min-h d-flex p-5"> <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 flex-row gap-2 col-12 col-md-8 col-lg-4 mb-md-0 align-items-center mb-2"> <div className="d-flex flex-row gap-2 col-12 col-md-8 col-lg-4 mb-md-0 align-items-center mb-2">
@ -194,6 +195,9 @@ const Documents = ({ Document_Entity, Entity }) => {
)} )}
</div> </div>
</div> </div>
<div className="ms-n1">
<DocumentFilterChips filters={filters} filterData={filterData} removeFilterChip={removeFilterChip} />
</div>
<DocumentsList <DocumentsList
Document_Entity={DocumentEntity} Document_Entity={DocumentEntity}
Entity={Entity} Entity={Entity}

View File

@ -197,7 +197,7 @@ const DocumentsList = ({
const isRestoring = restoringIds.includes(doc.id); const isRestoring = restoringIds.includes(doc.id);
return ( return (
<tr key={doc.id}> <tr key={doc.id} style={{ height: "50px" }}>
{DocumentColumns.map((col) => ( {DocumentColumns.map((col) => (
<td key={col.key} className={`sorting ${col.align}`}> <td key={col.key} className={`sorting ${col.align}`}>
{col.customRender {col.customRender

View File

@ -17,6 +17,8 @@ import {
import showToast from "../../services/toastService"; import showToast from "../../services/toastService";
import { useDocumentContext } from "./Documents"; import { useDocumentContext } from "./Documents";
import { isPending } from "@reduxjs/toolkit"; import { isPending } from "@reduxjs/toolkit";
import { AppFormController, AppFormProvider } from "../../hooks/appHooks/useAppForm";
import SelectField from "../common/Forms/SelectField";
const toBase64 = (file) => const toBase64 = (file) =>
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
@ -72,9 +74,12 @@ const ManageDocument = ({ closeModal, Document_Entity, Entity }) => {
handleSubmit, handleSubmit,
watch, watch,
setValue, setValue,
control,
reset, reset,
formState: { errors }, formState: { errors },
} = methods; } = methods;
const { mutate: UploadDocument, isPending: isUploading } = useUploadDocument( const { mutate: UploadDocument, isPending: isUploading } = useUploadDocument(
() => { () => {
showToast("Document Uploaded Successfully", "success"); showToast("Document Uploaded Successfully", "success");
@ -88,33 +93,33 @@ const ManageDocument = ({ closeModal, Document_Entity, Entity }) => {
} }
); );
const onSubmit = (data) => { const onSubmit = (data) => {
const normalizeAttachment = (attachment) => { const normalizeAttachment = (attachment) => {
if (!attachment) return null; if (!attachment) return null;
return { return {
...attachment, ...attachment,
fileSize: Math.ceil(attachment.fileSize / 1024), fileSize: Math.ceil(attachment.fileSize / 1024),
};
}; };
};
const payload = { const payload = {
...data, ...data,
attachment: normalizeAttachment(data.attachment), attachment: normalizeAttachment(data.attachment),
};
if (ManageDoc?.document) {
const DocumentPayload = {
...payload,
id: DocData.id,
tags: MergedTagsWithExistenStatus(data?.tags, DocData?.tags),
}; };
UpdateDocument({ documentId: DocData?.id, DocumentPayload });
} else { if (ManageDoc?.document) {
const DocumentPayload = { ...payload, entityId: Entity }; const DocumentPayload = {
UploadDocument(DocumentPayload); ...payload,
} id: DocData.id,
}; tags: MergedTagsWithExistenStatus(data?.tags, DocData?.tags),
};
UpdateDocument({ documentId: DocData?.id, DocumentPayload });
} else {
const DocumentPayload = { ...payload, entityId: Entity };
UploadDocument(DocumentPayload);
}
};
const { const {
data: DocData, data: DocData,
@ -134,7 +139,7 @@ const ManageDocument = ({ closeModal, Document_Entity, Entity }) => {
const { DocumentTypes, isLoading: isTypeLoading } = useDocumentTypes( const { DocumentTypes, isLoading: isTypeLoading } = useDocumentTypes(
categoryId || null categoryId || null
); );
const {data:DocumentTags} = useDocumentTags() const { data: DocumentTags } = useDocumentTags()
// Update schema whenever document type changes // Update schema whenever document type changes
useEffect(() => { useEffect(() => {
@ -144,7 +149,7 @@ const ManageDocument = ({ closeModal, Document_Entity, Entity }) => {
(t) => String(t.id) === String(documentTypeId) (t) => String(t.id) === String(documentTypeId)
); );
if (!type) return; if (!type) return;
setSelectedType(type) setSelectedType(type)
const newSchema = DocumentPayloadSchema({ const newSchema = DocumentPayloadSchema({
isMandatory: type.isMandatory ?? false, isMandatory: type.isMandatory ?? false,
regexExpression: type.regexExpression ?? null, regexExpression: type.regexExpression ?? null,
@ -200,10 +205,10 @@ const ManageDocument = ({ closeModal, Document_Entity, Entity }) => {
t === "application/pdf" t === "application/pdf"
? ".pdf" ? ".pdf"
: t === "image/jpeg" : t === "image/jpeg"
? ".jpg,.jpeg" ? ".jpg,.jpeg"
: t === "image/png" : t === "image/png"
? ".png" ? ".png"
: "" : ""
) )
.join(",") || ""; .join(",") || "";
@ -231,200 +236,209 @@ const ManageDocument = ({ closeModal, Document_Entity, Entity }) => {
const isPending = isUploading || isUpdating; const isPending = isUploading || isUpdating;
return ( return (
<div className="p-2"> <AppFormProvider {...methods}>
<p className="fw-bold fs-6">Upload New Document</p> <div className="p-2">
<FormProvider key={documentTypeId} {...methods}> <h5 className="">Upload New Document</h5>
<form onSubmit={handleSubmit(onSubmit)} className="text-start"> <FormProvider key={documentTypeId} {...methods}>
{/* Category */} <form onSubmit={handleSubmit(onSubmit)} className="text-start">
<div className="mb-2"> {/* Category */}
<Label htmlFor="documentCategoryId" required>Document Category</Label> <div className="col-12 col-md-12 mb-2 mb-md-4">
<select <AppFormController
{...register("documentCategoryId")} name="documentCategoryId"
className="form-select form-select-sm" control={control}
> render={({ field }) => (
{isLoading && ( <SelectField
<option disabled value=""> label="Document Category"
Loading... options={DocumentCategories ?? []}
</option> placeholder="Select Category"
)} required
{!isLoading && <option value="">Select Category</option>} labelKey="name"
{DocumentCategories?.map((type) => ( valueKeyKey="id"
<option key={type.id} value={type.id}> value={field.value}
{type.name} onChange={field.onChange}
</option> isLoading={isLoading}
))} className="m-0"
</select> />
{errors.documentCategoryId && (
<div className="danger-text">
{errors.documentCategoryId.message}
</div>
)}
</div>
{/* Type */}
{categoryId && (
<div className="mb-2">
<Label htmlFor="documentTypeId" required>Document Type</Label>
<select
{...register("documentTypeId")}
className="form-select form-select-sm"
>
{isTypeLoading && (
<option disabled value="">
Loading...
</option>
)} )}
{DocumentTypes?.map((type) => ( />
<option key={type.id} value={type.id}>
{type.name} {errors.documentCategoryId && (
</option> <small className="danger-text">
))} {errors.documentCategoryId.message}
</select> </small>
{errors.documentTypeId && (
<div className="danger-text">
{errors.documentTypeId.message}
</div>
)} )}
</div> </div>
)}
{/* Document ID */}
<div className="mb-2">
<label
htmlFor="documentId"
required={selectedType?.isMandatory ?? false}
>
Document ID
</label>
<input
type="text"
className="form-control form-control-sm"
{...register("documentId")}
/>
{errors.documentId && (
<div className="danger-text">{errors.documentId.message}</div>
)}
</div>
{/* Document Name */} {/* Type */}
<div className="mb-2"> {categoryId && (
<Label htmlFor="name" required> <div className="col-12 col-md-12 mb-2 mb-md-4">
Document Name <AppFormController
</Label> name="documentTypeId"
<input control={control}
type="text" render={({ field }) => (
className="form-control form-control-sm" <SelectField
{...register("name")} label="Document Type"
/> options={DocumentTypes ?? []}
{errors.name && ( placeholder="Select Document Type"
<div className="danger-text">{errors.name.message}</div> required
)} labelKey="name"
</div> valueKeyKey="id"
value={field.value}
onChange={field.onChange}
isLoading={isTypeLoading}
{/* Upload */} className="m-0"
<div className="row my-2"> />
<div className="col-md-12"> )}
<Label htmlFor="attachment" required>Upload Document</Label>
<div
className="border border-secondary border-dashed rounded p-4 text-center bg-textMuted position-relative"
style={{ cursor: "pointer" }}
onClick={() => document.getElementById("attachment").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">
({selectedType?.allowedContentType || "PDF/JPG/PNG"}, max{" "}
{selectedType?.maxSizeAllowedInMB ?? 25}MB)
</small>
<input
type="file"
id="attachment"
accept={selectedType?.allowedContentType}
style={{ display: "none" }}
onChange={(e) => {
onFileChange(e);
e.target.value = ""; // reset input
}}
/> />
{errors.documentTypeId && (
<small className="danger-text">
{errors.documentTypeId.message}
</small>
)}
</div> </div>
{errors.attachment && ( )}
<small className="danger-text">
{errors.attachment.message
? errors.attachment.message {/* Document ID */}
: errors.attachment.fileName?.message || <div className="mb-4">
<label
htmlFor="documentId"
required={selectedType?.isMandatory ?? false}
>
Document ID
</label>
<input
type="text"
className="form-control "
{...register("documentId")}
/>
{errors.documentId && (
<div className="danger-text">{errors.documentId.message}</div>
)}
</div>
{/* Document Name */}
<div className="mb-2">
<Label htmlFor="name" required>
Document Name
</Label>
<input
type="text"
className="form-control "
{...register("name")}
/>
{errors.name && (
<div className="danger-text">{errors.name.message}</div>
)}
</div>
{/* Upload */}
<div className="row my-4">
<div className="col-md-12">
<Label htmlFor="attachment" required>Upload Document</Label>
<div
className="border border-secondary border-dashed rounded p-4 text-center bg-textMuted position-relative"
style={{ cursor: "pointer" }}
onClick={() => document.getElementById("attachment").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">
({selectedType?.allowedContentType || "PDF/JPG/PNG"}, max{" "}
{selectedType?.maxSizeAllowedInMB ?? 25}MB)
</small>
<input
type="file"
id="attachment"
accept={selectedType?.allowedContentType}
style={{ display: "none" }}
onChange={(e) => {
onFileChange(e);
e.target.value = ""; // reset input
}}
/>
</div>
{errors.attachment && (
<small className="danger-text">
{errors.attachment.message
? errors.attachment.message
: errors.attachment.fileName?.message ||
errors.attachment.base64Data?.message || errors.attachment.base64Data?.message ||
errors.attachment.contentType?.message || errors.attachment.contentType?.message ||
errors.attachment.fileSize?.message} errors.attachment.fileSize?.message}
</small> </small>
)} )}
{file?.base64Data && ( {file?.base64Data && (
<div className="d-flex justify-content-between text-start p-1 mt-2"> <div className="d-flex justify-content-between text-start p-1 mt-2">
<div> <div>
<span className="mb-0 text-secondary small d-block"> <span className="mb-0 text-secondary small d-block">
{file.fileName} {file.fileName}
</span> </span>
<span className="text-body-secondary small d-block"> <span className="text-body-secondary small d-block">
{(file.fileSize / 1024).toFixed(1)} KB {(file.fileSize / 1024).toFixed(1)} KB
</span> </span>
</div>
<i
className="bx bx-trash bx-sm cursor-pointer text-danger"
onClick={removeFile}
></i>
</div> </div>
<i )}
className="bx bx-trash bx-sm cursor-pointer text-danger" </div>
onClick={removeFile} </div>
></i> <div className="mb-4">
</div> <TagInput name="tags" label="Tags" placeholder="Tags.." options={DocumentTags} />
{errors.tags && (
<small className="danger-text">{errors.tags.message}</small>
)} )}
</div> </div>
</div>
<div className="mb-2">
<TagInput name="tags" label="Tags" placeholder="Tags.." options={DocumentTags} />
{errors.tags && (
<small className="danger-text">{errors.tags.message}</small>
)}
</div>
{/* Description */} {/* Description */}
<div className="mb-2"> <div className="mb-4">
<Label htmlFor="description" required>Description</Label> <Label htmlFor="description" required>Description</Label>
<textarea <textarea
rows="2" rows="2"
className="form-control" className="form-control"
{...register("description")} {...register("description")}
></textarea> ></textarea>
{errors.description && ( {errors.description && (
<div className="danger-text">{errors.description.message}</div> <div className="danger-text">{errors.description.message}</div>
)} )}
</div> </div>
{/* Buttons */} {/* Buttons */}
<div className="d-flex justify-content-end gap-3 mt-4"> <div className="d-flex justify-content-end gap-3 mt-4">
<button <button
type="reset" type="reset"
className="btn btn-label-secondary btn-sm" className="btn btn-label-secondary btn-sm"
disabled={isPending} disabled={isPending}
onClick={closeModal} onClick={closeModal}
> >
Cancel Cancel
</button> </button>
<button <button
type="submit" type="submit"
className="btn btn-primary btn-sm" className="btn btn-primary btn-sm"
disabled={isPending} disabled={isPending}
> >
{isPending ? "Please Wait..." : " Submit"} {isPending ? "Please Wait..." : " Submit"}
</button> </button>
</div> </div>
</form> </form>
</FormProvider> </FormProvider>
</div> </div>
</AppFormProvider>
); );
}; };

View File

@ -21,7 +21,7 @@ const EmpActivities = ({ employee }) => {
if (isLoading) return <div>Loading...</div> if (isLoading) return <div>Loading...</div>
return ( return (
<> <>
<div className="card h-100 mt-4"> <div className="card page-min-h mt-3">
<div className="card-body"> <div className="card-body">
<div className="my-0 text-start"> <div className="my-0 text-start">
<DateRangePicker <DateRangePicker

View File

@ -71,7 +71,7 @@ const EmpAttendance = () => {
<AttendLogs Id={attendanceId} /> <AttendLogs Id={attendanceId} />
</GlobalModel> </GlobalModel>
)} )}
<div className="card px-4 mt-5 py-2 " style={{ minHeight: "500px" }}> <div className="card px-4 mt-3 py-2 " style={{ minHeight: "500px" }}>
<div <div
className="dataTables_length text-start py-2 d-flex justify-content-between " className="dataTables_length text-start py-2 d-flex justify-content-between "
id="DataTables_Table_0_length" id="DataTables_Table_0_length"
@ -103,6 +103,9 @@ const EmpAttendance = () => {
<th className="border-top-1" colSpan={2}> <th className="border-top-1" colSpan={2}>
Name Name
</th> </th>
<th className="border-top-1" colSpan={2}>
ProjectName
</th>
<th className="border-top-1">Date</th> <th className="border-top-1">Date</th>
<th> <th>
<i className="bx bxs-down-arrow-alt text-success"></i>{" "} <i className="bx bxs-down-arrow-alt text-success"></i>{" "}
@ -118,7 +121,7 @@ const EmpAttendance = () => {
<tbody> <tbody>
{currentItems?.map((attendance, index) => ( {currentItems?.map((attendance, index) => (
<tr key={index}> <tr key={index}>
<td colSpan={2}> <td colSpan={3}>
<div className="d-flex justify-content-start align-items-center"> <div className="d-flex justify-content-start align-items-center">
<Avatar <Avatar
firstName={attendance.firstName} firstName={attendance.firstName}
@ -133,6 +136,7 @@ const EmpAttendance = () => {
</div> </div>
</div> </div>
</td> </td>
<td>{attendance.projectName}</td>
<td> <td>
{" "} {" "}
{moment(attendance.checkInTime).format("DD-MMM-YYYY")} {moment(attendance.checkInTime).format("DD-MMM-YYYY")}

View File

@ -18,7 +18,7 @@ const EmpDashboard = ({ profile }) => {
<EmpOverview profile={profile}></EmpOverview> <EmpOverview profile={profile}></EmpOverview>
</div> </div>
<div className="col col-sm-6 pt-5"> <div className="col col-sm-6 mt-3">
<div className="card "> <div className="card ">
<div className="card-body"> <div className="card-body">
<small className="card-text text-uppercase text-body-secondary small text-start d-block"> <small className="card-text text-uppercase text-body-secondary small text-start d-block">
@ -82,7 +82,7 @@ const EmpDashboard = ({ profile }) => {
</div> </div>
</div> </div>
</div> </div>
<div className="col-12 col-sm-6 pt-5"> <div className="col-12 col-sm-6 pt-2">
<EmpReportingManager <EmpReportingManager
employeeId={profile?.id} employeeId={profile?.id}
employee={profile} employee={profile}

View File

@ -6,10 +6,12 @@ import { useParams } from "react-router-dom";
import { DOCUMENTS_ENTITIES } from "../../utils/constants"; import { DOCUMENTS_ENTITIES } from "../../utils/constants";
const EmpDocuments = ({ profile, loggedInUser }) => { const EmpDocuments = ({ profile, loggedInUser }) => {
const {employeeId} = useParams() const { employeeId } = useParams()
return ( return (
<> <>
<Documents Document_Entity={DOCUMENTS_ENTITIES.EmployeeEntity} Entity={employeeId} /> <div className="mt-3">
<Documents Document_Entity={DOCUMENTS_ENTITIES.EmployeeEntity} Entity={employeeId} />
</div>
</> </>
); );
}; };

View File

@ -5,7 +5,7 @@ const EmpOverview = ({ profile }) => {
const { loggedInUserProfile } = useProfile(); const { loggedInUserProfile } = useProfile();
return ( return (
<div className="row"> <div className="row mt-n2">
<div className="col-12 mb-4"> <div className="col-12 mb-4">
<div className="card"> <div className="card">
<div className="card-body"> <div className="card-body">

View File

@ -17,6 +17,8 @@ import DatePicker from "../common/DatePicker";
import { defatEmployeeObj, employeeSchema } from "./EmployeeSchema"; import { defatEmployeeObj, employeeSchema } from "./EmployeeSchema";
import { useOrganizationsList } from "../../hooks/useOrganization"; import { useOrganizationsList } from "../../hooks/useOrganization";
import { ITEMS_PER_PAGE } from "../../utils/constants"; import { ITEMS_PER_PAGE } from "../../utils/constants";
import { AppFormController } from "../../hooks/appHooks/useAppForm";
import SelectField from "../common/Forms/SelectField";
const ManageEmployee = ({ employeeId, onClosed }) => { const ManageEmployee = ({ employeeId, onClosed }) => {
const dispatch = useDispatch(); const dispatch = useDispatch();
@ -96,26 +98,26 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
reset( reset(
currentEmployee currentEmployee
? { ? {
id: currentEmployee.id || null, id: currentEmployee.id || null,
firstName: currentEmployee.firstName || "", firstName: currentEmployee.firstName || "",
middleName: currentEmployee.middleName || "", middleName: currentEmployee.middleName || "",
lastName: currentEmployee.lastName || "", lastName: currentEmployee.lastName || "",
email: currentEmployee.email || "", email: currentEmployee.email || "",
currentAddress: currentEmployee.currentAddress || "", currentAddress: currentEmployee.currentAddress || "",
birthDate: formatDate(currentEmployee.birthDate) || "", birthDate: formatDate(currentEmployee.birthDate) || "",
joiningDate: formatDate(currentEmployee.joiningDate) || "", joiningDate: formatDate(currentEmployee.joiningDate) || "",
emergencyPhoneNumber: currentEmployee.emergencyPhoneNumber || "", emergencyPhoneNumber: currentEmployee.emergencyPhoneNumber || "",
emergencyContactPerson: emergencyContactPerson:
currentEmployee.emergencyContactPerson || "", currentEmployee.emergencyContactPerson || "",
aadharNumber: currentEmployee.aadharNumber || "", aadharNumber: currentEmployee.aadharNumber || "",
gender: currentEmployee.gender || "", gender: currentEmployee.gender || "",
panNumber: currentEmployee.panNumber || "", panNumber: currentEmployee.panNumber || "",
permanentAddress: currentEmployee.permanentAddress || "", permanentAddress: currentEmployee.permanentAddress || "",
phoneNumber: currentEmployee.phoneNumber || "", phoneNumber: currentEmployee.phoneNumber || "",
jobRoleId: currentEmployee.jobRoleId?.toString() || "", jobRoleId: currentEmployee.jobRoleId?.toString() || "",
organizationId: currentEmployee.organizationId || "", organizationId: currentEmployee.organizationId || "",
hasApplicationAccess: currentEmployee.hasApplicationAccess || false, hasApplicationAccess: currentEmployee.hasApplicationAccess || false,
} }
: {} : {}
); );
setCurrentAddressLength(currentEmployee?.currentAddress?.length || 0); setCurrentAddressLength(currentEmployee?.currentAddress?.length || 0);
@ -125,7 +127,7 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
const hasAccessAplication = watch("hasApplicationAccess"); const hasAccessAplication = watch("hasApplicationAccess");
return ( return (
<> <>
<form onSubmit={handleSubmit(onSubmit)} className="p-sm-0 p-2"> <form onSubmit={handleSubmit(onSubmit)} className="p-sm-2 p-2">
<div className="text-center"> <div className="text-center">
<p className="fs-5 fw-semibold"> <p className="fs-5 fw-semibold">
{" "} {" "}
@ -147,7 +149,7 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
message: "Only letters are allowed", message: "Only letters are allowed",
}, },
})} })}
className="form-control form-control-sm" className="form-control "
id="firstName" id="firstName"
placeholder="First Name" placeholder="First Name"
onInput={(e) => { onInput={(e) => {
@ -173,7 +175,7 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
message: "Only letters are allowed", message: "Only letters are allowed",
}, },
})} })}
className="form-control form-control-sm" className="form-control "
id="middleName" id="middleName"
placeholder="Middle Name" placeholder="Middle Name"
onInput={(e) => { onInput={(e) => {
@ -201,7 +203,7 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
message: "Only letters are allowed", message: "Only letters are allowed",
}, },
})} })}
className="form-control form-control-sm" className="form-control "
id="lastName" id="lastName"
placeholder="Last Name" placeholder="Last Name"
onInput={(e) => { onInput={(e) => {
@ -231,7 +233,7 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
type="email" type="email"
id="email" id="email"
{...register("email")} {...register("email")}
className="form-control form-control-sm" className="form-control "
placeholder="example@domain.com" placeholder="example@domain.com"
maxLength={80} maxLength={80}
aria-describedby="Email" aria-describedby="Email"
@ -255,7 +257,7 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
keyboardType="numeric" keyboardType="numeric"
id="phoneNumber" id="phoneNumber"
{...register("phoneNumber")} {...register("phoneNumber")}
className="form-control form-control-sm" className="form-control "
placeholder="Phone Number" placeholder="Phone Number"
inputMode="numeric" inputMode="numeric"
maxLength={10} maxLength={10}
@ -272,7 +274,7 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
</div> </div>
<div className="row mb-3"></div> <div className="row mb-3"></div>
<div className="row mb-3"> <div className="row mb-3">
<div className="col-sm-4"> {/* <div className="col-sm-4">
<Label className="form-text text-start" required> <Label className="form-text text-start" required>
Gender Gender
</Label> </Label>
@ -300,7 +302,44 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
{errors.gender.message} {errors.gender.message}
</div> </div>
)} )}
</div> */}
<div className="col-sm-4">
<Label className="form-text text-start" required>
Gender
</Label>
<div className="">
<AppFormController
name="gender"
control={control}
render={({ field }) => (
<SelectField
label=""
options={[
{ id: "Male", name: "Male" },
{ id: "Female", name: "Female" },
{ id: "Other", name: "Other" },
]}
placeholder="Select Gender"
required
labelKey="name"
valueKey="id"
value={field.value}
onChange={field.onChange}
/>
)}
/>
</div>
{errors.gender && (
<div className="danger-text text-start" style={{ fontSize: "12px" }}>
{errors.gender.message}
</div>
)}
</div> </div>
<div className="col-sm-4"> <div className="col-sm-4">
<Label className="form-text text-start" required> <Label className="form-text text-start" required>
Birth Date Birth Date
@ -358,7 +397,7 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
<textarea <textarea
id="currentAddress" id="currentAddress"
className="form-control form-control-sm" className="form-control "
placeholder="Current Address" placeholder="Current Address"
aria-label="Current Address" aria-label="Current Address"
aria-describedby="basic-icon-default-message2" aria-describedby="basic-icon-default-message2"
@ -388,7 +427,7 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
<textarea <textarea
id="permanentAddress" id="permanentAddress"
className="form-control form-control-sm" className="form-control "
placeholder="Permanent Address" placeholder="Permanent Address"
aria-label="Permanent Address" aria-label="Permanent Address"
aria-describedby="basic-icon-default-message2" aria-describedby="basic-icon-default-message2"
@ -419,25 +458,34 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
<Label className="form-text text-start" required> <Label className="form-text text-start" required>
Organization Organization
</Label> </Label>
<div className="input-group">
<select <div>
className="form-select form-select-sm" <AppFormController
{...register("organizationId")} name="organizationId"
id="organizationId" control={control}
aria-label="" render={({ field }) => (
> <SelectField
<option disabled value=""> label="" // Already showing label above
Select Organization options={
</option> organzationList?.data
{organzationList?.data ?.sort((a, b) => a?.name?.localeCompare(b?.name))
.sort((a, b) => a?.name?.localeCompare(b?.name)) ?.map((item) => ({
.map((item) => ( id: item.id,
<option value={item?.id} key={item?.id}> name: item.name,
{item?.name} })) || []
</option> }
))} placeholder="Select Organization"
</select> required
labelKey="name"
valueKey="id"
value={field.value}
onChange={field.onChange}
className="m-0 form-select-sm w-100"
/>
)}
/>
</div> </div>
{errors.organizationId && ( {errors.organizationId && (
<div <div
className="danger-text text-start justify-content-center" className="danger-text text-start justify-content-center"
@ -448,6 +496,7 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
)} )}
</div> </div>
<div className="col-sm-6 d-flex align-items-center mt-2"> <div className="col-sm-6 d-flex align-items-center mt-2">
<label className="form-check-label d-flex align-items-center"> <label className="form-check-label d-flex align-items-center">
<input <input
@ -468,46 +517,42 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
</div> </div>
</div> </div>
<div className="row mb-3"> <div className="row mb-3">
<div className="col-sm-4"> <div className="col-sm-4 text-start">
<Label className="form-text text-start" required> <AppFormController
Official Designation name="jobRoleId"
</Label> control={control}
<div className="input-group"> render={({ field }) => (
<select <SelectField
className="form-select form-select-sm" label="Official Designation"
{...register("jobRoleId")} required
id="jobRoleId" options={[...job_role].sort((a, b) =>
aria-label="" a?.name?.localeCompare(b?.name)
> )}
<option disabled value=""> placeholder="Select Role"
Select Role labelKey="name"
</option> valueKeyKey="id"
{[...job_role] value={field.value}
.sort((a, b) => a?.name?.localeCompare(b.name)) onChange={field.onChange}
.map((item) => ( className="m-0"
<option value={item?.id} key={item.id}> />
{item?.name}{" "} )}
</option> />
))}
</select>
</div>
{errors.jobRoleId && ( {errors.jobRoleId && (
<div <div className="danger-text text-start" style={{ fontSize: "12px" }}>
className="danger-text text-start"
style={{ fontSize: "12px" }}
>
{errors.jobRoleId.message} {errors.jobRoleId.message}
</div> </div>
)} )}
</div> </div>
<div className="col-sm-4">
<div className="col-sm-4 mt-n1">
<Label className="form-text text-start" required> <Label className="form-text text-start" required>
Emergency Contact Person Emergency Contact Person
</Label> </Label>
<input <input
type="text" type="text"
{...register("emergencyContactPerson")} {...register("emergencyContactPerson")}
className="form-control form-control-sm" className="form-control "
id="emergencyContactPerson" id="emergencyContactPerson"
maxLength={50} maxLength={50}
placeholder="Contact Person" placeholder="Contact Person"
@ -521,14 +566,14 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
</div> </div>
)} )}
</div> </div>
<div className="col-sm-4"> <div className="col-sm-4 mt-n1">
<Label className="form-text text-start" required> <Label className="form-text text-start" required>
Emergency Phone Number Emergency Phone Number
</Label> </Label>
<input <input
type="text" type="text"
{...register("emergencyPhoneNumber")} {...register("emergencyPhoneNumber")}
className="form-control form-control-sm phone-mask" className="form-control phone-mask"
id="emergencyPhoneNumber" id="emergencyPhoneNumber"
placeholder="Phone Number" placeholder="Phone Number"
inputMode="numeric" inputMode="numeric"
@ -551,7 +596,7 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
<input <input
type="text" type="text"
{...register("aadharNumber")} {...register("aadharNumber")}
className="form-control form-control-sm" className="form-control "
id="aadharNumber" id="aadharNumber"
placeholder="AADHAR Number" placeholder="AADHAR Number"
maxLength={12} maxLength={12}
@ -569,7 +614,7 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
<input <input
type="text" type="text"
{...register("panNumber")} {...register("panNumber")}
className="form-control form-control-sm" className="form-control "
id="panNumber" id="panNumber"
placeholder="PAN Number" placeholder="PAN Number"
maxLength={10} maxLength={10}

View File

@ -1,4 +1,10 @@
import React, { forwardRef, useEffect, useImperativeHandle, 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";
@ -15,282 +21,297 @@ import { useExpenseFilter } from "../../hooks/useExpense";
import { ExpenseFilterSkeleton } from "./ExpenseSkeleton"; import { ExpenseFilterSkeleton } from "./ExpenseSkeleton";
import { useLocation, useNavigate, useParams } from "react-router-dom"; import { useLocation, useNavigate, useParams } from "react-router-dom";
const ExpenseFilterPanel = forwardRef(({ onApply, handleGroupBy, setFilterdata }, ref) => { const ExpenseFilterPanel = forwardRef(
const { status } = useParams(); ({ onApply, handleGroupBy, setFilterdata }, ref) => {
const navigate = useNavigate(); const { status } = useParams();
const selectedProjectId = useSelector( const navigate = useNavigate();
(store) => store.localVariables.projectId const selectedProjectId = useSelector(
); (store) => store.localVariables.projectId
const { data, isLoading, isError, error, isFetching, isFetched } = );
useExpenseFilter(); const { data, isLoading, isError, error, isFetching, isFetched } =
useExpenseFilter();
const groupByList = useMemo(() => { const groupByList = useMemo(() => {
return [ return [
{ id: "transactionDate", name: "Transaction Date" }, { id: "none", name: "None" },
{ id: "status", name: "Status" }, { id: "transactionDate", name: "Transaction Date" },
{ id: "submittedBy", name: "Submitted By" }, { id: "status", name: "Status" },
{ id: "project", name: "Project" }, { id: "submittedBy", name: "Submitted By" },
{ id: "paymentMode", name: "Payment Mode" }, { id: "project", name: "Project" },
{ id: "expenseCategory", name: "Expense Category" }, { id: "paymentMode", name: "Payment Mode" },
{ id: "createdAt", name: "Submitted Date" }, { id: "expenseCategory", name: "Expense Category" },
].sort((a, b) => a.name.localeCompare(b.name)); { id: "createdAt", name: "Submitted Date" },
}, []); ].sort((a, b) => a.name.localeCompare(b.name));
}, []);
const [selectedGroup, setSelectedGroup] = useState(groupByList[6]); const [selectedGroup, setSelectedGroup] = useState(groupByList[0]);
const [resetKey, setResetKey] = useState(0); const [resetKey, setResetKey] = useState(0);
const dynamicDefaultFilter = useMemo(() => { const dynamicDefaultFilter = useMemo(() => {
return { return {
...defaultFilter, ...defaultFilter,
statusIds: status ? [status] : defaultFilter.statusIds || [], statusIds: status ? [status] : defaultFilter.statusIds || [],
projectIds: defaultFilter.projectIds || [], projectIds: defaultFilter.projectIds || [],
createdByIds: defaultFilter.createdByIds || [], createdByIds: defaultFilter.createdByIds || [],
paidById: defaultFilter.paidById || [], paidById: defaultFilter.paidById || [],
expenseCategoryIds: defaultFilter.expenseCategoryIds || [], expenseCategoryIds: defaultFilter.expenseCategoryIds || [],
isTransactionDate: defaultFilter.isTransactionDate ?? true, isTransactionDate: defaultFilter.isTransactionDate ?? true,
startDate: defaultFilter.startDate, startDate: defaultFilter.startDate,
endDate: defaultFilter.endDate, endDate: defaultFilter.endDate,
};
}, [status, selectedProjectId]);
const methods = useForm({
resolver: zodResolver(SearchSchema),
defaultValues: dynamicDefaultFilter,
});
const { control, handleSubmit, reset, setValue, watch } = methods;
const isTransactionDate = watch("isTransactionDate");
const closePanel = () => {
document.querySelector(".offcanvas.show .btn-close")?.click();
};
// Change here
useEffect(() => {
if (data && setFilterdata) {
setFilterdata(data);
}
}, [data, setFilterdata]);
const handleGroupChange = (e) => {
const group = groupByList.find((g) => g.id === e.target.value);
if (group) setSelectedGroup(group);
};
useImperativeHandle(ref, () => ({
resetFieldValue: (name, value) => {
// Reset specific field
if (value !== undefined) {
setValue(name, value);
} else {
reset({ ...methods.getValues(), [name]: defaultFilter[name] });
}
},
getValues: methods.getValues, // optional, to read current filter state
}));
const onSubmit = (formData) => {
onApply({
...formData,
startDate: moment.utc(formData.startDate, "DD-MM-YYYY").toISOString(),
endDate: moment.utc(formData.endDate, "DD-MM-YYYY").toISOString(),
});
handleGroupBy(selectedGroup.id);
// closePanel();
};
const onClear = () => {
reset(defaultFilter);
setResetKey((prev) => prev + 1);
setSelectedGroup(groupByList[0]);
onApply(defaultFilter);
handleGroupBy(groupByList[0].id);
// closePanel();
if (status) {
navigate("/expenses", { replace: true });
}
};
const location = useLocation();
useEffect(() => {
closePanel();
}, [location]);
const [appliedStatusId, setAppliedStatusId] = useState(null);
useEffect(() => {
if (!status || !data) return;
if (status !== appliedStatusId) {
const filterWithStatus = {
...dynamicDefaultFilter,
projectIds: selectedProjectId ? [selectedProjectId] : dynamicDefaultFilter.projectIds || [],
startDate: dynamicDefaultFilter.startDate
? moment.utc(dynamicDefaultFilter.startDate, "DD-MM-YYYY").toISOString()
: undefined,
endDate: dynamicDefaultFilter.endDate
? moment.utc(dynamicDefaultFilter.endDate, "DD-MM-YYYY").toISOString()
: undefined,
}; };
}, [status, selectedProjectId]);
onApply(filterWithStatus); const methods = useForm({
resolver: zodResolver(SearchSchema),
defaultValues: dynamicDefaultFilter,
});
const { control, handleSubmit, reset, setValue, watch } = methods;
const isTransactionDate = watch("isTransactionDate");
const closePanel = () => {
document.querySelector(".offcanvas.show .btn-close")?.click();
};
// Change here
useEffect(() => {
if (data && setFilterdata) {
setFilterdata(data);
}
}, [data, setFilterdata]);
const handleGroupChange = (e) => {
const group = groupByList.find((g) => g.id === e.target.value);
if (group) setSelectedGroup(group);
};
useImperativeHandle(ref, () => ({
resetFieldValue: (name, value) => {
// Reset specific field
if (value !== undefined) {
setValue(name, value);
} else {
reset({ ...methods.getValues(), [name]: defaultFilter[name] });
}
},
// --- START FIX: Add resetDateRange method ---
resetDateRange: () => {
setValue("startDate", null);
setValue("endDate", null);
// Trigger re-render/reset of the DateRangePicker component
setResetKey((prev) => prev + 1);
},
// --- END FIX ---
getValues: methods.getValues, // optional, to read current filter state
}));
const onSubmit = (formData) => {
onApply({
...formData,
startDate: moment.utc(formData.startDate, "DD-MM-YYYY").toISOString(),
endDate: moment.utc(formData.endDate, "DD-MM-YYYY").toISOString(),
});
handleGroupBy(selectedGroup.id); handleGroupBy(selectedGroup.id);
setAppliedStatusId(status); // closePanel();
} };
}, [
status,
data,
dynamicDefaultFilter,
onApply,
handleGroupBy,
selectedGroup.id,
appliedStatusId,
selectedProjectId,
]);
if (isLoading || isFetching) return <ExpenseFilterSkeleton />; const onClear = () => {
if (isError && isFetched) reset(defaultFilter);
return <div>Something went wrong Here- {error.message} </div>; setResetKey((prev) => prev + 1);
setSelectedGroup(groupByList[0]);
onApply(defaultFilter);
handleGroupBy(groupByList[0].id);
// closePanel();
if (status) {
navigate("/expenses", { replace: true });
}
};
const location = useLocation();
useEffect(() => {
closePanel();
}, [location]);
const [appliedStatusId, setAppliedStatusId] = useState(null);
return ( useEffect(() => {
<> if (!status || !data) return;
<FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)} className="p-2 text-start"> if (status !== appliedStatusId) {
<div className="mb-3 w-100"> const filterWithStatus = {
<div className="d-flex align-items-center mb-2"> ...dynamicDefaultFilter,
<label className="form-label me-2">Filter By:</label> projectIds: selectedProjectId
<div className="d-inline-flex border rounded-pill mb-1 overflow-hidden shadow-none"> ? [selectedProjectId]
<button : dynamicDefaultFilter.projectIds || [],
type="button" startDate: dynamicDefaultFilter.startDate
className={`btn px-2 py-1 rounded-0 text-tiny ${isTransactionDate ? "active btn-primary text-white" : "" ? moment
}`} .utc(dynamicDefaultFilter.startDate, "DD-MM-YYYY")
onClick={() => setValue("isTransactionDate", true)} .toISOString()
> : undefined,
Transaction Date endDate: dynamicDefaultFilter.endDate
</button> ? moment
<button .utc(dynamicDefaultFilter.endDate, "DD-MM-YYYY")
type="button" .toISOString()
className={`btn px-2 py-1 rounded-0 text-tiny ${!isTransactionDate ? "active btn-primary text-white" : "" : undefined,
}`} };
onClick={() => setValue("isTransactionDate", false)}
> onApply(filterWithStatus);
Submitted Date handleGroupBy(selectedGroup.id);
</button> setAppliedStatusId(status);
}
}, [
status,
data,
dynamicDefaultFilter,
onApply,
handleGroupBy,
selectedGroup.id,
appliedStatusId,
selectedProjectId,
]);
if (isLoading || isFetching) return <ExpenseFilterSkeleton />;
if (isError && isFetched)
return <div>Something went wrong Here- {error.message} </div>;
return (
<>
<FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)} className="p-2 text-start">
<div className="mb-3 w-100">
<div className="d-flex align-items-center mb-2">
<label className="form-label me-2">Filter By:</label>
<div className="d-inline-flex border rounded-pill mb-1 overflow-hidden shadow-none">
<button
type="button"
className={`btn px-2 py-1 rounded-0 text-tiny ${isTransactionDate ? "active btn-primary text-white" : ""
}`}
onClick={() => setValue("isTransactionDate", true)}
>
Transaction Date
</button>
<button
type="button"
className={`btn px-2 py-1 rounded-0 text-tiny ${!isTransactionDate ? "active btn-primary text-white" : ""
}`}
onClick={() => setValue("isTransactionDate", false)}
>
Submitted Date
</button>
</div>
</div>
<DateRangePicker1
placeholder="DD-MM-YYYY To DD-MM-YYYY"
startField="startDate"
endField="endDate"
resetSignal={resetKey}
defaultRange={false}
maxDate={new Date()}
className="w-100"
/>
</div>
<div className="row g-2">
<SelectMultiple
name="projectIds"
label="Projects :"
options={data.projects}
labelKey="name"
valueKey="id"
/>
<SelectMultiple
name="createdByIds"
label="Submitted By :"
options={data.createdBy}
labelKey={(item) => item.name}
valueKey="id"
/>
<SelectMultiple
name="paidById"
label="Paid By :"
options={data.paidBy}
labelKey={(item) => item.name}
valueKey="id"
/>
<SelectMultiple
name="expenseCategoryIds"
label="Category :"
options={data.expenseCategory}
labelKey={(item) => item.name}
valueKey="id"
/>
<div className="mb-3">
<label className="form-label">Status :</label>
<div className="row flex-wrap">
{data?.status
?.slice()
.sort((a, b) => a.name.localeCompare(b.name))
.map((status) => (
<div className="col-6" key={status.id}>
<Controller
control={control}
name="statusIds"
render={({ field: { value = [], onChange } }) => (
<div className="d-flex align-items-center me-3 mb-2">
<input
type="checkbox"
className="form-check-input"
value={status.id}
checked={value.includes(status.id)}
onChange={(e) => {
const checked = e.target.checked;
onChange(
checked
? [...value, status.id]
: value.filter((v) => v !== status.id)
);
}}
/>
<label className="ms-2 mb-0">{status.name}</label>
</div>
)}
/>
</div>
))}
</div>
</div> </div>
</div> </div>
<DateRangePicker1 <div className="mb-2 text-start ">
placeholder="DD-MM-YYYY To DD-MM-YYYY" <label htmlFor="groupBySelect" className="form-label">
startField="startDate" Group By :
endField="endDate" </label>
resetSignal={resetKey} <select
defaultRange={false} id="groupBySelect"
maxDate={new Date()} className="form-select form-select-sm"
className="w-100" value={selectedGroup?.id || "none"}
/> onChange={handleGroupChange}
</div> >
{groupByList.map((group) => (
<div className="row g-2"> <option key={group.id} value={group.id}>
<SelectMultiple {group.name}
name="projectIds" </option>
label="Projects :" ))}
options={data.projects} </select>
labelKey="name"
valueKey="id"
/>
<SelectMultiple
name="createdByIds"
label="Submitted By :"
options={data.createdBy}
labelKey={(item) => item.name}
valueKey="id"
/>
<SelectMultiple
name="paidById"
label="Paid By :"
options={data.paidBy}
labelKey={(item) => item.name}
valueKey="id"
/>
<SelectMultiple
name="expenseCategoryIds"
label="Category :"
options={data.expenseCategory}
labelKey={(item) => item.name}
valueKey="id"
/>
<div className="mb-3">
<label className="form-label">Status :</label>
<div className="row flex-wrap">
{data?.status
?.slice()
.sort((a, b) => a.name.localeCompare(b.name))
.map((status) => (
<div className="col-6" key={status.id}>
<Controller
control={control}
name="statusIds"
render={({ field: { value = [], onChange } }) => (
<div className="d-flex align-items-center me-3 mb-2">
<input
type="checkbox"
className="form-check-input"
value={status.id}
checked={value.includes(status.id)}
onChange={(e) => {
const checked = e.target.checked;
onChange(
checked
? [...value, status.id]
: value.filter((v) => v !== status.id)
);
}}
/>
<label className="ms-2 mb-0">{status.name}</label>
</div>
)}
/>
</div>
))}
</div>
</div> </div>
</div>
<div className="mb-2 text-start ">
<label htmlFor="groupBySelect" className="form-label">
Group By :
</label>
<select
id="groupBySelect"
className="form-select form-select-sm"
value={selectedGroup?.id || ""}
onChange={handleGroupChange}
>
{groupByList.map((group) => (
<option key={group.id} value={group.id}>
{group.name}
</option>
))}
</select>
</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={onClear} onClick={onClear}
> >
Clear Clear
</button> </button>
<button type="submit" className="btn btn-primary btn-sm"> <button type="submit" className="btn btn-primary btn-sm">
Apply Apply
</button> </button>
</div> </div>
</form> </form>
</FormProvider> </FormProvider>
</> </>
); );
}); }
);
export default ExpenseFilterPanel; export default ExpenseFilterPanel;

View File

@ -1,4 +1,4 @@
import React, { useState } from "react"; import React, { useEffect, useState } from "react";
import { useDeleteExpense, useExpenseList } from "../../hooks/useExpense"; import { useDeleteExpense, useExpenseList } from "../../hooks/useExpense";
import Avatar from "../common/Avatar"; import Avatar from "../common/Avatar";
import { useExpenseContext } from "../../pages/Expense/ExpensePage"; import { useExpenseContext } from "../../pages/Expense/ExpensePage";
@ -23,8 +23,15 @@ import { useSelector } from "react-redux";
import ExpenseFilterChips from "./ExpenseFilterChips"; import ExpenseFilterChips from "./ExpenseFilterChips";
import { defaultFilter } from "./ExpenseSchema"; import { defaultFilter } from "./ExpenseSchema";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { displayName } from "react-quill";
const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => { const ExpenseList = ({
filters,
groupBy,
searchText,
tableRef,
onDataFiltered,
}) => {
const [deletingId, setDeletingId] = useState(null); const [deletingId, setDeletingId] = useState(null);
const [IsDeleteModalOpen, setIsDeleteModalOpen] = useState(false); const [IsDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const { const {
@ -47,6 +54,12 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
debouncedSearch debouncedSearch
); );
useEffect(() => {
if (onDataFiltered) {
onDataFiltered(data?.data ?? []);
}
}, [data, onDataFiltered]);
const SelfId = useSelector( const SelfId = useSelector(
(store) => store?.globalVariables?.loginUser?.employeeInfo?.id (store) => store?.globalVariables?.loginUser?.employeeInfo?.id
); );
@ -71,6 +84,16 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
}; };
const groupByField = (items, field) => { const groupByField = (items, field) => {
if (!field || field === "none") {
return {
All: {
key: "All",
displayField: "All",
items: items || []
}
};
}
return items.reduce((acc, item) => { return items.reduce((acc, item) => {
let key; let key;
let displayField; let displayField;
@ -85,8 +108,7 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
displayField = "Status"; displayField = "Status";
break; break;
case "submittedBy": case "submittedBy":
key = `${item?.createdBy?.firstName ?? ""} ${item.createdBy?.lastName ?? "" key = `${item?.createdBy?.firstName ?? ""} ${item?.createdBy?.lastName ?? ""}`.trim();
}`.trim();
displayField = "Submitted By"; displayField = "Submitted By";
break; break;
case "project": case "project":
@ -110,7 +132,7 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
displayField = "Others"; displayField = "Others";
} }
const groupKey = `${field}_${key}`; // unique key for object property const groupKey = `${field}_${key}`;
if (!acc[groupKey]) { if (!acc[groupKey]) {
acc[groupKey] = { key, displayField, items: [] }; acc[groupKey] = { key, displayField, items: [] };
} }
@ -120,6 +142,7 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
}, {}); }, {});
}; };
const expenseColumns = [ const expenseColumns = [
{ {
key: "expenseUId", key: "expenseUId",
@ -212,12 +235,18 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
return <ExpenseTableSkeleton headers={headers} />; return <ExpenseTableSkeleton headers={headers} />;
if (isError) return <div>{error?.message}</div>; if (isError) return <div>{error?.message}</div>;
const grouped = groupBy const isNoGrouping = !groupBy || groupBy === "none";
? groupByField(data?.data ?? [], groupBy) const grouped = isNoGrouping
: { All: data?.data ?? [] }; ? { All: { key: "All", displayField: "All", items: data?.data ?? [] } }
: groupByField(data?.data ?? [], groupBy);
const IsGroupedByDate = [ const IsGroupedByDate = [
{ key: "none", displayField: "None" },
{ key: "transactionDate", displayField: "Transaction Date" }, { key: "transactionDate", displayField: "Transaction Date" },
{ key: "createdAt", displayField: "created Date" }, { key: "createdAt", displayField: "created Date", },
]?.includes(groupBy); ]?.includes(groupBy);
const canEditExpense = (expense) => { const canEditExpense = (expense) => {
@ -258,7 +287,8 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
groupBy={groupBy} groupBy={groupBy}
/> />
<div <div
className="card-datatable table-responsive " className="card-datatable table-responsive"
ref={tableRef}
id="horizontal-example" id="horizontal-example"
> >
<div className="dataTables_wrapper no-footer px-2 "> <div className="dataTables_wrapper no-footer px-2 ">
@ -286,21 +316,23 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
{Object.keys(grouped).length > 0 ? ( {Object.keys(grouped).length > 0 ? (
Object.values(grouped).map(({ key, displayField, items }) => ( Object.values(grouped).map(({ key, displayField, items }) => (
<React.Fragment key={key}> <React.Fragment key={key}>
<tr className="tr-group text-dark"> {!isNoGrouping && (
<td colSpan={8} className="text-start"> <tr className="tr-group text-dark">
<div className="d-flex align-items-center px-2"> <td colSpan={8} className="text-start">
{" "} <div className="d-flex align-items-center px-2">
<small className="fs-6 py-1"> {" "}
{displayField} :{" "} <small className="fs-6 py-1">
</small>{" "} {displayField} :{" "}
<small className="fs-6 ms-3"> </small>{" "}
{IsGroupedByDate <small className="fs-6 ms-3">
? formatUTCToLocalTime(key) {IsGroupedByDate
: key} ? formatUTCToLocalTime(key)
</small> : key}
</div> </small>
</td> </div>
</tr> </td>
</tr>
)}
{items?.map((expense) => ( {items?.map((expense) => (
<tr key={expense.id}> <tr key={expense.id}>
{expenseColumns.map( {expenseColumns.map(
@ -406,7 +438,18 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
<tr> <tr>
<td colSpan={8} className="text-center border-0 "> <td colSpan={8} className="text-center border-0 ">
<div className="py-8"> <div className="py-8">
<p>No Expense Found</p> <p
className="text-center"
style={{
height: "250px",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
No Expense found
</p>
</div> </div>
</td> </td>
</tr> </tr>

View File

@ -22,14 +22,16 @@ const Filelist = ({ files, removeFile, expenseToEdit, sm = 6, md = 4 }) => {
style={{ minWidth: "30px" }} style={{ minWidth: "30px" }}
></i> ></i>
<div className="d-flex flex-column text-truncate"> <Tooltip text={file.fileName}>
<span className="fw-semibold small text-truncate"> <div className="d-flex flex-column text-truncate">
{file.fileName} <span className="fw-semibold small text-truncate">
</span> {file.fileName}
<span className="text-body-secondary small"> </span>
{file.fileSize ? formatFileSize(file.fileSize) : ""} <span className="text-body-secondary small">
</span> {file.fileSize ? formatFileSize(file.fileSize) : ""}
</div> </span>
</div>
</Tooltip>
</div> </div>
{/* Delete icon */} {/* Delete icon */}
@ -39,7 +41,7 @@ const Filelist = ({ files, removeFile, expenseToEdit, sm = 6, md = 4 }) => {
role="button" role="button"
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();
removeFile(expenseToEdit ? file.documentId : idx); removeFile(expenseToEdit ? file.documentId ?? file.tempId ?? idx : file.tempId ?? idx);
}} }}
></i> ></i>
</Tooltip> </Tooltip>
@ -102,7 +104,7 @@ export const FileView = ({ file, viewFile }) => {
<div className="row align-items-center"> <div className="row align-items-center">
{/* File icon and info */} {/* File icon and info */}
<div className="col-12 d-flex align-items-center gap-2 ms-n1"> <div className="col-12 d-flex align-items-center gap-2 ms-n1">
<i className={`bx ${getIconByFileType(file?.fileName)} fs-4`}></i> <i className={`bx ${getIconByFileType(file?.contentType)} fs-4`}></i>
<div <div
className="d-flex flex-column text-truncate" className="d-flex flex-column text-truncate"
@ -117,7 +119,7 @@ export const FileView = ({ file, viewFile }) => {
<span className="text-muted small text-truncate mb-n4"> <span className="text-muted small text-truncate mb-n4">
{file.fileName} {file.fileName}
</span> </span>
<span className="text-body-secondary small"> <span className="text-body-secondary small mt-2">
<Tooltip text={"Click on file"}> <Tooltip text={"Click on file"}>
{" "} {" "}
{file.fileSize ? formatFileSize(file.fileSize) : ""} {file.fileSize ? formatFileSize(file.fileSize) : ""}

View File

@ -37,6 +37,7 @@ import SelectEmployeeServerSide, {
} from "../common/Forms/SelectFieldServerSide"; } from "../common/Forms/SelectFieldServerSide";
import { useAllocationServiceProjectTeam } from "../../hooks/useServiceProject"; import { useAllocationServiceProjectTeam } from "../../hooks/useServiceProject";
import { AppFormController } from "../../hooks/appHooks/useAppForm"; import { AppFormController } from "../../hooks/appHooks/useAppForm";
import SelectField from "../common/Forms/SelectField";
const ManageExpense = ({ closeModal, expenseToEdit = null }) => { const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
const { const {
@ -182,15 +183,15 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
currencyId: data.currency.id || DEFAULT_CURRENCY, currencyId: data.currency.id || DEFAULT_CURRENCY,
billAttachments: data.documents billAttachments: data.documents
? data.documents.map((doc) => ({ ? data.documents.map((doc) => ({
fileName: doc.fileName, fileName: doc.fileName,
base64Data: null, base64Data: null,
contentType: doc.contentType, contentType: doc.contentType,
documentId: doc.documentId, documentId: doc.documentId,
fileSize: 0, fileSize: 0,
description: "", description: "",
preSignedUrl: doc.preSignedUrl, preSignedUrl: doc.preSignedUrl,
isActive: doc.isActive ?? true, isActive: doc.isActive ?? true,
})) }))
: [], : [],
}); });
} }
@ -236,7 +237,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
{expenseToEdit ? "Update Expense " : "Create New Expense"} {expenseToEdit ? "Update Expense " : "Create New Expense"}
</h5> </h5>
<form id="expenseForm" onSubmit={handleSubmit(onSubmit)}> <form id="expenseForm" onSubmit={handleSubmit(onSubmit)}>
<div className="row my-2 text-start"> <div className="row my-2 text-start">
<div className="col-12 col-md-6"> <div className="col-12 col-md-6">
<SelectProjectField <SelectProjectField
label="Project" label="Project"
@ -259,30 +260,32 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
<Label htmlFor="expenseCategoryId" className="form-label" required> <Label htmlFor="expenseCategoryId" className="form-label" required>
Expense Category Expense Category
</Label> </Label>
<select
className="form-select " <AppFormController
id="expenseCategoryId" name="expenseCategoryId"
{...register("expenseCategoryId")} control={control}
> rules={{ required: "Expense Category is required" }}
<option value="" disabled> render={({ field }) => (
Select Category <SelectField
</option> label="" // Label already shown above
{ExpenseLoading ? ( placeholder="Select Category"
<option disabled>Loading...</option> options={expenseCategories ?? []}
) : ( value={field.value || ""}
expenseCategories?.map((expense) => ( onChange={field.onChange}
<option key={expense.id} value={expense.id}> required
{expense.name} isLoading={ExpenseLoading}
</option> className="m-0 form-select-sm w-100"
)) />
)} )}
</select> />
{errors.expensesCategoryId && (
{errors.expenseCategoryId && (
<small className="danger-text"> <small className="danger-text">
{errors.expensesCategoryId.message} {errors.expenseCategoryId.message}
</small> </small>
)} )}
</div> </div>
</div> </div>
<div className="row my-2 text-start"> <div className="row my-2 text-start">
@ -290,40 +293,40 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
<Label htmlFor="paymentModeId" className="form-label" required> <Label htmlFor="paymentModeId" className="form-label" required>
Payment Mode Payment Mode
</Label> </Label>
<select
className="form-select " <AppFormController
id="paymentModeId" name="paymentModeId"
{...register("paymentModeId")} control={control}
> rules={{ required: "Payment Mode is required" }}
<option value="" disabled> render={({ field }) => (
Select Mode <SelectField
</option> label="" // Label is shown above
{PaymentModeLoading ? ( placeholder="Select Mode"
<option disabled>Loading...</option> options={PaymentModes ?? []}
) : ( value={field.value || ""}
PaymentModes?.map((payment) => ( onChange={field.onChange}
<option key={payment.id} value={payment.id}> required
{payment.name} isLoading={PaymentModeLoading}
</option> className="m-0 form-select-sm w-100"
)) />
)} )}
</select> />
{errors.paymentModeId && ( {errors.paymentModeId && (
<small className="danger-text"> <small className="danger-text">{errors.paymentModeId.message}</small>
{errors.paymentModeId.message}
</small>
)} )}
</div> </div>
<div className="col-12 col-md-6 text-start">
<div className="col-12 col-md-6 text-start">
<AppFormController <AppFormController
name="paidById" name="paidById"
control={control} control={control}
render={({ field }) => ( render={({ field }) => (
<SelectEmployeeServerSide <SelectEmployeeServerSide
label="Paid By" required label="Paid By" required
value={field.value} value={field.value}
onChange={field.onChange} onChange={field.onChange}
isFullObject={false} isFullObject={false}
/> />
)} )}
/> />
@ -437,32 +440,37 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
</div> </div>
</div> </div>
<div className="row mb-4"> <div className="row mb-4">
<div className="col-md-6 text-start "> <div className="col-md-6 text-start">
<Label htmlFor="currencyId" className="form-label" required> <Label htmlFor="currencyId" className="form-label" required>
Select Currency Select Currency
</Label> </Label>
<select
className="form-select " <AppFormController
id="currencyId" name="currencyId"
{...register("currencyId")} control={control}
> rules={{ required: "Currency is required" }}
<option value="" disabled> render={({ field }) => (
Select Currency <SelectField
</option> label="" // Label already shown above
{currencyLoading ? ( placeholder="Select Currency"
<option disabled>Loading...</option> options={currencies?.map((currency) => ({
) : ( id: currency.id,
currencies?.map((currency) => ( name: `${currency.currencyName} (${currency.symbol})`,
<option key={currency.id} value={currency.id}> })) ?? []}
{`${currency.currencyName} (${currency.symbol}) `} value={field.value || ""}
</option> onChange={field.onChange}
)) required
isLoading={currencyLoading}
className="m-0 form-select-sm w-100"
/>
)} )}
</select> />
{errors.currencyId && ( {errors.currencyId && (
<small className="danger-text">{errors.currencyId.message}</small> <small className="danger-text">{errors.currencyId.message}</small>
)} )}
</div> </div>
{expenseCategory?.noOfPersonsRequired && ( {expenseCategory?.noOfPersonsRequired && (
<div className="col-md-6 text-start"> <div className="col-md-6 text-start">
<Label className="form-label" required> <Label className="form-label" required>
@ -553,7 +561,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
(fileError?.fileSize?.message || (fileError?.fileSize?.message ||
fileError?.contentType?.message || fileError?.contentType?.message ||
fileError?.base64Data?.message, fileError?.base64Data?.message,
fileError?.documentId?.message) fileError?.documentId?.message)
} }
</div> </div>
))} ))}
@ -578,8 +586,8 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
{isPending || createPending {isPending || createPending
? "Please Wait..." ? "Please Wait..."
: expenseToEdit : expenseToEdit
? "Update" ? "Update"
: "Save as Draft"} : "Save as Draft"}
</button> </button>
</div> </div>
</form> </form>

View File

@ -1,4 +1,6 @@
import { error } from "pdf-lib";
import { useState, useRef, useEffect } from "react"; import { useState, useRef, useEffect } from "react";
import { iframeDocuments } from "../../utils/constants";
const PreviewDocument = ({ files = [] }) => { const PreviewDocument = ({ files = [] }) => {
const images = Array.isArray(files) ? files : [files]; const images = Array.isArray(files) ? files : [files];
@ -15,9 +17,13 @@ const PreviewDocument = ({ files = [] }) => {
const MIN_ZOOM = 0.4; const MIN_ZOOM = 0.4;
const MAX_ZOOM = 3; const MAX_ZOOM = 3;
const currentImage = images[index]; const currentFile = images[index];
const fileUrl = currentFile?.preSignedUrl;
const isDocumentType = iframeDocuments.includes(
currentFile?.contentType.toLowerCase()
);
// Reset on image change
useEffect(() => { useEffect(() => {
setRotation(0); setRotation(0);
setScale(1); setScale(1);
@ -25,8 +31,10 @@ const PreviewDocument = ({ files = [] }) => {
setLoading(true); setLoading(true);
}, [index]); }, [index]);
const zoomIn = () => setScale((prev) => Math.min(prev + 0.2, MAX_ZOOM)); const zoomIn = () =>
const zoomOut = () => setScale((prev) => Math.max(prev - 0.2, MIN_ZOOM)); !isDocumentType && setScale((prev) => Math.min(prev + 0.2, MAX_ZOOM));
const zoomOut = () =>
!isDocumentType && setScale((prev) => Math.max(prev - 0.2, MIN_ZOOM));
const resetAll = () => { const resetAll = () => {
setRotation(0); setRotation(0);
@ -42,24 +50,8 @@ const PreviewDocument = ({ files = [] }) => {
if (index > 0) setIndex((i) => i - 1); if (index > 0) setIndex((i) => i - 1);
}; };
const handleWheel = (e) => {
e.preventDefault();
if (e.ctrlKey) {
const delta = e.deltaY > 0 ? -0.1 : 0.1;
setScale((prev) => {
let next = prev + delta;
if (next < MIN_ZOOM) next = MIN_ZOOM;
if (next > MAX_ZOOM) next = MAX_ZOOM;
return next;
});
} else {
if (e.deltaY > 0) nextImage();
else prevImage();
}
};
const handleMouseDown = (e) => { const handleMouseDown = (e) => {
if (isDocumentType) return;
setDragging(true); setDragging(true);
startPos.current = { startPos.current = {
x: e.clientX - position.x, x: e.clientX - position.x,
@ -67,8 +59,30 @@ const PreviewDocument = ({ files = [] }) => {
}; };
}; };
const handleWheel = (e) => {
if (isDocumentType) return;
e.preventDefault();
const delta = e.deltaY;
setScale((prev) => {
let newScale = prev;
if (delta < 0) {
// Scroll UP -> Zoom IN
newScale = Math.min(prev + 0.1, MAX_ZOOM);
} else {
// Scroll DOWN -> Zoom OUT
newScale = Math.max(prev - 0.1, MIN_ZOOM);
}
return newScale;
});
};
const handleMouseMove = (e) => { const handleMouseMove = (e) => {
if (!dragging) return; if (!dragging || isDocumentType) return;
setPosition({ setPosition({
x: e.clientX - startPos.current.x, x: e.clientX - startPos.current.x,
@ -78,14 +92,15 @@ const PreviewDocument = ({ files = [] }) => {
const handleMouseUp = () => setDragging(false); const handleMouseUp = () => setDragging(false);
const handleDoubleClick = () => resetAll(); const handleDoubleClick = () => !isDocumentType && resetAll();
return ( return (
<> <>
{/* Top Controls */} {/* Controls */}
<div className="d-flex justify-content-start align-items-center mb-2"> <div className="d-flex justify-content-start align-items-center mb-2">
{/* Left */} <div className="d-flex gap-3">
<div className="d-flex gap-3"> {!isDocumentType && (
<>
<i <i
className="bx bx-rotate-right cursor-pointer fs-4" className="bx bx-rotate-right cursor-pointer fs-4"
onClick={() => setRotation((prev) => prev + 90)} onClick={() => setRotation((prev) => prev + 90)}
@ -106,63 +121,80 @@ const PreviewDocument = ({ files = [] }) => {
onClick={resetAll} onClick={resetAll}
title="Reset" title="Reset"
/> />
</div> </>
</div> )}
</div>
</div>
<div <div
onWheel={handleWheel}
onMouseDown={handleMouseDown} onWheel={handleWheel}
onMouseMove={handleMouseMove} onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp} onMouseMove={handleMouseMove}
onMouseLeave={handleMouseUp} onMouseUp={handleMouseUp}
onDoubleClick={handleDoubleClick} onMouseLeave={handleMouseUp}
className="position-relative d-flex justify-content-center align-items-center bg-light-secondary overflow-hidden" onDoubleClick={handleDoubleClick}
className="position-relative d-flex justify-content-center align-items-center bg-light-secondary overflow-hidden"
style={{
minHeight: "70vh",
userSelect: "none",
borderRadius: "10px",
}}
>
{loading && <div className="text-secondary">Loading...</div>}
{isDocumentType ? (
<iframe
src={fileUrl}
title="Document Preview"
style={{ style={{
minHeight: "70vh", width: "100%",
userSelect: "none", height: "70vh",
borderRadius: "10px", border: "none",
}} }}
> onLoad={() => setLoading(false)}
{loading && <div className="text-secondary">Loading...</div>} />
) : (
<img
src={fileUrl}
alt="Preview"
draggable="false"
style={{
maxHeight: "60vh",
display: loading ? "none" : "block",
transform: `
translate(${position.x}px, ${position.y}px)
scale(${scale})
rotate(${rotation}deg)
`,
transition: dragging ? "none" : "transform 0.2s ease",
cursor: dragging ? "grabbing" : "grab",
}}
onLoad={() => setLoading(false)}
/>
)}
</div>
<img <div className="d-flex justify-content-between mt-2">
src={currentImage?.preSignedUrl} <div className="text-muted small">
alt="Preview" Scroll = change file | Double click = reset (images only)
draggable="false" </div>
style={{ <div className="d-flex align-items-center gap-2">
maxHeight: "60vh", <i
display: loading ? "none" : "block", className="bx bx-chevron-left cursor-pointer fs-4"
transform: ` onClick={prevImage}
translate(${position.x}px, ${position.y}px) />
scale(${scale}) <span>
rotate(${rotation}deg) {index + 1} / {images.length}
`, </span>
transition: dragging ? "none" : "transform 0.2s ease", <i
cursor: dragging ? "grabbing" : "grab", className="bx bx-chevron-right cursor-pointer fs-4"
}} onClick={nextImage}
onLoad={() => setLoading(false)} />
/> </div>
</div> </div>
</>
<div className="d-flex justify-content-between">
<div className="text-center text-muted mt-2 small">
Scroll = change image | Double click = reset
</div>
<div className="d-flex align-items-center gap-2">
<i
className="bx bx-chevron-left cursor-pointer fs-4"
onClick={prevImage}
/>
<span>
{index + 1} / {images.length}
</span>
<i
className="bx bx-chevron-right cursor-pointer fs-4"
onClick={nextImage}
/>
</div>
</div>
</>
); );
}; };

View File

@ -390,12 +390,10 @@ const tdsPercentage = Number(watch("tdsPercentage")) || 0;
key={doc.documentId} key={doc.documentId}
className="d-flex align-items-center cusor-pointer" className="d-flex align-items-center cusor-pointer"
onClick={() => { onClick={() => {
if (isImage) {
setDocumentView({ setDocumentView({
IsOpen: true, IsOpen: true,
Images: data?.documents, Images: data?.documents,
}); });
}
}} }}
> >
<i <i
@ -620,4 +618,4 @@ const tdsPercentage = Number(watch("tdsPercentage")) || 0;
); );
}; };
export default ViewExpense; export default ViewExpense;

View File

@ -0,0 +1,16 @@
import React from 'react'
const WarningBlock = ({content}) => {
return (
<div className="col-12 my-1">
<div className="d-flex align-items-center gap-2 p-3 rounded bg-warning bg-opacity-10 border border-warning-subtle text-start align-item-start">
<i className="bx bx-info-circle text-warning fs-5"></i>
<p className="mb-0 small">
{content}
</p>
</div>
</div>
)
}
export default WarningBlock

View File

@ -13,37 +13,22 @@ const Sidebar = () => {
id="layout-menu" id="layout-menu"
className="layout-menu menu-vertical menu bg-menu-theme " className="layout-menu menu-vertical menu bg-menu-theme "
> >
<div className="app-brand" style={{ paddingLeft: "30px" }}> <div className="app-brand" style={{ paddingLeft: "15px" }}>
<Link to="/dashboard" className="app-brand-link"> <Link to="/dashboard" className="app-brand-link">
{/* <span className="app-brand-logo rounded-circle app-brand-logo-border"> <span className="app-brand-logo demo d-flex align-items-center">
<img <img
className="app-brand-logo-sidebar"
src="/img/brand/marco.png" src="/img/brand/marco.png"
alt="logo" width="50"
aria-label="logo image" height="40"
style={{ margin: "5px", paddingRight: "5px" }} alt="OnFieldWork logo"
/> />
</span> */} </span>
<a <span className="app-brand-text">
href="/" <span className="text-blue ms-1">OnField</span>
className="app-brand-link d-flex align-items-center gap-1 fw-bold navbar-brand " <span className="text-green">Work</span>
> <span className="text-dark">.com</span>
<span className="app-brand-logo demo d-flex align-items-center"> </span>
<img
src="/img/brand/marco.png"
width="40"
height="40"
alt="OnFieldWork logo"
/>
</span>
<span className="app-brand-text">
<span className="text-primary ">OnField</span>
<span className="mx-1">Work</span>
<span className="text-dark">.com</span>
</span>
</a>
</Link> </Link>
<small className="layout-menu-toggle menu-link text-large ms-auto cursor-pointer"> <small className="layout-menu-toggle menu-link text-large ms-auto cursor-pointer">
@ -69,7 +54,7 @@ const Sidebar = () => {
</> </>
)} )}
{data && {data &&
data?.data.map((section) => ( data?.data?.map((section) => (
<React.Fragment <React.Fragment
key={section.id || section.header || section.items[0]?.id} key={section.id || section.header || section.items[0]?.id}
> >

View File

@ -33,8 +33,11 @@ const AssignOrg = ({ setStep }) => {
}); });
const isPending = isPendingProject || isPendingTenat; const isPending = isPendingProject || isPendingTenat;
const mergedServices = useMemo(() => { const mergedServices = useMemo(() => {
if (!masterService || !projectServices) return []; const master = Array.isArray(masterService?.data) ? masterService.data : [];
const combined = [...masterService?.data, ...projectServices]; const project = Array.isArray(projectServices) ? projectServices : [];
const combined = [...master, ...project];
return combined.filter( return combined.filter(
(item, index, self) => index === self.findIndex((s) => s.id === item.id) (item, index, self) => index === self.findIndex((s) => s.id === item.id)
); );
@ -96,11 +99,12 @@ const AssignOrg = ({ setStep }) => {
<div className="d-flex justify-content-between align-items-center text-start mb-1"> <div className="d-flex justify-content-between align-items-center text-start mb-1">
<div className="d-flex flex-row gap-2 align-items-center text-wrap"> <div className="d-flex flex-row gap-2 align-items-center text-wrap">
<img <img
src="/public/assets/img/orgLogo.png" src="/public/assets/img/orgLogo.png"
alt="logo" alt="logo"
width={40} width={40}
height={40} height={40}
/> <p className="fw-semibold fs-6 m-0">{orgData.name}</p> />{" "}
<p className="fw-semibold fs-5 mt-2 m-0">{orgData.name}</p>
</div> </div>
<div className="text-end"> <div className="text-end">
<button <button
@ -113,60 +117,63 @@ const AssignOrg = ({ setStep }) => {
</div> </div>
</div> </div>
</div> </div>
<div className="d-flex text-secondary mb-2"> <i className="bx bx-sm bx-info-circle me-1" /> Organization Info</div> <div className="d-flex text-secondary mb-3">
{" "}
<i className="bx bx-sm bx-info-circle me-2" /> Organization Info
</div>
{/* Contact Info */} {/* Contact Info */}
<div className="col-md-6 mb-3"> <div className="col-md-12 mb-4">
<div className="d-flex"> <div className="d-flex">
<label <label
className="form-label me-2 mb-0 fw-semibold" className="form-label me-2 mb-0 fw-semibold"
style={{ minWidth: "130px" }} style={{ minWidth: "130px" }}
> >
<i className="bx bx-sm bx-user me-1" /> Contact Person : <i className="bx bx-sm bx-user me-1" /> Contact Person :
</label> </label>
<div className="text-muted">{orgData.contactPerson}</div> <div className="text-muted">{orgData.contactPerson}</div>
</div> </div>
</div> </div>
<div className="col-md-6 mb-3"> <div className="col-md-12 mb-4">
<div className="d-flex"> <div className="d-flex">
<label <label
className="form-label me-2 mb-0 fw-semibold" className="form-label me-2 mb-0 fw-semibold"
style={{ minWidth: "130px" }} style={{ minWidth: "130px" }}
> >
<i className='bx bx-sm me-1 bx-phone'></i> Contact Number : <i className="bx bx-sm me-1 bx-phone"></i> Contact Number :
</label> </label>
<div className="text-muted">{orgData.contactNumber}</div> <div className="text-muted">{orgData.contactNumber}</div>
</div> </div>
</div> </div>
<div className="col-md-6 mb-3"> <div className="col-md-12 mb-4">
<div className="d-flex"> <div className="d-flex">
<label <label
className="form-label me-2 mb-0 fw-semibold" className="form-label me-2 mb-0 fw-semibold"
style={{ minWidth: "130px" }} style={{ minWidth: "130px" }}
> >
<i className='bx bx-sm me-1 bx-envelope'></i> Email Address : <i className="bx bx-sm me-1 bx-envelope"></i> Email Address :
</label> </label>
<div className="text-muted">{orgData.email}</div> <div className="text-muted text-wrap">{orgData.email}</div>
</div> </div>
</div> </div>
<div className="col-12 mb-3"> <div className="col-12 mb-4">
<div className="d-flex"> <div className="d-flex">
<label <label
className="form-label me-2 mb-0 fw-semibold" className="form-label me-2 mb-0 fw-semibold"
style={{ maxWidth: "130px" }} style={{ maxWidth: "130px" }}
> >
<i className="bx bx-sm me-1 bx-barcode"></i> <i className="bx bx-sm me-2 bx-barcode"></i>
Service Provider Id (SPRID) : Service Provider Id (SPRID) :
</label> </label>
<div className="text-muted">{orgData.sprid}</div> <div className="text-muted">{orgData.sprid}</div>
</div> </div>
</div> </div>
<div className="col-12 mb-3"> <div className="col-12 mb-4">
<div className="d-flex"> <div className="d-flex">
<label <label
className="form-label me-1 mb-0 fw-semibold" className="form-label me-1 mb-0 fw-semibold"
style={{ minWidth: "130px" }} style={{ minWidth: "130px" }}
> >
<i className='bx bx-sm me-1 bx-map'></i> Address : <i className="bx bx-sm me-1 bx-map"></i> Address :
</label> </label>
<div className="text-muted text-start">{orgData.address}</div> <div className="text-muted text-start">{orgData.address}</div>
</div> </div>
@ -180,7 +187,11 @@ const AssignOrg = ({ setStep }) => {
<> <>
{/* Organization Type */} {/* Organization Type */}
<div className="mb-3 text-start"> <div className="mb-3 text-start">
<Label htmlFor="organizationTypeId" className="mb-3 fw-semibold" required> <Label
htmlFor="organizationTypeId"
className="mb-3 fw-semibold"
required
>
Organization Type Organization Type
</Label> </Label>
<div className="d-flex flex-wrap gap-3 mt-1"> <div className="d-flex flex-wrap gap-3 mt-1">
@ -214,7 +225,11 @@ const AssignOrg = ({ setStep }) => {
{/* Services */} {/* Services */}
<div className="mb-3"> <div className="mb-3">
<Label htmlFor="serviceIds" className="mb-3 fw-semibold" required> <Label
htmlFor="serviceIds"
className="mb-3 fw-semibold"
required
>
Select Services Select Services
</Label> </Label>
{mergedServices?.map((service) => ( {mergedServices?.map((service) => (
@ -255,8 +270,8 @@ const AssignOrg = ({ setStep }) => {
{isPending {isPending
? "Please wait..." ? "Please wait..."
: flowType === "default" : flowType === "default"
? "Assign to Organization" ? "Assign to Organization"
: "Assign to Project"} : "Assign to Project"}
</button> </button>
</div> </div>
</form> </form>

View File

@ -189,7 +189,7 @@ const ManagOrg = () => {
)} )}
</div> </div>
<div className="d-flex justify-content-between gap-2 my-2"> <div className="d-flex justify-content-between gap-2 my-5">
<button <button
type="button" type="button"
className="btn btn-sm btn-outline-secondary" className="btn btn-sm btn-outline-secondary"

View File

@ -45,7 +45,7 @@ const OrgPickerFromSPId = ({ title, placeholder }) => {
return ( return (
<div className="d-block mt-4"> <div className="d-block mt-4">
<form onSubmit={handleSubmit(onSubmit)}> <form onSubmit={handleSubmit(onSubmit)}>
<div className="row align-items-center g-2"> <div className="row align-items-center g-2 mb-3">
{/* Input Section */} {/* 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="col-12 col-md-8 d-block d-md-flex align-items-center gap-2 m-0 text-start">
<Label className="text-nowrap mb-1 mb-md-0" required> <Label className="text-nowrap mb-1 mb-md-0" required>
@ -88,7 +88,7 @@ const OrgPickerFromSPId = ({ title, placeholder }) => {
<div className="py-2 text-tiny text-center"> <div className="py-2 text-tiny text-center">
<div className="d-flex flex-column gap-2 border-0 bg-none"> <div className="d-flex flex-column gap-2 border-0 bg-none">
{data.data.map((org) => ( {data.data.map((org) => (
<div className="d-flex flex-row gap-2 text-start text-black "> <div className="d-flex flex-row gap-2 text-start text-black mt-3">
<div className="mt-1"> <div className="mt-1">
<img <img
src="/public/assets/img/orgLogo.png" src="/public/assets/img/orgLogo.png"
@ -97,19 +97,19 @@ const OrgPickerFromSPId = ({ title, placeholder }) => {
height={50} height={50}
/> />
</div> </div>
<div className="d-flex flex-column p-0 m-0 cursor-pointer"> <div className="d-flex flex-column p-0 m-0 cursor-pointer mb-3">
<span className="fs-6 fw-semibold">{org.name}</span> <span className="fs-6 fw-semibold mb-2">{org.name}</span>
<div className="d-flex gap-2"> <div className="d-flex gap-2">
<small <small
className=" fw-semibold text-uppercase" className=" fw-semibold text-uppercase mb-2"
style={{ letterSpacing: "1px" }} style={{ letterSpacing: "1px" }}
> >
SPRID :{" "} SPRID :{" "}
</small> </small>
<small className="fs-6">{org.sprid}</small> <small className="fs-6">{org.sprid}</small>
</div> </div>
<div className="d-flex flex-row gap-2"> <div className="d-flex flex-row gap-2 mb-4">
<small className="text-small fw-semibold">Address:</small> <small className="text-small fw-semibold ">Address:</small>
<div className="d-flex text-wrap">{org.address}</div> <div className="d-flex text-wrap">{org.address}</div>
</div> </div>
<div className="m-0 p-0"> <div className="m-0 p-0">

View File

@ -43,7 +43,7 @@ const OrgPickerfromTenant = ({ title }) => {
label: "Name", label: "Name",
getValue: (org) => ( getValue: (org) => (
<div className="d-flex gap-2 py-1 "> <div className="d-flex gap-2 py-1 ">
<i class="bx bx-buildings"></i> <i className="bx bx-buildings"></i>
<span <span
className="text-truncate d-inline-block " className="text-truncate d-inline-block "
style={{ maxWidth: "150px" }} style={{ maxWidth: "150px" }}
@ -126,7 +126,7 @@ const OrgPickerfromTenant = ({ title }) => {
onOpen({ startStep: 3, orgData: row }) onOpen({ startStep: 3, orgData: row })
} }
> >
<i class='bx bx-right-arrow-circle text-primary'></i> <i className='bx bx-right-arrow-circle text-primary'></i>
</span> </span>
</div> </div>
</td> </td>

View File

@ -122,6 +122,7 @@ const OrganizationsList = ({searchText}) => {
{organizationsColumns.map((col) => ( {organizationsColumns.map((col) => (
<td <td
key={col.key} key={col.key}
style={{ height: "50px" }}
className={`d-table-cell ${col.align ?? ""}`} className={`d-table-cell ${col.align ?? ""}`}
> >
{col.customRender {col.customRender

View File

@ -9,7 +9,7 @@ const VieworgDataanization = ({ orgId }) => {
return ( return (
<div className="row text-black text-black text-start "> <div className="row text-black text-black text-start ">
{/* Header */} {/* Header */}
<div className="col-12 mb-3"> <div className="col-12 mb-5">
<div className="d-flex justify-content-between align-items-center text-start mb-1"> <div className="d-flex justify-content-between align-items-center text-start mb-1">
<div className="d-flex flex-row gap-2 align-items-center text-wrap"> <div className="d-flex flex-row gap-2 align-items-center text-wrap">
<img <img
@ -18,7 +18,7 @@ const VieworgDataanization = ({ orgId }) => {
width={40} width={40}
height={40} height={40}
/>{" "} />{" "}
<p className="fw-semibold fs-6 m-0">{data?.name}</p> <p className="fw-semibold fs-5 mt-2 m-0">{data?.name}</p>
</div> </div>
<div className="text-end"> <div className="text-end">
<span <span
@ -30,12 +30,12 @@ const VieworgDataanization = ({ orgId }) => {
</div> </div>
</div> </div>
</div> </div>
<div className="d-flex text-secondary mb-2"> <div className="d-flex text-secondary mb-5">
{" "} {" "}
<i className="bx bx-sm bx-info-circle me-1" /> Organization Info <i className="bx bx-sm bx-info-circle me-1" /> Organization Info
</div> </div>
{/* Contact Info */} {/* Contact Info */}
<div className="col-md-6 mb-3"> <div className="col-md-12 mb-5">
<div className="d-flex"> <div className="d-flex">
<label <label
className="form-label me-2 mb-0 fw-semibold" className="form-label me-2 mb-0 fw-semibold"
@ -46,7 +46,7 @@ const VieworgDataanization = ({ orgId }) => {
<div className="text-muted">{data?.contactPerson}</div> <div className="text-muted">{data?.contactPerson}</div>
</div> </div>
</div> </div>
<div className="col-md-6 mb-3"> <div className="col-md-12 mb-5">
<div className="d-flex"> <div className="d-flex">
<label <label
className="form-label me-2 mb-0 fw-semibold" className="form-label me-2 mb-0 fw-semibold"
@ -57,7 +57,7 @@ const VieworgDataanization = ({ orgId }) => {
<div className="text-muted">{data?.contactNumber}</div> <div className="text-muted">{data?.contactNumber}</div>
</div> </div>
</div> </div>
<div className="col-md-12 mb-3"> <div className="col-md-12 mb-5">
<div className="d-flex"> <div className="d-flex">
<label <label
className="form-label me-2 mb-0 fw-semibold" className="form-label me-2 mb-0 fw-semibold"
@ -68,32 +68,32 @@ const VieworgDataanization = ({ orgId }) => {
<div className="text-muted">{data?.email}</div> <div className="text-muted">{data?.email}</div>
</div> </div>
</div> </div>
<div className="col-6 mb-3"> <div className="col-12 mb-5">
<div className="d-flex"> <div className="d-flex">
<label <label
className="form-label me-2 mb-0 fw-semibold" className="form-label me-2 mb-0 fw-semibold"
style={{ maxWidth: "130px" }} style={{ maxWidth: "130px" }}
> >
<i className="bx bx-sm me-1 bx-barcode"></i> <i className="bx bx-sm me-2 bx-barcode"></i>
Service Provider Id (SPRID) : Service Provider Id (SPRID) :
</label> </label>
<div className="text-muted">{data?.sprid}</div> <div className="text-muted">{data?.sprid}</div>
</div> </div>
</div> </div>
<div className="col-6 mb-3"> <div className="col-12 mb-5">
<div className="d-flex"> <div className="d-flex">
<label <label
className="form-label me-2 mb-0 fw-semibold" className="form-label me-2 mb-0 fw-semibold"
style={{ maxWidth: "130px" }} style={{ maxWidth: "130px" }}
> >
<i className="bx bx-sm me-1 bx-group"></i> <i className="bx bx-sm me-2 bx-group"></i>
Employees : Employees :
</label> </label>
<div className="text-muted">{data?.activeEmployeeCount}</div> <div className="text-muted">{data?.activeEmployeeCount}</div>
</div> </div>
</div> </div>
<div className="col-12 mb-3"> <div className="col-12 mb-5">
<div className="d-flex"> <div className="d-flex">
<label <label
className="form-label me-1 mb-0 fw-semibold" className="form-label me-1 mb-0 fw-semibold"
@ -104,7 +104,7 @@ const VieworgDataanization = ({ orgId }) => {
<div className="text-muted text-start">{data?.address}</div> <div className="text-muted text-start">{data?.address}</div>
</div> </div>
</div> </div>
<div className="col-12 mb-3"> <div className="col-12 mb-5">
<div <div
className="d-flex justify-content-between align-items-center text-secondary mb-2 cursor-pointer" className="d-flex justify-content-between align-items-center text-secondary mb-2 cursor-pointer"
data-bs-toggle="collapse" data-bs-toggle="collapse"
@ -162,7 +162,7 @@ const VieworgDataanization = ({ orgId }) => {
</div> </div>
{/* Services Section */} {/* Services Section */}
<div className="col-12 mb-3"> <div className="col-12 mb-5">
<div <div
className="d-flex justify-content-between align-items-center text-secondary mb-2 cursor-pointer" className="d-flex justify-content-between align-items-center text-secondary mb-2 cursor-pointer"
data-bs-toggle="collapse" data-bs-toggle="collapse"
@ -180,7 +180,7 @@ const VieworgDataanization = ({ orgId }) => {
{data?.services && data.services.length > 0 ? ( {data?.services && data.services.length > 0 ? (
<div className="row"> <div className="row">
{data.services.map((service) => ( {data.services.map((service) => (
<div key={service.id} className="col-md-12 mb-3"> <div key={service.id} className="col-md-12 mb-5">
<div className="card h-100 shadow-sm border-0"> <div className="card h-100 shadow-sm border-0">
<div className="card-body"> <div className="card-body">
<h6 className="fw-semibold mb-1"> <h6 className="fw-semibold mb-1">

View File

@ -191,16 +191,16 @@ const ActionPaymentRequest = ({ requestId }) => {
{IsPaymentProcess && nextStatusWithPermission?.length > 0 && ( {IsPaymentProcess && nextStatusWithPermission?.length > 0 && (
<> <>
{isProccesed ? ( {isProccesed ? (
<div class="accordion-item active shadow-none"> <div className="accordion-item active shadow-none">
<h2 class="accordion-header d-flex align-items-center"> <h2 className="accordion-header d-flex align-items-center">
<button <button
type="button" type="button"
class="accordion-button" className="accordion-button"
data-bs-toggle="collapse" data-bs-toggle="collapse"
data-bs-target="#accordionWithIcon-1" data-bs-target="#accordionWithIcon-1"
aria-expanded="true" aria-expanded="true"
> >
<i class="icon-base bx bx-receipt me-2"></i> <i className="icon-base bx bx-receipt me-2"></i>
Make Expense Make Expense
</button> </button>
</h2> </h2>

View File

@ -30,6 +30,8 @@ import InputSuggestions from "../common/InputSuggestion";
import { useProfile } from "../../hooks/useProfile"; import { useProfile } from "../../hooks/useProfile";
import { blockUI } from "../../utils/blockUI"; import { blockUI } from "../../utils/blockUI";
import { SelectProjectField } from "../common/Forms/SelectFieldServerSide"; import { SelectProjectField } from "../common/Forms/SelectFieldServerSide";
import { AppFormController } from "../../hooks/appHooks/useAppForm";
import SelectField from "../common/Forms/SelectField";
function ManagePaymentRequest({ closeModal, requestToEdit = null }) { function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
const { const {
@ -176,15 +178,15 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
isAdvancePayment: data.isAdvancePayment || false, isAdvancePayment: data.isAdvancePayment || false,
billAttachments: data.attachments billAttachments: data.attachments
? data?.attachments?.map((doc) => ({ ? data?.attachments?.map((doc) => ({
fileName: doc.fileName, fileName: doc.fileName,
base64Data: null, base64Data: null,
contentType: doc.contentType, contentType: doc.contentType,
documentId: doc.id, documentId: doc.id,
fileSize: 0, fileSize: 0,
description: "", description: "",
preSignedUrl: doc.preSignedUrl, preSignedUrl: doc.preSignedUrl,
isActive: doc.isActive ?? true, isActive: doc.isActive ?? true,
})) }))
: [], : [],
}); });
} }
@ -266,9 +268,9 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
shouldDirty: true, shouldDirty: true,
shouldValidate: true, shouldValidate: true,
}) })
} }
disabled={ disabled={
data?.recurringPayment?.isVariable && !isDraft && !isProcessed data?.recurringPayment?.isVariable && !isDraft && !isProcessed
} }
/> />
@ -281,33 +283,33 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
<Label htmlFor="expenseCategoryId" className="form-label" required> <Label htmlFor="expenseCategoryId" className="form-label" required>
Expense Category Expense Category
</Label> </Label>
<select
className="form-select " <AppFormController
id="expenseCategoryId" name="expenseCategoryId"
{...register("expenseCategoryId")} control={control}
disabled={ rules={{ required: "Expense Category is required" }}
data?.recurringPayment?.isVariable && !isDraft && !isProcessed render={({ field }) => (
} <SelectField
> label="" // Label already above
<option value="" disabled> placeholder="Select Category"
Select Category options={expenseCategories ?? []}
</option> value={field.value || ""}
{ExpenseLoading ? ( onChange={field.onChange}
<option disabled>Loading...</option> required
) : ( isLoading={ExpenseLoading}
expenseCategories?.map((expense) => ( isDisabled={data?.recurringPayment?.isVariable && !isDraft && !isProcessed}
<option key={expense.id} value={expense.id}> className="m-0 form-select-sm w-100"
{expense.name} />
</option>
))
)} )}
</select> />
{errors.expenseCategoryId && ( {errors.expenseCategoryId && (
<small className="danger-text"> <small className="danger-text">
{errors.expenseCategoryId.message} {errors.expenseCategoryId.message}
</small> </small>
)} )}
</div> </div>
</div> </div>
{/* Title and Advance Payment */} {/* Title and Advance Payment */}
@ -458,30 +460,39 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
<Label htmlFor="currencyId" className="form-label" required> <Label htmlFor="currencyId" className="form-label" required>
Currency Currency
</Label> </Label>
<select
id="currencyId"
className="form-select "
{...register("currencyId")}
disabled={
data?.recurringPayment?.isVariable && !isDraft && !isProcessed
}
>
<option value="">Select Currency</option>
{currencyLoading && <option>Loading...</option>} <AppFormController
name="currencyId"
control={control}
rules={{ required: "Currency is required" }}
render={({ field }) => (
<SelectField
label="" // Label already above
placeholder="Select Currency"
options={currencyData?.map((currency) => ({
id: currency.id,
name: `${currency.currencyName} (${currency.symbol})`,
})) ?? []}
value={field.value || ""}
onChange={field.onChange}
required
isLoading={currencyLoading}
isDisabled={data?.recurringPayment?.isVariable && !isDraft && !isProcessed}
noOptionsMessage={() =>
!currencyLoading && !currencyError && (!currencyData || currencyData.length === 0)
? "No currency found"
: null
}
className="m-0 form-select-sm w-100"
/>
)}
/>
{!currencyLoading &&
!currencyError &&
currencyData?.map((currency) => (
<option key={currency.id} value={currency.id}>
{`${currency.currencyName} (${currency.symbol})`}
</option>
))}
</select>
{errors.currencyId && ( {errors.currencyId && (
<small className="danger-text">{errors.currencyId.message}</small> <small className="danger-text">{errors.currencyId.message}</small>
)} )}
</div> </div>
</div> </div>
{/* Description */} {/* Description */}
@ -508,7 +519,7 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
</div> </div>
{/* Upload Document */} {/* Upload Document */}
<div className="row my-2 text-start"> <div className="row my-4 text-start">
<div className="col-md-12"> <div className="col-md-12">
<Label className="form-label">Upload Bill </Label> <Label className="form-label">Upload Bill </Label>
@ -559,7 +570,7 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
(fileError?.fileSize?.message || (fileError?.fileSize?.message ||
fileError?.contentType?.message || fileError?.contentType?.message ||
fileError?.base64Data?.message, fileError?.base64Data?.message,
fileError?.documentId?.message) fileError?.documentId?.message)
} }
</div> </div>
))} ))}
@ -582,8 +593,8 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
{createPending || isPending {createPending || isPending
? "Please Wait..." ? "Please Wait..."
: requestToEdit : requestToEdit
? "Update" ? "Update"
: "Save as Draft"} : "Save as Draft"}
</button> </button>
</div> </div>
</form> </form>

View File

@ -1,3 +1,4 @@
import moment from "moment";
import React, { useMemo } from "react"; import React, { useMemo } from "react";
const PaymentRequestFilterChips = ({ filters, filterData, removeFilterChip, clearFilter }) => { const PaymentRequestFilterChips = ({ filters, filterData, removeFilterChip, clearFilter }) => {
@ -22,6 +23,21 @@ const PaymentRequestFilterChips = ({ filters, filterData, removeFilterChip, clea
addGroup(filters.projectIds, data.projects, "Projects", "projectIds"); addGroup(filters.projectIds, data.projects, "Projects", "projectIds");
addGroup(filters.statusIds, data.status, "Status", "statusIds"); addGroup(filters.statusIds, data.status, "Status", "statusIds");
if (filters.startDate || filters.endDate) {
const start = filters.startDate ? moment(filters.startDate).format("DD MMM YYYY") : "";
const end = filters.endDate ? moment(filters.endDate).format("DD MMM YYYY") : "";
chips.push({
key: "dateRange",
label: "Date",
items: [
{
id: "dateRange",
name: start && end ? `${start} to ${end}` : start || end,
},
],
});
}
return chips; return chips;
}, [filters, filterData]); }, [filters, filterData]);

View File

@ -76,9 +76,18 @@ const PaymentRequestFilterPanel = forwardRef(({ onApply, handleGroupBy, setFilte
if (value !== undefined) { if (value !== undefined) {
setValue(name, value); setValue(name, value);
} else { } else {
reset({ ...methods.getValues(), [name]: defaultFilter[name] }); // NOTE: Using defaultPaymentRequestFilter for clear functionality
reset({ ...methods.getValues(), [name]: defaultPaymentRequestFilter[name] });
} }
}, },
// --- START FIX: Add resetDateRange method ---
resetDateRange: () => {
setValue("startDate", null);
setValue("endDate", null);
// Trigger re-render/reset of the DateRangePicker component
setResetKey((prev) => prev + 1);
},
// --- END FIX ---
getValues: methods.getValues, // optional, to read current filter state getValues: methods.getValues, // optional, to read current filter state
})); }));
@ -94,7 +103,7 @@ const PaymentRequestFilterPanel = forwardRef(({ onApply, handleGroupBy, setFilte
startDate: moment.utc(formData.startDate, "DD-MM-YYYY").toISOString(), startDate: moment.utc(formData.startDate, "DD-MM-YYYY").toISOString(),
endDate: moment.utc(formData.endDate, "DD-MM-YYYY").toISOString(), endDate: moment.utc(formData.endDate, "DD-MM-YYYY").toISOString(),
}); });
handleGroupBy(selectedGroup.id); // handleGroupBy(selectedGroup.id);
// closePanel(); // closePanel();
}; };

View File

@ -1,4 +1,4 @@
import React, { useState } from "react"; import React, { useEffect, useState } from "react";
import { import {
EXPENSE_DRAFT, EXPENSE_DRAFT,
EXPENSE_REJECTEDBY, EXPENSE_REJECTEDBY,
@ -22,7 +22,7 @@ import Error from "../common/Error";
import Pagination from "../common/Pagination"; import Pagination from "../common/Pagination";
import PaymentRequestFilterChips from "./PaymentRequestFilterChips"; import PaymentRequestFilterChips from "./PaymentRequestFilterChips";
const PaymentRequestList = ({ filters, filterData, removeFilterChip, clearFilter, search, groupBy = "submittedBy" }) => { const PaymentRequestList = ({ filters, filterData, removeFilterChip, clearFilter, search, groupBy = "submittedBy", tableRef, onDataFiltered }) => {
const { setManageRequest, setVieRequest } = usePaymentRequestContext(); const { setManageRequest, setVieRequest } = usePaymentRequestContext();
const navigate = useNavigate(); const navigate = useNavigate();
const [IsDeleteModalOpen, setIsDeleteModalOpen] = useState(false); const [IsDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
@ -30,6 +30,7 @@ const PaymentRequestList = ({ filters, filterData, removeFilterChip, clearFilter
const SelfId = useSelector( const SelfId = useSelector(
(store) => store?.globalVariables?.loginUser?.employeeInfo?.id (store) => store?.globalVariables?.loginUser?.employeeInfo?.id
); );
const groupByField = (items, field) => { const groupByField = (items, field) => {
return items.reduce((acc, item) => { return items.reduce((acc, item) => {
let key; let key;
@ -149,6 +150,12 @@ const PaymentRequestList = ({ filters, filterData, removeFilterChip, clearFilter
debouncedSearch debouncedSearch
); );
useEffect(() => {
if (onDataFiltered) {
onDataFiltered(data?.data ?? []);
}
}, [data, onDataFiltered]);
if (isError) { if (isError) {
return <Error error={error} isFeteching={isRefetching} refetch={refetch} />; return <Error error={error} isFeteching={isRefetching} refetch={refetch} />;
} }
@ -222,7 +229,7 @@ const PaymentRequestList = ({ filters, filterData, removeFilterChip, clearFilter
paramData={deletingId} paramData={deletingId}
/> />
)} )}
<div className="card page-min-h table-responsive px-sm-4"> <div className="card page-min-h table-responsive px-sm-4" ref={tableRef}>
<div className="card-datatable mx-2" id="payment-request-table "> <div className="card-datatable mx-2" id="payment-request-table ">
<div className="col-12 mb-2 mt-2"> <div className="col-12 mb-2 mt-2">
<PaymentRequestFilterChips <PaymentRequestFilterChips
@ -240,7 +247,7 @@ const PaymentRequestList = ({ filters, filterData, removeFilterChip, clearFilter
{col.label} {col.label}
</th> </th>
))} ))}
<th className="text-center">Action</th> <th className="text-start">Action</th>
</tr> </tr>
</thead> </thead>
@ -262,7 +269,7 @@ const PaymentRequestList = ({ filters, filterData, removeFilterChip, clearFilter
</td> </td>
</tr> </tr>
{items?.map((paymentRequest) => ( {items?.map((paymentRequest) => (
<tr key={paymentRequest.id} style={{ height: "40px" }}> <tr key={paymentRequest.id} style={{ height: "40px" }}>
{paymentRequestColumns.map( {paymentRequestColumns.map(
(col) => (col) =>
(col.isAlwaysVisible || groupBy !== col.key) && ( (col.isAlwaysVisible || groupBy !== col.key) && (
@ -300,7 +307,7 @@ const PaymentRequestList = ({ filters, filterData, removeFilterChip, clearFilter
data-bs-toggle="tooltip" data-bs-toggle="tooltip"
data-bs-offset="0,8" data-bs-offset="0,8"
data-bs-placement="top" data-bs-placement="top"
data-bs-custom-class="tooltip-dark" data-bs-custom-className="tooltip-dark"
title="More Action" title="More Action"
></i> ></i>
</button> </button>
@ -348,8 +355,18 @@ const PaymentRequestList = ({ filters, filterData, removeFilterChip, clearFilter
) : ( ) : (
<tr> <tr>
<td colSpan={8} className="text-center border-0 "> <td colSpan={8} className="text-center border-0 ">
<div className="py-8"> <div >
<p>No Request Found</p> <p
className="text-center"
style={{
height: "250px",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
No data found
</p>
</div> </div>
</td> </td>
</tr> </tr>

View File

@ -0,0 +1,85 @@
import ExpenseRepository from "../../repositories/ExpsenseRepository";
import moment from "moment";
import { exportToCSV, exportToExcel, exportToPDF, printTable } from "../../utils/tableExportUtils";
import showToast from "../../services/toastService";
const HandleExpenseExport = async (
type,
filters = {},
searchString = "",
tableRef = null,
setLoading = null
) => {
try {
if (setLoading) setLoading(true);
const safeSearchString = typeof searchString === "string" ? searchString : "";
let allExpenses = [];
let pageNumber = 1;
const pageSize = 1000; // fetch 1000 per API call
let hasMore = true;
while (hasMore) {
const response = await ExpenseRepository.GetExpenseList(
pageSize,
pageNumber,
filters,
safeSearchString
);
const currentPageData = response?.data?.data || [];
allExpenses = allExpenses.concat(currentPageData);
// If returned data length is less than pageSize, we reached the last page
if (currentPageData.length < pageSize) {
hasMore = false;
} else {
pageNumber += 1; // fetch next page
}
}
if (!allExpenses.length) {
showToast("No expenses found!", "warning");
return;
}
// Map export data
const exportData = allExpenses.map((item) => ({
"Expense ID": item?.expenseUId ?? "-",
"Expense Category": item?.expenseCategory?.name ?? "-",
"Payment Mode": item?.paymentMode?.name ?? "-",
"Submitted By": `${item?.createdBy?.firstName ?? ""} ${item?.createdBy?.lastName ?? ""}`.trim() || "-",
"Submitted": item?.createdAt ? moment(item.createdAt).format("DD-MMM-YYYY") : "-",
"Amount": item?.amount != null
? `${item.amount.toLocaleString()} ${item.currency?.currencyCode ?? ""}`
: "-",
"Status": item?.status?.name ?? "-",
}));
switch (type) {
case "csv":
exportToCSV(exportData, "Expenses");
break;
case "excel":
exportToExcel(exportData, "Expenses");
break;
case "pdf":
exportToPDF(exportData, "Expenses");
break;
case "print":
if (tableRef?.current) printTable(tableRef.current);
break;
default:
console.warn("Unknown export type:", type);
}
} catch (err) {
console.error(err);
showToast("Failed to export expenses", "error");
} finally {
if (setLoading) setLoading(false);
}
};
export default HandleExpenseExport;

View File

@ -0,0 +1,84 @@
import moment from "moment";
import { exportToCSV, exportToExcel, exportToPDF, printTable } from "../../utils/tableExportUtils";
import ExpenseRepository from "../../repositories/ExpsenseRepository";
const HandlePaymentRequestExport = async (
type,
filters = {},
searchString = "",
tableRef = null,
setLoading = null
) => {
try {
if (setLoading) setLoading(true);
const safeSearchString = typeof searchString === "string" ? searchString : "";
let allPaymentRequest = [];
let pageNumber = 1;
const pageSize = 1000;
let hasMore = true;
while (hasMore) {
const response = await ExpenseRepository.GetPaymentRequestList(
pageSize,
pageNumber,
filters,
true, // isActive
safeSearchString
);
const currentPageData = response?.data?.data || [];
allPaymentRequest = allPaymentRequest.concat(currentPageData);
if (currentPageData.length < pageSize) {
hasMore = false;
} else {
pageNumber += 1;
}
}
if (!allPaymentRequest.length) {
console.warn("No payment requests found!");
return;
}
const exportData = allPaymentRequest.map((item) => ({
"Request ID": item?.paymentRequestUID ?? "-",
"Title": item?.title ?? "-",
"Payee": item?.payee ?? "-",
"Amount": item?.amount != null ? Number(item.amount).toLocaleString() : "-",
"Currency": item?.currency?.currencyCode ?? "-",
"Created At": item?.createdAt ? moment(item.createdAt).format("DD-MMM-YYYY") : "-",
"Due Date": item?.dueDate ? moment(item.dueDate).format("DD-MMM-YYYY") : "-",
"Status": item?.expenseStatus?.name ?? "-",
"Submitted By": `${item?.createdBy?.firstName ?? ""} ${item?.createdBy?.lastName ?? ""}`.trim() || "-",
"Project": item?.project?.name ?? "-",
}));
switch (type) {
case "csv":
exportToCSV(exportData, "PaymentRequests");
break;
case "excel":
exportToExcel(exportData, "PaymentRequests");
break;
case "pdf":
exportToPDF(exportData, "PaymentRequests");
break;
case "print":
if (tableRef?.current) printTable(tableRef.current);
break;
default:
console.warn("Unknown export type:", type);
}
} catch (err) {
console.error("Export failed:", err);
} finally {
if (setLoading) setLoading(false);
}
};
export default HandlePaymentRequestExport;

View File

@ -18,6 +18,8 @@ import {
import eventBus from "../../services/eventBus"; import eventBus from "../../services/eventBus";
import { useCreateTask } from "../../hooks/useTasks"; import { useCreateTask } from "../../hooks/useTasks";
import Label from "../common/Label"; import Label from "../common/Label";
import { AppFormController } from "../../hooks/appHooks/useAppForm";
import SelectField from "../common/Forms/SelectField";
const TaskSchema = (maxPlanned) => { const TaskSchema = (maxPlanned) => {
return z.object({ return z.object({
@ -107,7 +109,7 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
); );
const dispatch = useDispatch(); const dispatch = useDispatch();
const { loading, data: jobRoleData } = useMaster(); const { loading, data: jobRoleData } = useMaster("Job Role");
const [selectedRoles, setSelectedRoles] = useState(["all"]); const [selectedRoles, setSelectedRoles] = useState(["all"]);
const [displayedSelection, setDisplayedSelection] = useState(""); const [displayedSelection, setDisplayedSelection] = useState("");
@ -128,8 +130,8 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
const handleCheckboxChange = (event, user) => { const handleCheckboxChange = (event, user) => {
const updatedSelectedEmployees = event.target.checked const updatedSelectedEmployees = event.target.checked
? [...(watch("selectedEmployees") || []), user.id].filter( ? [...(watch("selectedEmployees") || []), user.id].filter(
(v, i, a) => a.indexOf(v) === i (v, i, a) => a.indexOf(v) === i
) )
: (watch("selectedEmployees") || []).filter((id) => id !== user.id); : (watch("selectedEmployees") || []).filter((id) => id !== user.id);
setValue("selectedEmployees", updatedSelectedEmployees); setValue("selectedEmployees", updatedSelectedEmployees);
@ -235,160 +237,169 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
))} ))}
</span> </span>
</p> </p>
<div
className="col-12 col-md-4 d-flex flex-row gap-3 align-items-center mt-4 mb-6 justify-content-end"
ref={dropdownRef}
>
<div className="d-flex justify-content-between align-items-center w-100">
{/* Left Side → Heading + Search */}
<div className="d-flex flex-column w-100">
<label className=" text-start small mb-1">Search Employee</label>
<input
type="text"
className="form-control form-control-sm"
placeholder="Search employees or roles..."
value={searchTerm}
onChange={handleSearchChange}
/>
</div>
{/* Right Side → Dropdown */}
<div className="dropdown position-relative d-inline-block ms-2 mt-4">
<a
className={`dropdown-toggle hide-arrow cursor-pointer ${selectedRoles.includes("all") || selectedRoles.length === 0
? "text-secondary"
: "text-primary"
}`}
onClick={() => setOpen(!open)}
>
<i className="bx bx-slider-alt ms-2"></i>
</a>
{/* Badge */}
{selectedRolesCount > 0 && (
<span
className="position-absolute top-0 start-100 translate-middle badge rounded-circle bg-warning text-white text-tiny"
style={{
fontSize: "0.65rem",
minWidth: "18px",
height: "18px",
padding: "0",
lineHeight: "18px",
textAlign: "center",
zIndex: 10,
}}
>
{selectedRolesCount}
</span>
)}
{/* Dropdown Menu */}
{open && (
<ul
className="dropdown-menu show p-2 text-capitalize"
style={{ maxHeight: "300px", overflowY: "auto" }}
>
{/* All Roles */}
<li key="all">
<div className="form-check dropdown-item py-0">
<input
className="form-check-input"
type="checkbox"
id="checkboxAllRoles"
value="all"
checked={selectedRoles.includes("all")}
onChange={(e) => handleRoleChange(e, e.target.value)}
/>
<label
className="form-check-label ms-2"
htmlFor="checkboxAllRoles"
>
All Roles
</label>
</div>
</li>
{/* Dynamic Roles */}
{jobRolesForDropdown?.map((role) => (
<li key={role.id}>
<div className="form-check dropdown-item py-0">
<input
className="form-check-input"
type="checkbox"
id={`checkboxRole-${role.id}`}
value={role.id}
checked={selectedRoles.includes(String(role.id))}
onChange={(e) => handleRoleChange(e, e.target.value)}
/>
<label
className="form-check-label ms-2"
htmlFor={`checkboxRole-${role.id}`}
>
{role.name}
</label>
</div>
</li>
))}
</ul>
)}
</div>
</div>
</div>
<form onSubmit={handleSubmit(onSubmit)}> <form onSubmit={handleSubmit(onSubmit)}>
<div className="form-label text-start"> <div className="form-label text-start">
<div className="row mb-1"> <div className="row mb-1">
<div className="col-12"> <div className="col-12">
<div className="row text-start"> <div className="row text-start">
<div className="col-12 col-md-8 d-flex flex-row gap-3 align-items-center"> <div className="col-12 col-md-8 d-flex flex-row gap-3 align-items-center mt-4 d-none">
<div> <div>
<select <AppFormController
className="form-select form-select-sm" name="organizationId"
value={selectedOrganization || ""} control={control}
onChange={(e) => rules={{ required: "Organization is required" }}
setSelectedOrganization(e.target.value) render={({ field }) => (
} <SelectField
> label="" // No label here, use external label if needed
{isServiceLoading ? ( options={organizationList ?? []}
<option>Loading...</option> placeholder="--Select Organization--"
) : ( required
<> labelKey="name"
<option value="">--Select Organization--</option> valueKeyKey="id"
{organizationList?.map((org,index) => ( value={field.value || ""}
<option key={`${org.id}-${index}`} value={org.id}> onChange={field.onChange}
{org.name} isLoading={isServiceLoading}
</option> className="m-0 form-select-sm w-100"
))} />
</>
)} )}
</select>
</div>
<div>
<select
className="form-select form-select-sm"
value={selectedService || ""}
onChange={(e) => setSelectedService(e.target.value)}
>
{isOrgLoading ? (
<option>Loading...</option>
) : (
<>
<option value="">--Select Service--</option>
{serviceList?.map((service,index) => (
<option key={`${service.id}-${index}`} value={service.id}>
{service.name}
</option>
))}
</>
)}
</select>
</div>
</div>
<div
className="col-12 col-md-4 d-flex flex-row gap-3 align-items-center justify-content-end"
ref={dropdownRef}
>
{/* Dropdown */}
<div className="dropdown position-relative d-inline-block">
<a
className={`dropdown-toggle hide-arrow cursor-pointer ${
selectedRoles.includes("all") ||
selectedRoles.length === 0
? "text-secondary"
: "text-primary"
}`}
onClick={() => setOpen(!open)}
>
<i className="bx bx-slider-alt ms-2"></i>
</a>
{/* Badge */}
{selectedRolesCount > 0 && (
<span
className="position-absolute top-0 start-100 translate-middle badge rounded-circle bg-warning text-white text-tiny"
style={{
fontSize: "0.65rem",
minWidth: "18px",
height: "18px",
padding: "0",
lineHeight: "18px",
textAlign: "center",
zIndex: 10,
}}
>
{selectedRolesCount}
</span>
)}
{/* Dropdown Menu */}
{open && (
<ul
className="dropdown-menu show p-2 text-capitalize"
style={{ maxHeight: "300px", overflowY: "auto" }}
>
{/* All Roles */}
<li key="all">
<div className="form-check dropdown-item py-0">
<input
className="form-check-input"
type="checkbox"
id="checkboxAllRoles"
value="all"
checked={selectedRoles.includes("all")}
onChange={(e) =>
handleRoleChange(e, e.target.value)
}
/>
<label
className="form-check-label ms-2"
htmlFor="checkboxAllRoles"
>
All Roles
</label>
</div>
</li>
{/* Dynamic Roles */}
{jobRolesForDropdown?.map((role) => (
<li key={role.id}>
<div className="form-check dropdown-item py-0">
<input
className="form-check-input"
type="checkbox"
id={`checkboxRole-${role.id}`}
value={role.id}
checked={selectedRoles.includes(
String(role.id)
)}
onChange={(e) =>
handleRoleChange(e, e.target.value)
}
/>
<label
className="form-check-label ms-2"
htmlFor={`checkboxRole-${role.id}`}
>
{role.name}
</label>
</div>
</li>
))}
</ul>
)}
</div>
{/* Search Box */}
<div>
<input
type="text"
className="form-control form-control-sm ms-auto mb-2 mt-2"
placeholder="Search employees or roles..."
value={searchTerm}
onChange={handleSearchChange}
/> />
{errors.organizationId && (
<small className="danger-text">{errors.organizationId.message}</small>
)}
</div>
<div>
<AppFormController
name="serviceId"
control={control}
rules={{ required: "Service is required" }}
render={({ field }) => (
<SelectField
label="" // No label as you have one above or elsewhere
options={serviceList ?? []}
placeholder="--Select Service--"
required
labelKey="name"
valueKeyKey="id"
value={field.value || ""}
onChange={field.onChange}
isLoading={isOrgLoading}
className="m-0 form-select-sm w-100"
/>
)}
/>
{errors.serviceId && (
<small className="danger-text">{errors.serviceId.message}</small>
)}
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
@ -409,7 +420,7 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
<p className="text-center">Loading employees...</p> <p className="text-center">Loading employees...</p>
</div> </div>
) : filteredEmployees?.length > 0 ? ( ) : filteredEmployees?.length > 0 ? (
filteredEmployees.map((emp,index) => { filteredEmployees.map((emp, index) => {
const jobRole = jobRoleData?.find( const jobRole = jobRoleData?.find(
(role) => role?.id === emp?.jobRoleId (role) => role?.id === emp?.jobRoleId
); );
@ -479,14 +490,14 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
{watch("selectedEmployees")?.length > 0 && ( {watch("selectedEmployees")?.length > 0 && (
<div className="mt-1"> <div className="mt-1">
<div className="text-start px-2"> <div className="text-start px-2">
{watch("selectedEmployees")?.map((empId,ind) => { {watch("selectedEmployees")?.map((empId, ind) => {
const emp = employees?.data?.find( const emp = employees?.data?.find(
(emp) => emp.id === empId (emp) => emp.id === empId
); );
return ( return (
emp && ( emp && (
<span <span
key={`${empId}-${ind}`} key={`${empId}-${ind}`}
className="badge rounded-pill bg-label-primary d-inline-flex align-items-center me-1 mb-1" className="badge rounded-pill bg-label-primary d-inline-flex align-items-center me-1 mb-1"
> >
{emp.firstName} {emp.lastName} {emp.firstName} {emp.lastName}

View File

@ -3,11 +3,11 @@ import { useForm } from "react-hook-form";
import { z } from "zod"; import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { getCachedData } from "../../../slices/apiDataManager";
import showToast from "../../../services/toastService"; import showToast from "../../../services/toastService";
import { useManageProjectInfra } from "../../../hooks/useProjects"; import { useManageProjectInfra } from "../../../hooks/useProjects";
import useSelect from "../../common/useSelect";
import Label from "../../common/Label"; import Label from "../../common/Label";
import { AppFormController, AppFormProvider } from "../../../hooks/appHooks/useAppForm";
import SelectField from "../../common/Forms/SelectField";
const buildingSchema = z.object({ const buildingSchema = z.object({
Id: z.string().optional(), Id: z.string().optional(),
@ -22,14 +22,8 @@ const BuildingModel = ({ project, onClose, editingBuilding = null }) => {
const selectedProject = useSelector( const selectedProject = useSelector(
(store) => store.localVariables.projectId (store) => store.localVariables.projectId
); );
const {
register, const methods = useForm({
handleSubmit,
formState: { errors },
setValue,
watch,
reset,
} = useForm({
resolver: zodResolver(buildingSchema), resolver: zodResolver(buildingSchema),
defaultValues: { defaultValues: {
Id: "0", Id: "0",
@ -37,12 +31,23 @@ const BuildingModel = ({ project, onClose, editingBuilding = null }) => {
description: "", description: "",
}, },
}); });
const {
register,
handleSubmit,
control,
watch,
reset,
setValue,
formState: { errors },
} = methods;
const watchedId = watch("Id"); const watchedId = watch("Id");
const { mutate: ManageBuilding, isPending } = useManageProjectInfra({ const { mutate: ManageBuilding, isPending } = useManageProjectInfra({
onSuccessCallback: (data, variables) => { onSuccessCallback: () => {
showToast( showToast(
watchedId != "0" watchedId !== "0"
? "Building updated Successfully" ? "Building updated Successfully"
: "Building created Successfully", : "Building created Successfully",
"success" "success"
@ -79,7 +84,7 @@ const BuildingModel = ({ project, onClose, editingBuilding = null }) => {
description: editingBuilding.description, description: editingBuilding.description,
}); });
} }
}, [editingBuilding]); }, [editingBuilding, reset]);
const onSubmitHandler = (data) => { const onSubmitHandler = (data) => {
const payload = { const payload = {
@ -88,95 +93,109 @@ const BuildingModel = ({ project, onClose, editingBuilding = null }) => {
projectId: selectedProject, projectId: selectedProject,
}; };
let infraObject = [ const infraObject = [
{ {
building: payload, building: payload,
floor: null, floor: null,
workArea: null, workArea: null,
}, },
]; ];
ManageBuilding({ infraObject, projectId: selectedProject }); ManageBuilding({ infraObject, projectId: selectedProject });
}; };
return ( return (
<form onSubmit={handleSubmit(onSubmitHandler)} className="row g-2"> <AppFormProvider {...methods}>
<h5 className="text-center mb-2">Manage Buildings </h5> <form onSubmit={handleSubmit(onSubmitHandler)} className="row g-2">
<div className="col-12 text-start"> <h5 className="text-center mb-2">Manage Buildings</h5>
<label className="form-label">Select Building</label>
<select {/* Building Select */}
{...register("Id")} <div className="col-12 text-start">
className="select2 form-select form-select-sm" <Label htmlFor="Id" className="form-label">
> Select Building
<option value="0">Add New Building</option> </Label>
{sortedBuildings.length > 0 ? ( <AppFormController
sortedBuildings.map((b) => ( name="Id"
<option key={b.id} value={b.id}> control={control}
{b.buildingName} rules={{ required: "Building is required" }}
</option> render={({ field }) => (
)) <SelectField
) : ( label=""
<option disabled>No buildings found</option> placeholder="Select Building"
options={[
{ id: "0", name: "Add New Building" },
...(sortedBuildings?.map((b) => ({
id: String(b.id),
name: b.buildingName,
})) ?? []),
]}
value={field.value || ""}
onChange={field.onChange}
required
noOptionsMessage={() =>
!sortedBuildings || sortedBuildings.length === 0
? "No buildings found"
: null
}
className="m-0 form-select-sm w-100"
/>
)}
/>
{errors.Id && <span className="danger-text">{errors.Id.message}</span>}
</div>
{/* Name */}
<div className="col-12 text-start">
<Label className="form-label" required>
{watchedId !== "0" ? "Rename Building Name" : "New Building Name"}
</Label>
<input
{...register("name")}
type="text"
className="form-control "
/>
{errors.name && <span className="danger-text">{errors.name.message}</span>}
</div>
{/* Description */}
<div className="col-12 text-start">
<Label className="form-label" required>
Description
</Label>
<textarea
{...register("description")}
rows="5"
maxLength="160"
className="form-control "
/>
{errors.description && (
<span className="danger-text">{errors.description.message}</span>
)} )}
</select> </div>
{errors.Id && <span className="danger-text">{errors.Id.message}</span>}
</div>
{/* Name */} {/* Buttons */}
<div className="col-12 text-start"> <div className="col-12 text-end mt-6 my-2">
<Label className="form-label" required> <button
{watchedId !== "0" ? "Rename Building Name" : "New Building Name"} type="reset"
</Label> className="btn btn-sm btn-label-secondary me-3"
<input disabled={isPending}
{...register("name")} onClick={() => {
type="text" onClose();
className="form-control form-control-sm" reset();
/> }}
{errors.name && ( >
<span className="danger-text">{errors.name.message}</span> Cancel
)} </button>
</div> <button type="submit" className="btn btn-sm btn-primary" disabled={isPending}>
{isPending
{/* Description */} ? "Please wait..."
<div className="col-12 text-start"> : watchedId !== "0"
<Label className="form-label" required>Description</Label> ? "Edit Building"
<textarea : "Add Building"}
{...register("description")} </button>
rows="5" </div>
maxLength="160" </form>
className="form-control form-control-sm" </AppFormProvider>
/>
{errors.description && (
<span className="danger-text">{errors.description.message}</span>
)}
</div>
<div className="col-12 text-end mt-5">
<button
type="reset"
className="btn btn-sm btn-label-secondary me-3"
disabled={isPending}
onClick={() => {
onClose();
reset();
}}
>
Cancel
</button>
<button
type="submit"
className="btn btn-sm btn-primary"
disabled={isPending}
>
{isPending
? "Please wait..."
: watchedId !== "0"
? "Edit Building"
: "Add Building"}
</button>
</div>
</form>
); );
}; };

View File

@ -12,12 +12,14 @@ import { useManageTask } from "../../../hooks/useProjects";
import { cacheData, getCachedData } from "../../../slices/apiDataManager"; import { cacheData, getCachedData } from "../../../slices/apiDataManager";
import { refreshData } from "../../../slices/localVariablesSlice"; import { refreshData } from "../../../slices/localVariablesSlice";
import showToast from "../../../services/toastService"; import showToast from "../../../services/toastService";
import { AppFormController, AppFormProvider } from "../../../hooks/appHooks/useAppForm";
import SelectField from "../../common/Forms/SelectField";
const taskSchema = z const taskSchema = z
.object({ .object({
activityID: z.string().min(1, "Activity is required"), activityID: z.string().min(1, "Activity is required"),
workCategoryId: z.string().min(1, "Work Category is required"), workCategoryId: z.string().min(1, "Work Category is required"),
plannedWork: z.number().min(1, "Planned Work must be greater than 0"), plannedWork: z.number().min(0.01, "Planned Work must be greater than 0"),
completedWork: z.number().min(0, "Completed Work must be ≥ 0"), completedWork: z.number().min(0, "Completed Work must be ≥ 0"),
comment: z.string(), comment: z.string(),
}) })
@ -37,17 +39,7 @@ const EditActivityModal = ({
const { activities, loading: loadingActivities } = useActivitiesMaster(); const { activities, loading: loadingActivities } = useActivitiesMaster();
const { categories, loading: loadingCategories } = useWorkCategoriesMaster(); const { categories, loading: loadingCategories } = useWorkCategoriesMaster();
const [selectedActivity, setSelectedActivity] = useState(null); const [selectedActivity, setSelectedActivity] = useState(null);
const methods = useForm({
const {
register,
handleSubmit,
formState: { errors },
reset,
setValue,
getValues,
watch,
} = useForm({
resolver: zodResolver(taskSchema),
defaultValues: { defaultValues: {
activityID: "", activityID: "",
workCategoryId: "", workCategoryId: "",
@ -55,7 +47,11 @@ const EditActivityModal = ({
completedWork: 0, completedWork: 0,
comment: "", comment: "",
}, },
resolver: zodResolver(taskSchema),
}); });
const { register, control, watch, handleSubmit, reset, setValue, getValues, formState: { errors } } = methods;
const { mutate: UpdateTask, isPending } = useManageTask({ const { mutate: UpdateTask, isPending } = useManageTask({
onSuccessCallback: (response) => { onSuccessCallback: (response) => {
showToast(response?.message, "success") showToast(response?.message, "success")
@ -63,8 +59,6 @@ const EditActivityModal = ({
} }
}); });
const activityID = watch("activityID"); const activityID = watch("activityID");
const sortedActivities = useMemo( const sortedActivities = useMemo(
@ -107,6 +101,7 @@ const EditActivityModal = ({
const onSubmitForm = (data) => { const onSubmitForm = (data) => {
const payload = { const payload = {
...data, ...data,
plannedWork: Number(data.plannedWork.toFixed(2)),
id: workItem?.workItem?.id ?? workItem?.id, id: workItem?.workItem?.id ?? workItem?.id,
buildingID: building?.id, buildingID: building?.id,
floorId: floor?.id, floorId: floor?.id,
@ -125,156 +120,169 @@ const EditActivityModal = ({
}); });
} }
return ( return (
<form className="row g-2 p-2 p-md-1" onSubmit={handleSubmit(onSubmitForm)}> <AppFormProvider {...methods}>
<div className="text-center mb-1"> <form className="row g-2 p-2 p-md-1" onSubmit={handleSubmit(onSubmitForm)}>
<h5 className="mb-1">Manage Task</h5> <div className="text-center mb-1">
</div> <h5 className="mb-1">Manage Task</h5>
</div>
<div className="row g-2 text-start"> <div className="row g-2 text-start">
<div className="col-12 col-md-6"> <div className="col-12 col-md-6">
<label className="form-label">Select Building</label> <label className="form-label">Select Building</label>
<input
className="form-control"
value={building?.buildingName}
disabled
/>
</div>
<div className="col-12 col-md-6">
<label className="form-label">Select Floor</label>
<input
className="form-control"
value={floor?.floorName}
disabled
/>
</div>
</div>
<div className="col-12 text-start">
<label className="form-label">Select Work Area</label>
<input <input
className="form-control form-control-sm" className="form-control"
value={building?.buildingName} value={workArea?.areaName}
disabled
/>
</div>
<div className="col-12 text-start">
<label className="form-label">Select Service</label>
<input
className="form-control"
value={
workItem?.activityMaster?.activityGroupMaster?.service?.name || ""
}
disabled disabled
/> />
</div> </div>
<div className="col-12 col-md-6">
<label className="form-label">Select Floor</label> <div className="col-12 text-start">
<input <label className="form-label">Select Activity</label>
className="form-control form-control-sm" <select
value={floor?.floorName} {...register("activityID")}
className="form-select"
disabled disabled
>
<option >Select Activity</option>
{loadingActivities ? (
<option>Loading...</option>
) : (
sortedActivities.map((a) => (
<option key={a.id} value={a.id}>
{a.activityName}
</option>
))
)}
</select>
{errors.activityID && (
<p className="danger-text">{errors.activityID.message}</p>
)}
</div>
<div className="col-12 text-start">
<AppFormController
name="workCategoryId"
control={control}
render={({ field }) => (
<SelectField
label="Select Work Category"
placeholder="Select Category"
options={
loadingCategories
? []
: sortedCategories?.map((c) => ({
id: String(c.id),
name: c.name,
})) ?? []
}
isLoading={loadingCategories}
labelKey="name"
valueKey="id"
value={field.value}
onChange={field.onChange}
className="m-0"
/>
)}
/>
{errors.workCategoryId && (
<small className="danger-text">{errors.workCategoryId.message}</small>
)}
</div>
<div className="col-5 text-start">
<label className="form-label">Planned Work</label>
<input
{...register("plannedWork", { valueAsNumber: true })}
type="number"
step="0.01" // <-- allows 2 decimal places
className="form-control"
/>
{errors.plannedWork && (
<p className="danger-text">{errors.plannedWork.message}</p>
)}
</div>
<div className="col-5 text-start">
<label className="form-label">Completed Work</label>
<input
{...register("completedWork", { valueAsNumber: true })}
type="number"
disabled={getValues("completedWork") > 0}
className="form-control"
/>
{errors.completedWork && (
<p className="danger-text">{errors.completedWork.message}</p>
)}
</div>
<div className="col-2 text-start">
<label className="form-label">Unit</label>
<input
className="form-control"
disabled
value={selectedActivity?.unitOfMeasurement || ""}
/> />
</div> </div>
</div>
<div className="col-12 text-start"> <div className="col-12 text-start">
<label className="form-label">Select Work Area</label> <label className="form-label">Comment</label>
<input <textarea {...register("comment")} rows="2" className="form-control" />
className="form-control form-control-sm" {errors.comment && (
value={workArea?.areaName} <div className="danger-text">{errors.comment.message}</div>
disabled
/>
</div>
<div className="col-12 text-start">
<label className="form-label">Select Service</label>
<input
className="form-control form-control-sm"
value={
workItem?.activityMaster?.activityGroupMaster?.service?.name || ""
}
disabled
/>
</div>
<div className="col-12 text-start">
<label className="form-label">Select Activity</label>
<select
{...register("activityID")}
className="form-select form-select-sm"
disabled
>
<option >Select Activity</option>
{loadingActivities ? (
<option>Loading...</option>
) : (
sortedActivities.map((a) => (
<option key={a.id} value={a.id}>
{a.activityName}
</option>
))
)} )}
</select> </div>
{errors.activityID && (
<p className="danger-text">{errors.activityID.message}</p>
)}
</div>
<div className="col-12 text-start"> <div className="col-12 text-end mt-5">
<label className="form-label">Select Work Category</label> <button
<select type="button"
{...register("workCategoryId")} className="btn btn-sm btn-label-secondary me-2"
className="form-select form-select-sm" onClick={onClose}
> disabled={isPending}
<option disabled>Select Category</option> >
{loadingCategories ? ( Cancel
<option>Loading...</option> </button>
) : ( <button
sortedCategories.map((c) => ( type="submit"
<option key={c.id} value={c.id}> className="btn btn-sm btn-primary"
{c.name} disabled={isPending}
</option> >
)) {isPending ? "Please Wait..." : "Edit Task"}
)} </button>
</select> </div>
{errors.workCategoryId && ( </form>
<p className="danger-text">{errors.workCategoryId.message}</p> </AppFormProvider>
)}
</div>
<div className="col-5 text-start">
<label className="form-label">Planned Work</label>
<input
{...register("plannedWork", { valueAsNumber: true })}
type="number"
className="form-control form-control-sm"
/>
{errors.plannedWork && (
<p className="danger-text">{errors.plannedWork.message}</p>
)}
</div>
<div className="col-5 text-start">
<label className="form-label">Completed Work</label>
<input
{...register("completedWork", { valueAsNumber: true })}
type="number"
disabled={getValues("completedWork") > 0}
className="form-control form-control-sm"
/>
{errors.completedWork && (
<p className="danger-text">{errors.completedWork.message}</p>
)}
</div>
<div className="col-2 text-start">
<label className="form-label">Unit</label>
<input
className="form-control form-control-sm"
disabled
value={selectedActivity?.unitOfMeasurement || ""}
/>
</div>
<div className="col-12 text-start">
<label className="form-label">Comment</label>
<textarea {...register("comment")} rows="2" className="form-control" />
{errors.comment && (
<div className="danger-text">{errors.comment.message}</div>
)}
</div>
<div className="col-12 text-end mt-5">
<button
type="button"
className="btn btn-sm btn-label-secondary me-2"
onClick={onClose}
disabled={isPending}
>
Cancel
</button>
<button
type="submit"
className="btn btn-sm btn-primary"
disabled={isPending}
>
{isPending ? "Please Wait..." : "Edit Task"}
</button>
</div>
</form>
); );
}; };

View File

@ -6,6 +6,8 @@ import showToast from "../../../services/toastService";
import { useManageProjectInfra } from "../../../hooks/useProjects"; import { useManageProjectInfra } from "../../../hooks/useProjects";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import Label from "../../common/Label"; import Label from "../../common/Label";
import { AppFormController, AppFormProvider } from "../../../hooks/appHooks/useAppForm";
import SelectField from "../../common/Forms/SelectField";
// Schema // Schema
const floorSchema = z.object({ const floorSchema = z.object({
@ -27,17 +29,12 @@ const FloorModel = ({ project, onClose, onSubmit }) => {
); );
const [selectedBuilding, setSelectedBuilding] = useState(null); const [selectedBuilding, setSelectedBuilding] = useState(null);
const { const methods = useForm({
register,
handleSubmit,
setValue,
reset,
watch,
formState: { errors },
} = useForm({
defaultValues, defaultValues,
resolver: zodResolver(floorSchema), resolver: zodResolver(floorSchema),
}); });
const { register, control, watch, handleSubmit, reset, setValue, formState: { errors } } = methods;
const watchId = watch("id"); const watchId = watch("id");
const watchBuildingId = watch("buildingId"); const watchBuildingId = watch("buildingId");
const { mutate: ManageFloor, isPending } = useManageProjectInfra({ const { mutate: ManageFloor, isPending } = useManageProjectInfra({
@ -48,7 +45,7 @@ const FloorModel = ({ project, onClose, onSubmit }) => {
: "Floor created Successfully", : "Floor created Successfully",
"success" "success"
); );
reset({ id: "0", floorName: ""}); reset({ id: "0", floorName: "" });
// onClose?.(); // onClose?.();
}, },
}); });
@ -98,94 +95,139 @@ const FloorModel = ({ project, onClose, onSubmit }) => {
}; };
return ( return (
<form className="row g-2" onSubmit={handleSubmit(onFormSubmit)}> <AppFormProvider {...methods}>
<div className="text-center mb-1"> <form className="row g-2" onSubmit={handleSubmit(onFormSubmit)}>
<h5 className="mb-1">Manage Floor</h5> <div className="text-center mb-1">
</div> <h5 className="mb-1">Manage Floor</h5>
<div className="col-12 text-start"> </div>
<Label className="form-label" required>Select Building</Label> <div className="col-12 text-start">
<select <Label className="form-label" required>
{...register("buildingId")} Select Building
className="form-select form-select-sm" </Label>
onChange={handleBuildingChange} <AppFormController
> name="buildingId"
<option value="0">Select Building</option> control={control}
{project?.length > 0 && rules={{ required: "Building is required" }}
project render={({ field }) => (
.filter((b) => b.buildingName) <SelectField
.sort((a, b) => a.buildingName.localeCompare(b.buildingName)) label=""
.map((b) => ( placeholder="Select Building"
<option key={b.id} value={b.id}> options={
{b.buildingName} project
</option> ?.filter((b) => b.buildingName)
))} .sort((a, b) => a.buildingName.localeCompare(b.buildingName))
</select> .map((b) => ({ id: String(b.id), name: b.buildingName })) ?? []
{errors.buildingId && ( }
<p className="danger-text">{errors.buildingId.message}</p> value={field.value || ""}
)} onChange={(value) => {
</div> field.onChange(value);
setValue("id", "0");
{watchBuildingId !== "0" && ( setValue("floorName", "");
<> }}
<div className="col-12 text-start"> required
<label className="form-label">Select Floor</label> noOptionsMessage={() => (!project || project.length === 0 ? "No buildings found" : null)}
<select className="m-0 form-select-sm w-100"
{...register("id")} />
className="form-select form-select-sm"
onChange={handleFloorChange}
>
<option value="0">Add New Floor</option>
{selectedBuilding?.floors?.length > 0 &&
selectedBuilding.floors
.filter((f) => f.floorName)
.sort((a, b) => a.floorName.localeCompare(b.floorName))
.map((f) => (
<option key={f.id} value={f.id}>
{f.floorName}
</option>
))}
</select>
</div>
<div className="col-12 text-start">
<Label className="form-label" required>
{watchId !== "0" ? "Edit Floor Name" : "New Floor Name"}
</Label>
<input
{...register("floorName")}
className="form-control form-control-sm"
placeholder="Floor Name"
/>
{errors.floorName && (
<p className="danger-text">{errors.floorName.message}</p>
)} )}
</div> />
</> {errors.buildingId && <p className="danger-text">{errors.buildingId.message}</p>}
)} </div>
<div className="col-12 text-end mt-5"> {watchBuildingId !== "0" && (
<button <>
type="button" <div className="col-12 text-start">
className="btn btn-sm btn-label-secondary me-3" <Label className="form-label">
disabled={isPending} Select Floor
onClick={onClose} </Label>
>
Cancel <AppFormController
</button> name="id"
<button control={control}
type="submit" rules={{ required: "Floor is required" }}
className="btn btn-sm btn-primary" render={({ field }) => {
disabled={isPending} // Prepare options
> const floorOptions = [
{isPending { id: "0", name: "Add New Floor" },
? "Please Wait" ...(selectedBuilding?.floors
: watchId !== "0" ?.filter((f) => f.floorName)
? "Edit Floor" .sort((a, b) => a.floorName.localeCompare(b.floorName))
: "Add Floor"} .map((f) => ({ id: f.id, name: f.floorName })) ?? []),
</button> ];
</div> return (
</form> <SelectField
label=""
placeholder="Select Floor"
options={floorOptions}
value={field.value || "0"} // default to "0"
onChange={(val) => {
field.onChange(val); // update react-hook-form
if (val === "0") {
setValue("floorName", ""); // clear for new floor
} else {
const floor = selectedBuilding?.floors?.find(f => f.id === val);
setValue("floorName", floor?.floorName || "");
}
}}
required
noOptionsMessage={() =>
!selectedBuilding?.floors || selectedBuilding.floors.length === 0
? "No floors found"
: null
}
className="m-0 form-select-sm w-100"
/>
);
}}
/>
{errors.id && (
<span className="danger-text">{errors.id.message}</span>
)}
</div>
<div className="col-12 text-start">
<Label className="form-label" required>
{watchId !== "0" ? "Edit Floor Name" : "New Floor Name"}
</Label>
<input
{...register("floorName")}
className="form-control"
placeholder="Floor Name"
/>
{errors.floorName && (
<p className="danger-text">{errors.floorName.message}</p>
)}
</div>
</>
)}
<div className="col-12 text-end mt-6 my-2">
<button
type="button"
className="btn btn-sm btn-label-secondary me-3"
disabled={isPending}
onClick={onClose}
>
Cancel
</button>
<button
type="submit"
className="btn btn-sm btn-primary"
disabled={isPending}
>
{isPending
? "Please Wait"
: watchId !== "0"
? "Edit Floor"
: "Add Floor"}
</button>
</div>
</form>
</AppFormProvider>
); );
}; };

View File

@ -8,10 +8,12 @@ import {
useGroups, useGroups,
useWorkCategoriesMaster, useWorkCategoriesMaster,
} from "../../../hooks/masterHook/useMaster"; } from "../../../hooks/masterHook/useMaster";
import { useManageTask, useProjectAssignedOrganizationsName, useProjectAssignedServices } from "../../../hooks/useProjects"; import { useCurrentService, useManageTask, useProjectAssignedOrganizationsName, useProjectAssignedServices } from "../../../hooks/useProjects";
import showToast from "../../../services/toastService"; import showToast from "../../../services/toastService";
import Label from "../../common/Label"; import Label from "../../common/Label";
import { useSelectedProject } from "../../../slices/apiDataManager"; import { useSelectedProject } from "../../../slices/apiDataManager";
import { AppFormController, AppFormProvider } from "../../../hooks/appHooks/useAppForm";
import SelectField from "../../common/Forms/SelectField";
const taskSchema = z.object({ const taskSchema = z.object({
buildingID: z.string().min(1, "Building is required"), buildingID: z.string().min(1, "Building is required"),
@ -26,12 +28,16 @@ const taskSchema = z.object({
comment: z.string(), comment: z.string(),
}); });
const defaultModel = {
const TaskModel = ({ project, onSubmit, onClose }) => {
const currentService = useCurrentService()
const defaultModel = {
id: null, id: null,
buildingID: "", buildingID: "",
floorId: "", floorId: "",
workAreaId: "", workAreaId: "",
serviceId: "", serviceId: currentService ?? "",
activityGroupId: "", activityGroupId: "",
activityID: "", activityID: "",
workCategoryId: "", workCategoryId: "",
@ -39,8 +45,6 @@ const defaultModel = {
completedWork: 0, completedWork: 0,
comment: "", comment: "",
}; };
const TaskModel = ({ project, onSubmit, onClose }) => {
// const { activities, loading: activityLoading } = useActivitiesMaster(); // const { activities, loading: activityLoading } = useActivitiesMaster();
const { categories, categoryLoading } = useWorkCategoriesMaster(); const { categories, categoryLoading } = useWorkCategoriesMaster();
@ -76,19 +80,13 @@ const TaskModel = ({ project, onSubmit, onClose }) => {
setValue("activityID", ""); setValue("activityID", "");
}; };
const methods = useForm({
const {
register,
handleSubmit,
watch,
setValue,
reset,
formState: { errors },
} = useForm({
resolver: zodResolver(taskSchema),
defaultValues: defaultModel, defaultValues: defaultModel,
resolver: zodResolver(taskSchema),
}); });
const { register, control, watch, handleSubmit, reset, setValue, formState: { errors } } = methods;
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
const [activityData, setActivityData] = useState([]); const [activityData, setActivityData] = useState([]);
const [categoryData, setCategoryData] = useState([]); const [categoryData, setCategoryData] = useState([]);
@ -112,10 +110,10 @@ const TaskModel = ({ project, onSubmit, onClose }) => {
const { mutate: CreateTask, isPending } = useManageTask({ const { mutate: CreateTask, isPending } = useManageTask({
onSuccessCallback: (response) => { onSuccessCallback: (response) => {
showToast(response?.message, "success"); showToast(response?.message, "success");
setValue("activityID",""), setValue("activityID", ""),
setValue("plannedWork",0), setValue("plannedWork", 0),
setValue("completedWork",0) setValue("completedWork", 0)
setValue("comment","") setValue("comment", "")
}, },
}); });
useEffect(() => { useEffect(() => {
@ -148,224 +146,290 @@ const TaskModel = ({ project, onSubmit, onClose }) => {
}; };
return ( return (
<form className="row g-2" onSubmit={handleSubmit(onSubmitForm)}> <AppFormProvider {...methods}>
<div className="text-center mb-1"> <form className="row g-2" onSubmit={handleSubmit(onSubmitForm)}>
<h5 className="mb-1">Manage Task</h5> <div className="text-center mb-1">
</div> <h5 className="mb-1">Manage Task</h5>
<div className="col-6 text-start"> </div>
<Label className="form-label" required>Select Building</Label> {/* Select Building */}
<select
className="form-select form-select-sm"
{...register("buildingID")}
>
<option value="">Select Building</option>
{project
?.filter((b) => b?.buildingName)
?.sort((a, b) => a?.buildingName.localeCompare(b.buildingName))
?.map((b) => (
<option key={b.id} value={b.id}>
{b.buildingName}
</option>
))}
</select>
{errors.buildingID && (
<p className="danger-text">{errors.buildingID.message}</p>
)}
</div>
{selectedBuilding && (
<div className="col-6 text-start"> <div className="col-6 text-start">
<Label className="form-label" required>Select Floor</Label> <AppFormController
<select name="buildingID"
className="form-select form-select-sm" control={control}
{...register("floorId")} render={({ field }) => (
> <SelectField
<option value="">Select Floor</option> label="Select Building"
{selectedBuilding.floors options={project ?? []}
?.sort((a, b) => a.floorName.localeCompare(b.floorName)) placeholder="Select Building"
?.map((f) => ( required
<option key={f.id} value={f.id}> labelKey="buildingName"
{f.floorName} valueKey="id"
</option> value={field.value}
))} onChange={(value) => {
</select> field.onChange(value);
{errors.floorId && ( setValue("floorId", "");
<p className="danger-text">{errors.floorId.message}</p> setValue("workAreaId", "");
)} setSelectedService("");
</div> setSelectedGroup("");
)} }}
className="m-0"
{/* Work Area Selection */} />
{selectedFloor && (
<div className="col-12 text-start">
<Label className="form-label" required>Select Work Area</Label>
<select
className="form-select form-select-sm"
{...register("workAreaId")}
>
<option value="">Select Work Area</option>
{selectedFloor.workAreas
?.sort((a, b) => a.areaName.localeCompare(b.areaName))
?.map((w) => (
<option key={w.id} value={w.id}>
{w.areaName}
</option>
))}
</select>
{errors.workAreaId && (
<p className="danger-text">{errors.workAreaId.message}</p>
)}
</div>
)}
{/* Services Selection */}
{selectedWorkArea && (
<div className="col-12 text-start">
<Label className="form-label" required>Select Service</Label>
<select
className="form-select form-select-sm"
{...register("serviceId")}
value={selectedService}
// onChange={handleServiceChange}
onChange={(e) => {
handleServiceChange(e);
setValue("serviceId", e.target.value);
}}
>
<option value="">Select Service</option>
{servicesLoading && <option>Loading...</option>}
{assignedServices?.map((service) => (
<option key={service.id} value={service.id}>
{service.name}
</option>
))}
</select>
</div>
)}
{/* Activity Group (Organization) Selection */}
{selectedService && (
<div className="col-12 text-start">
<Label className="form-label" required>Select Activity Group</Label>
<select
className="form-select form-select-sm"
{...register("activityGroupId")}
value={selectedGroup}
onChange={handleGroupChange}
>
<option value="">Select Group</option>
{groupsLoading && <option>Loading...</option>}
{groups?.map((g) => (
<option key={g.id} value={g.id}>{g.name}</option>
))}
</select>
{errors.activityGroupId && <p className="danger-text">{errors.activityGroupId.message}</p>}
</div>
)}
{/* Activity Selection */}
{selectedGroup && (
<div className="col-12 text-start">
<Label className="form-label" required>Select Activity</Label>
<select className="form-select form-select-sm" {...register("activityID")}>
<option value="">Select Activity</option>
{activitiesLoading && <option>Loading...</option>}
{activities?.map((a) => (
<option key={a.id} value={a.id}>{a.activityName}</option>
))}
</select>
{errors.activityID && <p className="danger-text">{errors.activityID.message}</p>}
</div>
)}
{watchActivityId && (
<div className="col-12 text-start">
<label className="form-label">Select Work Category</label>
<select
className="form-select form-select-sm"
{...register("workCategoryId")}
>
{categoryData.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
{errors.workCategoryId && (
<p className="danger-text">{errors.workCategoryId.message}</p>
)}
</div>
)}
{selectedActivity && selectedCategory && (
<>
<div className="col-5 text-start">
<Label className="form-label" required>Planned Work</Label>
<input
type="number"
className="form-control form-control-sm"
{...register("plannedWork", { valueAsNumber: true })}
/>
{errors.plannedWork && (
<p className="danger-text">{errors.plannedWork.message}</p>
)} )}
</div>
<div className="col-5 text-start">
<label className="form-label">Completed Work</label>
<input
type="number"
className="form-control form-control-sm"
{...register("completedWork", { valueAsNumber: true })}
/>
{errors.completedWork && (
<p className="danger-text">{errors.completedWork.message}</p>
)}
</div>
<div className="col-2 text-start">
<label className="form-label">Unit</label>
<input
type="text"
className="form-control form-control-sm"
disabled
value={selectedActivity?.unitOfMeasurement || ""}
/>
</div>
</>
)}
{selectedActivity && selectedCategory && (
<div className="col-12 text-start">
<label className="form-label">Comment</label>
<textarea
className="form-control"
rows="2"
{...register("comment")}
/> />
{errors.comment && ( {errors.buildingID && (
<p className="danger-text">{errors.comment.message}</p> <small className="danger-text">{errors.buildingID.message}</small>
)} )}
</div> </div>
)}
<div className="col-12 text-end mt-5"> {/* Select Floor */}
<button {selectedBuilding && (
type="button" <div className="col-6 text-start">
className="btn btn-sm btn-label-secondary me-3" <AppFormController
onClick={onClose} name="floorId"
> control={control}
Cancel render={({ field }) => (
</button> <SelectField
<button label="Select Floor"
type="submit" options={selectedBuilding?.floors ?? []}
className="btn btn-sm btn-primary" placeholder={
// disabled={isSubmitting} selectedBuilding?.floors?.length > 0
disabled={isPending} ? "Select Floor"
> : "No Floor Found"
{isPending ? "Please Wait..." : "Add Task"} }
</button> required
</div> labelKey="floorName"
</form> valueKey="id"
value={field.value}
onChange={(value) => {
field.onChange(value);
setValue("workAreaId", "");
}}
className="m-0"
/>
)}
/>
{errors.floorId && (
<small className="danger-text">{errors.floorId.message}</small>
)}
</div>
)}
{/* Select Work Area */}
{selectedFloor && (
<div className="col-12 text-start">
<AppFormController
name="workAreaId"
control={control}
render={({ field }) => (
<SelectField
label="Select Work Area"
options={selectedFloor?.workAreas ?? []}
placeholder="Select Work Area"
required
labelKey="areaName"
valueKey="id"
value={field.value}
onChange={(value) => {
field.onChange(value);
setSelectedService("");
setSelectedGroup("");
}}
className="m-0"
/>
)}
/>
{errors.workAreaId && (
<small className="danger-text">{errors.workAreaId.message}</small>
)}
</div>
)}
{/* Select Service */}
{selectedWorkArea && (
<div className="col-12 text-start">
<AppFormController
name="serviceId"
control={control}
render={({ field }) => (
<SelectField
label="Select Service"
options={assignedServices ?? []}
placeholder="Select Service"
required
labelKey="name"
valueKey="id"
value={field.value}
onChange={(value) => {
field.onChange(value);
setSelectedService(value);
setSelectedGroup("");
setValue("activityGroupId", "");
setValue("activityID", "");
}}
isLoading={servicesLoading}
className="m-0"
/>
)}
/>
{errors.serviceId && (
<small className="danger-text">{errors.serviceId.message}</small>
)}
</div>
)}
{/* Select Activity Group */}
{selectedService && (
<div className="col-12 text-start">
<AppFormController
name="activityGroupId"
control={control}
render={({ field }) => (
<SelectField
label="Select Activity Group"
options={groups ?? []}
placeholder="Select Activity Group"
required
labelKey="name"
valueKey="id"
value={field.value}
onChange={(value) => {
field.onChange(value);
setSelectedGroup(value);
setValue("activityID", "");
}}
isLoading={groupsLoading}
className="m-0"
/>
)}
/>
{errors.activityGroupId && (
<small className="danger-text">{errors.activityGroupId.message}</small>
)}
</div>
)}
{/* Select Activity */}
{selectedGroup && (
<div className="col-12 text-start">
<AppFormController
name="activityID"
control={control}
render={({ field }) => (
<SelectField
label="Select Activity"
options={activities ?? []}
placeholder="Select Activity"
required
labelKey="activityName"
valueKey="id"
value={field.value}
onChange={field.onChange}
isLoading={activitiesLoading}
className="m-0"
/>
)}
/>
{errors.activityID && (
<small className="danger-text">{errors.activityID.message}</small>
)}
</div>
)}
{watchActivityId && (
<div className="col-12 text-start">
<AppFormController
name="workCategoryId"
control={control}
render={({ field }) => (
<SelectField
label="Select Work Category"
options={categoryData ?? []}
placeholder="Select Work Category"
required
labelKey="name"
valueKey="id"
value={field.value}
onChange={field.onChange}
className="m-0"
/>
)}
/>
{errors.workCategoryId && (
<small className="danger-text">{errors.workCategoryId.message}</small>
)}
</div>
)}
{selectedActivity && selectedCategory && (
<>
<div className="col-5 text-start">
<Label className="form-label" required>Planned Work</Label>
<input
type="number"
className="form-control "
{...register("plannedWork", { valueAsNumber: true })}
/>
{errors.plannedWork && (
<p className="danger-text">{errors.plannedWork.message}</p>
)}
</div>
<div className="col-5 text-start">
<label className="form-label">Completed Work</label>
<input
type="number"
className="form-control "
{...register("completedWork", { valueAsNumber: true })}
/>
{errors.completedWork && (
<p className="danger-text">{errors.completedWork.message}</p>
)}
</div>
<div className="col-2 text-start">
<label className="form-label">Unit</label>
<input
type="text"
className="form-control "
disabled
value={selectedActivity?.unitOfMeasurement || ""}
/>
</div>
</>
)}
{selectedActivity && selectedCategory && (
<div className="col-12 text-start">
<label className="form-label">Comment</label>
<textarea
className="form-control"
rows="2"
{...register("comment")}
/>
{errors.comment && (
<p className="danger-text">{errors.comment.message}</p>
)}
</div>
)}
<div className="col-12 text-end mt-6 my-2">
<button
type="button"
className="btn btn-sm btn-label-secondary me-3"
onClick={onClose}
>
Cancel
</button>
<button
type="submit"
className="btn btn-sm btn-primary"
// disabled={isSubmitting}
disabled={isPending}
>
{isPending ? "Please Wait..." : "Add Task"}
</button>
</div>
</form>
</AppFormProvider>
); );
}; };

View File

@ -6,6 +6,8 @@ import showToast from "../../../services/toastService";
import { useManageProjectInfra } from "../../../hooks/useProjects"; import { useManageProjectInfra } from "../../../hooks/useProjects";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import Label from "../../common/Label"; import Label from "../../common/Label";
import { AppFormController, AppFormProvider } from "../../../hooks/appHooks/useAppForm";
import SelectField from "../../common/Forms/SelectField";
const workAreaSchema = z.object({ const workAreaSchema = z.object({
id: z.string().optional(), id: z.string().optional(),
@ -26,19 +28,14 @@ const defaultModel = {
const WorkAreaModel = ({ project, onSubmit, onClose }) => { const WorkAreaModel = ({ project, onSubmit, onClose }) => {
const [selectedBuilding, setSelectedBuilding] = useState(null); const [selectedBuilding, setSelectedBuilding] = useState(null);
const [selectedFloor, setSelectedFloor] = useState(null); const [selectedFloor, setSelectedFloor] = useState(null);
const selectedProject = useSelector((store) => store.localVariables.projectId) const selectedProject = useSelector((store) => store.localVariables.projectId);
const { const methods = useForm({
register,
handleSubmit,
formState: { errors },
setValue,
reset,
watch,
} = useForm({
resolver: zodResolver(workAreaSchema),
defaultValues: defaultModel, defaultValues: defaultModel,
resolver: zodResolver(workAreaSchema),
}); });
const { register, control, watch, handleSubmit, reset, setValue, formState: { errors } } = methods;
const watchBuildingId = watch("buildingId"); const watchBuildingId = watch("buildingId");
const watchFloorId = watch("floorId"); const watchFloorId = watch("floorId");
const watchWorkAreaId = watch("id"); const watchWorkAreaId = watch("id");
@ -104,99 +101,122 @@ const WorkAreaModel = ({ project, onSubmit, onClose }) => {
}; };
return ( return (
<form className="row g-2 p-2 p-md-1" onSubmit={handleSubmit(onSubmitForm)}> <AppFormProvider {...methods}>
<div className="text-center mb-1"> <form className="row g-2 p-2 p-md-1" onSubmit={handleSubmit(onSubmitForm)}>
<h5 className="mb-1">Manage Work Area</h5> <div className="text-center mb-1">
</div> <h5 className="mb-1">Manage Work Area</h5>
<div className="col-12 col-sm-6 text-start"> </div>
<Label className="form-label" required>Select Building</Label>
<select
{...register("buildingId")}
className="form-select form-select-sm"
>
<option value="0">Select Building</option>
{project?.map((b) => (
<option key={b.id} value={b.id}>
{b.buildingName}
</option>
))}
</select>
{errors.buildingId && (
<p className="danger-text">{errors.buildingId.message}</p>
)}
</div>
{watchBuildingId !== "0" && (
<div className="col-12 col-sm-6 text-start"> <div className="col-12 col-sm-6 text-start">
<Label className="form-label" required>Select Floor</Label> <AppFormController
<select name="buildingId"
{...register("floorId")} control={control}
className="form-select form-select-sm" render={({ field }) => (
> <SelectField
<option value="0"> label="Select Building"
{selectedBuilding?.floor?.length > 0 options={project ?? []}
? "NO Floor Found" placeholder="Select Building"
: "Select Floor"} required
</option> labelKey="buildingName"
valueKey="id"
value={field.value}
onChange={field.onChange}
className="m-0"
/>
)}
/>
{selectedBuilding?.floors?.map((f) => ( {errors.buildingId && (
<option key={f.id} value={f.id}> <small className="danger-text">{errors.buildingId.message}</small>
{f.floorName}
</option>
))}
</select>
{errors.floorId && (
<p className="danger-text">{errors.floorId.message}</p>
)} )}
</div> </div>
)}
{watchFloorId !== "0" && (
<>
<div className="col-12 text-start">
<label className="form-label">Select Work Area</label>
<select
{...register("id")}
className="form-select form-select-sm"
onChange={handleWrokAreaChange}
>
<option value="0">Create New Work Area</option>
{selectedFloor?.workAreas?.length > 0 &&
selectedFloor?.workAreas?.map((w) => (
<option key={w.id} value={w.id}>
{w.areaName}
</option>
))}
</select>
</div>
<div className="col-12 text-start">
<Label className="form-label" required> {watchBuildingId !== "0" && (
{watchWorkAreaId === "0" <div className="col-12 col-sm-6 text-start">
? "Enter Work Area Name" <AppFormController
: "Edit Work Area Name"} name="floorId"
</Label> control={control}
<input render={({ field }) => (
type="text" <SelectField
className="form-control form-control-sm" label="Select Floor"
placeholder="Work Area" options={selectedBuilding?.floors ?? []}
{...register("areaName")} placeholder={
selectedBuilding?.floors?.length > 0
? "Select Floor"
: "No Floor Found"
}
required
labelKey="floorName"
valueKey="id"
value={field.value}
onChange={(value) => {
field.onChange(value);
setValue("areaName", ""); // reset Work Area name when floor changes
}}
className="m-0"
/>
)}
/> />
{errors.areaName && ( {errors.floorId && (
<p className="danger-text">{errors.areaName.message}</p> <small className="danger-text">{errors.floorId.message}</small>
)} )}
</div> </div>
</> )}
)}
<div className="col-12 text-end mt-5">
<button type="button" className="btn btn-sm btn-label-secondary me-3" disabled={isPending} onClick={onClose}>
Cancel
</button>
<button type="submit" className="btn btn-sm btn-primary" disabled={isPending}>
{isPending ? "Please Wait.." : watchWorkAreaId === "0" ? "Add Work Area" : "Update Work Area"}
</button>
</div> {watchFloorId !== "0" && (
</form> <>
<div className="col-12 text-start">
<AppFormController
name="id"
control={control}
render={({ field }) => (
<SelectField
label="Select Work Area"
options={selectedFloor?.workAreas ?? []}
placeholder="Create New Work Area"
required={false}
labelKey="areaName"
valueKey="id"
value={field.value}
onChange={(value) => {
field.onChange(value);
handleWrokAreaChange({ target: { value } }); // preserve your existing handler
}}
className="m-0"
/>
)}
/>
</div>
<div className="col-12 text-start">
<Label className="form-label" required>
{watchWorkAreaId === "0"
? "Enter Work Area Name"
: "Edit Work Area Name"}
</Label>
<input
type="text"
className="form-control"
placeholder="Work Area"
{...register("areaName")}
/>
{errors.areaName && (
<p className="danger-text">{errors.areaName.message}</p>
)}
</div>
</>
)}
<div className="col-12 text-end mt-6 my-2">
<button type="button" className="btn btn-sm btn-label-secondary me-3" disabled={isPending} onClick={onClose}>
Cancel
</button>
<button type="submit" className="btn btn-sm btn-primary" disabled={isPending}>
{isPending ? "Please Wait.." : watchWorkAreaId === "0" ? "Add Work Area" : "Update Work Area"}
</button>
</div>
</form>
</AppFormProvider>
); );
}; };

View File

@ -17,6 +17,8 @@ import {
useOrganizationsList, useOrganizationsList,
} from "../../hooks/useOrganization"; } from "../../hooks/useOrganization";
import { localToUtc } from "../../utils/appUtils"; import { localToUtc } from "../../utils/appUtils";
import { AppFormController } from "../../hooks/appHooks/useAppForm";
import SelectField from "../common/Forms/SelectField";
const currentDate = new Date().toLocaleDateString("en-CA"); const currentDate = new Date().toLocaleDateString("en-CA");
const formatDate = (date) => { const formatDate = (date) => {
@ -42,8 +44,8 @@ const ManageProjectInfo = ({ project, onClose }) => {
1, 1,
true true
); );
const { mutate: UpdateProject, isPending } = useUpdateProject(() => {onClose?.()}); const { mutate: UpdateProject, isPending } = useUpdateProject(() => { onClose?.() });
const {mutate:CeateProject,isPending:isCreating} = useCreateProject(()=>{onClose?.()}) const { mutate: CeateProject, isPending: isCreating } = useCreateProject(() => { onClose?.() })
const { const {
register, register,
@ -74,7 +76,7 @@ const ManageProjectInfo = ({ project, onClose }) => {
pmcId: projects_Details?.pmc?.id || "", pmcId: projects_Details?.pmc?.id || "",
}); });
setAddressLength(projects_Details?.projectAddress?.length || 0); setAddressLength(projects_Details?.projectAddress?.length || 0);
}, [project, projects_Details, reset,data]); }, [project, projects_Details, reset, data]);
const onSubmitForm = (formData) => { const onSubmitForm = (formData) => {
if (project) { if (project) {
@ -85,8 +87,8 @@ const ManageProjectInfo = ({ project, onClose }) => {
id: project, id: project,
}; };
UpdateProject({ projectId: project, payload: payload }); UpdateProject({ projectId: project, payload: payload });
}else{ } else {
let payload = { let payload = {
...formData, ...formData,
startDate: localToUtc(formData.startDate), startDate: localToUtc(formData.startDate),
endDate: localToUtc(formData.endDate), endDate: localToUtc(formData.endDate),
@ -122,7 +124,7 @@ const ManageProjectInfo = ({ project, onClose }) => {
type="text" type="text"
id="name" id="name"
name="name" name="name"
className="form-control form-control-sm" className="form-control "
placeholder="Project Name" placeholder="Project Name"
{...register("name")} {...register("name")}
/> />
@ -143,7 +145,7 @@ const ManageProjectInfo = ({ project, onClose }) => {
type="text" type="text"
id="shortName" id="shortName"
name="shortName" name="shortName"
className="form-control form-control-sm" className="form-control "
placeholder="Short Name" placeholder="Short Name"
{...register("shortName")} {...register("shortName")}
/> />
@ -164,7 +166,7 @@ const ManageProjectInfo = ({ project, onClose }) => {
type="text" type="text"
id="contactPerson" id="contactPerson"
name="contactPerson" name="contactPerson"
className="form-control form-control-sm" className="form-control "
placeholder="Contact Person" placeholder="Contact Person"
maxLength={50} maxLength={50}
{...register("contactPerson")} {...register("contactPerson")}
@ -190,6 +192,7 @@ const ManageProjectInfo = ({ project, onClose }) => {
placeholder="DD-MM-YYYY" placeholder="DD-MM-YYYY"
maxDate={new Date()} // optional: restrict future dates maxDate={new Date()} // optional: restrict future dates
className="w-100" className="w-100"
size="md"
/> />
{errors.startDate && ( {errors.startDate && (
@ -213,6 +216,7 @@ const ManageProjectInfo = ({ project, onClose }) => {
placeholder="DD-MM-YYYY" placeholder="DD-MM-YYYY"
minDate={getValues("startDate")} // optional: restrict future dates minDate={getValues("startDate")} // optional: restrict future dates
className="w-100" className="w-100"
size="md"
/> />
{errors.endDate && ( {errors.endDate && (
@ -225,103 +229,108 @@ const ManageProjectInfo = ({ project, onClose }) => {
)} )}
</div> </div>
<div className="col-12 "> <div className="col-12">
<label className="form-label" htmlFor="modalEditUserStatus"> <Label htmlFor="modalEditUserStatus" className="form-label">
Status Status
</label> </Label>
<select
id="modalEditUserStatus" <AppFormController
name="modalEditUserStatus" name="projectStatusId"
className="select2 form-select form-select-sm" control={control}
aria-label="Default select example" rules={{ required: "Status is required" }}
{...register("projectStatusId", { render={({ field }) => (
required: "Status is required", <SelectField
valueAsNumber: false, label="" // Label is already above
})} placeholder="Select Status"
> options={PROJECT_STATUS?.map((status) => ({
{PROJECT_STATUS.map((status) => ( id: status.id,
<option key={status.id} value={status.id}> name: status.label,
{status.label} })) ?? []}
</option> value={field.value || ""}
))} onChange={field.onChange}
</select> required
className="m-0 form-select-sm w-100"
/>
)}
/>
{errors.projectStatusId && ( {errors.projectStatusId && (
<div <div className="danger-text text-start" style={{ fontSize: "12px" }}>
className="danger-text text-start"
style={{ fontSize: "12px" }}
>
{errors.projectStatusId.message} {errors.projectStatusId.message}
</div> </div>
)} )}
</div> </div>
<div className="col-12 ">
<label className="form-label" htmlFor="modalEditUserStatus"> <div className="col-12">
<Label htmlFor="promoterId" className="form-label">
Promoter Promoter
</label> </Label>
<select
className="select2 form-select form-select-sm" <AppFormController
aria-label="Default select example" name="promoterId"
{...register("promoterId", { control={control}
required: "Promoter is required", rules={{ required: "Promoter is required" }}
valueAsNumber: false, render={({ field }) => (
})} <SelectField
> label="" // Label is already above
{isLoading ? ( placeholder="Select Promoter"
<option>Loading...</option> options={data?.data ?? []}
) : ( value={field.value || ""}
<> onChange={field.onChange}
<option value="">Select Promoter</option> required
{data?.data?.map((org) => ( isLoading={isLoading}
<option key={org.id} value={org.id}> className="m-0 form-select-sm w-100"
{org.name} noOptionsMessage={() =>
</option> !isLoading && (!data?.data || data.data.length === 0)
))} ? "No promoters found"
</> : null
}
/>
)} )}
</select> />
{errors.promoterId && ( {errors.promoterId && (
<div <div className="danger-text text-start" style={{ fontSize: "12px" }}>
className="danger-text text-start"
style={{ fontSize: "12px" }}
>
{errors.promoterId.message} {errors.promoterId.message}
</div> </div>
)} )}
</div> </div>
<div className="col-12 ">
<label className="form-label" htmlFor="modalEditUserStatus"> <div className="col-12">
<Label htmlFor="pmcId" className="form-label">
PMC PMC
</label> </Label>
<select
className="select2 form-select form-select-sm" <AppFormController
aria-label="Default select example" name="pmcId"
{...register("pmcId", { control={control}
required: "Promoter is required", rules={{ required: "PMC is required" }}
valueAsNumber: false, render={({ field }) => (
})} <SelectField
> label="" // Label is already above
{isLoading ? ( placeholder="Select PMC"
<option>Loading...</option> options={data?.data ?? []}
) : ( value={field.value || ""}
<> onChange={field.onChange}
<option value="">Select PMC</option> required
{data?.data?.map((org) => ( isLoading={isLoading}
<option key={org.id} value={org.id}> className="m-0 form-select-sm w-100"
{org.name} noOptionsMessage={() =>
</option> !isLoading && (!data?.data || data.data.length === 0)
))} ? "No PMC found"
</> : null
}
/>
)} )}
</select> />
{errors.pmcId && ( {errors.pmcId && (
<div <div className="danger-text text-start" style={{ fontSize: "12px" }}>
className="danger-text text-start"
style={{ fontSize: "12px" }}
>
{errors.pmcId.message} {errors.pmcId.message}
</div> </div>
)} )}
</div> </div>
<div className="d-flex justify-content-between text-secondary text-tiny text-wrap"> <div className="d-flex justify-content-between text-secondary text-tiny text-wrap">
<span> <span>
<i className="bx bx-sm bx-info-circle"></i> Not found PMC and <i className="bx bx-sm bx-info-circle"></i> Not found PMC and
@ -376,7 +385,7 @@ const ManageProjectInfo = ({ project, onClose }) => {
className="btn btn-primary btn-sm" className="btn btn-primary btn-sm"
disabled={isPending || isCreating || loading} disabled={isPending || isCreating || loading}
> >
{isPending||isCreating ? "Please Wait..." : project ? "Update" : "Submit"} {isPending || isCreating ? "Please Wait..." : project ? "Update" : "Submit"}
</button> </button>
</div> </div>
</form> </form>

View File

@ -105,7 +105,7 @@ const ProjectCard = ({ project, isCore = true }) => {
> >
{project?.shortName ? project?.shortName : project?.name} {project?.shortName ? project?.shortName : project?.name}
</h5> </h5>
<div className="client-info text-body"> <div className="client-info text-body text-start">
<span>{project?.shortName ? project?.name : ""}</span> <span>{project?.shortName ? project?.name : ""}</span>
</div> </div>
</div> </div>

View File

@ -30,6 +30,9 @@ import { useParams } from "react-router-dom";
import GlobalModel from "../common/GlobalModel"; import GlobalModel from "../common/GlobalModel";
import { setService } from "../../slices/globalVariablesSlice"; import { setService } from "../../slices/globalVariablesSlice";
import { SpinnerLoader } from "../common/Loader"; import { SpinnerLoader } from "../common/Loader";
import { useForm } from "react-hook-form";
import { AppFormController } from "../../hooks/appHooks/useAppForm";
import SelectField from "../common/Forms/SelectField";
const ProjectInfra = ({ data, onDataChange, eachSiteEngineer }) => { const ProjectInfra = ({ data, onDataChange, eachSiteEngineer }) => {
const projectId = useSelectedProject(); const projectId = useSelectedProject();
@ -52,6 +55,12 @@ const ProjectInfra = ({ data, onDataChange, eachSiteEngineer }) => {
const { data: assignedServices, isLoading: servicesLoading } = const { data: assignedServices, isLoading: servicesLoading } =
useProjectAssignedServices(projectId); useProjectAssignedServices(projectId);
const { control, setValue } = useForm({
defaultValues: {
serviceId: selectedService || "",
},
});
useEffect(() => { useEffect(() => {
setProject(projectInfra); setProject(projectInfra);
}, [data, projects_Details]); }, [data, projects_Details]);
@ -60,6 +69,27 @@ const ProjectInfra = ({ data, onDataChange, eachSiteEngineer }) => {
setProject(response); setProject(response);
}; };
const handleServiceChange = (serviceId) => {
dispatch(setService(serviceId));
};
useEffect(() => {
if (!servicesLoading && assignedServices?.length === 1) {
const serviceId = assignedServices[0].id;
// set form value
setValue("serviceId", serviceId, {
shouldDirty: true,
shouldValidate: true,
});
// sync redux
dispatch(setService(serviceId));
}
}, [assignedServices, servicesLoading, setValue, dispatch]);
return ( return (
<> <>
{showModalBuilding && ( {showModalBuilding && (
@ -115,37 +145,35 @@ const ProjectInfra = ({ data, onDataChange, eachSiteEngineer }) => {
<div className="card-body" style={{ padding: "0.5rem" }}> <div className="card-body" style={{ padding: "0.5rem" }}>
<div className="align-items-center"> <div className="align-items-center">
<div className="row "> <div className="row ">
<div <div className="col-md-4 col-12 dataTables_length text-start py-2 px-2">
className="dataTables_length text-start py-2 px-6 col-md-4 col-12" <div className="ms-4 mt-n1">
id="DataTables_Table_0_length" {!servicesLoading && assignedServices?.length > 0 && (
> <AppFormController
{!servicesLoading && name="serviceId"
assignedServices?.length > 0 && control={control}
(assignedServices.length > 1 ? ( render={({ field }) => (
<label> <SelectField
<select label="Select Service"
name="DataTables_Table_0_length" options={[...(assignedServices ?? [])]}
aria-controls="DataTables_Table_0" placeholder="Choose a Service"
className="form-select form-select-sm" labelKey="name"
aria-label="Select Service" valueKey="id"
value={selectedService} value={field.value}
onChange={(e) => dispatch(setService(e.target.value))} onChange={(val) => {
> field.onChange(val);
<option value="">All Services</option> dispatch(setService(val));
{assignedServices.map((service) => ( }}
<option key={service.id} value={service.id}> isLoading={servicesLoading}
{service.name} />
</option> )}
))} />
</select> )}
</label>
) : ( </div>
<h5>{assignedServices[0].name}</h5>
))}
</div> </div>
{/* Buttons Section (aligned to right) */} {/* Buttons Section (aligned to right) */}
<div className="col-md-8 col-12 text-end mb-1"> <div className="col-md-8 col-12 text-end mt-4">
{ManageInfra && ( {ManageInfra && (
<> <>
<button <button
@ -199,7 +227,7 @@ const ProjectInfra = ({ data, onDataChange, eachSiteEngineer }) => {
serviceId={selectedService} serviceId={selectedService}
/> />
) : ( ) : (
<div className="text-center py-5"> <div className="text-center py-12">
<p className="text-muted fs-6">No infrastructure data available.</p> <p className="text-muted fs-6">No infrastructure data available.</p>
</div> </div>
)} )}

View File

@ -159,8 +159,9 @@ const ProjectListView = ({ data, currentPage, totalPages, paginate }) => {
</td> </td>
))} ))}
<td <td
className={`mx-2 ${canManageProject ? "d-sm-table-cell" : "d-none" className={`mx-2 ${
}`} canManageProject ? "d-sm-table-cell" : "d-none"
}`}
> >
<div className="dropdown z-2"> <div className="dropdown z-2">
<button <button
@ -218,7 +219,7 @@ const ProjectListView = ({ data, currentPage, totalPages, paginate }) => {
<tr <tr
className="no-hover" className="no-hover"
style={{ style={{
pointerEvents: "none", pointerEvents: "none",
backgroundColor: "transparent", backgroundColor: "transparent",
}} }}
> >
@ -238,7 +239,7 @@ const ProjectListView = ({ data, currentPage, totalPages, paginate }) => {
<Pagination <Pagination
currentPage={currentPage} currentPage={currentPage}
totalPages={totalPages} totalPages={totalPages}
paginate={paginate} onPageChange={paginate}
/> />
</div> </div>
); );

View File

@ -27,6 +27,7 @@ const ProjectNav = ({ onPillClick, activePill }) => {
const ProjectTab = [ const ProjectTab = [
{ key: "profile", icon: "bx bx-user", label: "Profile" }, { key: "profile", icon: "bx bx-user", label: "Profile" },
{ key: "organization", icon: "bx bx-buildings", label: "Organization" },
{ key: "teams", icon: "bx bx-group", label: "Teams" }, { key: "teams", icon: "bx bx-group", label: "Teams" },
{ {
key: "infra", key: "infra",
@ -41,7 +42,7 @@ const ProjectNav = ({ onPillClick, activePill }) => {
hidden: !(DirAdmin || DireManager || DirUser), hidden: !(DirAdmin || DireManager || DirUser),
}, },
{ key: "documents", icon: "bx bx-folder-open", label: "Documents", hidden: !(isViewDocuments || isModifyDocument || isUploadDocument) }, { key: "documents", icon: "bx bx-folder-open", label: "Documents", hidden: !(isViewDocuments || isModifyDocument || isUploadDocument) },
{ key: "organization", icon: "bx bx-buildings", label: "Organization" },
{ key: "setting", icon: "bx bxs-cog", label: "Setting", hidden: !isManageTeam }, { key: "setting", icon: "bx bxs-cog", label: "Setting", hidden: !isManageTeam },
]; ];
return ( return (

View File

@ -15,7 +15,7 @@ const ProjectAssignedOrgs = () => {
label: "Organization Name", label: "Organization Name",
getValue: (org) => ( getValue: (org) => (
<div className="d-flex gap-2 py-1 "> <div className="d-flex gap-2 py-1 ">
<i class="bx bx-buildings"></i> <i className="bx bx-buildings"></i>
<span <span
className="text-truncate d-inline-block " className="text-truncate d-inline-block "
style={{ maxWidth: "150px" }} style={{ maxWidth: "150px" }}
@ -103,7 +103,7 @@ const ProjectAssignedOrgs = () => {
<tbody> <tbody>
{Array.isArray(data) && data.length > 0 ? ( {Array.isArray(data) && data.length > 0 ? (
data.map((row, i) => ( data.map((row, i) => (
<tr key={i}> <tr key={i} style={{ height: "50px" }}>
{orgList.map((col) => ( {orgList.map((col) => (
<td key={col.key} className={col.align}> <td key={col.key} className={col.align}>
{col.getValue(row)} {col.getValue(row)}

View File

@ -10,6 +10,8 @@ import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod"; import { z } from "zod";
import showToast from "../../services/toastService"; import showToast from "../../services/toastService";
import { AppFormController } from "../../hooks/appHooks/useAppForm";
import SelectField from "../common/Forms/SelectField";
export const ProjectPermissionSchema = z.object({ export const ProjectPermissionSchema = z.object({
employeeId: z.string().min(1, "Employee is required"), employeeId: z.string().min(1, "Employee is required"),
@ -46,26 +48,26 @@ const ProjectPermission = () => {
); );
useEffect(() => { useEffect(() => {
if (!selectedEmployee) return; if (!selectedEmployee) return;
const enabledPerms = const enabledPerms =
selectedEmpPermissions?.permissions
?.filter((perm) => perm.isEnabled)
?.map((perm) => perm.id) || [];
setValue("selectedPermissions", enabledPerms, { shouldValidate: true });
}, [selectedEmpPermissions, setValue, selectedEmployee]);
const selectedPermissions = watch("selectedPermissions") || [];
const existingEnabledIds =
selectedEmpPermissions?.permissions selectedEmpPermissions?.permissions
?.filter((perm) => perm.isEnabled) ?.filter((p) => p.isEnabled)
?.map((perm) => perm.id) || []; ?.map((p) => p.id) || [];
setValue("selectedPermissions", enabledPerms, { shouldValidate: true }); const hasChanges =
}, [selectedEmpPermissions, setValue, selectedEmployee]); selectedPermissions.length !== existingEnabledIds.length ||
selectedPermissions.some((id) => !existingEnabledIds.includes(id));
const selectedPermissions = watch("selectedPermissions") || [];
const existingEnabledIds =
selectedEmpPermissions?.permissions
?.filter((p) => p.isEnabled)
?.map((p) => p.id) || [];
const hasChanges =
selectedPermissions.length !== existingEnabledIds.length ||
selectedPermissions.some((id) => !existingEnabledIds.includes(id));
const { mutate: updatePermission, isPending } = const { mutate: updatePermission, isPending } =
useUpdateProjectLevelEmployeePermission(); useUpdateProjectLevelEmployeePermission();
@ -115,35 +117,42 @@ const hasChanges =
<form className="row" onSubmit={handleSubmit(onSubmit)}> <form className="row" onSubmit={handleSubmit(onSubmit)}>
<div className="d-flex justify-content-between align-items-end gap-2 mb-3"> <div className="d-flex justify-content-between align-items-end gap-2 mb-3">
<div className="text-start d-flex align-items-center gap-2"> <div className="text-start d-flex align-items-center gap-2">
<div className="d-block"> {/* <div className="d-block">
<label className="form-label">Select Employee</label> <label className="form-label">Select Employee</label>
</div> </div> */}
<div className="d-block">
{" "} <div className="d-block flex-grow-1">
<select <AppFormController
className="form-select form-select-sm" name="employeeId"
{...register("employeeId")} control={control}
disabled={isPending} render={({ field }) => (
> <SelectField
{loading ? ( label="Select Employee"
<option value="">Loading...</option> options={
) : ( employees
<> ?.sort((a, b) =>
<option value="">-- Select Employee --</option> `${a?.firstName} ${a?.lastName}`.localeCompare(
{[...employees] `${b?.firstName} ${b?.lastName}`
?.sort((a, b) => )
`${a?.firstName} ${a?.firstName}`?.localeCompare(
`${b?.firstName} ${b?.lastName}`
) )
) ?.map((emp) => ({
?.map((emp) => ( id: emp.id,
<option key={emp.id} value={emp.id}> name: `${emp.firstName} ${emp.lastName}`,
{emp.firstName} {emp.lastName} })) ?? []
</option> }
))} placeholder="-- Select Employee --"
</> required
labelKey="name"
valueKeyKey="id"
value={field.value}
onChange={field.onChange}
isLoading={loading}
disabled={isPending}
className="m-0"
/>
)} )}
</select> />
{errors.employeeId && ( {errors.employeeId && (
<div className="d-block text-danger small"> <div className="d-block text-danger small">
{errors.employeeId.message} {errors.employeeId.message}
@ -152,6 +161,7 @@ const hasChanges =
</div> </div>
</div> </div>
<div className="mt-3 text-end"> <div className="mt-3 text-end">
{hasChanges && ( {hasChanges && (
<button <button

View File

@ -170,7 +170,7 @@ const ProjectStatistics = ({ project }) => {
<h5 className="card-action-title mb-0"> <h5 className="card-action-title mb-0">
{" "} {" "}
<i className="fa fa-line-chart rounded-circle text-primary"></i> <i className="fa fa-line-chart rounded-circle text-primary"></i>
<span className="ms-2 fw-bold">Project Statistics</span> <span className="ms-2 fw-semibold">Project Statistics</span>
</h5> </h5>
</div> </div>
<div className="card-body"> <div className="card-body">

View File

@ -1,9 +1,12 @@
import React, { useState } from "react"; import React, { useEffect, useState } from "react";
import TeamEmployeeList from "./TeamEmployeeList"; import TeamEmployeeList from "./TeamEmployeeList";
import { useOrganization } from "../../../hooks/useDirectory"; import { useOrganization } from "../../../hooks/useDirectory";
import { useOrganizationsList } from "../../../hooks/useOrganization"; import { useOrganizationsList } from "../../../hooks/useOrganization";
import { useProjectAssignedOrganizationsName } from "../../../hooks/useProjects"; import { useProjectAssignedOrganizationsName } from "../../../hooks/useProjects";
import { useSelectedProject } from "../../../slices/apiDataManager"; import { useSelectedProject } from "../../../slices/apiDataManager";
import { AppFormController } from "../../../hooks/appHooks/useAppForm";
import SelectField from "../../common/Forms/SelectField";
import { useForm } from "react-hook-form";
const TeamAssignToProject = ({ closeModal }) => { const TeamAssignToProject = ({ closeModal }) => {
const [searchText, setSearchText] = useState(""); const [searchText, setSearchText] = useState("");
@ -11,53 +14,58 @@ const TeamAssignToProject = ({ closeModal }) => {
const project = useSelectedProject(); const project = useSelectedProject();
const { data, isLoading, isError, error } = const { data, isLoading, isError, error } =
useProjectAssignedOrganizationsName(project); useProjectAssignedOrganizationsName(project);
const { control, watch, setValue, formState: { errors } } = useForm({
defaultValues: { organizationId: "" },
});
useEffect(() => {
if (data?.length === 1) {
setValue("organizationId", data[0].id, {
shouldValidate: true,
shouldDirty: true,
});
}
}, [data, setValue]);
return ( return (
<div className="container"> <div className="container">
<p className="fs-5 fs-seminbod ">Assign Employee To Project </p> {/* <p className="fs-5 fs-seminbod ">Assign Employee To Project </p> */}
<h5 className="mb-4">Assign Employee To Project</h5>
<div className="row align-items-center gx-5"> <div className="row align-items-center gx-5 text-start">
<div className="col"> <div className="col-12 col-md-6 mb-2">
<div className="d-flex flex-grow-1 align-items-center gap-2"> <AppFormController
{isLoading ? ( name="organizationId"
<select className="form-select form-select-sm w-100" disabled> control={control}
<option value="">Loading...</option> rules={{ required: "Organization is required" }}
</select> render={({ field }) => (
) : data?.length === 0 ? ( <SelectField
<p className="mb-0 badge bg-label-secondary">No organizations found</p> label="Select Organization"
) : ( options={data ?? []}
<> placeholder="Choose an Organization"
<label required
htmlFor="organization" labelKey="name"
className="form-label mb-0 text-nowrap" valueKey="id"
> value={field.value}
Select Organization onChange={field.onChange}
</label> isLoading={isLoading}
<select className="m-0 w-100"
id="organization" />
className="form-select form-select-sm w-100"
value={selectedOrg || ""}
onChange={(e) => setSelectedOrg(e.target.value)}
>
<option value="">Select</option>
{data.map((org) => (
<option key={org.id} value={org.id}>
{org.name}
</option>
))}
</select>
</>
)} )}
</div> />
{errors.organizationId && (
<small className="danger-text">{errors.organizationId.message}</small>
)}
</div> </div>
<div className="col"> <div className="col-12 col-md-6 mt-n2">
<div className="d-flex flex-grow-1 align-items-center gap-2"> <div className="d-flex flex-column">
<label htmlFor="search" className="form-label mb-0 text-nowrap"> <label htmlFor="search" className="form-label mb-1">
Search Employee Search Employee
</label> </label>
<input <input
id="search" id="search"
type="search" type="search"
className="form-control form-control-sm w-100" className="form-control w-100"
placeholder="Search..." placeholder="Search..."
value={searchText} value={searchText}
onChange={(e) => setSearchText(e.target.value)} onChange={(e) => setSearchText(e.target.value)}

View File

@ -10,11 +10,13 @@ import {
import useMaster, { useServices } from "../../../hooks/masterHook/useMaster"; import useMaster, { useServices } from "../../../hooks/masterHook/useMaster";
import showToast from "../../../services/toastService"; import showToast from "../../../services/toastService";
import { useOrganizationEmployees } from "../../../hooks/useOrganization"; import { useOrganizationEmployees } from "../../../hooks/useOrganization";
import { useDispatch } from "react-redux";
import { changeMaster } from "../../../slices/localVariablesSlice";
const TeamEmployeeList = ({ organizationId, searchTerm, closeModal }) => { const TeamEmployeeList = ({ organizationId, searchTerm, closeModal }) => {
const selectedProject = useSelectedProject(); const selectedProject = useSelectedProject();
const debounceSearchTerm = useDebounce(searchTerm, 500); const debounceSearchTerm = useDebounce(searchTerm, 500);
const dispatch = useDispatch();
const { const {
data: employeesData = [], data: employeesData = [],
isLoading, isLoading,
@ -45,6 +47,7 @@ const TeamEmployeeList = ({ organizationId, searchTerm, closeModal }) => {
}); });
useEffect(() => { useEffect(() => {
dispatch(changeMaster("Job Role"));
if (employeesData?.data?.length > 0) { if (employeesData?.data?.length > 0) {
const available = employeesData.data.filter((emp) => { const available = employeesData.data.filter((emp) => {
const projEmp = projectEmployees.find((pe) => pe.employeeId === emp.id); const projEmp = projectEmployees.find((pe) => pe.employeeId === emp.id);
@ -119,7 +122,7 @@ const TeamEmployeeList = ({ organizationId, searchTerm, closeModal }) => {
status: true, status: true,
})); }));
handleAssignEmployee({ payload,actionType:"assign"} ); handleAssignEmployee({ payload, actionType: "assign" });
setEmployees((prev) => setEmployees((prev) =>
prev.map((emp) => ({ prev.map((emp) => ({
@ -132,42 +135,50 @@ const TeamEmployeeList = ({ organizationId, searchTerm, closeModal }) => {
); );
}; };
if (isLoading) { if (isLoading) {
return ( <div className="page-min-h d-flex justify-content-center align-items-center "><p className="text-muted">Loading employees...</p></div>) ; return (<div className="page-min-h d-flex justify-content-center align-items-center "><p className="text-muted">Loading employees...</p></div>);
} }
if (isError) { if (isError) {
return ( return (
<div className="page-min-h d-flex justify-content-center align-items-center "> <div className="page-min-h d-flex justify-content-center align-items-center ">
{error?.status === 400 ? ( {error?.status === 400 ? (
<p className="m-0">Enter employee you want to find.</p> <p className="m-0">Enter employee you want to find.</p>
) : ( ) : (
<p className="m-0 dange-text">Something went wrong. Please try again later.</p> <p className="m-0 dange-text">Something went wrong. Please try again later.</p>
)} )}
</div> </div>
); );
} }
if (employees.length === 0) { if (employees.length === 0) {
return(<div className="page-min-h d-flex justify-content-center align-items-center "><p className="text-muted">No available employees to assign.</p></div>) ; return (<div className="page-min-h d-flex justify-content-center align-items-center "><p className="text-muted">No available employees to assign.</p></div>);
} }
return ( return (
<div className=" position-relative"> <div className="position-relative mt-5">
<table className="table" style={{ maxHeight: "80px", overflowY: "auto" }}> <table className="table" style={{ maxHeight: "80px", overflowY: "auto" }}>
<thead className=" position-sticky top-0"> <thead className=" position-sticky top-0">
<tr> <tr>
<th>Select</th>
<th>Employee</th> <th>Employee</th>
<th>Service</th> <th>Service</th>
<th>Job Role</th> <th>Job Role</th>
<th>Select</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{employees.map((emp, index) => ( {employees.map((emp, index) => (
<tr key={emp.id}> <tr key={emp.id}>
<td>
<input
type="checkbox"
className="form-check-input"
checked={emp.isChecked}
onChange={() => handleCheckboxChange(index)}
/>
</td>
<td> <td>
<div className="d-flex align-items-center"> <div className="d-flex align-items-center">
<Avatar firstName={emp.firstName} lastName={emp.lastName} /> <Avatar firstName={emp.firstName} lastName={emp.lastName} />
@ -176,6 +187,7 @@ if (employees.length === 0) {
</span> </span>
</div> </div>
</td> </td>
<td> <td>
<select <select
value={emp.serviceId} value={emp.serviceId}
@ -183,9 +195,8 @@ if (employees.length === 0) {
onChange={(e) => onChange={(e) =>
handleSelectChange(index, "serviceId", e.target.value) handleSelectChange(index, "serviceId", e.target.value)
} }
className={`form-select form-select-sm w-auto border-none rounded-0 py-1 px-auto ${ className={`form-select form-select-sm w-auto border-none rounded-0 py-1 px-auto ${emp.errors.serviceId ? "is-invalid" : ""
emp.errors.serviceId ? "is-invalid" : "" }`}
}`}
> >
<option value="">Select Service</option> <option value="">Select Service</option>
{services?.map((s) => ( {services?.map((s) => (
@ -205,9 +216,8 @@ if (employees.length === 0) {
onChange={(e) => onChange={(e) =>
handleSelectChange(index, "jobRole", e.target.value) handleSelectChange(index, "jobRole", e.target.value)
} }
className={`form-select form-select-sm w-auto border-none rounded-0 py-1 px-auto ${ className={`form-select form-select-sm w-auto border-none rounded-0 py-1 px-auto ${emp.errors.jobRole ? "is-invalid" : ""
emp.errors.jobRole ? "is-invalid" : "" }`}
}`}
> >
<option value="">Select Job Role</option> <option value="">Select Job Role</option>
{jobRoles?.map((r) => ( {jobRoles?.map((r) => (
@ -220,27 +230,20 @@ if (employees.length === 0) {
<div className="danger-text">{emp.errors.jobRole}</div> <div className="danger-text">{emp.errors.jobRole}</div>
)} )}
</td> </td>
<td>
<input
type="checkbox"
className="form-check-input"
checked={emp.isChecked}
onChange={() => handleCheckboxChange(index)}
/>
</td>
</tr> </tr>
))} ))}
</tbody> </tbody>
</table> </table>
<div className="position-sticky bottom-0 bg-white d-flex justify-content-end gap-3 z-25 "> <div className="position-sticky bottom-0 bg-white d-flex justify-content-end gap-3 z-25 my-3">
<button <button
type="button" type="button"
className="btn btn-sm btn-label-secondary" className="btn btn-sm btn-label-secondary mt-2"
onClick={() => closeModal()} onClick={() => closeModal()}
> >
Cancel Cancel
</button> </button>
<button onClick={onSubmit} className="btn btn-primary"> <button onClick={onSubmit} className="btn btn-primary btn-sm mt-2">
{isPending ? "Please Wait..." : "Assign to Project"} {isPending ? "Please Wait..." : "Assign to Project"}
</button> </button>
</div> </div>

View File

@ -22,6 +22,9 @@ import { useSelectedProject } from "../../../slices/apiDataManager";
import GlobalModel from "../../common/GlobalModel"; import GlobalModel from "../../common/GlobalModel";
import TeamAssignToProject from "./TeamAssignToProject"; import TeamAssignToProject from "./TeamAssignToProject";
import { SpinnerLoader } from "../../common/Loader"; import { SpinnerLoader } from "../../common/Loader";
import { AppFormController } from "../../../hooks/appHooks/useAppForm";
import SelectField from "../../common/Forms/SelectField";
import { useForm } from "react-hook-form";
const Teams = () => { const Teams = () => {
const selectedProject = useSelectedProject(); const selectedProject = useSelectedProject();
@ -30,9 +33,15 @@ const Teams = () => {
const [employees, setEmployees] = useState([]); const [employees, setEmployees] = useState([]);
const [selectedEmployee, setSelectedEmployee] = useState(null); const [selectedEmployee, setSelectedEmployee] = useState(null);
const [deleteEmployee, setDeleteEmplyee] = useState(null); const [deleteEmployee, setDeleteEmplyee] = useState(null);
const [searchTerm, setSearchTerm] = useState(""); // State for search term
const [selectedService, setSelectedService] = useState(null);
const [activeEmployee, setActiveEmployee] = useState(false); const [activeEmployee, setActiveEmployee] = useState(false);
const { control, watch, setValue } = useForm({
defaultValues: {
selectedService: "",
searchTerm: "",
},
});
const selectedService = watch("selectedService");
const searchTerm = watch("searchTerm");
const { data: assignedServices, isLoading: servicesLoading } = const { data: assignedServices, isLoading: servicesLoading } =
useProjectAssignedServices(selectedProject); useProjectAssignedServices(selectedProject);
@ -95,26 +104,23 @@ const Teams = () => {
const filteredEmployees = useMemo(() => { const filteredEmployees = useMemo(() => {
if (!projectEmployees) return []; if (!projectEmployees) return [];
let filtered = projectEmployees; let filtered = projectEmployees;
if (activeEmployee) { if (activeEmployee) {
filtered = projectEmployees.filter((emp) => !emp.isActive); filtered = projectEmployees.filter((emp) => !emp.isActive);
} }
// Apply search filter if present
if (searchTerm?.trim()) { if (searchTerm?.trim()) {
const lower = searchTerm.toLowerCase(); const lower = searchTerm.toLowerCase();
filtered = filtered.filter((emp) => { filtered = filtered.filter((emp) => {
const fullName = `${emp.firstName ?? ""} ${emp.lastName ?? ""}`.toLowerCase(); const fullName = `${emp.firstName ?? ""} ${emp.lastName ?? ""}`.toLowerCase();
const jobRole = getJobRole(emp?.jobRoleId)?.toLowerCase(); return fullName.includes(lower) || (emp.jobRoleName ?? "").toLowerCase().includes(lower);
return fullName.includes(lower) || jobRole.includes(lower);
}); });
} }
return filtered; return filtered;
}, [projectEmployees, searchTerm, activeEmployee]); }, [projectEmployees, searchTerm, activeEmployee]);
const handleSearch = (e) => setSearchTerm(e.target.value);
const employeeHandler = useCallback( const employeeHandler = useCallback(
(msg) => { (msg) => {
if (filteredEmployees.some((emp) => emp.employeeId == msg.employeeId)) { if (filteredEmployees.some((emp) => emp.employeeId == msg.employeeId)) {
@ -124,11 +130,24 @@ const Teams = () => {
[filteredEmployees, refetch] [filteredEmployees, refetch]
); );
useEffect(() => { useEffect(() => {
eventBus.on("employee", employeeHandler); eventBus.on("employee", employeeHandler);
return () => eventBus.off("employee", employeeHandler); return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]); }, [employeeHandler]);
useEffect(() => {
if (!servicesLoading && assignedServices?.length === 1) {
const serviceId = assignedServices[0].id;
setValue("selectedService", serviceId, {
shouldDirty: true,
shouldValidate: true,
});
}
}, [assignedServices, servicesLoading, setValue]);
return ( return (
<> <>
{AssigTeam && ( {AssigTeam && (
@ -154,62 +173,61 @@ const Teams = () => {
<div className="card card-action mb-6"> <div className="card card-action mb-6">
<div className="card-body"> <div className="card-body">
<div className="row align-items-center justify-content-between mb-4 g-3"> <div className="row align-items-center justify-content-between mb-4 g-3">
<div className="col-md-6 col-12 algin-items-center"> <div className="col-md-6 col-12 d-flex flex-wrap align-items-center gap-3">
<div className="d-flex flex-wrap align-items-center gap-3"> {!servicesLoading && assignedServices?.length > 0 && (
<div> <div className="col-12 col-md-6 mb-2 text-start">
{!servicesLoading && ( <AppFormController
<> name="selectedService"
{assignedServices?.length === 1 && ( control={control}
<h5 className="mb-2">{assignedServices[0].name}</h5> render={({ field }) => (
)} <SelectField
label="Select Service"
{assignedServices?.length > 1 && ( options={[ ...assignedServices]}
<select placeholder="Choose a Service"
className="form-select form-select-sm" labelKey="name"
aria-label="Select Service" valueKey="id"
value={selectedService} value={field.value}
onChange={handleServiceChange} onChange={field.onChange}
> isLoading={servicesLoading}
<option value="">All Services</option> className="w-100"
{assignedServices.map((service) => ( />
<option key={service.id} value={service.id}> )}
{service.name}
</option>
))}
</select>
)}
</>
)}
</div>
<div className="form-check form-switch d-flex align-items-center text-nowrap">
<input
type="checkbox"
className="form-check-input"
id="activeEmployeeSwitch"
checked={activeEmployee}
onChange={handleToggleActive}
/> />
<label
className="form-check-label ms-2"
htmlFor="activeEmployeeSwitch"
>
{activeEmployee ? "Active Employees" : "In-active Employees"}
</label>
</div> </div>
)}
<div className="form-check form-switch d-flex align-items-center text-nowrap">
<input
type="checkbox"
className="form-check-input"
id="activeEmployeeSwitch"
checked={activeEmployee}
onChange={handleToggleActive}
/>
<label className="form-check-label ms-2" htmlFor="activeEmployeeSwitch">
{activeEmployee ? "Active Employees" : "In-active Employees"}
</label>
</div> </div>
</div> </div>
<div className="col-md-6 col-12 d-flex justify-content-md-end align-items-center justify-content-start gap-3"> <div className="col-md-6 col-12 d-flex justify-content-md-end align-items-center justify-content-start gap-3 mt-n1">
<input <div className="col-12 col-md-4">
type="search" <AppFormController
className="form-control form-control-sm" name="searchTerm"
placeholder="Search by Name or Role" control={control}
aria-controls="DataTables_Table_0" render={({ field }) => (
style={{ maxWidth: "200px" }} <input
value={searchTerm} type="search"
onChange={handleSearch} className="form-control form-control-sm w-100"
/> placeholder="Search by Name or Role"
value={field.value}
onChange={field.onChange}
/>
)}
/>
</div>
{HasAssignUserPermission && ( {HasAssignUserPermission && (
<button <button
@ -246,74 +264,73 @@ const Teams = () => {
</tr> </tr>
</thead> </thead>
<tbody className="table-border-bottom-0"> <tbody className="table-border-bottom-0">
{filteredEmployees && {filteredEmployees
filteredEmployees .sort((a, b) =>
.sort((a, b) => (a.firstName || "").localeCompare(b.firstName || "")
(a.firstName || "").localeCompare(b.firstName || "") )
) .map((emp) => (
.map((emp) => ( <tr key={emp.id}>
<tr key={emp.id}> <td>
<td> <div className="d-flex justify-content-start align-items-center">
<div className="d-flex justify-content-start align-items-center"> <Avatar
<Avatar firstName={emp.firstName}
firstName={emp.firstName} lastName={emp.lastName}
lastName={emp.lastName} />
/> <div className="d-flex flex-column">
<div className="d-flex flex-column"> <a
<a onClick={() =>
onClick={() => navigate(
navigate( `/employee/${emp.employeeId}?for=attendance`
`/employee/${emp.employeeId}?for=attendance` )
) }
} className="text-heading text-truncate cursor-pointer"
className="text-heading text-truncate cursor-pointer"
>
<span className="fw-normal">
{emp.firstName}{" "}
{emp.lastName}
</span>
</a>
</div>
</div>
</td>
<td>{emp.serviceName || "N/A"}</td>
<td>{emp.organizationName || "N/A"}</td>
<td>
{moment(emp.allocationDate).format("DD-MMM-YYYY")}
</td>
{activeEmployee && (
<td>
{emp.reAllocationDate
? moment(emp.reAllocationDate).format(
"DD-MMM-YYYY"
)
: "Present"}
</td>
)}
<td>
<span className="badge bg-label-primary me-1">
{getJobRole(emp.jobRoleId)}
</span>
</td>
<td>
{emp.isActive ? (
<button
aria-label="Delete"
type="button"
title="Remove from project"
className="btn p-0 dropdown-toggle hide-arrow"
onClick={() => setSelectedEmployee(emp)}
> >
<i className="bx bx-trash me-1 text-danger"></i> <span className="fw-normal">
</button> {emp.firstName}{" "}
) : ( {emp.lastName}
<span>Not in project</span> </span>
)} </a>
</div>
</div>
</td>
<td>{emp.serviceName || "N/A"}</td>
<td>{emp.organizationName || "N/A"}</td>
<td>
{moment(emp.allocationDate).format("DD-MMM-YYYY")}
</td>
{activeEmployee && (
<td>
{emp.reAllocationDate
? moment(emp.reAllocationDate).format(
"DD-MMM-YYYY"
)
: "Present"}
</td> </td>
</tr> )}
))} <td>
<span className="badge bg-label-primary me-1">
{getJobRole(emp.jobRoleId)}
</span>
</td>
<td>
{emp.isActive ? (
<button
aria-label="Delete"
type="button"
title="Remove from project"
className="btn p-0 dropdown-toggle hide-arrow"
onClick={() => setSelectedEmployee(emp)}
>
<i className="bx bx-trash me-1 text-danger"></i>
</button>
) : (
<span>Not in project</span>
)}
</td>
</tr>
))}
</tbody> </tbody>
</table> </table>
)} )}

View File

@ -28,6 +28,8 @@ import { useEmployeesName } from "../../hooks/useEmployees";
import PmsEmployeeInputTag from "../common/PmsEmployeeInputTag"; import PmsEmployeeInputTag from "../common/PmsEmployeeInputTag";
import HoverPopup from "../common/HoverPopup"; import HoverPopup from "../common/HoverPopup";
import { SelectProjectField } from "../common/Forms/SelectFieldServerSide"; import { SelectProjectField } from "../common/Forms/SelectFieldServerSide";
import { AppFormController } from "../../hooks/appHooks/useAppForm";
import SelectField from "../common/Forms/SelectField";
const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => { const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
const { const {
@ -200,30 +202,32 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
<Label htmlFor="expenseCategoryId" className="form-label" required> <Label htmlFor="expenseCategoryId" className="form-label" required>
Expense Category Expense Category
</Label> </Label>
<select
className="form-select" <AppFormController
id="expenseCategoryId" name="expenseCategoryId"
{...register("expenseCategoryId")} control={control}
> rules={{ required: "Expense Category is required" }}
<option value="" disabled> render={({ field }) => (
Select Category <SelectField
</option> label="" // Label is already above
{ExpenseLoading ? ( placeholder="Select Category"
<option disabled>Loading...</option> options={expenseCategories ?? []}
) : ( value={field.value || ""}
expenseCategories?.map((expense) => ( onChange={field.onChange}
<option key={expense.id} value={expense.id}> required
{expense.name} isLoading={ExpenseLoading}
</option> className="m-0 form-select-sm w-100"
)) />
)} )}
</select> />
{errors.expenseCategoryId && ( {errors.expenseCategoryId && (
<small className="danger-text"> <small className="danger-text">
{errors.expenseCategoryId.message} {errors.expenseCategoryId.message}
</small> </small>
)} )}
</div> </div>
</div> </div>
{/* Title and Is Variable */} {/* Title and Is Variable */}
@ -375,34 +379,45 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
<Label htmlFor="currencyId" className="form-label" required> <Label htmlFor="currencyId" className="form-label" required>
Currency Currency
</Label> </Label>
<select
id="currencyId"
className="form-select"
{...register("currencyId")}
>
<option value="">Select Currency</option>
{currencyLoading && <option>Loading...</option>} <AppFormController
name="currencyId"
control={control}
rules={{ required: "Currency is required" }}
render={({ field }) => (
<SelectField
label="" // Label already shown above
placeholder="Select Currency"
options={currencyData?.map((currency) => ({
id: currency.id,
name: `${currency.currencyName} (${currency.symbol})`,
})) ?? []}
value={field.value || ""}
onChange={field.onChange}
required
isLoading={currencyLoading}
noOptionsMessage={() =>
!currencyLoading && !currencyError && (!currencyData || currencyData.length === 0)
? "No currency found"
: null
}
className="m-0 form-select-sm w-100"
/>
)}
/>
{!currencyLoading &&
!currencyError &&
currencyData?.map((currency) => (
<option key={currency.id} value={currency.id}>
{`${currency.currencyName} (${currency.symbol})`}
</option>
))}
</select>
{errors.currencyId && ( {errors.currencyId && (
<small className="danger-text">{errors.currencyId.message}</small> <small className="danger-text">{errors.currencyId.message}</small>
)} )}
</div> </div>
</div> </div>
{/* Frequency To and Status Id */} {/* Frequency To and Status Id */}
<div className="row my-2 text-start mt-n2"> <div className="row my-2 text-start mt-n2">
<div className="col-md-6"> <div className="col-md-6">
<div className="d-flex justify-content-start align-items-center gap-2"> <div className="d-flex justify-content-start align-items-center gap-2">
<Label htmlFor="frequency" className="form-label mb-0" required> <Label htmlFor="frequency" className="form-label mb-1" required>
Frequency Frequency
</Label> </Label>
<HoverPopup <HoverPopup
@ -415,51 +430,69 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
</p> </p>
} }
> >
<i className="bx bx-info-circle bx-xs text-muted cursor-pointer"></i> <i className="bx bx-info-circle bx-xs text-muted cursor-pointer mb-1"></i>
</HoverPopup> </HoverPopup>
</div> </div>
<select <AppFormController
id="frequency" name="frequency"
className="form-select mt-1" control={control}
{...register("frequency", { valueAsNumber: true })} rules={{ required: "Frequency is required" }}
> render={({ field }) => (
<option value="">Select Frequency</option> <SelectField
{Object.entries(FREQUENCY_FOR_RECURRING).map(([key, label]) => ( label="" // Label shown above
<option key={key} value={key}> placeholder="Select Frequency"
{label} options={Object.entries(FREQUENCY_FOR_RECURRING).map(([key, label]) => ({
</option> id: key,
))} name: label,
</select> }))}
value={field.value || ""}
onChange={field.onChange}
required
className="m-0 mt-1"
/>
)}
/>
{errors.frequency && ( {errors.frequency && (
<small className="danger-text">{errors.frequency.message}</small> <small className="danger-text">{errors.frequency.message}</small>
)} )}
</div> </div>
<div className="col-md-6"> <div className="col-md-6">
<Label htmlFor="statusId" className="form-label" required> <Label htmlFor="statusId" className="form-label" required>
Status Status
</Label> </Label>
<select
id="statusId" <AppFormController
className="form-select" name="statusId"
{...register("statusId")} control={control}
> rules={{ required: "Status is required" }}
<option value="">Select Status</option> render={({ field }) => (
{statusLoading && <option>Loading...</option>} <SelectField
{!statusLoading && label="" // Label already shown above
!statusError && placeholder="Select Status"
statusData?.map((status) => ( options={statusData ?? []}
<option key={status.id} value={status.id}> value={field.value || ""}
{status.name} onChange={field.onChange}
</option> required
))} isLoading={statusLoading}
</select> noOptionsMessage={() =>
!statusLoading && !statusError && (!statusData || statusData.length === 0)
? "No status found"
: null
}
className="m-0 form-select-sm w-100"
/>
)}
/>
{errors.statusId && ( {errors.statusId && (
<small className="danger-text">{errors.statusId.message}</small> <small className="danger-text">{errors.statusId.message}</small>
)} )}
</div> </div>
</div> </div>
{/* Payment Buffer Days and End Date */} {/* Payment Buffer Days and End Date */}
@ -564,7 +597,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
</div> </div>
{/* Description */} {/* Description */}
<div className="row my-2 text-start"> <div className="row my-4 text-start">
<div className="col-md-12"> <div className="col-md-12">
<Label htmlFor="description" className="form-label" required> <Label htmlFor="description" className="form-label" required>
Description Description

View File

@ -1,4 +1,4 @@
import React, { useState } from "react"; import React, { useEffect, useMemo, useState } from "react";
import { import {
EXPENSE_DRAFT, EXPENSE_DRAFT,
EXPENSE_REJECTEDBY, EXPENSE_REJECTEDBY,
@ -18,7 +18,7 @@ import { useRecurringExpenseList } from "../../hooks/useExpense";
import Pagination from "../common/Pagination"; import Pagination from "../common/Pagination";
import { SpinnerLoader } from "../common/Loader"; import { SpinnerLoader } from "../common/Loader";
const RecurringExpenseList = ({ search, filterStatuses }) => { const RecurringExpenseList = ({ search, filterStatuses, tableRef, onDataFiltered }) => {
const { setManageRequest, setVieRequest, setViewRecurring } = const { setManageRequest, setVieRequest, setViewRecurring } =
useRecurringExpenseContext(); useRecurringExpenseContext();
const navigate = useNavigate(); const navigate = useNavigate();
@ -70,9 +70,8 @@ const RecurringExpenseList = ({ search, filterStatuses }) => {
align: "text-end", align: "text-end",
getValue: (e) => getValue: (e) =>
e?.amount e?.amount
? `${ ? `${e?.currency?.symbol ? e.currency.symbol + " " : ""
e?.currency?.symbol ? e.currency.symbol + " " : "" }${e.amount.toLocaleString()}`
}${e.amount.toLocaleString()}`
: "N/A", : "N/A",
}, },
{ {
@ -112,6 +111,17 @@ const RecurringExpenseList = ({ search, filterStatuses }) => {
debouncedSearch debouncedSearch
); );
const filteredData = useMemo(
() =>
data?.data?.filter((item) => filterStatuses.includes(item?.status?.id)) ||
[],
[data?.data, filterStatuses]
);
useEffect(() => {
onDataFiltered(filteredData);
}, [filteredData, onDataFiltered]);
const paginate = (page) => { const paginate = (page) => {
if (page >= 1 && page <= (data?.totalPages ?? 1)) { if (page >= 1 && page <= (data?.totalPages ?? 1)) {
setCurrentPage(page); setCurrentPage(page);
@ -150,10 +160,6 @@ const RecurringExpenseList = ({ search, filterStatuses }) => {
); );
}; };
const filteredData = data?.data?.filter((item) =>
filterStatuses.includes(item?.status?.id)
);
const handleDelete = (id) => { const handleDelete = (id) => {
setDeletingId(id); setDeletingId(id);
DeleteExpense( DeleteExpense(
@ -180,111 +186,111 @@ const RecurringExpenseList = ({ search, filterStatuses }) => {
/> />
)} )}
<div className="card page-min-h table-responsive px-sm-4"> <div className="card page-min-h table-responsive px-sm-4" ref={tableRef}>
<div className="card-datatable" id="payment-request-table"> <div className="card-datatable" id="payment-request-table">
<div className="mx-2"> <div className="mx-2">
{Array.isArray(filteredData) && filteredData.length > 0 && ( {Array.isArray(filteredData) && filteredData.length > 0 && (
<table className="table border-top dataTable text-nowrap align-middle"> <table className="table border-top dataTable text-nowrap align-middle">
<thead> <thead>
<tr>
{recurringExpenseColumns.map((col) => (
<th key={col.key} className={`sorting ${col.align}`}>
{col.label}
</th>
))}
<th className="text-center">Action</th>
</tr>
</thead>
<tbody>
{filteredData?.length > 0 ? (
filteredData?.map((recurringExpense) => (
<tr
key={recurringExpense.id}
className="align-middle"
style={{ height: "40px" }}
>
{recurringExpenseColumns.map((col) => (
<td
key={col.key}
className={`d-table-cell ${col.align ?? ""} py-3`}
>
{col?.customRender
? col?.customRender(recurringExpense)
: col?.getValue(recurringExpense)}
</td>
))}
<td className="sticky-action-column bg-white">
<div className="d-flex flex-row gap-2 gap-0">
<i
className="bx bx-show text-primary cursor-pointer"
onClick={() =>
setViewRecurring({
recurringId: recurringExpense?.id,
view: true,
})
}
></i>
<div className="dropdown z-2">
<button
type="button"
className="btn btn-xs btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow p-0 m-0"
data-bs-toggle="dropdown"
>
<i className="bx bx-dots-vertical-rounded text-muted p-0"></i>
</button>
<ul className="dropdown-menu dropdown-menu-end w-auto">
<li
onClick={() =>
setManageRequest({
IsOpen: true,
RecurringId: recurringExpense?.id,
})
}
>
<a className="dropdown-item px-2 cursor-pointer py-1">
<i className="bx bx-edit text-primary bx-xs me-2"></i>
Modify
</a>
</li>
<li
onClick={() => {
setIsDeleteModalOpen(true);
setDeletingId(recurringExpense.id);
}}
>
<a className="dropdown-item px-2 cursor-pointer py-1">
<i className="bx bx-trash text-danger bx-xs me-2"></i>
Delete
</a>
</li>
</ul>
</div>
</div>
</td>
</tr>
))
) : (
<tr> <tr>
<td {recurringExpenseColumns.map((col) => (
colSpan={recurringExpenseColumns?.length + 1} <th key={col.key} className={`sorting ${col.align}`}>
className="text-center border-0 py-8" {col.label}
></td> </th>
))}
<th className="text-end">Action</th>
</tr> </tr>
)} </thead>
</tbody>
</table> <tbody>
)} {filteredData?.length > 0 ? (
{!filteredData || filteredData?.map((recurringExpense) => (
filteredData.length === 0 <tr
&& ( key={recurringExpense.id}
<div className="d-flex justify-content-center align-items-center h-64"> className="align-middle"
{isError ? (<p>{error.message}</p>):(<p>No Recurring Expense Found</p>)} style={{ height: "40px" }}
</div> >
{recurringExpenseColumns.map((col) => (
<td
key={col.key}
className={`d-table-cell ${col.align ?? ""} py-3`}
>
{col?.customRender
? col?.customRender(recurringExpense)
: col?.getValue(recurringExpense)}
</td>
))}
<td className="sticky-action-column bg-white text-end">
<div className="d-flex justify-content-end flex-row gap-2 gap-0">
<i
className="bx bx-show text-primary cursor-pointer"
onClick={() =>
setViewRecurring({
recurringId: recurringExpense?.id,
view: true,
})
}
></i>
<div className="dropdown z-2">
<button
type="button"
className="btn btn-xs btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow p-0 m-0"
data-bs-toggle="dropdown"
>
<i className="bx bx-dots-vertical-rounded text-muted p-0"></i>
</button>
<ul className="dropdown-menu dropdown-menu-end w-auto">
<li
onClick={() =>
setManageRequest({
IsOpen: true,
RecurringId: recurringExpense?.id,
})
}
>
<a className="dropdown-item px-2 cursor-pointer py-1">
<i className="bx bx-edit text-primary bx-xs me-2"></i>
Modify
</a>
</li>
<li
onClick={() => {
setIsDeleteModalOpen(true);
setDeletingId(recurringExpense.id);
}}
>
<a className="dropdown-item px-2 cursor-pointer py-1">
<i className="bx bx-trash text-danger bx-xs me-2"></i>
Delete
</a>
</li>
</ul>
</div>
</div>
</td>
</tr>
))
) : (
<tr>
<td
colSpan={recurringExpenseColumns?.length + 1}
className="text-center border-0 py-8"
></td>
</tr>
)}
</tbody>
</table>
)} )}
</div> {!filteredData ||
filteredData.length === 0
&& (
<div className="d-flex justify-content-center align-items-center h-64">
{isError ? (<p>{error.message}</p>) : (<p>No Recurring Expense Found</p>)}
</div>
)}
</div>
</div> </div>
{/* Pagination */} {/* Pagination */}

View File

@ -0,0 +1,107 @@
import moment from "moment";
import {
exportToCSV,
exportToExcel,
exportToPDF,
printTable,
} from "../../utils/tableExportUtils";
import { FREQUENCY_FOR_RECURRING } from "../../utils/constants";
import ExpenseRepository from "../../repositories/ExpsenseRepository";
const HandleRecurringExpenseExport = async (
type,
filters = {},
searchString = "",
tableRef = null,
setLoading = null
) => {
try {
if (setLoading) setLoading(true);
const safeSearchString =
typeof searchString === "string" ? searchString : "";
let allRecurringExpense = [];
let pageNumber = 1;
const pageSize = 1000;
let hasMore = true;
while (hasMore) {
const response = await ExpenseRepository.GetRecurringExpenseList(
pageSize,
pageNumber,
filters,
true, // isActive
safeSearchString
);
const currentPageData = response?.data?.data || [];
allRecurringExpense = allRecurringExpense.concat(currentPageData);
if (currentPageData.length < pageSize) {
hasMore = false;
} else {
pageNumber += 1;
}
}
if (!allRecurringExpense.length) {
console.warn("No payment requests found!");
return;
}
const exportData = allRecurringExpense.map((item) => ({
Category: item?.expenseCategory?.name ?? "-",
Title: item?.title ?? "-",
Payee: item?.payee ?? "-",
Frequency:
item?.frequency !== undefined && item?.frequency !== null
? FREQUENCY_FOR_RECURRING[item?.frequency] ?? "-"
: "-",
Amount: item?.amount ? item.amount.toLocaleString() : "-",
Currency: item?.currency?.symbol ?? "-",
"Next Generation Date": item?.nextGenerationDate
? moment(item.nextGenerationDate).format("DD-MMM-YYYY")
: "-",
Status: item?.status?.name ?? "-",
"Created At": item?.createdAt
? moment(item.createdAt).format("DD-MMM-YYYY")
: "-",
}));
// COLUMN ORDER
const columns = [
"Category",
"Title",
"Payee",
"Frequency",
"Amount",
"Currency",
"Next Generation Date",
"Status",
"Created At",
];
switch (type) {
case "csv":
exportToCSV(exportData, "recurring-expense", columns);
break;
case "excel":
exportToExcel(exportData, "recurring-expense", columns);
break;
case "pdf":
exportToPDF(exportData, "recurring-expense", columns);
break;
case "print":
if (tableRef?.current) printTable(tableRef.current);
break;
default:
console.warn("Unknown export type:", type);
}
} catch (err) {
console.error("Export failed:", err);
} finally {
if (setLoading) setLoading(false);
}
};
export default HandleRecurringExpenseExport;

View File

@ -175,12 +175,9 @@ const JobList = ({ isArchive }) => {
<td <td
key={col.key} key={col.key}
className={col.className} className={col.className}
// onClick={() =>
// setSelectedJob({ showCanvas: true, job: row?.id })
// }
onClick={() => { onClick={() => {
if (!isArchive) { if (!isArchive) {
setSelectedJob({ showCanvas: true, job: e?.id }); setSelectedJob({ showCanvas: true, job: row?.id });
} }
}} }}

View File

@ -23,6 +23,8 @@ import {
useServiceProject, useServiceProject,
useUpdateServiceProject, useUpdateServiceProject,
} from "../../hooks/useServiceProject"; } from "../../hooks/useServiceProject";
import { AppFormController } from "../../hooks/appHooks/useAppForm";
import SelectField from "../common/Forms/SelectField";
const ManageServiceProject = ({ serviceProjectId, onClose }) => { const ManageServiceProject = ({ serviceProjectId, onClose }) => {
const { const {
@ -117,51 +119,54 @@ const ManageServiceProject = ({ serviceProjectId, onClose }) => {
</div> </div>
<div className="row text-start"> <div className="row text-start">
<div className="col-12 mb-2"> <div className="col-12 mb-2">
<Label htmlFor="name" required> <Label htmlFor="clientId" required>
Client Client
</Label> </Label>
<div className="d-flex align-items-center gap-2">
<select <div className="d-flex align-items-center gap-2 w-100">
className="select2 form-select form-select-sm flex-grow-1" <div className="flex-grow-1" style={{ minWidth: "250px" }}>
aria-label="Default select example" <AppFormController
{...register("clientId", { name="clientId"
required: "Client is required", control={control}
valueAsNumber: false, rules={{ required: "Client is required" }}
})} render={({ field }) => (
> <SelectField
{isLoading ? ( label=""
<option>Loading...</option> options={organization?.data ?? []}
) : ( placeholder="Select Client"
<> required
<option value="">Select Client</option> labelKey="name"
{organization?.data?.map((org) => ( valueKeyKey="id"
<option key={org.id} value={org.id}> value={field.value}
{org.name} onChange={field.onChange}
</option> isLoading={isLoading}
))} className="m-0 w-100"
</> />
)} )}
</select> />
</div>
<i <i
className="bx bx-plus-circle bx-xs cursor-pointer text-primary" className="bx bx-plus-circle bx-xs cursor-pointer text-primary "
onClick={() => { onClick={() => {
onClose(); onClose();
openOrgModal({ startStep: 2 }); // Step 4 = ManagOrg openOrgModal({ startStep: 2 });
}} }}
/> />
</div> </div>
{errors?.clientId && ( {errors?.clientId && (
<span className="danger-text">{errors.clientId.message}</span> <small className="danger-text">{errors.clientId.message}</small>
)} )}
</div> </div>
<div className="col-12 mb-2"> <div className="col-12 mb-4">
<Label htmlFor="name" required> <Label htmlFor="name" required>
Project Name Project Name
</Label> </Label>
<input <input
type="text" type="text"
className="form-control form-control-sm" className="form-control "
{...register("name")} {...register("name")}
placeholder="Enter Project Name.." placeholder="Enter Project Name.."
/> />
@ -175,7 +180,7 @@ const ManageServiceProject = ({ serviceProjectId, onClose }) => {
</Label> </Label>
<input <input
type="text" type="text"
className="form-control form-control-sm" className="form-control "
{...register("shortName")} {...register("shortName")}
placeholder="Enter Project Short Name.." placeholder="Enter Project Short Name.."
/> />
@ -183,24 +188,38 @@ const ManageServiceProject = ({ serviceProjectId, onClose }) => {
<span className="danger-text">{errors.shortName.message}</span> <span className="danger-text">{errors.shortName.message}</span>
)} )}
</div> </div>
<div className="col-12 col-md-6 mb-2"> <div className="col-12 col-md-6">
<Label htmlFor="name" required> <Label htmlFor="statusId" required>
Select Status Select Status
</Label> </Label>
<select
className="form-select form-select-sm" <AppFormController
{...register("statusId")} name="statusId"
> control={control}
<option>Select Service</option> render={({ field }) => (
{PROJECT_STATUS?.map((status) => ( <SelectField
<option key={status.id} value={status.id}>{status.label}</option> label="" // label already above
))} options={PROJECT_STATUS?.map((status) => ({
</select> id: status.id,
name: status.label,
}))}
placeholder="Select Status"
required
labelKey="name"
valueKey="id"
value={field.value}
onChange={field.onChange}
className="form-select w-100"
/>
)}
/>
{errors?.statusId && ( {errors?.statusId && (
<span className="danger-text">{errors.statusId.message}</span> <span className="danger-text">{errors.statusId.message}</span>
)} )}
</div> </div>
<div className="col-12 mb-2">
<div className="col-12 mb-4">
<SelectMultiple <SelectMultiple
options={data?.data} options={data?.data}
isLoading={isLoading} isLoading={isLoading}
@ -214,15 +233,15 @@ const ManageServiceProject = ({ serviceProjectId, onClose }) => {
)} )}
</div> </div>
<div className="col-12 col-md-6 mb-2"> <div className="col-12 col-md-6 mb-4">
<Label htmlFor="name" required> <Label htmlFor="name" required>
Contact Person Contact Person
</Label> </Label>
<input <input
type="text" type="text"
className="form-control form-control-sm" className="form-control "
{...register("contactName")} {...register("contactName")}
placeholder="Enter Employee name.." placeholder="Enter Employee name.."
/> />
{errors?.contactName && ( {errors?.contactName && (
<span className="danger-text">{errors.contactName.message}</span> <span className="danger-text">{errors.contactName.message}</span>
@ -234,7 +253,7 @@ const ManageServiceProject = ({ serviceProjectId, onClose }) => {
</Label> </Label>
<input <input
type="text" type="text"
className="form-control form-control-sm" className="form-control "
{...register("contactEmail")} {...register("contactEmail")}
placeholder="Enter Employee Email.." placeholder="Enter Employee Email.."
/> />
@ -242,14 +261,14 @@ const ManageServiceProject = ({ serviceProjectId, onClose }) => {
<span className="danger-text">{errors.contactEmail.message}</span> <span className="danger-text">{errors.contactEmail.message}</span>
)} )}
</div> </div>
<div className="col-12 col-md-6 mb-2"> <div className="col-12 col-md-6 mb-4">
<Label htmlFor="name" required> <Label htmlFor="name" required>
Contact Number Contact Number
</Label> </Label>
<input <input
type="text" type="text"
maxLength={10} maxLength={10}
className="form-control form-control-sm" className="form-control "
{...register("contactPhone")} {...register("contactPhone")}
placeholder="Enter Employee Contact.." placeholder="Enter Employee Contact.."
onInput={(e) => { onInput={(e) => {
@ -268,6 +287,7 @@ const ManageServiceProject = ({ serviceProjectId, onClose }) => {
name="assignedDate" name="assignedDate"
className="w-100" className="w-100"
control={control} control={control}
size="md"
/> />
</div> </div>
<div className="col-12 col-md-12 mb-2"> <div className="col-12 col-md-12 mb-2">
@ -297,7 +317,7 @@ const ManageServiceProject = ({ serviceProjectId, onClose }) => {
)} )}
</div> </div>
</div> </div>
<div className="d-flex justify-content-end gap-4"> <div className="d-flex justify-content-end gap-2 mt-4">
<button <button
className="btn btn-sm btn-outline-secondary" className="btn btn-sm btn-outline-secondary"
disabled={isPending || isUpdating} disabled={isPending || isUpdating}

View File

@ -113,7 +113,7 @@ const ManageBranch = ({ closeModal, BranchToEdit = null }) => {
<input <input
type="text" type="text"
id="branchName" id="branchName"
className="form-control form-control-sm" className="form-control form-control-md"
{...register("branchName")} {...register("branchName")}
placeholder="Enter Branch" placeholder="Enter Branch"
/> />
@ -147,7 +147,7 @@ const ManageBranch = ({ closeModal, BranchToEdit = null }) => {
<input <input
type="text" type="text"
id="googleMapUrl" id="googleMapUrl"
className="form-control form-control-sm" className="form-control form-control-md"
{...register("googleMapUrl")} {...register("googleMapUrl")}
/> />
{errors.googleMapUrl && ( {errors.googleMapUrl && (
@ -183,7 +183,7 @@ const ManageBranch = ({ closeModal, BranchToEdit = null }) => {
<input <input
type="text" type="text"
placeholder="Contact Name" placeholder="Contact Name"
className="form-control form-control-sm" className="form-control form-control-md"
value={item.contactPerson} value={item.contactPerson}
onChange={(e) => { onChange={(e) => {
const list = [...contacts]; const list = [...contacts];
@ -198,7 +198,7 @@ const ManageBranch = ({ closeModal, BranchToEdit = null }) => {
<input <input
type="text" type="text"
placeholder="Designation" placeholder="Designation"
className="form-control form-control-sm" className="form-control form-control-md"
value={item.designation} value={item.designation}
onChange={(e) => { onChange={(e) => {
const list = [...contacts]; const list = [...contacts];
@ -220,7 +220,7 @@ const ManageBranch = ({ closeModal, BranchToEdit = null }) => {
<input <input
type="text" type="text"
placeholder="Number" placeholder="Number"
className="form-control form-control-sm" className="form-control form-control-md"
maxLength={10} maxLength={10}
value={num} value={num}
onChange={(e) => { onChange={(e) => {
@ -267,7 +267,7 @@ const ManageBranch = ({ closeModal, BranchToEdit = null }) => {
<input <input
type="email" type="email"
placeholder="Email" placeholder="Email"
className="form-control form-control-sm" className="form-control form-control-md"
value={email} value={email}
onChange={(e) => { onChange={(e) => {
const list = [...contacts]; const list = [...contacts];
@ -328,7 +328,7 @@ const ManageBranch = ({ closeModal, BranchToEdit = null }) => {
</Label> </Label>
<textarea <textarea
id="address" id="address"
className="form-control form-control-sm" className="form-control "
{...register("address")} {...register("address")}
/> />
{errors.address && ( {errors.address && (

View File

@ -8,6 +8,7 @@ import { useParams } from "react-router-dom";
import Pagination from "../../common/Pagination"; import Pagination from "../../common/Pagination";
import ConfirmModal from "../../common/ConfirmModal"; import ConfirmModal from "../../common/ConfirmModal";
import { SpinnerLoader } from "../../common/Loader"; import { SpinnerLoader } from "../../common/Loader";
import ViewBranchDetails from "./ViewBranchDetails";
const ServiceBranch = () => { const ServiceBranch = () => {
const { projectId } = useParams(); const { projectId } = useParams();
@ -19,6 +20,7 @@ const ServiceBranch = () => {
}); });
const { mutate: DeleteBranch, isPending } = useDeleteBranch(); const { mutate: DeleteBranch, isPending } = useDeleteBranch();
const [deletingId, setDeletingId] = useState(null); const [deletingId, setDeletingId] = useState(null);
const [ViewRequest, setViewRequest] = useState({ requestId: null, view: false });
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
@ -84,7 +86,7 @@ const ServiceBranch = () => {
<div className="col-md-4 col-sm-12 ms-n3 text-start "> <div className="col-md-4 col-sm-12 ms-n3 text-start ">
<h5 className="mb-0"> <h5 className="mb-0">
<i className="bx bx-buildings text-primary"></i> <i className="bx bx-buildings text-primary"></i>
<span className="ms-2 fw-bold">Branchs</span> <span className="ms-2 fw-bold">Branches</span>
</h5> </h5>
</div> </div>
@ -171,37 +173,78 @@ const ServiceBranch = () => {
!isError && !isError &&
data?.data?.length > 0 && data?.data?.length > 0 &&
data.data.map((branch) => ( data.data.map((branch) => (
<tr key={branch.id} style={{ height: "35px" }}> <tr
key={branch.id}
style={{ height: "35px", cursor: showInactive ? "default" : "pointer" }}
onClick={(e) => {
if (!showInactive && !e.target.closest(".dropdown") && !e.target.closest(".bx-show")) {
setViewRequest({ branchId: branch.id, view: true });
}
}}
>
{columns.map((col) => ( {columns.map((col) => (
<td key={col.key} className={`${col.align} py-3`}> <td key={col.key} className={`${col.align} py-3`}>
{col.getValue(branch)} {col.getValue(branch)}
</td> </td>
))} ))}
<td className="text-center"> <td className="text-center">
<div className="dropdown z-2"> <div className="d-flex justify-content-center align-items-center gap-2">
<button {/* View Icon */}
type="button" {/* <i
className="btn btn-xs btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow p-0 m-0" className="bx bx-show text-primary cursor-pointer"
data-bs-toggle="dropdown" onClick={() =>
> setViewRequest({ branchId: branch.id, view: true })
<i className="bx bx-dots-vertical-rounded text-muted p-0"></i> }
</button> ></i> */}
<ul className="dropdown-menu dropdown-menu-end w-auto">
{!showInactive ? ( <div className="dropdown z-2">
<> <button
<li type="button"
onClick={() => className="btn btn-xs btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow p-0 m-0"
setManageState({ data-bs-toggle="dropdown"
IsOpen: true, >
branchId: branch.id, <i className="bx bx-dots-vertical-rounded text-muted p-0"></i>
}) </button>
} <ul className="dropdown-menu dropdown-menu-end w-auto">
> {!showInactive ? (
<a className="dropdown-item px-2 cursor-pointer py-1"> <>
<i className="bx bx-edit text-primary bx-xs me-2"></i> <li
Modify onClick={() =>
</a> setManageState({
</li> IsOpen: true,
branchId: branch.id,
})
}
>
<a className="dropdown-item px-2 cursor-pointer py-1">
<i className="bx bx-edit text-primary bx-xs me-2"></i>
Modify
</a>
</li>
<li
onClick={() => {
setIsDeleteModalOpen(true);
setDeletingId(branch.id);
}}
>
<a className="dropdown-item px-2 cursor-pointer py-1">
<i className="bx bx-trash text-danger bx-xs me-2"></i>
Delete
</a>
</li>
<li
onClick={() =>
setViewRequest({ branchId: branch.id, view: true })
}
>
<a className="dropdown-item px-2 cursor-pointer py-1">
<i className="bx bx-show text-primary cursor-pointer me-2"></i>
View
</a>
</li>
</>
) : (
<li <li
onClick={() => { onClick={() => {
setIsDeleteModalOpen(true); setIsDeleteModalOpen(true);
@ -209,25 +252,13 @@ const ServiceBranch = () => {
}} }}
> >
<a className="dropdown-item px-2 cursor-pointer py-1"> <a className="dropdown-item px-2 cursor-pointer py-1">
<i className="bx bx-trash text-danger bx-xs me-2"></i> <i className="bx bx-undo text-danger me-2"></i>
Delete Restore
</a> </a>
</li> </li>
</> )}
) : ( </ul>
<li </div>
onClick={() => {
setIsDeleteModalOpen(true);
setDeletingId(branch.id);
}}
>
<a className="dropdown-item px-2 cursor-pointer py-1">
<i className="bx bx-undo text-danger me-2"></i>
Restore
</a>
</li>
)}
</ul>
</div> </div>
</td> </td>
</tr> </tr>
@ -277,6 +308,17 @@ const ServiceBranch = () => {
/> />
</GlobalModel> </GlobalModel>
)} )}
{ViewRequest.view && (
<GlobalModel
isOpen
size="md"
modalType="top"
closeModal={() => setViewRequest({ branchId: null, view: false })}
>
<ViewBranchDetails BranchToEdit={ViewRequest.branchId} />
</GlobalModel>
)}
</div> </div>
</div> </div>
</> </>

View File

@ -0,0 +1,140 @@
import React from "react";
import { useBranchDetails } from "../../../hooks/useServiceProject";
import Avatar from "../../common/Avatar";
import { formatUTCToLocalTime } from "../../../utils/dateUtils";
const ViewBranchDetails = ({ BranchToEdit }) => {
const { data, isLoading, isError, error: requestError } = useBranchDetails(BranchToEdit);
if (isLoading) return <p>Loading...</p>;
if (isError) return <p>Error: {requestError?.message}</p>;
return (
<form className="container px-3">
<div className="col-12 mb-1">
<h5 className="fw-semibold m-0">Branch Details</h5>
</div>
<div className="row mb-1 mt-5">
<div className="col-md-12 mb-4">
<div className="d-flex">
<label
className="form-label me-2 mb-0 fw-semibold text-start"
style={{ minWidth: "130px" }}
>
Branch Name:
</label>
<div className="text-muted">{data?.branchName || "N/A"}</div>
</div>
</div>
<div className="col-md-12 mb-4">
<div className="d-flex">
<label
className="form-label me-2 mb-0 fw-semibold text-start"
style={{ minWidth: "130px" }}
>
Branch Type:
</label>
<div className="text-muted">{data?.branchName || "N/A"}</div>
</div>
</div>
<div className="col-md-12 mb-4">
<div className="d-flex">
<label
className="form-label me-2 mb-0 fw-semibold text-start"
style={{ minWidth: "130px" }}
>
Project:
</label>
<div className="text-muted text-start">{data?.project?.name || "N/A"}</div>
</div>
</div>
{/* <div className="col-md-12 text-start mb-2">
<div className="d-flex align-items-center">
<label
className="form-label me-2 mb-0 fw-semibold"
style={{ minWidth: "125px" }}
>
Updated By :
</label>
<>
<Avatar
size="xs"
classAvatar="m-0 me-1"
firstName={data?.updatedBy?.firstName}
lastName={data?.updatedBy?.lastName}
/>
<span className="text-muted">
{`${data?.updatedBy?.firstName ?? ""} ${data?.updatedBy?.lastName ?? ""
}`.trim() || "N/A"}
</span>
</>
</div>
</div> */}
<div className="col-md-12 text-start mb-3">
<div className="d-flex align-items-center">
<label
className="form-label me-2 mb-0 fw-semibold"
style={{ minWidth: "125px" }}
>
Created By :
</label>
<Avatar
size="xs"
classAvatar="m-0 me-1"
firstName={data?.createdBy?.firstName}
lastName={data?.createdBy?.lastName}
/>
<span className="text-muted">
{`${data?.createdBy?.firstName ?? ""} ${data?.createdBy?.lastName ?? ""
}`.trim() || "N/A"}
</span>
</div>
</div>
<div className="col-md-12 mb-3">
<div className="d-flex">
<label
className="form-label me-2 mb-0 fw-semibold text-start"
style={{ minWidth: "130px" }}
>
Created At :
</label>
<div className="text-muted">
{data?.createdAt
? formatUTCToLocalTime(data.createdAt, true)
: "N/A"}
</div>
</div>
</div>
<div className="col-12 mb-3 text-start">
<label className="form-label mb-2 fw-semibold">Contact Information:</label>
<div className="text-muted">
{data?.contactInformation ? (
JSON.parse(data.contactInformation).map((contact, index) => (
<div key={index} className="mb-3">
<div className="text-secondary mb-1">Person {index + 1}</div>
<div>
<label className="fw-semibold mb-1">Person Name:</label> {contact.contactPerson || "N/A"}
</div>
<div>
<label className="fw-semibold mb-1">Designation:</label> {contact.designation || "N/A"}
</div>
<div>
<label className="fw-semibold mb-1">Emails:</label> {contact.contactEmails?.join(", ") || "N/A"}
</div>
<div>
<label className="fw-semibold mb-1">Number:</label> {contact.contactNumbers?.join(", ") || "N/A"}
</div>
</div>
))
) : (
"N/A"
)}
</div>
</div>
</div>
</form>
);
};
export default ViewBranchDetails;

View File

@ -68,7 +68,7 @@ const ChangeStatus = ({ statusId, projectId, jobId, popUpId }) => {
options={data ?? []} options={data ?? []}
placeholder="Choose a Status" placeholder="Choose a Status"
required required
labelKeyKey="name" labelKey="name"
valueKeyKey="id" valueKeyKey="id"
value={field.value} value={field.value}
onChange={field.onChange} onChange={field.onChange}

View File

@ -150,7 +150,7 @@ const JobComments = ({ data }) => {
type="submit" type="submit"
disabled={!watch("comment")?.trim() || isPending} disabled={!watch("comment")?.trim() || isPending}
> >
Send Submit
</button> </button>
</div> </div>
</form> </form>

View File

@ -1,56 +1,38 @@
import React from "react"; import React, { useMemo } from "react";
import Avatar from "../../common/Avatar";
import { formatUTCToLocalTime } from "../../../utils/dateUtils";
import { getColorNameFromHex } from "../../../utils/appUtils";
import Timeline from "../../common/TimeLine";
const JobStatusLog = ({ data }) => { const JobStatusLog = ({ data }) => {
// Prepare timeline items
const timelineData = useMemo(() => {
if (!data) return [];
return data
.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
.map((log) => ({
id: log.id,
title: log.nextStatus?.displayName || log.status?.displayName || "Status Updated",
description: log.nextStatus?.description || "",
timeAgo: log.updatedAt,
color: getColorNameFromHex(log.nextStatus?.color) || "primary",
userComment: log.comment,
users: log.updatedBy
? [
{
firstName: log.updatedBy.firstName || "",
lastName: log.updatedBy.lastName || "",
role: log.updatedBy.jobRoleName || "",
avatar: log.updatedBy.photo || null,
},
]
: [],
}));
}, [data]);
return ( return (
<div className="card shadow-none p-0"> <div className="card shadow-none p-0">
<div className="card-body p-0"> <div className="card-body p-3">
<div className="list-group"> <Timeline items={timelineData} transparent={true} />
{data?.map((item) => (
<div
key={item.id}
className="list-group-item border-0 border-bottom p-1"
>
<div className="d-flex justify-content-between">
<div>
<span className="fw-semibold">
{item.nextStatus?.displayName ??
item.status?.displayName ??
"Status"}
</span>
</div>
<span className="text-secondary">
{formatUTCToLocalTime(item?.updatedAt,true)}
</span>
</div>
<div className="d-flex align-items-start mt-2 mx-0 px-0">
<Avatar
firstName={item.updatedBy?.firstName}
lastName={item.updatedBy?.lastName}
/>
<div className="">
<div className="d-flex flex-row gap-3">
<span className="fw-semibold">
{item.updatedBy?.firstName} {item.updatedBy?.lastName}
</span>
<span className="text-secondary">
{/* <em>{formatUTCToLocalTime(item?.createdAt, true)}</em> */}
</span>
</div>
<div className="text-muted text-secondary">
{item?.updatedBy?.jobRoleName}
</div>
<div className="text-wrap">
<p className="mb-1 mt-2 text-muted">{item.comment}</p>
</div>
</div>
</div>
</div>
))}
</div>
</div> </div>
</div> </div>
); );

View File

@ -89,7 +89,7 @@ const ManageJob = ({ Job }) => {
})); }));
const updatedEmployees = [...oldEmployees, ...newEmployees]; const updatedEmployees = [...oldEmployees, ...newEmployees];
const payload = [ const payload = [
{ {
op: "replace", op: "replace",
@ -128,6 +128,11 @@ const ManageJob = ({ Job }) => {
value: formData.statusId, value: formData.statusId,
}, },
]; ];
if(payload.length === 0){
showToast("Please change any field value", "warning");
return;
}
UpdateJob({ id: Job, payload }); UpdateJob({ id: Job, payload });
} else { } else {
formData.assignees = formData.assignees.map((emp) => ({ formData.assignees = formData.assignees.map((emp) => ({
@ -140,6 +145,7 @@ const ManageJob = ({ Job }) => {
formData.projectId = projectId; formData.projectId = projectId;
CreateJob(formData); CreateJob(formData);
setManageJob({ isOpen: false, jobId: null });
} }
}; };
@ -235,8 +241,8 @@ const ManageJob = ({ Job }) => {
options={data ?? []} options={data ?? []}
placeholder="Choose a Status" placeholder="Choose a Status"
required required
labelKeyKey="name" labelKey="name"
valueKeyKey="id" valueKey="id"
value={field.value} value={field.value}
onChange={field.onChange} onChange={field.onChange}
isLoading={isLoading} isLoading={isLoading}

View File

@ -23,20 +23,21 @@ const ManageJobTicket = ({ Job }) => {
); );
const drawerRef = useRef(); const drawerRef = useRef();
const tabsData = [ const tabsData = [
{
id: "history",
title: "History",
icon: "bx bx-time me-2",
active: true,
content: <JobStatusLog data={data?.updateLogs} />,
},
{ {
id: "comment", id: "comment",
title: "Comments", title: "Comments",
icon: "bx bx-comment me-2", icon: "bx bx-comment me-2",
active: true, active: false,
content: <JobComments data={data} />, content: <JobComments data={data} />,
}, },
{
id: "history",
title: "History",
icon: "bx bx-time me-2",
active: false,
content: <JobStatusLog data={data?.updateLogs} />,
},
]; ];
if (isLoading) return <JobDetailsSkeleton />; if (isLoading) return <JobDetailsSkeleton />;
@ -69,7 +70,7 @@ const ManageJobTicket = ({ Job }) => {
id="STATUS_CHANEG" id="STATUS_CHANEG"
Mode="click" Mode="click"
className="" className=""
align="right" align="left"
content={ content={
<ChangeStatus <ChangeStatus
statusId={data?.status?.id} statusId={data?.status?.id}
@ -141,7 +142,7 @@ const ManageJobTicket = ({ Job }) => {
})()} })()}
</div> </div>
{data?.projectBranch && ( {data?.projectBranch && (
<div className="d-flex gap-3 my-2 position-relative" ref={drawerRef} > <div className="d-flex gap-3 my-2 position-relative" ref={drawerRef} >
<span className="text-secondary"> <span className="text-secondary">
<i className="bx bx-buildings"></i> Branch Name: <i className="bx bx-buildings"></i> Branch Name:
</span> </span>
@ -149,7 +150,8 @@ const ManageJobTicket = ({ Job }) => {
<HoverPopup <HoverPopup
id="BRANCH_DETAILS" id="BRANCH_DETAILS"
Mode="click" Mode="click"
align="auto" align="right"
minWidth="340px"
boundaryRef={drawerRef} boundaryRef={drawerRef}
content={<BranchDetails branch={data?.projectBranch?.id} />} content={<BranchDetails branch={data?.projectBranch?.id} />}
> >

View File

@ -7,6 +7,7 @@ import GlobalModel from "../common/GlobalModel";
import { SpinnerLoader } from "../common/Loader"; import { SpinnerLoader } from "../common/Loader";
import ServiceBranch from "./ServiceProjectBranch/ServiceBranch"; import ServiceBranch from "./ServiceProjectBranch/ServiceBranch";
import ServiceProfile from "./ServiceProfile"; import ServiceProfile from "./ServiceProfile";
import ServiceJobs from "../Dashboard/ServiceJobs";
const ServiceProjectProfile = () => { const ServiceProjectProfile = () => {
const { projectId } = useParams(); const { projectId } = useParams();
@ -40,6 +41,9 @@ const ServiceProjectProfile = () => {
<div className="col-md-6 col-lg-7 order-2 mb-6"> <div className="col-md-6 col-lg-7 order-2 mb-6">
<ServiceBranch /> <ServiceBranch />
</div> </div>
<div className="col-md-6 col-lg-5 order-2 mb-6">
<ServiceJobs/>
</div>
</div> </div>
</> </>
); );

View File

@ -66,7 +66,7 @@ const ServiceProjectTeamList = () => {
<tbody> <tbody>
{data?.length > 0 ? ( {data?.length > 0 ? (
data.map((row) => ( data.map((row) => (
<tr key={row.id}> <tr key={row.id} style={{ height: "50px" }}>
{servceProjectColmen.map((col) => ( {servceProjectColmen.map((col) => (
<td key={col.key} className={col.align}>{col.getValue(row)}</td> <td key={col.key} className={col.align}>{col.getValue(row)}</td>
))} ))}

View File

@ -32,7 +32,7 @@ const ContactInfro = ({ onNext }) => {
<input <input
id="firstName" id="firstName"
type="text" type="text"
className={`form-control form-control-sm`} className={`form-control `}
{...register("firstName")} {...register("firstName")}
/> />
{errors.firstName && ( {errors.firstName && (
@ -46,7 +46,7 @@ const ContactInfro = ({ onNext }) => {
<input <input
id="lastName" id="lastName"
type="text" type="text"
className={`form-control form-control-sm `} className={`form-control `}
{...register("lastName")} {...register("lastName")}
/> />
{errors.lastName && ( {errors.lastName && (
@ -60,7 +60,7 @@ const ContactInfro = ({ onNext }) => {
<input <input
id="email" id="email"
type="email" type="email"
className={`form-control form-control-sm `} className={`form-control `}
{...register("email")} {...register("email")}
/> />
{errors.email && ( {errors.email && (
@ -74,7 +74,7 @@ const ContactInfro = ({ onNext }) => {
<input <input
id="contactNumber" id="contactNumber"
type="text" type="text"
className={`form-control form-control-sm `} className={`form-control `}
{...register("contactNumber")} {...register("contactNumber")}
inputMode="tel" inputMode="tel"
placeholder="+91 9876543210" placeholder="+91 9876543210"

View File

@ -7,6 +7,8 @@ import { LogoUpload } from './LogoUpload';
import showToast from '../../services/toastService'; import showToast from '../../services/toastService';
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from '@hookform/resolvers/zod';
import { EditTenant } from './TenantSchema'; import { EditTenant } from './TenantSchema';
import { AppFormController } from '../../hooks/appHooks/useAppForm';
import SelectField from '../common/Forms/SelectField';
const EditProfile = ({ TenantId, onClose }) => { const EditProfile = ({ TenantId, onClose }) => {
const { data, isLoading, isError, error } = useTenantDetails(TenantId); const { data, isLoading, isError, error } = useTenantDetails(TenantId);
@ -37,7 +39,7 @@ const EditProfile = ({ TenantId, onClose }) => {
} }
}); });
const { register, reset, handleSubmit, formState: { errors } } = methods; const { register, control, reset, handleSubmit, formState: { errors } } = methods;
const onSubmit = (formData) => { const onSubmit = (formData) => {
const tenantPayload = { ...formData, contactName: `${formData.firstName} ${formData.lastName}`, id: data.id, } const tenantPayload = { ...formData, contactName: `${formData.firstName} ${formData.lastName}`, id: data.id, }
@ -74,93 +76,122 @@ const EditProfile = ({ TenantId, onClose }) => {
<form className="row g-6" onSubmit={handleSubmit(onSubmit)}> <form className="row g-6" onSubmit={handleSubmit(onSubmit)}>
<h5>Edit Tenant</h5> <h5>Edit Tenant</h5>
<div className="col-sm-6 mt-1 text-start"> <div className="col-sm-6 mt-n2 text-start">
<Label htmlFor="firstName" required>First Name</Label> <Label htmlFor="firstName" required>First Name</Label>
<input id="firstName" type="text" className="form-control form-control-sm" {...register("firstName")} inputMode='text' /> <input id="firstName" type="text" className="form-control " {...register("firstName")} inputMode='text' />
{errors.firstName && <div className="danger-text">{errors.firstName.message}</div>} {errors.firstName && <div className="danger-text">{errors.firstName.message}</div>}
</div> </div>
<div className="col-sm-6 mt-1 text-start"> <div className="col-sm-6 mt-n2 text-start">
<Label htmlFor="lastName" required>Last Name</Label> <Label htmlFor="lastName" required>Last Name</Label>
<input id="lastName" type="text" className="form-control form-control-sm" {...register("lastName")} /> <input id="lastName" type="text" className="form-control " {...register("lastName")} />
{errors.lastName && <div className="danger-text">{errors.lastName.message}</div>} {errors.lastName && <div className="danger-text">{errors.lastName.message}</div>}
</div> </div>
<div className="col-sm-6 mt-1 text-start"> <div className="col-sm-6 text-start">
<Label htmlFor="contactNumber" required>Contact Number</Label> <Label htmlFor="contactNumber" required>Contact Number</Label>
<input id="contactNumber" type="text" className="form-control form-control-sm" {...register("contactNumber")} inputMode="tel" <input id="contactNumber" type="text" className="form-control " {...register("contactNumber")} inputMode="tel"
placeholder="+91 9876543210" /> placeholder="+91 9876543210" />
{errors.contactNumber && <div className="danger-text">{errors.contactNumber.message}</div>} {errors.contactNumber && <div className="danger-text">{errors.contactNumber.message}</div>}
</div> </div>
<div className="col-sm-6 mt-1 text-start"> <div className="col-sm-6 text-start">
<Label htmlFor="domainName" >Domain Name</Label> <Label htmlFor="domainName" >Domain Name</Label>
<input id="domainName" type="text" className="form-control form-control-sm" {...register("domainName")} /> <input id="domainName" type="text" className="form-control " {...register("domainName")} />
{errors.domainName && <div className="danger-text">{errors.domainName.message}</div>} {errors.domainName && <div className="danger-text">{errors.domainName.message}</div>}
</div> </div>
<div className="col-sm-6 mt-1 text-start"> <div className="col-sm-6 text-start">
<Label htmlFor="taxId" >Tax ID</Label> <Label htmlFor="taxId" >Tax ID</Label>
<input id="taxId" type="text" className="form-control form-control-sm" {...register("taxId")} /> <input id="taxId" type="text" className="form-control " {...register("taxId")} />
{errors.taxId && <div className="danger-text">{errors.taxId.message}</div>} {errors.taxId && <div className="danger-text">{errors.taxId.message}</div>}
</div> </div>
<div className="col-sm-6 mt-1 text-start"> <div className="col-sm-6 text-start">
<Label htmlFor="officeNumber" >Office Number</Label> <Label htmlFor="officeNumber" >Office Number</Label>
<input id="officeNumber" type="text" className="form-control form-control-sm" {...register("officeNumber")} /> <input id="officeNumber" type="text" className="form-control " {...register("officeNumber")} />
{errors.officeNumber && <div className="danger-text">{errors.officeNumber.message}</div>} {errors.officeNumber && <div className="danger-text">{errors.officeNumber.message}</div>}
</div> </div>
<div className="col-sm-6 mt-1 text-start">
<Label htmlFor="industryId" required>Industry</Label>
<select className="form-select form-select-sm" {...register("industryId")}>
{industryLoading ? <option value="">Loading...</option> :
Industries?.map((indu) => (
<option key={indu.id} value={indu.id}>{indu.name}</option>
))
}
</select>
{errors.industryId && <div className="danger-text">{errors.industryId.message}</div>}
</div>
<div className="col-sm-6 mt-1 text-start">
<Label htmlFor="reference">Reference</Label>
<select className="form-select form-select-sm" {...register("reference")}>
{reference.map((org) => (
<option key={org.val} value={org.val}>{org.name}</option>
))}
</select>
{errors.reference && <div className="danger-text">{errors.reference.message}</div>}
</div>
<div className="col-sm-6 text-start"> <div className="col-sm-6 text-start">
<Label htmlFor="organizationSize" required> <AppFormController
Organization Size name="industryId"
</Label> control={control}
render={({ field }) => (
<SelectField
label="Industry"
options={Industries ?? []}
placeholder={industryLoading ? "Loading..." : "Choose an Industry"}
required
labelKey="name"
valueKey="id"
value={field.value}
onChange={field.onChange}
isLoading={industryLoading}
className="m-0 w-100"
/>
)}
/>
<select {errors.industryId && (
className="form-select form-select-sm" <small className="danger-text">{errors.industryId.message}</small>
{...register("organizationSize")}
>
{orgSize.map((org) => (
<option key={org.val} value={org.val}>
{org.name}
</option>
))}
</select>
{errors.organizationSize && (
<div className="danger-text">{errors.organizationSize.message}</div>
)} )}
</div> </div>
<div className="col-12 mt-1 text-start">
<div className="col-sm-6 text-start">
<AppFormController
name="reference"
control={control}
render={({ field }) => (
<SelectField
label="Reference"
placeholder="Select Reference"
options={reference ?? []}
labelKey="name"
valueKey="val"
value={field.value}
onChange={field.onChange}
className="shadow-none border py-1 px-2 small m-0"
/>
)}
/>
{errors.reference && (
<small className="danger-text">{errors.reference.message}</small>
)}
</div>
<div className="col-sm-6 text-start">
<AppFormController
name="organizationSize"
control={control}
render={({ field }) => (
<SelectField
label="Organization Size"
placeholder="Select Organization Size"
options={orgSize ?? []}
labelKey="name"
valueKey="val"
value={field.value}
onChange={field.onChange}
className="shadow-none border py-1 px-2 small m-0"
required
/>
)}
/>
{errors.organizationSize && (
<small className="danger-text">{errors.organizationSize.message}</small>
)}
</div>
<div className="col-12 text-start">
<Label htmlFor="billingAddress" required>Billing Address</Label> <Label htmlFor="billingAddress" required>Billing Address</Label>
<textarea id="billingAddress" className="form-control" {...register("billingAddress")} rows={2} /> <textarea id="billingAddress" className="form-control" {...register("billingAddress")} rows={2} />
{errors.billingAddress && <div className="danger-text">{errors.billingAddress.message}</div>} {errors.billingAddress && <div className="danger-text">{errors.billingAddress.message}</div>}
</div> </div>
<div className="col-12 mt-1 text-start"> <div className="col-12 text-start">
<Label htmlFor="description">Description</Label> <Label htmlFor="description">Description</Label>
<textarea id="description" className="form-control" {...register("description")} rows={2} /> <textarea id="description" className="form-control" {...register("description")} rows={2} />
{errors.description && <div className="danger-text">{errors.description.message}</div>} {errors.description && <div className="danger-text">{errors.description.message}</div>}

View File

@ -8,6 +8,9 @@ import { orgSize, reference } from "../../utils/constants";
import moment from "moment"; import moment from "moment";
import { useGlobalServices } from "../../hooks/masterHook/useMaster"; import { useGlobalServices } from "../../hooks/masterHook/useMaster";
import SelectMultiple from "../common/SelectMultiple"; import SelectMultiple from "../common/SelectMultiple";
import { AppFormController } from "../../hooks/appHooks/useAppForm";
import SelectField from "../common/Forms/SelectField";
import { fill } from "pdf-lib";
const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => { const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
const { data, isError, isLoading: industryLoading } = useIndustries(); const { data, isError, isLoading: industryLoading } = useIndustries();
@ -58,16 +61,16 @@ const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
}; };
useEffect(() => { useEffect(() => {
const logoImage = getValues("logoImage"); const logoImage = getValues("logoImage");
if (logoImage) { if (logoImage) {
setLogoPreview(logoImage); setLogoPreview(logoImage);
setLogoName("Uploaded Logo"); setLogoName("Uploaded Logo");
} }
}, [getValues]); }, [getValues]);
return ( return (
<div className="row g-2 text-start"> <div className="row g-6 text-start">
<div className="col-sm-6"> <div className="col-sm-6">
<Label htmlFor="organizationName" required> <Label htmlFor="organizationName" required>
Organization Name Organization Name
@ -75,7 +78,7 @@ const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
<input <input
id="organizationName" id="organizationName"
className={`form-control form-control-sm `} className={`form-control `}
{...register("organizationName")} {...register("organizationName")}
/> />
{errors.organizationName && ( {errors.organizationName && (
@ -89,7 +92,7 @@ const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
</Label> </Label>
<input <input
id="officeNumber" id="officeNumber"
className={`form-control form-control-sm `} className={`form-control `}
{...register("officeNumber")} {...register("officeNumber")}
/> />
{errors.officeNumber && ( {errors.officeNumber && (
@ -103,7 +106,7 @@ const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
</Label> </Label>
<input <input
id="domainName" id="domainName"
className={`form-control form-control-sm `} className={`form-control `}
{...register("domainName")} {...register("domainName")}
/> />
{errors.domainName && ( {errors.domainName && (
@ -117,7 +120,7 @@ const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
</Label> </Label>
<input <input
id="taxId" id="taxId"
className={`form-control form-control-sm `} className={`form-control `}
{...register("taxId")} {...register("taxId")}
/> />
{errors.taxId && ( {errors.taxId && (
@ -131,10 +134,11 @@ const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
</Label> </Label>
<DatePicker <DatePicker
name="onBoardingDate" name="onBoardingDate"
size="md"
control={control} control={control}
placeholder="DD-MM-YYYY" placeholder="DD-MM-YYYY"
maxDate={new Date()} maxDate={new Date()}
className={errors.onBoardingDate ? "is-invalid" : ""} className={`w-100 ${errors.onBoardingDate ? "is-invalid" : ""}`}
/> />
{errors.onBoardingDate && ( {errors.onBoardingDate && (
<div className="invalid-feedback"> <div className="invalid-feedback">
@ -143,74 +147,80 @@ const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
)} )}
</div> </div>
<div className="col-sm-6"> <div className="col-sm-6 mb-2 mb-md-4">
<Label htmlFor="organizationSize" required> <AppFormController
Organization Size name="organizationSize"
</Label> control={control}
render={({ field }) => (
<select <SelectField
id="organizationSize" label="Organization Size"
className="form-select shadow-none border py-1 px-2" placeholder="Select Organization Size"
style={{ fontSize: "0.875rem" }} // Bootstrap's small text size options={orgSize ?? []}
{...register("organizationSize", { required: "Organization size is required" })} labelKey="name"
> valueKey="val"
{orgSize.map((org) => ( value={field.value}
<option key={org.val} value={org.val}> onChange={field.onChange}
{org.name} className="shadow-none border py-1 px-2 small m-0"
</option> required
))} />
</select> )}
/>
{errors.organizationSize && ( {errors.organizationSize && (
<div className="danger-text">{errors.organizationSize.message}</div> <small className="danger-text">{errors.organizationSize.message}</small>
)} )}
</div> </div>
<div className="col-sm-6 mt-n3">
<div className="col-sm-6"> <AppFormController
<Label htmlFor="industryId" required> name="industryId"
Industry control={control} // make sure `control` comes from useForm
</Label> render={({ field }) => (
<select <SelectField
id="industryId" label="Industry"
className="form-select shadow-none border py-1 px-2 small" placeholder={industryLoading ? "Loading..." : "Select Industry"}
{...register("industryId")} options={data ?? []}
> labelKey="name"
{industryLoading ? ( valueKeyKey="id"
<option value="">Loading...</option> value={field.value}
) : ( onChange={field.onChange}
data?.map((indu) => ( isLoading={industryLoading}
<option key={indu.id} value={indu.id}> className="shadow-none border py-1 px-2 small"
{indu.name} required
</option> />
))
)} )}
</select> />
{errors.industryId && ( {errors.industryId && (
<div className="danger-text">{errors.industryId.message}</div> <div className="danger-text">{errors.industryId.message}</div>
)} )}
</div> </div>
<div className="col-sm-6"> <div className="col-sm-6 mb-2 mb-md-4 mt-n3">
<Label htmlFor="reference" required>Reference</Label> <AppFormController
<select name="reference"
id="reference" control={control}
className="form-select shadow-none border py-1 px-2 small" render={({ field }) => (
{...register("reference")} <SelectField
> label="Reference"
{reference.map((org) => ( placeholder="Select Reference"
<option key={org.val} value={org.val}> options={reference ?? []}
{org.name} labelKey="name"
</option> valueKey="val"
))} value={field.value}
</select> onChange={field.onChange}
className="shadow-none border py-1 px-2 small m-0"
required
/>
)}
/>
{errors.reference && ( {errors.reference && (
<div className="danger-text">{errors.reference.message}</div> <small className="danger-text">{errors.reference.message}</small>
)} )}
</div> </div>
<div className="col-sm-6">
<SelectMultiple <div className="col-sm-6 mt-n3">
<SelectMultiple
name="serviceIds" name="serviceIds"
label="Services" label="Services"
options={services?.data} options={services?.data}
@ -229,7 +239,7 @@ const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
<textarea <textarea
id="description" id="description"
rows={3} rows={3}
className={`form-control form-control-sm `} className={`form-control `}
{...register("description")} {...register("description")}
/> />
{errors.description && ( {errors.description && (

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