108 Commits

Author SHA1 Message Date
f0cf2d5223 fix: prevent profile page from crashing for null profile values 🔨
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 11m11s
2025-09-24 20:04:04 +05:00
9ad1887f88 refactor: add animations
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 10m27s
2025-09-24 19:33:48 +05:00
f8774f51e6 style: add skeletons to paymentId and deviceId pages ♻️
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 9m13s
2025-09-24 18:20:35 +05:00
31a05ae917 style: add skeletons to paymentId and deviceId pages ♻️
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 10m58s
2025-09-24 17:46:04 +05:00
5dab74b14b refactor: create utility function to hide AccountInformation component for topup and payment 🔧
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 8m50s
2025-09-21 10:07:16 +05:00
a60e9a9c85 chore: add skeletons to tables and loading.tsx files for routes and run formatting ♻️
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 12m20s
2025-09-20 20:42:14 +05:00
5277c13fb7 fix: allow admins only to block with details in parental control page (mobile view) 🐛
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 9m39s
2025-09-20 19:07:08 +05:00
035cd02012 fix: payment info display logic condition 🐛
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 15m16s
2025-09-20 14:57:21 +05:00
dc10fa6be4 chore: release v0.2.2
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 1m26s
2025-09-20 14:41:32 +05:00
39e84723b1 refactor: remove table captions from all tables 🔧 2025-09-20 14:40:55 +05:00
19043aa692 fix: set 100 MVR for default wallet topup amount 🔧 2025-09-20 14:25:48 +05:00
f2a17d522b fix: hide account information once the payment is verified/expired/cancelled 🔧 2025-09-20 14:17:48 +05:00
43b8e22196 fix: remove pagination if there is only 1 page 🔧 2025-09-20 14:09:12 +05:00
c041c2e7d7 chore: release v0.2.1
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 14m23s
2025-09-20 13:39:13 +05:00
e5298aa323 fix: add release script 🔧 2025-09-20 13:37:35 +05:00
741358e32f fix: add missing release script
Some checks are pending
Build and Push Docker Images / Build and Push Docker Images (push) Has started running
2025-09-20 13:31:15 +05:00
1399527ddb fix: added missing release script to package.json 🔧 2025-09-20 13:26:41 +05:00
950ac676f0 Show no agreements if there is no agreement in agreement page 🔨
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 8m19s
2025-09-20 11:16:06 +05:00
b32b61afe8 rename walet page to transaction history 🔨 2025-09-20 11:15:44 +05:00
1e2329e7f1 refactor(sidebar): re arrange sidebar links 🔨 2025-09-20 11:14:38 +05:00
6c5f848856 remove welcome banner after 4 seconds with animation 2025-09-20 11:14:11 +05:00
c67b8ade10 fix: verification response handling 🐛
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 12m34s
2025-09-15 22:00:57 +05:00
17aa65a686 feat(user-update-form): display field errors in user update form
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 7m52s
2025-07-28 10:03:17 +05:00
21938657ca fix(wallet-transactions): improve badge text color for transaction types (mobile)
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 8m44s
2025-07-27 22:23:37 +05:00
a717c3d242 feat(admin-topup): add description field to topup request payload
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 8m2s
fix(wallet-transactions-table): update badge colors for better visibility
2025-07-27 22:13:49 +05:00
171b1d4d7c feat(agreements): implement agreement fetching and display with error handling
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 13m34s
feat(agreement-card): create AgreementCard component for displaying user agreements
fix(devices-table): update no devices message for clarity based on parental control
fix(payments-table): update no payments message for consistency
fix(topups-table): update no topups message for consistency
feat(user): add agreement field to User interface
2025-07-27 19:43:01 +05:00
dcf58c4349 fix(sidebar): adjust transition durations for consistency 🐛 2025-07-27 19:41:50 +05:00
3da668a94a feat(admin-topup): add description field to topup form and validation for amount
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 8m56s
fix(verify-registration-otp): improve styling and structure of OTP verification form
2025-07-27 16:01:15 +05:00
76a4e3d66e fix(devices): fix payment amount generation by passing actual values 🐛
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 7m43s
2025-07-27 15:22:15 +05:00
db261ae0bd fix(signup-form): update header and welcome message for clarity
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 8m55s
2025-07-27 14:22:32 +05:00
644e4f730f feat(user): add admin topup functionality in user details page
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 6m16s
2025-07-27 12:37:38 +05:00
3943c0d6c8 fix(wallet): update styling for total debit/credit display in wallet transactions table
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 6m56s
2025-07-26 18:56:28 +05:00
e9af120c7b feat(wallet): update transaction type from CREDIT to TOPUP and display total debit/credit amounts
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 5m27s
2025-07-26 00:17:22 +05:00
e0b76bb865 feat(wallet): implement wallet transactions table and filtering options
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 7m19s
2025-07-25 16:01:20 +05:00
9b2f2c1528 add admin checks for admin pages and run biome formating 🔨
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 11m8s
2025-07-25 13:31:12 +05:00
aedf7cdf7d feat(topups): add support for fetching all topups in getTopups function
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 7m2s
2025-07-25 11:06:55 +05:00
a2425009ee update readme
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 5m14s
2025-07-25 10:59:54 +05:00
eadd790fe1 feat(verify-user): add link to view user agreement and improve layout for user information
Some checks are pending
Build and Push Docker Images / Build and Push Docker Images (push) Has started running
2025-07-25 10:58:39 +05:00
c2578f1c8f feat(user-agreement): implement user agreement upload functionality and update related components 2025-07-25 10:39:15 +05:00
5fda723653 chore(package-lock): update brace-expansion to version 1.1.12 and form-data to version 4.0.4
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 9m45s
2025-07-24 23:03:58 +05:00
1f6fe7db38 feat(user-topups): add user topups page with dynamic filtering and admin table integration
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Has been cancelled
feat(admin-devices-table): update admin check to use is_admin and clean up device display logic 
feat(admin-topup-table): create admin topups table with pagination and detail view links 
fix(user-payments-table): correct user data access and display payment amount with currency 
feat(app-sidebar): add link for user topups in the admin sidebar 
fix(backend-types): enhance Payment interface to include user details for better data handling 
2025-07-24 23:01:41 +05:00
d7b8e4ec64 chore(user-payments-table): remove unused imports 🔧
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 44s
2025-07-23 23:13:04 +05:00
c34285c66d feat(admin): add admin payment tables + filters
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Has been cancelled
2025-07-23 23:12:10 +05:00
dc3b5f9bf9 feat(user-verification): implement user verification functionality and update dialog UI
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 6m54s
2025-07-16 02:03:03 +05:00
7a02cb2415 chore(user-update-form): remove unused import for cleaner code 🔧
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 5m40s
2025-07-14 21:40:22 +05:00
9926de99d6 feat(filters): replace existing filters with dynamic filters for improved user and device management 2025-07-14 21:39:31 +05:00
8bcf4812be chore(README): update task list to reflect completed features in parental control and admin controls 🔧 2025-07-14 21:39:17 +05:00
8fac07bb60 feat(user): implement user update functionality and enhance verification page UI 2025-07-14 21:38:29 +05:00
780239dbbe feat(admin): add usertable and update next config
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 5m25s
2025-07-13 23:09:02 +05:00
Abdulla Aidhaan
d198a1bdcf Merge pull request #17 from i701/feat/user-verification-handling
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 8m20s
fix getProfile import in PaymentId 🐛
2025-07-13 22:58:17 +05:00
361a01d86c fix getProfile import in PaymentId 🐛 2025-07-13 22:57:20 +05:00
Abdulla Aidhaan
74b19ed5b9 Merge pull request #16 from i701/feat/user-verification-handling
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 1m43s
feat/user verification handling
2025-07-13 22:53:16 +05:00
255c03ae6a feat: implement user verification and rejection functionality with improved error handling 2025-07-13 22:51:46 +05:00
5809e26593 refactor: simplify FloatingInput and Textarea components by removing unnecessary forwardRef usage 🔨 2025-07-13 22:49:55 +05:00
b90a4afc73 fix: enhance error handling in handleApiResponse function for better clarity 🐛 2025-07-13 22:41:26 +05:00
Abdulla Aidhaan
644db022a1 Merge pull request #15 from i701/feat/user-profile
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 2m30s
feat/user profile 
2025-07-11 14:50:06 +05:00
9c1d1c5d2b feat: add floating label input component for enhanced form usability 2025-07-11 14:41:47 +05:00
78673e050c refactor: remove unused user verification function and clean up user type definitions 🔨 2025-07-11 14:41:30 +05:00
a20c939c91 feat: implement user profile page and integrate profile fetching logic in AccountPopover and ApplicationLayout components 2025-07-11 14:41:06 +05:00
d1fdcc873a fix: simplify condition for displaying pending payment link in ClickableRow component 🐛
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 18m1s
2025-07-11 09:59:29 +05:00
71f48b1270 fix: remove unnecessary JSON display of payment creation date and improve conditional styling in MobilePaymentDetails component 🐛
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 7m52s
2025-07-09 21:44:54 +05:00
27a0b5d4b3 bug: fix payment status display and force timezones in creation date in PaymentsTable and DevicesToPay components 🐛
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 7m27s
2025-07-09 21:14:49 +05:00
783d4b360d fix: pagination in PaymentsTable and TopupsTable components 🐛
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 7m35s
2025-07-08 22:40:06 +05:00
fa12cd74d7 refactor: use single seperate AccountInfomation component and integrate it into DevicesToPay and TopupToPay components 🔨
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 5m31s
2025-07-08 21:09:17 +05:00
8f9b4ba2e5 refactor: remove unused imports in TopupToPay component 🔨
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 12m18s
2025-07-08 19:54:48 +05:00
a61231cf6b refactor: improve state management and layout in Topup components 🔨
Some checks are pending
Build and Push Docker Images / Build and Push Docker Images (push) Has started running
2025-07-08 19:54:07 +05:00
9f9f2e4e91 feat: add disabled prop to DevicesToPay component and update button state management
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 5m36s
2025-07-06 23:19:12 +05:00
Abdulla Aidhaan
3ac57a9c07 Merge pull request #14 from i701/feat/device-payments
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 6m26s
refactor: implement device payment verification with useActionState hook 🔨
2025-07-06 23:10:04 +05:00
1a11f1a06c refactor: implement device payment verification with useActionState hook 🔨 2025-07-06 23:06:51 +05:00
Abdulla Aidhaan
2232cdcf72 Merge pull request #13 from i701/feat/device-payments
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 5m22s
feat/device payments
2025-07-06 22:41:28 +05:00
837cc35ad3 refactor: reorder imports and improve variable naming in CancelPaymentButton component 🔨 2025-07-06 22:39:16 +05:00
e984705849 refactor: update cancelPayment function to use PATCH method and new endpoint 🔨 2025-07-06 22:38:55 +05:00
4797ee8dde feat: add expiry label to ExpiryCountDown component 2025-07-06 22:38:39 +05:00
df2b3da22e feat: enhance payment and topup interfaces with status and expiration details 2025-07-06 22:38:01 +05:00
9e25da717b feat: add expiry label to ExpiryCountDown component in TopupPage 2025-07-06 22:37:23 +05:00
Abdulla Aidhaan
62678b6a84 Merge pull request #12 from i701/feat/wallet-topups
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 4m59s
refactor: enhance topup status display and improve conditional rendering in TopupsTable component 🔨
2025-07-06 20:16:27 +05:00
8c94c92281 refactor: enhance topup status display and improve conditional rendering in TopupsTable component 🔨 2025-07-06 20:12:25 +05:00
Abdulla Aidhaan
b3805feefe Merge pull request #11 from i701/feat/wallet-topups
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 5m15s
feat/wallet topups
2025-07-06 20:02:16 +05:00
b9d8e56c3c feat: update cancelTopup API call to use PATCH method and enhance success message with topup details 2025-07-06 20:01:10 +05:00
d4993530f7 feat: add radio filter for topup expiry 2025-07-06 20:01:10 +05:00
3e3b5f15db feat: add custom headers configuration to next.js config for stream/suspense support 2025-07-06 20:01:10 +05:00
13f0e720f4 feat: add payment method filter to payments page 2025-07-06 20:01:10 +05:00
9fe3c3b774 feat: enhance payment retrieval with flexible query parameters and add dynamic filters to payments page 2025-07-06 20:01:10 +05:00
135edf80a8 deploy in 1 ssh session 2025-07-06 20:01:10 +05:00
c0a71dd811 fix docker build yml 2025-07-06 20:01:10 +05:00
2597ac7d79 clean up dangling images after restart 2025-07-06 20:01:10 +05:00
154226b48d feat: add radio filter for topup expiry
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 4m49s
2025-07-06 19:48:24 +05:00
683d85798a feat: add custom headers configuration to next.js config for stream/suspense support
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 4m58s
2025-07-05 21:21:08 +05:00
da7d101ea6 feat: add payment method filter to payments page
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 5m58s
2025-07-05 20:47:31 +05:00
fa0d088f7f feat: enhance payment retrieval with flexible query parameters and add dynamic filters to payments page
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 2m18s
2025-07-05 20:41:12 +05:00
5bc8366003 deploy in 1 ssh session
Some checks are pending
Build and Push Docker Images / Build and Push Docker Images (push) Has started running
2025-07-05 20:38:35 +05:00
b22a26a2e8 fix docker build yml
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 7m47s
2025-07-05 20:25:42 +05:00
f9ed95ae18 clean up dangling images after restart 2025-07-05 20:21:11 +05:00
5de4bb9100 refactor: add topup expiry filter to the Topups component and simplify expired badge display in TopupsTable 🔨 2025-07-05 20:16:39 +05:00
Abdulla Aidhaan
d5968a5c6b Merge pull request #10 from i701/feat/wallet-topups
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 19m58s
refactor: update topup status handling in DynamicFilter and TopupsTable components 
2025-07-05 19:45:45 +05:00
378fb4074c refactor: update topup status handling in DynamicFilter and TopupsTable components 2025-07-05 19:44:36 +05:00
Abdulla Aidhaan
15c2713a1b Merge pull request #9 from i701/feat/wallet-topups
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 7m9s
feat: update Topup interface with status and paid_at fields; modify t…
2025-07-05 17:54:36 +05:00
ef7121f247 feat: update Topup interface with status and paid_at fields; modify table display for topup details 2025-07-05 17:53:32 +05:00
Abdulla Aidhaan
a41be97cdf Merge pull request #8 from i701/feat/wallet-topups
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 6m36s
feature/wallet topups
2025-07-05 15:36:39 +05:00
0c7f34fa85 fix: correct conditional expression for progress indicator color 🐛 2025-07-05 15:35:13 +05:00
013befa433 refactor: enhance topup payment verification with improved state management and error handling 🔨 2025-07-05 15:34:02 +05:00
f4c34d3b7b feat: enhance dual-range-slider handling in DynamicFilter component
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 12m44s
2025-07-04 23:11:01 +05:00
Abdulla Aidhaan
f6e60c0188 Merge pull request #7 from i701/feat/wallet-topups
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Has been cancelled
feature/wallet topups
2025-07-04 23:08:54 +05:00
f3328f7a7b feat: add topup management features including topup creation, cancellation, and countdown timer 2025-07-04 23:07:02 +05:00
ee461bbbf8 feat: implement topup functionality with create, get, and cancel operations 2025-07-04 23:06:13 +05:00
89a35a9674 feat: add "Top Ups" option to sidebar with appropriate permissions and icon 2025-07-04 23:05:30 +05:00
cd1dba06f0 refactor: update progress component styles and add radix-ui/react-progress dependency 🔨 2025-07-04 23:04:38 +05:00
Abdulla Aidhaan
ed19f440d8 Merge pull request #6 from i701/feat/block-devices
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 10m44s
refactor: enhance parental control features and improve device blocki…
2025-07-02 23:31:06 +05:00
159 changed files with 15128 additions and 7545 deletions

View File

@@ -1,9 +1,6 @@
{
"extends": [
"next/core-web-vitals",
"next/typescript"
],
"rules": {
"@typescript-eslint/no-explicit-any": "error"
}
}
"extends": ["next/core-web-vitals", "next/typescript"],
"rules": {
"@typescript-eslint/no-explicit-any": "error"
}
}

View File

@@ -35,6 +35,11 @@ jobs:
- name: Deploy production
if: github.event_name != 'pull_request'
run: |
ssh root@10.0.1.5 -t "cd /mnt && docker compose --progress plain pull portal-ui"
ssh root@10.0.1.5 -t "cd /mnt && docker compose --progress plain down portal-ui"
ssh root@10.0.1.5 -t "cd /mnt && docker compose --progress plain up -d portal-ui"
ssh root@10.0.1.5 -t "cd /mnt && \
docker compose --progress plain pull portal-ui && \
docker compose --progress plain down portal-ui && \
docker compose --progress plain up -d portal-ui"
- name: Clean up dangling images
if: github.event_name != 'pull_request'
run: ssh root@10.0.1.5 -t "docker image prune -f"

1
.husky/commit-msg Executable file
View File

@@ -0,0 +1 @@
npx commitlint --edit $1

1
.husky/pre-commit Executable file
View File

@@ -0,0 +1 @@
npm run lint

View File

@@ -1,3 +1,3 @@
{
"typescript.tsdk": "node_modules/typescript/lib"
}
"typescript.tsdk": "node_modules/typescript/lib"
}

241
CHANGELOG.md Normal file
View File

