56 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
157 changed files with 14469 additions and 8062 deletions

View File

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

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

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

@@ -8,10 +8,9 @@ import type {
ApiResponse,
NewPayment,
Payment,
Topup
Topup,
} from "@/lib/backend-types";
import type { TopupResponse } from "@/lib/types";
import type { User } from "@/lib/types/user";
import { handleApiResponse } from "@/utils/tryCatch";
type GenericGetResponseProps = {
@@ -25,7 +24,8 @@ export async function createPayment(data: NewPayment) {
const session = await getServerSession(authOptions);
console.log("data", data);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL // });
`${
process.env.SARLINK_API_BASE_URL // });
}/api/billing/payment/`,
{
method: "POST",
@@ -94,15 +94,21 @@ type GetPaymentProps = {
[key: string]: string | number | undefined; // Allow additional properties for flexibility
};
export async function getPayments(params: GetPaymentProps) {
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))}`)
.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/?${query}`,
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/?${query}&all_payments=${allPayments}`,
{
method: "GET",
headers: {
@@ -123,17 +129,22 @@ export async function getPayments(params: GetPaymentProps) {
return data;
}
export async function getTopups(params: GenericGetResponseProps) {
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))}`)
.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/topup/?${query}`,
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/?${query}&all_topups=${all_topups}`,
{
method: "GET",
headers: {
@@ -224,17 +235,17 @@ export type VerifyDevicePaymentState = {
success: boolean;
fieldErrors: Record<string, string>;
payload?: FormData;
}
};
export async function verifyDevicePayment(
_prevState: VerifyDevicePaymentState,
formData: FormData
formData: FormData,
): Promise<VerifyDevicePaymentState> {
const session = await getServerSession(authOptions);
// 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";
const paymentId = formData.get("paymentId") as string;
const method = formData.get("method") as "TRANSFER" | "WALLET";
if (!paymentId) {
return {
@@ -267,12 +278,16 @@ export async function verifyDevicePayment(
},
);
const result = await handleApiResponse<Payment>(response, "verifyDevicePayment");
const result = await handleApiResponse<Payment>(
response,
"verifyDevicePayment",
);
revalidatePath("/payments/[paymentId]", "page");
return {
message: method === "WALLET"
message:
method === "WALLET"
? "Payment completed successfully using wallet!"
: "Payment verification successful!",
success: true,
@@ -282,7 +297,8 @@ export async function verifyDevicePayment(
} catch (error: unknown) {
if (error instanceof Error) {
return {
message: error.message || "Payment verification failed. Please try again.",
message:
error.message || "Payment verification failed. Please try again.",
success: false,
fieldErrors: {},
};
@@ -296,7 +312,6 @@ export async function verifyDevicePayment(
}
}
export type VerifyTopupPaymentState = {
transaction?: {
sourceBank: string;
@@ -306,15 +321,15 @@ export type VerifyTopupPaymentState = {
success: boolean;
fieldErrors: Record<string, string>;
payload?: FormData;
}
};
export async function verifyTopupPayment(
_prevState: VerifyTopupPaymentState,
formData: FormData
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;
const topupId = formData.get("topupId") as string;
if (!topupId) {
return {
@@ -336,7 +351,10 @@ export async function verifyTopupPayment(
},
);
const result = await handleApiResponse<TopupResponse>(response, "verifyTopupPayment");
const result = await handleApiResponse<TopupResponse>(
response,
"verifyTopupPayment",
);
revalidatePath("/top-ups/[topupId]", "page");
@@ -349,7 +367,8 @@ export async function verifyTopupPayment(
} catch (error: unknown) {
if (error instanceof Error) {
return {
message: error.message || "Please check your payment details and try again.",
message:
error.message || "Please check your payment details and try again.",
success: false,
fieldErrors: {},
};
@@ -362,5 +381,3 @@ export async function verifyTopupPayment(
}
}
}

View File

@@ -1,56 +1,59 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth";
import type { User, UserProfile } from "@/lib/types/user";
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;
}
try {
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() {
@@ -69,21 +72,231 @@ export async function getProfile() {
return handleApiResponse<User>(response, "getProfile");
}
export async function getProfileById(userId: string) {
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}/`,
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/${userId}/reject/`,
{
method: "GET",
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
body: JSON.stringify({ rejection_details: rejection_details }),
},
);
return handleApiResponse<UserProfile>(response, "getProfilebyId");
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: `Token ${session?.apiToken}`,
},
body: JSON.stringify({
amount: Number.parseInt(amount),
user_id: Number.parseInt(user_id),
description,
}),
},
);
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,
};
}
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() {
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>
<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,9 +1,9 @@
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,
@@ -25,13 +25,18 @@ export default async function DeviceDetails({
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 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 font-bold">
<h3 className="text-2xl text-sarLinkOrange motion-preset-slide-down-md font-bold">
{device?.name}
</h3>
<Badge variant={"secondary"}>{device?.mac}</Badge>
<p className="text-muted-foreground text-sm mt-2">
<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",
@@ -40,7 +45,7 @@ export default async function DeviceDetails({
})}
</p>
</div>
<div className="flex items-center gap-2 flex-col">
<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

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,6 +1,7 @@
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,
@@ -11,7 +12,6 @@ export default async function ParentalControl({
status: string;
}>;
}) {
const parentalControlFilters = {
is_active: "true",
has_a_pending_payment: "false",
@@ -27,9 +27,40 @@ export default async function ParentalControl({
id="user-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
>
<Search />
<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={"loading...."}>
<Suspense
key={(await searchParams).page}
fallback={
<DevicesTableSkeleton
headers={["Device Name", "Mac Address", "Vendor", "#"]}
length={10}
/>
}
>
<DevicesTable
parentalControl={true}
searchParams={searchParams}

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,5 +1,6 @@
import { redirect } from "next/navigation";
import { getPayment, getProfile } from "@/actions/payment";
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";
@@ -30,7 +31,9 @@ export default async function PaymentPage({
<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" && (
{!payment.is_expired &&
payment.paid &&
payment.status !== "PENDING" && (
<Button
disabled
className={cn(

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,4 +1,5 @@
import { Suspense } from "react";
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import DynamicFilter from "@/components/generic-filter";
import { PaymentsTable } from "@/components/payments-table";
@@ -14,8 +15,8 @@ export default async function Payments({
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"
@@ -72,7 +73,15 @@ export default async function Payments({
]}
/>{" "}
</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

@@ -1,10 +1,10 @@
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { getProfileById } from "@/actions/user-actions";
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() {
@@ -41,14 +41,14 @@ export default async function Profile() {
<FloatingLabelInput
id="floating-island"
label="Island"
value={`${profile?.atoll.name}. ${profile?.island.name}`}
value={`${profile?.atoll?.name}. ${profile?.island?.name}`}
readOnly
/>
<FloatingLabelInput
id="floating-dob"
label="Date of Birth"
value={`${new Date(
profile?.dob.toString() ?? "",
profile?.dob?.toString() ?? "",
).toLocaleDateString("en-US", {
month: "short",
day: "2-digit",

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

@@ -1,4 +1,5 @@
import { Suspense } from "react";
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import DynamicFilter from "@/components/generic-filter";
import { TopupsTable } from "@/components/topups-table";
@@ -78,7 +79,15 @@ export default async function Topups({
]}
/>
</div>
<Suspense key={query} fallback={"loading...."}>
<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",
},
{
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",
},
{
value: "verified",
label: "Verified",
icon: <Hourglass size={14} />,
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 async function Wallet({
searchParams,
}: {
searchParams: Promise<{
query: string;
page: number;
sortBy: string;
status: string;
}>;
}) {
const query = (await searchParams)?.query || "";
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>
<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>
);
}

View File

@@ -1,4 +1,4 @@
@import 'tailwindcss';
@import "tailwindcss";
@plugin "tailwindcss-animate";
@plugin "@pyncz/tailwind-mask-image";
@plugin "tailwindcss-motion";
@@ -76,6 +76,14 @@
}
}
.credit-bg {
background-image: url("data:image/svg+xml,%3Csvg width='6' height='6' viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='%2340b02f' fill-opacity='0.29' fill-rule='evenodd'%3E%3Cpath d='M5 0h1L0 6V5zM6 5v1H5z'/%3E%3C/g%3E%3C/svg%3E");
}
.debit-bg {
background-image: url("data:image/svg+xml,%3Csvg width='6' height='6' viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='%23d35c5c' fill-opacity='0.2' fill-rule='evenodd'%3E%3Cpath d='M5 0h1L0 6V5zM6 5v1H5z'/%3E%3C/g%3E%3C/svg%3E");
}
.error-bg {
background-image: url("data:image/svg+xml,%3Csvg width='6' height='6' viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='%23e06f10' fill-opacity='0.35' fill-rule='evenodd'%3E%3Cpath d='M5 0h1L0 6V5zM6 5v1H5z'/%3E%3C/g%3E%3C/svg%3E");
}
@@ -117,7 +125,6 @@ background-image: url("data:image/svg+xml,%3Csvg width='6' height='6' viewBox='0
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
@@ -152,7 +159,6 @@ background-image: url("data:image/svg+xml,%3Csvg width='6' height='6' viewBox='0
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {

View File

@@ -35,7 +35,9 @@ export default async function RootLayout({
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`}>
<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} />
@@ -46,14 +48,11 @@ export default async function RootLayout({
enableSystem
disableTransitionOnChange
>
<QueryProvider>
{children}
</QueryProvider>
<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;
}

3
commitlint.config.js Normal file
View File

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

View File

@@ -1,4 +1,4 @@
"use client"
"use client";
import { Clipboard, ClipboardCheck } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";

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",
{
{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>
);
}

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",
// },
// });
// 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>
// <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>
// <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>
// );
// 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 [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;
// 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.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

@@ -54,7 +54,6 @@ export function AccountPopover() {
</Button>
</Link>
</div>
</div>
</PopoverContent>
</Popover>

View File

@@ -1,6 +1,6 @@
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { NuqsAdapter } from 'nuqs/adapters/next/app'
import { NuqsAdapter } from "nuqs/adapters/next/app";
import { getProfile } from "@/actions/user-actions";
import { authOptions } from "@/app/auth";
import { DeviceCartDrawer } from "@/components/device-cart";
@@ -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>
@@ -105,7 +115,9 @@ export default function SignUpForm() {
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
@@ -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,7 +234,10 @@ 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
@@ -233,7 +262,10 @@ 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
@@ -244,7 +276,9 @@ export default function SignUpForm() {
)}
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>
@@ -273,7 +310,9 @@ export default function SignUpForm() {
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
@@ -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

@@ -10,14 +10,18 @@ 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, payment] = await tryCatch(cancelPayment({ id: paymentId }));
const [error, payment] = await tryCatch(
cancelPayment({ id: paymentId }),
);
console.log(payment);
if (error) {
toast.error(error.message);

View File

@@ -8,9 +8,7 @@ import { cancelTopup } from "@/actions/payment";
import { tryCatch } from "@/utils/tryCatch";
import { Button } from "../ui/button";
export default function CancelTopupButton({
topupId,
}: { topupId: string }) {
export default function CancelTopupButton({ topupId }: { topupId: string }) {
const router = useRouter();
const [loading, setLoading] = React.useState(false);
return (
@@ -25,7 +23,7 @@ export default function CancelTopupButton({
toast.success("Topup cancelled successfully!", {
description: `Your topup of ${topup?.amount} MVR has been cancelled.`,
closeButton: true,
})
});
router.replace("/top-ups");
}
}}

View File

@@ -1,57 +1,67 @@
'use client'
import { usePathname, useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'
import { Progress } from '@/components/ui/progress'
"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 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`
}
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()
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)
}, [])
setMounted(true);
}, []);
useEffect(() => {
const timer = setInterval(() => {
setTimeLeft(calculateTimeLeft(expiresAt))
}, 1000)
setTimeLeft(calculateTimeLeft(expiresAt));
}, 1000);
return () => clearInterval(timer)
}, [expiresAt])
return () => clearInterval(timer);
}, [expiresAt]);
useEffect(() => {
if (timeLeft <= 0) {
router.replace(pathname)
router.replace(pathname);
}
}, [timeLeft, router, pathname])
}, [timeLeft, router, pathname]);
if (!mounted) {
return null
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' />
<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} />
<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">

View File

@@ -12,7 +12,13 @@ export default function ClickableRow({
device,
parentalControl,
admin = false,
}: { device: Device; parentalControl?: boolean; admin?: boolean }) {
idx,
}: {
device: Device;
parentalControl?: boolean;
admin?: boolean;
idx?: number;
}) {
const [devices, setDeviceCart] = useAtom(deviceCartAtom);
return (
@@ -22,6 +28,7 @@ export default function ClickableRow({
(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;

View File

@@ -12,12 +12,18 @@ import { Badge } from "./ui/badge";
export default function DeviceCard({
device,
parentalControl,
}: { device: Device; parentalControl?: boolean }) {
isAdmin,
}: {
device: Device;
parentalControl?: boolean;
isAdmin?: boolean;
}) {
const [devices, setDeviceCart] = useAtom(deviceCartAtom);
const isChecked = devices.some((d) => d.id === device.id);
return (
// biome-ignore lint/a11y/noStaticElementInteractions: <dw about it>
<div
onKeyUp={() => {}}
onClick={() => {
@@ -35,7 +41,7 @@ export default function DeviceCard({
>
<div
className={cn(
"flex text-sm justify-between items-center my-2 p-4 border rounded-md",
"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"
@@ -45,7 +51,10 @@ export default function DeviceCard({
<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" : "")}
className={cn(
"font-medium hover:underline ml-0.5",
device.is_active ? "text-green-600" : "",
)}
href={`/devices/${device.id}`}
>
{device.name}
@@ -77,7 +86,7 @@ export default function DeviceCard({
)}
{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">
<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>
@@ -96,7 +105,7 @@ export default function DeviceCard({
<AddDevicesToCartButton device={device} />
) : (
<BlockDeviceDialog
admin={false}
admin={isAdmin}
type={device.blocked ? "unblock" : "block"}
device={device}
/>

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

@@ -4,7 +4,6 @@ import { authOptions } from "@/app/auth";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableFooter,
TableHead,
@@ -52,9 +51,7 @@ export async function DevicesTable({
}
apiParams.limit = limit;
apiParams.offset = offset;
const [error, devices] = await tryCatch(
getDevices(apiParams),
);
const [error, devices] = await tryCatch(getDevices(apiParams));
if (error) {
if (error.message === "UNAUTHORIZED") {
redirect("/auth/signin");
@@ -67,13 +64,12 @@ export async function DevicesTable({
<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>
<h3>{parentalControl ? "No active devices" : "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>
@@ -83,12 +79,13 @@ export async function DevicesTable({
</TableRow>
</TableHeader>
<TableBody className="overflow-scroll">
{data?.map((device) => (
{data?.map((device, idx) => (
<ClickableRow
admin={isAdmin}
key={device.id}
device={device}
parentalControl={parentalControl}
idx={idx + 1}
/>
))}
</TableBody>
@@ -96,9 +93,7 @@ export async function DevicesTable({
<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} device.</p>
) : (
<p className="text-center">
Total {meta?.total} devices.
@@ -115,6 +110,7 @@ export async function DevicesTable({
parentalControl={parentalControl}
key={device.id}
device={device}
isAdmin={isAdmin}
/>
))}
</div>
@@ -123,8 +119,7 @@ export async function DevicesTable({
currentPage={meta?.current_page}
/>
</>
)
}
)}
</div>
);
}

View File

@@ -1,12 +1,11 @@
"use client";
import {
BadgeDollarSign,
Loader2,
Wallet
} from "lucide-react";
import { BadgeDollarSign, Loader2, Wallet } from "lucide-react";
import { useActionState, useEffect } from "react";
import { toast } from "sonner";
import { type VerifyDevicePaymentState, verifyDevicePayment } from "@/actions/payment";
import {
type VerifyDevicePaymentState,
verifyDevicePayment,
} from "@/actions/payment";
import {
Table,
TableBody,
@@ -17,6 +16,7 @@ import {
} 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";
@@ -29,9 +29,16 @@ const initialState: VerifyDevicePaymentState = {
export default function DevicesToPay({
payment,
user,
disabled
}: { payment?: Payment; user?: User, disabled?: boolean }) {
const [state, formAction, isPending] = useActionState(verifyDevicePayment, initialState);
disabled,
}: {
payment?: Payment;
user?: User;
disabled?: boolean;
}) {
const [state, formAction, isPending] = useActionState(
verifyDevicePayment,
initialState,
);
// Handle toast notifications based on state changes
useEffect(() => {
@@ -40,7 +47,11 @@ export default function DevicesToPay({
closeButton: true,
description: state.message,
});
} else if (!state.success && state.message && state.message !== initialState.message) {
} else if (
!state.success &&
state.message &&
state.message !== initialState.message
) {
toast.error("Payment Verification Failed", {
closeButton: true,
description: state.message,
@@ -67,11 +78,13 @@ export default function DevicesToPay({
{devices?.map((device) => (
<div
key={device.id}
className="bg-muted border rounded p-2 flex gap-2 items-center"
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">{device.name}</div>
<div className="text-xs text-muted-foreground">
<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>
@@ -82,6 +95,7 @@ export default function DevicesToPay({
<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
@@ -101,27 +115,38 @@ export default function DevicesToPay({
<div className="flex flex-col gap-2">
{isWalletPayVisible && (
<form action={formAction}>
<input type="hidden" name="paymentId" value={payment?.id ?? ""} />
<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"}
{isPending
? "Processing payment..."
: "Pay with wallet"}
<Wallet />
</Button>
</form>
)}
<form action={formAction}>
<input type="hidden" name="paymentId" value={payment?.id ?? ""} />
<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"
className="mb-4 w-full"
>
{isPending ? "Processing payment..." : "I have paid"}
{isPending ? (
@@ -134,39 +159,42 @@ export default function DevicesToPay({
</div>
)}
</div>
)}
</TableCaption>
<TableBody className="">
<TableRow>
<TableCell>Payment created</TableCell>
<TableCell className="text-right">
{new Date(payment?.created_at ?? "").toLocaleDateString("en-US", {
<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">
<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">
<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">
<TableCell className="text-right text-3xl font-bold motion-preset-slide-up-sm motion-delay-150">
{payment?.amount?.toFixed(2)}
</TableCell>
</TableRow>
@@ -176,5 +204,3 @@ export default function DevicesToPay({
</div>
);
}

View File

@@ -1,13 +1,22 @@
"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();
@@ -17,16 +26,15 @@ export default function DeviceFilter() {
const pathname = usePathname();
const params = new URLSearchParams(searchParams.toString());
const [urlInputName] = useQueryState("name", {
clearOnDefault: true
})
clearOnDefault: true,
});
const [urlInputMac] = useQueryState("mac", {
clearOnDefault: true
})
clearOnDefault: true,
});
const [urlInputVendor] = useQueryState("vendor", {
clearOnDefault: true
})
clearOnDefault: true,
});
// Local state for input fields
const [inputName, setInputName] = useState(urlInputName ?? "");
@@ -34,16 +42,29 @@ export default function DeviceFilter() {
const [inputVendor, setInputVendor] = useState(urlInputVendor ?? "");
// Map filter keys to their state setters
const filterSetters: Record<string, React.Dispatch<React.SetStateAction<string>>> = {
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");
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");
startTransition(() => {
@@ -54,12 +75,16 @@ export default function DeviceFilter() {
const appliedFilters = searchParams
.toString()
.split("&")
.filter((filter) => !filter.startsWith("page=") && filter)
.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">
<Button
className="w-full sm:w-48 flex items-end justify-between"
onClick={() => setIsOpen(!isOpen)}
variant="outline"
>
Filter
<ListFilter />
</Button>
@@ -69,9 +94,7 @@ export default function DeviceFilter() {
<DrawerHeader>
<DrawerTitle>Device Filters</DrawerTitle>
<DrawerDescription asChild>
<div>
Select your desired filters here
</div>
<div>Select your desired filters here</div>
</DrawerDescription>
</DrawerHeader>
@@ -79,17 +102,17 @@ export default function DeviceFilter() {
<Input
placeholder="Device name ..."
value={inputName || searchParams.get("name") || ""}
onChange={e => setInputName(e.target.value)}
onChange={(e) => setInputName(e.target.value)}
/>
<Input
placeholder="Device Mac address ..."
value={inputMac || searchParams.get("mac") || ""}
onChange={e => setInputMac(e.target.value)}
onChange={(e) => setInputMac(e.target.value)}
/>
<Input
placeholder="Device vendor ..."
value={inputVendor || searchParams.get("vendor") || ""}
onChange={e => setInputVendor(e.target.value)}
onChange={(e) => setInputVendor(e.target.value)}
/>
</div>
<DrawerFooter className="max-w-sm mx-auto">
@@ -107,17 +130,18 @@ export default function DeviceFilter() {
<Loader2 className="ml-2 animate-spin" />
</>
) : (
<>
Apply Filters
</>
<>Apply Filters</>
)}
</Button>
<Button variant="secondary" onClick={() => {
<Button
variant="secondary"
onClick={() => {
setInputName("");
setInputMac("");
setInputVendor("");
replace(pathname)
}}>
replace(pathname);
}}
>
Clear Filters
</Button>
@@ -133,11 +157,13 @@ export default function DeviceFilter() {
<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}>
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 ? (
{disabled ? (
<Loader2 className="animate-spin" size={16} />
) : (
<X
@@ -157,8 +183,7 @@ export default function DeviceFilter() {
>
Remove
</X>
)
}
)}
</Badge>
))}
</div>
@@ -166,18 +191,28 @@ export default function DeviceFilter() {
);
}
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>;
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>;
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>;
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 className="flex items-center justify-center h-screen">
<Loader2 className="animate-spin" />
</div>
)
);
}

View File

@@ -181,11 +181,10 @@ export default function DynamicFilter<
const maxValue = searchParams.get(`${input.name}_max`);
const parsedMin = minValue ? Number(minValue) : input.min;
const parsedMax = maxValue ? Number(maxValue) : input.max;
(initialState as FilterValues<TFilterKeys, TInputs>)[input.name] =
[parsedMin, parsedMax] as FilterValues<
TFilterKeys,
TInputs
>[typeof input.name];
(initialState as FilterValues<TFilterKeys, TInputs>)[input.name] = [
parsedMin,
parsedMax,
] as FilterValues<TFilterKeys, TInputs>[typeof input.name];
} else {
(initialState as FilterValues<TFilterKeys, TInputs>)[input.name] =
(urlValue || "") as FilterValues<
@@ -227,8 +226,7 @@ export default function DynamicFilter<
};
// Handler for dual range slider changes
const handleDualRangeChange =
(name: TFilterKeys) => (values: number[]) => {
const handleDualRangeChange = (name: TFilterKeys) => (values: number[]) => {
setInputValues((prev) => ({
...prev,
[name]: values,
@@ -253,7 +251,10 @@ export default function DynamicFilter<
} else if (input.type === "dual-range-slider") {
const rangeValues = value as number[];
// Only set params if values are different from the default min/max
if (rangeValues.length === 2 && (rangeValues[0] !== input.min || rangeValues[1] !== input.max)) {
if (
rangeValues.length === 2 &&
(rangeValues[0] !== input.min || rangeValues[1] !== input.max)
) {
newParams.set(`${input.name}_min`, rangeValues[0].toString());
newParams.set(`${input.name}_max`, rangeValues[1].toString());
} else {
@@ -290,8 +291,15 @@ export default function DynamicFilter<
} else if (input.type === "dual-range-slider") {
(clearedInputState as FilterValues<TFilterKeys, TInputs>)[
input.name as TFilterKeys
] = [input.min, input.max] as FilterValues<TFilterKeys, TInputs>[typeof input.name];
} else if (input.type === "radio-group" || input.type === "string" || input.type === "number") {
] = [input.min, input.max] as FilterValues<
TFilterKeys,
TInputs
>[typeof input.name];
} else if (
input.type === "radio-group" ||
input.type === "string" ||
input.type === "number"
) {
(clearedInputState as FilterValues<TFilterKeys, TInputs>)[
input.name as TFilterKeys
] = "" as FilterValues<TFilterKeys, TInputs>[typeof input.name];
@@ -378,7 +386,9 @@ export default function DynamicFilter<
}
if (config.type === "dual-range-slider") {
const rangeValues = value as number[];
const formatLabel = config.formatLabel || ((val: number | undefined) => val?.toString() || "");
const formatLabel =
config.formatLabel ||
((val: number | undefined) => val?.toString() || "");
return (
<p>
{config.label}:{" "}
@@ -396,14 +406,16 @@ export default function DynamicFilter<
const displayValue = option?.label || stringValue;
return (
<p>
{config.label}: <span className="text-muted-foreground">{displayValue}</span>
{config.label}:{" "}
<span className="text-muted-foreground">{displayValue}</span>
</p>
);
}
// For other values, display as normal
return (
<p>
{config.label}: <span className="text-muted-foreground">{stringValue}</span>
{config.label}:{" "}
<span className="text-muted-foreground">{stringValue}</span>
</p>
);
}
@@ -501,7 +513,12 @@ export default function DynamicFilter<
</Label>
<div className="px-3 py-2 mt-5">
<DualRangeSlider
label={(value) => <span className="text-xs">{value}{input.sliderLabel}</span>}
label={(value) => (
<span className="text-xs">
{value}
{input.sliderLabel}
</span>
)}
value={inputValues[input.name] as number[]}
onValueChange={handleDualRangeChange(input.name)}
min={input.min}

View File

@@ -1,21 +1,16 @@
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"
} from "@/components/ui/accordion";
import { Button } from "@/components/ui/button";
export function GetMacAccordion() {
return (
<Accordion
type="single"
collapsible
className="w-full"
>
<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">
@@ -46,19 +41,15 @@ export function GetMacAccordion() {
<AccordionItem value="windows">
<AccordionTrigger>Windows Laptop</AccordionTrigger>
<AccordionContent>
Settings Network and Internet Wi-Fi Hardware
Properties Physical address (MAC):
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"
>
<p>Please contact SAR Link for assistance.</p>
<Link href="tel:+9609198026">
<Button className="mt-4">
<PhoneIcon className="mr-2" />
9198026
@@ -70,5 +61,5 @@ export function GetMacAccordion() {
</AccordionContent>
</AccordionItem>
</Accordion>
)
);
}

View File

@@ -1,19 +1,33 @@
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 }: {
export default function InputReadOnly({
label,
value,
labelClassName,
className,
showCheck = true,
checkTrue = false,
}: {
label: string;
value: string;
labelClassName?: string;
className?: string;
showCheck?: boolean;
checkTrue?: 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
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
htmlFor="input-33"
className={cn("block px-3 pt-2 text-xs font-medium", labelClassName)}
>
{label}
</label>
<input
@@ -29,13 +43,12 @@ export default function InputReadOnly({ label, value, labelClassName, className,
{showCheck && (
<div>
{checkTrue ? (
<CheckCheck className='mx-4 text-green-500' />
<CheckCheck className="mx-4 text-green-500" />
) : (
<X className='mx-4 text-red-500' />
<X className="mx-4 text-red-500" />
)}
</div>
)}
</div>
)
);
}

View File

@@ -1,4 +1,3 @@
import { cn } from "@/lib/utils";
import { Minus, Plus } from "lucide-react";
import { useEffect } from "react";
import {
@@ -8,16 +7,23 @@ import {
Label,
NumberField,
} from "react-aria-components";
import { cn } from "@/lib/utils";
export default function NumberInput({
maxAllowed,
label,
value,
value = 100,
onChange,
className,
isDisabled,
}: { maxAllowed?: number, label: string; value: number; onChange: (value: number) => void, className?: string, isDisabled?: boolean }) {
}: {
maxAllowed?: number;
label: string;
value?: number;
onChange: (value: number) => void;
className?: string;
isDisabled?: boolean;
}) {
useEffect(() => {
if (maxAllowed) {
if (value > maxAllowed) {
@@ -25,8 +31,15 @@ export default function NumberInput({
}
}
}, [maxAllowed, value, onChange]);
return (
<NumberField isDisabled={isDisabled} className={cn(className)} value={value} minValue={0} onChange={onChange}>
<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">

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

@@ -5,7 +5,6 @@ import { getPayments } from "@/actions/payment";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableFooter,
TableHead,
@@ -52,14 +51,13 @@ export async function PaymentsTable({
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 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">
<TableCaption>Table of all devices.</TableCaption>
<TableHeader>
<TableRow>
<TableHead>Details</TableHead>
@@ -70,7 +68,7 @@ export async function PaymentsTable({
</TableHeader>
<TableBody className="overflow-scroll">
{payments?.data?.map((payment) => (
<TableRow key={payment.id}>
<TableRow className="motion-preset-fade-md" key={payment.id}>
<TableCell>
<div
className={cn(
@@ -189,11 +187,17 @@ export async function PaymentsTable({
);
}
function MobilePaymentDetails({ payment }: { payment: Payment }) {
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",
"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
@@ -264,6 +268,14 @@ function MobilePaymentDetails({ payment }: { payment: Payment }) {
<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>

View File

@@ -10,7 +10,6 @@ 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(
@@ -36,9 +35,7 @@ export default function PriceCalculator() {
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>
<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 */}
@@ -87,4 +84,3 @@ export default function PriceCalculator() {
</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>

View File

@@ -1,8 +1,5 @@
"use client";
import {
BadgeDollarSign,
Loader2
} from "lucide-react";
import { BadgeDollarSign, Loader2 } from "lucide-react";
import { useActionState, useEffect } from "react";
import { toast } from "sonner";
import {
@@ -18,6 +15,7 @@ import {
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";
@@ -64,6 +62,7 @@ export default function TopupToPay({
<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
@@ -104,6 +103,7 @@ export default function TopupToPay({
</div>
)}
</div>
)}
</TableCaption>
<TableBody className="">
<TableRow>
@@ -154,5 +154,3 @@ export default function TopupToPay({
</div>
);
}

View File

@@ -5,7 +5,6 @@ import { getTopups } from "@/actions/payment";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableFooter,
TableHead,
@@ -52,14 +51,13 @@ export async function TopupsTable({
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 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">
<TableCaption>Table of all topups.</TableCaption>
<TableHeader>
<TableRow>
<TableHead>Details</TableHead>
@@ -73,7 +71,7 @@ export async function TopupsTable({
<TableCell>
<div
className={cn(
"flex flex-col items-start border rounded p-2",
"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
@@ -167,9 +165,11 @@ function MobileTopupDetails({ topup }: { topup: Topup }) {
return (
<div
className={cn(
"flex flex-col items-start border rounded p-2 my-2",
"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"
? "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",
)}
>

View File

@@ -1,15 +1,15 @@
"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
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
return <AccordionPrimitive.Root data-slot="accordion" {...props} />;
}
function AccordionItem({
@@ -22,7 +22,7 @@ function AccordionItem({
className={cn("border-b last:border-b-0", className)}
{...props}
/>
)
);
}
function AccordionTrigger({
@@ -36,7 +36,7 @@ function AccordionTrigger({
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
className,
)}
{...props}
>
@@ -44,7 +44,7 @@ function AccordionTrigger({
<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({
@@ -60,7 +60,7 @@ function AccordionContent({
>
<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,130 +1,145 @@
"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
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-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
"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}
ref={ref}
/>
))
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
);
}
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
function AlertDialogContent({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
data-slot="alert-dialog-content"
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
"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>
))
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
);
}
const AlertDialogHeader = ({
function AlertDialogHeader({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
);
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
/>
)
AlertDialogHeader.displayName = "AlertDialogHeader"
);
}
const AlertDialogFooter = ({
function AlertDialogTitle({
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"
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
ref={ref}
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...props}
/>
))
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
);
}
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
))
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName
);
}
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
function AlertDialogAction({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return (
<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) => (
function AlertDialogCancel({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(
buttonVariants({ variant: "outline" }),
"mt-2 sm:mt-0",
className
)}
className={cn(buttonVariants({ variant: "outline" }), className)}
{...props}
/>
))
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
);
}
export {
AlertDialog,
@@ -138,4 +153,4 @@ export {
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
}
};

View File

@@ -1,7 +1,7 @@
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",
@@ -16,8 +16,8 @@ const alertVariants = cva(
defaultVariants: {
variant: "default",
},
}
)
},
);
const Alert = React.forwardRef<
HTMLDivElement,
@@ -29,8 +29,8 @@ const Alert = React.forwardRef<
className={cn(alertVariants({ variant }), className)}
{...props}
/>
))
Alert.displayName = "Alert"
));
Alert.displayName = "Alert";
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
@@ -41,8 +41,8 @@ const AlertTitle = React.forwardRef<
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
));
AlertTitle.displayName = "AlertTitle";
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
@@ -53,7 +53,7 @@ const AlertDescription = React.forwardRef<
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
));
AlertDescription.displayName = "AlertDescription";
export { Alert, AlertTitle, AlertDescription }
export { Alert, AlertTitle, AlertDescription };

View File

@@ -69,7 +69,13 @@ export async function AppSidebar({
icon: <Smartphone size={16} />,
},
{
title: "Payments",
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",
@@ -81,10 +87,10 @@ export async function AppSidebar({
perm_identifier: "topup",
},
{
title: "Parental Control",
link: "/parental-control?page=1",
icon: <CreditCard size={16} />,
perm_identifier: "device",
title: "Transaction History",
link: "/wallet",
icon: <Wallet2Icon size={16} />,
perm_identifier: "wallet transaction",
},
{
title: "Agreements",
@@ -92,12 +98,6 @@ export async function AppSidebar({
icon: <Handshake size={16} />,
perm_identifier: "device",
},
{
title: "Wallet",
link: "/wallet",
icon: <Wallet2Icon size={16} />,
perm_identifier: "wallet",
},
],
},
{
@@ -122,6 +122,12 @@ export async function AppSidebar({
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",
@@ -140,17 +146,19 @@ export async function AppSidebar({
} else {
// Filter out ADMIN CONTROL category for non-admin users
const nonAdminCategories = categories.filter(
(category) => category.id !== "ADMIN CONTROL"
(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) => {
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 };
@@ -195,7 +203,9 @@ export async function AppSidebar({
<SidebarMenuButton className="py-6" asChild>
<Link className="text-md" href={item.link}>
{item.icon}
<span className="opacity-70 ml-2">
<span
className={`opacity-70 motion-preset-fade motion-duration-300 ml-2`}
>
{item.title}
</span>
</Link>

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,9 +1,9 @@
"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>,
@@ -13,12 +13,12 @@ const Avatar = React.forwardRef<
ref={ref}
className={cn(
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
className
className,
)}
{...props}
/>
))
Avatar.displayName = AvatarPrimitive.Root.displayName
));
Avatar.displayName = AvatarPrimitive.Root.displayName;
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
@@ -29,8 +29,8 @@ const AvatarImage = React.forwardRef<
className={cn("aspect-square h-full w-full", className)}
{...props}
/>
))
AvatarImage.displayName = AvatarPrimitive.Image.displayName
));
AvatarImage.displayName = AvatarPrimitive.Image.displayName;
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
@@ -40,11 +40,11 @@ const AvatarFallback = React.forwardRef<
ref={ref}
className={cn(
"flex h-full w-full items-center justify-center rounded-full bg-muted",
className
className,
)}
{...props}
/>
))
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
));
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName;
export { Avatar, AvatarImage, AvatarFallback }
export { Avatar, AvatarImage, AvatarFallback };

View File

@@ -1,7 +1,7 @@
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",
@@ -20,8 +20,8 @@ const badgeVariants = cva(
defaultVariants: {
variant: "default",
},
}
)
},
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
@@ -30,7 +30,7 @@ export interface BadgeProps
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
);
}
export { Badge, badgeVariants }
export { Badge, badgeVariants };

View File

@@ -1,16 +1,16 @@
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
separator?: React.ReactNode;
}
>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />)
Breadcrumb.displayName = "Breadcrumb"
>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />);
Breadcrumb.displayName = "Breadcrumb";
const BreadcrumbList = React.forwardRef<
HTMLOListElement,
@@ -20,12 +20,12 @@ const BreadcrumbList = React.forwardRef<
ref={ref}
className={cn(
"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
className
className,
)}
{...props}
/>
))
BreadcrumbList.displayName = "BreadcrumbList"
));
BreadcrumbList.displayName = "BreadcrumbList";
const BreadcrumbItem = React.forwardRef<
HTMLLIElement,
@@ -36,16 +36,16 @@ const BreadcrumbItem = React.forwardRef<
className={cn("inline-flex items-center gap-1.5", className)}
{...props}
/>
))
BreadcrumbItem.displayName = "BreadcrumbItem"
));
BreadcrumbItem.displayName = "BreadcrumbItem";
const BreadcrumbLink = React.forwardRef<
HTMLAnchorElement,
React.ComponentPropsWithoutRef<"a"> & {
asChild?: boolean
asChild?: boolean;
}
>(({ asChild, className, ...props }, ref) => {
const Comp = asChild ? SlotPrimitive.Slot : "a"
const Comp = asChild ? SlotPrimitive.Slot : "a";
return (
<Comp
@@ -53,9 +53,9 @@ const BreadcrumbLink = React.forwardRef<
className={cn("transition-colors hover:text-foreground", className)}
{...props}
/>
)
})
BreadcrumbLink.displayName = "BreadcrumbLink"
);
});
BreadcrumbLink.displayName = "BreadcrumbLink";
const BreadcrumbPage = React.forwardRef<
HTMLSpanElement,
@@ -69,8 +69,8 @@ const BreadcrumbPage = React.forwardRef<
className={cn("font-normal text-foreground", className)}
{...props}
/>
))
BreadcrumbPage.displayName = "BreadcrumbPage"
));
BreadcrumbPage.displayName = "BreadcrumbPage";
const BreadcrumbSeparator = ({
children,
@@ -85,8 +85,8 @@ const BreadcrumbSeparator = ({
>
{children ?? <ChevronRight />}
</li>
)
BreadcrumbSeparator.displayName = "BreadcrumbSeparator"
);
BreadcrumbSeparator.displayName = "BreadcrumbSeparator";
const BreadcrumbEllipsis = ({
className,
@@ -101,8 +101,8 @@ const BreadcrumbEllipsis = ({
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More</span>
</span>
)
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis"
);
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis";
export {
Breadcrumb,
@@ -112,4 +112,4 @@ export {
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
}
};

View File

@@ -1,8 +1,8 @@
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",
@@ -32,8 +32,8 @@ const buttonVariants = cva(
variant: "default",
size: "default",
},
}
)
},
);
function Button({
className,
@@ -43,9 +43,9 @@ function Button({
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
asChild?: boolean;
}) {
const Comp = asChild ? SlotPrimitive.Slot : "button"
const Comp = asChild ? SlotPrimitive.Slot : "button";
return (
<Comp
@@ -53,7 +53,7 @@ function Button({
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
);
}
export { Button, buttonVariants }
export { Button, buttonVariants };

View File

@@ -1,15 +1,15 @@
"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"
} 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,
@@ -21,9 +21,9 @@ function Calendar({
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
@@ -32,7 +32,7 @@ function Calendar({
"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
className,
)}
captionLayout={captionLayout}
formatters={{
@@ -44,34 +44,34 @@ function Calendar({
root: cn("w-fit", defaultClassNames.root),
months: cn(
"relative flex flex-col gap-4 md:flex-row",
defaultClassNames.months
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
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
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
defaultClassNames.button_next,
),
month_caption: cn(
"flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",
defaultClassNames.month_caption
defaultClassNames.month_caption,
),
dropdowns: cn(
"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
defaultClassNames.dropdowns
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
defaultClassNames.dropdown_root,
),
dropdown: cn("absolute inset-0 opacity-0", defaultClassNames.dropdown),
caption_label: cn(
@@ -79,44 +79,44 @@ function Calendar({
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
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
defaultClassNames.weekday,
),
week: cn("mt-2 flex w-full", defaultClassNames.week),
week_number_header: cn(
"w-(--cell-size) select-none",
defaultClassNames.week_number_header
defaultClassNames.week_number_header,
),
week_number: cn(
"text-muted-foreground select-none text-[0.8rem]",
defaultClassNames.week_number
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
defaultClassNames.day,
),
range_start: cn(
"bg-accent rounded-l-md",
defaultClassNames.range_start
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
defaultClassNames.today,
),
outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside
defaultClassNames.outside,
),
disabled: cn(
"text-muted-foreground opacity-50",
defaultClassNames.disabled
defaultClassNames.disabled,
),
hidden: cn("invisible", defaultClassNames.hidden),
...classNames,
@@ -130,13 +130,13 @@ function Calendar({
className={cn(className)}
{...props}
/>
)
);
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === "left") {
return (
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
)
);
}
if (orientation === "right") {
@@ -145,12 +145,12 @@ function Calendar({
className={cn("size-4", className)}
{...props}
/>
)
);
}
return (
<ChevronDownIcon className={cn("size-4", className)} {...props} />
)
);
},
DayButton: CalendarDayButton,
WeekNumber: ({ children, ...props }) => {
@@ -160,13 +160,13 @@ function Calendar({
{children}
</div>
</td>
)
);
},
...components,
}}
{...props}
/>
)
);
}
function CalendarDayButton({
@@ -175,12 +175,12 @@ function CalendarDayButton({
modifiers,
...props
}: React.ComponentProps<typeof DayButton>) {
const defaultClassNames = getDefaultClassNames()
const defaultClassNames = getDefaultClassNames();
const ref = React.useRef<HTMLButtonElement>(null)
const ref = React.useRef<HTMLButtonElement>(null);
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus()
}, [modifiers.focused])
if (modifiers.focused) ref.current?.focus();
}, [modifiers.focused]);
return (
<Button
@@ -200,11 +200,11 @@ function CalendarDayButton({
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
className,
)}
{...props}
/>
)
);
}
export { Calendar, CalendarDayButton }
export { Calendar, CalendarDayButton };

View File

@@ -1,6 +1,6 @@
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,
@@ -10,12 +10,12 @@ const Card = React.forwardRef<
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className
className,
)}
{...props}
/>
))
Card.displayName = "Card"
));
Card.displayName = "Card";
const CardHeader = React.forwardRef<
HTMLDivElement,
@@ -26,8 +26,8 @@ const CardHeader = React.forwardRef<
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
));
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<
HTMLDivElement,
@@ -38,8 +38,8 @@ const CardTitle = React.forwardRef<
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
));
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef<
HTMLDivElement,
@@ -50,16 +50,16 @@ const CardDescription = React.forwardRef<
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
));
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
));
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef<
HTMLDivElement,
@@ -70,7 +70,14 @@ const CardFooter = React.forwardRef<
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
));
CardFooter.displayName = "CardFooter";
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardDescription,
CardContent,
};

View File

@@ -1,45 +1,45 @@
"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"
} 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 />")
throw new Error("useCarousel must be used within a <Carousel />");
}
return context
return context;
}
const Carousel = React.forwardRef<
@@ -56,69 +56,69 @@ const Carousel = React.forwardRef<
children,
...props
},
ref
ref,
) => {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === "horizontal" ? "x" : "y",
},
plugins
)
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
const [canScrollNext, setCanScrollNext] = React.useState(false)
plugins,
);
const [canScrollPrev, setCanScrollPrev] = React.useState(false);
const [canScrollNext, setCanScrollNext] = React.useState(false);
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) {
return
return;
}
setCanScrollPrev(api.canScrollPrev())
setCanScrollNext(api.canScrollNext())
}, [])
setCanScrollPrev(api.canScrollPrev());
setCanScrollNext(api.canScrollNext());
}, []);
const scrollPrev = React.useCallback(() => {
api?.scrollPrev()
}, [api])
api?.scrollPrev();
}, [api]);
const scrollNext = React.useCallback(() => {
api?.scrollNext()
}, [api])
api?.scrollNext();
}, [api]);
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowLeft") {
event.preventDefault()
scrollPrev()
event.preventDefault();
scrollPrev();
} else if (event.key === "ArrowRight") {
event.preventDefault()
scrollNext()
event.preventDefault();
scrollNext();
}
},
[scrollPrev, scrollNext]
)
[scrollPrev, scrollNext],
);
React.useEffect(() => {
if (!api || !setApi) {
return
return;
}
setApi(api)
}, [api, setApi])
setApi(api);
}, [api, setApi]);
React.useEffect(() => {
if (!api) {
return
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])
api?.off("select", onSelect);
};
}, [api, onSelect]);
return (
<CarouselContext.Provider
@@ -145,16 +145,16 @@ const Carousel = React.forwardRef<
{children}
</div>
</CarouselContext.Provider>
)
}
)
Carousel.displayName = "Carousel"
);
},
);
Carousel.displayName = "Carousel";
const CarouselContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { carouselRef, orientation } = useCarousel()
const { carouselRef, orientation } = useCarousel();
return (
<div ref={carouselRef} className="overflow-hidden">
@@ -163,20 +163,20 @@ const CarouselContent = React.forwardRef<
className={cn(
"flex",
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
className
className,
)}
{...props}
/>
</div>
)
})
CarouselContent.displayName = "CarouselContent"
);
});
CarouselContent.displayName = "CarouselContent";
const CarouselItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { orientation } = useCarousel()
const { orientation } = useCarousel();
return (
<div
@@ -186,19 +186,19 @@ const CarouselItem = React.forwardRef<
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-4" : "pt-4",
className
className,
)}
{...props}
/>
)
})
CarouselItem.displayName = "CarouselItem"
);
});
CarouselItem.displayName = "CarouselItem";
const CarouselPrevious = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
const { orientation, scrollPrev, canScrollPrev } = useCarousel();
return (
<Button
@@ -210,7 +210,7 @@ const CarouselPrevious = React.forwardRef<
orientation === "horizontal"
? "-left-12 top-1/2 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className
className,
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
@@ -219,15 +219,15 @@ const CarouselPrevious = React.forwardRef<
<ArrowLeft className="h-4 w-4" />
<span className="sr-only">Previous slide</span>
</Button>
)
})
CarouselPrevious.displayName = "CarouselPrevious"
);
});
CarouselPrevious.displayName = "CarouselPrevious";
const CarouselNext = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollNext, canScrollNext } = useCarousel()
const { orientation, scrollNext, canScrollNext } = useCarousel();
return (
<Button
@@ -239,7 +239,7 @@ const CarouselNext = React.forwardRef<
orientation === "horizontal"
? "-right-12 top-1/2 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className
className,
)}
disabled={!canScrollNext}
onClick={scrollNext}
@@ -248,9 +248,9 @@ const CarouselNext = React.forwardRef<
<ArrowRight className="h-4 w-4" />
<span className="sr-only">Next slide</span>
</Button>
)
})
CarouselNext.displayName = "CarouselNext"
);
});
CarouselNext.displayName = "CarouselNext";
export {
type CarouselApi,
@@ -259,4 +259,4 @@ export {
CarouselItem,
CarouselPrevious,
CarouselNext,
}
};

