init vite rewrite
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 31s
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 31s
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
FROM node:22.17.0-alpine
|
||||
|
||||
WORKDIR /var/www/html/
|
||||
|
||||
CMD npm install && npm run dev -- --host 0.0.0.0
|
||||
@@ -1,7 +0,0 @@
|
||||
FROM node:22-slim
|
||||
|
||||
WORKDIR /var/www/html
|
||||
|
||||
# Source is bind-mounted at runtime; install on start so package.json changes
|
||||
# are picked up without a rebuild, then run the Next.js dev server.
|
||||
CMD npm install --legacy-peer-deps && npm run dev -- -H 0.0.0.0
|
||||
@@ -0,0 +1,17 @@
|
||||
# NextAuth (v4)
|
||||
NEXTAUTH_SECRET="MLWncPe5b7688ghElVLu_rNSNE5Y5egy9an9vtpOO2g"
|
||||
NEXTAUTH_URL="http://localhost:3000"
|
||||
|
||||
# Portal API (Django backend, over the compose network)
|
||||
SARLINK_API_BASE_URL="http://backend:5000"
|
||||
|
||||
# ID / person verification
|
||||
PERSON_VERIFY_BASE_URL="http://10.0.1.235:6000"
|
||||
|
||||
# Omada (TP-Link) proxy
|
||||
OMADA_BASE_URL=""
|
||||
OMADA_SITE_ID=""
|
||||
OMADA_PROXY_API_KEY=""
|
||||
|
||||
# Invoice Ninja finance
|
||||
NINJA_API_KEY=""
|
||||
@@ -1,29 +0,0 @@
|
||||
# =============================================================================
|
||||
# NextAuth (next-auth v4)
|
||||
# =============================================================================
|
||||
NEXTAUTH_SECRET=""
|
||||
# Canonical site URL. Dev: http://localhost:3000
|
||||
NEXTAUTH_URL="http://localhost:3000"
|
||||
|
||||
# =============================================================================
|
||||
# Portal API (Django backend)
|
||||
# Server-side calls over the compose network. Dev: http://backend:5000
|
||||
# =============================================================================
|
||||
SARLINK_API_BASE_URL="http://backend:5000"
|
||||
|
||||
# =============================================================================
|
||||
# ID / person verification — {PERSON_VERIFY_BASE_URL}/api/person/{id_card}
|
||||
# =============================================================================
|
||||
PERSON_VERIFY_BASE_URL=""
|
||||
|
||||
# =============================================================================
|
||||
# Omada (TP-Link) proxy — device access control
|
||||
# =============================================================================
|
||||
OMADA_BASE_URL=""
|
||||
OMADA_SITE_ID=""
|
||||
OMADA_PROXY_API_KEY=""
|
||||
|
||||
# =============================================================================
|
||||
# Invoice Ninja — finance/clients integration
|
||||
# =============================================================================
|
||||
NINJA_API_KEY=""
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"extends": ["next/core-web-vitals", "next/typescript"],
|
||||
"rules": {
|
||||
"@typescript-eslint/no-explicit-any": "error"
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
name: Sync Gitea Mirror on Push
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
sync-mirror:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Trigger Gitea Mirror Sync
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Authorization: token ${{ secrets.SAR_GITEA_TOKEN }}" \
|
||||
-H "Accept: application/json" \
|
||||
-H "Content-Type: application/json" \
|
||||
https://git.shihaam.dev/api/v1/repos/${{ vars.SAR_GITEA_REPO_OWNER }}/${{ vars.SAR_GITEA_REPO_NAME }}/mirror-sync
|
||||
+19
-41
@@ -1,46 +1,24 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env
|
||||
.env.local
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
||||
|
||||
#sqlite
|
||||
*.db
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
npx commitlint --edit $1
|
||||
@@ -1 +0,0 @@
|
||||
npm run lint
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
Vendored
-3
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"typescript.tsdk": "node_modules/typescript/lib"
|
||||
}
|
||||
-241
@@ -1,241 +0,0 @@
|
||||
# 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))
|
||||
@@ -1,47 +1,32 @@
|
||||
This is a web portal for SAR Link customers.
|
||||
# Todos
|
||||
## Layout
|
||||
- [ ] Auto hide the welcome banner after 5 seconds
|
||||
# React + TypeScript + Vite
|
||||
|
||||
## User Menu
|
||||
### Devices
|
||||
- [x] Add mac vendor validation for adding devices
|
||||
- [x] Add all the filters for devices table (mobile responsive)
|
||||
- [x] Add cancel feature to selected devices floating button
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
### 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
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
|
||||
### Parental Control
|
||||
- [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
|
||||
## React Compiler
|
||||
|
||||
### Topups
|
||||
- [ ] add textarea in topup dialog for admin. if no detail given generate on backend otherwise take the text from text area
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
### Agreements
|
||||
- [x] Implement file upload for admin side
|
||||
- [ ] Add customer relavant documents in a grid view
|
||||
## Expanding the Oxlint configuration
|
||||
|
||||
## Admin Controls
|
||||
### Users
|
||||
- [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
|
||||
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
|
||||
|
||||
### User Devices
|
||||
- [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
|
||||
```json
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"options": {
|
||||
"typeAware": true
|
||||
},
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### User Payments
|
||||
- [x] Show user payments table
|
||||
- [x] Add relevant filters for user payments table
|
||||
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
|
||||
|
||||
@@ -1,209 +0,0 @@
|
||||
"use server";
|
||||
|
||||
import { redirect } from "next/navigation";
|
||||
import { z } from "zod";
|
||||
import { signUpFormSchema } from "@/lib/schemas";
|
||||
import {
|
||||
backendRegister,
|
||||
checkIdOrPhone,
|
||||
checkTempIdOrPhone,
|
||||
} from "@/queries/authentication";
|
||||
import { handleApiResponse, tryCatch } from "@/utils/tryCatch";
|
||||
|
||||
const formSchema = z.object({
|
||||
phoneNumber: z
|
||||
.string()
|
||||
.regex(/^[7|9][0-9]{2}-[0-9]{4}$/, "Please enter a valid phone number"),
|
||||
});
|
||||
|
||||
export type FilterUserResponse = {
|
||||
ok: boolean;
|
||||
verified: boolean;
|
||||
};
|
||||
export type FilterTempUserResponse = {
|
||||
ok: boolean;
|
||||
otp_verified: boolean;
|
||||
t_verified: boolean;
|
||||
};
|
||||
|
||||
export async function signin(_previousState: ActionState, formData: FormData) {
|
||||
const phoneNumber = formData.get("phoneNumber") as string;
|
||||
const result = formSchema.safeParse({ phoneNumber });
|
||||
console.log(phoneNumber);
|
||||
|
||||
if (!result.success) {
|
||||
return {
|
||||
message: result.error.errors[0].message, // Get the error message from Zod
|
||||
status: "error",
|
||||
};
|
||||
}
|
||||
|
||||
if (!phoneNumber) {
|
||||
return {
|
||||
message: "Please enter a phone number",
|
||||
status: "error",
|
||||
};
|
||||
}
|
||||
const FORMATTED_MOBILE_NUMBER: string = `${phoneNumber.split("-").join("")}`;
|
||||
console.log({ FORMATTED_MOBILE_NUMBER });
|
||||
|
||||
const user = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/filter/?mobile=${FORMATTED_MOBILE_NUMBER}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
},
|
||||
);
|
||||
const userData = (await user.json()) as FilterUserResponse;
|
||||
console.log({ userData });
|
||||
if (!userData.ok) {
|
||||
redirect(`/auth/signup?phone_number=${phoneNumber}`);
|
||||
}
|
||||
if (!userData.verified) {
|
||||
return {
|
||||
message:
|
||||
"Your account is on pending verification. Please wait for a response from admin or contact shihaam.",
|
||||
status: "error",
|
||||
};
|
||||
}
|
||||
|
||||
const sendOTPResponse = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/auth/mobile/`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
mobile: FORMATTED_MOBILE_NUMBER,
|
||||
}),
|
||||
},
|
||||
);
|
||||
const otpResponse = await sendOTPResponse.json();
|
||||
console.log("otpResponse", otpResponse);
|
||||
|
||||
redirect(`/auth/verify-otp?phone_number=${FORMATTED_MOBILE_NUMBER}`);
|
||||
}
|
||||
|
||||
export type ActionState = {
|
||||
status?: string;
|
||||
payload?: FormData;
|
||||
errors?: z.typeToFlattenedError<
|
||||
{
|
||||
id_card: string;
|
||||
phone_number: string;
|
||||
name: string;
|
||||
atoll_id: string;
|
||||
island_id: string;
|
||||
address: string;
|
||||
dob: Date;
|
||||
terms: string;
|
||||
policy: string;
|
||||
accNo: string;
|
||||
},
|
||||
string
|
||||
>;
|
||||
db_error?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export async function signup(_actionState: ActionState, formData: FormData) {
|
||||
const data = Object.fromEntries(formData.entries());
|
||||
const parsedData = signUpFormSchema.safeParse(data);
|
||||
// get phone number from /signup?phone_number=999-1231
|
||||
|
||||
console.log("DATA ON SERVER SIDE", data);
|
||||
|
||||
if (!parsedData.success) {
|
||||
return {
|
||||
message: "Invalid form data",
|
||||
payload: formData,
|
||||
errors: parsedData.error.flatten(),
|
||||
};
|
||||
}
|
||||
const age =
|
||||
new Date().getFullYear() - new Date(parsedData.data.dob).getFullYear();
|
||||
if (age < 18) {
|
||||
return {
|
||||
message: "You must be at least 18 years old to register.",
|
||||
payload: formData,
|
||||
db_error: "dob",
|
||||
};
|
||||
}
|
||||
|
||||
const idCardExists = await checkIdOrPhone({
|
||||
id_card: parsedData.data.id_card,
|
||||
});
|
||||
if (idCardExists.ok) {
|
||||
return {
|
||||
message: "ID card already exists.",
|
||||
payload: formData,
|
||||
db_error: "id_card",
|
||||
};
|
||||
}
|
||||
|
||||
const phoneNumberExists = await checkIdOrPhone({
|
||||
phone_number: parsedData.data.phone_number,
|
||||
});
|
||||
|
||||
const tempPhoneNumberExists = await checkTempIdOrPhone({
|
||||
phone_number: parsedData.data.phone_number,
|
||||
});
|
||||
if (phoneNumberExists.ok || tempPhoneNumberExists.ok) {
|
||||
return {
|
||||
message: "Phone number already exists.",
|
||||
payload: formData,
|
||||
db_error: "phone_number",
|
||||
};
|
||||
}
|
||||
|
||||
const [signupError, signupResponse] = await tryCatch(
|
||||
backendRegister({
|
||||
payload: {
|
||||
firstname: parsedData.data.name.split(" ")[0],
|
||||
lastname: parsedData.data.name.split(" ").slice(1).join(" "),
|
||||
username: parsedData.data.phone_number,
|
||||
address: parsedData.data.address,
|
||||
id_card: parsedData.data.id_card,
|
||||
dob: new Date(parsedData.data.dob).toISOString().split("T")[0],
|
||||
mobile: parsedData.data.phone_number,
|
||||
island: Number.parseInt(parsedData.data.island_id),
|
||||
atoll: Number.parseInt(parsedData.data.atoll_id),
|
||||
acc_no: parsedData.data.accNo,
|
||||
terms_accepted: parsedData.data.terms,
|
||||
policy_accepted: parsedData.data.policy,
|
||||
},
|
||||
}),
|
||||
);
|
||||
if (signupError) {
|
||||
return {
|
||||
message: signupError.message,
|
||||
payload: formData,
|
||||
db_error: "phone_number",
|
||||
};
|
||||
}
|
||||
console.log("SIGNUP RESPONSE", signupResponse);
|
||||
|
||||
redirect(
|
||||
`/auth/verify-otp-registration?phone_number=${encodeURIComponent(signupResponse.t_username)}`,
|
||||
);
|
||||
return { message: "User created successfully", error: "success" };
|
||||
}
|
||||
|
||||
export async function backendMobileLogin({ mobile }: { mobile: string }) {
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/auth/mobile/`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
mobile,
|
||||
}),
|
||||
},
|
||||
);
|
||||
return handleApiResponse<{ detail: string }>(response, "backendMobileLogin");
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
"use server";
|
||||
|
||||
type CreateClientProps = {
|
||||
group_settings_id: string;
|
||||
address1: string;
|
||||
city: string;
|
||||
state: string;
|
||||
postal_code: string;
|
||||
country_id: string;
|
||||
address2: string;
|
||||
contacts: Contact;
|
||||
};
|
||||
|
||||
type Contact = {
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
send_email: boolean;
|
||||
custom_value1: string;
|
||||
custom_value2: string;
|
||||
custom_value3: string;
|
||||
};
|
||||
export async function CreateClient({
|
||||
group_settings_id = "",
|
||||
address1 = "",
|
||||
city,
|
||||
state,
|
||||
postal_code = "",
|
||||
country_id = "462",
|
||||
address2,
|
||||
contacts,
|
||||
}: CreateClientProps) {
|
||||
const response = await fetch(
|
||||
"https://finance-staging.baraveli.dev/api/v1/clients",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-api-token": `${process.env.NINJA_API_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
group_settings_id,
|
||||
address1,
|
||||
city,
|
||||
state,
|
||||
postal_code,
|
||||
country_id,
|
||||
address2,
|
||||
contacts: [
|
||||
{
|
||||
first_name: contacts.first_name,
|
||||
last_name: contacts.last_name,
|
||||
email: contacts.email || "",
|
||||
phone: contacts.phone,
|
||||
send_email: contacts.send_email,
|
||||
custom_value1: contacts.custom_value1,
|
||||
custom_value2: contacts.custom_value2,
|
||||
custom_value3: contacts.custom_value3 || "",
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
);
|
||||
const data = await response.json();
|
||||
console.log(data.data.contacts);
|
||||
return data;
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import type { GroupProfile, MacAddress, OmadaResponse } from "@/lib/types";
|
||||
import { formatMacAddress } from "@/lib/utils";
|
||||
|
||||
async function fetchOmadaGroupProfiles(siteId: string): Promise<OmadaResponse> {
|
||||
if (!siteId) {
|
||||
throw new Error("siteId is a required parameter");
|
||||
}
|
||||
|
||||
const baseUrl: string = process.env.OMADA_BASE_URL || "";
|
||||
const url: string = `${baseUrl}/api/v2/sites/${siteId}/setting/profiles/groups`;
|
||||
|
||||
const headers: HeadersInit = {
|
||||
"X-API-key": process.env.OMADA_PROXY_API_KEY || "",
|
||||
};
|
||||
|
||||
try {
|
||||
const response: Response = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: headers,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const data: OmadaResponse = await response.json();
|
||||
if (data.errorCode !== 0) {
|
||||
throw new Error(`Error fetching group profiles: ${data.msg}`);
|
||||
}
|
||||
console.log({ data });
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error("Error fetching Omada group profiles:", error);
|
||||
throw error instanceof Error ? error : new Error("Unknown error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
export { fetchOmadaGroupProfiles };
|
||||
|
||||
export async function addDevicesToGroup({
|
||||
siteId,
|
||||
groupId,
|
||||
newDevices,
|
||||
}: {
|
||||
siteId?: string;
|
||||
groupId?: string;
|
||||
newDevices: MacAddress[];
|
||||
}) {
|
||||
if (!siteId || !groupId) {
|
||||
throw new Error("omadacId, siteId, and groupId are required parameters");
|
||||
}
|
||||
|
||||
try {
|
||||
// Fetch the existing group profiles
|
||||
const groupProfiles: OmadaResponse = await fetchOmadaGroupProfiles(siteId);
|
||||
// console.log(groupProfiles);
|
||||
// Find the group profile with the specified groupId
|
||||
const groupProfile: GroupProfile | undefined =
|
||||
groupProfiles.result.data.find((profile) => profile.groupId === groupId);
|
||||
|
||||
if (!groupProfile) {
|
||||
throw new Error(`Group with ID ${groupId} not found`);
|
||||
}
|
||||
|
||||
// Create a new array with the existing and new devices
|
||||
const updatedMacAddressList: MacAddress[] = [
|
||||
...(groupProfile.macAddressList || []),
|
||||
...newDevices,
|
||||
];
|
||||
// console.log({ updatedMacAddressList });
|
||||
// Prepare the request payload
|
||||
const requestBody = {
|
||||
name: groupProfile.name,
|
||||
type: groupProfile.type,
|
||||
resource: groupProfile.resource,
|
||||
ipList: groupProfile.ipList,
|
||||
ipv6List: groupProfile.ipv6List,
|
||||
macAddressList: updatedMacAddressList,
|
||||
portList: null,
|
||||
countryList: null,
|
||||
portType: null,
|
||||
portMaskList: null,
|
||||
domainNamePort: null,
|
||||
};
|
||||
|
||||
console.log(requestBody);
|
||||
const baseUrl = process.env.OMADA_BASE_URL || "";
|
||||
const url: string = `${baseUrl}/api/v2/sites/${siteId}/setting/profiles/groups/2/${groupId}`;
|
||||
|
||||
const headers: HeadersInit = {
|
||||
"X-API-key": process.env.OMADA_PROXY_API_KEY || "",
|
||||
};
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: "PATCH",
|
||||
headers: headers,
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
console.log(response.status);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error adding devices to group:", error);
|
||||
throw error instanceof Error ? error : new Error("Unknown error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
export async function blockDevice({
|
||||
macAddress,
|
||||
type,
|
||||
reason,
|
||||
blockedBy = "PARENT",
|
||||
}: {
|
||||
macAddress: string;
|
||||
type: "block" | "unblock";
|
||||
reason?: string;
|
||||
blockedBy?: "ADMIN" | "PARENT";
|
||||
}) {
|
||||
console.log("hello world asdasd");
|
||||
if (!macAddress) {
|
||||
throw new Error("macAddress is a required parameter");
|
||||
}
|
||||
|
||||
try {
|
||||
const baseUrl: string = process.env.OMADA_BASE_URL || "";
|
||||
const url: string = `${baseUrl}/api/v2/sites/${process.env.OMADA_SITE_ID}/cmd/clients/${formatMacAddress(macAddress)}/${type}`;
|
||||
console.log(url);
|
||||
const headers: HeadersInit = {
|
||||
"X-API-key": process.env.OMADA_PROXY_API_KEY || "",
|
||||
};
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: headers,
|
||||
});
|
||||
console.log("blocking...");
|
||||
console.log(response);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
// await prisma.device.update({
|
||||
// where: {
|
||||
// id: device?.id,
|
||||
// },
|
||||
// data: {
|
||||
// reasonForBlocking: type === "block" ? reason : "",
|
||||
// blocked: type === "block",
|
||||
// blockedBy: blockedBy,
|
||||
// },
|
||||
// });
|
||||
revalidatePath("/parental-control");
|
||||
} catch (error) {
|
||||
console.error("Error blocking device:", error);
|
||||
throw error instanceof Error ? error : new Error("Unknown error occurred");
|
||||
}
|
||||
}
|
||||
@@ -1,385 +0,0 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/app/auth";
|
||||
import type {
|
||||
ApiError,
|
||||
ApiResponse,
|
||||
NewPayment,
|
||||
Payment,
|
||||
Topup,
|
||||
} from "@/lib/backend-types";
|
||||
import type { TopupResponse } from "@/lib/types";
|
||||
import { handleApiResponse } from "@/utils/tryCatch";
|
||||
|
||||
type GenericGetResponseProps = {
|
||||
offset?: number;
|
||||
limit?: number;
|
||||
page?: number;
|
||||
[key: string]: string | number | undefined;
|
||||
};
|
||||
|
||||
export async function createPayment(data: NewPayment) {
|
||||
const session = await getServerSession(authOptions);
|
||||
console.log("data", data);
|
||||
const response = await fetch(
|
||||
`${
|
||||
process.env.SARLINK_API_BASE_URL // });
|
||||
}/api/billing/payment/`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
const errorData = (await response.json()) as ApiError;
|
||||
const errorMessage =
|
||||
errorData.message || errorData.detail || "An error occurred.";
|
||||
const error = new Error(errorMessage);
|
||||
(error as ApiError & { details?: ApiError }).details = errorData; // Attach the errorData to the error object
|
||||
throw error;
|
||||
}
|
||||
const payment = (await response.json()) as Payment;
|
||||
revalidatePath("/devices");
|
||||
return payment;
|
||||
}
|
||||
|
||||
export async function createTopup(data: { amount: number }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
},
|
||||
);
|
||||
return handleApiResponse<Topup>(response, "createTopup");
|
||||
}
|
||||
|
||||
export async function getPayment({ id }: { id: string }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/${id}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = (await response.json()) as ApiError;
|
||||
const errorMessage =
|
||||
errorData.message || errorData.detail || "An error occurred.";
|
||||
const error = new Error(errorMessage);
|
||||
(error as ApiError & { details?: ApiError }).details = errorData; // Attach the errorData to the error object
|
||||
throw error;
|
||||
}
|
||||
const data = (await response.json()) as Payment;
|
||||
return data;
|
||||
}
|
||||
|
||||
type GetPaymentProps = {
|
||||
[key: string]: string | number | undefined; // Allow additional properties for flexibility
|
||||
};
|
||||
|
||||
export async function getPayments(
|
||||
params: GetPaymentProps,
|
||||
allPayments = false,
|
||||
) {
|
||||
// Build query string from all defined params
|
||||
const query = Object.entries(params)
|
||||
.filter(([_, value]) => value !== undefined && value !== "")
|
||||
.map(
|
||||
([key, value]) =>
|
||||
`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`,
|
||||
)
|
||||
.join("&");
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/?${query}&all_payments=${allPayments}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
const errorData = (await response.json()) as ApiError;
|
||||
const errorMessage =
|
||||
errorData.message || errorData.detail || "An error occurred.";
|
||||
const error = new Error(errorMessage);
|
||||
(error as ApiError & { details?: ApiError }).details = errorData; // Attach the errorData to the error object
|
||||
throw error;
|
||||
}
|
||||
const data = (await response.json()) as ApiResponse<Payment>;
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function getTopups(
|
||||
params: GenericGetResponseProps,
|
||||
all_topups = false,
|
||||
) {
|
||||
// Build query string from all defined params
|
||||
const query = Object.entries(params)
|
||||
.filter(([_, value]) => value !== undefined && value !== "")
|
||||
.map(
|
||||
([key, value]) =>
|
||||
`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`,
|
||||
)
|
||||
.join("&");
|
||||
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/?${query}&all_topups=${all_topups}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
return handleApiResponse<ApiResponse<Topup>>(response, "getTopups");
|
||||
}
|
||||
|
||||
export async function getTopup({ id }: { id: string }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/${id}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return handleApiResponse<Topup>(response, "getTopup");
|
||||
}
|
||||
|
||||
export async function cancelTopup({ id }: { id: string }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/${id}/cancel/`,
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
return handleApiResponse<Topup>(response, "cancelTopup");
|
||||
}
|
||||
|
||||
export async function cancelPayment({ id }: { id: string }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/${id}/cancel/`,
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
return handleApiResponse<Payment>(response, "cancelPayment");
|
||||
}
|
||||
|
||||
type UpdatePayment = {
|
||||
id: string;
|
||||
method: "TRANSFER" | "WALLET";
|
||||
benefName?: string;
|
||||
accountNo?: string;
|
||||
absAmount?: string;
|
||||
time?: string;
|
||||
};
|
||||
export async function verifyPayment({ id, method }: UpdatePayment) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/${id}/verify/`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
method,
|
||||
}),
|
||||
},
|
||||
);
|
||||
revalidatePath("/payments/[paymentId]", "page");
|
||||
return handleApiResponse<Payment>(response, "updatePayment");
|
||||
}
|
||||
|
||||
export type VerifyDevicePaymentState = {
|
||||
payment?: Payment;
|
||||
message: string;
|
||||
success: boolean;
|
||||
fieldErrors: Record<string, string>;
|
||||
payload?: FormData;
|
||||
};
|
||||
|
||||
export async function verifyDevicePayment(
|
||||
_prevState: VerifyDevicePaymentState,
|
||||
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";
|
||||
|
||||
if (!paymentId) {
|
||||
return {
|
||||
message: "Payment ID is required",
|
||||
success: false,
|
||||
fieldErrors: { paymentId: "Payment ID is required" },
|
||||
};
|
||||
}
|
||||
|
||||
if (!method) {
|
||||
return {
|
||||
message: "Payment method is required",
|
||||
success: false,
|
||||
fieldErrors: { method: "Payment method is required" },
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/${paymentId}/verify/`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
method,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
const result = await handleApiResponse<Payment>(
|
||||
response,
|
||||
"verifyDevicePayment",
|
||||
);
|
||||
|
||||
revalidatePath("/payments/[paymentId]", "page");
|
||||
|
||||
return {
|
||||
message:
|
||||
method === "WALLET"
|
||||
? "Payment completed successfully using wallet!"
|
||||
: "Payment verification successful!",
|
||||
success: true,
|
||||
fieldErrors: {},
|
||||
payment: result,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
const fallback =
|
||||
"Unable to verify payment. Please try again or contact support.";
|
||||
if (error instanceof Error) {
|
||||
return {
|
||||
message: error.message || fallback,
|
||||
success: false,
|
||||
fieldErrors: {},
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
message: fallback,
|
||||
success: false,
|
||||
fieldErrors: {},
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type VerifyTopupPaymentState = {
|
||||
transaction?: {
|
||||
sourceBank: string;
|
||||
trxDate: string;
|
||||
};
|
||||
message: string;
|
||||
success: boolean;
|
||||
fieldErrors: Record<string, string>;
|
||||
payload?: FormData;
|
||||
};
|
||||
export async function verifyTopupPayment(
|
||||
_prevState: VerifyTopupPaymentState,
|
||||
formData: FormData,
|
||||
): Promise<VerifyTopupPaymentState> {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
// Get the topup ID from the form data or use a hidden input
|
||||
const topupId = formData.get("topupId") as string;
|
||||
|
||||
if (!topupId) {
|
||||
return {
|
||||
message: "Topup ID is required",
|
||||
success: false,
|
||||
fieldErrors: { topupId: "Topup ID is required" },
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/${topupId}/verify/`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const result = await handleApiResponse<TopupResponse>(
|
||||
response,
|
||||
"verifyTopupPayment",
|
||||
);
|
||||
|
||||
revalidatePath("/top-ups/[topupId]", "page");
|
||||
|
||||
return {
|
||||
message: result.message || "Topup payment verified successfully",
|
||||
success: true,
|
||||
fieldErrors: {},
|
||||
transaction: result.transaction,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
const fallback =
|
||||
"Unable to verify payment. Please try again or contact support.";
|
||||
if (error instanceof Error) {
|
||||
return {
|
||||
message: error.message || fallback,
|
||||
success: false,
|
||||
fieldErrors: {},
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
message: fallback,
|
||||
success: false,
|
||||
fieldErrors: {},
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,302 +0,0 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/app/auth";
|
||||
import type { RejectUserFormState } from "@/components/user/user-reject-dialog";
|
||||
import type { ApiError } from "@/lib/backend-types";
|
||||
import type { User } from "@/lib/types/user";
|
||||
import { handleApiResponse } from "@/utils/tryCatch";
|
||||
|
||||
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() {
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/auth/profile/`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return handleApiResponse<User>(response, "getProfile");
|
||||
}
|
||||
|
||||
export async function rejectUser(
|
||||
_prevState: RejectUserFormState,
|
||||
formData: FormData,
|
||||
): Promise<RejectUserFormState> {
|
||||
const userId = formData.get("userId") as string;
|
||||
const rejection_details = formData.get("rejection_details") as string;
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/${userId}/reject/`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
body: JSON.stringify({ rejection_details: rejection_details }),
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(
|
||||
errorData.message || errorData.detail || "Failed to reject user",
|
||||
);
|
||||
}
|
||||
|
||||
// Handle 204 No Content response (successful deletion)
|
||||
if (response.status === 204) {
|
||||
revalidatePath("/users");
|
||||
redirect("/users");
|
||||
}
|
||||
|
||||
revalidatePath("/users");
|
||||
const error = await response.json();
|
||||
return {
|
||||
message:
|
||||
(error as ApiError).message ||
|
||||
(error as ApiError).detail ||
|
||||
"An unexpected error occurred.",
|
||||
fieldErrors: {},
|
||||
payload: formData,
|
||||
};
|
||||
}
|
||||
|
||||
export type UpdateUserFormState = {
|
||||
message: string;
|
||||
fieldErrors?: {
|
||||
id_card?: string[];
|
||||
first_name?: string[];
|
||||
last_name?: string[];
|
||||
dob?: string[];
|
||||
mobile?: string[];
|
||||
address?: string[];
|
||||
};
|
||||
payload?: FormData;
|
||||
};
|
||||
|
||||
export async function updateUser(
|
||||
_prevState: UpdateUserFormState,
|
||||
formData: FormData,
|
||||
): Promise<UpdateUserFormState> {
|
||||
const userId = formData.get("userId") as string;
|
||||
const data: Record<string, string | number | boolean> = {};
|
||||
|
||||
for (const [key, value] of formData.entries()) {
|
||||
if (value !== undefined && value !== "") {
|
||||
data[key] = typeof value === "number" ? value : String(value);
|
||||
}
|
||||
}
|
||||
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/${userId}/update/`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
},
|
||||
);
|
||||
|
||||
const json = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
const isFieldErrorObject =
|
||||
json &&
|
||||
typeof json === "object" &&
|
||||
!Array.isArray(json) &&
|
||||
Object.values(json).every(
|
||||
(val) => Array.isArray(val) && val.every((v) => typeof v === "string"),
|
||||
);
|
||||
|
||||
return {
|
||||
message:
|
||||
json.message ||
|
||||
json.detail ||
|
||||
(isFieldErrorObject
|
||||
? "Please correct the highlighted fields."
|
||||
: "An error occurred while updating the user."),
|
||||
fieldErrors: isFieldErrorObject ? json : json.field_errors || {},
|
||||
payload: formData,
|
||||
};
|
||||
}
|
||||
|
||||
// Successful update
|
||||
const updatedUser = json as User;
|
||||
revalidatePath("/users/[userId]/update", "page");
|
||||
revalidatePath("/users/[userId]/verify", "page");
|
||||
|
||||
return {
|
||||
...updatedUser,
|
||||
message: "User updated successfully",
|
||||
};
|
||||
}
|
||||
|
||||
export async function updateUserAgreement(
|
||||
_prevState: UpdateUserFormState,
|
||||
formData: FormData,
|
||||
): Promise<UpdateUserFormState> {
|
||||
const userId = formData.get("userId") as string;
|
||||
// Remove userId from formData before sending to API
|
||||
const apiFormData = new FormData();
|
||||
for (const [key, value] of formData.entries()) {
|
||||
if (key !== "userId") {
|
||||
apiFormData.append(key, value);
|
||||
}
|
||||
}
|
||||
console.log({ apiFormData });
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/${userId}/agreement/`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
body: apiFormData,
|
||||
},
|
||||
);
|
||||
console.log("response in update user agreement action", response);
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
return {
|
||||
message:
|
||||
errorData.message ||
|
||||
errorData.detail ||
|
||||
"An error occurred while updating the user agreement.",
|
||||
fieldErrors: errorData.field_errors || {},
|
||||
payload: formData,
|
||||
};
|
||||
}
|
||||
|
||||
const updatedUserAgreement = (await response.json()) as { agreement: string };
|
||||
revalidatePath("/users/[userId]/update", "page");
|
||||
revalidatePath("/users/[userId]/verify", "page");
|
||||
revalidatePath("/users/[userId]/agreement", "page");
|
||||
|
||||
return {
|
||||
...updatedUserAgreement,
|
||||
message: "User agreement updated successfully",
|
||||
};
|
||||
}
|
||||
|
||||
export type AddTopupFormState = {
|
||||
status: boolean;
|
||||
message: string;
|
||||
fieldErrors?: {
|
||||
amount?: string[];
|
||||
description?: string[];
|
||||
};
|
||||
payload?: FormData;
|
||||
};
|
||||
|
||||
export async function adminUserTopup(
|
||||
_prevState: AddTopupFormState,
|
||||
formData: FormData,
|
||||
): Promise<AddTopupFormState> {
|
||||
const user_id = formData.get("user_id") as string;
|
||||
const amount = formData.get("amount") as string;
|
||||
const description = formData.get("description") as string;
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!amount) {
|
||||
return {
|
||||
status: false,
|
||||
message: "Amount is required",
|
||||
fieldErrors: { amount: ["Amount is required"], description: [] },
|
||||
payload: formData,
|
||||
};
|
||||
}
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/admin-topup/`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `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,
|
||||
};
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
export default function AuthLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="bg-gray-100 dark:bg-black w-full h-screen flex items-center justify-center font-sans">
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import LoginForm from "@/components/auth/login-form";
|
||||
|
||||
export default async function LoginPage() {
|
||||
return <LoginForm />;
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import SignUpForm from "@/components/auth/signup-form";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export default async function SignupPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ phone_number: string }>;
|
||||
}) {
|
||||
const phone_number = (await searchParams).phone_number;
|
||||
console.log({ phone_number });
|
||||
if (!phone_number) {
|
||||
return redirect("/auth/login");
|
||||
}
|
||||
|
||||
return <SignUpForm />;
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import { authOptions } from "@/app/auth";
|
||||
import VerifyRegistrationOTPForm from "@/components/auth/verify-registration-otp-form";
|
||||
import ClientErrorMessage from "@/components/client-error-message";
|
||||
import { checkTempIdOrPhone } from "@/queries/authentication";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export default async function VerifyRegistrationOTP({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ phone_number: string }>;
|
||||
}) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (session) {
|
||||
// If the user is already logged in, redirect them to the home page
|
||||
return redirect("/");
|
||||
}
|
||||
const phone_number = (await searchParams).phone_number;
|
||||
if (!phone_number) {
|
||||
return redirect("/login");
|
||||
}
|
||||
console.log(
|
||||
"phone number from server page params (verify otp page)",
|
||||
phone_number,
|
||||
);
|
||||
const [error, response] = await tryCatch(
|
||||
checkTempIdOrPhone({ phone_number }),
|
||||
);
|
||||
if (error) {
|
||||
console.log("Error in checkIdOrPhone", error);
|
||||
return <ClientErrorMessage message={error.message} />;
|
||||
}
|
||||
if (response.otp_verified) redirect("/auth/signin");
|
||||
return <VerifyRegistrationOTPForm phone_number={phone_number} />;
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import VerifyOTPForm from "@/components/auth/verify-otp-form";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export default async function VerifyOTP({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ phone_number: string }>;
|
||||
}) {
|
||||
const phone_number = (await searchParams).phone_number;
|
||||
if (!phone_number) {
|
||||
return redirect("/login");
|
||||
}
|
||||
console.log(
|
||||
"phone number from server page params (verify otp page)",
|
||||
phone_number,
|
||||
);
|
||||
|
||||
return <VerifyOTPForm phone_number={phone_number} />;
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { getProfile } from "@/actions/user-actions";
|
||||
import { AgreementCard } from "@/components/agreement-card";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
|
||||
export default async function Agreements() {
|
||||
const [error, profile] = await tryCatch(getProfile());
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
|
||||
<h3 className="text-sarLinkOrange text-2xl">Agreements</h3>
|
||||
</div>
|
||||
<div className="grid grid-cols-1">
|
||||
{error ? (
|
||||
<div className="text-red-500">
|
||||
An error occurred while fetching agreements: {error.message}
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
{profile.agreement ? (
|
||||
<AgreementCard agreement={profile.agreement} />
|
||||
) : (
|
||||
<div className="text-gray-500">No agreement found.</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import FullPageLoader from "@/components/full-page-loader";
|
||||
import React from "react";
|
||||
|
||||
export default function Loading() {
|
||||
return <FullPageLoader />;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import DevicesForPayment from "@/components/devices-for-payment";
|
||||
import React from "react";
|
||||
|
||||
export default async function DevicesToPay() {
|
||||
return (
|
||||
<div>
|
||||
<DevicesForPayment />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
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";
|
||||
|
||||
export default async function DeviceDetails({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ deviceId: string }>;
|
||||
}) {
|
||||
const deviceId = (await params)?.deviceId;
|
||||
const [error, device] = await tryCatch(getDevice({ deviceId: deviceId }));
|
||||
if (error) {
|
||||
// Handle specific actions for certain errors, but reuse the error message
|
||||
if (error.message === "UNAUTHORIZED") {
|
||||
redirect("/auth/signin");
|
||||
} else {
|
||||
// For all other errors, display the error message directly
|
||||
return <ClientErrorMessage message={error.message} />;
|
||||
}
|
||||
}
|
||||
if (!device) return null;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between title-bg title-bg ring-2 ring-sarLinkOrange/50 rounded-lg p-4">
|
||||
<div className="flex flex-col justify-between items-start">
|
||||
<h3 className="text-2xl text-sarLinkOrange motion-preset-slide-down-md font-bold">
|
||||
{device?.name}
|
||||
</h3>
|
||||
<Badge
|
||||
className="motion-preset-slide-down-md motion-delay-75"
|
||||
variant={"secondary"}
|
||||
>
|
||||
{device?.mac}
|
||||
</Badge>
|
||||
<p className="text-muted-foreground text-sm mt-2 motion-preset-slide-down-md motion-delay-100">
|
||||
Device active until{" "}
|
||||
{new Date(device?.expiry_date || "").toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-col motion-preset-fade">
|
||||
{device?.expiry_date && new Date() < new Date(device.expiry_date) && (
|
||||
<p className="text-base font-semibold font-mono w-full text-center px-2 p-1 rounded-md bg-green-500/10 text-green-900 dark:text-green-400">
|
||||
ACTIVE
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
id="user-filters"
|
||||
className=" py-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||
>
|
||||
<Search />
|
||||
{/* <Filter
|
||||
options={sortfilterOptions}
|
||||
defaultOption="asc"
|
||||
queryParamKey="sortBy"
|
||||
/> */}
|
||||
</div>
|
||||
{/* <Suspense key={query} fallback={"loading...."}>
|
||||
<DevicesTable searchParams={searchParams} />
|
||||
</Suspense> */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
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";
|
||||
|
||||
export default async function Devices({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{
|
||||
query: string;
|
||||
page: number;
|
||||
}>;
|
||||
}) {
|
||||
const query = (await searchParams)?.query || "";
|
||||
const page = (await searchParams)?.page || 1;
|
||||
const session = await getServerSession(authOptions);
|
||||
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 Devices</h3>
|
||||
<AddDeviceDialogForm user_id={session?.user?.id} />
|
||||
</div>
|
||||
<div
|
||||
id="user-filters"
|
||||
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-endO"
|
||||
>
|
||||
{/* <DeviceFilter /> */}
|
||||
<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={query || page}
|
||||
fallback={
|
||||
<DevicesTableSkeleton
|
||||
headers={["Device Name", "Mac Address", "Vendor", "#"]}
|
||||
length={10}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<DevicesTable parentalControl={false} searchParams={searchParams} />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
"use client"; // Error boundaries must be Client Components
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { TriangleAlert } from "lucide-react";
|
||||
import { useEffect } from "react";
|
||||
export default function DashboardError({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
// Log the error to an error reporting service
|
||||
console.error(error);
|
||||
}, [error]);
|
||||
|
||||
return (
|
||||
<div className="error-bg dark:error-bg-dark rounded-lg p-4 h-full flex flex-col gap-4 items-center justify-center">
|
||||
<div className="bg-white dark:bg-transparent p-6 rounded flex flex-col items-center justify-center gap-4">
|
||||
<TriangleAlert color="red" />
|
||||
<h2 className="text-red-500 text-xl font-semibold">
|
||||
Something went wrong!
|
||||
</h2>
|
||||
<Button
|
||||
variant={"destructive"}
|
||||
size={"lg"}
|
||||
onClick={
|
||||
// Attempt to recover by trying to re-render the segment
|
||||
() => reset()
|
||||
}
|
||||
>
|
||||
Try again
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import { ApplicationLayout } from "@/components/auth/application-layout";
|
||||
import QueryProvider from "@/providers/query-provider";
|
||||
|
||||
export default function DashboardLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<ApplicationLayout>
|
||||
<QueryProvider>{children}</QueryProvider>
|
||||
</ApplicationLayout>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import { Suspense } from "react";
|
||||
import DevicesTableSkeleton from "@/components/device-table-skeleton";
|
||||
import { DevicesTable } from "@/components/devices-table";
|
||||
import DynamicFilter from "@/components/generic-filter";
|
||||
|
||||
export default async function ParentalControl({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{
|
||||
page: number;
|
||||
sortBy: string;
|
||||
status: string;
|
||||
}>;
|
||||
}) {
|
||||
const parentalControlFilters = {
|
||||
is_active: "true",
|
||||
has_a_pending_payment: "false",
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
|
||||
<h3 className="text-sarLinkOrange text-2xl">Parental Control</h3>
|
||||
</div>
|
||||
|
||||
<div
|
||||
id="user-filters"
|
||||
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||
>
|
||||
<DynamicFilter
|
||||
description="Filter devices by name, MAC address, or vendor."
|
||||
title="Device Filter"
|
||||
inputs={[
|
||||
{
|
||||
name: "name",
|
||||
label: "Device Name",
|
||||
type: "string",
|
||||
placeholder: "Enter device name",
|
||||
},
|
||||
{
|
||||
name: "mac",
|
||||
label: "MAC Address",
|
||||
type: "string",
|
||||
placeholder: "Enter MAC address",
|
||||
},
|
||||
{
|
||||
name: "vendor",
|
||||
label: "Vendor",
|
||||
type: "string",
|
||||
placeholder: "Enter vendor name",
|
||||
},
|
||||
]}
|
||||
/>{" "}
|
||||
</div>
|
||||
<Suspense
|
||||
key={(await searchParams).page}
|
||||
fallback={
|
||||
<DevicesTableSkeleton
|
||||
headers={["Device Name", "Mac Address", "Vendor", "#"]}
|
||||
length={10}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<DevicesTable
|
||||
parentalControl={true}
|
||||
searchParams={searchParams}
|
||||
additionalFilters={parentalControlFilters}
|
||||
/>
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { getPayment } from "@/actions/payment";
|
||||
import { getProfile } from "@/actions/user-actions";
|
||||
import CancelPaymentButton from "@/components/billing/cancel-payment-button";
|
||||
import ExpiryCountDown from "@/components/billing/expiry-time-countdown";
|
||||
import ClientErrorMessage from "@/components/client-error-message";
|
||||
import DevicesToPay from "@/components/devices-to-pay";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { TextShimmer } from "@/components/ui/text-shimmer";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
export default async function PaymentPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ paymentId: string }>;
|
||||
}) {
|
||||
const paymentId = (await params).paymentId;
|
||||
const [error, payment] = await tryCatch(getPayment({ id: paymentId }));
|
||||
if (error) {
|
||||
if (error.message === "Invalid token.") redirect("/auth/signin");
|
||||
return <ClientErrorMessage message={error.message} />;
|
||||
}
|
||||
const [userError, userProfile] = await tryCatch(getProfile());
|
||||
if (userError) {
|
||||
if (userError.message === "Invalid token.") redirect("/auth/signin");
|
||||
return <ClientErrorMessage message={userError.message} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-4 mb-4 mx-2">
|
||||
<h3 className="text-sarLinkOrange text-2xl">Payment</h3>
|
||||
<div className="flex flex-col gap-4 items-end w-full">
|
||||
{!payment.is_expired &&
|
||||
payment.paid &&
|
||||
payment.status !== "PENDING" && (
|
||||
<Button
|
||||
disabled
|
||||
className={cn(
|
||||
"rounded-md opacity-100! uppercase font-semibold",
|
||||
payment?.paid
|
||||
? "text-green-900 bg-green-500/20"
|
||||
: "text-inherit bg-yellow-400",
|
||||
)}
|
||||
>
|
||||
{payment.status}
|
||||
</Button>
|
||||
)}
|
||||
{payment.status === "PENDING" && !payment.is_expired && (
|
||||
<Button>
|
||||
<TextShimmer>Payment Pending</TextShimmer>{" "}
|
||||
</Button>
|
||||
)}
|
||||
{!payment.paid &&
|
||||
(payment.is_expired ? (
|
||||
<Button
|
||||
disabled
|
||||
className="rounded-md opacity-100! uppercase font-semibold text-red-500 bg-red-500/20"
|
||||
>
|
||||
Payment Expired
|
||||
</Button>
|
||||
) : payment.status === "PENDING" ? (
|
||||
<CancelPaymentButton paymentId={paymentId} />
|
||||
) : payment.status === "CANCELLED" ? (
|
||||
<Button disabled>Payment Cancelled</Button>
|
||||
) : (
|
||||
""
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{!payment.paid && (
|
||||
<ExpiryCountDown expiryLabel="Payment" expiresAt={payment.expires_at} />
|
||||
)}
|
||||
<div
|
||||
id="user-device-payments"
|
||||
className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||
>
|
||||
<DevicesToPay
|
||||
disabled={payment.paid || payment.is_expired}
|
||||
user={userProfile || undefined}
|
||||
payment={payment || undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
import { Suspense } from "react";
|
||||
import DevicesTableSkeleton from "@/components/device-table-skeleton";
|
||||
import DynamicFilter from "@/components/generic-filter";
|
||||
import { PaymentsTable } from "@/components/payments-table";
|
||||
|
||||
export default async function Payments({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{
|
||||
query: string;
|
||||
page: number;
|
||||
}>;
|
||||
}) {
|
||||
const query = (await searchParams)?.query || "";
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-3 mb-4">
|
||||
<h3 className="text-sarLinkOrange text-2xl">My Subscriptions</h3>
|
||||
</div>
|
||||
<div
|
||||
id="user-filters"
|
||||
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||
>
|
||||
<DynamicFilter
|
||||
inputs={[
|
||||
{
|
||||
label: "Payment",
|
||||
name: "paid",
|
||||
type: "radio-group",
|
||||
options: [
|
||||
{
|
||||
label: "All",
|
||||
value: "",
|
||||
},
|
||||
{
|
||||
label: "Paid",
|
||||
value: "true",
|
||||
},
|
||||
{
|
||||
label: "Unpaid",
|
||||
value: "false",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Payment Method",
|
||||
name: "method",
|
||||
type: "radio-group",
|
||||
options: [
|
||||
{
|
||||
label: "All",
|
||||
value: "",
|
||||
},
|
||||
{
|
||||
label: "Transfer",
|
||||
value: "TRANSFER",
|
||||
},
|
||||
{
|
||||
label: "Wallet",
|
||||
value: "WALLET",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Number of months",
|
||||
name: "number_of_months",
|
||||
type: "dual-range-slider",
|
||||
min: 1,
|
||||
max: 12,
|
||||
step: 1,
|
||||
},
|
||||
]}
|
||||
/>{" "}
|
||||
</div>
|
||||
<Suspense
|
||||
key={query}
|
||||
fallback={
|
||||
<DevicesTableSkeleton
|
||||
headers={["Details", "Duration", "Status", "Amount"]}
|
||||
length={10}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<PaymentsTable searchParams={searchParams} />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import PriceCalculator from "@/components/price-calculator";
|
||||
import React from "react";
|
||||
|
||||
export default function Pricing() {
|
||||
return <PriceCalculator />;
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/app/auth";
|
||||
import ClientErrorMessage from "@/components/client-error-message";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { getProfileById } from "@/queries/users";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
|
||||
export default async function Profile() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) return redirect("/auth/signin?callbackUrl=/profile");
|
||||
const [error, profile] = await tryCatch(getProfileById(session?.user.id));
|
||||
if (error) {
|
||||
if (error.message === "Invalid token.") redirect("/auth/signin");
|
||||
return <ClientErrorMessage message={error.message} />;
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between items-center font-bold border rounded-md border-dashed title-bg py-4 px-2 mb-4">
|
||||
<h3 className="text-sarLinkOrange text-2xl">Profile</h3>
|
||||
<div className="text-sarLinkOrange uppercase font-mono text-sm flex flex-col items-center rounded gap-2 py-2 px-4">
|
||||
<span>Profile Status</span>
|
||||
{verifiedStatus(profile?.verified ?? false)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-md border bg-muted/30 p-4">
|
||||
<dl className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-x-6 gap-y-4 max-w-4xl">
|
||||
<ReadOnlyField
|
||||
label="Full Name"
|
||||
value={`${profile?.first_name} ${profile?.last_name}`}
|
||||
/>
|
||||
<ReadOnlyField label="ID Card" value={profile?.id_card} />
|
||||
<ReadOnlyField
|
||||
label="Island"
|
||||
value={`${profile?.atoll?.name}. ${profile?.island?.name}`}
|
||||
/>
|
||||
<ReadOnlyField
|
||||
label="Date of Birth"
|
||||
value={
|
||||
profile?.dob
|
||||
? new Date(profile.dob.toString()).toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<ReadOnlyField label="Address" value={profile?.address} />
|
||||
<ReadOnlyField label="Phone Number" value={profile?.mobile} />
|
||||
<ReadOnlyField label="Account Number" value={profile?.acc_no} />
|
||||
</dl>
|
||||
</div>
|
||||
{/* <Suspense key={query} fallback={"loading...."}>
|
||||
<TopupsTable searchParams={searchParams} />
|
||||
</Suspense> */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ReadOnlyField({
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
label: string;
|
||||
value?: string | null;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<dt className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
{label}
|
||||
</dt>
|
||||
<dd className="text-sm font-medium text-foreground break-words">
|
||||
{value?.trim() ? value : "—"}
|
||||
</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function verifiedStatus(status: boolean) {
|
||||
switch (status) {
|
||||
case true:
|
||||
return <Badge className="bg-green-500 text-white">Verified</Badge>;
|
||||
case false:
|
||||
return <Badge className="bg-red-500 text-white">Not Verified</Badge>;
|
||||
default:
|
||||
return <Badge className="bg-yellow-500 text-white">Unknown</Badge>;
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { getTopup } from "@/actions/payment";
|
||||
import CancelTopupButton from "@/components/billing/cancel-topup-button";
|
||||
import ExpiryCountDown from "@/components/billing/expiry-time-countdown";
|
||||
import ClientErrorMessage from "@/components/client-error-message";
|
||||
import TopupToPay from "@/components/topup-to-pay";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { TextShimmer } from "@/components/ui/text-shimmer";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
export default async function TopupPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ topupId: string }>;
|
||||
}) {
|
||||
const topupId = (await params).topupId;
|
||||
const [error, topup] = await tryCatch(getTopup({ id: topupId }));
|
||||
if (error) {
|
||||
if (error.message === "Invalid token.") redirect("/auth/signin");
|
||||
return <ClientErrorMessage message={error.message} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-4 mb-4 mx-2">
|
||||
<h3 className="text-sarLinkOrange text-2xl">Topup</h3>
|
||||
<div className="flex flex-col gap-4 items-end w-full">
|
||||
{!topup.is_expired && topup.paid && topup.status !== "PENDING" && (
|
||||
<Button
|
||||
disabled
|
||||
className={cn(
|
||||
"rounded-md opacity-100! uppercase font-semibold",
|
||||
topup?.paid
|
||||
? "text-green-900 bg-green-500/20"
|
||||
: "text-inherit bg-yellow-400",
|
||||
)}
|
||||
>
|
||||
{topup.status}
|
||||
</Button>
|
||||
)}
|
||||
{topup.status === "PENDING" && !topup.is_expired && (
|
||||
<Button>
|
||||
<TextShimmer>Payment Pending</TextShimmer>{" "}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{!topup.paid &&
|
||||
(topup.is_expired ? (
|
||||
<Button
|
||||
disabled
|
||||
className="rounded-md opacity-100! uppercase font-semibold text-red-500 bg-red-500/20"
|
||||
>
|
||||
Topup Expired
|
||||
</Button>
|
||||
) : topup.status === "PENDING" ? (
|
||||
<CancelTopupButton topupId={topupId} />
|
||||
) : topup.status === "CANCELLED" ? (
|
||||
<Button disabled>Topup Cancelled</Button>
|
||||
) : (
|
||||
""
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{!topup.paid && topup.status === "PENDING" && !topup.is_expired && (
|
||||
<ExpiryCountDown expiryLabel="Top up" expiresAt={topup.expires_at} />
|
||||
)}
|
||||
<div
|
||||
id="user-topup-details"
|
||||
className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||
>
|
||||
<TopupToPay
|
||||
disabled={
|
||||
topup.paid || topup.is_expired || topup.status === "CANCELLED"
|
||||
}
|
||||
topup={topup || undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
import { Suspense } from "react";
|
||||
import DevicesTableSkeleton from "@/components/device-table-skeleton";
|
||||
import DynamicFilter from "@/components/generic-filter";
|
||||
import { TopupsTable } from "@/components/topups-table";
|
||||
|
||||
export default async function Topups({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{
|
||||
query: string;
|
||||
page: number;
|
||||
sortBy: string;
|
||||
status: string;
|
||||
}>;
|
||||
}) {
|
||||
const query = (await searchParams)?.query || "";
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
|
||||
<h3 className="text-sarLinkOrange text-2xl">My Topups</h3>
|
||||
</div>
|
||||
<div
|
||||
id="topup-filters"
|
||||
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||
>
|
||||
<DynamicFilter
|
||||
inputs={[
|
||||
{
|
||||
label: "Status",
|
||||
name: "status",
|
||||
type: "radio-group",
|
||||
options: [
|
||||
{
|
||||
label: "All",
|
||||
value: "",
|
||||
},
|
||||
{
|
||||
label: "Pending",
|
||||
value: "PENDING",
|
||||
},
|
||||
{
|
||||
label: "Cancelled",
|
||||
value: "CANCELLED",
|
||||
},
|
||||
{
|
||||
label: "Paid",
|
||||
value: "PAID",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Topup Expiry",
|
||||
name: "is_expired",
|
||||
type: "radio-group",
|
||||
options: [
|
||||
{
|
||||
label: "All",
|
||||
value: "",
|
||||
},
|
||||
{
|
||||
label: "Expired",
|
||||
value: "true",
|
||||
},
|
||||
{
|
||||
label: "Not Expired",
|
||||
value: "false",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Topup Amount",
|
||||
name: "amount",
|
||||
type: "dual-range-slider",
|
||||
min: 0,
|
||||
max: 1000,
|
||||
step: 10,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<Suspense
|
||||
key={query}
|
||||
fallback={
|
||||
<DevicesTableSkeleton
|
||||
headers={["Details", "Status", "Amount"]}
|
||||
length={10}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<TopupsTable searchParams={searchParams} />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { Suspense } from "react";
|
||||
import { authOptions } from "@/app/auth";
|
||||
import { AdminDevicesTable } from "@/components/admin/admin-devices-table";
|
||||
import DynamicFilter from "@/components/generic-filter";
|
||||
|
||||
export default async function UserDevices({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{
|
||||
query: string;
|
||||
page: number;
|
||||
sortBy: string;
|
||||
status: string;
|
||||
}>;
|
||||
}) {
|
||||
const query = (await searchParams)?.query || "";
|
||||
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">
|
||||
<h3 className="text-sarLinkOrange text-2xl">User Devices</h3>
|
||||
</div>
|
||||
|
||||
<div
|
||||
id="user-filters"
|
||||
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||
>
|
||||
<DynamicFilter
|
||||
description="Filter devices by name, MAC address, or vendor."
|
||||
title="Device Filter"
|
||||
inputs={[
|
||||
{
|
||||
name: "name",
|
||||
label: "Device Name",
|
||||
type: "string",
|
||||
placeholder: "Enter device name",
|
||||
},
|
||||
{
|
||||
name: "mac",
|
||||
label: "MAC Address",
|
||||
type: "string",
|
||||
placeholder: "Enter device MAC address",
|
||||
},
|
||||
{
|
||||
name: "vendor",
|
||||
label: "Vendor",
|
||||
type: "string",
|
||||
placeholder: "Enter device vendor name",
|
||||
},
|
||||
{
|
||||
name: "user",
|
||||
label: "Device User",
|
||||
type: "string",
|
||||
placeholder: "User name or id card",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<Suspense key={query} fallback={"loading...."}>
|
||||
<AdminDevicesTable searchParams={searchParams} />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
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,
|
||||
}: {
|
||||
searchParams: Promise<{
|
||||
query: string;
|
||||
page: number;
|
||||
sortBy: string;
|
||||
status: string;
|
||||
}>;
|
||||
}) {
|
||||
const query = (await searchParams)?.query || "";
|
||||
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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,211 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { Suspense } from "react";
|
||||
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<{
|
||||
[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">
|
||||
<h3 className="text-sarLinkOrange text-2xl">Users</h3>
|
||||
</div>
|
||||
|
||||
<div
|
||||
id="user-table-filters"
|
||||
className=" pb-4 gap-4 flex items-center justify-start"
|
||||
>
|
||||
<DynamicFilter
|
||||
description="Filter users by id card, name, or house name and more."
|
||||
title="User Filter"
|
||||
inputs={[
|
||||
{
|
||||
name: "first_name",
|
||||
label: "User First Name",
|
||||
type: "string",
|
||||
placeholder: "Enter user first name",
|
||||
},
|
||||
{
|
||||
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",
|
||||
},
|
||||
{
|
||||
label: "Verified",
|
||||
value: "true",
|
||||
},
|
||||
{
|
||||
label: "Unverified",
|
||||
value: "false",
|
||||
},
|
||||
],
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<Suspense fallback={"loading...."}>
|
||||
<UsersTable searchParams={searchParams} />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
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 || "";
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
|
||||
<h3 className="text-sarLinkOrange text-2xl">Transaction History</h3>
|
||||
</div>
|
||||
<div
|
||||
id="wallet-filters"
|
||||
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||
>
|
||||
<DynamicFilter
|
||||
inputs={[
|
||||
{
|
||||
label: "Type",
|
||||
name: "transaction_type",
|
||||
type: "radio-group",
|
||||
options: [
|
||||
{
|
||||
label: "All",
|
||||
value: "",
|
||||
},
|
||||
{
|
||||
label: "Debit",
|
||||
value: "debit",
|
||||
},
|
||||
{
|
||||
label: "Credit",
|
||||
value: "credit",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Topup Amount",
|
||||
name: "amount",
|
||||
type: "dual-range-slider",
|
||||
min: 0,
|
||||
max: 1000,
|
||||
step: 10,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<Suspense
|
||||
key={query}
|
||||
fallback={
|
||||
<DevicesTableSkeleton
|
||||
headers={[
|
||||
"Description",
|
||||
"Amount",
|
||||
"Transaction Type",
|
||||
"View Details",
|
||||
"Created at",
|
||||
]}
|
||||
length={10}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<WalletTransactionsTable searchParams={searchParams} />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { authOptions } from "@/app/auth";
|
||||
import NextAuth from "next-auth";
|
||||
|
||||
const handler = NextAuth(authOptions);
|
||||
export { handler as GET, handler as POST };
|
||||
@@ -1,4 +0,0 @@
|
||||
export async function GET(request: Request) {
|
||||
console.log(request.url);
|
||||
return Response.json({ message: "Request received" });
|
||||
}
|
||||
-106
@@ -1,106 +0,0 @@
|
||||
import { logout } from "@/queries/authentication";
|
||||
import type { NextAuthOptions } from "next-auth";
|
||||
import type { JWT } from "next-auth/jwt";
|
||||
import CredentialsProvider from "next-auth/providers/credentials";
|
||||
|
||||
export const authOptions: NextAuthOptions = {
|
||||
pages: {
|
||||
signIn: "/auth/signin",
|
||||
},
|
||||
session: {
|
||||
strategy: "jwt",
|
||||
maxAge: 30 * 60, // 30 mins
|
||||
},
|
||||
events: {
|
||||
signOut({ token }) {
|
||||
const apitoken = token.apiToken;
|
||||
console.log("apitoken", apitoken);
|
||||
logout({ token: apitoken as string });
|
||||
},
|
||||
},
|
||||
providers: [
|
||||
CredentialsProvider({
|
||||
name: "Credentials",
|
||||
credentials: {
|
||||
pin: { label: "Pin", type: "text", placeholder: "000000" },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
const { pin } = credentials as {
|
||||
pin: string;
|
||||
};
|
||||
console.log("pin", pin);
|
||||
const res = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/callback/auth/`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
token: pin,
|
||||
}),
|
||||
},
|
||||
);
|
||||
console.log(res);
|
||||
console.log("status", res.status);
|
||||
|
||||
const data = await res.json();
|
||||
console.log({ data });
|
||||
switch (res.status) {
|
||||
case 200:
|
||||
return { ...data.user, apiToken: data.token, expiry: data.expiry };
|
||||
case 400:
|
||||
throw new Error(
|
||||
JSON.stringify({ message: data.token[0], status: res.status }),
|
||||
);
|
||||
case 429:
|
||||
throw new Error(
|
||||
JSON.stringify({ message: data.message, status: res.status }),
|
||||
);
|
||||
case 403:
|
||||
throw new Error(
|
||||
JSON.stringify({ message: data.error, status: res.status }),
|
||||
);
|
||||
default:
|
||||
throw new Error(
|
||||
JSON.stringify({
|
||||
message: "FATAL: Unexprted Error occured!",
|
||||
status: res.status,
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
redirect: async ({ url, baseUrl }) => {
|
||||
// Allows relative callback URLs
|
||||
if (url.startsWith("/")) return `${baseUrl}${url}`;
|
||||
return baseUrl;
|
||||
},
|
||||
session: async ({ session, token }) => {
|
||||
const sanitizedToken = Object.keys(token).reduce((p, c) => {
|
||||
// strip unnecessary properties
|
||||
if (c !== "iat" && c !== "exp" && c !== "jti" && c !== "apiToken") {
|
||||
Object.assign(p, { [c]: token[c] });
|
||||
}
|
||||
return p;
|
||||
}, {});
|
||||
// session.expires = token.expiry
|
||||
return {
|
||||
...session,
|
||||
user: sanitizedToken,
|
||||
apiToken: token.apiToken,
|
||||
// expires: token.expiry,
|
||||
};
|
||||
},
|
||||
jwt: ({ token, user }) => {
|
||||
if (typeof user !== "undefined") {
|
||||
// user has just signed in so the user object is populated
|
||||
return user as unknown as JWT;
|
||||
}
|
||||
return token;
|
||||
},
|
||||
},
|
||||
secret: process.env.NEXTAUTH_SECRET,
|
||||
};
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB |
Binary file not shown.
Binary file not shown.
-171
File diff suppressed because one or more lines are too long
@@ -1,58 +0,0 @@
|
||||
import { Provider } from "jotai";
|
||||
import { ThemeProvider } from "@/providers/theme-provider";
|
||||
|
||||
import type { Metadata } from "next";
|
||||
import { Barlow, Bokor } from "next/font/google";
|
||||
import NextTopLoader from "nextjs-toploader";
|
||||
import { Toaster } from "sonner";
|
||||
import "./globals.css";
|
||||
import { AuthProvider } from "@/providers/AuthProvider";
|
||||
import QueryProvider from "@/providers/query-provider";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "./auth";
|
||||
const barlow = Barlow({
|
||||
subsets: ["latin"],
|
||||
weight: ["100", "300", "400", "500", "600", "700", "800", "900"],
|
||||
variable: "--font-barlow",
|
||||
});
|
||||
|
||||
const bokor = Bokor({
|
||||
subsets: ["latin"],
|
||||
weight: ["400"],
|
||||
variable: "--font-bokor",
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "SAR Link Portal",
|
||||
description: "Sarlink Portal",
|
||||
};
|
||||
|
||||
export default async function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
const session = await getServerSession(authOptions);
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<body
|
||||
className={`${barlow.variable} ${bokor.variable} antialiased font-sans bg-gray-100 dark:bg-black`}
|
||||
>
|
||||
<AuthProvider session={session || undefined}>
|
||||
<Provider>
|
||||
<NextTopLoader color="#f49d1b" showSpinner={false} zIndex={9999} />
|
||||
<Toaster richColors />
|
||||
<ThemeProvider
|
||||
attribute="class"
|
||||
defaultTheme="system"
|
||||
enableSystem
|
||||
disableTransitionOnChange
|
||||
>
|
||||
<QueryProvider>{children}</QueryProvider>
|
||||
</ThemeProvider>
|
||||
</Provider>
|
||||
</AuthProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
Vendored
-34
@@ -1,34 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
// @ts-expect-error importing unused types are required here
|
||||
import NextAuth, { DefaultSession, Session, type User } from "next-auth";
|
||||
|
||||
/* eslint-enable @typescript-eslint/no-unused-vars */
|
||||
declare module "next-auth" {
|
||||
/**
|
||||
* Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
|
||||
*/
|
||||
|
||||
interface Session {
|
||||
apiToken?: string;
|
||||
name?: string | null;
|
||||
email?: string | null;
|
||||
image?: string | null;
|
||||
user?: User & {
|
||||
expiry?: string;
|
||||
id?: number;
|
||||
username?: string;
|
||||
user_permissions?: { id: number; name: string }[];
|
||||
id_card?: string;
|
||||
mobile?: string;
|
||||
wallet_balance?: number;
|
||||
first_name?: string;
|
||||
last_name?: string;
|
||||
last_login?: string;
|
||||
date_joined?: string;
|
||||
is_superuser?: boolean;
|
||||
is_admin?: boolean;
|
||||
agreement?: string;
|
||||
};
|
||||
expires: ISODateString;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export default async function Home() {
|
||||
return redirect("/devices");
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
{
|
||||
"$schema": "https://biomejs.dev/schemas/2.0.6/schema.json",
|
||||
"vcs": {
|
||||
"enabled": false,
|
||||
"clientKind": "git",
|
||||
"useIgnoreFile": false
|
||||
},
|
||||
"files": {
|
||||
"ignoreUnknown": false
|
||||
},
|
||||
"formatter": {
|
||||
"enabled": true,
|
||||
"indentStyle": "tab"
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true,
|
||||
"rules": {
|
||||
"suspicious": {
|
||||
"noImplicitAnyLet": "error"
|
||||
},
|
||||
"recommended": true
|
||||
}
|
||||
},
|
||||
"javascript": {
|
||||
"formatter": {
|
||||
"quoteStyle": "double"
|
||||
}
|
||||
},
|
||||
"assist": {
|
||||
"enabled": true,
|
||||
"actions": {
|
||||
"source": {
|
||||
"organizeImports": "on"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
export default {
|
||||
extends: ["@commitlint/config-conventional"],
|
||||
};
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": true,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "tailwind.config.ts",
|
||||
"css": "app/globals.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
"use client";
|
||||
import { Clipboard, ClipboardCheck } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "./ui/button";
|
||||
|
||||
export function AccountInfomation({
|
||||
accountNo,
|
||||
accName,
|
||||
}: {
|
||||
accountNo: string;
|
||||
accName: string;
|
||||
}) {
|
||||
const [accNo, setAccNo] = useState(false);
|
||||
return (
|
||||
<div className="justify-center items-center border my-4 flex flex-col gap-2 p-2 rounded-md">
|
||||
<h6 className="title-bg uppercase p-2 border rounded w-full font-semibold">
|
||||
Account Information
|
||||
</h6>
|
||||
<div className="border justify-center flex flex-col items-center bg-white/10 w-full p-2 rounded">
|
||||
<div className="text-sm font-semibold">Account Name</div>
|
||||
<span>{accName}</span>
|
||||
</div>
|
||||
<div className="border flex justify-between items-center gap-2 w-full p-2 rounded">
|
||||
<div className="flex flex-col items-center justify-center w-full">
|
||||
<p className="text-sm font-semibold">Account No</p>
|
||||
<span>{accountNo}</span>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setTimeout(() => {
|
||||
setAccNo(true);
|
||||
navigator.clipboard.writeText(accountNo);
|
||||
}, 2000);
|
||||
toast.success("Account number copied!");
|
||||
setAccNo((prev) => !prev);
|
||||
}}
|
||||
className="mt-2 w-full"
|
||||
variant={"secondary"}
|
||||
>
|
||||
{accNo ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<span>Copy Account Number</span>
|
||||
<Clipboard />
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<span>Copy Account Number</span>
|
||||
<ClipboardCheck color="green" />
|
||||
</div>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
"use client";
|
||||
import { deviceCartAtom } from "@/lib/atoms";
|
||||
import type { Device } from "@/lib/backend-types";
|
||||
import { useAtomValue, useSetAtom } from "jotai";
|
||||
import React from "react";
|
||||
|
||||
export default function AddDevicesToCartButton({ device }: { device: Device }) {
|
||||
const setDeviceCart = useSetAtom(deviceCartAtom);
|
||||
const devices = useAtomValue(deviceCartAtom);
|
||||
|
||||
const isChecked = devices.some((d) => d.id === device.id);
|
||||
|
||||
if (device.has_a_pending_payment || device.is_active) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled={device.blocked || device.is_active}
|
||||
className="peer accent-[#f49d1b] size-4"
|
||||
checked={isChecked}
|
||||
onChange={() =>
|
||||
setDeviceCart((prev) =>
|
||||
isChecked
|
||||
? prev.filter((d) => d.id !== device.id)
|
||||
: [...prev, device],
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
import { HandCoins } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/app/auth";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getDevices } from "@/queries/devices";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
import BlockDeviceDialog from "../block-device-dialog";
|
||||
import ClientErrorMessage from "../client-error-message";
|
||||
import Pagination from "../pagination";
|
||||
|
||||
export async function AdminDevicesTable({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{
|
||||
[key: string]: unknown;
|
||||
}>;
|
||||
}) {
|
||||
const resolvedParams = await searchParams;
|
||||
const session = await getServerSession(authOptions);
|
||||
const isAdmin = session?.user?.is_admin;
|
||||
|
||||
const page = Number.parseInt(resolvedParams.page as string) || 1;
|
||||
const limit = 10;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
// 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, devices] = await tryCatch(getDevices(apiParams, true));
|
||||
if (error) {
|
||||
if (error.message === "UNAUTHORIZED") {
|
||||
redirect("/auth/signin");
|
||||
} else {
|
||||
return <ClientErrorMessage message={error.message} />;
|
||||
}
|
||||
}
|
||||
const { meta, data } = devices;
|
||||
return (
|
||||
<div>
|
||||
{data?.length === 0 ? (
|
||||
<div className="h-[calc(100svh-400px)] text-muted-foreground flex flex-col items-center justify-center my-4">
|
||||
<h3>No devices.</h3>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div>
|
||||
<Table className="overflow-scroll">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Device Name</TableHead>
|
||||
<TableHead>User</TableHead>
|
||||
<TableHead>MAC Address</TableHead>
|
||||
<TableHead>Vendor</TableHead>
|
||||
<TableHead>#</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody className="overflow-scroll">
|
||||
{data?.map((device) => (
|
||||
<TableRow key={device.id}>
|
||||
<TableCell>
|
||||
<div className="flex flex-col items-start">
|
||||
<Link
|
||||
className={cn(
|
||||
"hover:underline font-semibold",
|
||||
device.is_active ? "text-green-600" : "",
|
||||
)}
|
||||
href={`/devices/${device.id}`}
|
||||
>
|
||||
{device.name}
|
||||
</Link>
|
||||
{device.is_active ? (
|
||||
<div className="text-muted-foreground">
|
||||
Active until{" "}
|
||||
<span className="font-semibold">
|
||||
{new Date(
|
||||
device.expiry_date || "",
|
||||
).toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground">
|
||||
Device Inactive
|
||||
</p>
|
||||
)}
|
||||
{device.has_a_pending_payment && (
|
||||
<Link href={`/payments/${device.pending_payment_id}`}>
|
||||
<span className="bg-muted rounded px-2 p-1 mt-2 flex hover:underline items-center justify-center gap-2 text-muted-foreground">
|
||||
Payment Pending{" "}
|
||||
<HandCoins className="animate-pulse" size={14} />
|
||||
</span>
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{device.blocked_by === "ADMIN" && device.blocked && (
|
||||
<div className="p-2 rounded border my-2 bg-white dark:bg-neutral-800 shadow">
|
||||
<span className="font-semibold">Comment</span>
|
||||
<p className="text-neutral-400">
|
||||
{device?.reason_for_blocking}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">
|
||||
<div className="flex flex-col items-start">
|
||||
{device?.user?.name}
|
||||
<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>
|
||||
{!device.has_a_pending_payment && (
|
||||
<BlockDeviceDialog
|
||||
admin={isAdmin}
|
||||
type={device.blocked ? "unblock" : "block"}
|
||||
device={device}
|
||||
/>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
<TableFooter>
|
||||
<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} devices.
|
||||
</p>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableFooter>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
<Pagination
|
||||
totalPages={meta?.last_page}
|
||||
currentPage={meta?.current_page}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
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<{
|
||||
[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 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>
|
||||
);
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
"use client";
|
||||
import { Loader2, User as UserIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { signOut, useSession } from "next-auth/react";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
|
||||
export function AccountPopover() {
|
||||
const session = useSession();
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
if (session.status === "loading") {
|
||||
<Button variant={"outline"} disabled>
|
||||
<Loader2 className="animate-spin" />
|
||||
</Button>;
|
||||
}
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button className="w-fit px-2" variant="outline">
|
||||
<UserIcon />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-fit mr-4">
|
||||
<div className="grid gap-4">
|
||||
<div className="space-y-2">
|
||||
<h4 className="font-medium leading-none">
|
||||
{session.data?.user?.first_name} {session.data?.user?.last_name}
|
||||
</h4>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<p className="font-semibold">{session.data?.user?.id_card}</p>
|
||||
<p>{session.data?.user?.mobile}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Button
|
||||
disabled={loading}
|
||||
onClick={async () => {
|
||||
setLoading(true);
|
||||
await signOut();
|
||||
setLoading(false);
|
||||
}}
|
||||
>
|
||||
{loading ? <Loader2 className="animate-spin" /> : "Logout"}
|
||||
</Button>
|
||||
<Link href="/profile" className="text-muted-foreground">
|
||||
<Button variant={"secondary"} className="w-full">
|
||||
View Profile
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { NuqsAdapter } from "nuqs/adapters/next/app";
|
||||
import { getProfile } from "@/actions/user-actions";
|
||||
import { authOptions } from "@/app/auth";
|
||||
import { DeviceCartDrawer } from "@/components/device-cart";
|
||||
import { ModeToggle } from "@/components/theme-toggle";
|
||||
import { AppSidebar } from "@/components/ui/app-sidebar";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import {
|
||||
SidebarInset,
|
||||
SidebarProvider,
|
||||
SidebarTrigger,
|
||||
} from "@/components/ui/sidebar";
|
||||
import { Wallet } from "@/components/wallet";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
import { WelcomeBanner } from "../welcome-banner";
|
||||
import { AccountPopover } from "./account-popver";
|
||||
|
||||
export async function ApplicationLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session) return redirect("/auth/signin");
|
||||
const [userError, userProfile] = await tryCatch(getProfile());
|
||||
if (userError) {
|
||||
if (userError.message === "Invalid token.") redirect("/auth/signin");
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<SidebarProvider>
|
||||
<AppSidebar />
|
||||
<SidebarInset>
|
||||
<header className="flex justify-between sticky top-0 bg-background h-16 shrink-0 items-center gap-2 border-b px-4 z-10">
|
||||
<div className="flex items-center gap-2 ">
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<Separator orientation="vertical" className="mr-2 h-4" />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Wallet walletBalance={userProfile?.wallet_balance || 0} />
|
||||
<ModeToggle />
|
||||
<AccountPopover />
|
||||
</div>
|
||||
</header>
|
||||
<WelcomeBanner
|
||||
firstName={session?.user?.first_name}
|
||||
lastName={session?.user?.last_name}
|
||||
/>
|
||||
<DeviceCartDrawer />
|
||||
<div className="p-4 flex flex-col flex-1 rounded-lg bg-background">
|
||||
<NuqsAdapter>{children}</NuqsAdapter>
|
||||
</div>
|
||||
</SidebarInset>
|
||||
</SidebarProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import { signin } from "@/actions/auth-actions";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useActionState } from "react";
|
||||
import { PhoneInput } from "../ui/phone-input";
|
||||
|
||||
export default function LoginForm() {
|
||||
const [state, formAction, isPending] = useActionState(signin, {
|
||||
message: "",
|
||||
status: "",
|
||||
});
|
||||
|
||||
return (
|
||||
<form
|
||||
className="overflow-clip title-bg w-full max-w-xs mx-auto rounded-lg shadow border-2 border-sarLinkOrange/50 dark:border-sarLinkOrange/50 mt-4"
|
||||
action={formAction}
|
||||
>
|
||||
<div className="py-4 px-4">
|
||||
<div className="grid gap-4">
|
||||
<PhoneInput
|
||||
id="phone-number"
|
||||
name="phoneNumber"
|
||||
maxLength={8}
|
||||
disabled={isPending}
|
||||
placeholder="Enter phone number"
|
||||
defaultCountry="MV"
|
||||
/>
|
||||
|
||||
{state.status === "error" && (
|
||||
<p className="text-red-500 text-sm">{state.message}</p>
|
||||
)}
|
||||
<Button className="" disabled={isPending} type="submit">
|
||||
{isPending ? <Loader2 className="animate-spin" /> : "Login"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -1,422 +0,0 @@
|
||||
"use client";
|
||||
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,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import type { ApiResponse, Atoll } from "@/lib/backend-types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getAtolls } from "@/queries/islands";
|
||||
|
||||
export default function SignUpForm() {
|
||||
const { data: atolls } = useQuery<ApiResponse<Atoll>>({
|
||||
queryKey: ["ATOLLS"],
|
||||
queryFn: () => getAtolls(),
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 1,
|
||||
});
|
||||
|
||||
const [atoll, setAtoll] = React.useState<Atoll>();
|
||||
|
||||
const [actionState, action, isPending] = React.useActionState(signup, {
|
||||
message: "",
|
||||
db_error: "",
|
||||
errors: undefined,
|
||||
payload: new FormData(),
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
console.log(atoll);
|
||||
}, [atoll]);
|
||||
|
||||
const params = useSearchParams();
|
||||
const phoneNumberFromUrl = params.get("phone_number");
|
||||
const NUMBER_WITHOUT_DASH = phoneNumberFromUrl?.split("-").join("");
|
||||
|
||||
if (actionState?.db_error === "invalidPersonValidation") {
|
||||
return (
|
||||
<>
|
||||
<div className="h-24 w-72 text-center text-green-500 p-4 flex my-4 flex-col items-center justify-center border dark:title-bg bg-white dark:bg-black rounded-lg">
|
||||
{actionState.message}
|
||||
</div>
|
||||
<div className="mb-4 text-center text-sm">
|
||||
Go to{" "}
|
||||
<Link href="login" className="underline">
|
||||
login
|
||||
</Link>
|
||||
</div>
|
||||
-
|
||||
</>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 w-full rounded h-screen overflow-y-scroll relative items-center justify-center">
|
||||
<div className="absolute inset-0 title-bg mask-dir-to-r mask-from-0 mask-via-100 mask-to-100 mask-linear" />
|
||||
<div className="hidden lg:flex relative overflow-hidden dark:text-white text-gray-900">
|
||||
<div className="relative z-10 flex flex-col justify-center items-center p-12 w-full">
|
||||
<div className="max-w-md text-center">
|
||||
{/* 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"
|
||||
/>
|
||||
</div>
|
||||
<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">Register your account</h1>
|
||||
<p className="text-xl mb-8 dark:text-orange-100">
|
||||
Pay for your devices and track your bills.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{/* Decorative elements */}
|
||||
</div>
|
||||
<form
|
||||
action={action}
|
||||
className="flex flex-col justify-center items-center p-6 lg:p-12 space-y-4 w-full "
|
||||
>
|
||||
<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"
|
||||
>
|
||||
Full Name
|
||||
</label>
|
||||
|
||||
<Input
|
||||
className={cn(
|
||||
"text-base",
|
||||
actionState?.errors?.fieldErrors.name &&
|
||||
"border-2 border-red-500",
|
||||
)}
|
||||
name="name"
|
||||
type="text"
|
||||
disabled={isPending}
|
||||
defaultValue={
|
||||
(actionState?.payload?.get("name") || "") as string
|
||||
}
|
||||
placeholder="Full Name"
|
||||
/>
|
||||
{actionState?.errors?.fieldErrors.name && (
|
||||
<span className="text-sm inline-block text-red-500">
|
||||
{actionState?.errors?.fieldErrors.name}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="id_card"
|
||||
className="text-sm font-medium text-slate-700 dark:text-slate-300"
|
||||
>
|
||||
ID Card
|
||||
</label>
|
||||
<Input
|
||||
name="id_card"
|
||||
type="text"
|
||||
maxLength={7}
|
||||
disabled={isPending}
|
||||
defaultValue={
|
||||
(actionState?.payload?.get("id_card") || "") as string
|
||||
}
|
||||
className={cn(
|
||||
"text-base",
|
||||
actionState?.errors?.fieldErrors?.id_card &&
|
||||
"border-2 border-red-500",
|
||||
)}
|
||||
placeholder="ID Card"
|
||||
/>
|
||||
{actionState?.errors?.fieldErrors?.id_card?.[0] && (
|
||||
<span className="text-sm inline-block text-red-500">
|
||||
{actionState?.errors.fieldErrors.id_card[0]}
|
||||
</span>
|
||||
)}
|
||||
{actionState?.db_error === "id_card" && (
|
||||
<span className="text-sm inline-block text-red-500">
|
||||
{actionState?.message}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="atoll"
|
||||
className="text-sm font-medium text-slate-700 dark:text-slate-300"
|
||||
>
|
||||
Atoll
|
||||
</label>
|
||||
<Select
|
||||
disabled={isPending}
|
||||
onValueChange={(v) => {
|
||||
console.log({ v });
|
||||
setAtoll(
|
||||
atolls?.data.find(
|
||||
(atoll) => atoll.id === Number.parseInt(v),
|
||||
),
|
||||
);
|
||||
}}
|
||||
name="atoll_id"
|
||||
value={atoll?.id?.toString() ?? ""}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="Select atoll" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectLabel>Atolls</SelectLabel>
|
||||
{atolls?.data.map((atoll) => (
|
||||
<SelectItem key={atoll.id} value={atoll.id.toString()}>
|
||||
{atoll.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
{actionState?.errors?.fieldErrors?.atoll_id && (
|
||||
<span className="text-sm inline-block text-red-500">
|
||||
{actionState?.errors?.fieldErrors?.atoll_id}
|
||||
</span>
|
||||
)}
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="island"
|
||||
className="text-sm font-medium text-slate-700 dark:text-slate-300"
|
||||
>
|
||||
Island
|
||||
</label>
|
||||
<Select disabled={isPending} name="island_id">
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="Select island" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectLabel>Islands</SelectLabel>
|
||||
{atoll?.islands?.map((island) => (
|
||||
<SelectItem
|
||||
key={island.id}
|
||||
value={island.id.toString()}
|
||||
>
|
||||
{island.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
{actionState?.errors?.fieldErrors?.island_id && (
|
||||
<span className="text-sm inline-block text-red-500">
|
||||
{actionState?.errors?.fieldErrors?.island_id}
|
||||
</span>
|
||||
)}
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="address"
|
||||
className="text-sm font-medium text-slate-700 dark:text-slate-300"
|
||||
>
|
||||
Address
|
||||
</label>
|
||||
<Input
|
||||
className={cn(
|
||||
"text-base",
|
||||
actionState?.errors?.fieldErrors?.address &&
|
||||
"border-2 border-red-500",
|
||||
)}
|
||||
disabled={isPending}
|
||||
name="address"
|
||||
defaultValue={
|
||||
(actionState?.payload?.get("address") || "") as string
|
||||
}
|
||||
type="text"
|
||||
placeholder="Address"
|
||||
/>
|
||||
{actionState?.errors?.fieldErrors?.address && (
|
||||
<span className="text-sm inline-block text-red-500">
|
||||
{actionState?.errors?.fieldErrors?.address}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="dob"
|
||||
className="text-sm font-medium text-slate-700 dark:text-slate-300"
|
||||
>
|
||||
Date of Birth
|
||||
</label>
|
||||
<Input
|
||||
className={cn(
|
||||
"text-base",
|
||||
actionState?.errors?.fieldErrors?.dob &&
|
||||
"border-2 border-red-500",
|
||||
)}
|
||||
name="dob"
|
||||
disabled={isPending}
|
||||
defaultValue={
|
||||
(actionState?.payload?.get("dob") || "") as string
|
||||
}
|
||||
type="date"
|
||||
placeholder="Date of birth"
|
||||
/>
|
||||
{actionState?.errors?.fieldErrors?.dob && (
|
||||
<span className="text-sm inline-block text-red-500">
|
||||
{actionState?.errors?.fieldErrors?.dob}
|
||||
</span>
|
||||
)}
|
||||
{actionState?.db_error === "dob" && (
|
||||
<span className="text-sm inline-block text-red-500">
|
||||
{actionState?.message}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="accNo"
|
||||
className="text-sm font-medium text-slate-700 dark:text-slate-300"
|
||||
>
|
||||
Account Number
|
||||
</label>
|
||||
|
||||
<Input
|
||||
className={cn(
|
||||
"text-base",
|
||||
actionState?.errors?.fieldErrors.accNo &&
|
||||
"border-2 border-red-500",
|
||||
)}
|
||||
name="accNo"
|
||||
type="number"
|
||||
disabled={isPending}
|
||||
defaultValue={
|
||||
(actionState?.payload?.get("accNo") || "") as string
|
||||
}
|
||||
placeholder="Account no"
|
||||
/>
|
||||
{actionState?.errors?.fieldErrors.accNo && (
|
||||
<span className="text-sm inline-block text-red-500">
|
||||
{actionState?.errors?.fieldErrors.accNo}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="phone_number"
|
||||
className="text-sm font-medium text-slate-700 dark:text-slate-300"
|
||||
>
|
||||
Phone Number
|
||||
</label>
|
||||
<Input
|
||||
id="phone-number"
|
||||
name="phone_number"
|
||||
maxLength={8}
|
||||
disabled={isPending}
|
||||
className={cn(
|
||||
!phoneNumberFromUrl &&
|
||||
actionState?.errors?.fieldErrors?.phone_number &&
|
||||
"border-2 border-red-500 rounded-md",
|
||||
)}
|
||||
defaultValue={NUMBER_WITHOUT_DASH ?? ""}
|
||||
readOnly={Boolean(phoneNumberFromUrl)}
|
||||
placeholder={phoneNumberFromUrl ?? "Phone number"}
|
||||
/>
|
||||
</div>
|
||||
{actionState?.errors?.fieldErrors?.phone_number?.[0] && (
|
||||
<span className="text-sm inline-block text-red-500">
|
||||
{actionState?.errors.fieldErrors.phone_number[0]}
|
||||
</span>
|
||||
)}
|
||||
{actionState?.db_error === "phone_number" && (
|
||||
<span className="text-sm inline-block text-red-500">
|
||||
{actionState?.message}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex flex-col gap-2 items-start justify-start py-2">
|
||||
<div className="flex gap-2 items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
defaultChecked={
|
||||
((actionState?.payload?.get("terms") || "") as string) ===
|
||||
"on"
|
||||
}
|
||||
name="terms"
|
||||
id="terms"
|
||||
/>
|
||||
<label
|
||||
htmlFor="terms"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
>
|
||||
<span>i accept</span>
|
||||
<Link className="ml-1 underline" href="">
|
||||
terms and conditions
|
||||
</Link>
|
||||
</label>
|
||||
</div>
|
||||
{actionState?.errors?.fieldErrors?.terms && (
|
||||
<span className="text-sm inline-block text-red-500">
|
||||
{actionState?.errors?.fieldErrors?.terms}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex gap-2 items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
defaultChecked={
|
||||
((actionState?.payload?.get("policy") || "") as string) ===
|
||||
"on"
|
||||
}
|
||||
name="policy"
|
||||
id="terms"
|
||||
/>
|
||||
<label
|
||||
htmlFor="terms"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
>
|
||||
<span>i undertand</span>
|
||||
<Link className="ml-1 underline" href="">
|
||||
the privacy policy
|
||||
</Link>
|
||||
</label>
|
||||
</div>
|
||||
{actionState?.errors?.fieldErrors?.policy && (
|
||||
<span className="text-sm inline-block text-red-500">
|
||||
{actionState?.errors?.fieldErrors?.policy}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Button disabled={isPending} className="mt-4 w-full" type="submit">
|
||||
{isPending ? <Loader2 className="animate-spin" /> : "Submit"}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="mb-4 text-center text-sm">
|
||||
Already have an account?{" "}
|
||||
<Link href="signin" className="underline">
|
||||
login
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Loader2 } from "lucide-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.",
|
||||
}),
|
||||
});
|
||||
|
||||
export default function VerifyOTPForm({
|
||||
phone_number,
|
||||
}: {
|
||||
phone_number: string;
|
||||
}) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const router = useRouter();
|
||||
console.log("verification in OTP form", phone_number);
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<z.infer<typeof OTPSchema>>({
|
||||
defaultValues: {
|
||||
pin: "",
|
||||
},
|
||||
resolver: zodResolver(OTPSchema),
|
||||
});
|
||||
const searchParams = useSearchParams();
|
||||
const callbackUrl = searchParams.get("callbackUrl") || "/dashboard";
|
||||
|
||||
const onSubmit: SubmitHandler<z.infer<typeof OTPSchema>> = (data) => {
|
||||
startTransition(async () => {
|
||||
const nextAuth = await signIn("credentials", {
|
||||
pin: data.pin,
|
||||
callbackUrl,
|
||||
redirect: false,
|
||||
});
|
||||
if (!nextAuth?.error) {
|
||||
router.push("/devices");
|
||||
} else {
|
||||
toast.error(JSON.parse(nextAuth?.error ?? "").message);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// "{\"message\":\"The token you entered isn't valid.\",\"status\":400}"
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
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">
|
||||
<p className="text-center text-sm text-sarLinkOrange">
|
||||
Login OTP Sent to {phone_number}
|
||||
</p>
|
||||
<Label htmlFor="otp-number" className="sr-only text-gray-500">
|
||||
Enter the OTP
|
||||
</Label>
|
||||
<Input
|
||||
disabled={isPending}
|
||||
id="otp-number"
|
||||
{...register("pin")}
|
||||
type="text"
|
||||
placeholder="Enter OTP"
|
||||
className="bg-white dark:bg-black"
|
||||
/>
|
||||
{errors.pin && (
|
||||
<p className="text-red-500 text-sm">{errors.pin.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<Button className="w-full" disabled={isPending} type="submit">
|
||||
{isPending ? <Loader2 className="animate-spin" /> : "Login"}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="mb-4 text-center text-sm">
|
||||
Change{" "}
|
||||
<Link href="signin" className="underline">
|
||||
phone number
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
"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";
|
||||
|
||||
export default function VerifyRegistrationOTPForm({
|
||||
phone_number,
|
||||
}: {
|
||||
phone_number: string;
|
||||
}) {
|
||||
console.log("verification in OTP form", phone_number);
|
||||
|
||||
const searchParams = useSearchParams();
|
||||
const mobile = searchParams.get("phone_number");
|
||||
if (!mobile) redirect("/auth/login");
|
||||
const [state, formAction, isPending] = useActionState(VerifyRegistrationOTP, {
|
||||
message: "",
|
||||
status: "",
|
||||
});
|
||||
|
||||
return (
|
||||
<form
|
||||
action={formAction}
|
||||
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">
|
||||
{state.status === "verify_success" ? (
|
||||
<p className="bg-green-100 dark:bg-dark-green-800 border border-green-900/50 text-green-700 rounded p-2 text-center text-sm">
|
||||
{state.message}
|
||||
</p>
|
||||
) : (
|
||||
<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>
|
||||
)}
|
||||
|
||||
<Label htmlFor="otp-number" className="sr-only text-gray-500">
|
||||
Enter the OTP
|
||||
</Label>
|
||||
<input
|
||||
type="number"
|
||||
name="mobile"
|
||||
defaultValue={phone_number}
|
||||
hidden
|
||||
/>
|
||||
<Input
|
||||
disabled={isPending || state.status === "verify_error"}
|
||||
id="otp-number"
|
||||
name="otp"
|
||||
maxLength={6}
|
||||
type="number"
|
||||
placeholder="Enter OTP"
|
||||
className={cn(
|
||||
"bg-white text-black dark:text-white dark:bg-gray-950",
|
||||
state.status === "verify_success" && "hidden",
|
||||
)}
|
||||
/>
|
||||
{state?.status === "error" && (
|
||||
<p className="text-yellow-500 text-sm">{state.message}</p>
|
||||
)}
|
||||
{state.status === "verify_error" && (
|
||||
<p className="text-red-500 text-sm">{state.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
className={cn(
|
||||
"w-full",
|
||||
state.status === "verify_success" && "hidden",
|
||||
)}
|
||||
disabled={isPending || state.status === "verify_error"}
|
||||
type="submit"
|
||||
>
|
||||
{isPending ? (
|
||||
<Loader2 className="animate-spin" />
|
||||
) : (
|
||||
"Request verification"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
{state.status === "verify_success" && (
|
||||
<div className="mb-4 text-center text-sm">
|
||||
Go to{" "}
|
||||
<Link href="signin" className="underline">
|
||||
login
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Loader2, Trash2 } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import React from "react";
|
||||
import { toast } from "sonner";
|
||||
import { cancelPayment } from "@/actions/payment";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
import { Button } from "../ui/button";
|
||||
|
||||
export default function CancelPaymentButton({
|
||||
paymentId,
|
||||
}: {
|
||||
paymentId: string;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [loading, setLoading] = React.useState(false);
|
||||
return (
|
||||
<Button
|
||||
onClick={async () => {
|
||||
setLoading(true);
|
||||
const [error, payment] = await tryCatch(
|
||||
cancelPayment({ id: paymentId }),
|
||||
);
|
||||
console.log(payment);
|
||||
if (error) {
|
||||
toast.error(error.message);
|
||||
setLoading(false);
|
||||
} else {
|
||||
toast.success("Payment cancelled successfully!", {
|
||||
description: `Your payment of ${payment?.amount} MVR has been cancelled.`,
|
||||
closeButton: true,
|
||||
});
|
||||
router.replace("/devices");
|
||||
}
|
||||
}}
|
||||
disabled={loading}
|
||||
variant={"destructive"}
|
||||
>
|
||||
Cancel Payment
|
||||
{loading ? <Loader2 className="animate-spin" /> : <Trash2 />}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Loader2, Trash2 } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import React from "react";
|
||||
import { toast } from "sonner";
|
||||
import { cancelTopup } from "@/actions/payment";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
import { Button } from "../ui/button";
|
||||
|
||||
export default function CancelTopupButton({ topupId }: { topupId: string }) {
|
||||
const router = useRouter();
|
||||
const [loading, setLoading] = React.useState(false);
|
||||
return (
|
||||
<Button
|
||||
onClick={async () => {
|
||||
setLoading(true);
|
||||
const [error, topup] = await tryCatch(cancelTopup({ id: topupId }));
|
||||
if (error) {
|
||||
toast.error(error.message);
|
||||
setLoading(false);
|
||||
} else {
|
||||
toast.success("Topup cancelled successfully!", {
|
||||
description: `Your topup of ${topup?.amount} MVR has been cancelled.`,
|
||||
closeButton: true,
|
||||
});
|
||||
router.replace("/top-ups");
|
||||
}
|
||||
}}
|
||||
disabled={loading}
|
||||
variant={"destructive"}
|
||||
>
|
||||
Cancel Topup
|
||||
{loading ? <Loader2 className="animate-spin" /> : <Trash2 />}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
"use client";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
|
||||
const calculateTimeLeft = (expiresAt: string) => {
|
||||
const now = Date.now();
|
||||
const expirationTime = new Date(expiresAt).getTime();
|
||||
return Math.max(0, Math.floor((expirationTime - now) / 1000));
|
||||
};
|
||||
|
||||
const HumanizeTimeLeft = (seconds: number) => {
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const remainingSeconds = seconds % 60;
|
||||
return `${minutes}m ${remainingSeconds}s`;
|
||||
};
|
||||
|
||||
export default function ExpiryCountDown({
|
||||
expiresAt,
|
||||
expiryLabel,
|
||||
}: {
|
||||
expiresAt: string;
|
||||
expiryLabel: string;
|
||||
}) {
|
||||
const [timeLeft, setTimeLeft] = useState(calculateTimeLeft(expiresAt));
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
setTimeLeft(calculateTimeLeft(expiresAt));
|
||||
}, 1000);
|
||||
|
||||
return () => clearInterval(timer);
|
||||
}, [expiresAt]);
|
||||
|
||||
useEffect(() => {
|
||||
if (timeLeft <= 0) {
|
||||
router.replace(pathname);
|
||||
}
|
||||
}, [timeLeft, router, pathname]);
|
||||
|
||||
if (!mounted) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<div className="overflow-clip relative mx-2 p-4 rounded-md border border-dashed flex items-center justify-between text-muted-foreground">
|
||||
<div className="absolute inset-0 title-bg mask-b-from-0" />
|
||||
{timeLeft ? (
|
||||
<span>Time left: {HumanizeTimeLeft(timeLeft)}</span>
|
||||
) : (
|
||||
<span>{expiryLabel} has expired.</span>
|
||||
)}
|
||||
{timeLeft > 0 && (
|
||||
<Progress
|
||||
className="absolute bottom-0 left-0 right-0"
|
||||
color="#f49b5b"
|
||||
value={(timeLeft / 600) * 100}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { DialogDescription } from "@radix-ui/react-dialog";
|
||||
import { OctagonX, ShieldBan } from "lucide-react";
|
||||
import { useActionState, useEffect, useState, useTransition } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import type { Device } from "@/lib/backend-types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { blockDeviceAction } from "@/queries/devices";
|
||||
import { TextShimmer } from "./ui/text-shimmer";
|
||||
import { Textarea } from "./ui/textarea";
|
||||
|
||||
export type BlockDeviceFormState = {
|
||||
message: string;
|
||||
success: boolean;
|
||||
fieldErrors?: {
|
||||
reason_for_blocking?: string[];
|
||||
};
|
||||
payload?: FormData;
|
||||
};
|
||||
|
||||
const initialState: BlockDeviceFormState = {
|
||||
message: "",
|
||||
success: false,
|
||||
fieldErrors: {},
|
||||
};
|
||||
|
||||
export default function BlockDeviceDialog({
|
||||
device,
|
||||
admin,
|
||||
parentalControl = false,
|
||||
}: {
|
||||
device: Device;
|
||||
type: "block" | "unblock";
|
||||
admin?: boolean;
|
||||
parentalControl?: boolean;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [state, formAction, isPending] = useActionState(
|
||||
blockDeviceAction,
|
||||
initialState,
|
||||
);
|
||||
const [isTransitioning, startTransition] = useTransition();
|
||||
|
||||
const handleSimpleBlock = () => {
|
||||
startTransition(() => {
|
||||
const formData = new FormData();
|
||||
formData.append("deviceId", String(device.id));
|
||||
formData.append("reason_for_blocking", "");
|
||||
formData.append("action", "simple-block");
|
||||
formData.append("blocked_by", "PARENT");
|
||||
|
||||
formAction(formData);
|
||||
});
|
||||
};
|
||||
|
||||
const handleUnblock = () => {
|
||||
startTransition(() => {
|
||||
const formData = new FormData();
|
||||
formData.append("deviceId", String(device.id));
|
||||
formData.append("reason_for_blocking", "");
|
||||
formData.append("action", "unblock");
|
||||
formData.append("blocked_by", "PARENT");
|
||||
|
||||
formAction(formData);
|
||||
});
|
||||
};
|
||||
|
||||
// Show toast notifications based on state changes
|
||||
useEffect(() => {
|
||||
if (state.message) {
|
||||
if (state.success) {
|
||||
toast.success(state.message);
|
||||
if (open) setOpen(false);
|
||||
} else {
|
||||
toast.error(state.message);
|
||||
}
|
||||
}
|
||||
}, [state, open]);
|
||||
|
||||
const isLoading = isPending || isTransitioning;
|
||||
|
||||
// If device is blocked and user is not admin, show unblock button
|
||||
if (device.blocked && parentalControl) {
|
||||
return (
|
||||
<Button onClick={handleUnblock} disabled={isLoading}>
|
||||
{isLoading ? <TextShimmer>Unblocking</TextShimmer> : "Unblock"}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
// If device is not blocked and user is not admin, show simple block button
|
||||
if ((!device.blocked && parentalControl) || !admin) {
|
||||
return (
|
||||
<Button
|
||||
onClick={handleSimpleBlock}
|
||||
disabled={isLoading}
|
||||
variant="destructive"
|
||||
>
|
||||
<ShieldBan />
|
||||
{isLoading ? <TextShimmer>Blocking</TextShimmer> : "Block"}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
// If user is admin, show block with reason dialog
|
||||
return (
|
||||
<div>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button disabled={isLoading} variant="destructive">
|
||||
<OctagonX />
|
||||
Block
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Block 🚫</DialogTitle>
|
||||
<DialogDescription className="text-sm text-muted-foreground">
|
||||
Please provide a reason for blocking this device
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form action={formAction} className="space-y-4">
|
||||
<input type="hidden" name="deviceId" value={String(device.id)} />
|
||||
<input type="hidden" name="action" value="block" />
|
||||
<input type="hidden" name="blocked_by" value="ADMIN" />
|
||||
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="flex flex-col items-start gap-1">
|
||||
<Label htmlFor="reason_for_blocking" className="text-right">
|
||||
Reason for blocking
|
||||
</Label>
|
||||
<Textarea
|
||||
rows={10}
|
||||
name="reason_for_blocking"
|
||||
id="reason_for_blocking"
|
||||
defaultValue={
|
||||
(state?.payload?.get("reason_for_blocking") || "") as string
|
||||
}
|
||||
className={cn(
|
||||
"col-span-5 mt-2",
|
||||
state.fieldErrors?.reason_for_blocking &&
|
||||
"ring-2 ring-red-500",
|
||||
)}
|
||||
/>
|
||||
<span className="text-sm text-red-500">
|
||||
{state.fieldErrors?.reason_for_blocking?.[0]}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="destructive" disabled={isLoading} type="submit">
|
||||
{isLoading ? "Blocking..." : "Block"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
"use client";
|
||||
import { useAtom } from "jotai";
|
||||
import { HandCoins } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { TableCell, TableRow } from "@/components/ui/table";
|
||||
import { deviceCartAtom } from "@/lib/atoms";
|
||||
import type { Device } from "@/lib/backend-types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import AddDevicesToCartButton from "./add-devices-to-cart-button";
|
||||
import BlockDeviceDialog from "./block-device-dialog";
|
||||
export default function ClickableRow({
|
||||
device,
|
||||
parentalControl,
|
||||
admin = false,
|
||||
idx,
|
||||
}: {
|
||||
device: Device;
|
||||
parentalControl?: boolean;
|
||||
admin?: boolean;
|
||||
idx?: number;
|
||||
}) {
|
||||
const [devices, setDeviceCart] = useAtom(deviceCartAtom);
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
key={device.id}
|
||||
className={cn(
|
||||
(parentalControl === false && device.blocked) || device.is_active
|
||||
? "cursor-not-allowed hover:bg-accent-foreground/10"
|
||||
: "cursor-pointer hover:bg-muted-foreground/10",
|
||||
`motion-preset-fade-md motion-delay-${(idx || 1) * 75}ms`,
|
||||
)}
|
||||
onClick={() => {
|
||||
if (device.blocked) return;
|
||||
if (device.is_active === true) return;
|
||||
if (device.has_a_pending_payment === true) return;
|
||||
if (parentalControl === true) return;
|
||||
setDeviceCart((prev) =>
|
||||
devices.some((d) => d.id === device.id)
|
||||
? prev.filter((d) => d.id !== device.id)
|
||||
: [...prev, device],
|
||||
);
|
||||
}}
|
||||
>
|
||||
<TableCell>
|
||||
<div className="flex flex-col items-start">
|
||||
<Link
|
||||
className={cn(
|
||||
"hover:underline font-semibold",
|
||||
device.is_active ? "text-green-600" : "",
|
||||
)}
|
||||
href={`/devices/${device.id}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{device.name}
|
||||
</Link>
|
||||
{device.is_active ? (
|
||||
<div className="text-muted-foreground">
|
||||
Active until{" "}
|
||||
<span className="font-semibold">
|
||||
{new Date(device.expiry_date || "").toLocaleDateString(
|
||||
"en-US",
|
||||
{
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
},
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground">Device Inactive</p>
|
||||
)}
|
||||
{device.has_a_pending_payment && (
|
||||
<Link href={`/payments/${device.pending_payment_id}`}>
|
||||
<span className="bg-muted rounded px-2 p-1 mt-2 flex hover:underline items-center justify-center gap-2 text-muted-foreground">
|
||||
Payment Pending{" "}
|
||||
<HandCoins className="animate-pulse" size={14} />
|
||||
</span>
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{device.blocked_by === "ADMIN" && device.blocked && (
|
||||
<div className="p-2 rounded border my-2 bg-white dark:bg-neutral-800 shadow">
|
||||
<span className="font-semibold">Comment</span>
|
||||
<p className="text-neutral-400">{device?.reason_for_blocking}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">{device.mac}</TableCell>
|
||||
<TableCell className="font-medium">{device?.vendor}</TableCell>
|
||||
<TableCell>
|
||||
{!parentalControl ? (
|
||||
<AddDevicesToCartButton device={device} />
|
||||
) : (
|
||||
<BlockDeviceDialog
|
||||
admin={admin}
|
||||
type={device.blocked ? "unblock" : "block"}
|
||||
device={device}
|
||||
parentalControl={parentalControl}
|
||||
/>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import { Phone, TriangleAlert } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { Button } from "./ui/button";
|
||||
|
||||
export default function ClientErrorMessage({ message }: { message: string }) {
|
||||
return (
|
||||
<div className="error-bg dark:error-bg-dark rounded-lg p-4 h-full flex flex-col gap-4 items-center justify-center">
|
||||
<div className="bg-white dark:bg-transparent p-6 rounded flex flex-col items-center justify-center gap-4">
|
||||
<TriangleAlert color="red" />
|
||||
<h6 className="text-red-500 text-sm font-semibold">{message}</h6>
|
||||
{message === "You do not have permission to perform this action." && (
|
||||
<>
|
||||
<span className="text-muted-foreground">
|
||||
Please contact the administrator to give you permissions.
|
||||
</span>
|
||||
<Link href="tel:9198026">
|
||||
<Button>
|
||||
<Phone /> 919-8026
|
||||
</Button>
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
"use client";
|
||||
import { useAtom } from "jotai";
|
||||
import { HandCoins } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { deviceCartAtom } from "@/lib/atoms";
|
||||
import type { Device } from "@/lib/backend-types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import AddDevicesToCartButton from "./add-devices-to-cart-button";
|
||||
import BlockDeviceDialog from "./block-device-dialog";
|
||||
import { Badge } from "./ui/badge";
|
||||
|
||||
export default function DeviceCard({
|
||||
device,
|
||||
parentalControl,
|
||||
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={() => {
|
||||
if (device.blocked) return;
|
||||
if (device.is_active === true) return;
|
||||
if (device.has_a_pending_payment === true) return;
|
||||
if (parentalControl === true) return;
|
||||
setDeviceCart((prev) =>
|
||||
devices.some((d) => d.id === device.id)
|
||||
? prev.filter((d) => d.id !== device.id)
|
||||
: [...prev, device],
|
||||
);
|
||||
}}
|
||||
className="w-full"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex text-sm justify-between items-center my-2 p-4 border rounded-md motion-preset-fade-md",
|
||||
isChecked ? "bg-accent" : "",
|
||||
device.is_active
|
||||
? "cursor-not-allowed text-green-600 hover:bg-accent-foreground/10"
|
||||
: "cursor-pointer hover:bg-muted-foreground/10",
|
||||
)}
|
||||
>
|
||||
<div className="">
|
||||
<div className="font-semibold flex flex-col items-start gap-2 mb-2">
|
||||
<Link
|
||||
className={cn(
|
||||
"font-medium hover:underline ml-0.5",
|
||||
device.is_active ? "text-green-600" : "",
|
||||
)}
|
||||
href={`/devices/${device.id}`}
|
||||
>
|
||||
{device.name}
|
||||
</Link>
|
||||
<Badge variant={"outline"}>
|
||||
<span className="font-medium">{device.mac}</span>
|
||||
</Badge>
|
||||
<Badge variant={"outline"}>
|
||||
<span className="font-medium">{device.vendor}</span>
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{device.is_active ? (
|
||||
<div className="text-muted-foreground ml-0.5">
|
||||
Active until{" "}
|
||||
<span className="font-semibold">
|
||||
{new Date(device.expiry_date || "").toLocaleDateString(
|
||||
"en-US",
|
||||
{
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
},
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground ml-0.5">Device Inactive</p>
|
||||
)}
|
||||
{device.has_a_pending_payment && (
|
||||
<Link href={`/payments/${device.pending_payment_id}`}>
|
||||
<span className="bg-muted rounded px-2 p-1 mt-2 flex hover:underline items-center justify-center gap-2 text-yellow-600">
|
||||
Payment Pending{" "}
|
||||
<HandCoins className="animate-pulse" size={14} />
|
||||
</span>
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{device.blocked && device.blocked_by === "ADMIN" && (
|
||||
<div className="p-2 rounded border my-2 w-full">
|
||||
<span className="uppercase text-red-500">Blocked by admin </span>
|
||||
<p className="text-neutral-500">{device?.reason_for_blocking}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
{!parentalControl ? (
|
||||
<AddDevicesToCartButton device={device} />
|
||||
) : (
|
||||
<BlockDeviceDialog
|
||||
admin={isAdmin}
|
||||
type={device.blocked ? "unblock" : "block"}
|
||||
device={device}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useAtom } from "jotai";
|
||||
import { MonitorSmartphone } from "lucide-react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { deviceCartAtom } from "@/lib/atoms";
|
||||
|
||||
export function DeviceCartDrawer() {
|
||||
const pathname = usePathname();
|
||||
const [devices, setDevices] = useAtom(deviceCartAtom);
|
||||
const router = useRouter();
|
||||
if (pathname === "/payment" || pathname === "/devices-to-pay") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (devices.length === 0) return null;
|
||||
return (
|
||||
<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"
|
||||
onClick={() => router.push("/devices-to-pay")}
|
||||
variant="secondary"
|
||||
>
|
||||
<MonitorSmartphone />
|
||||
Pay {devices.length > 0 && `(${devices.length})`}{" "}
|
||||
{devices.length > 1 ? "devices" : "device"}
|
||||
</Button>
|
||||
<Button
|
||||
variant={"destructive"}
|
||||
onClick={() => setDevices([])}
|
||||
className="w-full"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
"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";
|
||||
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 FullPageLoader from "./full-page-loader";
|
||||
export default function DevicesForPayment() {
|
||||
const pathname = usePathname();
|
||||
const devices = useAtomValue(deviceCartAtom);
|
||||
const setDeviceCart = useSetAtom(deviceCartAtom);
|
||||
const [months, setMonths] = useAtom(numberOfMonths);
|
||||
const [disabled, setDisabled] = useState(false);
|
||||
|
||||
if (pathname === "/payments") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const data: NewPayment = {
|
||||
number_of_months: months,
|
||||
device_ids: devices.map((device) => device.id),
|
||||
};
|
||||
|
||||
if (disabled) {
|
||||
return <FullPageLoader />;
|
||||
}
|
||||
return (
|
||||
<div className="max-w-lg mx-auto space-y-4 px-4">
|
||||
<div className="flex max-h-[calc(100svh-400px)] flex-col overflow-auto pb-4 gap-4">
|
||||
{devices.map((device) => (
|
||||
<DeviceCard key={device.id} device={device} />
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-col gap-4">
|
||||
<NumberInput
|
||||
label="Set No of Months"
|
||||
value={months}
|
||||
onChange={(value: number) => setMonths(value)}
|
||||
maxAllowed={12}
|
||||
isDisabled={devices.length === 0}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={async () => {
|
||||
setDisabled(true);
|
||||
const [error, response] = await tryCatch(createPayment(data));
|
||||
if (error) {
|
||||
setDisabled(false);
|
||||
toast.error(JSON.stringify(error, null, 2));
|
||||
return;
|
||||
}
|
||||
setDeviceCart([]);
|
||||
setMonths(1);
|
||||
redirect(`/payments/${response.id}`);
|
||||
}}
|
||||
className="w-full"
|
||||
disabled={devices.length === 0 || disabled}
|
||||
>
|
||||
{disabled ? (
|
||||
<>
|
||||
<Loader2 className="ml-2 animate-spin" />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Go to payment
|
||||
<CircleDollarSign />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/app/auth";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { getDevices } from "@/queries/devices";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
import ClickableRow from "./clickable-row";
|
||||
import ClientErrorMessage from "./client-error-message";
|
||||
import DeviceCard from "./device-card";
|
||||
import Pagination from "./pagination";
|
||||
|
||||
export async function DevicesTable({
|
||||
searchParams,
|
||||
parentalControl,
|
||||
additionalFilters = {},
|
||||
}: {
|
||||
searchParams: Promise<{
|
||||
[key: string]: unknown;
|
||||
}>;
|
||||
parentalControl?: boolean;
|
||||
additionalFilters?: Record<string, string | number | boolean>;
|
||||
}) {
|
||||
const resolvedParams = await searchParams;
|
||||
const session = await getServerSession(authOptions);
|
||||
const isAdmin = session?.user?.is_admin;
|
||||
|
||||
const page = Number.parseInt(resolvedParams.page as string) || 1;
|
||||
const limit = 10;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
// Build params object for getDevices
|
||||
const apiParams: Record<string, string | number | undefined> = {};
|
||||
for (const [key, value] of Object.entries(resolvedParams)) {
|
||||
if (value !== undefined && value !== "") {
|
||||
apiParams[key] = typeof value === "number" ? value : String(value);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [key, value] of Object.entries(additionalFilters)) {
|
||||
if (value !== undefined && value !== "") {
|
||||
apiParams[key] = typeof value === "number" ? value : String(value);
|
||||
}
|
||||
}
|
||||
apiParams.limit = limit;
|
||||
apiParams.offset = offset;
|
||||
const [error, devices] = await tryCatch(getDevices(apiParams));
|
||||
if (error) {
|
||||
if (error.message === "UNAUTHORIZED") {
|
||||
redirect("/auth/signin");
|
||||
} else {
|
||||
return <ClientErrorMessage message={error.message} />;
|
||||
}
|
||||
}
|
||||
const { meta, data } = devices;
|
||||
return (
|
||||
<div>
|
||||
{data?.length === 0 ? (
|
||||
<div className="h-[calc(100svh-400px)] text-muted-foreground flex flex-col items-center justify-center my-4">
|
||||
<h3>{parentalControl ? "No active devices" : "No devices."}</h3>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="hidden sm:block">
|
||||
<Table className="overflow-scroll">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Device Name</TableHead>
|
||||
<TableHead>MAC Address</TableHead>
|
||||
<TableHead>Vendor</TableHead>
|
||||
<TableHead>#</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody className="overflow-scroll">
|
||||
{data?.map((device, idx) => (
|
||||
<ClickableRow
|
||||
admin={isAdmin}
|
||||
key={device.id}
|
||||
device={device}
|
||||
parentalControl={parentalControl}
|
||||
idx={idx + 1}
|
||||
/>
|
||||
))}
|
||||
</TableBody>
|
||||
<TableFooter>
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="text-muted-foreground">
|
||||
{meta?.total === 1 ? (
|
||||
<p className="text-center">Total {meta?.total} device.</p>
|
||||
) : (
|
||||
<p className="text-center">
|
||||
Total {meta?.total} devices.
|
||||
</p>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableFooter>
|
||||
</Table>
|
||||
</div>
|
||||
<div className="sm:hidden my-4">
|
||||
{data?.map((device) => (
|
||||
<DeviceCard
|
||||
parentalControl={parentalControl}
|
||||
key={device.id}
|
||||
device={device}
|
||||
isAdmin={isAdmin}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<Pagination
|
||||
totalPages={meta?.last_page}
|
||||
currentPage={meta?.current_page}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
"use client";
|
||||
import { BadgeDollarSign, Loader2, Wallet } from "lucide-react";
|
||||
import { useActionState, useEffect } from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
type VerifyDevicePaymentState,
|
||||
verifyDevicePayment,
|
||||
} from "@/actions/payment";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCaption,
|
||||
TableCell,
|
||||
TableFooter,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import type { Payment } from "@/lib/backend-types";
|
||||
import type { User } from "@/lib/types/user";
|
||||
import { shouldShowPaymentInfo } from "@/lib/utils";
|
||||
import { AccountInfomation } from "./account-information";
|
||||
import { Button } from "./ui/button";
|
||||
|
||||
const initialState: VerifyDevicePaymentState = {
|
||||
message: "",
|
||||
success: false,
|
||||
fieldErrors: {},
|
||||
};
|
||||
|
||||
export default function DevicesToPay({
|
||||
payment,
|
||||
user,
|
||||
disabled,
|
||||
}: {
|
||||
payment?: Payment;
|
||||
user?: User;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const [state, formAction, isPending] = useActionState(
|
||||
verifyDevicePayment,
|
||||
initialState,
|
||||
);
|
||||
|
||||
// Handle toast notifications based on state changes
|
||||
useEffect(() => {
|
||||
if (state.success && state.message) {
|
||||
toast.success("Payment successful!", {
|
||||
closeButton: true,
|
||||
description: state.message,
|
||||
});
|
||||
} else if (
|
||||
!state.success &&
|
||||
state.message &&
|
||||
state.message !== initialState.message
|
||||
) {
|
||||
toast.error("Payment Verification Failed", {
|
||||
closeButton: true,
|
||||
description: state.message,
|
||||
});
|
||||
}
|
||||
}, [state]);
|
||||
|
||||
const devices = payment?.devices;
|
||||
if (devices?.length === 0) {
|
||||
return null;
|
||||
}
|
||||
// 100+(n−1)×75
|
||||
const walletBalance = user?.wallet_balance ?? 0;
|
||||
|
||||
const isWalletPayVisible = walletBalance > (payment?.amount ?? 0);
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<div className="p-2 flex flex-col gap-2">
|
||||
<h3 className="title-bg my-1 p-2 border border-dashed rounded-md font-semibold text-lg">
|
||||
{!payment?.paid ? "Devices to pay" : "Devices Paid"}
|
||||
</h3>
|
||||
<div className="flex flex-col gap-2">
|
||||
{devices?.map((device) => (
|
||||
<div
|
||||
key={device.id}
|
||||
className="bg-muted border rounded p-2 flex gap-2 items-center motion-preset-fade"
|
||||
>
|
||||
<div className="flex flex-col">
|
||||
<div className="text-sm font-medium motion-preset-slide-up">
|
||||
{device.name}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground motion-preset-slide-up motion-delay-100">
|
||||
{device.mac}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="m-2 flex items-end justify-end p-2 text-sm text-foreground border rounded">
|
||||
<Table>
|
||||
<TableCaption>
|
||||
{shouldShowPaymentInfo(payment) && (
|
||||
<div className="max-w-sm mx-auto">
|
||||
<p>Please send the following amount to the payment address</p>
|
||||
<AccountInfomation
|
||||
accName="Baraveli Dev"
|
||||
accountNo="90101400028321000"
|
||||
/>
|
||||
{payment?.paid ? (
|
||||
<Button
|
||||
size={"lg"}
|
||||
variant={"secondary"}
|
||||
disabled
|
||||
className="dark:text-green-200 text-green-900 bg-green-500/20 uppercase font-semibold"
|
||||
>
|
||||
Payment Verified
|
||||
</Button>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{isWalletPayVisible && (
|
||||
<form action={formAction}>
|
||||
<input
|
||||
type="hidden"
|
||||
name="paymentId"
|
||||
value={payment?.id ?? ""}
|
||||
/>
|
||||
<input type="hidden" name="method" value="WALLET" />
|
||||
<Button
|
||||
disabled={isPending}
|
||||
type="submit"
|
||||
variant={"secondary"}
|
||||
size={"lg"}
|
||||
className="w-full"
|
||||
>
|
||||
{isPending
|
||||
? "Processing payment..."
|
||||
: "Pay with wallet"}
|
||||
<Wallet />
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
<form action={formAction}>
|
||||
<input
|
||||
type="hidden"
|
||||
name="paymentId"
|
||||
value={payment?.id ?? ""}
|
||||
/>
|
||||
<input type="hidden" name="method" value="TRANSFER" />
|
||||
<Button
|
||||
disabled={isPending || disabled}
|
||||
type="submit"
|
||||
size={"lg"}
|
||||
className="mb-4 w-full"
|
||||
>
|
||||
{isPending ? "Processing payment..." : "I have paid"}
|
||||
{isPending ? (
|
||||
<Loader2 className="animate-spin" />
|
||||
) : (
|
||||
<BadgeDollarSign />
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</TableCaption>
|
||||
<TableBody className="">
|
||||
<TableRow>
|
||||
<TableCell>Payment created</TableCell>
|
||||
<TableCell className="text-right motion-preset-slide-up-sm">
|
||||
{new Date(payment?.created_at ?? "").toLocaleDateString(
|
||||
"en-US",
|
||||
{
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
minute: "2-digit",
|
||||
hour: "2-digit",
|
||||
second: "2-digit",
|
||||
},
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>Total Devices</TableCell>
|
||||
<TableCell className="text-right text-xl motion-preset-slide-up-sm motion-delay-75">
|
||||
{devices?.length}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>Duration</TableCell>
|
||||
<TableCell className="text-right text-xl motion-preset-slide-up-sm motion-delay-100">
|
||||
{payment?.number_of_months} Months
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
<TableFooter>
|
||||
<TableRow className="">
|
||||
<TableCell colSpan={1}>Total Due</TableCell>
|
||||
<TableCell className="text-right text-3xl font-bold motion-preset-slide-up-sm motion-delay-150">
|
||||
{payment?.amount?.toFixed(2)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableFooter>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
"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 { 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";
|
||||
export default function DeviceFilter() {
|
||||
const { replace } = useRouter();
|
||||
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [disabled, startTransition] = useTransition();
|
||||
const searchParams = useSearchParams();
|
||||
const pathname = usePathname();
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
|
||||
const [urlInputName] = useQueryState("name", {
|
||||
clearOnDefault: true,
|
||||
});
|
||||
const [urlInputMac] = useQueryState("mac", {
|
||||
clearOnDefault: true,
|
||||
});
|
||||
const [urlInputVendor] = useQueryState("vendor", {
|
||||
clearOnDefault: true,
|
||||
});
|
||||
|
||||
// Local state for input fields
|
||||
const [inputName, setInputName] = useState(urlInputName ?? "");
|
||||
const [inputMac, setInputMac] = useState(urlInputMac ?? "");
|
||||
const [inputVendor, setInputVendor] = useState(urlInputVendor ?? "");
|
||||
|
||||
// Map filter keys to their state setters
|
||||
const filterSetters: Record<
|
||||
string,
|
||||
React.Dispatch<React.SetStateAction<string>>
|
||||
> = {
|
||||
name: setInputName,
|
||||
mac: setInputMac,
|
||||
vendor: setInputVendor,
|
||||
};
|
||||
function handleSearch({
|
||||
name,
|
||||
mac,
|
||||
vendor,
|
||||
}: {
|
||||
name: string;
|
||||
mac: string;
|
||||
vendor: string;
|
||||
}) {
|
||||
if (name) params.set("name", name);
|
||||
else params.delete("name");
|
||||
if (mac) params.set("mac", mac);
|
||||
else params.delete("mac");
|
||||
if (vendor) params.set("vendor", vendor);
|
||||
else params.delete("vendor");
|
||||
params.set("page", "1");
|
||||
|
||||
startTransition(() => {
|
||||
replace(`${pathname}?${params.toString()}`);
|
||||
});
|
||||
}
|
||||
|
||||
const appliedFilters = searchParams
|
||||
.toString()
|
||||
.split("&")
|
||||
.filter((filter) => !filter.startsWith("page=") && filter);
|
||||
return (
|
||||
<div className="flex flex-col items-start justify-start gap-2 w-full">
|
||||
<Drawer open={isOpen} onOpenChange={setIsOpen}>
|
||||
<DrawerTrigger asChild>
|
||||
<Button
|
||||
className="w-full sm:w-48 flex items-end justify-between"
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
variant="outline"
|
||||
>
|
||||
Filter
|
||||
<ListFilter />
|
||||
</Button>
|
||||
</DrawerTrigger>
|
||||
<DrawerContent>
|
||||
<div className="mx-auto w-full max-w-3xl">
|
||||
<DrawerHeader>
|
||||
<DrawerTitle>Device Filters</DrawerTitle>
|
||||
<DrawerDescription asChild>
|
||||
<div>Select your desired filters here</div>
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
|
||||
<div className="grid sm:grid-cols-3 gap-4 p-4">
|
||||
<Input
|
||||
placeholder="Device name ..."
|
||||
value={inputName || searchParams.get("name") || ""}
|
||||
onChange={(e) => setInputName(e.target.value)}
|
||||
/>
|
||||
<Input
|
||||
placeholder="Device Mac address ..."
|
||||
value={inputMac || searchParams.get("mac") || ""}
|
||||
onChange={(e) => setInputMac(e.target.value)}
|
||||
/>
|
||||
<Input
|
||||
placeholder="Device vendor ..."
|
||||
value={inputVendor || searchParams.get("vendor") || ""}
|
||||
onChange={(e) => setInputVendor(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<DrawerFooter className="max-w-sm mx-auto">
|
||||
<Button
|
||||
onClick={() => {
|
||||
handleSearch({
|
||||
name: inputName ?? "",
|
||||
mac: inputMac ?? "",
|
||||
vendor: inputVendor ?? "",
|
||||
});
|
||||
}}
|
||||
>
|
||||
{disabled ? (
|
||||
<>
|
||||
<Loader2 className="ml-2 animate-spin" />
|
||||
</>
|
||||
) : (
|
||||
<>Apply Filters</>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setInputName("");
|
||||
setInputMac("");
|
||||
setInputVendor("");
|
||||
replace(pathname);
|
||||
}}
|
||||
>
|
||||
Clear Filters
|
||||
</Button>
|
||||
|
||||
<DrawerClose asChild>
|
||||
<Button variant="outline">Cancel</Button>
|
||||
</DrawerClose>
|
||||
</DrawerFooter>
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
<div className="flex gap-2 w-fit flex-wrap">
|
||||
{appliedFilters.map((filter) => (
|
||||
<Badge
|
||||
aria-disabled={disabled}
|
||||
variant={"outline"}
|
||||
className={cn("flex p-2 gap-2 items-center justify-between", {
|
||||
"opacity-50 pointer-events-none": disabled,
|
||||
})}
|
||||
key={filter}
|
||||
>
|
||||
<span className="text-md">{prettyPrintFilter(filter)}</span>
|
||||
{disabled ? (
|
||||
<Loader2 className="animate-spin" size={16} />
|
||||
) : (
|
||||
<X
|
||||
className="bg-sarLinkOrange/50 rounded-full p-1 hover:cursor-pointer hover:ring ring-sarLinkOrange"
|
||||
size={16}
|
||||
onClick={() => {
|
||||
const key = filter.split("=")[0];
|
||||
params.delete(key);
|
||||
|
||||
// Use the mapping to clear the correct input state
|
||||
filterSetters[key]?.("");
|
||||
|
||||
startTransition(() => {
|
||||
replace(`${pathname}?${params.toString()}`);
|
||||
});
|
||||
}}
|
||||
>
|
||||
Remove
|
||||
</X>
|
||||
)}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function prettyPrintFilter(filter: string) {
|
||||
const [key, value] = filter.split("=");
|
||||
switch (key) {
|
||||
case "name":
|
||||
return (
|
||||
<p>
|
||||
Device Name: <span className="text-muted-foreground">{value}</span>
|
||||
</p>
|
||||
);
|
||||
case "mac":
|
||||
return (
|
||||
<p>
|
||||
MAC Address: <span className="text-muted-foreground">{value}</span>
|
||||
</p>
|
||||
);
|
||||
case "vendor":
|
||||
return (
|
||||
<p>
|
||||
Vendor: <span className="text-muted-foreground">{value}</span>
|
||||
</p>
|
||||
);
|
||||
default:
|
||||
return filter;
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
"use client";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import { useState, useTransition } from "react";
|
||||
|
||||
interface FilterOption {
|
||||
value: string;
|
||||
label: string;
|
||||
icon: React.ReactNode;
|
||||
}
|
||||
|
||||
interface FilterProps {
|
||||
options: FilterOption[];
|
||||
defaultOption: string;
|
||||
queryParamKey: string;
|
||||
}
|
||||
|
||||
export default function Filter({
|
||||
options,
|
||||
defaultOption,
|
||||
queryParamKey,
|
||||
}: FilterProps) {
|
||||
const [selectedOption, setSelectedOption] = useState(defaultOption);
|
||||
const searchParams = useSearchParams();
|
||||
const { replace } = useRouter();
|
||||
const pathname = usePathname();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
function handleFilterChange(value: string) {
|
||||
setSelectedOption(value);
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
|
||||
params.set(queryParamKey, value);
|
||||
params.set("page", "1");
|
||||
|
||||
startTransition(() => {
|
||||
replace(`${pathname}?${params.toString()}`);
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn(isPending && "animate-pulse")}>
|
||||
<Select
|
||||
disabled={isPending}
|
||||
value={selectedOption}
|
||||
onValueChange={(val) => handleFilterChange(val)}
|
||||
>
|
||||
<SelectTrigger className="w-auto">
|
||||
<SelectValue>
|
||||
{options.find((option) => option.value === selectedOption)?.label}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent align="end">
|
||||
{options.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
<div className="flex items-center gap-4">
|
||||
{option.icon}
|
||||
<span>{option.label}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,621 +0,0 @@
|
||||
"use client";
|
||||
import { ListFilter, Loader2, X } from "lucide-react";
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect, useMemo, useState, useTransition } from "react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import {
|
||||
Drawer,
|
||||
DrawerClose,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerFooter,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
DrawerTrigger,
|
||||
} from "@/components/ui/drawer";
|
||||
import { DualRangeSlider } from "@/components/ui/dual-range-slider";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { RadioGroup, RadioGroupItem } from "./ui/radio-group";
|
||||
|
||||
interface CheckboxGroupProps {
|
||||
label: string;
|
||||
options: Array<{ value: string; label: string }>;
|
||||
selectedValues: string[];
|
||||
onChange: (values: string[]) => void;
|
||||
name: string;
|
||||
}
|
||||
|
||||
const CheckboxGroup: React.FC<CheckboxGroupProps> = ({
|
||||
label,
|
||||
options,
|
||||
selectedValues,
|
||||
onChange,
|
||||
name,
|
||||
}) => {
|
||||
const handleCheckedChange = (value: string, checked: boolean) => {
|
||||
if (checked) {
|
||||
onChange([...selectedValues, value]);
|
||||
} else {
|
||||
onChange(selectedValues.filter((v) => v !== value));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 p-2 border rounded-md">
|
||||
<Label className="font-semibold text-sm">{label}</Label>
|
||||
<div className="flex flex-col gap-2">
|
||||
{options.map((option) => (
|
||||
<div
|
||||
key={`${name}-${option.value}`}
|
||||
className="flex items-center space-x-2"
|
||||
>
|
||||
<Checkbox
|
||||
id={`${name}-${option.value}`}
|
||||
checked={selectedValues.includes(option.value)}
|
||||
onCheckedChange={(checked) =>
|
||||
handleCheckedChange(option.value, !!checked)
|
||||
}
|
||||
/>
|
||||
<Label htmlFor={`${name}-${option.value}`}>{option.label}</Label>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
type FilterOption = { value: string; label: string };
|
||||
|
||||
type FilterInputConfig<TKey extends string> =
|
||||
| {
|
||||
name: TKey;
|
||||
label: string;
|
||||
placeholder: string;
|
||||
type: "string" | "number";
|
||||
}
|
||||
| {
|
||||
name: TKey;
|
||||
label: string;
|
||||
type: "checkbox-group";
|
||||
options: FilterOption[];
|
||||
serialize?: (values: string[]) => string;
|
||||
deserialize?: (urlValue: string) => string[];
|
||||
}
|
||||
| {
|
||||
name: TKey;
|
||||
label: string;
|
||||
type: "radio-group";
|
||||
options: FilterOption[];
|
||||
}
|
||||
| {
|
||||
name: TKey;
|
||||
label: string;
|
||||
type: "dual-range-slider";
|
||||
min: number;
|
||||
max: number;
|
||||
step?: number;
|
||||
sliderLabel?: string;
|
||||
formatLabel?: (value: number | undefined) => React.ReactNode;
|
||||
};
|
||||
|
||||
// Utility type to extract the config for a specific key from the array
|
||||
type GetConfigForKey<
|
||||
TKey,
|
||||
TConfigArray extends FilterInputConfig<string>[],
|
||||
> = TConfigArray extends ReadonlyArray<infer U>
|
||||
? U extends FilterInputConfig<string> & { name: TKey }
|
||||
? U
|
||||
: never
|
||||
: never;
|
||||
|
||||
// This type maps filter keys to their appropriate value types (string or string[])
|
||||
type FilterValues<
|
||||
TFilterKeys extends string,
|
||||
TInputs extends FilterInputConfig<string>[],
|
||||
> = {
|
||||
[K in TFilterKeys]: GetConfigForKey<K, TInputs> extends {
|
||||
type: "checkbox-group";
|
||||
}
|
||||
? string[]
|
||||
: GetConfigForKey<K, TInputs> extends { type: "radio-group" }
|
||||
? string
|
||||
: GetConfigForKey<K, TInputs> extends { type: "dual-range-slider" }
|
||||
? number[]
|
||||
: string;
|
||||
};
|
||||
|
||||
// Default serialization/deserialization for checkbox-group if not provided
|
||||
const defaultSerialize = (values: string[]) => values.join(",");
|
||||
const defaultDeserialize = (urlValue: string) =>
|
||||
urlValue ? urlValue.split(",") : [];
|
||||
|
||||
// --- Component Props ---
|
||||
interface DynamicFilterProps<
|
||||
TFilterKeys extends string,
|
||||
TInputs extends FilterInputConfig<TFilterKeys>[],
|
||||
> {
|
||||
inputs: TInputs;
|
||||
title?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export default function DynamicFilter<
|
||||
TFilterKeys extends string,
|
||||
TInputs extends FilterInputConfig<TFilterKeys>[],
|
||||
>({
|
||||
inputs,
|
||||
title = "Filters",
|
||||
description = "Select your desired filters here",
|
||||
}: DynamicFilterProps<TFilterKeys, TInputs>) {
|
||||
const { replace } = useRouter();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [disabled, startTransition] = useTransition();
|
||||
const searchParams = useSearchParams();
|
||||
const pathname = usePathname();
|
||||
|
||||
// Use a ref or memoized value for URLSearchParams to avoid re-creations
|
||||
// and ensure it's always based on the latest searchParams.
|
||||
const currentParams = useMemo(
|
||||
() => new URLSearchParams(searchParams.toString()),
|
||||
[searchParams],
|
||||
);
|
||||
|
||||
// Initialize local state for input values based on URL
|
||||
const initialInputState = useMemo(() => {
|
||||
const initialState: Partial<FilterValues<TFilterKeys, TInputs>> = {};
|
||||
for (const input of inputs) {
|
||||
const urlValue = searchParams.get(input.name);
|
||||
if (input.type === "checkbox-group") {
|
||||
const deserialize = input.deserialize || defaultDeserialize;
|
||||
(initialState as FilterValues<TFilterKeys, TInputs>)[input.name] =
|
||||
deserialize(urlValue || "") as FilterValues<
|
||||
TFilterKeys,
|
||||
TInputs
|
||||
>[typeof input.name];
|
||||
} else if (input.type === "dual-range-slider") {
|
||||
const minValue = searchParams.get(`${input.name}_min`);
|
||||
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];
|
||||
} else {
|
||||
(initialState as FilterValues<TFilterKeys, TInputs>)[input.name] =
|
||||
(urlValue || "") as FilterValues<
|
||||
TFilterKeys,
|
||||
TInputs
|
||||
>[typeof input.name];
|
||||
}
|
||||
}
|
||||
return initialState as FilterValues<TFilterKeys, TInputs>;
|
||||
}, [inputs, searchParams]); // Re-initialize if inputs config or URL searchParams change
|
||||
|
||||
const [inputValues, setInputValues] =
|
||||
useState<FilterValues<TFilterKeys, TInputs>>(initialInputState);
|
||||
|
||||
// Update local state if URL searchParams change while drawer is closed
|
||||
// This is important if filters are applied externally or on page load
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
setInputValues(initialInputState);
|
||||
}
|
||||
}, [isOpen, initialInputState]);
|
||||
|
||||
// Handler for text/number input changes
|
||||
const handleTextOrNumberInputChange =
|
||||
(name: TFilterKeys) => (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setInputValues((prev) => ({
|
||||
...prev,
|
||||
[name]: e.target.value,
|
||||
}));
|
||||
};
|
||||
|
||||
// Handler for checkbox group changes
|
||||
const handleCheckboxGroupChange =
|
||||
(name: TFilterKeys) => (values: string[]) => {
|
||||
setInputValues((prev) => ({
|
||||
...prev,
|
||||
[name]: values,
|
||||
}));
|
||||
};
|
||||
|
||||
// Handler for dual range slider changes
|
||||
const handleDualRangeChange = (name: TFilterKeys) => (values: number[]) => {
|
||||
setInputValues((prev) => ({
|
||||
...prev,
|
||||
[name]: values,
|
||||
}));
|
||||
};
|
||||
|
||||
// Handles applying all filters
|
||||
const handleApplyFilters = () => {
|
||||
const newParams = new URLSearchParams(currentParams.toString()); // Start fresh with current params
|
||||
|
||||
for (const input of inputs) {
|
||||
const value = inputValues[input.name];
|
||||
|
||||
if (input.type === "checkbox-group") {
|
||||
const serialize = input.serialize || defaultSerialize;
|
||||
const serializedValue = serialize(value as string[]);
|
||||
if (serializedValue) {
|
||||
newParams.set(input.name, serializedValue);
|
||||
} else {
|
||||
newParams.delete(input.name);
|
||||
}
|
||||
} 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)
|
||||
) {
|
||||
newParams.set(`${input.name}_min`, rangeValues[0].toString());
|
||||
newParams.set(`${input.name}_max`, rangeValues[1].toString());
|
||||
} else {
|
||||
newParams.delete(`${input.name}_min`);
|
||||
newParams.delete(`${input.name}_max`);
|
||||
}
|
||||
} else {
|
||||
// String/Number inputs
|
||||
if (value) {
|
||||
newParams.set(input.name, value as string);
|
||||
} else {
|
||||
newParams.delete(input.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
newParams.set("page", "1");
|
||||
|
||||
startTransition(() => {
|
||||
replace(`${pathname}?${newParams.toString()}`);
|
||||
setIsOpen(false);
|
||||
});
|
||||
};
|
||||
|
||||
// Handles clearing all filters
|
||||
const handleClearFilters = () => {
|
||||
// Reset local input values
|
||||
const clearedInputState: Partial<FilterValues<TFilterKeys, TInputs>> = {};
|
||||
for (const input of inputs) {
|
||||
if (input.type === "checkbox-group") {
|
||||
(clearedInputState as FilterValues<TFilterKeys, TInputs>)[
|
||||
input.name as TFilterKeys
|
||||
] = [] as FilterValues<TFilterKeys, TInputs>[typeof input.name];
|
||||
} 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"
|
||||
) {
|
||||
(clearedInputState as FilterValues<TFilterKeys, TInputs>)[
|
||||
input.name as TFilterKeys
|
||||
] = "" as FilterValues<TFilterKeys, TInputs>[typeof input.name];
|
||||
}
|
||||
}
|
||||
setInputValues(clearedInputState as FilterValues<TFilterKeys, TInputs>);
|
||||
|
||||
startTransition(() => {
|
||||
replace(pathname);
|
||||
setIsOpen(false);
|
||||
});
|
||||
};
|
||||
|
||||
// Dynamically constructs applied filters for badges
|
||||
const appliedFilters = useMemo(() => {
|
||||
const filters: Array<{
|
||||
key: TFilterKeys;
|
||||
value: string | string[] | number[];
|
||||
label: string;
|
||||
config: FilterInputConfig<TFilterKeys>;
|
||||
}> = [];
|
||||
|
||||
for (const input of inputs) {
|
||||
if (input.type === "dual-range-slider") {
|
||||
const minValue = searchParams.get(`${input.name}_min`);
|
||||
const maxValue = searchParams.get(`${input.name}_max`);
|
||||
if (minValue && maxValue) {
|
||||
const parsedMin = Number(minValue);
|
||||
const parsedMax = Number(maxValue);
|
||||
// Only show as applied filter if values are different from defaults
|
||||
if (parsedMin !== input.min || parsedMax !== input.max) {
|
||||
filters.push({
|
||||
key: input.name,
|
||||
value: [parsedMin, parsedMax],
|
||||
label: input.label,
|
||||
config: input,
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const urlValue = searchParams.get(input.name);
|
||||
if (urlValue) {
|
||||
if (input.type === "checkbox-group") {
|
||||
const deserialize = input.deserialize || defaultDeserialize;
|
||||
const deserialized = deserialize(urlValue);
|
||||
if (deserialized.length > 0) {
|
||||
filters.push({
|
||||
key: input.name,
|
||||
value: deserialized,
|
||||
label: input.label,
|
||||
config: input,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
filters.push({
|
||||
key: input.name,
|
||||
value: urlValue,
|
||||
label: input.label,
|
||||
config: input,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return filters;
|
||||
}, [searchParams, inputs]);
|
||||
|
||||
// Dynamic `prettyPrintFilter` for badges
|
||||
const prettyPrintFilter = (
|
||||
_key: TFilterKeys,
|
||||
value: string | string[] | number[],
|
||||
config: FilterInputConfig<TFilterKeys>,
|
||||
) => {
|
||||
if (config.type === "checkbox-group") {
|
||||
const labels = (value as string[])
|
||||
.map((v) => config.options.find((opt) => opt.value === v)?.label || v)
|
||||
.join(", ");
|
||||
return (
|
||||
<p>
|
||||
{config.label.replace(/%20/g, " ")}:{" "}
|
||||
<span className="text-muted-foreground">{labels}</span>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (config.type === "dual-range-slider") {
|
||||
const rangeValues = value as number[];
|
||||
const formatLabel =
|
||||
config.formatLabel ||
|
||||
((val: number | undefined) => val?.toString() || "");
|
||||
return (
|
||||
<p>
|
||||
{config.label}:{" "}
|
||||
<span className="text-muted-foreground">
|
||||
{formatLabel(rangeValues[0])} - {formatLabel(rangeValues[1])}
|
||||
</span>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (config.type === "radio-group") {
|
||||
const stringValue = value as string;
|
||||
// For true/false values, display the label instead of the value
|
||||
if (stringValue === "true" || stringValue === "false") {
|
||||
const option = config.options.find((opt) => opt.value === stringValue);
|
||||
const displayValue = option?.label || stringValue;
|
||||
return (
|
||||
<p>
|
||||
{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>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<p>
|
||||
{config.label}: <span className="text-muted-foreground">{value}</span>
|
||||
</p>
|
||||
);
|
||||
};
|
||||
|
||||
// Handles removing an individual filter
|
||||
const handleRemoveFilter = (keyToRemove: TFilterKeys) => {
|
||||
const newParams = new URLSearchParams(currentParams.toString());
|
||||
|
||||
// Clear the specific input's local state
|
||||
const inputConfig = inputs.find((input) => input.name === keyToRemove);
|
||||
|
||||
if (inputConfig?.type === "dual-range-slider") {
|
||||
newParams.delete(`${keyToRemove}_min`);
|
||||
newParams.delete(`${keyToRemove}_max`);
|
||||
setInputValues((prev) => ({
|
||||
...prev,
|
||||
[keyToRemove]: [inputConfig.min, inputConfig.max],
|
||||
}));
|
||||
} else {
|
||||
newParams.delete(keyToRemove);
|
||||
setInputValues((prev) => ({
|
||||
...prev,
|
||||
[keyToRemove]: inputConfig?.type === "checkbox-group" ? [] : "",
|
||||
}));
|
||||
}
|
||||
|
||||
newParams.set("page", "1"); // Reset page after removing a filter
|
||||
|
||||
startTransition(() => {
|
||||
replace(`${pathname}?${newParams.toString()}`);
|
||||
});
|
||||
};
|
||||
|
||||
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 font-barlow sm:w-48 flex items-end justify-between"
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
variant="outline"
|
||||
>
|
||||
Filter
|
||||
<ListFilter />
|
||||
</Button>
|
||||
</DrawerTrigger>
|
||||
<DrawerContent>
|
||||
<div className="mx-auto w-full max-w-3xl">
|
||||
<DrawerHeader>
|
||||
<DrawerTitle>{title}</DrawerTitle>
|
||||
<DrawerDescription asChild>
|
||||
<div>{description}</div>
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
|
||||
<div className="grid sm:grid-cols-3 gap-4 p-4">
|
||||
{inputs.map((input) => {
|
||||
switch (input.type) {
|
||||
case "string":
|
||||
case "number":
|
||||
return (
|
||||
<Input
|
||||
key={input.name}
|
||||
placeholder={input.placeholder}
|
||||
value={inputValues[input.name] as string}
|
||||
onChange={handleTextOrNumberInputChange(input.name)}
|
||||
type={input.type}
|
||||
/>
|
||||
);
|
||||
case "checkbox-group":
|
||||
return (
|
||||
<CheckboxGroup
|
||||
key={input.name}
|
||||
name={input.name}
|
||||
label={input.label}
|
||||
options={input.options}
|
||||
selectedValues={inputValues[input.name] as string[]}
|
||||
onChange={handleCheckboxGroupChange(input.name)}
|
||||
/>
|
||||
);
|
||||
case "dual-range-slider":
|
||||
return (
|
||||
<div
|
||||
key={input.name}
|
||||
className="px-2 w-full flex flex-col gap-2 p-2 border rounded-md"
|
||||
>
|
||||
<Label className="font-semibold text-sm">
|
||||
{input.label}
|
||||
</Label>
|
||||
<div className="px-3 py-2 mt-5">
|
||||
<DualRangeSlider
|
||||
label={(value) => (
|
||||
<span className="text-xs">
|
||||
{value}
|
||||
{input.sliderLabel}
|
||||
</span>
|
||||
)}
|
||||
value={inputValues[input.name] as number[]}
|
||||
onValueChange={handleDualRangeChange(input.name)}
|
||||
min={input.min}
|
||||
max={input.max}
|
||||
step={input.step || 1}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
case "radio-group":
|
||||
return (
|
||||
<div
|
||||
key={input.name}
|
||||
className="flex flex-col gap-2 p-2 border rounded-md"
|
||||
>
|
||||
<Label className="font-semibold text-sm">
|
||||
{input.label}
|
||||
</Label>
|
||||
<RadioGroup
|
||||
value={inputValues[input.name] as string}
|
||||
onValueChange={(value) =>
|
||||
setInputValues((prev) => ({
|
||||
...prev,
|
||||
[input.name]: value,
|
||||
}))
|
||||
}
|
||||
>
|
||||
{input.options.map((option) => (
|
||||
<div
|
||||
key={`${input.name}-${option.value}`}
|
||||
className="flex items-center space-x-2"
|
||||
>
|
||||
<RadioGroupItem
|
||||
value={option.value}
|
||||
id={`${input.name}-${option.value}`}
|
||||
/>
|
||||
<Label htmlFor={`${input.name}-${option.value}`}>
|
||||
{option.label}
|
||||
</Label>
|
||||
</div>
|
||||
))}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
})}
|
||||
</div>
|
||||
<DrawerFooter className="max-w-sm mx-auto">
|
||||
<Button onClick={handleApplyFilters} disabled={disabled}>
|
||||
{disabled ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Applying...
|
||||
</>
|
||||
) : (
|
||||
<>Apply Filters</>
|
||||
)}
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={handleClearFilters}>
|
||||
Clear Filters
|
||||
</Button>
|
||||
<DrawerClose asChild>
|
||||
<Button variant="outline">Cancel</Button>
|
||||
</DrawerClose>
|
||||
</DrawerFooter>
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
<div className="flex gap-2 w-fit flex-wrap">
|
||||
{appliedFilters.map((filter) => (
|
||||
<Badge
|
||||
aria-disabled={disabled}
|
||||
variant={"outline"}
|
||||
className={cn("flex p-2 gap-2 items-center justify-between", {
|
||||
"opacity-50 pointer-events-none": disabled,
|
||||
})}
|
||||
key={filter.key}
|
||||
>
|
||||
<span className="text-md">
|
||||
{prettyPrintFilter(filter.key, filter.value, filter.config)}
|
||||
</span>
|
||||
{disabled ? (
|
||||
<Loader2 className="animate-spin" size={16} />
|
||||
) : (
|
||||
<X
|
||||
className="bg-sarLinkOrange/50 rounded-full p-1 hover:cursor-pointer hover:ring ring-sarLinkOrange"
|
||||
size={16}
|
||||
onClick={() => handleRemoveFilter(filter.key)}
|
||||
>
|
||||
Remove
|
||||
</X>
|
||||
)}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
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";
|
||||
|
||||
export function GetMacAccordion() {
|
||||
return (
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="item-1">
|
||||
<AccordionTrigger>How do I find my MAC Address?</AccordionTrigger>
|
||||
<AccordionContent className="flex flex-col gap-4 text-start">
|
||||
<p>
|
||||
A MAC (Media Access Control) address is a unique identifier assigned
|
||||
to a device`'`s network. It is used to identify the device on a
|
||||
network, helping to differentiate devices on a network.
|
||||
</p>
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="iphone">
|
||||
<AccordionTrigger>iPhone</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
Settings ➜ General ➜ About ➜ Wi-Fi Address
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
<AccordionItem value="redmi">
|
||||
<AccordionTrigger>Redmi</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
Settings ➜ About ➜ Wi-Fi MAC Address
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
<AccordionItem value="samsung">
|
||||
<AccordionTrigger>Samsung</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
Settings ➜ About phone ➜ Status Information ➜ Wi-Fi MAC Address
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
<AccordionItem value="windows">
|
||||
<AccordionTrigger>Windows Laptop</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
Settings ➜ Network and Internet ➜ Wi-Fi ➜ Hardware Properties ➜
|
||||
Physical address (MAC):
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
<AccordionItem value="other">
|
||||
<AccordionTrigger>Other Device</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<p>Please contact SAR Link for assistance.</p>
|
||||
<Link href="tel:+9609198026">
|
||||
<Button className="mt-4">
|
||||
<PhoneIcon className="mr-2" />
|
||||
9198026
|
||||
</Button>
|
||||
</Link>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import { CheckCheck, X } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export default function InputReadOnly({
|
||||
label,
|
||||
value,
|
||||
labelClassName,
|
||||
className,
|
||||
showCheck = true,
|
||||
checkTrue = false,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
labelClassName?: string;
|
||||
className?: string;
|
||||
showCheck?: boolean;
|
||||
checkTrue?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"relative flex items-center justify-between rounded-lg border border-input bg-background shadow-sm shadow-black/5 transition-shadow focus-within:border-ring focus-within:outline-none focus-within:ring-[3px] focus-within:ring-ring/20 has-disabled:cursor-not-allowed has-disabled:opacity-80 [&:has(input:is(:disabled))_*]:pointer-events-none col-span-2 sm:col-span-1",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div>
|
||||
<label
|
||||
htmlFor="input-33"
|
||||
className={cn("block px-3 pt-2 text-xs font-medium", labelClassName)}
|
||||
>
|
||||
{label}
|
||||
</label>
|
||||
<input
|
||||
id="input-33"
|
||||
className="flex h-10 w-full bg-transparent px-3 pb-2 text-sm text-foreground placeholder:text-muted-foreground/70 focus-visible:outline-none"
|
||||
placeholder={value}
|
||||
disabled
|
||||
value={value}
|
||||
type="text"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{showCheck && (
|
||||
<div>
|
||||
{checkTrue ? (
|
||||
<CheckCheck className="mx-4 text-green-500" />
|
||||
) : (
|
||||
<X className="mx-4 text-red-500" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import { Minus, Plus } from "lucide-react";
|
||||
import { useEffect } from "react";
|
||||
import {
|
||||
Button,
|
||||
Group,
|
||||
Input,
|
||||
Label,
|
||||
NumberField,
|
||||
} from "react-aria-components";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export default function NumberInput({
|
||||
maxAllowed,
|
||||
label,
|
||||
value = 100,
|
||||
onChange,
|
||||
className,
|
||||
isDisabled,
|
||||
}: {
|
||||
maxAllowed?: number;
|
||||
label: string;
|
||||
value?: number;
|
||||
onChange: (value: number) => void;
|
||||
className?: string;
|
||||
isDisabled?: boolean;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
if (maxAllowed) {
|
||||
if (value > maxAllowed) {
|
||||
onChange(maxAllowed);
|
||||
}
|
||||
}
|
||||
}, [maxAllowed, value, onChange]);
|
||||
|
||||
return (
|
||||
<NumberField
|
||||
isDisabled={isDisabled}
|
||||
className={cn(className)}
|
||||
value={value}
|
||||
minValue={0}
|
||||
onChange={onChange}
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm font-medium text-foreground">{label}</Label>
|
||||
<Group className="relative inline-flex h-9 w-full items-center overflow-hidden whitespace-nowrap rounded-lg border border-input text-sm shadow-sm shadow-black/5 transition-shadow data-[focus-within]:border-ring data-disabled:opacity-50 data-focus-within:outline-none data-focus-within:ring-[3px] data-[focus-within]:ring-ring/20">
|
||||
<Button
|
||||
slot="decrement"
|
||||
className="-ms-px flex aspect-square h-[inherit] items-center justify-center rounded-s-lg border border-input bg-background text-sm text-muted-foreground/80 transition-shadow hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
<Minus size={16} strokeWidth={2} aria-hidden="true" />
|
||||
</Button>
|
||||
<Input className="w-full grow bg-background px-3 py-2 text-center text-base tabular-nums text-foreground focus:outline-none" />
|
||||
<Button
|
||||
slot="increment"
|
||||
className="-me-px flex aspect-square h-[inherit] items-center justify-center rounded-e-lg border border-input bg-background text-sm text-muted-foreground/80 transition-shadow hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
<Plus size={16} strokeWidth={2} aria-hidden="true" />
|
||||
</Button>
|
||||
</Group>
|
||||
</div>
|
||||
</NumberField>
|
||||
);
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
"use client";
|
||||
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;
|
||||
currentPage: number;
|
||||
maxVisible?: number;
|
||||
};
|
||||
|
||||
export default function Pagination({
|
||||
totalPages,
|
||||
currentPage,
|
||||
maxVisible = 4,
|
||||
}: PaginationProps) {
|
||||
const searchParams = useSearchParams();
|
||||
const activePage = searchParams.get("page") ?? 1;
|
||||
const router = useRouter();
|
||||
|
||||
const [queryParams, setQueryParams] = useState<{ [key: string]: string }>({});
|
||||
|
||||
useEffect(() => {
|
||||
const params = Object.fromEntries(
|
||||
Array.from(searchParams.entries()).filter(([key]) => key !== "page"),
|
||||
);
|
||||
setQueryParams(params);
|
||||
}, [searchParams]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!searchParams.has("page")) {
|
||||
router.replace(`?page=1${IncludeQueries()}`);
|
||||
}
|
||||
});
|
||||
|
||||
function IncludeQueries() {
|
||||
return Object.entries(queryParams)
|
||||
.map(([key, value]) => `&${key}=${value}`)
|
||||
.join("");
|
||||
}
|
||||
|
||||
const generatePageNumbers = (): (number | string)[] => {
|
||||
const halfVisible = Math.floor(maxVisible / 2);
|
||||
let startPage = Math.max(currentPage - halfVisible, 1);
|
||||
const endPage = Math.min(startPage + maxVisible - 1, totalPages);
|
||||
|
||||
if (endPage - startPage + 1 < maxVisible) {
|
||||
startPage = Math.max(endPage - maxVisible + 1, 1);
|
||||
}
|
||||
|
||||
const pageNumbers: (number | string)[] = [];
|
||||
|
||||
if (startPage > 1) {
|
||||
pageNumbers.push(1);
|
||||
if (startPage > 2) pageNumbers.push("...");
|
||||
}
|
||||
|
||||
for (let i = startPage; i <= endPage; i++) {
|
||||
pageNumbers.push(i);
|
||||
}
|
||||
|
||||
if (endPage < totalPages) {
|
||||
if (endPage < totalPages - 1) pageNumbers.push("...");
|
||||
pageNumbers.push(totalPages);
|
||||
}
|
||||
|
||||
return pageNumbers;
|
||||
};
|
||||
|
||||
const pageNumbers = generatePageNumbers();
|
||||
|
||||
if (totalPages <= 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center space-x-2 my-4">
|
||||
{currentPage > 1 && (
|
||||
<Link href={`?page=${Number(currentPage) - 1}${IncludeQueries()}`}>
|
||||
<Button variant="secondary" className="flex items-center gap-2">
|
||||
<ArrowLeftIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{pageNumbers.map((page) => (
|
||||
<React.Fragment key={`${page}`}>
|
||||
{typeof page === "number" ? (
|
||||
<Link href={`?page=${page}${IncludeQueries()}`}>
|
||||
<Button
|
||||
variant={Number(activePage) === page ? "default" : "outline"}
|
||||
>
|
||||
{page}
|
||||
</Button>
|
||||
</Link>
|
||||
) : (
|
||||
<span className="px-2">...</span>
|
||||
)}
|
||||
</React.Fragment>
|
||||
))}
|
||||
|
||||
{currentPage < totalPages && (
|
||||
<Link href={`?page=${Number(currentPage) + 1}${IncludeQueries()}`}>
|
||||
<Button variant="secondary" className="flex items-center gap-2">
|
||||
<ArrowRightIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,284 +0,0 @@
|
||||
import { Calendar } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getPayments } from "@/actions/payment";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import type { Payment } from "@/lib/backend-types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
import Pagination from "./pagination";
|
||||
import { Badge } from "./ui/badge";
|
||||
import { Button } from "./ui/button";
|
||||
import { Separator } from "./ui/separator";
|
||||
|
||||
export async function PaymentsTable({
|
||||
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;
|
||||
const apiParams: Record<string, string | number | undefined> = {};
|
||||
for (const [key, value] of Object.entries(resolvedParams)) {
|
||||
if (value !== undefined && value !== "") {
|
||||
apiParams[key] = typeof value === "number" ? value : String(value);
|
||||
}
|
||||
}
|
||||
apiParams.limit = limit;
|
||||
apiParams.offset = offset;
|
||||
const [error, payments] = await tryCatch(getPayments(apiParams));
|
||||
|
||||
if (error) {
|
||||
if (error.message.includes("Unauthorized")) {
|
||||
redirect("/auth/signin");
|
||||
} else {
|
||||
return <pre>{JSON.stringify(error, null, 2)}</pre>;
|
||||
}
|
||||
}
|
||||
const { data, meta } = payments;
|
||||
return (
|
||||
<div>
|
||||
{data?.length === 0 ? (
|
||||
<div className="h-[calc(100svh-400px)] text-muted-foreground flex flex-col items-center justify-center my-4">
|
||||
<h3>No Payments.</h3>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="hidden sm:block">
|
||||
<Table className="overflow-scroll">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Details</TableHead>
|
||||
<TableHead>Duration</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Amount</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody className="overflow-scroll">
|
||||
{payments?.data?.map((payment) => (
|
||||
<TableRow className="motion-preset-fade-md" key={payment.id}>
|
||||
<TableCell>
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col items-start border rounded p-2",
|
||||
payment?.paid
|
||||
? "bg-green-500/10 border-dashed border-green-500"
|
||||
: payment?.is_expired
|
||||
? "bg-gray-500/10 border-dashed border-gray-500 dark:border-gray-500/50"
|
||||
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar size={16} opacity={0.5} />
|
||||
<span className="text-muted-foreground">
|
||||
{new Date(payment.created_at).toLocaleDateString(
|
||||
"en-US",
|
||||
{
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
minute: "2-digit",
|
||||
hour: "2-digit",
|
||||
timeZone: "Indian/Maldives", // Force consistent timezone
|
||||
},
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<Link
|
||||
className="font-medium hover:underline"
|
||||
href={`/payments/${payment.id}`}
|
||||
>
|
||||
<Button size={"sm"} variant="outline">
|
||||
View Details
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
|
||||
<h3 className="text-sm font-medium">Devices</h3>
|
||||
<ol className="list-disc list-inside text-sm">
|
||||
{payment.devices.map((device) => (
|
||||
<li
|
||||
key={device.id}
|
||||
className="text-sm text-muted-foreground"
|
||||
>
|
||||
{device.name}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
|
||||
<TableCell className="font-medium">
|
||||
{payment.number_of_months} Months
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span className="font-semibold pr-2">
|
||||
{payment.paid ? (
|
||||
<Badge
|
||||
className={cn(
|
||||
payment.status === "PENDING"
|
||||
? "bg-yellow-100 text-yellow-700 dark:bg-yellow-700 dark:text-yellow-100"
|
||||
: "bg-green-100 dark:bg-green-700",
|
||||
)}
|
||||
variant="outline"
|
||||
>
|
||||
{payment.status}
|
||||
</Badge>
|
||||
) : payment.is_expired ? (
|
||||
<Badge>Expired</Badge>
|
||||
) : (
|
||||
<Badge variant="outline">{payment.status}</Badge>
|
||||
)}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span className="font-semibold pr-2">
|
||||
{payment.amount.toFixed(2)}
|
||||
</span>
|
||||
MVR
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
<TableFooter>
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="text-muted-foreground">
|
||||
{meta?.total === 1 ? (
|
||||
<p className="text-center">
|
||||
Total {meta?.total} payment.
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-center">
|
||||
Total {meta?.total} payments.
|
||||
</p>
|
||||
)}{" "}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableFooter>
|
||||
</Table>
|
||||
<Pagination
|
||||
totalPages={meta.last_page}
|
||||
currentPage={meta.current_page}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:hidden block">
|
||||
{data.map((payment) => (
|
||||
<MobilePaymentDetails key={payment.id} payment={payment} />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function MobilePaymentDetails({
|
||||
payment,
|
||||
isAdmin = false,
|
||||
}: {
|
||||
payment: Payment;
|
||||
isAdmin?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col items-start border rounded p-2 my-2 motion-preset-fade-md",
|
||||
payment?.paid
|
||||
? "bg-green-500/10 border-dashed border-green-500"
|
||||
: payment?.is_expired
|
||||
? "bg-gray-500/10 border-dashed border-gray-500 dark:border-gray-500/50"
|
||||
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar size={16} opacity={0.5} />
|
||||
<span className="text-muted-foreground text-sm">
|
||||
{new Date(payment.created_at).toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
minute: "2-digit",
|
||||
hour: "2-digit",
|
||||
timeZone: "Indian/Maldives", // Force consistent timezone
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<Link
|
||||
className="font-medium hover:underline"
|
||||
href={`/payments/${payment.id}`}
|
||||
>
|
||||
<Button size={"sm"} variant="outline">
|
||||
View Details
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
|
||||
<h3 className="text-sm font-medium">Devices</h3>
|
||||
<ol className="list-disc list-inside text-sm">
|
||||
{payment.devices.map((device) => (
|
||||
<li key={device.id} className="text-sm text-muted-foreground">
|
||||
{device.name}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<div className="block sm:hidden">
|
||||
<Separator className="my-2" />
|
||||
<h3 className="text-sm font-medium">Duration</h3>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{payment.number_of_months} Months
|
||||
</span>
|
||||
<Separator className="my-2" />
|
||||
<h3 className="text-sm font-medium">Amount</h3>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{payment.amount.toFixed(2)} MVR
|
||||
</span>
|
||||
<span className="font-semibold pr-2">
|
||||
{payment.paid ? (
|
||||
<Badge
|
||||
className={cn(
|
||||
payment.status === "PENDING"
|
||||
? "bg-yellow-100 text-yellow-700 dark:bg-yellow-700 dark:text-yellow-100"
|
||||
: "bg-green-100 dark:bg-green-700",
|
||||
)}
|
||||
variant="outline"
|
||||
>
|
||||
{payment.status}
|
||||
</Badge>
|
||||
) : payment.is_expired ? (
|
||||
<Badge>Expired</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">{payment.status}</Badge>
|
||||
)}
|
||||
</span>
|
||||
{isAdmin && (
|
||||
<div className="my-2 text-primary flex flex-col items-start text-sm border rounded p-2 mt-2 w-full bg-white dark:bg-black">
|
||||
{payment?.user?.name}
|
||||
<span className="text-muted-foreground">
|
||||
{payment?.user?.id_card}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
"use client";
|
||||
import {
|
||||
discountPercentageAtom,
|
||||
formulaResultAtom,
|
||||
initialPriceAtom,
|
||||
numberOfDaysAtom,
|
||||
numberOfDevicesAtom,
|
||||
} from "@/lib/atoms";
|
||||
import { useAtom } from "jotai";
|
||||
import { useEffect } from "react";
|
||||
import NumberInput from "./number-input";
|
||||
|
||||
export default function PriceCalculator() {
|
||||
const [initialPrice, setInitialPrice] = useAtom(initialPriceAtom);
|
||||
const [discountPercentage, setDiscountPercentage] = useAtom(
|
||||
discountPercentageAtom,
|
||||
);
|
||||
const [numberOfDevices, setNumberOfDevices] = useAtom(numberOfDevicesAtom);
|
||||
const [numberOfDays, setNumberOfDays] = useAtom(numberOfDaysAtom);
|
||||
const [formulaResult, setFormulaResult] = useAtom(formulaResultAtom);
|
||||
|
||||
useEffect(() => {
|
||||
const basePrice = initialPrice + (numberOfDevices - 1) * discountPercentage;
|
||||
setFormulaResult(
|
||||
`Price for ${numberOfDevices} device(s) over ${numberOfDays} day(s): MVR ${basePrice.toFixed(2)}`,
|
||||
);
|
||||
}, [
|
||||
initialPrice,
|
||||
discountPercentage,
|
||||
numberOfDevices,
|
||||
numberOfDays,
|
||||
setFormulaResult,
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className="border p-2 rounded-xl">
|
||||
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
|
||||
<h3 className="text-sarLinkOrange text-2xl">Price Calculator</h3>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
{/* Initial Price Input */}
|
||||
<NumberInput
|
||||
label="Initial Price"
|
||||
value={initialPrice}
|
||||
onChange={(value) => setInitialPrice(value)}
|
||||
/>
|
||||
{/* Number of Devices Input */}
|
||||
<NumberInput
|
||||
label="Number of Devices"
|
||||
value={numberOfDevices}
|
||||
onChange={(value) => setNumberOfDevices(value)}
|
||||
/>
|
||||
{/* Number of Days Input */}
|
||||
<NumberInput
|
||||
label="Number of Days"
|
||||
value={numberOfDays}
|
||||
onChange={(value) => setNumberOfDays(value)}
|
||||
/>
|
||||
|
||||
{/* Discount Percentage Input */}
|
||||
<NumberInput
|
||||
label="Discount Percentage"
|
||||
value={discountPercentage}
|
||||
onChange={(value) => setDiscountPercentage(value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-4">
|
||||
<div className="title-bg relative rounded-lg border border-input shadow-sm shadow-black/5 transition-shadow focus-within:border-ring focus-within:outline-none focus-within:ring-[3px] focus-within:ring-ring/20 has-disabled:cursor-not-allowed has-disabled:opacity-50 [&:has(input:is(:disabled))_*]:pointer-events-none">
|
||||
<label
|
||||
htmlFor=""
|
||||
className="block px-3 pt-2 text-md font-medium text-foreground"
|
||||
>
|
||||
Total
|
||||
</label>
|
||||
<input
|
||||
className="flex font-mono font-semibold h-10 w-full bg-transparent px-3 pb-2 text-sm text-foreground placeholder:text-muted-foreground/70 focus-visible:outline-none"
|
||||
value={formulaResult}
|
||||
readOnly
|
||||
placeholder={"Result"}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import { useRef, useTransition } from "react";
|
||||
|
||||
export default function Search({ disabled }: { disabled?: boolean }) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const { replace } = useRouter();
|
||||
|
||||
const pathname = usePathname();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const searchParams = useSearchParams();
|
||||
const searchQuery = searchParams.get("query");
|
||||
|
||||
function handleSearch(term: string) {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
|
||||
if (term) {
|
||||
params.set("query", term);
|
||||
params.set("page", "1");
|
||||
} else {
|
||||
params.delete("query");
|
||||
}
|
||||
|
||||
startTransition(() => {
|
||||
replace(`${pathname}?${params.toString()}`);
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Input
|
||||
ref={inputRef}
|
||||
placeholder="Search..."
|
||||
type="search"
|
||||
className={cn("sm:w-fit", isPending && "animate-pulse")}
|
||||
name="search"
|
||||
id="search"
|
||||
defaultValue={searchQuery ? searchQuery : ""}
|
||||
disabled={disabled}
|
||||
spellCheck={false}
|
||||
onChange={(e) => handleSearch(e.target.value)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user