@@ -0,0 +1,241 @@
# Changelog
## <small>0.2.2 (2025-09-20)</small>
* refactor: remove table captions from all tables 🔧 ([39e8472](https://github.com/i701/sarlink-portal/commit/39e8472))
* fix: hide account information once the payment is verified/expired/cancelled 🔧 ([f2a17d5](https://github.com/i701/sarlink-portal/commit/f2a17d5))
* fix: remove pagination if there is only 1 page 🔧 ([43b8e22](https://github.com/i701/sarlink-portal/commit/43b8e22))
* fix: set 100 MVR for default wallet topup amount 🔧 ([19043aa](https://github.com/i701/sarlink-portal/commit/19043aa))
## <small>0.2.1 (2025-09-20)</small>
* fix: add release script 🔧 ([e5298aa](https://github.com/i701/sarlink-portal/commit/e5298aa))
## 0.2.0 (2025-09-20)
* fix: add error message display for general errors in OTP verification form ([25404b6](https://github.com/i701/sarlink-portal/commit/25404b6))
* fix: add logging for user data and adjust verification check in signin function ([4127035](https://github.com/i701/sarlink-portal/commit/4127035))
* fix: add missing release script ([741358e](https://github.com/i701/sarlink-portal/commit/741358e))
* fix: added missing release script to package.json 🔧 ([1399527](https://github.com/i701/sarlink-portal/commit/1399527))
* fix: correct conditional expression for progress indicator color 🐛 ([0c7f34f](https://github.com/i701/sarlink-portal/commit/0c7f34f))
* fix: correct font variable usage and improve type handling in dynamic filter ([3f92a00](https://github.com/i701/sarlink-portal/commit/3f92a00))
* fix: correct OTP type in VerifyRegistrationOTP function ([de1e76f](https://github.com/i701/sarlink-portal/commit/de1e76f))
* fix: correct user verification logic in VerifyRegistrationOTP function ([9c67386](https://github.com/i701/sarlink-portal/commit/9c67386))
* fix: enhance error handling in handleApiResponse function for better clarity 🐛 ([b90a4af](https://github.com/i701/sarlink-portal/commit/b90a4af))
* fix: enhance verification feedback in VerifyRegistrationOTP function and update UI messages ([3703b3e](https://github.com/i701/sarlink-portal/commit/3703b3e))
* fix: ensure device list is refreshed after adding a new device ([ac11fee](https://github.com/i701/sarlink-portal/commit/ac11fee))
* fix: openssl ([b9cfc55](https://github.com/i701/sarlink-portal/commit/b9cfc55))
* fix: pagination in PaymentsTable and TopupsTable components 🐛 ([783d4b3](https://github.com/i701/sarlink-portal/commit/783d4b3))
* fix: remove unnecessary JSON display of payment creation date and improve conditional styling in Mob ([71f48b1](https://github.com/i701/sarlink-portal/commit/71f48b1))
* fix: remove unused authentication imports in PaymentPage component ([886b0b1](https://github.com/i701/sarlink-portal/commit/886b0b1))
* fix: remove unused components and fix build 🐛 ([383ffdd](https://github.com/i701/sarlink-portal/commit/383ffdd))
* fix: remove unused imports from authentication pages for cleaner code ([1ae529c](https://github.com/i701/sarlink-portal/commit/1ae529c))
* fix: remove unused session retrieval in PaymentPage component ([3d12786](https://github.com/i701/sarlink-portal/commit/3d12786))
* fix: remove unused type prop from BlockDeviceDialog component ([de1e842](https://github.com/i701/sarlink-portal/commit/de1e842))
* fix: reset form after successfully adding a device in AddDeviceDialog ([067acef](https://github.com/i701/sarlink-portal/commit/067acef))
* fix: revert wut ([ff70624](https://github.com/i701/sarlink-portal/commit/ff70624))
* fix: simplify condition for displaying pending payment link in ClickableRow component 🐛 ([d1fdcc8](https://github.com/i701/sarlink-portal/commit/d1fdcc8))
* fix: streamline redirect logic for verified OTP response ([322f526](https://github.com/i701/sarlink-portal/commit/322f526))
* fix: update error messages and statuses in VerifyRegistrationOTP function for clarity ([e0e3de0](https://github.com/i701/sarlink-portal/commit/e0e3de0))
* fix: update OTP verification status message in VerifyRegistrationOTP function ([6a078d9](https://github.com/i701/sarlink-portal/commit/6a078d9))
* fix: update signin function to handle user verification response correctly ([00705bc](https://github.com/i701/sarlink-portal/commit/00705bc))
* fix: update verification error message in VerifyRegistrationOTP function ([12f9811](https://github.com/i701/sarlink-portal/commit/12f9811))
* fix: update welcome message in ApplicationLayout and simplify payment verification logic in DevicesT ([a093ab1](https://github.com/i701/sarlink-portal/commit/a093ab1))
* fix: verification response handling 🐛 ([c67b8ad](https://github.com/i701/sarlink-portal/commit/c67b8ad))
* fix(devices): fix payment amount generation by passing actual values 🐛 ([76a4e3d](https://github.com/i701/sarlink-portal/commit/76a4e3d))
* fix(sidebar): adjust transition durations for consistency 🐛 ([dcf58c4](https://github.com/i701/sarlink-portal/commit/dcf58c4))
* fix(signup-form): update header and welcome message for clarity ([db261ae](https://github.com/i701/sarlink-portal/commit/db261ae))
* fix(wallet-transactions): improve badge text color for transaction types (mobile) ([2193865](https://github.com/i701/sarlink-portal/commit/2193865))
* fix(wallet): update styling for total debit/credit display in wallet transactions table ([3943c0d](https://github.com/i701/sarlink-portal/commit/3943c0d))
* add admin checks for admin pages and run biome formating 🔨 ([9b2f2c1](https://github.com/i701/sarlink-portal/commit/9b2f2c1))
* Add Agreements page, enhance Devices and Users components with sorting and filtering options, and im ([9021f01](https://github.com/i701/sarlink-portal/commit/9021f01))
* Add AlertDialog and Badge components for user verification ([8e6f802](https://github.com/i701/sarlink-portal/commit/8e6f802))
* add auto deploy ([02e1bcb](https://github.com/i701/sarlink-portal/commit/02e1bcb))
* add auto deploy ([5e1364e](https://github.com/i701/sarlink-portal/commit/5e1364e))
* Add filter, pagination, search, and user table components ([1b43c85](https://github.com/i701/sarlink-portal/commit/1b43c85))
* add mirror to gitea ([d60dd3a](https://github.com/i701/sarlink-portal/commit/d60dd3a))
* add mirror to gitea ([9e9fab5](https://github.com/i701/sarlink-portal/commit/9e9fab5))
* add non stretched favicon ([e9c71c1](https://github.com/i701/sarlink-portal/commit/e9c71c1))
* Add payment processing and device management features ([e815da4](https://github.com/i701/sarlink-portal/commit/e815da4))
* add seed script and use postgres for db ([a0d85b1](https://github.com/i701/sarlink-portal/commit/a0d85b1))
* Add title background styling to globals.css ([762939b](https://github.com/i701/sarlink-portal/commit/762939b))
* Add user rejection and device addition functionalities ([2cbf9fb](https://github.com/i701/sarlink-portal/commit/2cbf9fb))
* attempt 2 building with docker ([a5b18e8](https://github.com/i701/sarlink-portal/commit/a5b18e8))
* attempt 4 docker ([8e068f1](https://github.com/i701/sarlink-portal/commit/8e068f1))
* attempt no 3 docker ([994956a](https://github.com/i701/sarlink-portal/commit/994956a))
* attempt to build docker again ([d72f9ae](https://github.com/i701/sarlink-portal/commit/d72f9ae))
* auto build ([fe3161e](https://github.com/i701/sarlink-portal/commit/fe3161e))
* bruh ([c79f06c](https://github.com/i701/sarlink-portal/commit/c79f06c))
* bun can build ([d5c9253](https://github.com/i701/sarlink-portal/commit/d5c9253))
* clean up dangling images after restart ([2597ac7](https://github.com/i701/sarlink-portal/commit/2597ac7))
* clean up dangling images after restart ([f9ed95a](https://github.com/i701/sarlink-portal/commit/f9ed95a))
* cleaner output ([4776952](https://github.com/i701/sarlink-portal/commit/4776952))
* cleaner output ([480f649](https://github.com/i701/sarlink-portal/commit/480f649))
* deploy in 1 ssh session ([135edf8](https://github.com/i701/sarlink-portal/commit/135edf8))
* deploy in 1 ssh session ([5bc8366](https://github.com/i701/sarlink-portal/commit/5bc8366))
* docker build works now ([5fb6f52](https://github.com/i701/sarlink-portal/commit/5fb6f52))
* down kohffa up kuraanee.. also there is 1 ui ([e841932](https://github.com/i701/sarlink-portal/commit/e841932))
* Enhance dashboard functionality with new payment and device management features ([c6f4571](https://github.com/i701/sarlink-portal/commit/c6f4571))
* Enhance device management and user experience features ([745f8d8](https://github.com/i701/sarlink-portal/commit/745f8d8))
* Enhance payment processing and device management features ([1a195d2](https://github.com/i701/sarlink-portal/commit/1a195d2))
* Enhance payment processing and device management features ([75ad431](https://github.com/i701/sarlink-portal/commit/75ad431))
* Enhance payment processing and user interaction features ([36f22c0](https://github.com/i701/sarlink-portal/commit/36f22c0))
* Enhance user management and payment processing features ([0a63e43](https://github.com/i701/sarlink-portal/commit/0a63e43))
* Enhance user verification and data validation features ([ff0eae6](https://github.com/i701/sarlink-portal/commit/ff0eae6))
* Enhance user verification and UI components ([2c67848](https://github.com/i701/sarlink-portal/commit/2c67848))
* example readme for prod deployment ([40b40ad](https://github.com/i701/sarlink-portal/commit/40b40ad))
* f all that just deploy ([1b724ca](https://github.com/i701/sarlink-portal/commit/1b724ca))
* final fix ([d14b0b3](https://github.com/i701/sarlink-portal/commit/d14b0b3))
* first commit ([7389de4](https://github.com/i701/sarlink-portal/commit/7389de4))
* fix docker build yml ([c0a71dd](https://github.com/i701/sarlink-portal/commit/c0a71dd))
* fix docker build yml ([b22a26a](https://github.com/i701/sarlink-portal/commit/b22a26a))
* fix getProfile import in PaymentId 🐛 ([361a01d](https://github.com/i701/sarlink-portal/commit/361a01d))
* fix:wut ([e2e5751](https://github.com/i701/sarlink-portal/commit/e2e5751))
* hamker magic ([ef32b74](https://github.com/i701/sarlink-portal/commit/ef32b74))
* Implement new features and enhance existing components for improved user experience ([bdf3729](https://github.com/i701/sarlink-portal/commit/bdf3729))
* Implement Omada device management and enhance payment processing ([e9d81c0](https://github.com/i701/sarlink-portal/commit/e9d81c0))
* Implement parental control features and enhance device management ([c06c4fe](https://github.com/i701/sarlink-portal/commit/c06c4fe))
* Initial commit from Create Next App ([92d9e90](https://github.com/i701/sarlink-portal/commit/92d9e90))
* installing openssl ([cd86a7a](https://github.com/i701/sarlink-portal/commit/cd86a7a))
* npx now ([bfba3cf](https://github.com/i701/sarlink-portal/commit/bfba3cf))
* optimize container build ([0e6f405](https://github.com/i701/sarlink-portal/commit/0e6f405))
* prepare for docker env ([fd4e147](https://github.com/i701/sarlink-portal/commit/fd4e147))
* prepare for docker env ([f9cac92](https://github.com/i701/sarlink-portal/commit/f9cac92))
* Refactor authentication actions and add user verification functionality ([3f68d83](https://github.com/i701/sarlink-portal/commit/3f68d83))
* Refactor authentication and dashboard components ([0322bee](https://github.com/i701/sarlink-portal/commit/0322bee))
* Refactor authentication components and enhance user session handling ([3f8bb4e](https://github.com/i701/sarlink-portal/commit/3f8bb4e))
* Refactor authentication middleware to use native fetch, update dependencies, and enhance error handl ([8ffabb1](https://github.com/i701/sarlink-portal/commit/8ffabb1))
* Refactor dashboard components and update global styles ([b91f34b](https://github.com/i701/sarlink-portal/commit/b91f34b))
* Refactor Docker setup and add Prisma Studio service ([1d6f4fa](https://github.com/i701/sarlink-portal/commit/1d6f4fa))
* Refactor Omada actions and enhance payment processing ([586c0e7](https://github.com/i701/sarlink-portal/commit/586c0e7))
* Refactor payment verification and add MAC address guide ([07349cd](https://github.com/i701/sarlink-portal/commit/07349cd))
* Refactor SMS notification handling to use environment variables ([5c167e4](https://github.com/i701/sarlink-portal/commit/5c167e4))
* Refactor UI components for improved consistency and functionality ([0f17800](https://github.com/i701/sarlink-portal/commit/0f17800))
* Refactor user actions and authentication components ([490150f](https://github.com/i701/sarlink-portal/commit/490150f))
* Refactor user verification and data handling ([a3f0759](https://github.com/i701/sarlink-portal/commit/a3f0759))
* registration verification WIP ([470e845](https://github.com/i701/sarlink-portal/commit/470e845))
* remove prisma stuff ([c799362](https://github.com/i701/sarlink-portal/commit/c799362))
* remove prisma stuff ([91563cb](https://github.com/i701/sarlink-portal/commit/91563cb))
* remove test api route ([0943898](https://github.com/i701/sarlink-portal/commit/0943898))
* remove unused imports ([fcf4f37](https://github.com/i701/sarlink-portal/commit/fcf4f37))
* remove welcome banner after 4 seconds with animation ✨ ([6c5f848](https://github.com/i701/sarlink-portal/commit/6c5f848))
* rename walet page to transaction history 🔨 ([b32b61a](https://github.com/i701/sarlink-portal/commit/b32b61a))
* Show no agreements if there is no agreement in agreement page 🔨 ([950ac67](https://github.com/i701/sarlink-portal/commit/950ac67))
* swap trusted origins for .env variables ([7acd118](https://github.com/i701/sarlink-portal/commit/7acd118))
* switch to node ([7bfdc10](https://github.com/i701/sarlink-portal/commit/7bfdc10))
* temporary fix for build and remove previous auth related code ([e8296ae](https://github.com/i701/sarlink-portal/commit/e8296ae))
* TEMPORARY FIX TO TEST BUILD ([b932fcf](https://github.com/i701/sarlink-portal/commit/b932fcf))
* Update dependencies and refactor calendar component ([df820ff](https://github.com/i701/sarlink-portal/commit/df820ff))
* update logo to omega ([cd2cff7](https://github.com/i701/sarlink-portal/commit/cd2cff7))
* Update package.json for turbopack support, enhance AppSidebar with new icons, and add Textarea and a ([2b0bd51](https://github.com/i701/sarlink-portal/commit/2b0bd51))
* update packages ([8673b87](https://github.com/i701/sarlink-portal/commit/8673b87))
* update readme ([a242500](https://github.com/i701/sarlink-portal/commit/a242500))
* update README todos ✏️ ([40bf841](https://github.com/i701/sarlink-portal/commit/40bf841))
* Update user schema and forms to include address and consent fields ([4e78ff2](https://github.com/i701/sarlink-portal/commit/4e78ff2))
* wip ([7fadcd5](https://github.com/i701/sarlink-portal/commit/7fadcd5))
* WIP feat(admin-devices): enhance device management from admin with dynamic filters and improved bloc ([01b064a](https://github.com/i701/sarlink-portal/commit/01b064a))
* wth what was yarn doing here 😭 ([967a1d2](https://github.com/i701/sarlink-portal/commit/967a1d2))
* refactor: add topup expiry filter to the Topups component and simplify expired badge display in Topu ([5de4bb9](https://github.com/i701/sarlink-portal/commit/5de4bb9))
* refactor: add tryCatch utility for error handling, update device-related components and types, and c ([aa18484](https://github.com/i701/sarlink-portal/commit/aa18484))
* refactor: enhance authentication and signup flow with new providers, update middleware matcher, and ([99c5fef](https://github.com/i701/sarlink-portal/commit/99c5fef))
* refactor: enhance error handling and add pagination to device queries ([aff9d26](https://github.com/i701/sarlink-portal/commit/aff9d26))
* refactor: enhance parental control features and improve device blocking logic 🔨 ([c90b003](https://github.com/i701/sarlink-portal/commit/c90b003))
* refactor: enhance topup payment verification with improved state management and error handling 🔨 ([013befa](https://github.com/i701/sarlink-portal/commit/013befa))
* refactor: enhance topup status display and improve conditional rendering in TopupsTable component 🔨 ([8c94c92](https://github.com/i701/sarlink-portal/commit/8c94c92))
* refactor: implement device payment verification with useActionState hook 🔨 ([1a11f1a](https://github.com/i701/sarlink-portal/commit/1a11f1a))
* refactor: implement session checking utility, enhance device queries with session validation, and im ([daab793](https://github.com/i701/sarlink-portal/commit/daab793))
* refactor: improve state management and layout in Topup components 🔨 ([a61231c](https://github.com/i701/sarlink-portal/commit/a61231c))
* refactor: migrate authentication and signup flow to use external API and improve type safety ([0fd269d](https://github.com/i701/sarlink-portal/commit/0fd269d))
* refactor: remove layout error component from dashboard ([bb5eff8](https://github.com/i701/sarlink-portal/commit/bb5eff8))
* refactor: remove unused import and improve conditional rendering in block device dialog 🔨 ([8051b00](https://github.com/i701/sarlink-portal/commit/8051b00))
* refactor: remove unused import from device-card and devices-table components ([4e16c0a](https://github.com/i701/sarlink-portal/commit/4e16c0a))
* refactor: remove unused import of checkIdOrPhone in OTP verification page ([acb0ead](https://github.com/i701/sarlink-portal/commit/acb0ead))
* refactor: remove unused imports in TopupToPay component 🔨 ([8f9b4ba](https://github.com/i701/sarlink-portal/commit/8f9b4ba))
* refactor: remove unused imports in user payments page component 🔨 ([905b4fa](https://github.com/i701/sarlink-portal/commit/905b4fa))
* refactor: remove unused user verification function and clean up user type definitions 🔨 ([78673e0](https://github.com/i701/sarlink-portal/commit/78673e0))
* refactor: reorder imports and improve variable naming in CancelPaymentButton component 🔨 ([837cc35](https://github.com/i701/sarlink-portal/commit/837cc35))
* refactor: reorganize imports and enhance admin category filtering in AppSidebar 🔨 ([1549b20](https://github.com/i701/sarlink-portal/commit/1549b20))
* refactor: reorganize imports and improve session handling in various components 🔨 ([a6d844e](https://github.com/i701/sarlink-portal/commit/a6d844e))
* refactor: replace custom authentication middleware with NextAuth, remove unused authentication pages ([32bb01b](https://github.com/i701/sarlink-portal/commit/32bb01b))
* refactor: simplify FloatingInput and Textarea components by removing unnecessary forwardRef usage 🔨 ([5809e26](https://github.com/i701/sarlink-portal/commit/5809e26))
* refactor: streamline authentication flow by removing unused code, replacing custom auth utilities wi ([ef9f032](https://github.com/i701/sarlink-portal/commit/ef9f032))
* refactor: streamline package.json and tailwind.config.ts ([9e0d2d2](https://github.com/i701/sarlink-portal/commit/9e0d2d2))
* refactor: update authentication flow to use NextAuth, replace better-auth with axios for API calls, ([020d74c](https://github.com/i701/sarlink-portal/commit/020d74c))
* refactor: update authentication flow to use PIN instead of email/password, enhance OTP verification ([dbdc1df](https://github.com/i701/sarlink-portal/commit/dbdc1df))
* refactor: update axios client import, enhance device and payment handling, and add cancel payment bu ([7e49bf1](https://github.com/i701/sarlink-portal/commit/7e49bf1))
* refactor: update cancelPayment function to use PATCH method and new endpoint 🔨 ([e984705](https://github.com/i701/sarlink-portal/commit/e984705))
* refactor: update payment types and user interface, enhance error handling, and adjust API base URL ([9e2a2f4](https://github.com/i701/sarlink-portal/commit/9e2a2f4))
* refactor: update progress component styles and add radix-ui/react-progress dependency 🔨 ([cd1dba0](https://github.com/i701/sarlink-portal/commit/cd1dba0))
* refactor: update topup status handling in DynamicFilter and TopupsTable components ✨ ([378fb40](https://github.com/i701/sarlink-portal/commit/378fb40))
* refactor: use single seperate AccountInfomation component and integrate it into DevicesToPay and Top ([fa12cd7](https://github.com/i701/sarlink-portal/commit/fa12cd7))
* refactor(sidebar): re arrange sidebar links 🔨 ([1e2329e](https://github.com/i701/sarlink-portal/commit/1e2329e))
* feat: add "Top Ups" option to sidebar with appropriate permissions and icon ✨ ([89a35a9](https://github.com/i701/sarlink-portal/commit/89a35a9))
* feat: add admin check for device and payment pages; update session type to include is_admin property ([6aea548](https://github.com/i701/sarlink-portal/commit/6aea548))
* feat: add age validation in signup and update payment verification logic ([0c093f1](https://github.com/i701/sarlink-portal/commit/0c093f1))
* feat: add custom headers configuration to next.js config for stream/suspense support ✨ ([3e3b5f1](https://github.com/i701/sarlink-portal/commit/3e3b5f1))
* feat: add custom headers configuration to next.js config for stream/suspense support ✨ ([683d857](https://github.com/i701/sarlink-portal/commit/683d857))
* feat: add Dashboard layout main Error component for error handling in dashboard ([7750c5a](https://github.com/i701/sarlink-portal/commit/7750c5a))
* feat: add disabled prop to DevicesToPay component and update button state management ✨ ([9f9f2e4](https://github.com/i701/sarlink-portal/commit/9f9f2e4))
* feat: add dual range slider component and integrate it into dynamic filter for device management ([0157ecc](https://github.com/i701/sarlink-portal/commit/0157ecc))
* feat: add example environment configuration file and update .gitignore to include .env files ([378c120](https://github.com/i701/sarlink-portal/commit/378c120))
* feat: add expiry label to ExpiryCountDown component ✨ ([4797ee8](https://github.com/i701/sarlink-portal/commit/4797ee8))
* feat: add expiry label to ExpiryCountDown component in TopupPage ✨ ([9e25da7](https://github.com/i701/sarlink-portal/commit/9e25da7))
* feat: add floating label input component for enhanced form usability ✨ ([9c1d1c5](https://github.com/i701/sarlink-portal/commit/9c1d1c5))
* feat: add getProfile function and integrate user profile retrieval in payment and layout components ([ba91d2c](https://github.com/i701/sarlink-portal/commit/ba91d2c))
* feat: add loading skeleton for devices table and improve payment processing logic ([0d578c9](https://github.com/i701/sarlink-portal/commit/0d578c9))
* feat: add loading state and full-page loader component; update payment page and application layout t ([bed426a](https://github.com/i701/sarlink-portal/commit/bed426a))
* feat: add payment method filter to payments page ✨ ([13f0e72](https://github.com/i701/sarlink-portal/commit/13f0e72))
* feat: add payment method filter to payments page ✨ ([da7d101](https://github.com/i701/sarlink-portal/commit/da7d101))
* feat: add radio filter for topup expiry ✨ ([d499353](https://github.com/i701/sarlink-portal/commit/d499353))
* feat: add radio filter for topup expiry ✨ ([154226b](https://github.com/i701/sarlink-portal/commit/154226b))
* feat: add topup management features including topup creation, cancellation, and countdown timer ✨ ([f3328f7](https://github.com/i701/sarlink-portal/commit/f3328f7))
* feat: add vendor information to device components and update related UI elements ([8438ceb](https://github.com/i701/sarlink-portal/commit/8438ceb))
* feat: enforce strict TypeScript rules and add biome configuration ([79ecb62](https://github.com/i701/sarlink-portal/commit/79ecb62))
* feat: enhance device cart with cancel feature and improve payments table filters ([2834f23](https://github.com/i701/sarlink-portal/commit/2834f23))
* feat: enhance dual-range-slider handling in DynamicFilter component ✨ ([f4c34d3](https://github.com/i701/sarlink-portal/commit/f4c34d3))
* feat: enhance error handling and improve API response management across components ([6365a70](https://github.com/i701/sarlink-portal/commit/6365a70))
* feat: enhance MAC address guide with contact button for assistance ([c705add](https://github.com/i701/sarlink-portal/commit/c705add))
* feat: enhance OTP verification flow with error handling and response checks ([0b2dcfc](https://github.com/i701/sarlink-portal/commit/0b2dcfc))
* feat: enhance payment and topup interfaces with status and expiration details ✨ ([df2b3da](https://github.com/i701/sarlink-portal/commit/df2b3da))
* feat: enhance payment retrieval with flexible query parameters and add dynamic filters to payments p ([9fe3c3b](https://github.com/i701/sarlink-portal/commit/9fe3c3b))
* feat: enhance payment retrieval with flexible query parameters and add dynamic filters to payments p ([fa0d088](https://github.com/i701/sarlink-portal/commit/fa0d088))
* feat: implement add device functionality with validation and error handling; refactor related compon ([d2b2812](https://github.com/i701/sarlink-portal/commit/d2b2812))
* feat: implement AuthLayout component and streamline OTP verification forms with enhanced messaging ([a4ffb1e](https://github.com/i701/sarlink-portal/commit/a4ffb1e))
* feat: implement checkTempIdOrPhone function and update OTP verification logic ([f3f5800](https://github.com/i701/sarlink-portal/commit/f3f5800))
* feat: implement topup functionality with create, get, and cancel operations ✨ ([ee461bb](https://github.com/i701/sarlink-portal/commit/ee461bb))
* feat: implement user profile page and integrate profile fetching logic in AccountPopover and Applica ([a20c939](https://github.com/i701/sarlink-portal/commit/a20c939))
* feat: implement user registration and OTP verification flow with backend integration ([0f9d110](https://github.com/i701/sarlink-portal/commit/0f9d110))
* feat: implement user verification and rejection functionality with improved error handling ✨ ([255c03a](https://github.com/i701/sarlink-portal/commit/255c03a))
* feat: integrate backend mobile login and enhance user verification flow ([2cb2059](https://github.com/i701/sarlink-portal/commit/2cb2059))
* feat: integrate checkTempIdOrPhone in signup logic to validate temporary phone numbers ([923887b](https://github.com/i701/sarlink-portal/commit/923887b))
* feat: update authentication layout and forms for improved user experience; add new dependencies and ([406733b](https://github.com/i701/sarlink-portal/commit/406733b))
* feat: update cancelTopup API call to use PATCH method and enhance success message with topup details ([b9d8e56](https://github.com/i701/sarlink-portal/commit/b9d8e56))
* feat: update signup and OTP verification forms to enhance error handling and state management ([1e023eb](https://github.com/i701/sarlink-portal/commit/1e023eb))
* feat: update Topup interface with status and paid_at fields; modify table display for topup details ([ef7121f](https://github.com/i701/sarlink-portal/commit/ef7121f))
* feat(admin-topup): add description field to topup form and validation for amount ([3da668a](https://github.com/i701/sarlink-portal/commit/3da668a))
* feat(admin-topup): add description field to topup request payload ([a717c3d](https://github.com/i701/sarlink-portal/commit/a717c3d))
* feat(admin): add admin payment tables + filters✨ ([c34285c](https://github.com/i701/sarlink-portal/commit/c34285c))
* feat(admin): add usertable and update next config ✨ ([780239d](https://github.com/i701/sarlink-portal/commit/780239d))
* feat(agreements): implement agreement fetching and display with error handling ([171b1d4](https://github.com/i701/sarlink-portal/commit/171b1d4))
* feat(devices): add proper filter handling and update shadcn 🔨 ([59adaaf](https://github.com/i701/sarlink-portal/commit/59adaaf))
* feat(filters): replace existing filters with dynamic filters for improved user and device management ([9926de9](https://github.com/i701/sarlink-portal/commit/9926de9))
* feat(portal-ui): enhance user and device information display in admin and user devices tables ✨ ([3cd3bba](https://github.com/i701/sarlink-portal/commit/3cd3bba))
* feat(topups): add support for fetching all topups in getTopups function ✨ ([aedf7cd](https://github.com/i701/sarlink-portal/commit/aedf7cd))
* feat(user-agreement): implement user agreement upload functionality and update related components ✨ ([c2578f1](https://github.com/i701/sarlink-portal/commit/c2578f1))
* feat(user-topups): add user topups page with dynamic filtering and admin table integration ✨ ([1f6fe7d](https://github.com/i701/sarlink-portal/commit/1f6fe7d))
* feat(user-update-form): display field errors in user update form ✨ ([17aa65a](https://github.com/i701/sarlink-portal/commit/17aa65a))
* feat(user-verification): implement user verification functionality and update dialog UI ✨ ([dc3b5f9](https://github.com/i701/sarlink-portal/commit/dc3b5f9))
* feat(user): add admin topup functionality in user details page ✨ ([644e4f7](https://github.com/i701/sarlink-portal/commit/644e4f7))
* feat(user): implement user update functionality and enhance verification page UI ✨ ([8fac07b](https://github.com/i701/sarlink-portal/commit/8fac07b))
* feat(verify-user): add link to view user agreement and improve layout for user information ([eadd790](https://github.com/i701/sarlink-portal/commit/eadd790))
* feat(wallet): implement wallet transactions table and filtering options ✨ ([e0b76bb](https://github.com/i701/sarlink-portal/commit/e0b76bb))
* feat(wallet): update transaction type from CREDIT to TOPUP and display total debit/credit amounts ✨ ([e9af120](https://github.com/i701/sarlink-portal/commit/e9af120))
* chore: update package.json ♻️ ([71fc914](https://github.com/i701/sarlink-portal/commit/71fc914))
* chore: update package.json to add millify dependency and remove unnecessary newline ([f7122cb](https://github.com/i701/sarlink-portal/commit/f7122cb))
* chore: update README with new todos 🔧 ([fb3ad13](https://github.com/i701/sarlink-portal/commit/fb3ad13))
* chore: upgrade to tailwind v4 and add a generic filter for dynamic filter handling ([11ac852](https://github.com/i701/sarlink-portal/commit/11ac852))
* chore(package-lock): update brace-expansion to version 1.1.12 and form-data to version 4.0.4 ([5fda723](https://github.com/i701/sarlink-portal/commit/5fda723))
* chore(README): update task list to reflect completed features in parental control and admin controls ([8bcf481](https://github.com/i701/sarlink-portal/commit/8bcf481))
* chore(user-payments-table): remove unused imports 🔧 ([d7b8e4e](https://github.com/i701/sarlink-portal/commit/d7b8e4e))
* chore(user-update-form): remove unused import for cleaner code 🔧 ([7a02cb2](https://github.com/i701/sarlink-portal/commit/7a02cb2))
* bug: fix payment status display and force timezones in creation date in PaymentsTable and DevicesTo ([27a0b5d](https://github.com/i701/sarlink-portal/commit/27a0b5d))

View File

@@ -10,36 +10,38 @@ This is a web portal for SAR Link customers.
- [x] Add cancel feature to selected devices floating button
### Payments1
### Payments
- [x] Show payments table
- [x] Add all the filters for payment table (mobile responsive)
- [x] add slider range filter
- [ ] Fix bill formula linking for generated payments
### Parental Control
- [ ] Fix block device feature
- [ ] Add all the filters for parental control table (mobile responsive)
- [ ] Disable blocking if payment is pending or omit from the table if device payment is pending
- [x] Fix block device feature
- [x] Add all the filters for parental control table (mobile responsive)
- [x] Disable blocking if payment is pending or omit from the table if device payment is pending
### Topups
- [ ] add textarea in topup dialog for admin. if no detail given generate on backend otherwise take the text from text area
### Agreements
- [ ] Implement file upload for admin side
- [x] Implement file upload for admin side
- [ ] Add customer relavant documents in a grid view
- [ ] Add filtering by date for agreements
## Admin Controls
### Users
- [ ] Show users table
- [ ] Add all relavant filters for users table
- [ ] Verify or reject users with a custom message
- [x] Show users table
- [x] handle verify api no response case
- [x] Add all relavant filters for users table
- [x] Verify or reject users with a custom message
- [ ] Add functionality to send custom sms to users in user:id page
### User Devices
- [ ] Block or unblock from admin with custom message
- [ ] Blocking devices for client and admin using useActionState instead of client side button onClick handlers
- [ ] Show the devices table
- [ ] Add all relevant filters for user devices table
- [x] Block or unblock from admin with custom message
- [x] Blocking devices for client and admin using useActionState instead of client side button onClick handlers
- [x] Show the devices table
- [x] Add all relevant filters for user devices table
### User Payments
- [ ] Show user payments table
- [ ] Add relevant filters for user payments table
- [ ] Add computation of total value for filtered results
- [x] Show user payments table
- [x] Add relevant filters for user payments table

View File

@@ -1,5 +1,7 @@
"use server";
import { redirect } from "next/navigation";
import { z } from "zod";
import { signUpFormSchema } from "@/lib/schemas";
import {
backendRegister,
@@ -7,8 +9,7 @@ import {
checkTempIdOrPhone,
} from "@/queries/authentication";
import { handleApiResponse, tryCatch } from "@/utils/tryCatch";
import { redirect } from "next/navigation";
import { z } from "zod";
const formSchema = z.object({
phoneNumber: z
.string()
@@ -22,9 +23,10 @@ export type FilterUserResponse = {
export type FilterTempUserResponse = {
ok: boolean;
otp_verified: boolean;
t_verified: boolean;
};
export async function signin(previousState: ActionState, formData: FormData) {
export async function signin(_previousState: ActionState, formData: FormData) {
const phoneNumber = formData.get("phoneNumber") as string;
const result = formSchema.safeParse({ phoneNumber });
console.log(phoneNumber);

View File

@@ -1,18 +1,24 @@
"use server";
import { revalidatePath } from "next/cache";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth";
import type {
ApiError,
ApiResponse,
NewPayment,
Payment,
Topup,
} from "@/lib/backend-types";
import type { User } from "@/lib/types/user";
import { checkSession } from "@/utils/session";
import { handleApiResponse, tryCatch } from "@/utils/tryCatch";
import { getServerSession } from "next-auth";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import type { TopupResponse } from "@/lib/types";
import { handleApiResponse } from "@/utils/tryCatch";
type GenericGetResponseProps = {
offset?: number;
limit?: number;
page?: number;
[key: string]: string | number | undefined;
};
export async function createPayment(data: NewPayment) {
const session = await getServerSession(authOptions);
@@ -43,6 +49,22 @@ export async function createPayment(data: NewPayment) {
return payment;
}
export async function createTopup(data: { amount: number }) {
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
body: JSON.stringify(data),
},
);
return handleApiResponse<Topup>(response, "createTopup");
}
export async function getPayment({ id }: { id: string }) {
const session = await getServerSession(authOptions);
const response = await fetch(
@@ -68,10 +90,25 @@ export async function getPayment({ id }: { id: string }) {
return data;
}
export async function getPayments() {
type GetPaymentProps = {
[key: string]: string | number | undefined; // Allow additional properties for flexibility
};
export async function getPayments(
params: GetPaymentProps,
allPayments = false,
) {
// Build query string from all defined params
const query = Object.entries(params)
.filter(([_, value]) => value !== undefined && value !== "")
.map(
([key, value]) =>
`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`,
)
.join("&");
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/`,
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/?${query}&all_payments=${allPayments}`,
{
method: "GET",
headers: {
@@ -92,27 +129,77 @@ export async function getPayments() {
return data;
}
export async function cancelPayment({ id }: { id: string }) {
export async function getTopups(
params: GenericGetResponseProps,
all_topups = false,
) {
// Build query string from all defined params
const query = Object.entries(params)
.filter(([_, value]) => value !== undefined && value !== "")
.map(
([key, value]) =>
`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`,
)
.join("&");
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/${id}/delete/`,
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/?${query}&all_topups=${all_topups}`,
{
method: "DELETE",
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
},
);
if (!response.ok) {
const errorData = (await response.json()) as ApiError;
const errorMessage =
errorData.message || errorData.detail || "An error occurred.";
const error = new Error(errorMessage);
(error as ApiError & { details?: ApiError }).details = errorData; // Attach the errorData to the error object
throw error;
}
return { message: "Payment successfully canceled." };
return handleApiResponse<ApiResponse<Topup>>(response, "getTopups");
}
export async function getTopup({ id }: { id: string }) {
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/${id}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
},
);
return handleApiResponse<Topup>(response, "getTopup");
}
export async function cancelTopup({ id }: { id: string }) {
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/${id}/cancel/`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
},
);
return handleApiResponse<Topup>(response, "cancelTopup");
}
export async function cancelPayment({ id }: { id: string }) {
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/${id}/cancel/`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
},
);
return handleApiResponse<Payment>(response, "cancelPayment");
}
type UpdatePayment = {
@@ -142,19 +229,155 @@ export async function verifyPayment({ id, method }: UpdatePayment) {
return handleApiResponse<Payment>(response, "updatePayment");
}
export type VerifyDevicePaymentState = {
payment?: Payment;
message: string;
success: boolean;
fieldErrors: Record<string, string>;
payload?: FormData;
};
export async function getProfile() {
export async function verifyDevicePayment(
_prevState: VerifyDevicePaymentState,
formData: FormData,
): Promise<VerifyDevicePaymentState> {
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/profile/`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
},
);
return handleApiResponse<User>(response, "getProfile");
// Get the payment ID and method from the form data
const paymentId = formData.get("paymentId") as string;
const method = formData.get("method") as "TRANSFER" | "WALLET";
if (!paymentId) {
return {
message: "Payment ID is required",
success: false,
fieldErrors: { paymentId: "Payment ID is required" },
};
}
if (!method) {
return {
message: "Payment method is required",
success: false,
fieldErrors: { method: "Payment method is required" },
};
}
try {
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/${paymentId}/verify/`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
body: JSON.stringify({
method,
}),
},
);
const result = await handleApiResponse<Payment>(
response,
"verifyDevicePayment",
);
revalidatePath("/payments/[paymentId]", "page");
return {
message:
method === "WALLET"
? "Payment completed successfully using wallet!"
: "Payment verification successful!",
success: true,
fieldErrors: {},
payment: result,
};
} catch (error: unknown) {
if (error instanceof Error) {
return {
message:
error.message || "Payment verification failed. Please try again.",
success: false,
fieldErrors: {},
};
} else {
return {
message: "Payment verification failed.",
success: false,
fieldErrors: {},
};
}
}
}
export type VerifyTopupPaymentState = {
transaction?: {
sourceBank: string;
trxDate: string;
};
message: string;
success: boolean;
fieldErrors: Record<string, string>;
payload?: FormData;
};
export async function verifyTopupPayment(
_prevState: VerifyTopupPaymentState,
formData: FormData,
): Promise<VerifyTopupPaymentState> {
const session = await getServerSession(authOptions);
// Get the topup ID from the form data or use a hidden input
const topupId = formData.get("topupId") as string;
if (!topupId) {
return {
message: "Topup ID is required",
success: false,
fieldErrors: { topupId: "Topup ID is required" },
};
}
try {
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/${topupId}/verify/`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
},
);
const result = await handleApiResponse<TopupResponse>(
response,
"verifyTopupPayment",
);
revalidatePath("/top-ups/[topupId]", "page");
return {
message: result.message || "Topup payment verified successfully",
success: true,
fieldErrors: {},
transaction: result.transaction,
};
} catch (error: unknown) {
if (error instanceof Error) {
return {
message:
error.message || "Please check your payment details and try again.",
success: false,
fieldErrors: {},
};
} else {
return {
message: "Topup verification failed.",
success: false,
fieldErrors: {},
};
}
}
}

View File

@@ -1,123 +1,302 @@
"use server";
import { VerifyUserDetails } from "@/lib/person";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { CreateClient } from "./ninja/client";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth";
import type { RejectUserFormState } from "@/components/user/user-reject-dialog";
import type { ApiError } from "@/lib/backend-types";
import type { User } from "@/lib/types/user";
import { handleApiResponse } from "@/utils/tryCatch";
export async function VerifyUser(userId: string) {
// const user = await prisma.user.findUnique({
// where: {
// id: userId,
// },
// include: {
// atoll: true,
// island: true,
// },
// });
// if (!user) {
// throw new Error("User not found");
// }
// const isValidPerson = await VerifyUserDetails({ user });
// if (!isValidPerson)
// throw new Error("The user details does not match national data.");
// if (isValidPerson) {
// await prisma.user.update({
// where: {
// id: userId,
// },
// data: {
// verified: true,
// },
// });
// const ninjaClient = await CreateClient({
// group_settings_id: "",
// address1: "",
// city: user.atoll?.name || "",
// state: user.island?.name || "",
// postal_code: "",
// country_id: "462",
// address2: user.address || "",
// contacts: {
// first_name: user.name?.split(" ")[0] || "",
// last_name: user.name?.split(" ")[1] || "",
// email: user.email || "",
// phone: user.phoneNumber || "",
// send_email: false,
// custom_value1: user.dob?.toISOString().split("T")[0] || "",
// custom_value2: user.id_card || "",
// custom_value3: "",
// },
// });
// }
// revalidatePath("/users");
}
type VerifyUserResponse =
| {
ok: boolean;
mismatch_fields: string[] | null;
error: string | null;
detail: string | null;
}
| {
message: boolean;
};
export async function verifyUser(userId: string) {
const session = await getServerSession(authOptions);
if (!session?.apiToken) {
return { ok: false, error: "Not authenticated" } as const;
}
export async function Rejectuser({
userId,
reason,
}: { userId: string; reason: string }) {
// const user = await prisma.user.findUnique({
// where: {
// id: userId,
// },
// });
// if (!user) {
// throw new Error("User not found");
// }
// await SendUserRejectionDetailSMS({
// details: reason,
// phoneNumber: user.phoneNumber,
// });
// await prisma.user.delete({
// where: {
// id: userId,
// },
// });
revalidatePath("/users");
redirect("/users");
}
export const SendUserRejectionDetailSMS = async ({
details,
phoneNumber,
}: {
details: string;
phoneNumber: string;
}) => {
try {
const respose = await fetch(`${process.env.SMS_API_BASE_URL}/api/sms`, {
const r = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/${userId}/verify/`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session.apiToken}`,
},
},
);
const body = (await r.json().catch(() => ({}))) as VerifyUserResponse & {
message?: string;
detail?: string;
};
if (!r.ok) {
const msg = body?.message || body?.detail || "User verification failed";
return {
ok: false,
error: msg,
mismatch_fields: body?.mismatch_fields || null,
} as const;
}
return { ok: true, data: body } as const;
} catch (err) {
return { ok: false, error: (err as Error).message } as const;
}
}
export async function getProfile() {
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/profile/`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
},
);
return handleApiResponse<User>(response, "getProfile");
}
export async function rejectUser(
_prevState: RejectUserFormState,
formData: FormData,
): Promise<RejectUserFormState> {
const userId = formData.get("userId") as string;
const rejection_details = formData.get("rejection_details") as string;
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/${userId}/reject/`,
{
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
body: JSON.stringify({ rejection_details: rejection_details }),
},
);
if (!response.ok) {
const errorData = await response.json();
throw new Error(
errorData.message || errorData.detail || "Failed to reject user",
);
}
// Handle 204 No Content response (successful deletion)
if (response.status === 204) {
revalidatePath("/users");
redirect("/users");
}
revalidatePath("/users");
const error = await response.json();
return {
message:
(error as ApiError).message ||
(error as ApiError).detail ||
"An unexpected error occurred.",
fieldErrors: {},
payload: formData,
};
}
export type UpdateUserFormState = {
message: string;
fieldErrors?: {
id_card?: string[];
first_name?: string[];
last_name?: string[];
dob?: string[];
mobile?: string[];
address?: string[];
};
payload?: FormData;
};
export async function updateUser(
_prevState: UpdateUserFormState,
formData: FormData,
): Promise<UpdateUserFormState> {
const userId = formData.get("userId") as string;
const data: Record<string, string | number | boolean> = {};
for (const [key, value] of formData.entries()) {
if (value !== undefined && value !== "") {
data[key] = typeof value === "number" ? value : String(value);
}
}
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/${userId}/update/`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
body: JSON.stringify(data),
},
);
const json = await response.json();
if (!response.ok) {
const isFieldErrorObject =
json &&
typeof json === "object" &&
!Array.isArray(json) &&
Object.values(json).every(
(val) => Array.isArray(val) && val.every((v) => typeof v === "string"),
);
return {
message:
json.message ||
json.detail ||
(isFieldErrorObject
? "Please correct the highlighted fields."
: "An error occurred while updating the user."),
fieldErrors: isFieldErrorObject ? json : json.field_errors || {},
payload: formData,
};
}
// Successful update
const updatedUser = json as User;
revalidatePath("/users/[userId]/update", "page");
revalidatePath("/users/[userId]/verify", "page");
return {
...updatedUser,
message: "User updated successfully",
};
}
export async function updateUserAgreement(
_prevState: UpdateUserFormState,
formData: FormData,
): Promise<UpdateUserFormState> {
const userId = formData.get("userId") as string;
// Remove userId from formData before sending to API
const apiFormData = new FormData();
for (const [key, value] of formData.entries()) {
if (key !== "userId") {
apiFormData.append(key, value);
}
}
console.log({ apiFormData });
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/${userId}/agreement/`,
{
method: "PUT",
headers: {
Authorization: `Token ${session?.apiToken}`,
},
body: apiFormData,
},
);
console.log("response in update user agreement action", response);
if (!response.ok) {
const errorData = await response.json();
return {
message:
errorData.message ||
errorData.detail ||
"An error occurred while updating the user agreement.",
fieldErrors: errorData.field_errors || {},
payload: formData,
};
}
const updatedUserAgreement = (await response.json()) as { agreement: string };
revalidatePath("/users/[userId]/update", "page");
revalidatePath("/users/[userId]/verify", "page");
revalidatePath("/users/[userId]/agreement", "page");
return {
...updatedUserAgreement,
message: "User agreement updated successfully",
};
}
export type AddTopupFormState = {
status: boolean;
message: string;
fieldErrors?: {
amount?: string[];
description?: string[];
};
payload?: FormData;
};
export async function adminUserTopup(
_prevState: AddTopupFormState,
formData: FormData,
): Promise<AddTopupFormState> {
const user_id = formData.get("user_id") as string;
const amount = formData.get("amount") as string;
const description = formData.get("description") as string;
const session = await getServerSession(authOptions);
if (!amount) {
return {
status: false,
message: "Amount is required",
fieldErrors: { amount: ["Amount is required"], description: [] },
payload: formData,
};
}
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/billing/admin-topup/`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.SMS_API_KEY}`,
Authorization: `Token ${session?.apiToken}`,
},
body: JSON.stringify({
check_delivery: false,
number: phoneNumber,
message: details,
amount: Number.parseInt(amount),
user_id: Number.parseInt(user_id),
description,
}),
});
const data = await respose.json();
console.log(data);
return data;
} catch (error) {
console.error(error);
},
);
if (!response.ok) {
const errorData = await response.json();
return {
status: false,
message:
errorData.message ||
errorData.detail ||
"An error occurred while topping up the user.",
fieldErrors: {},
payload: formData,
};
}
};
export async function AddDevice({
name,
mac_address,
user_id,
}: { name: string; mac_address: string; user_id: string }) {
// const newDevice = await prisma.device.create({
// data: {
// name: name,
// mac: mac_address,
// userId: user_id,
// },
// });
revalidatePath("/devices");
// return newDevice;
revalidatePath("/users/[userId]/topup", "page");
return {
status: true,
message: "User topped up successfully",
fieldErrors: {},
payload: formData,
};
}

View File

@@ -1,7 +1,8 @@
export default function AuthLayout({
children,
}: { children: React.ReactNode }) {
}: {
children: React.ReactNode;
}) {
return (
<div className="bg-gray-100 dark:bg-black w-full h-screen flex items-center justify-center font-sans">
{children}

View File

@@ -11,7 +11,7 @@ export default async function VerifyRegistrationOTP({
}: {
searchParams: Promise<{ phone_number: string }>;
}) {
const session = await getServerSession(authOptions)
const session = await getServerSession(authOptions);
if (session) {
// If the user is already logged in, redirect them to the home page
return redirect("/");

View File

@@ -1,13 +1,29 @@
import React from 'react'
import { getProfile } from "@/actions/user-actions";
import { AgreementCard } from "@/components/agreement-card";
import { tryCatch } from "@/utils/tryCatch";
export default function Agreements() {
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">
Agreements
</h3>
</div>
</div>
)
export default async function Agreements() {
const [error, profile] = await tryCatch(getProfile());
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">Agreements</h3>
</div>
<div className="grid grid-cols-1">
{error ? (
<div className="text-red-500">
An error occurred while fetching agreements: {error.message}
</div>
) : (
<div>
{profile.agreement ? (
<AgreementCard agreement={profile.agreement} />
) : (
<div className="text-gray-500">No agreement found.</div>
)}
</div>
)}
</div>
</div>
);
}

View File

@@ -1,8 +1,6 @@
import FullPageLoader from '@/components/full-page-loader'
import React from 'react'
import FullPageLoader from "@/components/full-page-loader";
import React from "react";
export default function Loading() {
return (
<FullPageLoader />
)
return <FullPageLoader />;
}

View File

@@ -0,0 +1,33 @@
import { Skeleton } from "@/components/ui/skeleton";
export default function DeviceLoading() {
return (
<div>
<div className="flex items-center justify-between title-bg title-bg ring-2 ring-sarLinkOrange/50 rounded-lg p-4">
<div className="flex flex-col space-y-2 justify-between items-start">
<Skeleton className="h-8 w-44" />
<Skeleton className="h-4 w-40" />
<Skeleton className="h-4 w-48" />
</div>
<div className="flex items-center gap-2 flex-col">
<Skeleton className="h-10 w-32" />
</div>
</div>
<div
id="user-filters"
className=" py-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
>
<Skeleton className="h-10 sm:w-64" />
{/* <Filter
options={sortfilterOptions}
defaultOption="asc"
queryParamKey="sortBy"
/> */}
</div>
{/* <Suspense key={query} fallback={"loading...."}>
<DevicesTable searchParams={searchParams} />
</Suspense> */}
</div>
);
}

View File

@@ -1,68 +1,73 @@
import { redirect } from "next/navigation";
import ClientErrorMessage from "@/components/client-error-message";
import Search from "@/components/search";
import { Badge } from "@/components/ui/badge";
import { getDevice } from "@/queries/devices";
import { tryCatch } from "@/utils/tryCatch";
import { redirect } from "next/navigation";
export default async function DeviceDetails({
params,
params,
}: {
params: Promise<{ deviceId: string }>;
params: Promise<{ deviceId: string }>;
}) {
const deviceId = (await params)?.deviceId;
const [error, device] = await tryCatch(getDevice({ deviceId: deviceId }));
if (error) {
// Handle specific actions for certain errors, but reuse the error message
if (error.message === "UNAUTHORIZED") {
redirect("/auth/signin");
} else {
// For all other errors, display the error message directly
return <ClientErrorMessage message={error.message} />;
}
}
if (!device) return null;
const deviceId = (await params)?.deviceId;
const [error, device] = await tryCatch(getDevice({ deviceId: deviceId }));
if (error) {
// Handle specific actions for certain errors, but reuse the error message
if (error.message === "UNAUTHORIZED") {
redirect("/auth/signin");
} else {
// For all other errors, display the error message directly
return <ClientErrorMessage message={error.message} />;
}
}
if (!device) return null;
return (
<div>
<div className="flex items-center justify-between title-bg title-bg ring-2 ring-sarLinkOrange/50 rounded-lg p-2">
<div className="flex flex-col justify-between items-start">
<h3 className="text-2xl text-sarLinkOrange font-bold">
{device?.name}
</h3>
<Badge variant={"secondary"}>{device?.mac}</Badge>
<p className="text-muted-foreground text-sm mt-2">
Device active until{" "}
{new Date(device?.expiry_date || "").toLocaleDateString("en-US", {
month: "short",
day: "2-digit",
year: "numeric",
})}
</p>
</div>
<div className="flex items-center gap-2 flex-col">
{device?.expiry_date && new Date() < new Date(device.expiry_date) && (
<p className="text-base font-semibold font-mono w-full text-center px-2 p-1 rounded-md bg-green-500/10 text-green-900 dark:text-green-400">
ACTIVE
</p>
)}
</div>
</div>
return (
<div>
<div className="flex items-center justify-between title-bg title-bg ring-2 ring-sarLinkOrange/50 rounded-lg p-4">
<div className="flex flex-col justify-between items-start">
<h3 className="text-2xl text-sarLinkOrange motion-preset-slide-down-md font-bold">
{device?.name}
</h3>
<Badge
className="motion-preset-slide-down-md motion-delay-75"
variant={"secondary"}
>
{device?.mac}
</Badge>
<p className="text-muted-foreground text-sm mt-2 motion-preset-slide-down-md motion-delay-100">
Device active until{" "}
{new Date(device?.expiry_date || "").toLocaleDateString("en-US", {
month: "short",
day: "2-digit",
year: "numeric",
})}
</p>
</div>
<div className="flex items-center gap-2 flex-col motion-preset-fade">
{device?.expiry_date && new Date() < new Date(device.expiry_date) && (
<p className="text-base font-semibold font-mono w-full text-center px-2 p-1 rounded-md bg-green-500/10 text-green-900 dark:text-green-400">
ACTIVE
</p>
)}
</div>
</div>
<div
id="user-filters"
className=" py-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
>
<Search />
{/* <Filter
<div
id="user-filters"
className=" py-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
>
<Search />
{/* <Filter
options={sortfilterOptions}
defaultOption="asc"
queryParamKey="sortBy"
/> */}
</div>
{/* <Suspense key={query} fallback={"loading...."}>
</div>
{/* <Suspense key={query} fallback={"loading...."}>
<DevicesTable searchParams={searchParams} />
</Suspense> */}
</div>
);
</div>
);
}

View File

@@ -1,78 +0,0 @@
import { Skeleton } from "@/components/ui/skeleton";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { cn } from "@/lib/utils";
export default function DevicesTableSkeleton() {
return (
<>
<div className="hidden sm:block">
<Table className="overflow-scroll">
<TableCaption>Table of all devices.</TableCaption>
<TableHeader>
<TableRow>
<TableHead>Device Name</TableHead>
<TableHead>MAC Address</TableHead>
<TableHead>#</TableHead>
</TableRow>
</TableHeader>
<TableBody className="overflow-scroll">
{Array.from({ length: 10 }).map((_, i) => (
<TableRow key={`${i + 1}`}>
<TableCell>
<Skeleton className="w-full h-10 rounded" />
</TableCell>
<TableCell>
<Skeleton className="w-full h-10 rounded" />
</TableCell>
<TableCell>
<Skeleton className="w-full h-10 rounded" />
</TableCell>
</TableRow>
))}
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={2}>
<Skeleton className="w-full h-4 rounded" />
</TableCell>
<TableCell className="text-muted-foreground">
<Skeleton className="w-20 h-4 rounded" />
</TableCell>
</TableRow>
</TableFooter>
</Table>
</div>
<div className="sm:hidden my-4">
{Array.from({ length: 10 }).map((_, i) => (
<DeviceCardSkeleton key={`${i + 1}`} />
))}
</div>
</>
);
}
function DeviceCardSkeleton() {
return (
<div
className={cn(
"flex text-sm justify-between items-center my-2 p-4 border rounded-md bg-gray-100",
)}
>
<div className="font-semibold flex w-full flex-col items-start gap-2 mb-2 relative">
<Skeleton className="w-32 h-6" />
<Skeleton className="w-36 h-6" />
<Skeleton className="w-32 h-4" />
<Skeleton className="w-40 h-8" />
</div>
</div>
);
}

View File

@@ -0,0 +1,25 @@
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import { Skeleton } from "@/components/ui/skeleton";
export default function LoadingComponent() {
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<Skeleton className="w-48 h-8" />
<Skeleton className="w-36 h-8" />
</div>
<div>
<Skeleton className="w-full rounded-md mt-5 mb-6 sm:w-48 h-9" />
</div>
<div
id="user-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-endO"
>
<DevicesTableSkeleton
headers={["Device Name", "Mac Address", "Vendor", "#"]}
length={10}
/>
</div>
</div>
);
}

View File

@@ -1,10 +1,10 @@
import { getServerSession } from "next-auth";
import { Suspense } from "react";
import { authOptions } from "@/app/auth";
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import { DevicesTable } from "@/components/devices-table";
import DynamicFilter from "@/components/generic-filter";
import AddDeviceDialogForm from "@/components/user/add-device-dialog";
import DevicesTableSkeleton from "./device-table-skeleton";
export default async function Devices({
searchParams,
@@ -49,11 +49,19 @@ export default async function Devices({
label: "Vendor",
type: "string",
placeholder: "Enter vendor name",
}
},
]}
/>
</div>
<Suspense key={query || page} fallback={<DevicesTableSkeleton />}>
<Suspense
key={query || page}
fallback={
<DevicesTableSkeleton
headers={["Device Name", "Mac Address", "Vendor", "#"]}
length={10}
/>
}
>
<DevicesTable parentalControl={false} searchParams={searchParams} />
</Suspense>
</div>

View File

@@ -6,9 +6,9 @@ export default function DashboardLayout({
}: Readonly<{
children: React.ReactNode;
}>) {
return <ApplicationLayout>
<QueryProvider>
{children}
</QueryProvider>
</ApplicationLayout>;
return (
<ApplicationLayout>
<QueryProvider>{children}</QueryProvider>
</ApplicationLayout>
);
}

View File

@@ -0,0 +1,25 @@
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import { Skeleton } from "@/components/ui/skeleton";
export default function LoadingComponent() {
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<Skeleton className="w-48 h-8" />
<Skeleton className="w-20 h-8" />
</div>
<div>
<Skeleton className="w-full rounded-md mt-5 mb-6 sm:w-48 h-9" />
</div>
<div
id="user-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-endO"
>
<DevicesTableSkeleton
headers={["Device Name", "Mac Address", "Vendor", "#"]}
length={10}
/>
</div>
</div>
);
}

View File

@@ -1,41 +1,72 @@
import { Suspense } from "react";
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import { DevicesTable } from "@/components/devices-table";
import Search from "@/components/search";
import DynamicFilter from "@/components/generic-filter";
export default async function ParentalControl({
searchParams,
searchParams,
}: {
searchParams: Promise<{
page: number;
sortBy: string;
status: string;
}>;
searchParams: Promise<{
page: number;
sortBy: string;
status: string;
}>;
}) {
const parentalControlFilters = {
is_active: "true",
has_a_pending_payment: "false",
};
const parentalControlFilters = {
is_active: "true",
has_a_pending_payment: "false",
};
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">Parental Control</h3>
</div>
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">Parental Control</h3>
</div>
<div
id="user-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
>
<Search />
</div>
<Suspense key={(await searchParams).page} fallback={"loading...."}>
<DevicesTable
parentalControl={true}
searchParams={searchParams}
additionalFilters={parentalControlFilters}
/>
</Suspense>
</div>
);
<div
id="user-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
>
<DynamicFilter
description="Filter devices by name, MAC address, or vendor."
title="Device Filter"
inputs={[
{
name: "name",
label: "Device Name",
type: "string",
placeholder: "Enter device name",
},
{
name: "mac",
label: "MAC Address",
type: "string",
placeholder: "Enter MAC address",
},
{
name: "vendor",
label: "Vendor",
type: "string",
placeholder: "Enter vendor name",
},
]}
/>{" "}
</div>
<Suspense
key={(await searchParams).page}
fallback={
<DevicesTableSkeleton
headers={["Device Name", "Mac Address", "Vendor", "#"]}
length={10}
/>
}
>
<DevicesTable
parentalControl={true}
searchParams={searchParams}
additionalFilters={parentalControlFilters}
/>
</Suspense>
</div>
);
}

View File

@@ -0,0 +1,63 @@
import { Skeleton } from "@/components/ui/skeleton";
import {
Table,
TableBody,
TableCell,
TableFooter,
TableRow,
} from "@/components/ui/table";
export default function PaymentLoading() {
return (
<div className="mx-2">
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-4 mb-4">
<Skeleton className="h-8 w-48" />
</div>
<div className="flex flex-col gap-4 mt-7 w-full border rounded-md border-dashed title-bg py-3 px-2 mb-3">
<Skeleton className="h-5 w-36" />
</div>
<div className="flex flex-col gap-3 w-full">
{Array.from({ length: 1 }).map((_, i) => (
<Skeleton
key={`${i + 1}`}
className="w-full border border-gray-300 h-13 rounded-sm"
/>
))}
<div className="pb-4 w-full gap-4 flex sm:flex-row flex-col items-start justify-start">
<div className="my-1 w-full flex items-center justify-between p-2 text-sm text-foreground border rounded">
<Table>
<TableBody className="">
<TableRow>
<TableCell>Payment created</TableCell>
<TableCell className="text-right">
<Skeleton className="h-5 inline-block w-24" />
</TableCell>
</TableRow>
<TableRow>
<TableCell>Total Devices</TableCell>
<TableCell className="text-right text-xl">
<Skeleton className="h-5 w-24 inline-block" />
</TableCell>
</TableRow>
<TableRow>
<TableCell>Duration</TableCell>
<TableCell className="text-right text-xl">
<Skeleton className="h-5 w-24 inline-block" />
</TableCell>
</TableRow>
</TableBody>
<TableFooter>
<TableRow className="">
<TableCell colSpan={1}>Total Due</TableCell>
<TableCell className="text-right text-3xl font-bold">
<Skeleton className="h-5 w-24 inline-block" />
</TableCell>
</TableRow>
</TableFooter>
</Table>
</div>
</div>
</div>
</div>
);
}

View File

@@ -1,59 +1,86 @@
import { getPayment, getProfile } from "@/actions/payment";
import { redirect } from "next/navigation";
import { getPayment } from "@/actions/payment";
import { getProfile } from "@/actions/user-actions";
import CancelPaymentButton from "@/components/billing/cancel-payment-button";
import ExpiryCountDown from "@/components/billing/expiry-time-countdown";
import ClientErrorMessage from "@/components/client-error-message";
import DevicesToPay from "@/components/devices-to-pay";
import { Button } from "@/components/ui/button";
import { TextShimmer } from "@/components/ui/text-shimmer";
import { cn } from "@/lib/utils";
import { tryCatch } from "@/utils/tryCatch";
import { redirect } from "next/navigation";
export default async function PaymentPage({
params,
params,
}: {
params: Promise<{ paymentId: string }>;
params: Promise<{ paymentId: string }>;
}) {
const paymentId = (await params).paymentId;
const [error, payment] = await tryCatch(getPayment({ id: paymentId }));
if (error) {
if (error.message === "Invalid token.") redirect("/auth/signin");
return <ClientErrorMessage message={error.message} />;
}
const [userError, userProfile] = await tryCatch(getProfile());
if (userError) {
if (userError.message === "Invalid token.") redirect("/auth/signin");
return <ClientErrorMessage message={userError.message} />;
}
const paymentId = (await params).paymentId;
const [error, payment] = await tryCatch(getPayment({ id: paymentId }));
if (error) {
if (error.message === "Invalid token.") redirect("/auth/signin");
return <ClientErrorMessage message={error.message} />;
}
const [userError, userProfile] = await tryCatch(getProfile());
if (userError) {
if (userError.message === "Invalid token.") redirect("/auth/signin");
return <ClientErrorMessage message={userError.message} />;
}
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-4 mb-4 mx-2">
<h3 className="text-sarLinkOrange text-2xl">Payment</h3>
<div className="flex flex-col gap-4 items-end w-full">
<Button
disabled
className={cn(
"rounded-md opacity-100! uppercase font-semibold",
payment?.paid
? "text-green-500 bg-green-500/20"
: "text-yellow-500 bg-yellow-900",
)}
>
{payment?.paid ? "Paid" : "Pending"}
</Button>
{!payment.paid && (
<CancelPaymentButton paymentId={paymentId} />
)}
</div>
</div>
<div
id="user-filters"
className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
>
<DevicesToPay
user={userProfile || undefined}
payment={payment || undefined}
/>
</div>
</div>
);
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-4 mb-4 mx-2">
<h3 className="text-sarLinkOrange text-2xl">Payment</h3>
<div className="flex flex-col gap-4 items-end w-full">
{!payment.is_expired &&
payment.paid &&
payment.status !== "PENDING" && (
<Button
disabled
className={cn(
"rounded-md opacity-100! uppercase font-semibold",
payment?.paid
? "text-green-900 bg-green-500/20"
: "text-inherit bg-yellow-400",
)}
>
{payment.status}
</Button>
)}
{payment.status === "PENDING" && !payment.is_expired && (
<Button>
<TextShimmer>Payment Pending</TextShimmer>{" "}
</Button>
)}
{!payment.paid &&
(payment.is_expired ? (
<Button
disabled
className="rounded-md opacity-100! uppercase font-semibold text-red-500 bg-red-500/20"
>
Payment Expired
</Button>
) : payment.status === "PENDING" ? (
<CancelPaymentButton paymentId={paymentId} />
) : payment.status === "CANCELLED" ? (
<Button disabled>Payment Cancelled</Button>
) : (
""
))}
</div>
</div>
{!payment.paid && (
<ExpiryCountDown expiryLabel="Payment" expiresAt={payment.expires_at} />
)}
<div
id="user-device-payments"
className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
>
<DevicesToPay
disabled={payment.paid || payment.is_expired}
user={userProfile || undefined}
payment={payment || undefined}
/>
</div>
</div>
);
}

View File

@@ -0,0 +1,25 @@
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import { Skeleton } from "@/components/ui/skeleton";
export default function LoadingComponent() {
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<Skeleton className="w-48 h-8" />
<Skeleton className="w-20 h-8" />
</div>
<div>
<Skeleton className="w-full rounded-md mt-5 mb-6 sm:w-48 h-9" />
</div>
<div
id="user-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-endO"
>
<DevicesTableSkeleton
headers={["Details", "Duration", "Status", "Amount"]}
length={10}
/>
</div>
</div>
);
}

View File

@@ -1,6 +1,7 @@
import { Suspense } from "react";
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import DynamicFilter from "@/components/generic-filter";
import { PaymentsTable } from "@/components/payments-table";
import Search from "@/components/search";
export default async function Payments({
searchParams,
@@ -8,24 +9,79 @@ export default async function Payments({
searchParams: Promise<{
query: string;
page: number;
sortBy: string;
status: string;
}>;
}) {
const query = (await searchParams)?.query || "";
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">My Payments</h3>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-3 mb-4">
<h3 className="text-sarLinkOrange text-2xl">My Subscriptions</h3>
</div>
<div
id="user-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
>
<Search />
<DynamicFilter
inputs={[
{
label: "Payment",
name: "paid",
type: "radio-group",
options: [
{
label: "All",
value: "",
},
{
label: "Paid",
value: "true",
},
{
label: "Unpaid",
value: "false",
},
],
},
{
label: "Payment Method",
name: "method",
type: "radio-group",
options: [
{
label: "All",
value: "",
},
{
label: "Transfer",
value: "TRANSFER",
},
{
label: "Wallet",
value: "WALLET",
},
],
},
{
label: "Number of months",
name: "number_of_months",
type: "dual-range-slider",
min: 1,
max: 12,
step: 1,
},
]}
/>{" "}
</div>
<Suspense key={query} fallback={"loading...."}>
<Suspense
key={query}
fallback={
<DevicesTableSkeleton
headers={["Details", "Duration", "Status", "Amount"]}
length={10}
/>
}
>
<PaymentsTable searchParams={searchParams} />
</Suspense>
</div>

View File

@@ -1,8 +1,6 @@
import PriceCalculator from '@/components/price-calculator'
import React from 'react'
import PriceCalculator from "@/components/price-calculator";
import React from "react";
export default function Pricing() {
return (
<PriceCalculator />
)
return <PriceCalculator />;
}

View File

@@ -0,0 +1,95 @@
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth";
import ClientErrorMessage from "@/components/client-error-message";
import { Badge } from "@/components/ui/badge";
import { FloatingLabelInput } from "@/components/ui/floating-label";
import { getProfileById } from "@/queries/users";
import { tryCatch } from "@/utils/tryCatch";
export default async function Profile() {
const session = await getServerSession(authOptions);
if (!session?.user) return redirect("/auth/signin?callbackUrl=/profile");
const [error, profile] = await tryCatch(getProfileById(session?.user.id));
if (error) {
if (error.message === "Invalid token.") redirect("/auth/signin");
return <ClientErrorMessage message={error.message} />;
}
return (
<div>
<div className="flex justify-between items-center font-bold border rounded-md border-dashed title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">Profile</h3>
<div className="text-sarLinkOrange uppercase font-mono text-sm flex flex-col items-center rounded gap-2 py-2 px-4">
<span>Profile Status</span>
{verifiedStatus(profile?.verified ?? false)}
</div>
</div>
<fieldset>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4 max-w-4xl">
<FloatingLabelInput
id="floating-name"
label="Full Name"
value={`${profile?.first_name} ${profile?.last_name}`}
readOnly
/>
<FloatingLabelInput
id="floating-id-card"
label="ID Card"
value={`${profile?.id_card}`}
readOnly
/>
<FloatingLabelInput
id="floating-island"
label="Island"
value={`${profile?.atoll?.name}. ${profile?.island?.name}`}
readOnly
/>
<FloatingLabelInput
id="floating-dob"
label="Date of Birth"
value={`${new Date(
profile?.dob?.toString() ?? "",
).toLocaleDateString("en-US", {
month: "short",
day: "2-digit",
year: "numeric",
})}`}
readOnly
/>
<FloatingLabelInput
id="floating-address"
label="Address"
value={`${profile?.address}`}
readOnly
/>
<FloatingLabelInput
id="floating-mobile"
label="Phone Number"
value={`${profile?.mobile}`}
readOnly
/>
<FloatingLabelInput
id="floating-account"
label="Account Number"
value={`${profile?.acc_no}`}
readOnly
/>
</div>
</fieldset>
{/* <Suspense key={query} fallback={"loading...."}>
<TopupsTable searchParams={searchParams} />
</Suspense> */}
</div>
);
}
function verifiedStatus(status: boolean) {
switch (status) {
case true:
return <Badge className="bg-green-500 text-white">Verified</Badge>;
case false:
return <Badge className="bg-red-500 text-white">Not Verified</Badge>;
default:
return <Badge className="bg-yellow-500 text-white">Unknown</Badge>;
}
}

View File

@@ -0,0 +1,80 @@
import { redirect } from "next/navigation";
import { getTopup } from "@/actions/payment";
import CancelTopupButton from "@/components/billing/cancel-topup-button";
import ExpiryCountDown from "@/components/billing/expiry-time-countdown";
import ClientErrorMessage from "@/components/client-error-message";
import TopupToPay from "@/components/topup-to-pay";
import { Button } from "@/components/ui/button";
import { TextShimmer } from "@/components/ui/text-shimmer";
import { cn } from "@/lib/utils";
import { tryCatch } from "@/utils/tryCatch";
export default async function TopupPage({
params,
}: {
params: Promise<{ topupId: string }>;
}) {
const topupId = (await params).topupId;
const [error, topup] = await tryCatch(getTopup({ id: topupId }));
if (error) {
if (error.message === "Invalid token.") redirect("/auth/signin");
return <ClientErrorMessage message={error.message} />;
}
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-4 mb-4 mx-2">
<h3 className="text-sarLinkOrange text-2xl">Topup</h3>
<div className="flex flex-col gap-4 items-end w-full">
{!topup.is_expired && topup.paid && topup.status !== "PENDING" && (
<Button
disabled
className={cn(
"rounded-md opacity-100! uppercase font-semibold",
topup?.paid
? "text-green-900 bg-green-500/20"
: "text-inherit bg-yellow-400",
)}
>
{topup.status}
</Button>
)}
{topup.status === "PENDING" && !topup.is_expired && (
<Button>
<TextShimmer>Payment Pending</TextShimmer>{" "}
</Button>
)}
{!topup.paid &&
(topup.is_expired ? (
<Button
disabled
className="rounded-md opacity-100! uppercase font-semibold text-red-500 bg-red-500/20"
>
Topup Expired
</Button>
) : topup.status === "PENDING" ? (
<CancelTopupButton topupId={topupId} />
) : topup.status === "CANCELLED" ? (
<Button disabled>Topup Cancelled</Button>
) : (
""
))}
</div>
</div>
{!topup.paid && topup.status === "PENDING" && !topup.is_expired && (
<ExpiryCountDown expiryLabel="Top up" expiresAt={topup.expires_at} />
)}
<div
id="user-topup-details"
className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
>
<TopupToPay
disabled={
topup.paid || topup.is_expired || topup.status === "CANCELLED"
}
topup={topup || undefined}
/>
</div>
</div>
);
}

View File

@@ -0,0 +1,25 @@
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import { Skeleton } from "@/components/ui/skeleton";
export default function LoadingComponent() {
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<Skeleton className="w-48 h-8" />
<Skeleton className="w-20 h-8" />
</div>
<div>
<Skeleton className="w-full rounded-md mt-5 mb-6 sm:w-48 h-9" />
</div>
<div
id="user-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-endO"
>
<DevicesTableSkeleton
headers={["Details", "Status", "Amount"]}
length={10}
/>
</div>
</div>
);
}

View File

@@ -0,0 +1,95 @@
import { Suspense } from "react";
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import DynamicFilter from "@/components/generic-filter";
import { TopupsTable } from "@/components/topups-table";
export default async function Topups({
searchParams,
}: {
searchParams: Promise<{
query: string;
page: number;
sortBy: string;
status: string;
}>;
}) {
const query = (await searchParams)?.query || "";
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">My Topups</h3>
</div>
<div
id="topup-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
>
<DynamicFilter
inputs={[
{
label: "Status",
name: "status",
type: "radio-group",
options: [
{
label: "All",
value: "",
},
{
label: "Pending",
value: "PENDING",
},
{
label: "Cancelled",
value: "CANCELLED",
},
{
label: "Paid",
value: "PAID",
},
],
},
{
label: "Topup Expiry",
name: "is_expired",
type: "radio-group",
options: [
{
label: "All",
value: "",
},
{
label: "Expired",
value: "true",
},
{
label: "Not Expired",
value: "false",
},
],
},
{
label: "Topup Amount",
name: "amount",
type: "dual-range-slider",
min: 0,
max: 1000,
step: 10,
},
]}
/>
</div>
<Suspense
key={query}
fallback={
<DevicesTableSkeleton
headers={["Details", "Status", "Amount"]}
length={10}
/>
}
>
<TopupsTable searchParams={searchParams} />
</Suspense>
</div>
);
}

View File

@@ -17,7 +17,7 @@ export default async function UserDevices({
}) {
const query = (await searchParams)?.query || "";
const session = await getServerSession(authOptions);
if (session?.user?.is_admin !== true) redirect("/devices?page=1");
if (!session?.user?.is_admin) redirect("/devices?page=1");
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
@@ -55,12 +55,12 @@ export default async function UserDevices({
label: "Device User",
type: "string",
placeholder: "User name or id card",
}
},
]}
/>
</div>
<Suspense key={query} fallback={"loading...."}>
<AdminDevicesTable parentalControl={true} searchParams={searchParams} />
<AdminDevicesTable searchParams={searchParams} />
</Suspense>
</div>
);

View File

@@ -1,5 +1,9 @@
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { Suspense } from "react";
import { authOptions } from "@/app/auth";
import { UsersPaymentsTable } from "@/components/admin/user-payments-table";
import DynamicFilter from "@/components/generic-filter";
export default async function UserPayments({
searchParams,
@@ -12,12 +16,69 @@ export default async function UserPayments({
}>;
}) {
const query = (await searchParams)?.query || "";
// const session = await getServerSession(authOptions);
const session = await getServerSession(authOptions);
if (!session?.user?.is_admin) redirect("/payments?page=1");
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">User Payments</h3>
</div>
<DynamicFilter
description="Filter user payments by name, MAC address, or vendor."
title="User Payments Filter"
inputs={[
{
name: "user",
label: "User",
type: "string",
placeholder: "Enter user name",
},
{
name: "mib_reference",
label: "MIB Reference",
type: "string",
placeholder: "Enter MIB Reference",
},
{
type: "dual-range-slider",
label: "Amount Range",
name: "amount",
max: 1200,
min: 0,
step: 10,
},
{
type: "dual-range-slider",
label: "Duration Range",
name: "number_of_months",
max: 12,
min: 1,
step: 1,
},
{
type: "radio-group",
label: "Payment Status",
name: "status",
options: [
{ label: "All", value: "" },
{ label: "Pending", value: "PENDING" },
{ label: "Paid", value: "PAID" },
{ label: "Cancelled", value: "CANCELLED" },
],
},
{
type: "radio-group",
label: "Payment Method",
name: "method",
options: [
{ label: "All", value: "" },
{ label: "Wallet", value: "WALLET" },
{ label: "Transfer", value: "TRANSFER" },
],
},
]}
/>
<Suspense key={query} fallback={"loading...."}>
<UsersPaymentsTable searchParams={searchParams} />
</Suspense>

View File

@@ -0,0 +1,90 @@
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { Suspense } from "react";
import { authOptions } from "@/app/auth";
import { AdminTopupsTable } from "@/components/admin/admin-topup-table";
import DynamicFilter from "@/components/generic-filter";
export default async function UserTopups({
searchParams,
}: {
searchParams: Promise<{
[key: string]: string;
}>;
}) {
const query = (await searchParams)?.query || "";
const session = await getServerSession(authOptions);
if (!session?.user?.is_admin) redirect("/top-ups?page=1");
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">User Topups</h3>
</div>
<DynamicFilter
title="User Topups Filter"
description="Filter user topups by status, topup expiry, or amount."
inputs={[
{
name: "user",
label: "User",
type: "string",
placeholder: "Enter user name",
},
{
label: "Status",
name: "status",
type: "radio-group",
options: [
{
label: "All",
value: "",
},
{
label: "Pending",
value: "PENDING",
},
{
label: "Cancelled",
value: "CANCELLED",
},
{
label: "Paid",
value: "PAID",
},
],
},
{
label: "Topup Expiry",
name: "is_expired",
type: "radio-group",
options: [
{
label: "All",
value: "",
},
{
label: "Expired",
value: "true",
},
{
label: "Not Expired",
value: "false",
},
],
},
{
label: "Topup Amount",
name: "amount",
type: "dual-range-slider",
min: 0,
max: 1000,
step: 10,
},
]}
/>
<Suspense key={query} fallback={"loading...."}>
<AdminTopupsTable searchParams={searchParams} />
</Suspense>
</div>
);
}

View File

@@ -0,0 +1,48 @@
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth";
import ClientErrorMessage from "@/components/client-error-message";
import UserAgreementForm from "@/components/user/user-agreement-form";
import { getProfileById } from "@/queries/users";
import { tryCatch } from "@/utils/tryCatch";
// import {
// Select,
// SelectContent,
// SelectGroup,
// SelectItem,
// SelectLabel,
// SelectTrigger,
// SelectValue,
// } from "@/components/ui/select";
export default async function UserUpdate({
params,
}: {
params: Promise<{
userId: string;
}>;
}) {
const { userId } = await params;
const session = await getServerSession(authOptions);
if (!session?.user?.is_admin) return redirect("/devices?page=1");
const [error, user] = await tryCatch(getProfileById(userId));
if (error) {
if (error.message === "UNAUTHORIZED") {
redirect("/auth/signin");
} else {
return <ClientErrorMessage message={error.message} />;
}
}
return (
<div>
<div className="flex items-center justify-between text-gray-500 text-2xl font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">
Upload user user agreement
</h3>
</div>
<UserAgreementForm user={user} />
</div>
);
}

View File

@@ -0,0 +1,211 @@
import { EyeIcon, FileTextIcon, PencilIcon } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { redirect } from "next/navigation";
import AddTopupDialogForm from "@/components/admin/admin-topup-form";
import ClientErrorMessage from "@/components/client-error-message";
import InputReadOnly from "@/components/input-read-only";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import UserRejectDialog from "@/components/user/user-reject-dialog";
import { UserVerifyDialog } from "@/components/user/user-verify-dialog";
import { getNationalPerson } from "@/lib/person";
import { getProfileById } from "@/queries/users";
import { tryCatch } from "@/utils/tryCatch";
export default async function VerifyUserPage({
params,
}: {
params: Promise<{
userId: string;
}>;
}) {
const userId = (await params).userId;
const [error, dbUser] = await tryCatch(getProfileById(userId));
const [nationalDataEror, nationalData] = await tryCatch(
getNationalPerson({ idCard: dbUser?.id_card ?? "" }),
);
if (nationalDataEror) {
console.warn("Error fetching national data:", nationalDataEror);
}
if (error) {
if (error.message === "UNAUTHORIZED") {
redirect("/auth/signin");
} else {
return <ClientErrorMessage message={error.message} />;
}
}
// return <pre>{JSON.stringify(nationalData, null, 2)}</pre>
const fullName = `${dbUser?.first_name} ${dbUser?.last_name}`;
const nationalDob = nationalData?.dob?.split("T")[0];
const dbUserDob = new Date(dbUser?.dob).toISOString().split("T")[0];
return (
<div>
<div className="flex flex-wrap gap-2 items-center justify-between text-gray-500 text-2xl font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">User Information</h3>
<div className="flex flex-wrap gap-2">
{dbUser && !dbUser?.verified && <UserVerifyDialog user={dbUser} />}
{dbUser && !dbUser?.verified && <UserRejectDialog user={dbUser} />}
<AddTopupDialogForm user_id={userId} />
<Link href={"update"}>
<Button className="hover:cursor-pointer">
<PencilIcon />
Update User
</Button>
</Link>
<Link href={"agreement"}>
<Button className="hover:cursor-pointer">
<FileTextIcon />
Update Agreement
</Button>
</Link>
<Link
href={dbUser?.agreement || "#"}
target="_blank"
rel="noopener noreferrer"
>
<Button className="hover:cursor-pointer">
<EyeIcon />
View Agreement
</Button>
</Link>
{dbUser?.verified && (
<Badge variant={"secondary"} className="bg-lime-500">
Verified
</Badge>
)}
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-start justify-start">
<div id="database-information">
<h4 className="p-2 rounded font-semibold">Database Information</h4>
<div className="shadow-md p-2 bg-sarLinkOrange/10 border border-dashed border-sarLinkOrange rounded-lg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2">
<InputReadOnly
showCheck
checkTrue={dbUser?.id_card === nationalData?.nic}
labelClassName="text-sarLinkOrange"
label="ID Card"
value={dbUser?.id_card ?? ""}
/>
<InputReadOnly
showCheck
checkTrue={fullName === nationalData?.name_en}
labelClassName="text-sarLinkOrange"
label="Name"
value={fullName}
/>
<InputReadOnly
showCheck
checkTrue={dbUser?.address === nationalData?.house_name_en}
labelClassName="text-sarLinkOrange"
label="House Name"
value={dbUser?.address ?? ""}
/>
<InputReadOnly
showCheck
checkTrue={dbUser?.island?.name === nationalData?.island_name_en}
labelClassName="text-sarLinkOrange"
label="Island"
value={dbUser?.island?.name ?? ""}
/>
<InputReadOnly
showCheck
checkTrue={dbUser?.atoll.name === nationalData?.atoll_en}
labelClassName="text-sarLinkOrange"
label="Atoll"
value={dbUser?.atoll?.name ?? ""}
/>
<InputReadOnly
showCheck
checkTrue={dbUserDob === nationalDob}
labelClassName="text-sarLinkOrange"
label="DOB"
value={new Date(dbUser?.dob ?? "").toLocaleDateString("en-US", {
month: "short",
day: "2-digit",
year: "numeric",
})}
/>
<InputReadOnly
showCheck
checkTrue={dbUser?.mobile === nationalData?.primary_contact}
labelClassName="text-sarLinkOrange"
label="Phone Number"
value={dbUser?.mobile ?? ""}
/>
</div>
</div>
{
<div id="national-information">
<h4 className="p-2 rounded font-semibold">National Information</h4>
<div className="bg-green-800/10 shadow p-2 rounded-lg border border-dashed border-green-800 space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2">
<InputReadOnly
showCheck={false}
labelClassName="text-green-500"
label="ID Card"
value={nationalData?.nic ?? ""}
/>
<InputReadOnly
showCheck={false}
labelClassName="text-green-500"
label="Name"
value={nationalData?.name_en ?? ""}
/>
<InputReadOnly
showCheck={false}
labelClassName="text-green-500"
label="House Name"
value={nationalData?.house_name_en ?? ""}
/>
<InputReadOnly
showCheck={false}
labelClassName="text-green-500"
label="Island"
value={nationalData?.island_name_en ?? ""}
/>
<InputReadOnly
showCheck={false}
labelClassName="text-green-500"
label="Atoll"
value={nationalData?.atoll_en ?? ""}
/>
<InputReadOnly
showCheck={false}
labelClassName="text-green-500"
label="DOB"
value={new Date(nationalData?.dob ?? "").toLocaleDateString(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
},
)}
/>
<InputReadOnly
showCheck={false}
labelClassName="text-green-500"
label="Phone Number"
value={nationalData?.primary_contact ?? ""}
/>
<div className="flex flex-col col-span-2 items-center justify-center">
<Image
src={nationalData?.image_url || "https://i.pravatar.cc/300"}
height={100}
width={100}
className="object-fit aspect-square rounded-full"
alt="id photo"
/>
</div>
</div>
</div>
}
</div>
</div>
);
}

View File

@@ -0,0 +1,46 @@
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth";
import ClientErrorMessage from "@/components/client-error-message";
import UserUpdateForm from "@/components/user/user-update-form";
import { getProfileById } from "@/queries/users";
import { tryCatch } from "@/utils/tryCatch";
// import {
// Select,
// SelectContent,
// SelectGroup,
// SelectItem,
// SelectLabel,
// SelectTrigger,
// SelectValue,
// } from "@/components/ui/select";
export default async function UserUpdate({
params,
}: {
params: Promise<{
userId: string;
}>;
}) {
const { userId } = await params;
const session = await getServerSession(authOptions);
if (!session?.user?.is_admin) return redirect("/devices?page=1");
const [error, user] = await tryCatch(getProfileById(userId));
if (error) {
if (error.message === "UNAUTHORIZED") {
redirect("/auth/signin");
} else {
return <ClientErrorMessage message={error.message} />;
}
}
return (
<div>
<div className="flex items-center justify-between text-gray-500 text-2xl font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">Verify user</h3>
</div>
<UserUpdateForm user={user} />
</div>
);
}

View File

@@ -1,169 +0,0 @@
export default async function VerifyUserPage({
params,
}: {
params: Promise<{
userId: string;
}>;
}) {
const userId = (await params).userId;
console.log("userId", userId);
// const dbUser = await prisma.user.findUnique({
// where: {
// id: userId,
// },
// include: {
// island: {
// include: {
// atoll: true
// }
// }
// }
// })
// const nationalData = await getNationalPerson({ idCard: dbUser?.id_card ?? "" })
return null;
// return (
// <div>
// <div className="flex items-center justify-between text-gray-500 text-2xl font-bold title-bg py-4 px-2 mb-4">
// <h3 className="text-sarLinkOrange text-2xl">Verify user</h3>
// <div className="flex gap-2">
// {dbUser && !dbUser?.verified && <UserVerifyDialog user={dbUser} />}
// {dbUser && !dbUser?.verified && <UserRejectDialog user={dbUser} />}
// {dbUser?.verified && (
// <Badge variant={"secondary"} className="bg-lime-500">
// Verified
// </Badge>
// )}
// </div>
// </div>
// <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-start justify-start">
// <div id="database-information">
// <h4 className="p-2 rounded font-semibold">Database Information</h4>
// <div className="shadow p-2 rounded-lg title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2">
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.id_card === nationalData.nic}
// labelClassName="text-sarLinkOrange"
// label="ID Card"
// value={dbUser?.id_card ?? ""}
// />
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.name === nationalData.name_en}
// labelClassName="text-sarLinkOrange"
// label="Name"
// value={dbUser?.name ?? ""}
// />
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.address === nationalData.house_name_en}
// labelClassName="text-sarLinkOrange"
// label="House Name"
// value={dbUser?.address ?? ""}
// />
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.island?.name === nationalData.island_name_en}
// labelClassName="text-sarLinkOrange"
// label="Island"
// value={dbUser?.island?.name ?? ""}
// />
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.island?.atoll.name === nationalData.atoll_en}
// labelClassName="text-sarLinkOrange"
// label="Atoll"
// value={dbUser?.island?.atoll.name ?? ""}
// />
// <InputReadOnly
// showCheck
// checkTrue={
// new Date(dbUser?.dob ?? "") === new Date(nationalData.dob)
// }
// labelClassName="text-sarLinkOrange"
// label="DOB"
// value={new Date(dbUser?.dob ?? "").toLocaleDateString("en-US", {
// month: "short",
// day: "2-digit",
// year: "numeric",
// })}
// />
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.phoneNumber === nationalData.primary_contact}
// labelClassName="text-sarLinkOrange"
// label="Phone Number"
// value={dbUser?.phoneNumber ?? ""}
// />
// </div>
// </div>
// <div id="national-information">
// <h4 className="p-2 rounded font-semibold">National Information</h4>
// <div className="shadow p-2 rounded-md title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2">
// <InputReadOnly
// showCheck={false}
// labelClassName="text-green-500"
// label="ID Card"
// value={nationalData?.nic ?? ""}
// />
// <InputReadOnly
// showCheck={false}
// labelClassName="text-green-500"
// label="Name"
// value={nationalData?.name_en ?? ""}
// />
// <InputReadOnly
// showCheck={false}
// labelClassName="text-green-500"
// label="House Name"
// value={nationalData?.house_name_en ?? ""}
// />
// <InputReadOnly
// showCheck={false}
// labelClassName="text-green-500"
// label="Island"
// value={nationalData?.island_name_en ?? ""}
// />
// <InputReadOnly
// showCheck={false}
// labelClassName="text-green-500"
// label="Atoll"
// value={nationalData?.atoll_en ?? ""}
// />
// <InputReadOnly
// showCheck={false}
// labelClassName="text-green-500"
// label="DOB"
// value={new Date(nationalData?.dob ?? "").toLocaleDateString(
// "en-US",
// {
// month: "short",
// day: "2-digit",
// year: "numeric",
// },
// )}
// />
// <InputReadOnly
// showCheck={false}
// labelClassName="text-green-500"
// label="Phone Number"
// value={nationalData?.primary_contact ?? ""}
// />
// <div className="flex flex-col col-span-2 items-center justify-center">
// <Image
// src={nationalData.image_url || "https://i.pravatar.cc/300"}
// height={100}
// width={100}
// className="object-fit aspect-square rounded-full"
// alt="id photo"
// />
// </div>
// </div>
// </div>
// </div>
// </div>
// );
}

View File

@@ -1,38 +1,19 @@
import Filter from "@/components/filter";
import Search from "@/components/search";
import { UsersTable } from "@/components/user-table";
import {
AArrowDown,
AArrowUp,
CheckCheck,
Hourglass,
Minus,
} from "lucide-react";
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { Suspense } from "react";
const sortfilterOptions = [
{
value: "asc",
label: "Ascending",
icon: <AArrowUp size={16} />,
},
{
value: "desc",
label: "Descending",
icon: <AArrowDown size={16} />,
},
];
import { authOptions } from "@/app/auth";
import DynamicFilter from "@/components/generic-filter";
import { UsersTable } from "@/components/user-table";
export default async function AdminUsers({
searchParams,
}: {
searchParams: Promise<{
query: string;
page: number;
sortBy: string;
status: string;
[key: string]: string;
}>;
}) {
const session = await getServerSession(authOptions);
if (!session?.user?.is_admin) redirect("/devices?page=1");
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
@@ -43,33 +24,60 @@ export default async function AdminUsers({
id="user-table-filters"
className=" pb-4 gap-4 flex items-center justify-start"
>
<Search />
<Filter
options={[
<DynamicFilter
description="Filter users by id card, name, or house name and more."
title="User Filter"
inputs={[
{
value: "all",
label: "ALL",
icon: <Minus size={14} />,
name: "first_name",
label: "User First Name",
type: "string",
placeholder: "Enter user first name",
},
{
value: "unverified",
label: "Unverfieid",
icon: <CheckCheck size={14} />,
name: "last_name",
label: "User Last Name",
type: "string",
placeholder: "Enter user last name",
},
{
value: "verified",
label: "Verified",
icon: <Hourglass size={14} />,
name: "id_card",
label: "ID Card",
type: "string",
placeholder: "Enter ID card number",
},
{
name: "house_name",
label: "House Name",
type: "string",
placeholder: "Enter house name",
},
{
name: "mobile",
label: "Phone Number",
type: "string",
placeholder: "Enter phone number",
},
{
name: "verified",
type: "radio-group",
label: "User Status",
options: [
{
value: "",
label: "All",
},
{
label: "Verified",
value: "true",
},
{
label: "Unverified",
value: "false",
},
],
},
]}
defaultOption="all"
queryParamKey="status"
/>
<Filter
options={sortfilterOptions}
defaultOption="asc"
queryParamKey="sortBy"
/>
</div>
<Suspense fallback={"loading...."}>

View File

@@ -1,13 +1,78 @@
import React from 'react'
import { Suspense } from "react";
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import DynamicFilter from "@/components/generic-filter";
import { WalletTransactionsTable } from "@/components/wallet-transactions-table";
export default function UserWallet() {
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">
My Wallet
</h3>
</div>
</div>
)
export default async function Wallet({
searchParams,
}: {
searchParams: Promise<{
query: string;
page: number;
sortBy: string;
status: string;
}>;
}) {
const query = (await searchParams)?.query || "";
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">Transaction History</h3>
</div>
<div
id="wallet-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
>
<DynamicFilter
inputs={[
{
label: "Type",
name: "transaction_type",
type: "radio-group",
options: [
{
label: "All",
value: "",
},
{
label: "Debit",
value: "debit",
},
{
label: "Credit",
value: "credit",
},
],
},
{
label: "Topup Amount",
name: "amount",
type: "dual-range-slider",
min: 0,
max: 1000,
step: 10,
},
]}
/>
</div>
<Suspense
key={query}
fallback={
<DevicesTableSkeleton
headers={[
"Description",
"Amount",
"Transaction Type",
"View Details",
"Created at",
]}
length={10}
/>
}
>
<WalletTransactionsTable searchParams={searchParams} />
</Suspense>
</div>
);
}

File diff suppressed because one or more lines are too long

View File

@@ -11,49 +11,48 @@ import QueryProvider from "@/providers/query-provider";
import { getServerSession } from "next-auth";
import { authOptions } from "./auth";
const barlow = Barlow({
subsets: ["latin"],
weight: ["100", "300", "400", "500", "600", "700", "800", "900"],
variable: "--font-barlow",
subsets: ["latin"],
weight: ["100", "300", "400", "500", "600", "700", "800", "900"],
variable: "--font-barlow",
});
const bokor = Bokor({
subsets: ["latin"],
weight: ["400"],
variable: "--font-bokor",
subsets: ["latin"],
weight: ["400"],
variable: "--font-bokor",
});
export const metadata: Metadata = {
title: "SAR Link Portal",
description: "Sarlink Portal",
title: "SAR Link Portal",
description: "Sarlink Portal",
};
export default async function RootLayout({
children,
children,
}: Readonly<{
children: React.ReactNode;
children: React.ReactNode;
}>) {
const session = await getServerSession(authOptions);
return (
<html lang="en" suppressHydrationWarning>
<body className={`${barlow.variable} ${bokor.variable} antialiased font-sans bg-gray-100 dark:bg-black`}>
<AuthProvider session={session || undefined}>
<Provider>
<NextTopLoader color="#f49d1b" showSpinner={false} zIndex={9999} />
<Toaster richColors />
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<QueryProvider>
{children}
</QueryProvider>
</ThemeProvider>
</Provider>
</AuthProvider>
</body>
</html>
);
const session = await getServerSession(authOptions);
return (
<html lang="en" suppressHydrationWarning>
<body
className={`${barlow.variable} ${bokor.variable} antialiased font-sans bg-gray-100 dark:bg-black`}
>
<AuthProvider session={session || undefined}>
<Provider>
<NextTopLoader color="#f49d1b" showSpinner={false} zIndex={9999} />
<Toaster richColors />
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<QueryProvider>{children}</QueryProvider>
</ThemeProvider>
</Provider>
</AuthProvider>
</body>
</html>
);
}

4
app/next-auth.d.ts vendored
View File

@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
// @ts-expect-error importing unused types are required here
import NextAuth, { DefaultSession, type User, Session } from "next-auth";
import NextAuth, { DefaultSession, Session, type User } from "next-auth";
/* eslint-enable @typescript-eslint/no-unused-vars */
declare module "next-auth" {
/**
@@ -26,6 +27,7 @@ declare module "next-auth" {
date_joined?: string;
is_superuser?: boolean;
is_admin?: boolean;
agreement?: string;
};
expires: ISODateString;
}

View File

@@ -1,5 +1,5 @@
import { redirect } from "next/navigation";
export default async function Home() {
return redirect("/devices");
return redirect("/devices");
}

3
commitlint.config.js Normal file
View File

@@ -0,0 +1,3 @@
export default {
extends: ["@commitlint/config-conventional"],
};

View File

@@ -1,21 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "tailwind.config.ts",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "tailwind.config.ts",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

View File

@@ -0,0 +1,56 @@
"use client";
import { Clipboard, ClipboardCheck } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "./ui/button";
export function AccountInfomation({
accountNo,
accName,
}: {
accountNo: string;
accName: string;
}) {
const [accNo, setAccNo] = useState(false);
return (
<div className="justify-center items-center border my-4 flex flex-col gap-2 p-2 rounded-md">
<h6 className="title-bg uppercase p-2 border rounded w-full font-semibold">
Account Information
</h6>
<div className="border justify-center flex flex-col items-center bg-white/10 w-full p-2 rounded">
<div className="text-sm font-semibold">Account Name</div>
<span>{accName}</span>
</div>
<div className="border flex justify-between items-center gap-2 w-full p-2 rounded">
<div className="flex flex-col items-center justify-center w-full">
<p className="text-sm font-semibold">Account No</p>
<span>{accountNo}</span>
<Button
onClick={() => {
setTimeout(() => {
setAccNo(true);
navigator.clipboard.writeText(accountNo);
}, 2000);
toast.success("Account number copied!");
setAccNo((prev) => !prev);
}}
className="mt-2 w-full"
variant={"secondary"}
>
{accNo ? (
<div className="flex items-center gap-2">
<span>Copy Account Number</span>
<Clipboard />
</div>
) : (
<div className="flex items-center gap-2">
<span>Copy Account Number</span>
<ClipboardCheck color="green" />
</div>
)}
</Button>
</div>
</div>
</div>
);
}

View File

@@ -6,7 +6,6 @@ import { authOptions } from "@/app/auth";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableFooter,
TableHead,
@@ -18,21 +17,18 @@ import { getDevices } from "@/queries/devices";
import { tryCatch } from "@/utils/tryCatch";
import BlockDeviceDialog from "../block-device-dialog";
import ClientErrorMessage from "../client-error-message";
import DeviceCard from "../device-card";
import Pagination from "../pagination";
export async function AdminDevicesTable({
searchParams,
parentalControl,
}: {
searchParams: Promise<{
[key: string]: unknown;
}>;
parentalControl?: boolean;
}) {
const resolvedParams = await searchParams;
const session = await getServerSession(authOptions);
const isAdmin = session?.user?.is_superuser;
const isAdmin = session?.user?.is_admin;
const page = Number.parseInt(resolvedParams.page as string) || 1;
const limit = 10;
@@ -48,9 +44,7 @@ export async function AdminDevicesTable({
apiParams.limit = limit;
apiParams.offset = offset;
const [error, devices] = await tryCatch(
getDevices(apiParams, true),
);
const [error, devices] = await tryCatch(getDevices(apiParams, true));
if (error) {
if (error.message === "UNAUTHORIZED") {
redirect("/auth/signin");
@@ -67,9 +61,8 @@ export async function AdminDevicesTable({
</div>
) : (
<>
<div className="hidden sm:block">
<div>
<Table className="overflow-scroll">
<TableCaption>Table of all devices.</TableCaption>
<TableHeader>
<TableRow>
<TableHead>Device Name</TableHead>
@@ -81,9 +74,7 @@ export async function AdminDevicesTable({
</TableHeader>
<TableBody className="overflow-scroll">
{data?.map((device) => (
<TableRow
key={device.id}
>
<TableRow key={device.id}>
<TableCell>
<div className="flex flex-col items-start">
<Link
@@ -99,18 +90,19 @@ export async function AdminDevicesTable({
<div className="text-muted-foreground">
Active until{" "}
<span className="font-semibold">
{new Date(device.expiry_date || "").toLocaleDateString(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
},
)}
{new Date(
device.expiry_date || "",
).toLocaleDateString("en-US", {
month: "short",
day: "2-digit",
year: "numeric",
})}
</span>
</div>
) : (
<p className="text-muted-foreground">Device Inactive</p>
<p className="text-muted-foreground">
Device Inactive
</p>
)}
{device.has_a_pending_payment && (
<Link href={`/payments/${device.pending_payment_id}`}>
@@ -124,7 +116,9 @@ export async function AdminDevicesTable({
{device.blocked_by === "ADMIN" && device.blocked && (
<div className="p-2 rounded border my-2 bg-white dark:bg-neutral-800 shadow">
<span className="font-semibold">Comment</span>
<p className="text-neutral-400">{device?.reason_for_blocking}</p>
<p className="text-neutral-400">
{device?.reason_for_blocking}
</p>
</div>
)}
</div>
@@ -132,12 +126,15 @@ export async function AdminDevicesTable({
<TableCell className="font-medium">
<div className="flex flex-col items-start">
{device?.user?.name}
<span className="text-muted-foreground">{device?.user?.id_card}</span>
<span className="text-muted-foreground">
{device?.user?.id_card}
</span>
</div>
</TableCell>
<TableCell className="font-medium">{device.mac}</TableCell>
<TableCell className="font-medium">{device?.vendor}</TableCell>
<TableCell className="font-medium">
{device?.vendor}
</TableCell>
<TableCell>
{!device.has_a_pending_payment && (
<BlockDeviceDialog
@@ -154,9 +151,7 @@ export async function AdminDevicesTable({
<TableRow>
<TableCell colSpan={5} className="text-muted-foreground">
{meta?.total === 1 ? (
<p className="text-center">
Total {meta?.total} device.
</p>
<p className="text-center">Total {meta?.total} device.</p>
) : (
<p className="text-center">
Total {meta?.total} devices.
@@ -167,22 +162,13 @@ export async function AdminDevicesTable({
</TableFooter>
</Table>
</div>
<div className="sm:hidden my-4">
{data?.map((device) => (
<DeviceCard
parentalControl={parentalControl}
key={device.id}
device={device}
/>
))}
</div>
<Pagination
totalPages={meta?.last_page}
currentPage={meta?.current_page}
/>
</>
)
}
</div >
)}
</div>
);
}

View File

@@ -0,0 +1,133 @@
"use client";
import { Loader2, PlusCircle } from "lucide-react";
import { useRouter } from "next/navigation";
import { useActionState, useEffect, useState } from "react"; // Import useActionState
import { toast } from "sonner";
import { adminUserTopup } from "@/actions/user-actions";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "../ui/textarea";
export type AddTopupFormState = {
status: boolean;
message: string;
fieldErrors?: {
amount?: string[];
description?: string[];
};
payload?: FormData;
};
export const initialState: AddTopupFormState = {
message: "",
fieldErrors: {},
status: false,
};
export default function AddTopupDialogForm({ user_id }: { user_id?: string }) {
const [open, setOpen] = useState(false);
const router = useRouter();
const [state, formAction, pending] = useActionState(
adminUserTopup,
initialState,
);
useEffect(() => {
if (state.message && state !== initialState) {
if (state.fieldErrors && Object.keys(state.fieldErrors).length > 0) {
toast.error(state.message);
} else if (state.status) {
setOpen(false);
toast.success(state.message);
router.push("/user-topups?page=1");
} else {
toast.error(state.message);
}
}
}, [state, router]);
if (!user_id) {
return null;
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button
className="gap-2 items-center"
disabled={pending}
variant="default"
>
Add cash topup
<PlusCircle size={16} />
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>New Manual Topup</DialogTitle>
<DialogDescription>
To add a new manual topup, enter the amount below. Click save when
you are done.
</DialogDescription>
</DialogHeader>
<form action={formAction}>
<div className="grid gap-4 py-4">
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-3">
<Label htmlFor="amount">Topup Amount</Label>
<input type="hidden" name="user_id" value={user_id} />
<Input
type="number"
defaultValue={(state?.payload?.get("amount") || "") as string}
name="amount"
id="topup_amount"
className="col-span-3"
/>
{state.fieldErrors?.amount && (
<span className="text-red-500 text-sm">
{state.fieldErrors.amount[0]}
</span>
)}
</div>
<div className="flex flex-col gap-3">
<Label htmlFor="description">Topup Description</Label>
<input type="hidden" name="user_id" value={user_id} />
<Textarea
defaultValue={
(state?.payload?.get("description") || "") as string
}
rows={10}
name="description"
id="topup_description"
className="col-span-5 max-w-[375px] h-32 resize-none"
style={{ overflowY: "auto" }}
/>
{state.fieldErrors?.description && (
<span className="text-red-500 text-sm">
{state.fieldErrors.description[0]}
</span>
)}
</div>
</div>
</div>
<DialogFooter>
<Button disabled={pending} type="submit">
{pending ? <Loader2 className="animate-spin" /> : "Save"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,137 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { getTopups } from "@/actions/payment";
import {
Table,
TableBody,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { tryCatch } from "@/utils/tryCatch";
import Pagination from "../pagination";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
export async function AdminTopupsTable({
searchParams,
}: {
searchParams: Promise<{
[key: string]: unknown;
}>;
}) {
const resolvedParams = await searchParams;
const page = Number.parseInt(resolvedParams.page as string) || 1;
const limit = 10;
const offset = (page - 1) * limit;
// Build params object
const apiParams: Record<string, string | number | undefined> = {};
for (const [key, value] of Object.entries(resolvedParams)) {
if (value !== undefined && value !== "") {
apiParams[key] = typeof value === "number" ? value : String(value);
}
}
apiParams.limit = limit;
apiParams.offset = offset;
const [error, topups] = await tryCatch(getTopups(apiParams, true));
if (error) {
if (error.message.includes("Unauthorized")) {
redirect("/auth/signin");
} else {
return <pre>{JSON.stringify(error, null, 2)}</pre>;
}
}
const { data, meta } = topups;
return (
<div>
{data?.length === 0 ? (
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
<h3>No topups yet.</h3>
</div>
) : (
<>
<div>
<Table className="overflow-scroll">
<TableHeader>
<TableRow>
<TableHead>User</TableHead>
<TableHead>Status</TableHead>
<TableHead>Amount</TableHead>
<TableHead>Action</TableHead>
</TableRow>
</TableHeader>
<TableBody className="overflow-scroll">
{topups?.data?.map((topup) => (
<TableRow key={topup.id}>
<TableCell>
<div className="flex flex-col items-start">
{topup?.user?.name}
<span className="text-muted-foreground">
{topup?.user?.id_card}
</span>
</div>
</TableCell>
<TableCell>
<span className="font-semibold pr-2">
{topup.paid ? (
<Badge
className="bg-green-100 dark:bg-green-700"
variant="outline"
>
{topup.status}
</Badge>
) : topup.is_expired ? (
<Badge>Expired</Badge>
) : (
<Badge variant="outline">{topup.status}</Badge>
)}
</span>
</TableCell>
<TableCell>
<span className="font-semibold pr-2">
{topup.amount.toFixed(2)}
</span>
MVR
</TableCell>
<TableCell>
<div>
<div className="flex items-center gap-2 mt-2">
<Link
className="font-medium hover:underline"
href={`/top-ups/${topup.id}`}
>
<Button size={"sm"} variant="outline">
View Details
</Button>
</Link>
</div>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={4} className="text-muted-foreground">
{meta?.total === 1 ? (
<p className="text-center">Total {meta?.total} topup.</p>
) : (
<p className="text-center">Total {meta?.total} topups.</p>
)}
</TableCell>
</TableRow>
</TableFooter>
</Table>
</div>
<Pagination
totalPages={meta?.last_page}
currentPage={meta?.current_page}
/>
</>
)}
</div>
);
}

View File

@@ -1,236 +1,172 @@
// import Pagination from "@/components/pagination";
// import { Badge } from "@/components/ui/badge";
// import { Button } from "@/components/ui/button";
// import {
// Table,
// TableBody,
// TableCaption,
// TableCell,
// TableFooter,
// TableHead,
// TableHeader,
// TableRow,
// } from "@/components/ui/table";
// import Link from "next/link";
import Link from "next/link";
import { redirect } from "next/navigation";
import { getPayments } from "@/actions/payment";
import Pagination from "@/components/pagination";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Table,
TableBody,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { tryCatch } from "@/utils/tryCatch";
import ClientErrorMessage from "../client-error-message";
export async function UsersPaymentsTable({
searchParams,
}: {
searchParams: Promise<{
query: string;
page: number;
sortBy: string;
status: string;
[key: string]: unknown;
}>;
}) {
const query = (await searchParams)?.query || "";
console.log(query);
// const page = (await searchParams)?.page;
// const sortBy = (await searchParams)?.sortBy || "asc";
// const totalPayments = await prisma.payment.count({
// where: {
// OR: [
// {
// user: {
// name: {
// contains: query || "",
// mode: "insensitive",
// }
// },
// },
// {
// user: {
// phoneNumber: {
// contains: query || "",
// mode: "insensitive",
// }
// },
// },
// {
// user: {
// address: {
// contains: query || "",
// mode: "insensitive",
// }
// },
// },
// {
// user: {
// id_card: {
// contains: query || "",
// mode: "insensitive",
// }
// },
// },
// ],
// },
// });
const resolvedParams = await searchParams;
// const totalPages = Math.ceil(totalPayments / 10);
// const limit = 10;
// const offset = (Number(page) - 1) * limit || 0;
const page = Number.parseInt(resolvedParams.page as string) || 1;
const limit = 10;
const offset = (page - 1) * limit;
// const payments = await prisma.payment.findMany({
// where: {
// OR: [
// {
// user: {
// name: {
// contains: query || "",
// mode: "insensitive",
// }
// },
// },
// {
// user: {
// phoneNumber: {
// contains: query || "",
// mode: "insensitive",
// }
// },
// },
// {
// user: {
// address: {
// contains: query || "",
// mode: "insensitive",
// }
// },
// },
// {
// user: {
// id_card: {
// contains: query || "",
// mode: "insensitive",
// }
// },
// },
// ],
// },
// include: {
// user: true,
// devices: true,
// },
// skip: offset,
// take: limit,
// orderBy: {
// id: `${sortBy}` as "asc" | "desc",
// },
// });
// Build params object for getDevices
const apiParams: Record<string, string | number | undefined> = {};
for (const [key, value] of Object.entries(resolvedParams)) {
if (value !== undefined && value !== "") {
apiParams[key] = typeof value === "number" ? value : String(value);
}
}
apiParams.limit = limit;
apiParams.offset = offset;
// const users = await prisma.user.findMany({
// where: {
// role: "USER",
// },
// include: {
// atoll: true,
// island: true,
// },
// });
return null;
// return (
// <div>
// {payments.length === 0 ? (
// <div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
// <h3>No user payments yet.</h3>
// </div>
// ) : (
// <>
// <Table className="overflow-scroll">
// <TableCaption>Table of all users.</TableCaption>
// <TableHeader>
// <TableRow>
// <TableHead>Devices paid</TableHead>
// <TableHead>User</TableHead>
// <TableHead>Amount</TableHead>
// <TableHead>Duration</TableHead>
// <TableHead>Payment Status</TableHead>
// <TableHead>Payment Method</TableHead>
// <TableHead>Paid At</TableHead>
// <TableHead>Action</TableHead>
// </TableRow>
// </TableHeader>
// <TableBody className="overflow-scroll">
// {payments.map((payment) => (
// <TableRow
// className={`${payment.paid && "title-bg dark:bg-black"}`}
// key={payment.id}
// >
// <TableCell className="font-medium">
// <ol className="list-disc list-inside text-sm">
// {payment.devices.map((device) => (
// <li
// key={device.id}
// className="text-sm text-muted-foreground"
// >
// {device.name}
// </li>
// ))}
// </ol>
// </TableCell>
// <TableCell className="font-medium">
// {payment.user.id_card}
// </TableCell>
// <TableCell>{payment.user?.name}</TableCell>
// <TableCell>{payment.user?.name}</TableCell>
// <TableCell>{payment.id}</TableCell>
const [error, payments] = await tryCatch(getPayments(apiParams, true));
if (error) {
if (error.message === "UNAUTHORIZED") {
redirect("/auth/signin");
} else {
return <ClientErrorMessage message={error.message} />;
}
}
const { meta, data } = payments;
// <TableCell>
// {payment.paid ? (
// <Badge
// variant="outline"
// className="bg-lime-100 text-black"
// >
// Verified
// </Badge>
// ) : (
// <Badge
// variant="outline"
// className="bg-yellow-100 text-black"
// >
// Unverified
// </Badge>
// )}
// </TableCell>
// <TableCell>
// {new Date(payment.paidAt ?? "").toLocaleDateString(
// "en-US",
// {
// month: "short",
// day: "2-digit",
// year: "numeric",
// },
// )}
// </TableCell>
// return <pre>{JSON.stringify(payments, null, 2)}</pre>;
return (
<div>
{data.length === 0 ? (
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
<h3>No user payments yet.</h3>
</div>
) : (
<>
<Table className="overflow-scroll">
<TableHeader>
<TableRow>
<TableHead>Devices paid</TableHead>
<TableHead>User</TableHead>
<TableHead>Amount</TableHead>
<TableHead>Duration</TableHead>
<TableHead>Payment Status</TableHead>
<TableHead>Payment Method</TableHead>
<TableHead>MIB Reference</TableHead>
<TableHead>Paid At</TableHead>
<TableHead>Action</TableHead>
</TableRow>
</TableHeader>
<TableBody className="overflow-scroll">
{data.map((payment) => (
<TableRow
className={`${payment.paid && "title-bg dark:bg-black"}`}
key={payment.id}
>
<TableCell className="font-medium">
<ol className="list-disc list-inside text-sm">
{payment.devices.map((device) => (
<li
key={device.id}
className="text-sm text-muted-foreground"
>
{device.name}
</li>
))}
</ol>
</TableCell>
<TableCell className="font-medium">
{/* {payment.user.id_card} */}
<div className="flex flex-col items-start">
{payment?.user?.name}
<span className="text-muted-foreground">
{payment?.user?.id_card}
</span>
</div>{" "}
</TableCell>
<TableCell>{payment.amount} MVR</TableCell>
<TableCell>{payment.number_of_months} Months</TableCell>
// <TableCell>{payment.id}</TableCell>
// <TableCell>
// <Link href={`/payments/${payment.id}/verify`}>
// <Button>Details</Button>
// </Link>
// </TableCell>
// </TableRow>
// ))}
// </TableBody>
// <TableFooter>
// <TableRow>
// <TableCell colSpan={8}>
// {query.length > 0 && (
// <p className="text-sm text-muted-foreground">
// Showing {payments.length} locations for &quot;{query}
// &quot;
// </p>
// )}
// </TableCell>
// <TableCell className="text-muted-foreground">
// {totalPayments} payments
// </TableCell>
// </TableRow>
// </TableFooter>
// </Table>
// <Pagination totalPages={totalPages} currentPage={page} />
// </>
// )}
// </div>
// );
<TableCell>
{payment.status === "PENDING" ? (
<Badge
variant="outline"
className="bg-yellow-100 text-black"
>
{payment.status}
</Badge>
) : payment.status === "PAID" ? (
<Badge
variant="outline"
className="bg-lime-100 text-black"
>
{payment.status}
</Badge>
) : (
<Badge
variant="outline"
className="bg-red-100 text-black"
>
{payment.status}
</Badge>
)}
</TableCell>
<TableCell>{payment.method}</TableCell>
<TableCell>{payment.mib_reference}</TableCell>
<TableCell>
{new Date(payment.paid_at ?? "").toLocaleDateString(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
minute: "2-digit",
hour: "2-digit",
},
)}
</TableCell>
<TableCell>
<Link href={`/payments/${payment.id}`}>
<Button>Details</Button>
</Link>
</TableCell>
</TableRow>
))}
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={10} className="text-muted-foreground">
{meta?.total === 1 ? (
<p className="text-center">Total {meta?.total} payment.</p>
) : (
<p className="text-center">Total {meta?.total} payments.</p>
)}{" "}
</TableCell>
</TableRow>
</TableFooter>
</Table>
<Pagination
totalPages={meta?.last_page}
currentPage={meta?.current_page}
/>
</>
)}
</div>
);
}

View File

@@ -0,0 +1,33 @@
import { EyeIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Card,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
export function AgreementCard({ agreement }: { agreement: string }) {
return (
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle>Sarlink User Agreement</CardTitle>
<CardDescription>User agreement for Sarlink services.</CardDescription>
</CardHeader>
<CardFooter className="flex-col gap-2">
<a
target="_blank"
rel="noopener noreferrer"
className="w-full hover:cursor-pointer"
href={agreement}
>
<Button type="button" className="w-full hover:cursor-pointer">
<EyeIcon />
View Agreement
</Button>
</a>
</CardFooter>
</Card>
);
}

View File

@@ -1,13 +1,14 @@
"use client";
import { Loader2, User as UserIcon } from "lucide-react";
import Link from "next/link";
import { signOut, useSession } from "next-auth/react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { Loader2, User as UserIcon } from "lucide-react";
import { signOut, useSession } from "next-auth/react";
import { useState } from "react";
export function AccountPopover() {
const session = useSession();
@@ -36,16 +37,23 @@ export function AccountPopover() {
<p>{session.data?.user?.mobile}</p>
</div>
</div>
<Button
disabled={loading}
onClick={async () => {
setLoading(true);
await signOut();
setLoading(false);
}}
>
{loading ? <Loader2 className="animate-spin" /> : "Logout"}
</Button>
<div className="flex flex-col gap-2">
<Button
disabled={loading}
onClick={async () => {
setLoading(true);
await signOut();
setLoading(false);
}}
>
{loading ? <Loader2 className="animate-spin" /> : "Logout"}
</Button>
<Link href="/profile" className="text-muted-foreground">
<Button variant={"secondary"} className="w-full">
View Profile
</Button>
</Link>
</div>
</div>
</PopoverContent>
</Popover>

View File

@@ -1,7 +1,7 @@
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { NuqsAdapter } from 'nuqs/adapters/next/app'
import { getProfile } from "@/actions/payment";
import { NuqsAdapter } from "nuqs/adapters/next/app";
import { getProfile } from "@/actions/user-actions";
import { authOptions } from "@/app/auth";
import { DeviceCartDrawer } from "@/components/device-cart";
import { ModeToggle } from "@/components/theme-toggle";
@@ -19,7 +19,9 @@ import { AccountPopover } from "./account-popver";
export async function ApplicationLayout({
children,
}: { children: React.ReactNode }) {
}: {
children: React.ReactNode;
}) {
const session = await getServerSession(authOptions);
if (!session) return redirect("/auth/signin");
@@ -50,9 +52,7 @@ export async function ApplicationLayout({
/>
<DeviceCartDrawer />
<div className="p-4 flex flex-col flex-1 rounded-lg bg-background">
<NuqsAdapter>
{children}
</NuqsAdapter>
<NuqsAdapter>{children}</NuqsAdapter>
</div>
</SidebarInset>
</SidebarProvider>

View File

@@ -1,14 +1,13 @@
"use client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import Link from "next/link";
import { signup } from "@/actions/auth-actions";
import { cn } from "@/lib/utils";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import * as React from "react";
import { signup } from "@/actions/auth-actions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
@@ -19,9 +18,8 @@ import {
SelectValue,
} from "@/components/ui/select";
import type { ApiResponse, Atoll } from "@/lib/backend-types";
import { cn } from "@/lib/utils";
import { getAtolls } from "@/queries/islands";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import Image from "next/image";
export default function SignUpForm() {
const { data: atolls } = useQuery<ApiResponse<Atoll>>({
@@ -59,7 +57,8 @@ export default function SignUpForm() {
<Link href="login" className="underline">
login
</Link>
</div>-
</div>
-
</>
);
}
@@ -72,12 +71,20 @@ export default function SignUpForm() {
{/* Logo */}
<div className="mb-8">
<div className="w-20 h-20 bg-transparent backdrop-blur-sm rounded-2xl flex items-center justify-center mx-auto mb-4">
<Image src="/logo.png" alt="Company Logo" height={1080} width={1080} className="w-12 h-12 text-white" />
<Image
src="/logo.png"
alt="Company Logo"
height={1080}
width={1080}
className="w-12 h-12 text-white"
/>
</div>
<h3 className="text-xl font-semibold dark:text-orange-100">SAR Link Portal</h3>
<h3 className="text-xl font-semibold dark:text-orange-100">
SAR Link by OmegaTech Solutions
</h3>
</div>
<h1 className="text-4xl font-bold mb-6">Welcome to Our Platform</h1>
<h1 className="text-4xl font-bold mb-6">Register your account</h1>
<p className="text-xl mb-8 dark:text-orange-100">
Pay for your devices and track your bills.
</p>
@@ -92,7 +99,10 @@ export default function SignUpForm() {
<div className="max-w-sm shadow-2xl shadow-sarLinkOrange/20 h-fit my-auto mt-2 w-full bg-white dark:bg-transparent rounded-lg m-auto backdrop-blur-lg self-center border-2 border-sarLinkOrange/10 dark:border-sarLinkOrange/50">
<div className="py-2 px-4 my-2 space-y-2">
<div className="space-y-2">
<label htmlFor="name" className="text-sm font-medium text-slate-700 dark:text-slate-300">
<label
htmlFor="name"
className="text-sm font-medium text-slate-700 dark:text-slate-300"
>
Full Name
</label>
@@ -100,12 +110,14 @@ export default function SignUpForm() {
className={cn(
"text-base",
actionState?.errors?.fieldErrors.name &&
"border-2 border-red-500",
"border-2 border-red-500",
)}
name="name"
type="text"
disabled={isPending}
defaultValue={(actionState?.payload?.get("name") || "") as string}
defaultValue={
(actionState?.payload?.get("name") || "") as string
}
placeholder="Full Name"
/>
{actionState?.errors?.fieldErrors.name && (
@@ -115,7 +127,10 @@ export default function SignUpForm() {
)}
</div>
<div className="space-y-2">
<label htmlFor="id_card" className="text-sm font-medium text-slate-700 dark:text-slate-300">
<label
htmlFor="id_card"
className="text-sm font-medium text-slate-700 dark:text-slate-300"
>
ID Card
</label>
<Input
@@ -129,7 +144,7 @@ export default function SignUpForm() {
className={cn(
"text-base",
actionState?.errors?.fieldErrors?.id_card &&
"border-2 border-red-500",
"border-2 border-red-500",
)}
placeholder="ID Card"
/>
@@ -146,7 +161,10 @@ export default function SignUpForm() {
</div>
<div>
<div className="space-y-2">
<label htmlFor="atoll" className="text-sm font-medium text-slate-700 dark:text-slate-300">
<label
htmlFor="atoll"
className="text-sm font-medium text-slate-700 dark:text-slate-300"
>
Atoll
</label>
<Select
@@ -154,7 +172,9 @@ export default function SignUpForm() {
onValueChange={(v) => {
console.log({ v });
setAtoll(
atolls?.data.find((atoll) => atoll.id === Number.parseInt(v)),
atolls?.data.find(
(atoll) => atoll.id === Number.parseInt(v),
),
);
}}
name="atoll_id"
@@ -181,7 +201,10 @@ export default function SignUpForm() {
</Select>
</div>
<div className="space-y-2">
<label htmlFor="island" className="text-sm font-medium text-slate-700 dark:text-slate-300">
<label
htmlFor="island"
className="text-sm font-medium text-slate-700 dark:text-slate-300"
>
Island
</label>
<Select disabled={isPending} name="island_id">
@@ -192,7 +215,10 @@ export default function SignUpForm() {
<SelectGroup>
<SelectLabel>Islands</SelectLabel>
{atoll?.islands?.map((island) => (
<SelectItem key={island.id} value={island.id.toString()}>
<SelectItem
key={island.id}
value={island.id.toString()}
>
{island.name}
</SelectItem>
))}
@@ -208,14 +234,17 @@ export default function SignUpForm() {
</div>
<div className="space-y-2">
<label htmlFor="address" className="text-sm font-medium text-slate-700 dark:text-slate-300">
<label
htmlFor="address"
className="text-sm font-medium text-slate-700 dark:text-slate-300"
>
Address
</label>
<Input
className={cn(
"text-base",
actionState?.errors?.fieldErrors?.address &&
"border-2 border-red-500",
"border-2 border-red-500",
)}
disabled={isPending}
name="address"
@@ -233,18 +262,23 @@ export default function SignUpForm() {
</div>
<div className="space-y-2">
<label htmlFor="dob" className="text-sm font-medium text-slate-700 dark:text-slate-300">
<label
htmlFor="dob"
className="text-sm font-medium text-slate-700 dark:text-slate-300"
>
Date of Birth
</label>
<Input
className={cn(
"text-base",
actionState?.errors?.fieldErrors?.dob &&
"border-2 border-red-500",
"border-2 border-red-500",
)}
name="dob"
disabled={isPending}
defaultValue={(actionState?.payload?.get("dob") || "") as string}
defaultValue={
(actionState?.payload?.get("dob") || "") as string
}
type="date"
placeholder="Date of birth"
/>
@@ -260,7 +294,10 @@ export default function SignUpForm() {
)}
</div>
<div className="space-y-2">
<label htmlFor="accNo" className="text-sm font-medium text-slate-700 dark:text-slate-300">
<label
htmlFor="accNo"
className="text-sm font-medium text-slate-700 dark:text-slate-300"
>
Account Number
</label>
@@ -268,12 +305,14 @@ export default function SignUpForm() {
className={cn(
"text-base",
actionState?.errors?.fieldErrors.accNo &&
"border-2 border-red-500",
"border-2 border-red-500",
)}
name="accNo"
type="number"
disabled={isPending}
defaultValue={(actionState?.payload?.get("accNo") || "") as string}
defaultValue={
(actionState?.payload?.get("accNo") || "") as string
}
placeholder="Account no"
/>
{actionState?.errors?.fieldErrors.accNo && (
@@ -283,7 +322,10 @@ export default function SignUpForm() {
)}
</div>
<div className="space-y-2">
<label htmlFor="phone_number" className="text-sm font-medium text-slate-700 dark:text-slate-300">
<label
htmlFor="phone_number"
className="text-sm font-medium text-slate-700 dark:text-slate-300"
>
Phone Number
</label>
<Input
@@ -293,8 +335,8 @@ export default function SignUpForm() {
disabled={isPending}
className={cn(
!phoneNumberFromUrl &&
actionState?.errors?.fieldErrors?.phone_number &&
"border-2 border-red-500 rounded-md",
actionState?.errors?.fieldErrors?.phone_number &&
"border-2 border-red-500 rounded-md",
)}
defaultValue={NUMBER_WITHOUT_DASH ?? ""}
readOnly={Boolean(phoneNumberFromUrl)}
@@ -316,7 +358,8 @@ export default function SignUpForm() {
<input
type="checkbox"
defaultChecked={
((actionState?.payload?.get("terms") || "") as string) === "on"
((actionState?.payload?.get("terms") || "") as string) ===
"on"
}
name="terms"
id="terms"
@@ -340,7 +383,8 @@ export default function SignUpForm() {
<input
type="checkbox"
defaultChecked={
((actionState?.payload?.get("policy") || "") as string) === "on"
((actionState?.payload?.get("policy") || "") as string) ===
"on"
}
name="policy"
id="terms"
@@ -372,9 +416,7 @@ export default function SignUpForm() {
</Link>
</div>
</div>
</form>
</div>
);
}

View File

@@ -1,17 +1,18 @@
"use client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2 } from "lucide-react";
import { signIn } from "next-auth/react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { signIn } from "next-auth/react";
import { useTransition } from "react";
import { type SubmitHandler, useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
const OTPSchema = z.object({
pin: z.string().min(6, {
message: "Your one-time password must be 6 characters.",
@@ -20,7 +21,9 @@ const OTPSchema = z.object({
export default function VerifyOTPForm({
phone_number,
}: { phone_number: string }) {
}: {
phone_number: string;
}) {
const [isPending, startTransition] = useTransition();
const router = useRouter();
console.log("verification in OTP form", phone_number);
@@ -57,7 +60,7 @@ export default function VerifyOTPForm({
return (
<form
onSubmit={handleSubmit(onSubmit)}
className="w-full max-w-xs title-bg border rounded-lg shadow my-4"
className="w-full max-w-xs title-bg border-2 border-sarLinkOrange/50 rounded-lg shadow my-4"
>
<div className="grid pb-4 pt-4 gap-4 px-4">
<div className="flex flex-col gap-4">

View File

@@ -1,18 +1,20 @@
"use client";
import { Loader2 } from "lucide-react";
import Link from "next/link";
import { redirect, useSearchParams } from "next/navigation";
import { useActionState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import { VerifyRegistrationOTP } from "@/queries/authentication";
import { Loader2 } from "lucide-react";
import Link from "next/link";
import { redirect, useSearchParams } from "next/navigation";
import { useActionState } from "react";
export default function VerifyRegistrationOTPForm({
phone_number,
}: { phone_number: string }) {
}: {
phone_number: string;
}) {
console.log("verification in OTP form", phone_number);
const searchParams = useSearchParams();
@@ -26,7 +28,7 @@ export default function VerifyRegistrationOTPForm({
return (
<form
action={formAction}
className="w-full max-w-xs bg-white dark:bg-sarLinkOrange/10 title-bg border rounded-lg shadow my-4"
className="w-full max-w-xs bg-white dark:bg-sarLinkOrange/10 title-bg border-2 border-sarLinkOrange/50 rounded-lg shadow my-4"
>
<div className="grid pb-4 pt-4 gap-4 px-4">
<div className="flex flex-col gap-4">
@@ -35,7 +37,7 @@ export default function VerifyRegistrationOTPForm({
{state.message}
</p>
) : (
<p className="bg-sarLinkOrange/50 border border-yellow-900/50 dark:border-sarLinkOrange/50 rounded p-2 text-center text-sm text-gray-900 dark:text-gray-300">
<p className="bg-sarLinkOrange border border-yellow-900/50 dark:border-sarLinkOrange/50 rounded p-2 text-center text-sm text-gray-900 dark:text-orange-950">
Account verification OTP sent to [{phone_number}]
</p>
)}
@@ -57,7 +59,7 @@ export default function VerifyRegistrationOTPForm({
type="number"
placeholder="Enter OTP"
className={cn(
"bg-white text-black",
"bg-white text-black dark:text-white dark:bg-gray-950",
state.status === "verify_success" && "hidden",
)}
/>

View File

@@ -1,28 +1,36 @@
"use client";
import { cancelPayment } from "@/actions/payment";
import { tryCatch } from "@/utils/tryCatch";
import { Loader2, Trash2 } from "lucide-react";
import { useRouter } from "next/navigation";
import React from "react";
import { toast } from "sonner";
import { cancelPayment } from "@/actions/payment";
import { tryCatch } from "@/utils/tryCatch";
import { Button } from "../ui/button";
export default function CancelPaymentButton({
paymentId,
}: { paymentId: string }) {
}: {
paymentId: string;
}) {
const router = useRouter();
const [loading, setLoading] = React.useState(false);
return (
<Button
onClick={async () => {
setLoading(true);
const [error, x] = await tryCatch(cancelPayment({ id: paymentId }));
console.log(x);
const [error, payment] = await tryCatch(
cancelPayment({ id: paymentId }),
);
console.log(payment);
if (error) {
toast.error(error.message);
setLoading(false);
} else {
toast.success("Payment cancelled successfully!", {
description: `Your payment of ${payment?.amount} MVR has been cancelled.`,
closeButton: true,
});
router.replace("/devices");
}
}}

View File

@@ -0,0 +1,37 @@
"use client";
import { Loader2, Trash2 } from "lucide-react";
import { useRouter } from "next/navigation";
import React from "react";
import { toast } from "sonner";
import { cancelTopup } from "@/actions/payment";
import { tryCatch } from "@/utils/tryCatch";
import { Button } from "../ui/button";
export default function CancelTopupButton({ topupId }: { topupId: string }) {
const router = useRouter();
const [loading, setLoading] = React.useState(false);
return (
<Button
onClick={async () => {
setLoading(true);
const [error, topup] = await tryCatch(cancelTopup({ id: topupId }));
if (error) {
toast.error(error.message);
setLoading(false);
} else {
toast.success("Topup cancelled successfully!", {
description: `Your topup of ${topup?.amount} MVR has been cancelled.`,
closeButton: true,
});
router.replace("/top-ups");
}
}}
disabled={loading}
variant={"destructive"}
>
Cancel Topup
{loading ? <Loader2 className="animate-spin" /> : <Trash2 />}
</Button>
);
}

View File

@@ -0,0 +1,67 @@
"use client";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { Progress } from "@/components/ui/progress";
const calculateTimeLeft = (expiresAt: string) => {
const now = Date.now();
const expirationTime = new Date(expiresAt).getTime();
return Math.max(0, Math.floor((expirationTime - now) / 1000));
};
const HumanizeTimeLeft = (seconds: number) => {
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
return `${minutes}m ${remainingSeconds}s`;
};
export default function ExpiryCountDown({
expiresAt,
expiryLabel,
}: {
expiresAt: string;
expiryLabel: string;
}) {
const [timeLeft, setTimeLeft] = useState(calculateTimeLeft(expiresAt));
const [mounted, setMounted] = useState(false);
const router = useRouter();
const pathname = usePathname();
useEffect(() => {
setMounted(true);
}, []);
useEffect(() => {
const timer = setInterval(() => {
setTimeLeft(calculateTimeLeft(expiresAt));
}, 1000);
return () => clearInterval(timer);
}, [expiresAt]);
useEffect(() => {
if (timeLeft <= 0) {
router.replace(pathname);
}
}, [timeLeft, router, pathname]);
if (!mounted) {
return null;
}
return (
<div className="overflow-clip relative mx-2 p-4 rounded-md border border-dashed flex items-center justify-between text-muted-foreground">
<div className="absolute inset-0 title-bg mask-b-from-0" />
{timeLeft ? (
<span>Time left: {HumanizeTimeLeft(timeLeft)}</span>
) : (
<span>{expiryLabel} has expired.</span>
)}
{timeLeft > 0 && (
<Progress
className="absolute bottom-0 left-0 right-0"
color="#f49b5b"
value={(timeLeft / 600) * 100}
/>
)}
</div>
);
}

View File

@@ -37,7 +37,7 @@ const initialState: BlockDeviceFormState = {
export default function BlockDeviceDialog({
device,
// admin,
admin,
parentalControl = false,
}: {
device: Device;
@@ -46,7 +46,10 @@ export default function BlockDeviceDialog({
parentalControl?: boolean;
}) {
const [open, setOpen] = useState(false);
const [state, formAction, isPending] = useActionState(blockDeviceAction, initialState);
const [state, formAction, isPending] = useActionState(
blockDeviceAction,
initialState,
);
const [isTransitioning, startTransition] = useTransition();
const handleSimpleBlock = () => {
@@ -97,9 +100,13 @@ export default function BlockDeviceDialog({
}
// If device is not blocked and user is not admin, show simple block button
if (!device.blocked && parentalControl) {
if ((!device.blocked && parentalControl) || !admin) {
return (
<Button onClick={handleSimpleBlock} disabled={isLoading} variant="destructive">
<Button
onClick={handleSimpleBlock}
disabled={isLoading}
variant="destructive"
>
<ShieldBan />
{isLoading ? <TextShimmer>Blocking</TextShimmer> : "Block"}
</Button>
@@ -137,10 +144,13 @@ export default function BlockDeviceDialog({
rows={10}
name="reason_for_blocking"
id="reason_for_blocking"
defaultValue={(state?.payload?.get("reason_for_blocking") || "") as string}
defaultValue={
(state?.payload?.get("reason_for_blocking") || "") as string
}
className={cn(
"col-span-5",
(state.fieldErrors?.reason_for_blocking) && "ring-2 ring-red-500",
"col-span-5 mt-2",
state.fieldErrors?.reason_for_blocking &&
"ring-2 ring-red-500",
)}
/>
<span className="text-sm text-red-500">
@@ -158,4 +168,4 @@ export default function BlockDeviceDialog({
</Dialog>
</div>
);
}
}

View File

@@ -9,92 +9,99 @@ import { cn } from "@/lib/utils";
import AddDevicesToCartButton from "./add-devices-to-cart-button";
import BlockDeviceDialog from "./block-device-dialog";
export default function ClickableRow({
device,
parentalControl,
admin = false,
}: { device: Device; parentalControl?: boolean; admin?: boolean }) {
const [devices, setDeviceCart] = useAtom(deviceCartAtom);
device,
parentalControl,
admin = false,
idx,
}: {
device: Device;
parentalControl?: boolean;
admin?: boolean;
idx?: number;
}) {
const [devices, setDeviceCart] = useAtom(deviceCartAtom);
return (
<TableRow
key={device.id}
className={cn(
(parentalControl === false && device.blocked) || device.is_active
? "cursor-not-allowed hover:bg-accent-foreground/10"
: "cursor-pointer hover:bg-muted-foreground/10",
)}
onClick={() => {
if (device.blocked) return;
if (device.is_active === true) return;
if (device.has_a_pending_payment === true) return;
if (parentalControl === true) return;
setDeviceCart((prev) =>
devices.some((d) => d.id === device.id)
? prev.filter((d) => d.id !== device.id)
: [...prev, device],
);
}}
>
<TableCell>
<div className="flex flex-col items-start">
<Link
className={cn(
"hover:underline font-semibold",
device.is_active ? "text-green-600" : "",
)}
href={`/devices/${device.id}`}
onClick={(e) => e.stopPropagation()}
>
{device.name}
</Link>
{device.is_active ? (
<div className="text-muted-foreground">
Active until{" "}
<span className="font-semibold">
{new Date(device.expiry_date || "").toLocaleDateString(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
},
)}
</span>
</div>
) : (
<p className="text-muted-foreground">Device Inactive</p>
)}
{device.has_a_pending_payment && (
<Link href={`/payments/${device.pending_payment_id}`}>
<span className="bg-muted rounded px-2 p-1 mt-2 flex hover:underline items-center justify-center gap-2 text-muted-foreground">
Payment Pending{" "}
<HandCoins className="animate-pulse" size={14} />
</span>
</Link>
)}
return (
<TableRow
key={device.id}
className={cn(
(parentalControl === false && device.blocked) || device.is_active
? "cursor-not-allowed hover:bg-accent-foreground/10"
: "cursor-pointer hover:bg-muted-foreground/10",
`motion-preset-fade-md motion-delay-${(idx || 1) * 75}ms`,
)}
onClick={() => {
if (device.blocked) return;
if (device.is_active === true) return;
if (device.has_a_pending_payment === true) return;
if (parentalControl === true) return;
setDeviceCart((prev) =>
devices.some((d) => d.id === device.id)
? prev.filter((d) => d.id !== device.id)
: [...prev, device],
);
}}
>
<TableCell>
<div className="flex flex-col items-start">
<Link
className={cn(
"hover:underline font-semibold",
device.is_active ? "text-green-600" : "",
)}
href={`/devices/${device.id}`}
onClick={(e) => e.stopPropagation()}
>
{device.name}
</Link>
{device.is_active ? (
<div className="text-muted-foreground">
Active until{" "}
<span className="font-semibold">
{new Date(device.expiry_date || "").toLocaleDateString(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
},
)}
</span>
</div>
) : (
<p className="text-muted-foreground">Device Inactive</p>
)}
{device.has_a_pending_payment && (
<Link href={`/payments/${device.pending_payment_id}`}>
<span className="bg-muted rounded px-2 p-1 mt-2 flex hover:underline items-center justify-center gap-2 text-muted-foreground">
Payment Pending{" "}
<HandCoins className="animate-pulse" size={14} />
</span>
</Link>
)}
{device.blocked_by === "ADMIN" && device.blocked && (
<div className="p-2 rounded border my-2 bg-white dark:bg-neutral-800 shadow">
<span className="font-semibold">Comment</span>
<p className="text-neutral-400">{device?.reason_for_blocking}</p>
</div>
)}
</div>
</TableCell>
<TableCell className="font-medium">{device.mac}</TableCell>
<TableCell className="font-medium">{device?.vendor}</TableCell>
<TableCell>
{!parentalControl ? (
<AddDevicesToCartButton device={device} />
) : (
<BlockDeviceDialog
admin={admin}
type={device.blocked ? "unblock" : "block"}
device={device}
parentalControl={parentalControl}
/>
)}
</TableCell>
</TableRow>
);
{device.blocked_by === "ADMIN" && device.blocked && (
<div className="p-2 rounded border my-2 bg-white dark:bg-neutral-800 shadow">
<span className="font-semibold">Comment</span>
<p className="text-neutral-400">{device?.reason_for_blocking}</p>
</div>
)}
</div>
</TableCell>
<TableCell className="font-medium">{device.mac}</TableCell>
<TableCell className="font-medium">{device?.vendor}</TableCell>
<TableCell>
{!parentalControl ? (
<AddDevicesToCartButton device={device} />
) : (
<BlockDeviceDialog
admin={admin}
type={device.blocked ? "unblock" : "block"}
device={device}
parentalControl={parentalControl}
/>
)}
</TableCell>
</TableRow>
);
}

View File

@@ -10,99 +10,108 @@ import BlockDeviceDialog from "./block-device-dialog";
import { Badge } from "./ui/badge";
export default function DeviceCard({
device,
parentalControl,
}: { device: Device; parentalControl?: boolean }) {
const [devices, setDeviceCart] = useAtom(deviceCartAtom);
device,
parentalControl,
isAdmin,
}: {
device: Device;
parentalControl?: boolean;
isAdmin?: boolean;
}) {
const [devices, setDeviceCart] = useAtom(deviceCartAtom);
const isChecked = devices.some((d) => d.id === device.id);
const isChecked = devices.some((d) => d.id === device.id);
return (
<div
onKeyUp={() => { }}
onClick={() => {
if (device.blocked) return;
if (device.is_active === true) return;
if (device.has_a_pending_payment === true) return;
if (parentalControl === true) return;
setDeviceCart((prev) =>
devices.some((d) => d.id === device.id)
? prev.filter((d) => d.id !== device.id)
: [...prev, device],
);
}}
className="w-full"
>
<div
className={cn(
"flex text-sm justify-between items-center my-2 p-4 border rounded-md",
isChecked ? "bg-accent" : "",
device.is_active
? "cursor-not-allowed text-green-600 hover:bg-accent-foreground/10"
: "cursor-pointer hover:bg-muted-foreground/10",
)}
>
<div className="">
<div className="font-semibold flex flex-col items-start gap-2 mb-2">
<Link
className={cn("font-medium hover:underline ml-0.5", device.is_active ? "text-green-600" : "")}
href={`/devices/${device.id}`}
>
{device.name}
</Link>
<Badge variant={"outline"}>
<span className="font-medium">{device.mac}</span>
</Badge>
<Badge variant={"outline"}>
<span className="font-medium">{device.vendor}</span>
</Badge>
</div>
return (
// biome-ignore lint/a11y/noStaticElementInteractions: <dw about it>
<div
onKeyUp={() => {}}
onClick={() => {
if (device.blocked) return;
if (device.is_active === true) return;
if (device.has_a_pending_payment === true) return;
if (parentalControl === true) return;
setDeviceCart((prev) =>
devices.some((d) => d.id === device.id)
? prev.filter((d) => d.id !== device.id)
: [...prev, device],
);
}}
className="w-full"
>
<div
className={cn(
"flex text-sm justify-between items-center my-2 p-4 border rounded-md motion-preset-fade-md",
isChecked ? "bg-accent" : "",
device.is_active
? "cursor-not-allowed text-green-600 hover:bg-accent-foreground/10"
: "cursor-pointer hover:bg-muted-foreground/10",
)}
>
<div className="">
<div className="font-semibold flex flex-col items-start gap-2 mb-2">
<Link
className={cn(
"font-medium hover:underline ml-0.5",
device.is_active ? "text-green-600" : "",
)}
href={`/devices/${device.id}`}
>
{device.name}
</Link>
<Badge variant={"outline"}>
<span className="font-medium">{device.mac}</span>
</Badge>
<Badge variant={"outline"}>
<span className="font-medium">{device.vendor}</span>
</Badge>
</div>
{device.is_active ? (
<div className="text-muted-foreground ml-0.5">
Active until{" "}
<span className="font-semibold">
{new Date(device.expiry_date || "").toLocaleDateString(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
},
)}
</span>
</div>
) : (
<p className="text-muted-foreground ml-0.5">Device Inactive</p>
)}
{device.has_a_pending_payment && (
<Link href={`/payments/${device.pending_payment_id}`}>
<span className="bg-muted rounded px-2 p-1 mt-2 flex hover:underline items-center justify-center gap-2 text-muted-foreground text-yellow-600">
Payment Pending{" "}
<HandCoins className="animate-pulse" size={14} />
</span>
</Link>
)}
{device.is_active ? (
<div className="text-muted-foreground ml-0.5">
Active until{" "}
<span className="font-semibold">
{new Date(device.expiry_date || "").toLocaleDateString(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
},
)}
</span>
</div>
) : (
<p className="text-muted-foreground ml-0.5">Device Inactive</p>
)}
{device.has_a_pending_payment && (
<Link href={`/payments/${device.pending_payment_id}`}>
<span className="bg-muted rounded px-2 p-1 mt-2 flex hover:underline items-center justify-center gap-2 text-yellow-600">
Payment Pending{" "}
<HandCoins className="animate-pulse" size={14} />
</span>
</Link>
)}
{device.blocked && device.blocked_by === "ADMIN" && (
<div className="p-2 rounded border my-2 w-full">
<span className="uppercase text-red-500">Blocked by admin </span>
<p className="text-neutral-500">{device?.reason_for_blocking}</p>
</div>
)}
</div>
<div>
{!parentalControl ? (
<AddDevicesToCartButton device={device} />
) : (
<BlockDeviceDialog
admin={false}
type={device.blocked ? "unblock" : "block"}
device={device}
/>
)}
</div>
</div>
</div>
);
{device.blocked && device.blocked_by === "ADMIN" && (
<div className="p-2 rounded border my-2 w-full">
<span className="uppercase text-red-500">Blocked by admin </span>
<p className="text-neutral-500">{device?.reason_for_blocking}</p>
</div>
)}
</div>
<div>
{!parentalControl ? (
<AddDevicesToCartButton device={device} />
) : (
<BlockDeviceDialog
admin={isAdmin}
type={device.blocked ? "unblock" : "block"}
device={device}
/>
)}
</div>
</div>
</div>
);
}

View File

@@ -16,7 +16,7 @@ export function DeviceCartDrawer() {
if (devices.length === 0) return null;
return (
<div className="bg-sarLinkOrange rounded-lg shadow-2xl dark:hover:bg-orange-900 fixed bottom-20 w-80 uppercase h-auto z-20 left-1/2 transform -translate-x-1/2 hover:ring-2 hover:ring-sarLinkOrange transition-all duration-200 p-2 flex flex-col gap-2">
<div className="bg-sarLinkOrange rounded-lg shadow-2xl dark:bg-orange-900 fixed bottom-20 w-80 uppercase h-auto z-20 left-1/2 transform -translate-x-1/2 hover:ring-2 hover:ring-sarLinkOrange transition-all duration-200 p-2 flex flex-col gap-2">
<Button
size={"lg"}
className="w-ful"
@@ -24,7 +24,8 @@ export function DeviceCartDrawer() {
variant="secondary"
>
<MonitorSmartphone />
Pay {devices.length > 0 && `(${devices.length})`} {devices.length > 1 ? "devices" : "device"}
Pay {devices.length > 0 && `(${devices.length})`}{" "}
{devices.length > 1 ? "devices" : "device"}
</Button>
<Button
variant={"destructive"}

View File

@@ -0,0 +1,66 @@
import { Skeleton } from "@/components/ui/skeleton";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { cn } from "@/lib/utils";
type TableSkeletonProps = {
headers: string[];
length: number;
};
export default function TableSkeleton({ headers, length }: TableSkeletonProps) {
return (
<>
<div className="hidden sm:block w-full">
<Table className="overflow-scroll w-full">
<TableHeader>
<TableRow>
{headers.map((header, index) => (
<TableHead key={`${index + 1}`}>{header}</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody className="overflow-scroll">
{Array.from({ length }).map((_, i) => (
<TableRow key={`${i + 1}`}>
{headers.map((_, index) => (
<TableCell key={`${index + 1}`}>
<Skeleton className="w-full h-10 rounded" />
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
<div className="sm:hidden my-4 w-full">
{Array.from({ length }).map((_, i) => (
<DeviceCardSkeleton key={`${i + 1}`} />
))}
</div>
</>
);
}
function DeviceCardSkeleton() {
return (
<div
className={cn(
"flex text-sm justify-between items-center my-2 p-4 border rounded-md w-full",
)}
>
<div className="font-semibold flex w-full flex-col items-start gap-2 mb-2 relative">
<Skeleton className="w-32 h-6" />
<Skeleton className="w-36 h-6" />
<Skeleton className="w-32 h-4" />
<Skeleton className="w-40 h-8" />
</div>
</div>
);
}

View File

@@ -1,5 +1,10 @@
"use client";
import { useAtom, useAtomValue, useSetAtom } from "jotai";
import { CircleDollarSign, Loader2 } from "lucide-react";
import { redirect, usePathname } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { createPayment } from "@/actions/payment";
import DeviceCard from "@/components/device-card";
import NumberInput from "@/components/number-input";
@@ -7,41 +12,20 @@ import { Button } from "@/components/ui/button";
import { deviceCartAtom, numberOfMonths } from "@/lib/atoms";
import type { NewPayment } from "@/lib/backend-types";
import { tryCatch } from "@/utils/tryCatch";
import { useAtom, useAtomValue, useSetAtom } from "jotai";
import { CircleDollarSign, Loader2 } from "lucide-react";
import { redirect, usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import FullPageLoader from "./full-page-loader";
export default function DevicesForPayment() {
const baseAmount = 100;
const discountPercentage = 75;
const pathname = usePathname();
const devices = useAtomValue(deviceCartAtom);
const setDeviceCart = useSetAtom(deviceCartAtom);
const [months, setMonths] = useAtom(numberOfMonths);
const [message, setMessage] = useState("");
const [disabled, setDisabled] = useState(false);
const [total, setTotal] = useState(0);
console.log(total);
useEffect(() => {
if (months === 7) {
setMessage("You will get 1 month free.");
} else if (months === 12) {
setMessage("You will get 2 months free.");
} else {
setMessage("");
}
setTotal(baseAmount + (devices.length + 1 - 1) * discountPercentage);
}, [months, devices.length]);
if (pathname === "/payments") {
return null;
}
const data: NewPayment = {
amount: 100,
number_of_months: 2,
number_of_months: months,
device_ids: devices.map((device) => device.id),
};
@@ -63,11 +47,6 @@ export default function DevicesForPayment() {
maxAllowed={12}
isDisabled={devices.length === 0}
/>
{message && (
<span className="title-bg text-lime-800 bg-lime-100/50 dark:text-lime-100 rounded text-center p-2 w-full">
{message}
</span>
)}
</div>
<Button
onClick={async () => {

View File

@@ -2,14 +2,13 @@ import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
Table,
TableBody,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { getDevices } from "@/queries/devices";
import { tryCatch } from "@/utils/tryCatch";
@@ -19,114 +18,108 @@ import DeviceCard from "./device-card";
import Pagination from "./pagination";
export async function DevicesTable({
searchParams,
parentalControl,
additionalFilters = {},
searchParams,
parentalControl,
additionalFilters = {},
}: {
searchParams: Promise<{
[key: string]: unknown;
}>;
parentalControl?: boolean;
additionalFilters?: Record<string, string | number | boolean>;
searchParams: Promise<{
[key: string]: unknown;
}>;
parentalControl?: boolean;
additionalFilters?: Record<string, string | number | boolean>;
}) {
const resolvedParams = await searchParams;
const session = await getServerSession(authOptions);
const isAdmin = session?.user?.is_admin;
const resolvedParams = await searchParams;
const session = await getServerSession(authOptions);
const isAdmin = session?.user?.is_admin;
const page = Number.parseInt(resolvedParams.page as string) || 1;
const limit = 10;
const offset = (page - 1) * limit;
const page = Number.parseInt(resolvedParams.page as string) || 1;
const limit = 10;
const offset = (page - 1) * limit;
// Build params object for getDevices
const apiParams: Record<string, string | number | undefined> = {};
for (const [key, value] of Object.entries(resolvedParams)) {
if (value !== undefined && value !== "") {
apiParams[key] = typeof value === "number" ? value : String(value);
}
}
// Build params object for getDevices
const apiParams: Record<string, string | number | undefined> = {};
for (const [key, value] of Object.entries(resolvedParams)) {
if (value !== undefined && value !== "") {
apiParams[key] = typeof value === "number" ? value : String(value);
}
}
for (const [key, value] of Object.entries(additionalFilters)) {
if (value !== undefined && value !== "") {
apiParams[key] = typeof value === "number" ? value : String(value);
}
}
apiParams.limit = limit;
apiParams.offset = offset;
console.log("API Params:", apiParams);
const [error, devices] = await tryCatch(
getDevices(apiParams),
);
if (error) {
if (error.message === "UNAUTHORIZED") {
redirect("/auth/signin");
} else {
return <ClientErrorMessage message={error.message} />;
}
}
const { meta, data } = devices;
return (
<div>
{data?.length === 0 ? (
<div className="h-[calc(100svh-400px)] text-muted-foreground flex flex-col items-center justify-center my-4">
<h3>No devices.</h3>
</div>
) : (
<>
<div className="hidden sm:block">
<Table className="overflow-scroll">
<TableCaption>Table of all devices.</TableCaption>
<TableHeader>
<TableRow>
<TableHead>Device Name</TableHead>
<TableHead>MAC Address</TableHead>
<TableHead>Vendor</TableHead>
<TableHead>#</TableHead>
</TableRow>
</TableHeader>
<TableBody className="overflow-scroll">
{data?.map((device) => (
<ClickableRow
admin={isAdmin}
key={device.id}
device={device}
parentalControl={parentalControl}
/>
))}
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={4} className="text-muted-foreground">
{meta?.total === 1 ? (
<p className="text-center">
Total {meta?.total} device.
</p>
) : (
<p className="text-center">
Total {meta?.total} devices.
</p>
)}
</TableCell>
</TableRow>
</TableFooter>
</Table>
</div>
<div className="sm:hidden my-4">
{data?.map((device) => (
<DeviceCard
parentalControl={parentalControl}
key={device.id}
device={device}
/>
))}
</div>
<Pagination
totalPages={meta?.last_page}
currentPage={meta?.current_page}
/>
</>
)
}
</div >
);
for (const [key, value] of Object.entries(additionalFilters)) {
if (value !== undefined && value !== "") {
apiParams[key] = typeof value === "number" ? value : String(value);
}
}
apiParams.limit = limit;
apiParams.offset = offset;
const [error, devices] = await tryCatch(getDevices(apiParams));
if (error) {
if (error.message === "UNAUTHORIZED") {
redirect("/auth/signin");
} else {
return <ClientErrorMessage message={error.message} />;
}
}
const { meta, data } = devices;
return (
<div>
{data?.length === 0 ? (
<div className="h-[calc(100svh-400px)] text-muted-foreground flex flex-col items-center justify-center my-4">
<h3>{parentalControl ? "No active devices" : "No devices."}</h3>
</div>
) : (
<>
<div className="hidden sm:block">
<Table className="overflow-scroll">
<TableHeader>
<TableRow>
<TableHead>Device Name</TableHead>
<TableHead>MAC Address</TableHead>
<TableHead>Vendor</TableHead>
<TableHead>#</TableHead>
</TableRow>
</TableHeader>
<TableBody className="overflow-scroll">
{data?.map((device, idx) => (
<ClickableRow
admin={isAdmin}
key={device.id}
device={device}
parentalControl={parentalControl}
idx={idx + 1}
/>
))}
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={4} className="text-muted-foreground">
{meta?.total === 1 ? (
<p className="text-center">Total {meta?.total} device.</p>
) : (
<p className="text-center">
Total {meta?.total} devices.
</p>
)}
</TableCell>
</TableRow>
</TableFooter>
</Table>
</div>
<div className="sm:hidden my-4">
{data?.map((device) => (
<DeviceCard
parentalControl={parentalControl}
key={device.id}
device={device}
isAdmin={isAdmin}
/>
))}
</div>
<Pagination
totalPages={meta?.last_page}
currentPage={meta?.current_page}
/>
</>
)}
</div>
);
}

View File

@@ -1,201 +1,206 @@
"use client";
import {
BadgeDollarSign,
Clipboard,
ClipboardCheck,
Loader2,
Wallet,
} from "lucide-react";
import { useState } from "react";
import { BadgeDollarSign, Loader2, Wallet } from "lucide-react";
import { useActionState, useEffect } from "react";
import { toast } from "sonner";
import { verifyPayment } from "@/actions/payment";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableFooter,
TableRow,
type VerifyDevicePaymentState,
verifyDevicePayment,
} from "@/actions/payment";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableFooter,
TableRow,
} from "@/components/ui/table";
import type { Payment } from "@/lib/backend-types";
import type { User } from "@/lib/types/user";
import { shouldShowPaymentInfo } from "@/lib/utils";
import { AccountInfomation } from "./account-information";
import { Button } from "./ui/button";
const initialState: VerifyDevicePaymentState = {
message: "",
success: false,
fieldErrors: {},
};
export default function DevicesToPay({
payment,
user,
}: { payment?: Payment; user?: User }) {
const [verifyingWalletPayment, setVerifyingWalletPayment] = useState(false);
const [verifyingTransferPayment, setVerifyingTransferPayment] = useState(false);
const devices = payment?.devices;
if (devices?.length === 0) {
return null;
}
// 100+(n1)×75
const walletBalance = user?.wallet_balance ?? 0;
const isWalletPayVisible = walletBalance > (payment?.amount ?? 0);
return (
<div className="w-full">
<div className="p-2 flex flex-col gap-2">
<h3 className="title-bg my-1 p-2 border border-dashed rounded-md font-semibold text-lg">
{!payment?.paid ? "Devices to pay" : "Devices Paid"}
</h3>
<div className="flex flex-col gap-2">
{devices?.map((device) => (
<div
key={device.id}
className="bg-muted border rounded p-2 flex gap-2 items-center"
>
<div className="flex flex-col">
<div className="text-sm font-medium">{device.name}</div>
<div className="text-xs text-muted-foreground">
{device.mac}
</div>
</div>
</div>
))}
</div>
</div>
<div className="m-2 flex items-end justify-end p-2 text-sm text-foreground border rounded">
<Table>
<TableCaption>
<div className="max-w-sm mx-auto">
<p>Please send the following amount to the payment address</p>
<AccountInfomation
accName="Baraveli Dev"
accountNo="90101400028321000"
/>
{payment?.paid ? (
<Button
size={"lg"}
variant={"secondary"}
disabled
className="dark:text-green-200 text-green-900 bg-green-500/20 uppercase font-semibold"
>
Payment Verified
</Button>
) : (
<div className="flex flex-col gap-2">
{isWalletPayVisible && (
<Button
disabled={verifyingWalletPayment || verifyingTransferPayment}
onClick={async () => {
setVerifyingWalletPayment(true);
await verifyPayment({
method: "WALLET",
id: payment?.id ?? "",
});
setVerifyingWalletPayment(false);
}}
variant={"secondary"}
size={"lg"}
>
{verifyingWalletPayment ? "Processing payment..." : "Pay with wallet"}
<Wallet />
</Button>
)}
<Button
disabled={verifyingTransferPayment || verifyingWalletPayment}
onClick={async () => {
setVerifyingTransferPayment(true);
try {
await verifyPayment({
id: payment?.id ?? "",
method: "TRANSFER"
});
toast.success("Payment verification successful!");
} catch (error: unknown) {
if (error instanceof Error) {
toast.error(error.message);
} else {
toast.error("Payment verification failed.");
}
} finally {
setVerifyingTransferPayment(false);
}
}}
size={"lg"}
className="mb-4"
>
{verifyingTransferPayment ? "Processing payment..." : "I have paid"}
{verifyingTransferPayment ? (
<Loader2 className="animate-spin" />
) : (
<BadgeDollarSign />
)}
</Button>
</div>
)}
</div>
</TableCaption>
<TableBody className="">
<TableRow>
<TableCell>Total Devices</TableCell>
<TableCell className="text-right text-xl">
{devices?.length}
</TableCell>
</TableRow>
<TableRow>
<TableCell>Duration</TableCell>
<TableCell className="text-right text-xl">
{payment?.number_of_months} Months
</TableCell>
</TableRow>
</TableBody>
<TableFooter>
<TableRow className="">
<TableCell colSpan={1}>Total Due</TableCell>
<TableCell className="text-right text-3xl font-bold">
{payment?.amount?.toFixed(2)}
</TableCell>
</TableRow>
</TableFooter>
</Table>
</div>
</div>
);
}
function AccountInfomation({
accountNo,
accName,
payment,
user,
disabled,
}: {
accountNo: string;
accName: string;
payment?: Payment;
user?: User;
disabled?: boolean;
}) {
const [accNo, setAccNo] = useState(false);
return (
<div className="justify-start items-start border my-4 flex flex-col gap-2 p-2 rounded-md">
<h6 className="title-bg uppercase p-2 border rounded w-full font-semibold">
Account Information
</h6>
<div className="border justify-start flex flex-col items-start bg-white/10 w-full p-2 rounded">
<div className="text-sm font-semibold">Account Name</div>
<span>{accName}</span>
</div>
<div className="border flex justify-between items-start gap-2 bg-white/10 w-full p-2 rounded">
<div className="flex flex-col items-start justify-start">
<p className="text-sm font-semibold">Account No</p>
<span>{accountNo}</span>
</div>
<Button
onClick={() => {
setTimeout(() => {
setAccNo(true);
navigator.clipboard.writeText(accountNo);
}, 2000);
toast.success("Account number copied!");
setAccNo((prev) => !prev);
}}
variant={"link"}
>
{accNo ? <Clipboard /> : <ClipboardCheck color="green" />}
</Button>
</div>
</div>
);
const [state, formAction, isPending] = useActionState(
verifyDevicePayment,
initialState,
);
// Handle toast notifications based on state changes
useEffect(() => {
if (state.success && state.message) {
toast.success("Payment successful!", {
closeButton: true,
description: state.message,
});
} else if (
!state.success &&
state.message &&
state.message !== initialState.message
) {
toast.error("Payment Verification Failed", {
closeButton: true,
description: state.message,
});
}
}, [state]);
const devices = payment?.devices;
if (devices?.length === 0) {
return null;
}
// 100+(n1)×75
const walletBalance = user?.wallet_balance ?? 0;
const isWalletPayVisible = walletBalance > (payment?.amount ?? 0);
return (
<div className="w-full">
<div className="p-2 flex flex-col gap-2">
<h3 className="title-bg my-1 p-2 border border-dashed rounded-md font-semibold text-lg">
{!payment?.paid ? "Devices to pay" : "Devices Paid"}
</h3>
<div className="flex flex-col gap-2">
{devices?.map((device) => (
<div
key={device.id}
className="bg-muted border rounded p-2 flex gap-2 items-center motion-preset-fade"
>
<div className="flex flex-col">
<div className="text-sm font-medium motion-preset-slide-up">
{device.name}
</div>
<div className="text-xs text-muted-foreground motion-preset-slide-up motion-delay-100">
{device.mac}
</div>
</div>
</div>
))}
</div>
</div>
<div className="m-2 flex items-end justify-end p-2 text-sm text-foreground border rounded">
<Table>
<TableCaption>
{shouldShowPaymentInfo(payment) && (
<div className="max-w-sm mx-auto">
<p>Please send the following amount to the payment address</p>
<AccountInfomation
accName="Baraveli Dev"
accountNo="90101400028321000"
/>
{payment?.paid ? (
<Button
size={"lg"}
variant={"secondary"}
disabled
className="dark:text-green-200 text-green-900 bg-green-500/20 uppercase font-semibold"
>
Payment Verified
</Button>
) : (
<div className="flex flex-col gap-2">
{isWalletPayVisible && (
<form action={formAction}>
<input
type="hidden"
name="paymentId"
value={payment?.id ?? ""}
/>
<input type="hidden" name="method" value="WALLET" />
<Button
disabled={isPending}
type="submit"
variant={"secondary"}
size={"lg"}
className="w-full"
>
{isPending
? "Processing payment..."
: "Pay with wallet"}
<Wallet />
</Button>
</form>
)}
<form action={formAction}>
<input
type="hidden"
name="paymentId"
value={payment?.id ?? ""}
/>
<input type="hidden" name="method" value="TRANSFER" />
<Button
disabled={isPending || disabled}
type="submit"
size={"lg"}
className="mb-4 w-full"
>
{isPending ? "Processing payment..." : "I have paid"}
{isPending ? (
<Loader2 className="animate-spin" />
) : (
<BadgeDollarSign />
)}
</Button>
</form>
</div>
)}
</div>
)}
</TableCaption>
<TableBody className="">
<TableRow>
<TableCell>Payment created</TableCell>
<TableCell className="text-right motion-preset-slide-up-sm">
{new Date(payment?.created_at ?? "").toLocaleDateString(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
minute: "2-digit",
hour: "2-digit",
second: "2-digit",
},
)}
</TableCell>
</TableRow>
<TableRow>
<TableCell>Total Devices</TableCell>
<TableCell className="text-right text-xl motion-preset-slide-up-sm motion-delay-75">
{devices?.length}
</TableCell>
</TableRow>
<TableRow>
<TableCell>Duration</TableCell>
<TableCell className="text-right text-xl motion-preset-slide-up-sm motion-delay-100">
{payment?.number_of_months} Months
</TableCell>
</TableRow>
</TableBody>
<TableFooter>
<TableRow className="">
<TableCell colSpan={1}>Total Due</TableCell>
<TableCell className="text-right text-3xl font-bold motion-preset-slide-up-sm motion-delay-150">
{payment?.amount?.toFixed(2)}
</TableCell>
</TableRow>
</TableFooter>
</Table>
</div>
</div>
);
}

View File

@@ -1,183 +1,218 @@
"use client"
import { Badge } from "@/components/ui/badge"
"use client";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Drawer, DrawerClose, DrawerContent, DrawerDescription, DrawerFooter, DrawerHeader, DrawerTitle, DrawerTrigger } from "@/components/ui/drawer";
import {
Drawer,
DrawerClose,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
} from "@/components/ui/drawer";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import { ListFilter, Loader2, X } from "lucide-react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useQueryState } from "nuqs";
import { useState, useTransition } from 'react';
import { useState, useTransition } from "react";
export default function DeviceFilter() {
const { replace } = useRouter();
const { replace } = useRouter();
const [isOpen, setIsOpen] = useState(false);
const [disabled, startTransition] = useTransition();
const searchParams = useSearchParams();
const pathname = usePathname();
const params = new URLSearchParams(searchParams.toString());
const [isOpen, setIsOpen] = useState(false);
const [disabled, startTransition] = useTransition();
const searchParams = useSearchParams();
const pathname = usePathname();
const params = new URLSearchParams(searchParams.toString());
const [urlInputName] = useQueryState("name", {
clearOnDefault: true,
});
const [urlInputMac] = useQueryState("mac", {
clearOnDefault: true,
});
const [urlInputVendor] = useQueryState("vendor", {
clearOnDefault: true,
});
const [urlInputName] = useQueryState("name", {
clearOnDefault: true
})
const [urlInputMac] = useQueryState("mac", {
clearOnDefault: true
})
const [urlInputVendor] = useQueryState("vendor", {
clearOnDefault: true
})
// Local state for input fields
const [inputName, setInputName] = useState(urlInputName ?? "");
const [inputMac, setInputMac] = useState(urlInputMac ?? "");
const [inputVendor, setInputVendor] = useState(urlInputVendor ?? "");
// Local state for input fields
const [inputName, setInputName] = useState(urlInputName ?? "");
const [inputMac, setInputMac] = useState(urlInputMac ?? "");
const [inputVendor, setInputVendor] = useState(urlInputVendor ?? "");
// Map filter keys to their state setters
const filterSetters: Record<
string,
React.Dispatch<React.SetStateAction<string>>
> = {
name: setInputName,
mac: setInputMac,
vendor: setInputVendor,
};
function handleSearch({
name,
mac,
vendor,
}: {
name: string;
mac: string;
vendor: string;
}) {
if (name) params.set("name", name);
else params.delete("name");
if (mac) params.set("mac", mac);
else params.delete("mac");
if (vendor) params.set("vendor", vendor);
else params.delete("vendor");
params.set("page", "1");
// Map filter keys to their state setters
const filterSetters: Record<string, React.Dispatch<React.SetStateAction<string>>> = {
name: setInputName,
mac: setInputMac,
vendor: setInputVendor,
};
function handleSearch({ name, mac, vendor }: { name: string; mac: string; vendor: string }) {
startTransition(() => {
replace(`${pathname}?${params.toString()}`);
});
}
if (name) params.set("name", name); else params.delete("name");
if (mac) params.set("mac", mac); else params.delete("mac");
if (vendor) params.set("vendor", vendor); else params.delete("vendor");
params.set("page", "1");
const appliedFilters = searchParams
.toString()
.split("&")
.filter((filter) => !filter.startsWith("page=") && filter);
return (
<div className="flex flex-col items-start justify-start gap-2 w-full">
<Drawer open={isOpen} onOpenChange={setIsOpen}>
<DrawerTrigger asChild>
<Button
className="w-full sm:w-48 flex items-end justify-between"
onClick={() => setIsOpen(!isOpen)}
variant="outline"
>
Filter
<ListFilter />
</Button>
</DrawerTrigger>
<DrawerContent>
<div className="mx-auto w-full max-w-3xl">
<DrawerHeader>
<DrawerTitle>Device Filters</DrawerTitle>
<DrawerDescription asChild>
<div>Select your desired filters here</div>
</DrawerDescription>
</DrawerHeader>
startTransition(() => {
replace(`${pathname}?${params.toString()}`);
});
}
<div className="grid sm:grid-cols-3 gap-4 p-4">
<Input
placeholder="Device name ..."
value={inputName || searchParams.get("name") || ""}
onChange={(e) => setInputName(e.target.value)}
/>
<Input
placeholder="Device Mac address ..."
value={inputMac || searchParams.get("mac") || ""}
onChange={(e) => setInputMac(e.target.value)}
/>
<Input
placeholder="Device vendor ..."
value={inputVendor || searchParams.get("vendor") || ""}
onChange={(e) => setInputVendor(e.target.value)}
/>
</div>
<DrawerFooter className="max-w-sm mx-auto">
<Button
onClick={() => {
handleSearch({
name: inputName ?? "",
mac: inputMac ?? "",
vendor: inputVendor ?? "",
});
}}
>
{disabled ? (
<>
<Loader2 className="ml-2 animate-spin" />
</>
) : (
<>Apply Filters</>
)}
</Button>
<Button
variant="secondary"
onClick={() => {
setInputName("");
setInputMac("");
setInputVendor("");
replace(pathname);
}}
>
Clear Filters
</Button>
const appliedFilters = searchParams
.toString()
.split("&")
.filter((filter) => !filter.startsWith("page=") && filter)
return (
<div className="flex flex-col items-start justify-start gap-2 w-full">
<Drawer open={isOpen} onOpenChange={setIsOpen}>
<DrawerTrigger asChild>
<Button className="w-full sm:w-48 flex items-end justify-between" onClick={() => setIsOpen(!isOpen)} variant="outline">
Filter
<ListFilter />
</Button>
</DrawerTrigger>
<DrawerContent>
<div className="mx-auto w-full max-w-3xl">
<DrawerHeader>
<DrawerTitle>Device Filters</DrawerTitle>
<DrawerDescription asChild>
<div>
Select your desired filters here
</div>
</DrawerDescription>
</DrawerHeader>
<DrawerClose asChild>
<Button variant="outline">Cancel</Button>
</DrawerClose>
</DrawerFooter>
</div>
</DrawerContent>
</Drawer>
<div className="flex gap-2 w-fit flex-wrap">
{appliedFilters.map((filter) => (
<Badge
aria-disabled={disabled}
variant={"outline"}
className={cn("flex p-2 gap-2 items-center justify-between", {
"opacity-50 pointer-events-none": disabled,
})}
key={filter}
>
<span className="text-md">{prettyPrintFilter(filter)}</span>
{disabled ? (
<Loader2 className="animate-spin" size={16} />
) : (
<X
className="bg-sarLinkOrange/50 rounded-full p-1 hover:cursor-pointer hover:ring ring-sarLinkOrange"
size={16}
onClick={() => {
const key = filter.split("=")[0];
params.delete(key);
<div className="grid sm:grid-cols-3 gap-4 p-4">
<Input
placeholder="Device name ..."
value={inputName || searchParams.get("name") || ""}
onChange={e => setInputName(e.target.value)}
/>
<Input
placeholder="Device Mac address ..."
value={inputMac || searchParams.get("mac") || ""}
onChange={e => setInputMac(e.target.value)}
/>
<Input
placeholder="Device vendor ..."
value={inputVendor || searchParams.get("vendor") || ""}
onChange={e => setInputVendor(e.target.value)}
/>
</div>
<DrawerFooter className="max-w-sm mx-auto">
<Button
onClick={() => {
handleSearch({
name: inputName ?? "",
mac: inputMac ?? "",
vendor: inputVendor ?? "",
});
}}
>
{disabled ? (
<>
<Loader2 className="ml-2 animate-spin" />
</>
) : (
<>
Apply Filters
</>
)}
</Button>
<Button variant="secondary" onClick={() => {
setInputName("");
setInputMac("");
setInputVendor("");
replace(pathname)
}}>
Clear Filters
</Button>
// Use the mapping to clear the correct input state
filterSetters[key]?.("");
<DrawerClose asChild>
<Button variant="outline">Cancel</Button>
</DrawerClose>
</DrawerFooter>
</div>
</DrawerContent>
</Drawer>
<div className="flex gap-2 w-fit flex-wrap">
{appliedFilters.map((filter) => (
<Badge
aria-disabled={disabled}
variant={"outline"}
className={cn("flex p-2 gap-2 items-center justify-between", { "opacity-50 pointer-events-none": disabled })}
key={filter}>
<span className="text-md">{prettyPrintFilter(filter)}</span>
{
disabled ? (
<Loader2 className="animate-spin" size={16} />
) : (
<X
className="bg-sarLinkOrange/50 rounded-full p-1 hover:cursor-pointer hover:ring ring-sarLinkOrange"
size={16}
onClick={() => {
const key = filter.split("=")[0];
params.delete(key);
// Use the mapping to clear the correct input state
filterSetters[key]?.("");
startTransition(() => {
replace(`${pathname}?${params.toString()}`);
});
}}
>
Remove
</X>
)
}
</Badge>
))}
</div>
</div>
);
startTransition(() => {
replace(`${pathname}?${params.toString()}`);
});
}}
>
Remove
</X>
)}
</Badge>
))}
</div>
</div>
);
}
function prettyPrintFilter(filter: string) {
const [key, value] = filter.split("=");
switch (key) {
case "name":
return <p>Device Name: <span className="text-muted-foreground">{value}</span></p>;
case "mac":
return <p>MAC Address: <span className="text-muted-foreground">{value}</span></p>;
case "vendor":
return <p>Vendor: <span className="text-muted-foreground">{value}</span></p>;
default:
return filter;
}
const [key, value] = filter.split("=");
switch (key) {
case "name":
return (
<p>
Device Name: <span className="text-muted-foreground">{value}</span>
</p>
);
case "mac":
return (
<p>
MAC Address: <span className="text-muted-foreground">{value}</span>
</p>
);
case "vendor":
return (
<p>
Vendor: <span className="text-muted-foreground">{value}</span>
</p>
);
default:
return filter;
}
}

View File

@@ -1,9 +1,9 @@
import React from 'react'
import { Loader2 } from 'lucide-react'
import React from "react";
import { Loader2 } from "lucide-react";
export default function FullPageLoader() {
return (
<div className='flex items-center justify-center h-screen'>
<Loader2 className='animate-spin' />
</div>
)
return (
<div className="flex items-center justify-center h-screen">
<Loader2 className="animate-spin" />
</div>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,74 +1,65 @@
import { PhoneIcon } from "lucide-react"
import Link from "next/link"
import { PhoneIcon } from "lucide-react";
import Link from "next/link";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion"
import { Button } from "@/components/ui/button"
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import { Button } from "@/components/ui/button";
export function GetMacAccordion() {
return (
<Accordion
type="single"
collapsible
className="w-full"
>
<AccordionItem value="item-1">
<AccordionTrigger>How do I find my MAC Address?</AccordionTrigger>
<AccordionContent className="flex flex-col gap-4 text-start">
<p>
A MAC (Media Access Control) address is a unique identifier assigned
to a device`&apos;`s network. It is used to identify the device on a
network, helping to differentiate devices on a network.
</p>
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="iphone">
<AccordionTrigger>iPhone</AccordionTrigger>
<AccordionContent>
Settings General About Wi-Fi Address
</AccordionContent>
</AccordionItem>
<AccordionItem value="redmi">
<AccordionTrigger>Redmi</AccordionTrigger>
<AccordionContent>
Settings About Wi-Fi MAC Address
</AccordionContent>
</AccordionItem>
<AccordionItem value="samsung">
<AccordionTrigger>Samsung</AccordionTrigger>
<AccordionContent>
Settings About phone Status Information Wi-Fi MAC Address
</AccordionContent>
</AccordionItem>
<AccordionItem value="windows">
<AccordionTrigger>Windows Laptop</AccordionTrigger>
<AccordionContent>
Settings Network and Internet Wi-Fi Hardware
Properties Physical address (MAC):
</AccordionContent>
</AccordionItem>
<AccordionItem value="other">
<AccordionTrigger>Other Device</AccordionTrigger>
<AccordionContent>
<p>
Please contact SAR Link for assistance.
</p>
<Link
href="tel:+9609198026"
>
<Button className="mt-4">
<PhoneIcon className="mr-2" />
9198026
</Button>
</Link>
</AccordionContent>
</AccordionItem>
</Accordion>
</AccordionContent>
</AccordionItem>
</Accordion>
)
return (
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="item-1">
<AccordionTrigger>How do I find my MAC Address?</AccordionTrigger>
<AccordionContent className="flex flex-col gap-4 text-start">
<p>
A MAC (Media Access Control) address is a unique identifier assigned
to a device`&apos;`s network. It is used to identify the device on a
network, helping to differentiate devices on a network.
</p>
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="iphone">
<AccordionTrigger>iPhone</AccordionTrigger>
<AccordionContent>
Settings General About Wi-Fi Address
</AccordionContent>
</AccordionItem>
<AccordionItem value="redmi">
<AccordionTrigger>Redmi</AccordionTrigger>
<AccordionContent>
Settings About Wi-Fi MAC Address
</AccordionContent>
</AccordionItem>
<AccordionItem value="samsung">
<AccordionTrigger>Samsung</AccordionTrigger>
<AccordionContent>
Settings About phone Status Information Wi-Fi MAC Address
</AccordionContent>
</AccordionItem>
<AccordionItem value="windows">
<AccordionTrigger>Windows Laptop</AccordionTrigger>
<AccordionContent>
Settings Network and Internet Wi-Fi Hardware Properties
Physical address (MAC):
</AccordionContent>
</AccordionItem>
<AccordionItem value="other">
<AccordionTrigger>Other Device</AccordionTrigger>
<AccordionContent>
<p>Please contact SAR Link for assistance.</p>
<Link href="tel:+9609198026">
<Button className="mt-4">
<PhoneIcon className="mr-2" />
9198026
</Button>
</Link>
</AccordionContent>
</AccordionItem>
</Accordion>
</AccordionContent>
</AccordionItem>
</Accordion>
);
}

View File

@@ -1,41 +1,54 @@
import { cn } from '@/lib/utils';
import { CheckCheck, X } from 'lucide-react';
import { CheckCheck, X } from "lucide-react";
import { cn } from "@/lib/utils";
export default function InputReadOnly({ label, value, labelClassName, className, showCheck = true, checkTrue = false }: {
label: string;
value: string;
labelClassName?: string;
className?: string;
showCheck?: boolean;
checkTrue?: boolean
export default function InputReadOnly({
label,
value,
labelClassName,
className,
showCheck = true,
checkTrue = false,
}: {
label: string;
value: string;
labelClassName?: string;
className?: string;
showCheck?: boolean;
checkTrue?: boolean;
}) {
return (
<div className={cn("relative flex items-center justify-between rounded-lg border border-input bg-background shadow-sm shadow-black/5 transition-shadow focus-within:border-ring focus-within:outline-none focus-within:ring-[3px] focus-within:ring-ring/20 has-disabled:cursor-not-allowed has-disabled:opacity-80 [&:has(input:is(:disabled))_*]:pointer-events-none", className)}>
<div>
return (
<div
className={cn(
"relative flex items-center justify-between rounded-lg border border-input bg-background shadow-sm shadow-black/5 transition-shadow focus-within:border-ring focus-within:outline-none focus-within:ring-[3px] focus-within:ring-ring/20 has-disabled:cursor-not-allowed has-disabled:opacity-80 [&:has(input:is(:disabled))_*]:pointer-events-none col-span-2 sm:col-span-1",
className,
)}
>
<div>
<label
htmlFor="input-33"
className={cn("block px-3 pt-2 text-xs font-medium", labelClassName)}
>
{label}
</label>
<input
id="input-33"
className="flex h-10 w-full bg-transparent px-3 pb-2 text-sm text-foreground placeholder:text-muted-foreground/70 focus-visible:outline-none"
placeholder={value}
disabled
value={value}
type="text"
/>
</div>
<label htmlFor="input-33" className={cn("block px-3 pt-2 text-xs font-medium", labelClassName)}>
{label}
</label>
<input
id="input-33"
className="flex h-10 w-full bg-transparent px-3 pb-2 text-sm text-foreground placeholder:text-muted-foreground/70 focus-visible:outline-none"
placeholder={value}
disabled
value={value}
type="text"
/>
</div>
{showCheck && (
<div>
{checkTrue ? (
<CheckCheck className='mx-4 text-green-500' />
) : (
<X className='mx-4 text-red-500' />
)}
</div>
)}
</div>
)
{showCheck && (
<div>
{checkTrue ? (
<CheckCheck className="mx-4 text-green-500" />
) : (
<X className="mx-4 text-red-500" />
)}
</div>
)}
</div>
);
}

View File

@@ -1,50 +1,63 @@
import { cn } from "@/lib/utils";
import { Minus, Plus } from "lucide-react";
import { useEffect } from "react";
import {
Button,
Group,
Input,
Label,
NumberField,
Button,
Group,
Input,
Label,
NumberField,
} from "react-aria-components";
import { cn } from "@/lib/utils";
export default function NumberInput({
maxAllowed,
label,
value,
onChange,
className,
isDisabled,
}: { maxAllowed?: number, label: string; value: number; onChange: (value: number) => void, className?: string, isDisabled?: boolean }) {
useEffect(() => {
if (maxAllowed) {
if (value > maxAllowed) {
onChange(maxAllowed);
}
}
}, [maxAllowed, value, onChange]);
return (
<NumberField isDisabled={isDisabled} className={cn(className)} value={value} minValue={0} onChange={onChange}>
<div className="space-y-2">
<Label className="text-sm font-medium text-foreground">{label}</Label>
<Group className="relative inline-flex h-9 w-full items-center overflow-hidden whitespace-nowrap rounded-lg border border-input text-sm shadow-sm shadow-black/5 transition-shadow data-[focus-within]:border-ring data-disabled:opacity-50 data-focus-within:outline-none data-focus-within:ring-[3px] data-[focus-within]:ring-ring/20">
<Button
slot="decrement"
className="-ms-px flex aspect-square h-[inherit] items-center justify-center rounded-s-lg border border-input bg-background text-sm text-muted-foreground/80 transition-shadow hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
>
<Minus size={16} strokeWidth={2} aria-hidden="true" />
</Button>
<Input className="w-full grow bg-background px-3 py-2 text-center text-base tabular-nums text-foreground focus:outline-none" />
<Button
slot="increment"
className="-me-px flex aspect-square h-[inherit] items-center justify-center rounded-e-lg border border-input bg-background text-sm text-muted-foreground/80 transition-shadow hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
>
<Plus size={16} strokeWidth={2} aria-hidden="true" />
</Button>
</Group>
</div>
</NumberField>
);
maxAllowed,
label,
value = 100,
onChange,
className,
isDisabled,
}: {
maxAllowed?: number;
label: string;
value?: number;
onChange: (value: number) => void;
className?: string;
isDisabled?: boolean;
}) {
useEffect(() => {
if (maxAllowed) {
if (value > maxAllowed) {
onChange(maxAllowed);
}
}
}, [maxAllowed, value, onChange]);
return (
<NumberField
isDisabled={isDisabled}
className={cn(className)}
value={value}
minValue={0}
onChange={onChange}
>
<div className="space-y-2">
<Label className="text-sm font-medium text-foreground">{label}</Label>
<Group className="relative inline-flex h-9 w-full items-center overflow-hidden whitespace-nowrap rounded-lg border border-input text-sm shadow-sm shadow-black/5 transition-shadow data-[focus-within]:border-ring data-disabled:opacity-50 data-focus-within:outline-none data-focus-within:ring-[3px] data-[focus-within]:ring-ring/20">
<Button
slot="decrement"
className="-ms-px flex aspect-square h-[inherit] items-center justify-center rounded-s-lg border border-input bg-background text-sm text-muted-foreground/80 transition-shadow hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
>
<Minus size={16} strokeWidth={2} aria-hidden="true" />
</Button>
<Input className="w-full grow bg-background px-3 py-2 text-center text-base tabular-nums text-foreground focus:outline-none" />
<Button
slot="increment"
className="-me-px flex aspect-square h-[inherit] items-center justify-center rounded-e-lg border border-input bg-background text-sm text-muted-foreground/80 transition-shadow hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
>
<Plus size={16} strokeWidth={2} aria-hidden="true" />
</Button>
</Group>
</div>
</NumberField>
);
}

View File

@@ -1,9 +1,9 @@
"use client";
import { Button } from "@/components/ui/button";
import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import React, { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
type PaginationProps = {
totalPages: number;
@@ -71,6 +71,10 @@ export default function Pagination({
const pageNumbers = generatePageNumbers();
if (totalPages <= 1) {
return null;
}
return (
<div className="flex items-center justify-center space-x-2 my-4">
{currentPage > 1 && (

View File

@@ -3,14 +3,13 @@ import Link from "next/link";
import { redirect } from "next/navigation";
import { getPayments } from "@/actions/payment";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
Table,
TableBody,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import type { Payment } from "@/lib/backend-types";
import { cn } from "@/lib/utils";
@@ -21,213 +20,265 @@ import { Button } from "./ui/button";
import { Separator } from "./ui/separator";
export async function PaymentsTable({
searchParams,
searchParams,
}: {
searchParams: Promise<{
query: string;
page: number;
sortBy: string;
}>;
searchParams: Promise<{
[key: string]: unknown;
}>;
}) {
const query = (await searchParams)?.query || "";
const [error, payments] = await tryCatch(getPayments());
const resolvedParams = await searchParams;
const page = Number.parseInt(resolvedParams.page as string) || 1;
const limit = 10;
const offset = (page - 1) * limit;
const apiParams: Record<string, string | number | undefined> = {};
for (const [key, value] of Object.entries(resolvedParams)) {
if (value !== undefined && value !== "") {
apiParams[key] = typeof value === "number" ? value : String(value);
}
}
apiParams.limit = limit;
apiParams.offset = offset;
const [error, payments] = await tryCatch(getPayments(apiParams));
if (error) {
if (error.message.includes("Unauthorized")) {
redirect("/auth/signin");
} else {
return <pre>{JSON.stringify(error, null, 2)}</pre>;
}
}
const { data, meta } = payments;
return (
<div>
{data?.length === 0 ? (
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
<h3>No Payments yet.</h3>
</div>
) : (
<>
<div className="hidden sm:block">
<Table className="overflow-scroll">
<TableCaption>Table of all devices.</TableCaption>
<TableHeader>
<TableRow>
<TableHead>Details</TableHead>
<TableHead>Duration</TableHead>
if (error) {
if (error.message.includes("Unauthorized")) {
redirect("/auth/signin");
} else {
return <pre>{JSON.stringify(error, null, 2)}</pre>;
}
}
const { data, meta } = payments;
return (
<div>
{data?.length === 0 ? (
<div className="h-[calc(100svh-400px)] text-muted-foreground flex flex-col items-center justify-center my-4">
<h3>No Payments.</h3>
</div>
) : (
<>
<div className="hidden sm:block">
<Table className="overflow-scroll">
<TableHeader>
<TableRow>
<TableHead>Details</TableHead>
<TableHead>Duration</TableHead>
<TableHead>Status</TableHead>
<TableHead>Amount</TableHead>
</TableRow>
</TableHeader>
<TableBody className="overflow-scroll">
{payments?.data?.map((payment) => (
<TableRow className="motion-preset-fade-md" key={payment.id}>
<TableCell>
<div
className={cn(
"flex flex-col items-start border rounded p-2",
payment?.paid
? "bg-green-500/10 border-dashed border-green-500"
: payment?.is_expired
? "bg-gray-500/10 border-dashed border-gray-500 dark:border-gray-500/50"
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
)}
>
<div className="flex items-center gap-2">
<Calendar size={16} opacity={0.5} />
<span className="text-muted-foreground">
{new Date(payment.created_at).toLocaleDateString(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
minute: "2-digit",
hour: "2-digit",
timeZone: "Indian/Maldives", // Force consistent timezone
},
)}
</span>
</div>
<TableHead>Amount</TableHead>
</TableRow>
</TableHeader>
<TableBody className="overflow-scroll">
{payments?.data?.map((payment) => (
<TableRow key={payment.id}>
<TableCell>
<div
className={cn(
"flex flex-col items-start border rounded p-2",
payment?.paid
? "bg-green-500/10 border-dashed border-green=500"
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
)}
>
<div className="flex items-center gap-2">
<Calendar size={16} opacity={0.5} />
<span className="text-muted-foreground">
{new Date(payment.created_at).toLocaleDateString(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
},
)}
</span>
</div>
<div className="flex items-center gap-2 mt-2">
<Link
className="font-medium hover:underline"
href={`/payments/${payment.id}`}
>
<Button size={"sm"} variant="outline">
View Details
</Button>
</Link>
</div>
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
<h3 className="text-sm font-medium">Devices</h3>
<ol className="list-disc list-inside text-sm">
{payment.devices.map((device) => (
<li
key={device.id}
className="text-sm text-muted-foreground"
>
{device.name}
</li>
))}
</ol>
</div>
</div>
</TableCell>
<div className="flex items-center gap-2 mt-2">
<Link
className="font-medium hover:underline"
href={`/payments/${payment.id}`}
>
<Button size={"sm"} variant="outline">
View Details
</Button>
</Link>
<Badge
className={cn(
payment?.paid
? "text-green-500 bg-green-500/20"
: "text-yellow-500 bg-yellow-500/20",
)}
variant={payment.paid ? "outline" : "secondary"}
>
{payment.paid ? "Paid" : "Unpaid"}
</Badge>
</div>
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
<h3 className="text-sm font-medium">Devices</h3>
<ol className="list-disc list-inside text-sm">
{payment.devices.map((device) => (
<li
key={device.id}
className="text-sm text-muted-foreground"
>
{device.name}
</li>
))}
</ol>
</div>
</div>
</TableCell>
<TableCell className="font-medium">
{payment.number_of_months} Months
</TableCell>
<TableCell>
<span className="font-semibold pr-2">
{payment.amount.toFixed(2)}
</span>
MVR
</TableCell>
</TableRow>
))}
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={2}>
{query.length > 0 && (
<p className="text-sm text-muted-foreground">
Showing {payments?.data?.length} payments for &quot;
{query}
&quot;
</p>
)}
</TableCell>
<TableCell className="text-muted-foreground">
{meta.total} payments
</TableCell>
</TableRow>
</TableFooter>
</Table>
<Pagination
totalPages={meta.total / meta.per_page}
currentPage={meta.current_page}
/>
</div>
<div className="sm:hidden block">
{data.map((payment) => (
<MobilePaymentDetails key={payment.id} payment={payment} />
))}
</div>
</>
)}
</div>
);
<TableCell className="font-medium">
{payment.number_of_months} Months
</TableCell>
<TableCell>
<span className="font-semibold pr-2">
{payment.paid ? (
<Badge
className={cn(
payment.status === "PENDING"
? "bg-yellow-100 text-yellow-700 dark:bg-yellow-700 dark:text-yellow-100"
: "bg-green-100 dark:bg-green-700",
)}
variant="outline"
>
{payment.status}
</Badge>
) : payment.is_expired ? (
<Badge>Expired</Badge>
) : (
<Badge variant="outline">{payment.status}</Badge>
)}
</span>
</TableCell>
<TableCell>
<span className="font-semibold pr-2">
{payment.amount.toFixed(2)}
</span>
MVR
</TableCell>
</TableRow>
))}
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={4} className="text-muted-foreground">
{meta?.total === 1 ? (
<p className="text-center">
Total {meta?.total} payment.
</p>
) : (
<p className="text-center">
Total {meta?.total} payments.
</p>
)}{" "}
</TableCell>
</TableRow>
</TableFooter>
</Table>
<Pagination
totalPages={meta.last_page}
currentPage={meta.current_page}
/>
</div>
<div className="sm:hidden block">
{data.map((payment) => (
<MobilePaymentDetails key={payment.id} payment={payment} />
))}
</div>
</>
)}
</div>
);
}
function MobilePaymentDetails({ payment }: { payment: Payment }) {
return (
<div
className={cn(
"flex flex-col items-start border rounded p-2 my-2",
payment?.paid
? "bg-green-500/10 border-dashed border-green=500"
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
)}
>
<div className="flex items-center gap-2">
<Calendar size={16} opacity={0.5} />
<span className="text-muted-foreground text-sm">
{new Date(payment.created_at).toLocaleDateString("en-US", {
month: "short",
day: "2-digit",
year: "numeric",
})}
</span>
</div>
export function MobilePaymentDetails({
payment,
isAdmin = false,
}: {
payment: Payment;
isAdmin?: boolean;
}) {
return (
<div
className={cn(
"flex flex-col items-start border rounded p-2 my-2 motion-preset-fade-md",
payment?.paid
? "bg-green-500/10 border-dashed border-green-500"
: payment?.is_expired
? "bg-gray-500/10 border-dashed border-gray-500 dark:border-gray-500/50"
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
)}
>
<div className="flex items-center gap-2">
<Calendar size={16} opacity={0.5} />
<span className="text-muted-foreground text-sm">
{new Date(payment.created_at).toLocaleDateString("en-US", {
month: "short",
day: "2-digit",
year: "numeric",
minute: "2-digit",
hour: "2-digit",
timeZone: "Indian/Maldives", // Force consistent timezone
})}
</span>
</div>
<div className="flex items-center gap-2 mt-2">
<Link
className="font-medium hover:underline"
href={`/payments/${payment.id}`}
>
<Button size={"sm"} variant="outline">
View Details
</Button>
</Link>
<Badge
className={cn(
payment?.paid
? "text-green-500 bg-green-500/20"
: "text-yellow-500 bg-yellow-500/20",
)}
variant={payment.paid ? "outline" : "secondary"}
>
{payment.paid ? "Paid" : "Unpaid"}
</Badge>
</div>
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
<h3 className="text-sm font-medium">Devices</h3>
<ol className="list-disc list-inside text-sm">
{payment.devices.map((device) => (
<li key={device.id} className="text-sm text-muted-foreground">
{device.name}
</li>
))}
</ol>
<div className="block sm:hidden">
<Separator className="my-2" />
<h3 className="text-sm font-medium">Duration</h3>
<span className="text-sm text-muted-foreground">
{payment.number_of_months} Months
</span>
<Separator className="my-2" />
<h3 className="text-sm font-medium">Amount</h3>
<span className="text-sm text-muted-foreground">
{payment.amount.toFixed(2)} MVR
</span>
</div>
</div>
</div>
);
<div className="flex items-center gap-2 mt-2">
<Link
className="font-medium hover:underline"
href={`/payments/${payment.id}`}
>
<Button size={"sm"} variant="outline">
View Details
</Button>
</Link>
</div>
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
<h3 className="text-sm font-medium">Devices</h3>
<ol className="list-disc list-inside text-sm">
{payment.devices.map((device) => (
<li key={device.id} className="text-sm text-muted-foreground">
{device.name}
</li>
))}
</ol>
<div className="block sm:hidden">
<Separator className="my-2" />
<h3 className="text-sm font-medium">Duration</h3>
<span className="text-sm text-muted-foreground">
{payment.number_of_months} Months
</span>
<Separator className="my-2" />
<h3 className="text-sm font-medium">Amount</h3>
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">
{payment.amount.toFixed(2)} MVR
</span>
<span className="font-semibold pr-2">
{payment.paid ? (
<Badge
className={cn(
payment.status === "PENDING"
? "bg-yellow-100 text-yellow-700 dark:bg-yellow-700 dark:text-yellow-100"
: "bg-green-100 dark:bg-green-700",
)}
variant="outline"
>
{payment.status}
</Badge>
) : payment.is_expired ? (
<Badge>Expired</Badge>
) : (
<Badge variant="secondary">{payment.status}</Badge>
)}
</span>
{isAdmin && (
<div className="my-2 text-primary flex flex-col items-start text-sm border rounded p-2 mt-2 w-full bg-white dark:bg-black">
{payment?.user?.name}
<span className="text-muted-foreground">
{payment?.user?.id_card}
</span>
</div>
)}
</div>
</div>
</div>
</div>
);
}

View File

@@ -1,90 +1,86 @@
"use client";
import {
discountPercentageAtom,
formulaResultAtom,
initialPriceAtom,
numberOfDaysAtom,
numberOfDevicesAtom,
discountPercentageAtom,
formulaResultAtom,
initialPriceAtom,
numberOfDaysAtom,
numberOfDevicesAtom,
} from "@/lib/atoms";
import { useAtom } from "jotai";
import { useEffect } from "react";
import NumberInput from "./number-input";
export default function PriceCalculator() {
const [initialPrice, setInitialPrice] = useAtom(initialPriceAtom);
const [discountPercentage, setDiscountPercentage] = useAtom(
discountPercentageAtom,
);
const [numberOfDevices, setNumberOfDevices] = useAtom(numberOfDevicesAtom);
const [numberOfDays, setNumberOfDays] = useAtom(numberOfDaysAtom);
const [formulaResult, setFormulaResult] = useAtom(formulaResultAtom);
const [initialPrice, setInitialPrice] = useAtom(initialPriceAtom);
const [discountPercentage, setDiscountPercentage] = useAtom(
discountPercentageAtom,
);
const [numberOfDevices, setNumberOfDevices] = useAtom(numberOfDevicesAtom);
const [numberOfDays, setNumberOfDays] = useAtom(numberOfDaysAtom);
const [formulaResult, setFormulaResult] = useAtom(formulaResultAtom);
useEffect(() => {
const basePrice = initialPrice + (numberOfDevices - 1) * discountPercentage;
setFormulaResult(
`Price for ${numberOfDevices} device(s) over ${numberOfDays} day(s): MVR ${basePrice.toFixed(2)}`,
);
}, [
initialPrice,
discountPercentage,
numberOfDevices,
numberOfDays,
setFormulaResult,
]);
useEffect(() => {
const basePrice = initialPrice + (numberOfDevices - 1) * discountPercentage;
setFormulaResult(
`Price for ${numberOfDevices} device(s) over ${numberOfDays} day(s): MVR ${basePrice.toFixed(2)}`,
);
}, [
initialPrice,
discountPercentage,
numberOfDevices,
numberOfDays,
setFormulaResult,
]);
return (
<div className="border p-2 rounded-xl">
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">
Price Calculator
</h3>
</div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
{/* Initial Price Input */}
<NumberInput
label="Initial Price"
value={initialPrice}
onChange={(value) => setInitialPrice(value)}
/>
{/* Number of Devices Input */}
<NumberInput
label="Number of Devices"
value={numberOfDevices}
onChange={(value) => setNumberOfDevices(value)}
/>
{/* Number of Days Input */}
<NumberInput
label="Number of Days"
value={numberOfDays}
onChange={(value) => setNumberOfDays(value)}
/>
return (
<div className="border p-2 rounded-xl">
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">Price Calculator</h3>
</div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
{/* Initial Price Input */}
<NumberInput
label="Initial Price"
value={initialPrice}
onChange={(value) => setInitialPrice(value)}
/>
{/* Number of Devices Input */}
<NumberInput
label="Number of Devices"
value={numberOfDevices}
onChange={(value) => setNumberOfDevices(value)}
/>
{/* Number of Days Input */}
<NumberInput
label="Number of Days"
value={numberOfDays}
onChange={(value) => setNumberOfDays(value)}
/>
{/* Discount Percentage Input */}
<NumberInput
label="Discount Percentage"
value={discountPercentage}
onChange={(value) => setDiscountPercentage(value)}
/>
</div>
{/* Discount Percentage Input */}
<NumberInput
label="Discount Percentage"
value={discountPercentage}
onChange={(value) => setDiscountPercentage(value)}
/>
</div>
<div className="mt-4">
<div className="title-bg relative rounded-lg border border-input shadow-sm shadow-black/5 transition-shadow focus-within:border-ring focus-within:outline-none focus-within:ring-[3px] focus-within:ring-ring/20 has-disabled:cursor-not-allowed has-disabled:opacity-50 [&:has(input:is(:disabled))_*]:pointer-events-none">
<label
htmlFor=""
className="block px-3 pt-2 text-md font-medium text-foreground"
>
Total
</label>
<input
className="flex font-mono font-semibold h-10 w-full bg-transparent px-3 pb-2 text-sm text-foreground placeholder:text-muted-foreground/70 focus-visible:outline-none"
value={formulaResult}
readOnly
placeholder={"Result"}
/>
</div>
</div>
</div>
);
<div className="mt-4">
<div className="title-bg relative rounded-lg border border-input shadow-sm shadow-black/5 transition-shadow focus-within:border-ring focus-within:outline-none focus-within:ring-[3px] focus-within:ring-ring/20 has-disabled:cursor-not-allowed has-disabled:opacity-50 [&:has(input:is(:disabled))_*]:pointer-events-none">
<label
htmlFor=""
className="block px-3 pt-2 text-md font-medium text-foreground"
>
Total
</label>
<input
className="flex font-mono font-semibold h-10 w-full bg-transparent px-3 pb-2 text-sm text-foreground placeholder:text-muted-foreground/70 focus-visible:outline-none"
value={formulaResult}
readOnly
placeholder={"Result"}
/>
</div>
</div>
</div>
);
}

View File

@@ -1,8 +1,7 @@
"use client";
import { Moon, Sun } from "lucide-react";
import { MonitorIcon, Moon, MoonIcon, Sun, SunIcon } from "lucide-react";
import { useTheme } from "next-themes";
import * as React from "react";
import { Button } from "@/components/ui/button";
import {
@@ -25,14 +24,26 @@ export function ModeToggle() {
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setTheme("light")}>
<DropdownMenuItem
className="flex justify-between items-center"
onClick={() => setTheme("light")}
>
Light
<SunIcon className="ml-2 h-4 w-4" />
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("dark")}>
<DropdownMenuItem
className="flex justify-between items-center"
onClick={() => setTheme("dark")}
>
Dark
<MoonIcon className="ml-2 h-4 w-4" />
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("system")}>
<DropdownMenuItem
className="flex justify-between items-center"
onClick={() => setTheme("system")}
>
System
<MonitorIcon className="ml-2 h-4 w-4" />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>

156
components/topup-to-pay.tsx Normal file
View File

@@ -0,0 +1,156 @@
"use client";
import { BadgeDollarSign, Loader2 } from "lucide-react";
import { useActionState, useEffect } from "react";
import { toast } from "sonner";
import {
type VerifyTopupPaymentState,
verifyTopupPayment,
} from "@/actions/payment";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableFooter,
TableRow,
} from "@/components/ui/table";
import type { Topup } from "@/lib/backend-types";
import { shouldShowTopupPaymentInfo } from "@/lib/utils";
import { AccountInfomation } from "./account-information";
import { Button } from "./ui/button";
const initialState: VerifyTopupPaymentState = {
message: "",
success: false,
fieldErrors: {},
};
export default function TopupToPay({
topup,
disabled,
}: {
topup?: Topup;
disabled?: boolean;
}) {
const [state, formAction, isPending] = useActionState(
verifyTopupPayment,
initialState,
);
// Handle toast notifications based on state changes
useEffect(() => {
if (state.success && state.message) {
toast.success("Topup successful!", {
closeButton: true,
description: state.transaction
? `Your topup payment has been verified successfully using ${state.transaction.sourceBank} bank transfer on ${state.transaction.trxDate}.`
: state.message,
});
} else if (
!state.success &&
state.message &&
state.message !== initialState.message
) {
toast.error("Topup Payment Verification Failed", {
closeButton: true,
description: state.message,
});
}
}, [state]);
return (
<div className="w-full">
<div className="m-2 flex items-end justify-end p-2 text-sm text-foreground border rounded">
<Table>
<TableCaption>
{shouldShowTopupPaymentInfo(topup) && (
<div className="max-w-sm mx-auto">
<p>Please send the following amount to the payment address</p>
<AccountInfomation
accName="Baraveli Dev"
accountNo="90101400028321000"
/>
{topup?.paid ? (
<Button
size={"lg"}
variant={"secondary"}
disabled
className="dark:text-green-200 text-green-900 bg-green-500/20 uppercase font-semibold"
>
Topup Payment Verified
</Button>
) : (
<div className="flex flex-col gap-2">
<form action={formAction}>
<input
type="hidden"
name="topupId"
value={topup?.id ?? ""}
/>
<Button
disabled={disabled || isPending}
type="submit"
size={"lg"}
className="mb-4 w-full"
>
{isPending ? "Processing payment..." : "I have paid"}
{isPending ? (
<Loader2 className="animate-spin" />
) : (
<BadgeDollarSign />
)}
</Button>
</form>
</div>
)}
</div>
)}
</TableCaption>
<TableBody className="">
<TableRow>
<TableCell>Topup created</TableCell>
<TableCell className="text-right text-muted-foreground">
{new Date(topup?.created_at ?? "").toLocaleDateString("en-US", {
month: "short",
day: "2-digit",
year: "numeric",
minute: "2-digit",
hour: "2-digit",
second: "2-digit",
})}
</TableCell>
</TableRow>
<TableRow>
<TableCell>Payment received</TableCell>
<TableCell className="text-right text-sarLinkOrange">
{topup?.paid_at
? new Date(topup.paid_at).toLocaleDateString("en-US", {
month: "short",
day: "2-digit",
year: "numeric",
minute: "2-digit",
hour: "2-digit",
second: "2-digit",
})
: "-"}
</TableCell>
</TableRow>
<TableRow>
<TableCell>MIB Reference</TableCell>
<TableCell className="text-right">
{topup?.mib_reference ? topup.mib_reference : "-"}
</TableCell>
</TableRow>
</TableBody>
<TableFooter>
<TableRow className="">
<TableCell colSpan={1}>Total Due</TableCell>
<TableCell className="text-right text-3xl font-bold">
{topup?.amount?.toFixed(2)}
</TableCell>
</TableRow>
</TableFooter>
</Table>
</div>
</div>
);
}

219
components/topups-table.tsx Normal file
View File

@@ -0,0 +1,219 @@
import { Calendar } from "lucide-react";
import Link from "next/link";
import { redirect } from "next/navigation";
import { getTopups } from "@/actions/payment";
import {
Table,
TableBody,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import type { Topup } from "@/lib/backend-types";
import { cn } from "@/lib/utils";
import { tryCatch } from "@/utils/tryCatch";
import Pagination from "./pagination";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
export async function TopupsTable({
searchParams,
}: {
searchParams: Promise<{
[key: string]: unknown;
}>;
}) {
const resolvedParams = await searchParams;
const page = Number.parseInt(resolvedParams.page as string) || 1;
const limit = 10;
const offset = (page - 1) * limit;
// Build params object
const apiParams: Record<string, string | number | undefined> = {};
for (const [key, value] of Object.entries(resolvedParams)) {
if (value !== undefined && value !== "") {
apiParams[key] = typeof value === "number" ? value : String(value);
}
}
apiParams.limit = limit;
apiParams.offset = offset;
const [error, topups] = await tryCatch(getTopups(apiParams));
if (error) {
if (error.message.includes("Unauthorized")) {
redirect("/auth/signin");
} else {
return <pre>{JSON.stringify(error, null, 2)}</pre>;
}
}
const { data, meta } = topups;
return (
<div>
{data?.length === 0 ? (
<div className="h-[calc(100svh-400px)] flex text-muted-foreground flex-col items-center justify-center my-4">
<h3>No topups.</h3>
</div>
) : (
<>
<div className="hidden sm:block">
<Table className="overflow-scroll">
<TableHeader>
<TableRow>
<TableHead>Details</TableHead>
<TableHead>Status</TableHead>
<TableHead>Amount</TableHead>
</TableRow>
</TableHeader>
<TableBody className="overflow-scroll">
{topups?.data?.map((topup) => (
<TableRow key={topup.id}>
<TableCell>
<div
className={cn(
"flex flex-col items-start border rounded p-2 motion-preset-fade-md",
topup?.paid
? "bg-green-500/10 border-dashed border-green-500"
: topup?.is_expired
? "bg-gray-500/10 border-dashed border-gray-500 dark:border-gray-500/50"
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
)}
>
<div className="flex items-center gap-2">
<Calendar size={16} opacity={0.5} />
<span className="text-muted-foreground">
{new Date(topup.created_at).toLocaleDateString(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
minute: "2-digit",
hour: "2-digit",
},
)}
</span>
</div>
<div className="flex items-center gap-2 mt-2">
<Link
className="font-medium hover:underline"
href={`/top-ups/${topup.id}`}
>
<Button size={"sm"} variant="outline">
View Details
</Button>
</Link>
</div>
</div>
</TableCell>
<TableCell>
<span className="font-semibold pr-2">
{topup.paid ? (
<Badge
className="bg-green-100 dark:bg-green-700"
variant="outline"
>
{topup.status}
</Badge>
) : topup.is_expired ? (
<Badge>Expired</Badge>
) : (
<Badge variant="outline">{topup.status}</Badge>
)}
</span>
</TableCell>
<TableCell>
<span className="font-semibold pr-2">
{topup.amount.toFixed(2)}
</span>
MVR
</TableCell>
</TableRow>
))}
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={4} className="text-muted-foreground">
{meta?.total === 1 ? (
<p className="text-center">Total {meta?.total} topup.</p>
) : (
<p className="text-center">Total {meta?.total} topups.</p>
)}
</TableCell>
</TableRow>
</TableFooter>
</Table>
</div>
<div className="sm:hidden block">
{data.map((topup) => (
<MobileTopupDetails key={topup.id} topup={topup} />
))}
</div>
<Pagination
totalPages={meta?.last_page}
currentPage={meta?.current_page}
/>
</>
)}
</div>
);
}
function MobileTopupDetails({ topup }: { topup: Topup }) {
return (
<div
className={cn(
"flex flex-col items-start border rounded p-2 my-2 motion-preset-fade-md",
topup?.paid
? "bg-green-500/10 border-dashed border-green-500"
: topup?.is_expired
? "bg-gray-500/10 border-dashed border-gray-500 dark:border-gray-500/50"
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
)}
>
<div className="flex items-center gap-2">
<Calendar size={16} opacity={0.5} />
<span className="text-muted-foreground text-sm">
{new Date(topup.created_at).toLocaleDateString("en-US", {
month: "short",
day: "2-digit",
year: "numeric",
})}
</span>
</div>
<div className="flex items-center gap-2 mt-2">
<Link
className="font-medium hover:underline"
href={`/top-ups/${topup.id}`}
>
<Button size={"sm"} variant="outline">
View Details
</Button>
</Link>
</div>
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border flex justify-between items-center">
<div className="block sm:hidden">
<h3 className="text-sm font-medium">Amount</h3>
<span className="text-sm text-muted-foreground">
{topup.amount.toFixed(2)} MVR
</span>
</div>
<span className="font-semibold pr-2">
{topup.paid ? (
<Badge className="bg-green-100 dark:bg-green-700" variant="outline">
{topup.status}
</Badge>
) : topup.is_expired ? (
<Badge>Expired</Badge>
) : (
<Badge variant="secondary">{topup.status}</Badge>
)}
</span>
</div>
</div>
);
}

View File

@@ -1,66 +1,66 @@
"use client"
"use client";
import * as React from "react"
import { Accordion as AccordionPrimitive } from "radix-ui"
import { ChevronDownIcon } from "lucide-react"
import * as React from "react";
import { Accordion as AccordionPrimitive } from "radix-ui";
import { ChevronDownIcon } from "lucide-react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Accordion({
...props
...props
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
return <AccordionPrimitive.Root data-slot="accordion" {...props} />;
}
function AccordionItem({
className,
...props
className,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
return (
<AccordionPrimitive.Item
data-slot="accordion-item"
className={cn("border-b last:border-b-0", className)}
{...props}
/>
)
return (
<AccordionPrimitive.Item
data-slot="accordion-item"
className={cn("border-b last:border-b-0", className)}
{...props}
/>
);
}
function AccordionTrigger({
className,
children,
...props
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
return (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
data-slot="accordion-trigger"
className={cn(
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
className
)}
{...props}
>
{children}
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
)
return (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
data-slot="accordion-trigger"
className={cn(
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
className,
)}
{...props}
>
{children}
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
);
}
function AccordionContent({
className,
children,
...props
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
return (
<AccordionPrimitive.Content
data-slot="accordion-content"
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
{...props}
>
<div className={cn("pt-0 pb-4", className)}>{children}</div>
</AccordionPrimitive.Content>
)
return (
<AccordionPrimitive.Content
data-slot="accordion-content"
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
{...props}
>
<div className={cn("pt-0 pb-4", className)}>{children}</div>
</AccordionPrimitive.Content>
);
}
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };

View File

@@ -1,141 +1,156 @@
"use client"
"use client";
import { AlertDialog as AlertDialogPrimitive } from "radix-ui"
import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
import * as React from "react";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button"
import { cn } from "@/lib/utils"
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />;
}
const AlertDialog = AlertDialogPrimitive.Root
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
);
}
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
);
}
const AlertDialogPortal = AlertDialogPrimitive.Portal
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
))
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
function AlertDialogContent({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className,
)}
{...props}
/>
</AlertDialogPortal>
);
}
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 [data-[state=closed]:slide-out-to-top-[48%]] data-[state=open]:slide-in-from-left-1/2 [data-[state=open]:slide-in-from-top-[48%]] sm:rounded-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
))
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
);
}
const AlertDialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className
)}
{...props}
/>
)
AlertDialogHeader.displayName = "AlertDialogHeader"
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
/>
);
}
const AlertDialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
AlertDialogFooter.displayName = "AlertDialogFooter"
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...props}
/>
);
}
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold", className)}
{...props}
/>
))
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName
function AlertDialogAction({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return (
<AlertDialogPrimitive.Action
className={cn(buttonVariants(), className)}
{...props}
/>
);
}
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action
ref={ref}
className={cn(buttonVariants(), className)}
{...props}
/>
))
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(
buttonVariants({ variant: "outline" }),
"mt-2 sm:mt-0",
className
)}
{...props}
/>
))
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
function AlertDialogCancel({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel
className={cn(buttonVariants({ variant: "outline" }), className)}
{...props}
/>
);
}
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
}
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};

View File

@@ -1,59 +1,59 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
)
"relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
},
);
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
))
Alert.displayName = "Alert"
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
));
Alert.displayName = "Alert";
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
));
AlertTitle.displayName = "AlertTitle";
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
));
AlertDescription.displayName = "AlertDescription";
export { Alert, AlertTitle, AlertDescription }
export { Alert, AlertTitle, AlertDescription };

View File

@@ -1,209 +1,226 @@
import {
Calculator,
ChevronRight,
Coins,
CreditCard,
Handshake,
MonitorSpeaker,
Smartphone,
UsersRound,
Wallet2Icon,
BadgePlus,
Calculator,
ChevronRight,
Coins,
CreditCard,
Handshake,
MonitorSpeaker,
Smartphone,
UsersRound,
Wallet2Icon,
} from "lucide-react";
import Link from "next/link";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import {
Sidebar,
SidebarContent,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarRail,
Sidebar,
SidebarContent,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarRail,
} from "@/components/ui/sidebar";
type Permission = {
id: number;
name: string;
id: number;
name: string;
};
type Categories = {
id: string;
children: (
| {
title: string;
link: string;
perm_identifier: string;
icon: React.JSX.Element;
}
| {
title: string;
link: string;
icon: React.JSX.Element;
perm_identifier?: undefined;
}
)[];
id: string;
children: (
| {
title: string;
link: string;
perm_identifier: string;
icon: React.JSX.Element;
}
| {
title: string;
link: string;
icon: React.JSX.Element;
perm_identifier?: undefined;
}
)[];
}[];
export async function AppSidebar({
...props
...props
}: React.ComponentProps<typeof Sidebar>) {
const categories = [
{
id: "MENU",
url: "#",
children: [
{
title: "Devices",
link: "/devices?page=1",
perm_identifier: "device",
icon: <Smartphone size={16} />,
},
{
title: "Payments",
link: "/payments?page=1",
icon: <CreditCard size={16} />,
perm_identifier: "payment",
},
{
title: "Parental Control",
link: "/parental-control",
icon: <CreditCard size={16} />,
perm_identifier: "device",
},
{
title: "Agreements",
link: "/agreements",
icon: <Handshake size={16} />,
perm_identifier: "device",
},
{
title: "Wallet",
link: "/wallet",
icon: <Wallet2Icon size={16} />,
perm_identifier: "wallet",
},
],
},
{
id: "ADMIN CONTROL",
url: "#",
children: [
{
title: "Users",
link: "/users",
icon: <UsersRound size={16} />,
perm_identifier: "device",
},
{
title: "User Devices",
link: "/user-devices",
icon: <MonitorSpeaker size={16} />,
perm_identifier: "device",
},
{
title: "User Payments",
link: "/user-payments",
icon: <Coins size={16} />,
perm_identifier: "payment",
},
{
title: "Price Calculator",
link: "/price-calculator",
icon: <Calculator size={16} />,
perm_identifier: "device",
},
],
},
];
const categories = [
{
id: "MENU",
url: "#",
children: [
{
title: "Devices",
link: "/devices?page=1",
perm_identifier: "device",
icon: <Smartphone size={16} />,
},
{
title: "Parental Control",
link: "/parental-control?page=1",
icon: <CreditCard size={16} />,
perm_identifier: "device",
},
{
title: "Subscriptions",
link: "/payments?page=1",
icon: <CreditCard size={16} />,
perm_identifier: "payment",
},
{
title: "Top Ups",
link: "/top-ups?page=1",
icon: <BadgePlus size={16} />,
perm_identifier: "topup",
},
{
title: "Transaction History",
link: "/wallet",
icon: <Wallet2Icon size={16} />,
perm_identifier: "wallet transaction",
},
{
title: "Agreements",
link: "/agreements",
icon: <Handshake size={16} />,
perm_identifier: "device",
},
],
},
{
id: "ADMIN CONTROL",
url: "#",
children: [
{
title: "Users",
link: "/users",
icon: <UsersRound size={16} />,
perm_identifier: "device",
},
{
title: "User Devices",
link: "/user-devices",
icon: <MonitorSpeaker size={16} />,
perm_identifier: "device",
},
{
title: "User Payments",
link: "/user-payments",
icon: <Coins size={16} />,
perm_identifier: "payment",
},
{
title: "User Topups",
link: "/user-topups",
icon: <Coins size={16} />,
perm_identifier: "topup",
},
{
title: "Price Calculator",
link: "/price-calculator",
icon: <Calculator size={16} />,
perm_identifier: "device",
},
],
},
];
const session = await getServerSession(authOptions);
const session = await getServerSession(authOptions);
let CATEGORIES: Categories;
if (session?.user?.is_admin) {
CATEGORIES = categories;
} else {
// Filter out ADMIN CONTROL category for non-admin users
const nonAdminCategories = categories.filter(
(category) => category.id !== "ADMIN CONTROL"
);
let CATEGORIES: Categories;
if (session?.user?.is_admin) {
CATEGORIES = categories;
} else {
// Filter out ADMIN CONTROL category for non-admin users
const nonAdminCategories = categories.filter(
(category) => category.id !== "ADMIN CONTROL",
);
const filteredCategories = nonAdminCategories.map((category) => {
const filteredChildren = category.children.filter((child) => {
const permIdentifier = child.perm_identifier;
return session?.user?.user_permissions?.some((permission: Permission) => {
const permissionParts = permission.name.split(" ");
const modelNameFromPermission = permissionParts.slice(2).join(" ");
return modelNameFromPermission === permIdentifier;
});
});
const filteredCategories = nonAdminCategories.map((category) => {
const filteredChildren = category.children.filter((child) => {
const permIdentifier = child.perm_identifier;
return session?.user?.user_permissions?.some(
(permission: Permission) => {
const permissionParts = permission.name.split(" ");
const modelNameFromPermission = permissionParts.slice(2).join(" ");
return modelNameFromPermission === permIdentifier;
},
);
});
return { ...category, children: filteredChildren };
});
return { ...category, children: filteredChildren };
});
CATEGORIES = filteredCategories.filter(
(category) => category.children.length > 0,
);
}
CATEGORIES = filteredCategories.filter(
(category) => category.children.length > 0,
);
}
return (
<Sidebar {...props} className="z-50">
<SidebarHeader>
<h4 className="p-2 rounded title-bg border text-center uppercase ">
Sar Link Portal
</h4>
</SidebarHeader>
<SidebarContent className="gap-0">
{CATEGORIES.map((item) => {
return (
<Collapsible
key={item.id}
title={item.id}
defaultOpen
className="group/collapsible"
>
<SidebarGroup>
<SidebarGroupLabel
asChild
className="group/label text-sm text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
>
<CollapsibleTrigger>
{item.id}{" "}
<ChevronRight className="ml-auto transition-transform group-data-[state=open]/collapsible:rotate-90" />
</CollapsibleTrigger>
</SidebarGroupLabel>
<CollapsibleContent>
<SidebarGroupContent>
<SidebarMenu>
{item.children.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton className="py-6" asChild>
<Link className="text-md" href={item.link}>
{item.icon}
<span className="opacity-70 ml-2">
{item.title}
</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</CollapsibleContent>
</SidebarGroup>
</Collapsible>
);
})}
</SidebarContent>
<SidebarRail />
</Sidebar>
);
return (
<Sidebar {...props} className="z-50">
<SidebarHeader>
<h4 className="p-2 rounded title-bg border text-center uppercase ">
Sar Link Portal
</h4>
</SidebarHeader>
<SidebarContent className="gap-0">
{CATEGORIES.map((item) => {
return (
<Collapsible
key={item.id}
title={item.id}
defaultOpen
className="group/collapsible"
>
<SidebarGroup>
<SidebarGroupLabel
asChild
className="group/label text-sm text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
>
<CollapsibleTrigger>
{item.id}{" "}
<ChevronRight className="ml-auto transition-transform group-data-[state=open]/collapsible:rotate-90" />
</CollapsibleTrigger>
</SidebarGroupLabel>
<CollapsibleContent>
<SidebarGroupContent>
<SidebarMenu>
{item.children.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton className="py-6" asChild>
<Link className="text-md" href={item.link}>
{item.icon}
<span
className={`opacity-70 motion-preset-fade motion-duration-300 ml-2`}
>
{item.title}
</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</CollapsibleContent>
</SidebarGroup>
</Collapsible>
);
})}
</SidebarContent>
<SidebarRail />
</Sidebar>
);
}

View File

@@ -1,7 +1,7 @@
"use client"
"use client";
import { AspectRatio as AspectRatioPrimitive } from "radix-ui"
import { AspectRatio as AspectRatioPrimitive } from "radix-ui";
const AspectRatio = AspectRatioPrimitive.Root
const AspectRatio = AspectRatioPrimitive.Root;
export { AspectRatio }
export { AspectRatio };

View File

@@ -1,50 +1,50 @@
"use client"
"use client";
import * as React from "react"
import { Avatar as AvatarPrimitive } from "radix-ui"
import * as React from "react";
import { Avatar as AvatarPrimitive } from "radix-ui";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn(
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
))
Avatar.displayName = AvatarPrimitive.Root.displayName
<AvatarPrimitive.Root
ref={ref}
className={cn(
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
className,
)}
{...props}
/>
));
Avatar.displayName = AvatarPrimitive.Root.displayName;
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full", className)}
{...props}
/>
))
AvatarImage.displayName = AvatarPrimitive.Image.displayName
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full", className)}
{...props}
/>
));
AvatarImage.displayName = AvatarPrimitive.Image.displayName;
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn(
"flex h-full w-full items-center justify-center rounded-full bg-muted",
className
)}
{...props}
/>
))
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
<AvatarPrimitive.Fallback
ref={ref}
className={cn(
"flex h-full w-full items-center justify-center rounded-full bg-muted",
className,
)}
{...props}
/>
));
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName;
export { Avatar, AvatarImage, AvatarFallback }
export { Avatar, AvatarImage, AvatarFallback };

View File

@@ -1,36 +1,36 @@
import { type VariantProps, cva } from "class-variance-authority"
import * as React from "react"
import { type VariantProps, cva } from "class-variance-authority";
import * as React from "react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
},
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> { }
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
);
}
export { Badge, badgeVariants }
export { Badge, badgeVariants };

View File

@@ -1,115 +1,115 @@
import * as React from "react"
import { Slot as SlotPrimitive } from "radix-ui"
import { ChevronRight, MoreHorizontal } from "lucide-react"
import * as React from "react";
import { Slot as SlotPrimitive } from "radix-ui";
import { ChevronRight, MoreHorizontal } from "lucide-react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const Breadcrumb = React.forwardRef<
HTMLElement,
React.ComponentPropsWithoutRef<"nav"> & {
separator?: React.ReactNode
}
>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />)
Breadcrumb.displayName = "Breadcrumb"
HTMLElement,
React.ComponentPropsWithoutRef<"nav"> & {
separator?: React.ReactNode;
}
>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />);
Breadcrumb.displayName = "Breadcrumb";
const BreadcrumbList = React.forwardRef<
HTMLOListElement,
React.ComponentPropsWithoutRef<"ol">
HTMLOListElement,
React.ComponentPropsWithoutRef<"ol">
>(({ className, ...props }, ref) => (
<ol
ref={ref}
className={cn(
"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
className
)}
{...props}
/>
))
BreadcrumbList.displayName = "BreadcrumbList"
<ol
ref={ref}
className={cn(
"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
className,
)}
{...props}
/>
));
BreadcrumbList.displayName = "BreadcrumbList";
const BreadcrumbItem = React.forwardRef<
HTMLLIElement,
React.ComponentPropsWithoutRef<"li">
HTMLLIElement,
React.ComponentPropsWithoutRef<"li">
>(({ className, ...props }, ref) => (
<li
ref={ref}
className={cn("inline-flex items-center gap-1.5", className)}
{...props}
/>
))
BreadcrumbItem.displayName = "BreadcrumbItem"
<li
ref={ref}
className={cn("inline-flex items-center gap-1.5", className)}
{...props}
/>
));
BreadcrumbItem.displayName = "BreadcrumbItem";
const BreadcrumbLink = React.forwardRef<
HTMLAnchorElement,
React.ComponentPropsWithoutRef<"a"> & {
asChild?: boolean
}
HTMLAnchorElement,
React.ComponentPropsWithoutRef<"a"> & {
asChild?: boolean;
}
>(({ asChild, className, ...props }, ref) => {
const Comp = asChild ? SlotPrimitive.Slot : "a"
const Comp = asChild ? SlotPrimitive.Slot : "a";
return (
<Comp
ref={ref}
className={cn("transition-colors hover:text-foreground", className)}
{...props}
/>
)
})
BreadcrumbLink.displayName = "BreadcrumbLink"
return (
<Comp
ref={ref}
className={cn("transition-colors hover:text-foreground", className)}
{...props}
/>
);
});
BreadcrumbLink.displayName = "BreadcrumbLink";
const BreadcrumbPage = React.forwardRef<
HTMLSpanElement,
React.ComponentPropsWithoutRef<"span">
HTMLSpanElement,
React.ComponentPropsWithoutRef<"span">
>(({ className, ...props }, ref) => (
<span
ref={ref}
role="link"
aria-disabled="true"
aria-current="page"
className={cn("font-normal text-foreground", className)}
{...props}
/>
))
BreadcrumbPage.displayName = "BreadcrumbPage"
<span
ref={ref}
role="link"
aria-disabled="true"
aria-current="page"
className={cn("font-normal text-foreground", className)}
{...props}
/>
));
BreadcrumbPage.displayName = "BreadcrumbPage";
const BreadcrumbSeparator = ({
children,
className,
...props
children,
className,
...props
}: React.ComponentProps<"li">) => (
<li
role="presentation"
aria-hidden="true"
className={cn("[&>svg]:w-3.5 [&>svg]:h-3.5", className)}
{...props}
>
{children ?? <ChevronRight />}
</li>
)
BreadcrumbSeparator.displayName = "BreadcrumbSeparator"
<li
role="presentation"
aria-hidden="true"
className={cn("[&>svg]:w-3.5 [&>svg]:h-3.5", className)}
{...props}
>
{children ?? <ChevronRight />}
</li>
);
BreadcrumbSeparator.displayName = "BreadcrumbSeparator";
const BreadcrumbEllipsis = ({
className,
...props
className,
...props
}: React.ComponentProps<"span">) => (
<span
role="presentation"
aria-hidden="true"
className={cn("flex h-9 w-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More</span>
</span>
)
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis"
<span
role="presentation"
aria-hidden="true"
className={cn("flex h-9 w-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More</span>
</span>
);
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis";
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
}
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
};

View File

@@ -1,59 +1,59 @@
import { Slot as SlotPrimitive } from "radix-ui"
import { type VariantProps, cva } from "class-variance-authority"
import * as React from "react"
import { Slot as SlotPrimitive } from "radix-ui";
import { type VariantProps, cva } from "class-variance-authority";
import * as React from "react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
destructive:
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
destructive:
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
function Button({
className,
variant,
size,
asChild = false,
...props
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? SlotPrimitive.Slot : "button"
VariantProps<typeof buttonVariants> & {
asChild?: boolean;
}) {
const Comp = asChild ? SlotPrimitive.Slot : "button";
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
);
}
export { Button, buttonVariants }
export { Button, buttonVariants };

View File

@@ -1,210 +1,210 @@
"use client"
"use client";
import * as React from "react"
import * as React from "react";
import {
ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
} from "lucide-react"
import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker"
ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
} from "lucide-react";
import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker";
import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"
import { cn } from "@/lib/utils";
import { Button, buttonVariants } from "@/components/ui/button";
function Calendar({
className,
classNames,
showOutsideDays = true,
captionLayout = "label",
buttonVariant = "ghost",
formatters,
components,
...props
className,
classNames,
showOutsideDays = true,
captionLayout = "label",
buttonVariant = "ghost",
formatters,
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
buttonVariant?: React.ComponentProps<typeof Button>["variant"];
}) {
const defaultClassNames = getDefaultClassNames()
const defaultClassNames = getDefaultClassNames();
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
"bg-background group/calendar p-3 [--cell-size:2rem] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent",
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className
)}
captionLayout={captionLayout}
formatters={{
formatMonthDropdown: (date) =>
date.toLocaleString("default", { month: "short" }),
...formatters,
}}
classNames={{
root: cn("w-fit", defaultClassNames.root),
months: cn(
"relative flex flex-col gap-4 md:flex-row",
defaultClassNames.months
),
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
nav: cn(
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
defaultClassNames.nav
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
"h-(--cell-size) w-(--cell-size) select-none p-0 aria-disabled:opacity-50",
defaultClassNames.button_previous
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
"h-(--cell-size) w-(--cell-size) select-none p-0 aria-disabled:opacity-50",
defaultClassNames.button_next
),
month_caption: cn(
"flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",
defaultClassNames.month_caption
),
dropdowns: cn(
"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
defaultClassNames.dropdowns
),
dropdown_root: cn(
"has-focus:border-ring border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] relative rounded-md border",
defaultClassNames.dropdown_root
),
dropdown: cn("absolute inset-0 opacity-0", defaultClassNames.dropdown),
caption_label: cn(
"select-none font-medium",
captionLayout === "label"
? "text-sm"
: "[&>svg]:text-muted-foreground flex h-8 items-center gap-1 rounded-md pl-2 pr-1 text-sm [&>svg]:size-3.5",
defaultClassNames.caption_label
),
table: "w-full border-collapse",
weekdays: cn("flex", defaultClassNames.weekdays),
weekday: cn(
"text-muted-foreground flex-1 select-none rounded-md text-[0.8rem] font-normal",
defaultClassNames.weekday
),
week: cn("mt-2 flex w-full", defaultClassNames.week),
week_number_header: cn(
"w-(--cell-size) select-none",
defaultClassNames.week_number_header
),
week_number: cn(
"text-muted-foreground select-none text-[0.8rem]",
defaultClassNames.week_number
),
day: cn(
"group/day relative aspect-square h-full w-full select-none p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md",
defaultClassNames.day
),
range_start: cn(
"bg-accent rounded-l-md",
defaultClassNames.range_start
),
range_middle: cn("rounded-none", defaultClassNames.range_middle),
range_end: cn("bg-accent rounded-r-md", defaultClassNames.range_end),
today: cn(
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
defaultClassNames.today
),
outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside
),
disabled: cn(
"text-muted-foreground opacity-50",
defaultClassNames.disabled
),
hidden: cn("invisible", defaultClassNames.hidden),
...classNames,
}}
components={{
Root: ({ className, rootRef, ...props }) => {
return (
<div
data-slot="calendar"
ref={rootRef}
className={cn(className)}
{...props}
/>
)
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === "left") {
return (
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
)
}
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
"bg-background group/calendar p-3 [--cell-size:2rem] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent",
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className,
)}
captionLayout={captionLayout}
formatters={{
formatMonthDropdown: (date) =>
date.toLocaleString("default", { month: "short" }),
...formatters,
}}
classNames={{
root: cn("w-fit", defaultClassNames.root),
months: cn(
"relative flex flex-col gap-4 md:flex-row",
defaultClassNames.months,
),
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
nav: cn(
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
defaultClassNames.nav,
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
"h-(--cell-size) w-(--cell-size) select-none p-0 aria-disabled:opacity-50",
defaultClassNames.button_previous,
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
"h-(--cell-size) w-(--cell-size) select-none p-0 aria-disabled:opacity-50",
defaultClassNames.button_next,
),
month_caption: cn(
"flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",
defaultClassNames.month_caption,
),
dropdowns: cn(
"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
defaultClassNames.dropdowns,
),
dropdown_root: cn(
"has-focus:border-ring border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] relative rounded-md border",
defaultClassNames.dropdown_root,
),
dropdown: cn("absolute inset-0 opacity-0", defaultClassNames.dropdown),
caption_label: cn(
"select-none font-medium",
captionLayout === "label"
? "text-sm"
: "[&>svg]:text-muted-foreground flex h-8 items-center gap-1 rounded-md pl-2 pr-1 text-sm [&>svg]:size-3.5",
defaultClassNames.caption_label,
),
table: "w-full border-collapse",
weekdays: cn("flex", defaultClassNames.weekdays),
weekday: cn(
"text-muted-foreground flex-1 select-none rounded-md text-[0.8rem] font-normal",
defaultClassNames.weekday,
),
week: cn("mt-2 flex w-full", defaultClassNames.week),
week_number_header: cn(
"w-(--cell-size) select-none",
defaultClassNames.week_number_header,
),
week_number: cn(
"text-muted-foreground select-none text-[0.8rem]",
defaultClassNames.week_number,
),
day: cn(
"group/day relative aspect-square h-full w-full select-none p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md",
defaultClassNames.day,
),
range_start: cn(
"bg-accent rounded-l-md",
defaultClassNames.range_start,
),
range_middle: cn("rounded-none", defaultClassNames.range_middle),
range_end: cn("bg-accent rounded-r-md", defaultClassNames.range_end),
today: cn(
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
defaultClassNames.today,
),
outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside,
),
disabled: cn(
"text-muted-foreground opacity-50",
defaultClassNames.disabled,
),
hidden: cn("invisible", defaultClassNames.hidden),
...classNames,
}}
components={{
Root: ({ className, rootRef, ...props }) => {
return (
<div
data-slot="calendar"
ref={rootRef}
className={cn(className)}
{...props}
/>
);
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === "left") {
return (
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
);
}
if (orientation === "right") {
return (
<ChevronRightIcon
className={cn("size-4", className)}
{...props}
/>
)
}
if (orientation === "right") {
return (
<ChevronRightIcon
className={cn("size-4", className)}
{...props}
/>
);
}
return (
<ChevronDownIcon className={cn("size-4", className)} {...props} />
)
},
DayButton: CalendarDayButton,
WeekNumber: ({ children, ...props }) => {
return (
<td {...props}>
<div className="flex size-(--cell-size) items-center justify-center text-center">
{children}
</div>
</td>
)
},
...components,
}}
{...props}
/>
)
return (
<ChevronDownIcon className={cn("size-4", className)} {...props} />
);
},
DayButton: CalendarDayButton,
WeekNumber: ({ children, ...props }) => {
return (
<td {...props}>
<div className="flex size-(--cell-size) items-center justify-center text-center">
{children}
</div>
</td>
);
},
...components,
}}
{...props}
/>
);
}
function CalendarDayButton({
className,
day,
modifiers,
...props
className,
day,
modifiers,
...props
}: React.ComponentProps<typeof DayButton>) {
const defaultClassNames = getDefaultClassNames()
const defaultClassNames = getDefaultClassNames();
const ref = React.useRef<HTMLButtonElement>(null)
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus()
}, [modifiers.focused])
const ref = React.useRef<HTMLButtonElement>(null);
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus();
}, [modifiers.focused]);
return (
<Button
ref={ref}
variant="ghost"
size="icon"
data-day={day.date.toLocaleDateString()}
data-selected-single={
modifiers.selected &&
!modifiers.range_start &&
!modifiers.range_end &&
!modifiers.range_middle
}
data-range-start={modifiers.range_start}
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
className={cn(
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 flex aspect-square h-auto w-full min-w-(--cell-size) flex-col gap-1 font-normal leading-none data-[range-end=true]:rounded-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] [&>span]:text-xs [&>span]:opacity-70",
defaultClassNames.day,
className
)}
{...props}
/>
)
return (
<Button
ref={ref}
variant="ghost"
size="icon"
data-day={day.date.toLocaleDateString()}
data-selected-single={
modifiers.selected &&
!modifiers.range_start &&
!modifiers.range_end &&
!modifiers.range_middle
}
data-range-start={modifiers.range_start}
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
className={cn(
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 flex aspect-square h-auto w-full min-w-(--cell-size) flex-col gap-1 font-normal leading-none data-[range-end=true]:rounded-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] [&>span]:text-xs [&>span]:opacity-70",
defaultClassNames.day,
className,
)}
{...props}
/>
);
}
export { Calendar, CalendarDayButton }
export { Calendar, CalendarDayButton };

View File

@@ -1,76 +1,83 @@
import * as React from "react"
import * as React from "react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className
)}
{...props}
/>
))
Card.displayName = "Card"
<div
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className,
)}
{...props}
/>
));
Card.displayName = "Card";
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
));
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
<div
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
));
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
));
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
));
CardFooter.displayName = "CardFooter";
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardDescription,
CardContent,
};

View File

@@ -1,262 +1,262 @@
"use client"
"use client";
import * as React from "react"
import * as React from "react";
import useEmblaCarousel, {
type UseEmblaCarouselType,
} from "embla-carousel-react"
import { ArrowLeft, ArrowRight } from "lucide-react"
type UseEmblaCarouselType,
} from "embla-carousel-react";
import { ArrowLeft, ArrowRight } from "lucide-react";
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
type CarouselApi = UseEmblaCarouselType[1]
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
type CarouselOptions = UseCarouselParameters[0]
type CarouselPlugin = UseCarouselParameters[1]
type CarouselApi = UseEmblaCarouselType[1];
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>;
type CarouselOptions = UseCarouselParameters[0];
type CarouselPlugin = UseCarouselParameters[1];
type CarouselProps = {
opts?: CarouselOptions
plugins?: CarouselPlugin
orientation?: "horizontal" | "vertical"
setApi?: (api: CarouselApi) => void
}
opts?: CarouselOptions;
plugins?: CarouselPlugin;
orientation?: "horizontal" | "vertical";
setApi?: (api: CarouselApi) => void;
};
type CarouselContextProps = {
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
api: ReturnType<typeof useEmblaCarousel>[1]
scrollPrev: () => void
scrollNext: () => void
canScrollPrev: boolean
canScrollNext: boolean
} & CarouselProps
carouselRef: ReturnType<typeof useEmblaCarousel>[0];
api: ReturnType<typeof useEmblaCarousel>[1];
scrollPrev: () => void;
scrollNext: () => void;
canScrollPrev: boolean;
canScrollNext: boolean;
} & CarouselProps;
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
const CarouselContext = React.createContext<CarouselContextProps | null>(null);
function useCarousel() {
const context = React.useContext(CarouselContext)
const context = React.useContext(CarouselContext);
if (!context) {
throw new Error("useCarousel must be used within a <Carousel />")
}
if (!context) {
throw new Error("useCarousel must be used within a <Carousel />");
}
return context
return context;
}
const Carousel = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & CarouselProps
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & CarouselProps
>(
(
{
orientation = "horizontal",
opts,
setApi,
plugins,
className,
children,
...props
},
ref
) => {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === "horizontal" ? "x" : "y",
},
plugins
)
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
const [canScrollNext, setCanScrollNext] = React.useState(false)
(
{
orientation = "horizontal",
opts,
setApi,
plugins,
className,
children,
...props
},
ref,
) => {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === "horizontal" ? "x" : "y",
},
plugins,
);
const [canScrollPrev, setCanScrollPrev] = React.useState(false);
const [canScrollNext, setCanScrollNext] = React.useState(false);
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) {
return
}
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) {
return;
}
setCanScrollPrev(api.canScrollPrev())
setCanScrollNext(api.canScrollNext())
}, [])
setCanScrollPrev(api.canScrollPrev());
setCanScrollNext(api.canScrollNext());
}, []);
const scrollPrev = React.useCallback(() => {
api?.scrollPrev()
}, [api])
const scrollPrev = React.useCallback(() => {
api?.scrollPrev();
}, [api]);
const scrollNext = React.useCallback(() => {
api?.scrollNext()
}, [api])
const scrollNext = React.useCallback(() => {
api?.scrollNext();
}, [api]);
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowLeft") {
event.preventDefault()
scrollPrev()
} else if (event.key === "ArrowRight") {
event.preventDefault()
scrollNext()
}
},
[scrollPrev, scrollNext]
)
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowLeft") {
event.preventDefault();
scrollPrev();
} else if (event.key === "ArrowRight") {
event.preventDefault();
scrollNext();
}
},
[scrollPrev, scrollNext],
);
React.useEffect(() => {
if (!api || !setApi) {
return
}
React.useEffect(() => {
if (!api || !setApi) {
return;
}
setApi(api)
}, [api, setApi])
setApi(api);
}, [api, setApi]);
React.useEffect(() => {
if (!api) {
return
}
React.useEffect(() => {
if (!api) {
return;
}
onSelect(api)
api.on("reInit", onSelect)
api.on("select", onSelect)
onSelect(api);
api.on("reInit", onSelect);
api.on("select", onSelect);
return () => {
api?.off("select", onSelect)
}
}, [api, onSelect])
return () => {
api?.off("select", onSelect);
};
}, [api, onSelect]);
return (
<CarouselContext.Provider
value={{
carouselRef,
api: api,
opts,
orientation:
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}}
>
<div
ref={ref}
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
)
}
)
Carousel.displayName = "Carousel"
return (
<CarouselContext.Provider
value={{
carouselRef,
api: api,
opts,
orientation:
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}}
>
<div
ref={ref}
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
);
},
);
Carousel.displayName = "Carousel";
const CarouselContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { carouselRef, orientation } = useCarousel()
const { carouselRef, orientation } = useCarousel();
return (
<div ref={carouselRef} className="overflow-hidden">
<div
ref={ref}
className={cn(
"flex",
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
className
)}
{...props}
/>
</div>
)
})
CarouselContent.displayName = "CarouselContent"
return (
<div ref={carouselRef} className="overflow-hidden">
<div
ref={ref}
className={cn(
"flex",
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
className,
)}
{...props}
/>
</div>
);
});
CarouselContent.displayName = "CarouselContent";
const CarouselItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { orientation } = useCarousel()
const { orientation } = useCarousel();
return (
<div
ref={ref}
role="group"
aria-roledescription="slide"
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-4" : "pt-4",
className
)}
{...props}
/>
)
})
CarouselItem.displayName = "CarouselItem"
return (
<div
ref={ref}
role="group"
aria-roledescription="slide"
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-4" : "pt-4",
className,
)}
{...props}
/>
);
});
CarouselItem.displayName = "CarouselItem";
const CarouselPrevious = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
const { orientation, scrollPrev, canScrollPrev } = useCarousel();
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-left-12 top-1/2 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft className="h-4 w-4" />
<span className="sr-only">Previous slide</span>
</Button>
)
})
CarouselPrevious.displayName = "CarouselPrevious"
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-left-12 top-1/2 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft className="h-4 w-4" />
<span className="sr-only">Previous slide</span>
</Button>
);
});
CarouselPrevious.displayName = "CarouselPrevious";
const CarouselNext = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollNext, canScrollNext } = useCarousel()
const { orientation, scrollNext, canScrollNext } = useCarousel();
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-right-12 top-1/2 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight className="h-4 w-4" />
<span className="sr-only">Next slide</span>
</Button>
)
})
CarouselNext.displayName = "CarouselNext"
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-right-12 top-1/2 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight className="h-4 w-4" />
<span className="sr-only">Next slide</span>
</Button>
);
});
CarouselNext.displayName = "CarouselNext";
export {
type CarouselApi,
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
}
type CarouselApi,
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
};

View File

@@ -1,30 +1,30 @@
"use client"
"use client";
import * as React from "react"
import { Checkbox as CheckboxPrimitive } from "radix-ui"
import { Check } from "lucide-react"
import * as React from "react";
import { Checkbox as CheckboxPrimitive } from "radix-ui";
import { Check } from "lucide-react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("flex items-center justify-center text-current")}
>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
))
Checkbox.displayName = CheckboxPrimitive.Root.displayName
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("flex items-center justify-center text-current")}
>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox }
export { Checkbox };

View File

@@ -1,11 +1,11 @@
"use client"
"use client";
import { Collapsible as CollapsiblePrimitive } from "radix-ui"
import { Collapsible as CollapsiblePrimitive } from "radix-ui";
const Collapsible = CollapsiblePrimitive.Root
const Collapsible = CollapsiblePrimitive.Root;
const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger
const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger;
const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent
const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent;
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
export { Collapsible, CollapsibleTrigger, CollapsibleContent };

View File

@@ -1,184 +1,184 @@
"use client"
"use client";
import * as React from "react"
import { Command as CommandPrimitive } from "cmdk"
import { SearchIcon } from "lucide-react"
import * as React from "react";
import { Command as CommandPrimitive } from "cmdk";
import { SearchIcon } from "lucide-react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
function Command({
className,
...props
className,
...props
}: React.ComponentProps<typeof CommandPrimitive>) {
return (
<CommandPrimitive
data-slot="command"
className={cn(
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
className
)}
{...props}
/>
)
return (
<CommandPrimitive
data-slot="command"
className={cn(
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
className,
)}
{...props}
/>
);
}
function CommandDialog({
title = "Command Palette",
description = "Search for a command to run...",
children,
className,
showCloseButton = true,
...props
title = "Command Palette",
description = "Search for a command to run...",
children,
className,
showCloseButton = true,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string
description?: string
className?: string
showCloseButton?: boolean
title?: string;
description?: string;
className?: string;
showCloseButton?: boolean;
}) {
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent
className={cn("overflow-hidden p-0", className)}
showCloseButton={showCloseButton}
>
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
)
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent
className={cn("overflow-hidden p-0", className)}
showCloseButton={showCloseButton}
>
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
);
}
function CommandInput({
className,
...props
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
<div
data-slot="command-input-wrapper"
className="flex h-9 items-center gap-2 border-b px-3"
>
<SearchIcon className="size-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
</div>
)
return (
<div
data-slot="command-input-wrapper"
className="flex h-9 items-center gap-2 border-b px-3"
>
<SearchIcon className="size-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
/>
</div>
);
}
function CommandList({
className,
...props
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.List>) {
return (
<CommandPrimitive.List
data-slot="command-list"
className={cn(
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
className
)}
{...props}
/>
)
return (
<CommandPrimitive.List
data-slot="command-list"
className={cn(
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
className,
)}
{...props}
/>
);
}
function CommandEmpty({
...props
...props
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
return (
<CommandPrimitive.Empty
data-slot="command-empty"
className="py-6 text-center text-sm"
{...props}
/>
)
return (
<CommandPrimitive.Empty
data-slot="command-empty"
className="py-6 text-center text-sm"
{...props}
/>
);
}
function CommandGroup({
className,
...props
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
return (
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
"text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
className
)}
{...props}
/>
)
return (
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
"text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
className,
)}
{...props}
/>
);
}
function CommandSeparator({
className,
...props
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
return (
<CommandPrimitive.Separator
data-slot="command-separator"
className={cn("bg-border -mx-1 h-px", className)}
{...props}
/>
)
return (
<CommandPrimitive.Separator
data-slot="command-separator"
className={cn("bg-border -mx-1 h-px", className)}
{...props}
/>
);
}
function CommandItem({
className,
...props
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
return (
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
return (
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function CommandShortcut({
className,
...props
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="command-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
return (
<span
data-slot="command-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className,
)}
{...props}
/>
);
}
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
};

View File

@@ -1,200 +1,200 @@
"use client"
"use client";
import * as React from "react"
import { ContextMenu as ContextMenuPrimitive } from "radix-ui"
import { Check, ChevronRight, Circle } from "lucide-react"
import * as React from "react";
import { ContextMenu as ContextMenuPrimitive } from "radix-ui";
import { Check, ChevronRight, Circle } from "lucide-react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const ContextMenu = ContextMenuPrimitive.Root
const ContextMenu = ContextMenuPrimitive.Root;
const ContextMenuTrigger = ContextMenuPrimitive.Trigger
const ContextMenuTrigger = ContextMenuPrimitive.Trigger;
const ContextMenuGroup = ContextMenuPrimitive.Group
const ContextMenuGroup = ContextMenuPrimitive.Group;
const ContextMenuPortal = ContextMenuPrimitive.Portal
const ContextMenuPortal = ContextMenuPrimitive.Portal;
const ContextMenuSub = ContextMenuPrimitive.Sub
const ContextMenuSub = ContextMenuPrimitive.Sub;
const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup
const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup;
const ContextMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean
}
React.ElementRef<typeof ContextMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<ContextMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</ContextMenuPrimitive.SubTrigger>
))
ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName
<ContextMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
inset && "pl-8",
className,
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</ContextMenuPrimitive.SubTrigger>
));
ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName;
const ContextMenuSubContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubContent>
React.ElementRef<typeof ContextMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-32 overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-(--radix-context-menu-content-transform-origin)",
className
)}
{...props}
/>
))
ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName
<ContextMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-32 overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-(--radix-context-menu-content-transform-origin)",
className,
)}
{...props}
/>
));
ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName;
const ContextMenuContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content>
React.ElementRef<typeof ContextMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
ref={ref}
className={cn(
"z-50 max-h-(--radix-context-menu-content-available-height) min-w-32 overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-(--radix-context-menu-content-transform-origin)",
className
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
))
ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
ref={ref}
className={cn(
"z-50 max-h-(--radix-context-menu-content-available-height) min-w-32 overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-(--radix-context-menu-content-transform-origin)",
className,
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
));
ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName;
const ContextMenuItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {
inset?: boolean
}
React.ElementRef<typeof ContextMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
))
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName
<ContextMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
inset && "pl-8",
className,
)}
{...props}
/>
));
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName;
const ContextMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.CheckboxItem>
React.ElementRef<typeof ContextMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<ContextMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
))
<ContextMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
className,
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
));
ContextMenuCheckboxItem.displayName =
ContextMenuPrimitive.CheckboxItem.displayName
ContextMenuPrimitive.CheckboxItem.displayName;
const ContextMenuRadioItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.RadioItem>
React.ElementRef<typeof ContextMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<ContextMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Circle className="h-4 w-4 fill-current" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>
))
ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName
<ContextMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
className,
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Circle className="h-4 w-4 fill-current" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>
));
ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName;
const ContextMenuLabel = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Label> & {
inset?: boolean
}
React.ElementRef<typeof ContextMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold text-foreground",
inset && "pl-8",
className
)}
{...props}
/>
))
ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName
<ContextMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold text-foreground",
inset && "pl-8",
className,
)}
{...props}
/>
));
ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName;
const ContextMenuSeparator = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Separator>
React.ElementRef<typeof ContextMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
))
ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName
<ContextMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
));
ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName;
const ContextMenuShortcut = ({
className,
...props
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
ContextMenuShortcut.displayName = "ContextMenuShortcut"
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className,
)}
{...props}
/>
);
};
ContextMenuShortcut.displayName = "ContextMenuShortcut";
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
}
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
};

View File

@@ -1,129 +1,136 @@
import { eachMonthOfInterval, endOfYear, format, startOfYear } from "date-fns"
import { Calendar as CalendarIcon } from "lucide-react"
import * as React from "react"
import { eachMonthOfInterval, endOfYear, format, startOfYear } from "date-fns";
import { Calendar as CalendarIcon } from "lucide-react";
import * as React from "react";
import { Button } from "@/components/ui/button"
import { Calendar } from "@/components/ui/calendar"
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { cn } from "@/lib/utils"
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { cn } from "@/lib/utils";
interface DatePickerProps {
date: Date | undefined
setDate: (date: Date | undefined) => void
date: Date | undefined;
setDate: (date: Date | undefined) => void;
}
export function DatePicker({ date, setDate }: DatePickerProps) {
const [month, setMonth] = React.useState<number>(date ? date.getMonth() : new Date().getMonth())
const [year, setYear] = React.useState<number>(date ? date.getFullYear() : new Date().getFullYear())
const [month, setMonth] = React.useState<number>(
date ? date.getMonth() : new Date().getMonth(),
);
const [year, setYear] = React.useState<number>(
date ? date.getFullYear() : new Date().getFullYear(),
);
const years = React.useMemo(() => {
const currentYear = new Date().getFullYear()
return Array.from({ length: currentYear - 1900 + 1 }, (_, i) => currentYear - i)
}, [])
const years = React.useMemo(() => {
const currentYear = new Date().getFullYear();
return Array.from(
{ length: currentYear - 1900 + 1 },
(_, i) => currentYear - i,
);
}, []);
const months = React.useMemo(() => {
if (year) {
return eachMonthOfInterval({
start: startOfYear(new Date(year, 0, 1)),
end: endOfYear(new Date(year, 0, 1))
})
}
return []
}, [year])
const months = React.useMemo(() => {
if (year) {
return eachMonthOfInterval({
start: startOfYear(new Date(year, 0, 1)),
end: endOfYear(new Date(year, 0, 1)),
});
}
return [];
}, [year]);
React.useEffect(() => {
if (date) {
setMonth(date.getMonth())
setYear(date.getFullYear())
}
}, [date])
React.useEffect(() => {
if (date) {
setMonth(date.getMonth());
setYear(date.getFullYear());
}
}, [date]);
const handleYearChange = (selectedYear: string) => {
const newYear = Number.parseInt(selectedYear, 10)
setYear(newYear)
if (date) {
const newDate = new Date(date)
newDate.setFullYear(newYear)
setDate(newDate)
}
}
const handleYearChange = (selectedYear: string) => {
const newYear = Number.parseInt(selectedYear, 10);
setYear(newYear);
if (date) {
const newDate = new Date(date);
newDate.setFullYear(newYear);
setDate(newDate);
}
};
const handleMonthChange = (selectedMonth: string) => {
const newMonth = Number.parseInt(selectedMonth, 10)
setMonth(newMonth)
if (date) {
const newDate = new Date(date)
newDate.setMonth(newMonth)
setDate(newDate)
} else {
setDate(new Date(year, newMonth, 1))
}
}
const handleMonthChange = (selectedMonth: string) => {
const newMonth = Number.parseInt(selectedMonth, 10);
setMonth(newMonth);
if (date) {
const newDate = new Date(date);
newDate.setMonth(newMonth);
setDate(newDate);
} else {
setDate(new Date(year, newMonth, 1));
}
};
return (
<Popover>
<PopoverTrigger asChild>
<Button
variant={"outline"}
className={cn(
"w-full justify-start text-left font-normal",
!date && "text-muted-foreground"
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{date ? format(date, "PPP") : <span>Pick a date</span>}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<div className="flex justify-between p-2 space-x-1">
<Select onValueChange={handleYearChange} value={year.toString()}>
<SelectTrigger className="w-[120px]">
<SelectValue placeholder="Year" />
</SelectTrigger>
<SelectContent>
{years.map((y) => (
<SelectItem key={y} value={y.toString()}>
{y}
</SelectItem>
))}
</SelectContent>
</Select>
<Select onValueChange={handleMonthChange} value={month.toString()}>
<SelectTrigger className="w-[120px]">
<SelectValue placeholder="Month" />
</SelectTrigger>
<SelectContent>
{months.map((m, index) => (
<SelectItem key={`${index + 1}`} value={index.toString()}>
{format(m, "MMMM")}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Calendar
mode="single"
selected={date}
onSelect={setDate}
month={new Date(year, month)}
onMonthChange={(newMonth) => {
setMonth(newMonth.getMonth())
setYear(newMonth.getFullYear())
}}
initialFocus
/>
</PopoverContent>
</Popover>
)
return (
<Popover>
<PopoverTrigger asChild>
<Button
variant={"outline"}
className={cn(
"w-full justify-start text-left font-normal",
!date && "text-muted-foreground",
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{date ? format(date, "PPP") : <span>Pick a date</span>}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<div className="flex justify-between p-2 space-x-1">
<Select onValueChange={handleYearChange} value={year.toString()}>
<SelectTrigger className="w-[120px]">
<SelectValue placeholder="Year" />
</SelectTrigger>
<SelectContent>
{years.map((y) => (
<SelectItem key={y} value={y.toString()}>
{y}
</SelectItem>
))}
</SelectContent>
</Select>
<Select onValueChange={handleMonthChange} value={month.toString()}>
<SelectTrigger className="w-[120px]">
<SelectValue placeholder="Month" />
</SelectTrigger>
<SelectContent>
{months.map((m, index) => (
<SelectItem key={`${index + 1}`} value={index.toString()}>
{format(m, "MMMM")}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Calendar
mode="single"
selected={date}
onSelect={setDate}
month={new Date(year, month)}
onMonthChange={(newMonth) => {
setMonth(newMonth.getMonth());
setYear(newMonth.getFullYear());
}}
initialFocus
/>
</PopoverContent>
</Popover>
);
}

View File

@@ -1,143 +1,143 @@
"use client"
"use client";
import { XIcon } from "lucide-react"
import { Dialog as DialogPrimitive } from "radix-ui"
import * as React from "react"
import { XIcon } from "lucide-react";
import { Dialog as DialogPrimitive } from "radix-ui";
import * as React from "react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Dialog({
...props
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
}
function DialogTrigger({
...props
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
}
function DialogPortal({
...props
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
}
function DialogClose({
...props
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}
function DialogOverlay({
className,
...props
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
showCloseButton?: boolean;
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
);
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
);
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
/>
);
}
function DialogTitle({
className,
...props
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
);
}
function DialogDescription({
className,
...props
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-start text-muted-foreground text-sm", className)}
{...props}
/>
)
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-start text-muted-foreground text-sm", className)}
{...props}
/>
);
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
};

View File

@@ -1,118 +1,118 @@
"use client"
"use client";
import * as React from "react"
import { Drawer as DrawerPrimitive } from "vaul"
import * as React from "react";
import { Drawer as DrawerPrimitive } from "vaul";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const Drawer = ({
shouldScaleBackground = true,
...props
shouldScaleBackground = true,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Root>) => (
<DrawerPrimitive.Root
shouldScaleBackground={shouldScaleBackground}
{...props}
/>
)
Drawer.displayName = "Drawer"
<DrawerPrimitive.Root
shouldScaleBackground={shouldScaleBackground}
{...props}
/>
);
Drawer.displayName = "Drawer";
const DrawerTrigger = DrawerPrimitive.Trigger
const DrawerTrigger = DrawerPrimitive.Trigger;
const DrawerPortal = DrawerPrimitive.Portal
const DrawerPortal = DrawerPrimitive.Portal;
const DrawerClose = DrawerPrimitive.Close
const DrawerClose = DrawerPrimitive.Close;
const DrawerOverlay = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>
React.ElementRef<typeof DrawerPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Overlay
ref={ref}
className={cn("fixed inset-0 z-50 bg-black/80", className)}
{...props}
/>
))
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName
<DrawerPrimitive.Overlay
ref={ref}
className={cn("fixed inset-0 z-50 bg-black/80", className)}
{...props}
/>
));
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName;
const DrawerContent = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>
React.ElementRef<typeof DrawerPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DrawerPortal>
<DrawerOverlay />
<DrawerPrimitive.Content
ref={ref}
className={cn(
"fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",
className
)}
{...props}
>
<div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
))
DrawerContent.displayName = "DrawerContent"
<DrawerPortal>
<DrawerOverlay />
<DrawerPrimitive.Content
ref={ref}
className={cn(
"fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",
className,
)}
{...props}
>
<div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
));
DrawerContent.displayName = "DrawerContent";
const DrawerHeader = ({
className,
...props
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("grid gap-1.5 p-4 text-center sm:text-left", className)}
{...props}
/>
)
DrawerHeader.displayName = "DrawerHeader"
<div
className={cn("grid gap-1.5 p-4 text-center sm:text-left", className)}
{...props}
/>
);
DrawerHeader.displayName = "DrawerHeader";
const DrawerFooter = ({
className,
...props
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
DrawerFooter.displayName = "DrawerFooter"
<div
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
);
DrawerFooter.displayName = "DrawerFooter";
const DrawerTitle = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>
React.ElementRef<typeof DrawerPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DrawerTitle.displayName = DrawerPrimitive.Title.displayName
<DrawerPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className,
)}
{...props}
/>
));
DrawerTitle.displayName = DrawerPrimitive.Title.displayName;
const DrawerDescription = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>
React.ElementRef<typeof DrawerPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DrawerDescription.displayName = DrawerPrimitive.Description.displayName
<DrawerPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
DrawerDescription.displayName = DrawerPrimitive.Description.displayName;
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
}
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
};

View File

@@ -1,201 +1,201 @@
"use client"
"use client";
import * as React from "react"
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"
import { Check, ChevronRight, Circle } from "lucide-react"
import * as React from "react";
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui";
import { Check, ChevronRight, Circle } from "lucide-react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const DropdownMenu = DropdownMenuPrimitive.Root
const DropdownMenu = DropdownMenuPrimitive.Root;
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
const DropdownMenuGroup = DropdownMenuPrimitive.Group
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
const DropdownMenuPortal = DropdownMenuPrimitive.Portal
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
const DropdownMenuSub = DropdownMenuPrimitive.Sub
const DropdownMenuSub = DropdownMenuPrimitive.Sub;
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto" />
</DropdownMenuPrimitive.SubTrigger>
))
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
inset && "pl-8",
className,
)}
{...props}
>
{children}
<ChevronRight className="ml-auto" />
</DropdownMenuPrimitive.SubTrigger>
));
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName
DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-32 overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-(--radix-dropdown-menu-content-transform-origin)",
className
)}
{...props}
/>
))
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-32 overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-(--radix-dropdown-menu-content-transform-origin)",
className,
)}
{...props}
/>
));
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName
DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-32 overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-(--radix-dropdown-menu-content-transform-origin)",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-32 overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-(--radix-dropdown-menu-content-transform-origin)",
className,
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
));
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
}
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0",
inset && "pl-8",
className,
)}
{...props}
/>
));
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
))
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
className,
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
));
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName
DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
className,
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
));
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className,
)}
{...props}
/>
));
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
));
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
const DropdownMenuShortcut = ({
className,
...props
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
)
}
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
return (
<span
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
);
};
DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
}
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
};

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