View File

@@ -1,10 +1,10 @@
"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>,
@@ -14,7 +14,7 @@ const Checkbox = React.forwardRef<
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
className,
)}
{...props}
>
@@ -24,7 +24,7 @@ const Checkbox = React.forwardRef<
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
))
Checkbox.displayName = CheckboxPrimitive.Root.displayName
));
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,17 +1,17 @@
"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"
} from "@/components/ui/dialog";
function Command({
className,
@@ -22,11 +22,11 @@ function Command({
data-slot="command"
className={cn(
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
className
className,
)}
{...props}
/>
)
);
}
function CommandDialog({
@@ -37,10 +37,10 @@ function CommandDialog({
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}>
@@ -57,7 +57,7 @@ function CommandDialog({
</Command>
</DialogContent>
</Dialog>
)
);
}
function CommandInput({
@@ -74,12 +74,12 @@ function CommandInput({
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
className,
)}
{...props}
/>
</div>
)
);
}
function CommandList({
@@ -91,11 +91,11 @@ function CommandList({
data-slot="command-list"
className={cn(
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
className
className,
)}
{...props}
/>
)
);
}
function CommandEmpty({
@@ -107,7 +107,7 @@ function CommandEmpty({
className="py-6 text-center text-sm"
{...props}
/>
)
);
}
function CommandGroup({
@@ -119,11 +119,11 @@ function CommandGroup({
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
className,
)}
{...props}
/>
)
);
}
function CommandSeparator({
@@ -136,7 +136,7 @@ function CommandSeparator({
className={cn("bg-border -mx-1 h-px", className)}
{...props}
/>
)
);
}
function CommandItem({
@@ -148,11 +148,11 @@ function CommandItem({
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
className,
)}
{...props}
/>
)
);
}
function CommandShortcut({
@@ -164,11 +164,11 @@ function CommandShortcut({
data-slot="command-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
className,
)}
{...props}
/>
)
);
}
export {
@@ -181,4 +181,4 @@ export {
CommandItem,
CommandShortcut,
CommandSeparator,
}
};

View File

@@ -1,27 +1,27 @@
"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
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<ContextMenuPrimitive.SubTrigger
@@ -29,15 +29,15 @@ const ContextMenuSubTrigger = React.forwardRef<
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
className,
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</ContextMenuPrimitive.SubTrigger>
))
ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName
));
ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName;
const ContextMenuSubContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubContent>,
@@ -47,12 +47,12 @@ const ContextMenuSubContent = React.forwardRef<
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
className,
)}
{...props}
/>
))
ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName
));
ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName;
const ContextMenuContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Content>,
@@ -63,18 +63,18 @@ const ContextMenuContent = React.forwardRef<
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
className,
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
))
ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName
));
ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName;
const ContextMenuItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {
inset?: boolean
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Item
@@ -82,12 +82,12 @@ const ContextMenuItem = React.forwardRef<
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
className,
)}
{...props}
/>
))
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName
));
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName;
const ContextMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.CheckboxItem>,
@@ -97,7 +97,7 @@ const ContextMenuCheckboxItem = React.forwardRef<
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
className,
)}
checked={checked}
{...props}
@@ -109,9 +109,9 @@ const ContextMenuCheckboxItem = React.forwardRef<
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
))
));
ContextMenuCheckboxItem.displayName =
ContextMenuPrimitive.CheckboxItem.displayName
ContextMenuPrimitive.CheckboxItem.displayName;
const ContextMenuRadioItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.RadioItem>,
@@ -121,7 +121,7 @@ const ContextMenuRadioItem = React.forwardRef<
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
className,
)}
{...props}
>
@@ -132,13 +132,13 @@ const ContextMenuRadioItem = React.forwardRef<
</span>
{children}
</ContextMenuPrimitive.RadioItem>
))
ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName
));
ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName;
const ContextMenuLabel = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Label> & {
inset?: boolean
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Label
@@ -146,12 +146,12 @@ const ContextMenuLabel = React.forwardRef<
className={cn(
"px-2 py-1.5 text-sm font-semibold text-foreground",
inset && "pl-8",
className
className,
)}
{...props}
/>
))
ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName
));
ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName;
const ContextMenuSeparator = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Separator>,
@@ -162,8 +162,8 @@ const ContextMenuSeparator = React.forwardRef<
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
))
ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName
));
ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName;
const ContextMenuShortcut = ({
className,
@@ -173,13 +173,13 @@ const ContextMenuShortcut = ({
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
className,
)}
{...props}
/>
)
}
ContextMenuShortcut.displayName = "ContextMenuShortcut"
);
};
ContextMenuShortcut.displayName = "ContextMenuShortcut";
export {
ContextMenu,
@@ -197,4 +197,4 @@ export {
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
}
};

View File

@@ -1,75 +1,82 @@
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"
} from "@/components/ui/popover";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { cn } from "@/lib/utils"
} 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 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))
})
end: endOfYear(new Date(year, 0, 1)),
});
}
return []
}, [year])
return [];
}, [year]);
React.useEffect(() => {
if (date) {
setMonth(date.getMonth())
setYear(date.getFullYear())
setMonth(date.getMonth());
setYear(date.getFullYear());
}
}, [date])
}, [date]);
const handleYearChange = (selectedYear: string) => {
const newYear = Number.parseInt(selectedYear, 10)
setYear(newYear)
const newYear = Number.parseInt(selectedYear, 10);
setYear(newYear);
if (date) {
const newDate = new Date(date)
newDate.setFullYear(newYear)
setDate(newDate)
}
const newDate = new Date(date);
newDate.setFullYear(newYear);
setDate(newDate);
}
};
const handleMonthChange = (selectedMonth: string) => {
const newMonth = Number.parseInt(selectedMonth, 10)
setMonth(newMonth)
const newMonth = Number.parseInt(selectedMonth, 10);
setMonth(newMonth);
if (date) {
const newDate = new Date(date)
newDate.setMonth(newMonth)
setDate(newDate)
const newDate = new Date(date);
newDate.setMonth(newMonth);
setDate(newDate);
} else {
setDate(new Date(year, newMonth, 1))
}
setDate(new Date(year, newMonth, 1));
}
};
return (
<Popover>
@@ -78,7 +85,7 @@ export function DatePicker({ date, setDate }: DatePickerProps) {
variant={"outline"}
className={cn(
"w-full justify-start text-left font-normal",
!date && "text-muted-foreground"
!date && "text-muted-foreground",
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
@@ -118,12 +125,12 @@ export function DatePicker({ date, setDate }: DatePickerProps) {
onSelect={setDate}
month={new Date(year, month)}
onMonthChange={(newMonth) => {
setMonth(newMonth.getMonth())
setYear(newMonth.getFullYear())
setMonth(newMonth.getMonth());
setYear(newMonth.getFullYear());
}}
initialFocus
/>
</PopoverContent>
</Popover>
)
);
}

View File

@@ -1,33 +1,33 @@
"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
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
}
function DialogTrigger({
...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
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}
function DialogOverlay({
@@ -39,11 +39,11 @@ function DialogOverlay({
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
className,
)}
{...props}
/>
)
);
}
function DialogContent({
@@ -52,7 +52,7 @@ function DialogContent({
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
showCloseButton?: boolean;
}) {
return (
<DialogPortal data-slot="dialog-portal">
@@ -61,7 +61,7 @@ function DialogContent({
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
className,
)}
{...props}
>
@@ -77,7 +77,7 @@ function DialogContent({
)}
</DialogPrimitive.Content>
</DialogPortal>
)
);
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
@@ -87,7 +87,7 @@ function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
);
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
@@ -96,11 +96,11 @@ function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
className,
)}
{...props}
/>
)
);
}
function DialogTitle({
@@ -113,7 +113,7 @@ function DialogTitle({
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
);
}
function DialogDescription({
@@ -126,7 +126,7 @@ function DialogDescription({
className={cn("text-start text-muted-foreground text-sm", className)}
{...props}
/>
)
);
}
export {
@@ -140,4 +140,4 @@ export {
DialogPortal,
DialogTitle,
DialogTrigger,
}
};

View File

@@ -1,9 +1,9 @@
"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,
@@ -13,14 +13,14 @@ const Drawer = ({
shouldScaleBackground={shouldScaleBackground}
{...props}
/>
)
Drawer.displayName = "Drawer"
);
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>,
@@ -31,8 +31,8 @@ const DrawerOverlay = React.forwardRef<
className={cn("fixed inset-0 z-50 bg-black/80", className)}
{...props}
/>
))
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName
));
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName;
const DrawerContent = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Content>,
@@ -44,7 +44,7 @@ const DrawerContent = React.forwardRef<
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
className,
)}
{...props}
>
@@ -52,8 +52,8 @@ const DrawerContent = React.forwardRef<
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
))
DrawerContent.displayName = "DrawerContent"
));
DrawerContent.displayName = "DrawerContent";
const DrawerHeader = ({
className,
@@ -63,8 +63,8 @@ const DrawerHeader = ({
className={cn("grid gap-1.5 p-4 text-center sm:text-left", className)}
{...props}
/>
)
DrawerHeader.displayName = "DrawerHeader"
);
DrawerHeader.displayName = "DrawerHeader";
const DrawerFooter = ({
className,
@@ -74,8 +74,8 @@ const DrawerFooter = ({
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
DrawerFooter.displayName = "DrawerFooter"
);
DrawerFooter.displayName = "DrawerFooter";
const DrawerTitle = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Title>,
@@ -85,12 +85,12 @@ const DrawerTitle = React.forwardRef<
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
className,
)}
{...props}
/>
))
DrawerTitle.displayName = DrawerPrimitive.Title.displayName
));
DrawerTitle.displayName = DrawerPrimitive.Title.displayName;
const DrawerDescription = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Description>,
@@ -101,8 +101,8 @@ const DrawerDescription = React.forwardRef<
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DrawerDescription.displayName = DrawerPrimitive.Description.displayName
));
DrawerDescription.displayName = DrawerPrimitive.Description.displayName;
export {
Drawer,
@@ -115,4 +115,4 @@ export {
DrawerFooter,
DrawerTitle,
DrawerDescription,
}
};

View File

@@ -1,27 +1,27 @@
"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
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
@@ -29,16 +29,16 @@ const DropdownMenuSubTrigger = React.forwardRef<
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
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>,
@@ -48,13 +48,13 @@ const DropdownMenuSubContent = React.forwardRef<
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
className,
)}
{...props}
/>
))
));
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName
DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
@@ -67,18 +67,18 @@ const DropdownMenuContent = React.forwardRef<
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
className,
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
));
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
@@ -86,12 +86,12 @@ const DropdownMenuItem = React.forwardRef<
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
className,
)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
));
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
@@ -101,7 +101,7 @@ const DropdownMenuCheckboxItem = React.forwardRef<
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
className,
)}
checked={checked}
{...props}
@@ -113,9 +113,9 @@ const DropdownMenuCheckboxItem = React.forwardRef<
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
))
));
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName
DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
@@ -125,7 +125,7 @@ const DropdownMenuRadioItem = React.forwardRef<
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
className,
)}
{...props}
>
@@ -136,13 +136,13 @@ const DropdownMenuRadioItem = React.forwardRef<
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
));
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
@@ -150,12 +150,12 @@ const DropdownMenuLabel = React.forwardRef<
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
className,
)}
{...props}
/>
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
));
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
@@ -166,8 +166,8 @@ const DropdownMenuSeparator = React.forwardRef<
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
));
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
const DropdownMenuShortcut = ({
className,
@@ -178,9 +178,9 @@ const DropdownMenuShortcut = ({
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
)
}
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
);
};
DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
export {
DropdownMenu,
@@ -198,4 +198,4 @@ export {
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
}
};

View File

@@ -1,25 +1,31 @@
'use client';
"use client";
import * as SliderPrimitive from '@radix-ui/react-slider';
import * as React from 'react';
import * as SliderPrimitive from "@radix-ui/react-slider";
import * as React from "react";
import { cn } from '@/lib/utils';
import { cn } from "@/lib/utils";
interface DualRangeSliderProps extends React.ComponentProps<typeof SliderPrimitive.Root> {
labelPosition?: 'top' | 'bottom';
interface DualRangeSliderProps
extends React.ComponentProps<typeof SliderPrimitive.Root> {
labelPosition?: "top" | "bottom";
label?: (value: number | undefined) => React.ReactNode;
}
const DualRangeSlider = React.forwardRef<
React.ElementRef<typeof SliderPrimitive.Root>,
DualRangeSliderProps
>(({ className, label, labelPosition = 'top', ...props }, ref) => {
const initialValue = Array.isArray(props.value) ? props.value : [props.min, props.max];
>(({ className, label, labelPosition = "top", ...props }, ref) => {
const initialValue = Array.isArray(props.value)
? props.value
: [props.min, props.max];
return (
<SliderPrimitive.Root
ref={ref}
className={cn('relative flex w-full touch-none select-none items-center', className)}
className={cn(
"relative flex w-full touch-none select-none items-center",
className,
)}
{...props}
>
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
@@ -31,9 +37,9 @@ const DualRangeSlider = React.forwardRef<
{label && (
<span
className={cn(
'absolute flex w-full justify-center',
labelPosition === 'top' && '-top-7',
labelPosition === 'bottom' && 'top-4',
"absolute flex w-full justify-center",
labelPosition === "top" && "-top-7",
labelPosition === "bottom" && "top-4",
)}
>
{label(value)}
@@ -45,6 +51,6 @@ const DualRangeSlider = React.forwardRef<
</SliderPrimitive.Root>
);
});
DualRangeSlider.displayName = 'DualRangeSlider';
DualRangeSlider.displayName = "DualRangeSlider";
export { DualRangeSlider };

View File

@@ -1,16 +1,22 @@
import * as React from 'react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';
import * as React from "react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> { }
const FloatingInput = React.forwardRef<HTMLInputElement, InputProps>(
({ className, ...props }, ref) => {
return <Input placeholder=" " className={cn('peer', className)} ref={ref} {...props} />;
},
const FloatingInput = React.forwardRef<
HTMLInputElement,
React.InputHTMLAttributes<HTMLInputElement>
>(({ className, ...props }, ref) => {
return (
<Input
placeholder=" "
className={cn("peer", className)}
ref={ref}
{...props}
/>
);
FloatingInput.displayName = 'FloatingInput';
});
FloatingInput.displayName = "FloatingInput";
const FloatingLabel = React.forwardRef<
React.ElementRef<typeof Label>,
@@ -19,7 +25,7 @@ const FloatingLabel = React.forwardRef<
return (
<Label
className={cn(
'peer-focus:secondary peer-focus:dark:secondary absolute start-2 top-2 z-10 origin-[0] -translate-y-4 scale-75 transform bg-background px-2 text-sm text-gray-500 duration-300 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-2 peer-focus:-translate-y-4 peer-focus:scale-75 peer-focus:px-2 dark:bg-background rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4 cursor-text',
"peer-focus:secondary peer-focus:dark:secondary absolute start-2 top-2 z-10 origin-[0] -translate-y-4 scale-75 transform bg-background px-2 text-sm text-gray-500 duration-300 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-2 peer-focus:-translate-y-4 peer-focus:scale-75 peer-focus:px-2 dark:bg-background rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4 cursor-text",
className,
)}
ref={ref}
@@ -27,9 +33,11 @@ const FloatingLabel = React.forwardRef<
/>
);
});
FloatingLabel.displayName = 'FloatingLabel';
FloatingLabel.displayName = "FloatingLabel";
type FloatingLabelInputProps = InputProps & { label?: string };
type FloatingLabelInputProps = React.InputHTMLAttributes<HTMLInputElement> & {
label?: string;
};
const FloatingLabelInput = React.forwardRef<
React.ElementRef<typeof FloatingInput>,
@@ -42,6 +50,6 @@ const FloatingLabelInput = React.forwardRef<
</div>
);
});
FloatingLabelInput.displayName = 'FloatingLabelInput';
FloatingLabelInput.displayName = "FloatingLabelInput";
export { FloatingInput, FloatingLabel, FloatingLabelInput };

View File

@@ -1,7 +1,7 @@
"use client"
"use client";
import * as React from "react"
import { Label as LabelPrimitive, Slot as SlotPrimitive } from "radix-ui"
import * as React from "react";
import { Label as LabelPrimitive, Slot as SlotPrimitive } from "radix-ui";
import {
Controller,
@@ -10,27 +10,27 @@ import {
type ControllerProps,
type FieldPath,
type FieldValues,
} from "react-hook-form"
} from "react-hook-form";
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
import { cn } from "@/lib/utils";
import { Label } from "@/components/ui/label";
const Form = FormProvider
const Form = FormProvider;
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> = {
name: TName
}
name: TName;
};
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
{} as FormFieldContextValue,
);
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
@@ -38,21 +38,21 @@ const FormField = <
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
);
};
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
const fieldContext = React.useContext(FormFieldContext);
const itemContext = React.useContext(FormItemContext);
const { getFieldState, formState } = useFormContext();
const fieldState = getFieldState(fieldContext.name, formState)
const fieldState = getFieldState(fieldContext.name, formState);
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
throw new Error("useFormField should be used within <FormField>");
}
const { id } = itemContext
const { id } = itemContext;
return {
id,
@@ -61,36 +61,36 @@ const useFormField = () => {
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
};
};
type FormItemContextValue = {
id: string
}
id: string;
};
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
{} as FormItemContextValue,
);
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId()
const id = React.useId();
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
)
})
FormItem.displayName = "FormItem"
);
});
FormItem.displayName = "FormItem";
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField()
const { error, formItemId } = useFormField();
return (
<Label
@@ -99,15 +99,16 @@ const FormLabel = React.forwardRef<
htmlFor={formItemId}
{...props}
/>
)
})
FormLabel.displayName = "FormLabel"
);
});
FormLabel.displayName = "FormLabel";
const FormControl = React.forwardRef<
React.ElementRef<typeof SlotPrimitive.Slot>,
React.ComponentPropsWithoutRef<typeof SlotPrimitive.Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
const { error, formItemId, formDescriptionId, formMessageId } =
useFormField();
return (
<SlotPrimitive.Slot
@@ -121,15 +122,15 @@ const FormControl = React.forwardRef<
aria-invalid={!!error}
{...props}
/>
)
})
FormControl.displayName = "FormControl"
);
});
FormControl.displayName = "FormControl";
const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField()
const { formDescriptionId } = useFormField();
return (
<p
@@ -138,19 +139,19 @@ const FormDescription = React.forwardRef<
className={cn("text-[0.8rem] text-muted-foreground", className)}
{...props}
/>
)
})
FormDescription.displayName = "FormDescription"
);
});
FormDescription.displayName = "FormDescription";
const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message ?? "") : children
const { error, formMessageId } = useFormField();
const body = error ? String(error?.message ?? "") : children;
if (!body) {
return null
return null;
}
return (
@@ -162,9 +163,9 @@ const FormMessage = React.forwardRef<
>
{body}
</p>
)
})
FormMessage.displayName = "FormMessage"
);
});
FormMessage.displayName = "FormMessage";
export {
useFormField,
@@ -175,4 +176,4 @@ export {
FormDescription,
FormMessage,
FormField,
}
};

View File

@@ -1,13 +1,13 @@
"use client"
"use client";
import * as React from "react"
import { HoverCard as HoverCardPrimitive } from "radix-ui"
import * as React from "react";
import { HoverCard as HoverCardPrimitive } from "radix-ui";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const HoverCard = HoverCardPrimitive.Root
const HoverCard = HoverCardPrimitive.Root;
const HoverCardTrigger = HoverCardPrimitive.Trigger
const HoverCardTrigger = HoverCardPrimitive.Trigger;
const HoverCardContent = React.forwardRef<
React.ElementRef<typeof HoverCardPrimitive.Content>,
@@ -19,11 +19,11 @@ const HoverCardContent = React.forwardRef<
sideOffset={sideOffset}
className={cn(
"z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none 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-hover-card-content-transform-origin)",
className
className,
)}
{...props}
/>
))
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName
));
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName;
export { HoverCard, HoverCardTrigger, HoverCardContent }
export { HoverCard, HoverCardTrigger, HoverCardContent };

View File

@@ -1,10 +1,10 @@
"use client"
"use client";
import * as React from "react"
import { OTPInput, OTPInputContext } from "input-otp"
import { Minus } from "lucide-react"
import * as React from "react";
import { OTPInput, OTPInputContext } from "input-otp";
import { Minus } from "lucide-react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const InputOTP = React.forwardRef<
React.ElementRef<typeof OTPInput>,
@@ -14,28 +14,28 @@ const InputOTP = React.forwardRef<
ref={ref}
containerClassName={cn(
"flex items-center gap-2 has-disabled:opacity-50",
containerClassName
containerClassName,
)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
))
InputOTP.displayName = "InputOTP"
));
InputOTP.displayName = "InputOTP";
const InputOTPGroup = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div">
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex items-center", className)} {...props} />
))
InputOTPGroup.displayName = "InputOTPGroup"
));
InputOTPGroup.displayName = "InputOTPGroup";
const InputOTPSlot = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div"> & { index: number }
>(({ index, className, ...props }, ref) => {
const inputOTPContext = React.useContext(OTPInputContext)
const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index]
const inputOTPContext = React.useContext(OTPInputContext);
const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index];
return (
<div
@@ -43,7 +43,7 @@ const InputOTPSlot = React.forwardRef<
className={cn(
"relative flex h-9 w-9 items-center justify-center border-y border-r border-input text-sm shadow-sm transition-all first:rounded-l-md first:border-l last:rounded-r-md",
isActive && "z-10 ring-1 ring-ring",
className
className,
)}
{...props}
>
@@ -54,9 +54,9 @@ const InputOTPSlot = React.forwardRef<
</div>
)}
</div>
)
})
InputOTPSlot.displayName = "InputOTPSlot"
);
});
InputOTPSlot.displayName = "InputOTPSlot";
const InputOTPSeparator = React.forwardRef<
React.ElementRef<"div">,
@@ -65,7 +65,7 @@ const InputOTPSeparator = React.forwardRef<
<div ref={ref} role="separator" {...props}>
<Minus />
</div>
))
InputOTPSeparator.displayName = "InputOTPSeparator"
));
InputOTPSeparator.displayName = "InputOTPSeparator";
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };

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