Compare commits

...

86 Commits

Author SHA1 Message Date
Amit Salunke 0e9d779c91 Merge pull request 'feat/dynamic-storefront-catalog' (#124) from feat/dynamic-storefront-catalog into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/124
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-12-04 05:21:33 +00:00
Urvish Prajapati 50550e1703 chore: merge origin/main (#123) into feat/dynamic-storefront-catalog 2026-12-03 15:37:39 +05:30
Amit Salunke 36dc2afc00 Merge pull request 'fix(storefront): keep storefront visible on stale token and filter unavailable plans' (#123) from fix/storefront-initial-load-redirect into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/123
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-12-03 04:58:19 +00:00
ShivaniKhaire 0f9212563f fix(storefront): keep storefront visible on stale token and filter unavailable plans 2026-12-02 16:40:58 +05:30
Urvish Prajapati 2013659a20 fix(catalog): keep Complete Packs last and omit redundant pack row for single-module NUTRITION_CORE 2026-12-02 16:01:28 +05:30
Urvish Prajapati d5fa9ad00d feat(storefront): drive catalog, unlocks, and ?planCode deep links dynamically from /api/plans 2026-12-02 15:18:33 +05:30
Amit Salunke 49a5ccbf54 Merge pull request 'test/storefront-e2e-setup' (#120) from test/storefront-e2e-setup into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/120
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-12-01 04:37:44 +00:00
Urvish Prajapati 723bf72570 test(e2e): add full Storefront edge cases (registration, deep-links, live currency switch, discounts, popstate) 2026-11-30 15:35:38 +05:30
Urvish Prajapati f8aa89d21b test(unit): add Phase 5 component and App integration tests with full src coverage 2026-11-27 16:32:01 +05:30
Urvish Prajapati 227bbd6550 test(e2e): add Phase 4 checkout, Razorpay, billing phone, and subscriptions tests 2026-11-27 16:01:59 +05:30
Urvish Prajapati 3371c4a3e5 test(storefront): phase 3 auth, deep-links, profile & logout E2E tests 2026-11-27 15:36:02 +05:30
Urvish Prajapati fc7660e672 test(storefront): phase 2 catalog, multi-currency, cart & coupon E2E tests 2026-11-27 15:26:15 +05:30
Urvish Prajapati 4356f8321f test(storefront): phase 1 unit & component test suite with 99% line coverage 2026-11-27 15:14:35 +05:30
Urvish Prajapati 25594ec512 test(storefront): add initial Playwright E2E setup and smoke test 2026-11-27 13:42:56 +05:30
Amit Salunke caa60c68fb Merge pull request 'fix(storefront): unify complete pack naming and badge UI across catalog' (#119) from fix/storefront-complete-pack-ui into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/119
2026-11-25 05:13:32 +00:00
Amit Salunke 75525b17ea Merge pull request 'fix(validation): implement generic country prefix validation for mobile numbers (issue #116)' (#118) from fix/issue-116-country-mobile-validation into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/118
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-25 05:13:23 +00:00
Urvish Prajapati 08dd2325dc fix(storefront): unify complete pack naming and badge UI across catalog 2026-11-24 13:27:38 +05:30
ShivaniKhaire 5241396999 fix(validation): implement generic country prefix validation for mobile numbers (issue #116)
- Add validPrefixes and example fields to CountryCode interface in constants/countries.ts
- Refactor validatePhoneNumber in utils/validation.ts to generically enforce starting prefixes across all countries
- Clearly indicate starting prefix requirement (e.g. 'For Pakistan, the mobile number must start with 3.')
- Improve phone input error matching in AuthModal and ProfileDrawer for mobile validation errors
2026-11-23 12:48:07 +05:30
Amit Salunke 1f11874755 Merge pull request 'fix(auth): clear stale password update success message on login, logout, and navigation' (#113) from fix/stale-password-success-message into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/113
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-23 04:54:09 +00:00
Amit Salunke b7cd62519d Merge pull request 'feat/country-currency-parity' (#117) from feat/country-currency-parity into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/117
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-23 04:53:24 +00:00
Urvish Prajapati dc55ab4acf feat(cart): implement phase 2 - lock currency to country, remove manual toggle, and add timezone region detection 2026-11-20 15:52:05 +05:30
Urvish Prajapati 342ca856d9 feat(pricing): implement phase 1 - EUR and USD price parity and EU country currency mapping 2026-11-20 15:46:28 +05:30
Urvish Prajapati 9af7a9ad33 Merge branch 'main' into fix/stale-password-success-message 2026-11-20 11:30:57 +05:30
Amit Salunke 551631773e Merge pull request 'fix/issue-84-country-code-search' (#112) from fix/issue-84-country-code-search into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/112
2026-11-19 10:11:16 +00:00
Urvish Prajapati 38d5149114 Merge branch 'main' into fix/issue-84-country-code-search 2026-11-19 14:36:08 +05:30
Urvish Prajapati aa4e1f0831 Merge branch 'main' into fix/stale-password-success-message 2026-11-19 13:46:01 +05:30
Amit Salunke a21a910d24 Merge pull request 'fix(catalog): robustly synchronize and reflect updated module categories on storefront' (#115) from issue-8 into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/115
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-19 05:14:41 +00:00
Amit Salunke eea2853d5d Merge pull request 'feat(auth): add dedicated successfully logged out page with url login support (issue #83)' (#111) from fix/issue-83-logged-out-page into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/111
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-19 05:12:10 +00:00
Amit Salunke 2aceec4c37 Merge pull request 'fix(validation): add country-specific mobile phone validation and libphonenumber-js' (#110) from fix/country-specific-phone-validation into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/110
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-19 05:11:21 +00:00
ShivaniKhaire d75d633c7d fix(catalog): robustly synchronize and reflect updated module categories on storefront 2026-11-18 09:51:34 +05:30
Urvish Prajapati 70b9e7146e fix(auth): clear stale password update success message on login, logout, and navigation 2026-11-17 14:13:39 +05:30
ShivaniKhaire 41e885a7c9 fix(billing): sync billing country with phone country and allow entering valid phone per country
- Synchronize Billing Country and Phone dial code in BillingPhoneModal and ProfileDrawer
- Reset phone and clear errors upon country change so user can enter a valid number per country rules
- Display Billing Country in CartDrawer's Billing Profile prefill summary
- Prioritize country-based rules over dial code in validation to support shared dial codes accurately
2026-11-17 13:41:17 +05:30
ShivaniKhaire 1567a96c54 feat(store): add search bar, alphabetical sorting, and country code display to phone input (issue #84)
- Replace native HTML select in PhoneInput with a custom searchable popover dropdown
- Sort country options alphabetically using SORTED_COUNTRY_CODES
- Display flag, country name, and dial code clearly for each option
- Support search filtering by country name, formatted dial code (+XX), and raw numeric code
- Apply seamlessly to Registration (AuthModal) and User Profile (ProfileDrawer)
2026-11-17 13:12:57 +05:30
ShivaniKhaire a4e7c169a3 feat(auth): add dedicated successfully logged out page with url login support (issue #83)
- Add LoggedOutView component displaying 'Successfully Logged Out' message and security notice
- Provide 'Log In Again' action with direct URL (?login=true)
- Support /store/logged-out routing and query parameter so page reloads without base URL errors
- Switch to logged-out tab on session logout and redirect back to storefront upon re-authentication
2026-11-17 12:36:56 +05:30
Urvish Prajapati 3d2c9c3c78 Merge branch 'main' into fix/country-specific-phone-validation 2026-11-17 11:49:03 +05:30
Amit Salunke 401ebb40d5 Merge pull request 'fix(checkout): validate and display duplicate mobile number errors in billing phone modal' (#109) from fix/billing-phone-validation-error into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/109
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-17 05:01:00 +00:00
Amit Salunke 131ed8d608 Merge pull request 'fix(auth): prevent login modal popup on authenticated mobile redirect and startup' (#108) from fix/mobile-redirect-auth-modal into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/108
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-17 04:59:54 +00:00
Urvish Prajapati 1dd80f23ba fix(validation): prioritize length errors over prefix errors in phone validation 2026-11-16 16:30:37 +05:30
Urvish Prajapati 841f9a86a5 fix(validation): add country-specific mobile phone validation and libphonenumber-js
- Integrate libphonenumber-js to validate country mobile numbering plans (e.g., France 06/07, India 6-9, UK 07)
- Add ISO-2 country codes to eliminate dropdown collisions between countries sharing dial codes (+1 for US and Canada)
- Automatically strip leading national trunk zero (0) when converting to standard international E.164 format
- Ensure new dependency is registered in package.json and package-lock.json for npm install
2026-11-16 16:13:26 +05:30
Urvish Prajapati 36a530b8d7 fix(checkout): validate and display duplicate mobile number errors in billing phone modal 2026-11-16 15:22:19 +05:30
Urvish Prajapati df28775be7 fix(auth): prevent login modal popup on authenticated mobile redirect and startup 2026-11-16 14:28:01 +05:30
Amit Salunke 7a2d966796 Merge pull request 'feat(store): add country search, alphabetical sorting, and country code display (#84)' (#96) from issue-84 into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/96
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-16 05:25:07 +00:00
Amit Salunke 590aef22aa Merge pull request 'fix(auth): add visibility toggle to confirm password and update mismatch error message' (#101) from fix/change-password-confirm-visibility-and-error into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/101
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-16 05:21:48 +00:00
Urvish Prajapati 47fa05d16b Merge branch 'main' into issue-84 2026-11-12 11:21:19 +05:30
Urvish Prajapati 1cd87a333d Merge branch 'main' into fix/change-password-confirm-visibility-and-error 2026-11-12 11:11:07 +05:30
Amit Salunke 93fee66482 Merge pull request 'fix(store): ensure trailing slash on storefront routing and redirect /store to prevent blank page on reload (#83)' (#95) from issue-83 into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/95
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-12 04:39:02 +00:00
Amit Salunke 091f83ee17 Merge pull request 'fix/standardized-phone-validation-and-billing' (#86) from fix/standardized-phone-validation-and-billing into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/86
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-12 04:38:26 +00:00
Urvish Prajapati 7f8bd75c99 fix(auth): add visibility toggle to confirm password and update mismatch error message 2026-11-11 15:45:34 +05:30
Urvish Prajapati 2513c85411 fix(auth): enforce strict national phone length and prevent country code combining 2026-11-11 13:21:45 +05:30
Urvish Prajapati 62c7a4aead Merge branch 'fix/consistent-complete-package-cart-ui' into fix/standardized-phone-validation-and-billing 2026-11-11 12:57:46 +05:30
Urvish Prajapati 7e2f3ed927 fix(cart): standardize complete package badge and UI layout in cart drawer 2026-11-11 12:04:25 +05:30
ShivaniKhaire 9c0315c36a feat(store): add country search, alphabetical sorting, and country code display (#84) 2026-11-07 16:01:38 +05:30
ShivaniKhaire 874221fdd8 fix(store): ensure trailing slash on storefront routing and redirect /store to prevent blank page on reload (#83) 2026-11-07 15:46:46 +05:30
Urvish Prajapati a1c127e684 Merge branch 'main' into fix/standardized-phone-validation-and-billing 2026-11-06 11:50:39 +05:30
Amit Salunke 6410d21e66 Merge pull request 'fix(catalog): update locked pass toggle link hover color to dark brown' (#87) from fix/lifetime-card-hover-color into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/87
2026-11-06 05:03:36 +00:00
Amit Salunke 54ce5bcd85 Merge pull request 'fix(store): display storefront and subscriptions navigation tabs on mobile' (#85) from fix/mobile-storefront-subscriptions-nav into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/85
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-06 05:03:20 +00:00
Amit Salunke ccc3d9c250 Merge pull request 'fix(auth): enforce RFC-compliant email validation across login, registration and password recovery' (#89) from fix/email-format-validation into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/89
2026-11-06 05:02:42 +00:00
Amit Salunke f46d9cdc8d Merge pull request 'fix(auth): clear mobile number field automatically when country changes during registration' (#90) from fix/clear-phone-on-country-change into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/90
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-06 05:02:15 +00:00
Urvish Prajapati 9f08b0a6a5 fix(auth): clear mobile number field automatically when country changes during registration 2026-11-05 15:29:53 +05:30
Urvish Prajapati 2445fefcfe fix(auth): enforce RFC-compliant email validation across login, registration and password recovery 2026-11-05 15:14:54 +05:30
Urvish Prajapati 9dffbbfa9b fix(catalog): update locked pass toggle link hover color to dark brown 2026-11-05 14:44:04 +05:30
Urvish Prajapati b865f57e4d fix(store): lock billing profile phone number to registration and disallow editing 2026-11-05 13:06:11 +05:30
Urvish Prajapati 79cb96ae5e fix(store): enforce Indian mobile prefix and ensure exact razorpay contact prefill 2026-11-05 12:54:58 +05:30
Urvish Prajapati a0c5a2d6fc fix(store): standardize phone number input, validation, and billing modal 2026-11-05 12:42:33 +05:30
Urvish Prajapati 9625643042 fix(store): display storefront and subscriptions navigation tabs on mobile 2026-11-05 11:44:28 +05:30
Amit Salunke 2a2a95ecf0 Merge pull request 'fix(mobile): resolve iPhone SE modal height cut-off and phone input overflow' (#79) from fix/mobile-modal-and-phone-overflow into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/79
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-02 04:50:26 +00:00
Urvish Prajapati 92d6869c7b fix(mobile): resolve iPhone SE modal height cut-off and phone input overflow 2026-10-30 15:39:50 +05:30
Amit Salunke 817be0ab9e Merge pull request 'fix(auth-issue-68): update registration copy to Create Account, block same password, and require re-authentication' (#76) from fix/change-password-validation-and-reauth into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/76
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-30 05:38:12 +00:00
Amit Salunke fac840a348 Merge pull request 'fix(issue-72): reset coupon code and pricing calculation after purchasse' (#75) from fix/store-clear-coupon-after-purchase into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/75
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-30 05:37:32 +00:00
Amit Salunke d6b2a37dde Merge pull request 'fix(profile): sync country dial code and prevent hyphens in phone numbers' (#74) from fix/profile-phone-country-code into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/74
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-30 05:37:05 +00:00
Amit Salunke c07bb6b52f Merge pull request 'bug-fix: added country wise phone number length restrictions' (#73) from phone-code into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/73
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-30 05:36:12 +00:00
Urvish Prajapati 687fad2ff0 fix(auth-issue-68): update registration copy to Create Account, block same password, and require re-authentication 2026-10-29 15:52:04 +05:30
Urvish Prajapati 847b1999b8 fix(issue-72): reset coupon code and pricing calculation after purchasse 2026-10-29 15:24:23 +05:30
Urvish Prajapati b65249e075 fix(profile): sync country dial code and prevent hyphens in phone numbers 2026-10-29 14:10:04 +05:30
Urvish Prajapati a09491bc87 bug-fix: added country wise phone number length restrictions 2026-10-29 13:04:24 +05:30
Amit Salunke 8dc9d871d9 Merge pull request 'fix(validation): standardize phone validation to 7-15 digits' (#70) from phone-code into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-store-ui/pulls/70
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-27 04:50:43 +00:00
Urvish Prajapati 57cf92f4a6 fix(validation): standardize phone validation to 7-15 digits 2026-10-26 16:14:21 +05:30
Amit Salunke 4b09297db5 Merge pull request 'update: added missing country codes' (#69) from phone-code into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-store-ui/pulls/69
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-26 08:31:35 +00:00
Urvish Prajapati c314d47228 update: added missing country codes 2026-10-26 13:29:56 +05:30
Amit Salunke d50d215f3d Merge pull request 'issue(49): enforce strict mobile number validation and sanitization across storefront' (#58) from issue-49 into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-store-ui/pulls/58
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-21 04:52:54 +00:00
Urvish Prajapati eba0870e7f issue(49): enforce strict mobile number validation and sanitization across storefront 2026-10-20 12:01:41 +05:30
Amit Salunke 1358a015cf Merge pull request 'issue-31' (#57) from issue-31 into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-store-ui/pulls/57
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-20 04:48:09 +00:00
Amit Salunke 2235aad102 Merge pull request 'issue(43):Razorpay Mobile Number Validation and Email Editing Issues Fixed' (#56) from issue-43 into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-store-ui/pulls/56
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-20 04:47:37 +00:00
Amit Salunke 84765d4d46 Merge pull request 'issue(47): added 10s auto-redirect countdown with pause and fixed discount issue' (#55) from issue-47 into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-store-ui/pulls/55
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-20 04:46:40 +00:00
Urvish Prajapati 7e19e51708 issue(31):Password validation fixed 2026-10-19 14:18:48 +05:30
Urvish Prajapati 5fbd17faed issue(43):Razorpay Mobile Number Validation and Email Editing Issues Fixed 2026-10-19 12:56:55 +05:30
53 changed files with 6997 additions and 588 deletions

View File

@ -1,2 +1,2 @@
Branch: main Branch: phone-code
Commit: 75acd1de923fe310458333b66b71450f444eee2b Commit: 57cf92f4a68510b598927e96163f4cce5d75c309

5
.gitignore vendored
View File

@ -31,3 +31,8 @@ dist-ssr
# Generated Git Info # Generated Git Info
.git_*_info .git_*_info
# Playwright & Coverage
playwright-report/
test-results/
coverage/

53
TESTING.md Normal file
View File

@ -0,0 +1,53 @@
# Running Storefront Tests (`acupedia_store_ui`)
All commands below should be run from the `acupedia_store_ui/` directory:
```bash
cd acupedia_store_ui
```
---
## 1. Prerequisites (First Time Only)
If dependencies or Playwright browsers are not installed yet:
```bash
npm install
npx playwright install chromium
```
---
## 2. Run Playwright E2E Tests
### Run all E2E tests (headless, Desktop + Mobile)
```bash
npm run test:e2e
```
> Playwright automatically starts the Vite dev server on `http://localhost:3000/store/` if it is not already running.
### Run in Interactive UI Mode (recommended for watching & debugging)
```bash
npm run test:e2e:ui
```
### Run in Headed Mode (watch the browser window)
```bash
npm run test:e2e:headed
```
### Run a specific test file
```bash
npx playwright test tests/e2e/smoke.spec.ts
```
### Run only Desktop or only Mobile
```bash
npx playwright test --project=chromium-desktop
npx playwright test --project=chromium-mobile
```
### View the HTML Test Report (after a run)
```bash
npm run test:e2e:report
```

1046
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -7,30 +7,45 @@
"dev": "vite", "dev": "vite",
"build": "tsc -b && vite build", "build": "tsc -b && vite build",
"lint": "eslint .", "lint": "eslint .",
"preview": "vite preview" "preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui",
"test:e2e:headed": "playwright test --headed",
"test:e2e:report": "playwright show-report"
}, },
"dependencies": { "dependencies": {
"axios": "^1.7.0", "axios": "^1.7.0",
"libphonenumber-js": "^1.13.16",
"lucide-react": "^0.460.0", "lucide-react": "^0.460.0",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0" "react-dom": "^19.0.0"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.0.0", "@eslint/js": "^9.0.0",
"@playwright/test": "^1.65.1",
"@tailwindcss/postcss": "^4.0.0", "@tailwindcss/postcss": "^4.0.0",
"@testing-library/jest-dom": "^8.0.0",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.13",
"@types/node": "^22.0.0", "@types/node": "^22.0.0",
"@types/react": "^19.0.0", "@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0", "@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.0", "@vitejs/plugin-react": "^4.3.0",
"@vitest/coverage-v8": "^5.1.2",
"autoprefixer": "^10.4.0", "autoprefixer": "^10.4.0",
"eslint": "^9.0.0", "eslint": "^9.0.0",
"eslint-plugin-react-hooks": "^5.0.0", "eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.0", "eslint-plugin-react-refresh": "^0.4.0",
"globals": "^15.0.0", "globals": "^15.0.0",
"jsdom": "^31.0.1",
"postcss": "^8.4.0", "postcss": "^8.4.0",
"tailwindcss": "^4.0.0", "tailwindcss": "^4.0.0",
"typescript": "^5.8.0", "typescript": "^5.8.0",
"typescript-eslint": "^8.0.0", "typescript-eslint": "^8.0.0",
"vite": "^6.0.0" "vite": "^6.0.0",
"vitest": "^5.1.2"
} }
} }

32
playwright.config.ts Normal file
View File

@ -0,0 +1,32 @@
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests/e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: [['list'], ['html', { open: 'never' }]],
use: {
baseURL: 'http://localhost:3000/store/',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
},
projects: [
{
name: 'chromium-desktop',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'chromium-mobile',
use: { ...devices['Pixel 5'] },
},
],
webServer: {
command: 'npm run dev -- --port 3000',
url: 'http://localhost:3000/store/',
reuseExistingServer: !process.env.CI,
timeout: 60_000,
},
});

View File

@ -1,12 +1,13 @@
import { useState, useEffect } from 'react'; import { useState, useEffect, useMemo } from 'react';
import axios from 'axios'; import axios from 'axios';
import { CURRICULUM_MODULES } from './constants/modules'; import { CURRICULUM_MODULES } from './constants/modules';
import { buildDynamicCatalog } from './utils/catalog';
import { getCountryRuleByName } from './constants/countries'; import { getCountryRuleByName } from './constants/countries';
import type { ModuleItem, Currency, UserProfile, VerificationResult, PublicPlan } from './types'; import type { ModuleItem, Currency, UserProfile, VerificationResult, PublicPlan } from './types';
import { API_BASE } from './services/api'; import { API_BASE } from './services/api';
import { loadRazorpayScript } from './services/razorpay'; import { loadRazorpayScript } from './services/razorpay';
import { cleanPhoneInput, validatePhoneNumber } from './utils/validation'; import { validatePhoneNumber, isValidPhoneNumber, validatePassword, parsePhoneNumber, formatE164Phone, validateEmail } from './utils/validation';
// Modular Subcomponents // Modular Subcomponents
import { StoreHeader } from './components/layout/StoreHeader'; import { StoreHeader } from './components/layout/StoreHeader';
@ -19,32 +20,58 @@ import { AuthModal } from './components/auth/AuthModal';
import { ProfileDrawer } from './components/auth/ProfileDrawer'; import { ProfileDrawer } from './components/auth/ProfileDrawer';
import { PaymentSuccessModal } from './components/checkout/PaymentSuccessModal'; import { PaymentSuccessModal } from './components/checkout/PaymentSuccessModal';
import { PasswordUpdatedModal } from './components/auth/PasswordUpdatedModal'; import { PasswordUpdatedModal } from './components/auth/PasswordUpdatedModal';
import { BillingPhoneModal } from './components/checkout/BillingPhoneModal';
import { LoggedOutView } from './components/auth/LoggedOutView';
import { openMobileApp, DEFAULT_RETURN_ROUTE } from './utils/navigation'; import { openMobileApp, DEFAULT_RETURN_ROUTE } from './utils/navigation';
const getInitialTab = (): 'storefront' | 'subscriptions' => { const getInitialTab = (): 'storefront' | 'subscriptions' | 'logged-out' => {
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
const path = window.location.pathname.toLowerCase(); const path = window.location.pathname.toLowerCase();
if (path.includes('/logged-out')) return 'logged-out';
if (path.includes('/subscriptions')) return 'subscriptions'; if (path.includes('/subscriptions')) return 'subscriptions';
const params = new URLSearchParams(window.location.search);
if (params.get('logged_out') === 'true' || params.get('status') === 'logged-out') {
return 'logged-out';
}
} }
return 'storefront'; return 'storefront';
}; };
export default function App() { const getInitialRegion = (): { currency: Currency; country: string; dialCode: string } => {
const [activeTab, setActiveTab] = useState<'storefront' | 'subscriptions'>(getInitialTab); if (typeof Intl !== 'undefined') {
try {
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || '';
if (tz.includes('Kolkata') || tz.includes('Calcutta')) {
return { currency: 'INR', country: 'India', dialCode: '+91' };
}
if (tz.startsWith('Europe/')) {
return { currency: 'EUR', country: 'Germany', dialCode: '+49' };
}
} catch {
// ignore
}
}
return { currency: 'USD', country: 'United States', dialCode: '+1' };
};
const switchTab = (tab: 'storefront' | 'subscriptions') => { export default function App() {
const [activeTab, setActiveTab] = useState<'storefront' | 'subscriptions' | 'logged-out'>(getInitialTab);
const switchTab = (tab: 'storefront' | 'subscriptions' | 'logged-out') => {
setActiveTab(tab); setActiveTab(tab);
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
const isStorePrefix = window.location.pathname.startsWith('/store'); const isStorePrefix = window.location.pathname.startsWith('/store');
const basePath = isStorePrefix ? '/store' : ''; const basePath = isStorePrefix ? '/store/' : '/';
const newPath = tab === 'storefront' ? (basePath || '/') : (basePath + '/' + tab); const newPath = tab === 'storefront' ? basePath : `${basePath}${tab}`;
if (window.location.pathname !== newPath) { if (window.location.pathname !== newPath) {
window.history.pushState({ tab }, '', newPath); window.history.pushState({ tab }, '', newPath);
} }
} }
}; };
const [currency, setCurrency] = useState<Currency>('INR'); const initialRegion = useMemo(getInitialRegion, []);
const [currency, setCurrency] = useState<Currency>(initialRegion.currency);
// Auth state // Auth state
const [userToken, setUserToken] = useState<string | null>(localStorage.getItem('access_token')); const [userToken, setUserToken] = useState<string | null>(localStorage.getItem('access_token'));
@ -67,13 +94,23 @@ export default function App() {
const [changePasswordError, setChangePasswordError] = useState<string | null>(null); const [changePasswordError, setChangePasswordError] = useState<string | null>(null);
const [changePasswordSuccess, setChangePasswordSuccess] = useState<boolean>(false); const [changePasswordSuccess, setChangePasswordSuccess] = useState<boolean>(false);
// Auto-clear change password success banner after 4 seconds
useEffect(() => {
if (changePasswordSuccess) {
const timer = setTimeout(() => {
setChangePasswordSuccess(false);
}, 4000);
return () => clearTimeout(timer);
}
}, [changePasswordSuccess]);
// Auth Form State // Auth Form State
const [authEmail, setAuthEmail] = useState(''); const [authEmail, setAuthEmail] = useState('');
const [authPassword, setAuthPassword] = useState(''); const [authPassword, setAuthPassword] = useState('');
const [authDisplayName, setAuthDisplayName] = useState(''); const [authDisplayName, setAuthDisplayName] = useState('');
const [authPhone, setAuthPhone] = useState(''); const [authPhone, setAuthPhone] = useState('');
const [authDialCode, setAuthDialCode] = useState('+91'); const [authDialCode, setAuthDialCode] = useState(initialRegion.dialCode);
const [authCountry, setAuthCountry] = useState('India'); const [authCountry, setAuthCountry] = useState(initialRegion.country);
const [authLoading, setAuthLoading] = useState(false); const [authLoading, setAuthLoading] = useState(false);
const [authError, setAuthError] = useState<string | null>(null); const [authError, setAuthError] = useState<string | null>(null);
@ -114,6 +151,10 @@ export default function App() {
} else { } else {
switchTab('subscriptions'); switchTab('subscriptions');
setVerificationResult(null); setVerificationResult(null);
setCart([]);
setAppliedCoupon(null);
setCouponCode('');
setPricingCalc(null);
} }
return; return;
} }
@ -132,80 +173,64 @@ export default function App() {
const [profileError, setProfileError] = useState<string | null>(null); const [profileError, setProfileError] = useState<string | null>(null);
const [profileSuccess, setProfileSuccess] = useState<boolean>(false); const [profileSuccess, setProfileSuccess] = useState<boolean>(false);
// Dynamic Public Storefront Plans // Billing Contact Phone Modal State
const [showBillingPhoneModal, setShowBillingPhoneModal] = useState<boolean>(false);
const [pendingCheckoutAfterPhone, setPendingCheckoutAfterPhone] = useState<boolean>(false);
// Dynamic Public Storefront Plans & Modules
const [publicPlans, setPublicPlans] = useState<PublicPlan[]>([]); const [publicPlans, setPublicPlans] = useState<PublicPlan[]>([]);
const [apiModules, setApiModules] = useState<any[]>([]);
const [pendingUrlPlanCode, setPendingUrlPlanCode] = useState<string | null>(null);
const [plansLoaded, setPlansLoaded] = useState<boolean>(false);
const fetchPublicPlans = async () => { const fetchPublicPlans = async () => {
try { try {
const res = await axios.get(`${API_BASE}/api/plans`); const res = await axios.get(`${API_BASE}/api/plans`);
if (Array.isArray(res.data)) { if (Array.isArray(res.data)) {
setPublicPlans(res.data); setPublicPlans(res.data);
setPlansLoaded(true);
} }
} catch (err) { } catch (err) {
console.error('Failed to load public plans:', err); console.error('Failed to load public plans:', err);
} }
}; };
// Dynamic Curriculum Modules with Live Categories // Dynamic Curriculum Modules derived from /api/plans + /api/contents/modules
const [curriculumModules, setCurriculumModules] = useState<ModuleItem[]>(CURRICULUM_MODULES); const [curriculumModules, setCurriculumModules] = useState<ModuleItem[]>(CURRICULUM_MODULES);
const fetchModuleCategories = async () => { const fetchModuleCategories = async () => {
try { try {
const res = await axios.get(`${API_BASE}/api/contents/modules`); const res = await axios.get(`${API_BASE}/api/contents/modules`);
const apiModules: any[] = res.data?.modules || []; const mods: any[] = Array.isArray(res.data) ? res.data : (res.data?.modules || []);
if (apiModules.length > 0) { if (mods.length > 0) {
const normalizeCategory = (cat?: string) => { setApiModules(mods);
if (!cat) return null;
const c = cat.toLowerCase();
if (c === 'point' || c === 'points') return 'Points';
if (c === 'pattern' || c === 'patterns') return 'Pattern';
if (c === 'nutrition') return 'Nutrition';
if (c === 'therapeutics' || c === 'therapeutic') return 'Therapeutics';
return cat;
};
setCurriculumModules((prev) =>
prev.map((item) => {
const matched = apiModules.find((m) => {
const mCode = (m.code || '').toLowerCase();
const iCode = (item.code || '').toLowerCase();
if (mCode && iCode && mCode === iCode) return true;
const slug = (m.slug || '').toLowerCase();
const mName = (m.name || '').toLowerCase();
const iName = item.name.toLowerCase();
const cleanI = iName.replace('points:', '').replace('therapeutics:', '').split('(')[0].trim();
const cleanM = mName.replace('points:', '').replace('therapeutics:', '').split('(')[0].trim();
if (cleanI.includes('acu') && cleanM.includes('acupuncture') && !cleanI.includes('scalp') && !cleanI.includes('ear')) return true;
if (cleanI.includes('scalp') && cleanM.includes('scalp')) return true;
if (cleanI.includes('ear') && (cleanM.includes('ear') || slug.includes('auriculo'))) return true;
if (cleanI.includes('gyneco') && slug.includes('gyneco')) return true;
if (cleanI.includes('eight') && slug.includes('eight')) return true;
if (cleanI.includes('zang') && slug.includes('tcm-pattern')) return true;
if (cleanI.includes('qi') && slug.includes('qi')) return true;
if (cleanI.includes('pathogenic') && slug.includes('pathogenic')) return true;
if (cleanI.includes('six') && slug.includes('six')) return true;
if (cleanI.includes('four') && slug.includes('four')) return true;
if (cleanI.includes('three') && slug.includes('three')) return true;
if (cleanI.includes('five') && slug.includes('five')) return true;
if (cleanI.includes('food') && slug.includes('nutrition')) return true;
return false;
});
const updatedCat = normalizeCategory(matched?.metadata?.category || matched?.category);
if (updatedCat) {
return { ...item, category: updatedCat };
}
return item;
})
);
} }
} catch (err) { } catch (err) {
console.error('Failed to load module categories:', err); console.error('Failed to load module categories:', err);
} }
}; };
useEffect(() => {
if (publicPlans.length > 0) {
setCurriculumModules(buildDynamicCatalog(publicPlans, apiModules));
}
}, [publicPlans, apiModules]);
useEffect(() => {
if (!pendingUrlPlanCode) return;
const targetModule = curriculumModules.find(
(m) => m.code.toUpperCase() === pendingUrlPlanCode,
);
if (targetModule) {
setCart([targetModule]);
setShowLockedByCategory((prev) => ({
...prev,
[targetModule.category]: true,
}));
setPendingUrlPlanCode(null);
}
}, [pendingUrlPlanCode, curriculumModules]);
const getLivePlan = (code: string) => { const getLivePlan = (code: string) => {
return publicPlans.find(p => p.code === code || p.base_code === code); return publicPlans.find(p => p.code === code || p.base_code === code);
@ -214,28 +239,49 @@ export default function App() {
const getModulePrice = (item: ModuleItem) => { const getModulePrice = (item: ModuleItem) => {
const livePlan = getLivePlan(item.code); const livePlan = getLivePlan(item.code);
if (livePlan) { if (livePlan) {
const priceInr = livePlan.price_inr ?? 0;
const priceUsd = livePlan.price_usd ?? 0;
const priceEur = livePlan.price_eur ?? livePlan.price_usd ?? 0;
const activeCurrencyPrice =
currency === 'INR' ? priceInr : currency === 'EUR' ? priceEur : priceUsd;
const planIsActive = livePlan.is_active !== undefined ? livePlan.is_active : true;
return { return {
priceInr: livePlan.price_inr ?? item.priceInr, priceInr: livePlan.price_inr ?? item.priceInr,
priceUsd: livePlan.price_usd ?? item.priceUsd, priceUsd: livePlan.price_usd ?? item.priceUsd,
priceEur: item.priceEur, priceEur: livePlan.price_eur ?? livePlan.price_usd ?? item.priceEur,
isActive: livePlan.is_active !== undefined ? livePlan.is_active : true, // Require active flag and a positive price in the user's billing currency
isActive: planIsActive && activeCurrencyPrice > 0,
}; };
} }
return { return {
priceInr: item.priceInr, priceInr: item.priceInr,
priceUsd: item.priceUsd, priceUsd: item.priceUsd,
priceEur: item.priceEur, priceEur: item.priceEur,
isActive: true, // Once /api/plans has loaded, catalog plans absent from it are inactive in the DB
isActive: !plansLoaded,
}; };
}; };
// Load configuration & user profile on startup // Load configuration & user profile on startup
useEffect(() => { useEffect(() => {
// Normalize URL if opened at /store without trailing slash
if (typeof window !== 'undefined' && window.location.pathname === '/store') {
const normalizedPath = '/store/' + (window.location.search || '') + (window.location.hash || '');
window.history.replaceState(window.history.state, document.title, normalizedPath);
}
const params = new URLSearchParams(window.location.search); const params = new URLSearchParams(window.location.search);
const urlToken = params.get('token'); const urlToken = params.get('token');
const urlPlanCode = params.get('planCode'); const urlPlanCode = params.get('planCode');
const urlReturnRoute = params.get('returnRoute') || params.get('redirectPath') || params.get('redirect'); const urlReturnRoute = params.get('returnRoute') || params.get('redirectPath') || params.get('redirect');
const urlScheme = params.get('scheme'); const urlScheme = params.get('scheme');
const shouldOpenLogin = params.get('login') === 'true' || params.get('auth') === 'login';
if (shouldOpenLogin) {
setAuthMode('login');
setShowAuthModal(true);
}
if (urlReturnRoute) { if (urlReturnRoute) {
setReturnRoute(urlReturnRoute); setReturnRoute(urlReturnRoute);
@ -244,29 +290,41 @@ export default function App() {
setAppScheme(urlScheme); setAppScheme(urlScheme);
} }
let activeToken = userToken; let activeToken = urlToken || localStorage.getItem('access_token');
if (urlToken) { if (urlToken) {
localStorage.setItem('access_token', urlToken); localStorage.setItem('access_token', urlToken);
setUserToken(urlToken); setUserToken(urlToken);
activeToken = urlToken;
fetchUserProfile(urlToken); fetchUserProfile(urlToken);
setShowAuthModal(false);
} else if (activeToken) {
fetchUserProfile(activeToken);
} }
if (urlPlanCode) { if (urlPlanCode) {
const targetModule = curriculumModules.find(m => m.code === urlPlanCode); const normalizedPlanCode = urlPlanCode.trim().toUpperCase();
const targetModule = curriculumModules.find(m => m.code.toUpperCase() === normalizedPlanCode);
if (targetModule) { if (targetModule) {
setCart([targetModule]); setCart([targetModule]);
setShowLockedByCategory(prev => ({ setShowLockedByCategory(prev => ({
...prev, ...prev,
[targetModule.category]: true [targetModule.category]: true
})); }));
} else {
setPendingUrlPlanCode(normalizedPlanCode);
} }
} }
if (urlToken || urlPlanCode) { if (urlToken || urlPlanCode || shouldOpenLogin) {
const newUrl = window.location.pathname; const isStorePrefix = window.location.pathname.startsWith('/store');
window.history.replaceState({}, document.title, newUrl); const basePath = isStorePrefix ? '/store/' : '/';
const cleanPath =
activeTab === 'subscriptions'
? `${basePath}subscriptions`
: activeTab === 'logged-out'
? `${basePath}logged-out`
: basePath;
window.history.replaceState({}, document.title, cleanPath);
} }
// Fetch public Razorpay Config // Fetch public Razorpay Config
@ -280,16 +338,7 @@ export default function App() {
fetchPublicPlans(); fetchPublicPlans();
fetchModuleCategories(); fetchModuleCategories();
}, []);
if (activeToken && !urlToken) {
fetchUserProfile(activeToken);
}
if (!activeToken && !urlToken) {
setAuthMode('login');
setShowAuthModal(true);
}
}, [userToken]);
// Recalculate price whenever cart, coupon, currency, or logged-in user changes // Recalculate price whenever cart, coupon, currency, or logged-in user changes
useEffect(() => { useEffect(() => {
@ -320,6 +369,7 @@ export default function App() {
const mergedUser = { const mergedUser = {
...profileRes.data, ...profileRes.data,
active_subscriptions: accessRes.data.active_subscriptions || [], active_subscriptions: accessRes.data.active_subscriptions || [],
unlocked_module_codes: accessRes.data.unlocked_module_codes || [],
unlocked_module_slugs: accessRes.data.unlocked_module_slugs || [], unlocked_module_slugs: accessRes.data.unlocked_module_slugs || [],
}; };
@ -331,23 +381,42 @@ export default function App() {
setCurrency(countryRule.currency); setCurrency(countryRule.currency);
} catch (err) { } catch (err) {
console.error('Failed to fetch user profile:', err); console.error('Failed to fetch user profile:', err);
handleLogout(); // Clear invalid/stale token silently so expired storage does not hijack initial storefront load into /logged-out.
resetAuthSession();
} }
}; };
const handleLogout = () => { const handleCloseProfileDrawer = () => {
setShowProfileDrawer(false);
setShowPasswordChange(false);
setChangePasswordError(null);
setChangePasswordSuccess(false);
setChangeOldPassword('');
setChangeNewPassword('');
setChangeConfirmPassword('');
};
const resetAuthSession = () => {
localStorage.removeItem('access_token'); localStorage.removeItem('access_token');
setUserToken(null); setUserToken(null);
setLoggedInUser(null); setLoggedInUser(null);
setCart([]); setCart([]);
setAppliedCoupon(null); setAppliedCoupon(null);
switchTab('storefront'); setCouponCode('');
setShowProfileDrawer(false); setPricingCalc(null);
handleCloseProfileDrawer();
setProfileDisplayName(''); setProfileDisplayName('');
setProfilePhone(''); setProfilePhone('');
setProfileCountry('India'); setProfileCountry(initialRegion.country);
setCurrency(initialRegion.currency);
setProfileError(null); setProfileError(null);
setProfileSuccess(false); setProfileSuccess(false);
setShowAuthModal(false);
};
const handleLogout = () => {
resetAuthSession();
switchTab('logged-out');
}; };
const handleUpdateProfile = async (e: React.FormEvent) => { const handleUpdateProfile = async (e: React.FormEvent) => {
@ -357,19 +426,22 @@ export default function App() {
setProfileError(null); setProfileError(null);
setProfileSuccess(false); setProfileSuccess(false);
let cleanedPhoneToSave: string | null = null;
if (profilePhone && profilePhone.trim()) { if (profilePhone && profilePhone.trim()) {
const phoneError = validatePhoneNumber(profilePhone, undefined, profileCountry); const parsed = parsePhoneNumber(profilePhone, profileCountry);
const phoneError = validatePhoneNumber(parsed.localDigits, parsed.dialCode, profileCountry);
if (phoneError) { if (phoneError) {
setProfileError(phoneError); setProfileError(phoneError);
setProfileSaving(false); setProfileSaving(false);
return; return;
} }
cleanedPhoneToSave = formatE164Phone(parsed.dialCode, parsed.localDigits, profileCountry);
} }
try { try {
await axios.put(`${API_BASE}/api/auth/profile`, { await axios.put(`${API_BASE}/api/auth/profile`, {
full_name: profileDisplayName, full_name: profileDisplayName,
phone_number: profilePhone, phone_number: cleanedPhoneToSave,
country: profileCountry, country: profileCountry,
}, { }, {
headers: { 'Authorization': `Bearer ${userToken}` } headers: { 'Authorization': `Bearer ${userToken}` }
@ -386,6 +458,42 @@ export default function App() {
} }
}; };
const handleSaveBillingPhone = async (phoneE164: string, country: string): Promise<boolean> => {
if (!userToken) return false;
try {
const res = await axios.put(`${API_BASE}/api/auth/profile`, {
phone_number: phoneE164,
country: country,
}, {
headers: { 'Authorization': `Bearer ${userToken}` }
});
if (res.data.status === 'success') {
if (loggedInUser) {
loggedInUser.phone_number = phoneE164;
loggedInUser.country = country;
setLoggedInUser({ ...loggedInUser });
}
setProfilePhone(phoneE164);
setProfileCountry(country);
const countryRule = getCountryRuleByName(country);
setCurrency(countryRule.currency);
setShowBillingPhoneModal(false);
if (pendingCheckoutAfterPhone) {
setPendingCheckoutAfterPhone(false);
setTimeout(() => {
handleCheckout();
}, 200);
}
return true;
}
return false;
} catch (err: any) {
const errorMsg = err.response?.data?.detail || 'Failed to save billing phone number.';
alert(errorMsg);
throw new Error(errorMsg);
}
};
const handleAuthSubmit = async (e: React.FormEvent) => { const handleAuthSubmit = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
setAuthLoading(true); setAuthLoading(true);
@ -393,15 +501,9 @@ export default function App() {
const trimmedEmail = authEmail.trim(); const trimmedEmail = authEmail.trim();
if (!trimmedEmail) { const emailErr = validateEmail(trimmedEmail);
setAuthError('Email address is required.'); if (emailErr) {
setAuthLoading(false); setAuthError(emailErr);
return;
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(trimmedEmail)) {
setAuthError('Please enter a valid email address.');
setAuthLoading(false); setAuthLoading(false);
return; return;
} }
@ -418,6 +520,7 @@ export default function App() {
return; return;
} }
let fullPhone: string | undefined = undefined;
if (authMode === 'register' && authPhone && authPhone.trim()) { if (authMode === 'register' && authPhone && authPhone.trim()) {
const phoneError = validatePhoneNumber(authPhone, authDialCode, authCountry); const phoneError = validatePhoneNumber(authPhone, authDialCode, authCountry);
if (phoneError) { if (phoneError) {
@ -425,40 +528,20 @@ export default function App() {
setAuthLoading(false); setAuthLoading(false);
return; return;
} }
fullPhone = formatE164Phone(authDialCode, authPhone, authCountry);
} }
const endpoint = authMode === 'login' ? '/api/auth/login' : '/api/auth/register'; const endpoint = authMode === 'login' ? '/api/auth/login' : '/api/auth/register';
if (authMode === 'register') { if (authMode === 'register') {
if (authPassword.length < 8) { const pwdError = validatePassword(authPassword, 'Password');
setAuthError('Password must be at least 8 characters long.'); if (pwdError) {
setAuthError(pwdError);
setAuthLoading(false); setAuthLoading(false);
return; return;
} }
if (!/[A-Z]/.test(authPassword)) {
setAuthError('Password must contain at least one uppercase letter.');
setAuthLoading(false);
return;
}
if (!/[0-9]/.test(authPassword)) {
setAuthError('Password must contain at least one number.');
setAuthLoading(false);
return;
}
if (/\p{Extended_Pictographic}/u.test(authPassword)) {
setAuthError('Password must not contain emojis.');
setAuthLoading(false);
return;
}
if (!/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?`~]/.test(authPassword)) {
setAuthError('Password must contain at least one special character.');
setAuthLoading(false);
return;
}
} }
const fullPhone = authPhone ? `${authDialCode}${authPhone}` : undefined;
const payload = authMode === 'login' const payload = authMode === 'login'
? { email: trimmedEmail, password: authPassword } ? { email: trimmedEmail, password: authPassword }
: { : {
@ -482,6 +565,15 @@ export default function App() {
setAuthEmail(''); setAuthEmail('');
setAuthDisplayName(''); setAuthDisplayName('');
setAuthPhone(''); setAuthPhone('');
if (activeTab === 'logged-out') {
switchTab('storefront');
}
setShowPasswordChange(false);
setChangeOldPassword('');
setChangeNewPassword('');
setChangeConfirmPassword('');
setChangePasswordError(null);
setChangePasswordSuccess(false);
} catch (err: any) { } catch (err: any) {
setAuthError(err.response?.data?.detail || 'Authentication failed. Please check credentials.'); setAuthError(err.response?.data?.detail || 'Authentication failed. Please check credentials.');
} finally { } finally {
@ -499,24 +591,17 @@ export default function App() {
setChangePasswordError('Please enter your current password.'); setChangePasswordError('Please enter your current password.');
return; return;
} }
if (changeNewPassword.length < 8) { const pwdError = validatePassword(changeNewPassword, 'New password');
setChangePasswordError('New password must be at least 8 characters long.'); if (pwdError) {
setChangePasswordError(pwdError);
return; return;
} }
if (!/[A-Z]/.test(changeNewPassword)) { if (changeOldPassword === changeNewPassword) {
setChangePasswordError('New password must contain at least one uppercase letter.'); setChangePasswordError('New password cannot be the same as current password.');
return;
}
if (!/[0-9]/.test(changeNewPassword)) {
setChangePasswordError('New password must contain at least one number.');
return;
}
if (!/[^A-Za-z0-9\s]/.test(changeNewPassword)) {
setChangePasswordError('New password must contain at least one special character.');
return; return;
} }
if (changeNewPassword !== changeConfirmPassword) { if (changeNewPassword !== changeConfirmPassword) {
setChangePasswordError('New passwords do not match.'); setChangePasswordError('Confirm password do not match.');
return; return;
} }
@ -528,12 +613,26 @@ export default function App() {
}, { }, {
headers: { 'Authorization': `Bearer ${userToken}` } headers: { 'Authorization': `Bearer ${userToken}` }
}); });
setChangePasswordSuccess(true);
setPasswordUpdatedPopup(true); const userEmail = loggedInUser?.email || authEmail;
// Invalidate active session without navigating to the logged-out screen so user stays in place for re-auth
resetAuthSession();
setShowProfileDrawer(false);
// Pre-fill email and set auth mode to login for seamless re-auth
setAuthEmail(userEmail);
setAuthPassword('');
setAuthMode('login');
setAuthError(null);
setChangeOldPassword(''); setChangeOldPassword('');
setChangeNewPassword(''); setChangeNewPassword('');
setChangeConfirmPassword(''); setChangeConfirmPassword('');
setShowPasswordChange(false); setShowPasswordChange(false);
setChangePasswordSuccess(false);
setChangePasswordError(null);
setPasswordUpdatedPopup(true);
} catch (err: any) { } catch (err: any) {
console.error(err); console.error(err);
setChangePasswordError(err.response?.data?.detail || 'Failed to update password.'); setChangePasswordError(err.response?.data?.detail || 'Failed to update password.');
@ -549,15 +648,9 @@ export default function App() {
setResetSuccessMessage(null); setResetSuccessMessage(null);
const trimmedEmail = authEmail.trim(); const trimmedEmail = authEmail.trim();
if (!trimmedEmail) { const emailErr = validateEmail(trimmedEmail);
setAuthError('Email address is required.'); if (emailErr) {
setAuthLoading(false); setAuthError(emailErr);
return;
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(trimmedEmail)) {
setAuthError('Please enter a valid email address.');
setAuthLoading(false); setAuthLoading(false);
return; return;
} }
@ -581,23 +674,9 @@ export default function App() {
setAuthLoading(true); setAuthLoading(true);
setAuthError(null); setAuthError(null);
if (resetNewPassword.length < 8) { const pwdError = validatePassword(resetNewPassword, 'New password');
setAuthError('New password must be at least 8 characters long.'); if (pwdError) {
setAuthLoading(false); setAuthError(pwdError);
return;
}
if (!/[A-Z]/.test(resetNewPassword)) {
setAuthError('New password must contain at least one uppercase letter.');
setAuthLoading(false);
return;
}
if (!/[0-9]/.test(resetNewPassword)) {
setAuthError('New password must contain at least one number.');
setAuthLoading(false);
return;
}
if (!/[^A-Za-z0-9\s]/.test(resetNewPassword)) {
setAuthError('New password must contain at least one special character.');
setAuthLoading(false); setAuthLoading(false);
return; return;
} }
@ -629,21 +708,40 @@ export default function App() {
} }
}; };
// Keep cart items dynamic prices updated when publicPlans are loaded // Keep cart synced with live plans: refresh prices and prune inactive/currency-unavailable plans
useEffect(() => { useEffect(() => {
if (publicPlans.length > 0 && cart.length > 0) { if (!plansLoaded || cart.length === 0) return;
setCart(prev =>
prev.map(item => { const nextCart: ModuleItem[] = [];
const live = getModulePrice(item); for (const item of cart) {
return { const live = getModulePrice(item);
...item, if (!live.isActive) continue;
priceInr: live.priceInr, nextCart.push({
priceUsd: live.priceUsd, ...item,
}; priceInr: live.priceInr,
}) priceUsd: live.priceUsd,
); priceEur: live.priceEur,
});
} }
}, [publicPlans]);
const changed =
nextCart.length !== cart.length ||
nextCart.some(
(n, idx) =>
n.priceInr !== cart[idx].priceInr ||
n.priceUsd !== cart[idx].priceUsd ||
n.priceEur !== cart[idx].priceEur
);
if (changed) {
setCart(nextCart);
if (nextCart.length === 0) {
setAppliedCoupon(null);
setCouponCode('');
setPricingCalc(null);
}
}
}, [publicPlans, plansLoaded, currency, cart]);
const calculatePricing = async () => { const calculatePricing = async () => {
setLoadingPricing(true); setLoadingPricing(true);
@ -719,11 +817,18 @@ export default function App() {
...module, ...module,
priceInr: live.priceInr, priceInr: live.priceInr,
priceUsd: live.priceUsd, priceUsd: live.priceUsd,
priceEur: live.priceEur,
}; };
const exists = cart.find(item => item.code === module.code); const exists = cart.find(item => item.code === module.code);
if (exists) { if (exists) {
setCart(cart.filter(item => item.code !== module.code)); const nextCart = cart.filter(item => item.code !== module.code);
setCart(nextCart);
if (nextCart.length === 0) {
setAppliedCoupon(null);
setCouponCode('');
setPricingCalc(null);
}
} else { } else {
if (module.code === 'LIFETIME_ALL') { if (module.code === 'LIFETIME_ALL') {
setCart([dynamicModule]); setCart([dynamicModule]);
@ -768,25 +873,60 @@ export default function App() {
if (!loggedInUser?.active_subscriptions) return false; if (!loggedInUser?.active_subscriptions) return false;
const hasLifetime = loggedInUser.active_subscriptions.some((sub: any) => const hasLifetime = loggedInUser.active_subscriptions.some((sub: any) =>
sub.plan_code === 'LIFETIME_ALL' || sub.plan_code === 'LIFETIME_ALL_USD' sub.plan_code === 'LIFETIME_ALL' ||
sub.plan_code === 'LIFETIME_ALL_USD' ||
sub.plan_code === 'LIFETIME_ALL_EUR'
); );
if (hasLifetime) return true; if (hasLifetime) return true;
const hasDirectSub = loggedInUser.active_subscriptions.some(
(sub: any) =>
sub.plan_code === code ||
sub.plan_code === `${code}_USD` ||
sub.plan_code === `${code}_EUR`
);
if (hasDirectSub) return true;
// Dynamic unlock check via /api/access/me unlocked_module_codes / unlocked_module_slugs
const unlockedCodes = new Set(
(loggedInUser.unlocked_module_codes || []).map((c: string) => c.toLowerCase()),
);
const unlockedSlugs = new Set(
(loggedInUser.unlocked_module_slugs || []).map((s: string) => s.toLowerCase()),
);
if (unlockedCodes.size > 0 || unlockedSlugs.size > 0) {
const matchedPlan = getLivePlan(code);
const planModules = matchedPlan?.modules || [];
if (planModules.length > 0) {
const allModulesUnlocked = planModules.every(
(m: any) =>
(m.code && unlockedCodes.has(String(m.code).toLowerCase())) ||
(m.slug && unlockedSlugs.has(String(m.slug).toLowerCase())),
);
if (allModulesUnlocked) return true;
}
const planSlugs = matchedPlan?.module_slugs || [];
if (planSlugs.length > 0 && planSlugs.every((s: string) => unlockedSlugs.has(s.toLowerCase()))) {
return true;
}
}
// Legacy fallback when publicPlans lacks module lists
if (code === 'POINTS_ACU' || code === 'POINTS_SCALP' || code === 'POINTS_EAR' || code === 'POINTS_TUNG') { if (code === 'POINTS_ACU' || code === 'POINTS_SCALP' || code === 'POINTS_EAR' || code === 'POINTS_TUNG') {
const hasPointsPack = loggedInUser.active_subscriptions.some((sub: any) => const hasPointsPack = loggedInUser.active_subscriptions.some((sub: any) =>
sub.plan_code === 'POINTS_PACK' || sub.plan_code === 'POINTS_PACK_USD' sub.plan_code === 'POINTS_PACK' || sub.plan_code === 'POINTS_PACK_USD' || sub.plan_code === 'POINTS_PACK_EUR'
); );
if (hasPointsPack) return true; if (hasPointsPack) return true;
} }
if (code === 'THERAPEUTICS_GYNAE' || code === 'THERAPEUTICS_EAR') { if (code === 'THERAPEUTICS_GYNAE' || code === 'THERAPEUTICS_EAR') {
const hasTherapeuticsPack = loggedInUser.active_subscriptions.some((sub: any) => const hasTherapeuticsPack = loggedInUser.active_subscriptions.some((sub: any) =>
sub.plan_code === 'THERAPEUTICS_CORE' || sub.plan_code === 'THERAPEUTICS_CORE_USD' sub.plan_code === 'THERAPEUTICS_CORE' || sub.plan_code === 'THERAPEUTICS_CORE_USD' || sub.plan_code === 'THERAPEUTICS_CORE_EUR'
); );
if (hasTherapeuticsPack) return true; if (hasTherapeuticsPack) return true;
} }
return loggedInUser.active_subscriptions.some((sub: any) => sub.plan_code === code || sub.plan_code === `${code}_USD`); return false;
}; };
// Automatically remove already unlocked modules from the cart // Automatically remove already unlocked modules from the cart
@ -795,6 +935,11 @@ export default function App() {
const filteredCart = cart.filter(item => !isModuleUnlocked(item.code)); const filteredCart = cart.filter(item => !isModuleUnlocked(item.code));
if (filteredCart.length !== cart.length) { if (filteredCart.length !== cart.length) {
setCart(filteredCart); setCart(filteredCart);
if (filteredCart.length === 0) {
setAppliedCoupon(null);
setCouponCode('');
setPricingCalc(null);
}
} }
} }
}, [loggedInUser, cart]); }, [loggedInUser, cart]);
@ -843,39 +988,22 @@ export default function App() {
return; return;
} }
if (!loggedInUser?.phone_number) { // Ensure the user has a valid billing contact phone number before opening Razorpay
const inputPhone = prompt("A billing phone number is required for Razorpay checkout. Please enter your contact number:"); const hasValidPhone = loggedInUser?.phone_number && isValidPhoneNumber(loggedInUser.phone_number, undefined, loggedInUser.country || 'India');
if (!inputPhone) { if (!hasValidPhone) {
setCheckoutLoading(false); setPendingCheckoutAfterPhone(true);
return; setShowBillingPhoneModal(true);
} setCheckoutLoading(false);
const cleanedPhone = cleanPhoneInput(inputPhone); return;
const phoneError = validatePhoneNumber(cleanedPhone, undefined, loggedInUser?.country || 'India');
if (phoneError) {
alert(phoneError);
setCheckoutLoading(false);
return;
}
try {
const res = await axios.put(`${API_BASE}/api/auth/profile`, {
phone_number: cleanedPhone
}, {
headers: { 'Authorization': `Bearer ${userToken}` }
});
if (res.data.status === 'success') {
loggedInUser.phone_number = inputPhone;
setLoggedInUser({ ...loggedInUser });
}
} catch (err: any) {
alert("Failed to save phone number: " + (err.response?.data?.detail || err.message));
setCheckoutLoading(false);
return;
}
} }
let isPaymentCancelled = false; let isPaymentCancelled = false;
let isPaymentCompleted = false; let isPaymentCompleted = false;
// Sanitize contact for Razorpay: strictly E.164 (+<dialCode><digits>)
const parsedContact = parsePhoneNumber(loggedInUser?.phone_number, loggedInUser?.country || 'India');
const sanitizedContact = formatE164Phone(parsedContact.dialCode, parsedContact.localDigits, loggedInUser?.country || 'India');
const rzpOptions = { const rzpOptions = {
key: razorpayKeyId, key: razorpayKeyId,
amount: Math.round(grand_total * 100), amount: Math.round(grand_total * 100),
@ -883,11 +1011,15 @@ export default function App() {
name: 'Acupedia', name: 'Acupedia',
description: cart.map(c => c.name).join(', '), description: cart.map(c => c.name).join(', '),
order_id: razorpay_order_id, order_id: razorpay_order_id,
customer_id: loggedInUser?.external_ref || undefined,
prefill: { prefill: {
name: loggedInUser?.display_name || '', name: loggedInUser?.display_name || '',
email: loggedInUser?.email || '', email: loggedInUser?.email || '',
contact: loggedInUser?.phone_number || loggedInUser?.phone || '' contact: sanitizedContact
},
readonly: {
contact: true,
email: true,
name: true
}, },
modal: { modal: {
confirm_close: true, confirm_close: true,
@ -940,6 +1072,8 @@ export default function App() {
setCart([]); setCart([]);
setAppliedCoupon(null); setAppliedCoupon(null);
setCouponCode('');
setPricingCalc(null);
await fetchUserProfile(userToken); await fetchUserProfile(userToken);
} catch (err: any) { } catch (err: any) {
setVerificationResult({ setVerificationResult({
@ -1001,7 +1135,11 @@ export default function App() {
activeTab={activeTab} activeTab={activeTab}
onSwitchTab={switchTab} onSwitchTab={switchTab}
loggedInUser={loggedInUser} loggedInUser={loggedInUser}
onOpenProfile={() => setShowProfileDrawer(true)} onOpenProfile={() => {
setChangePasswordSuccess(false);
setChangePasswordError(null);
setShowProfileDrawer(true);
}}
onOpenAuth={(mode) => { onOpenAuth={(mode) => {
setAuthMode(mode); setAuthMode(mode);
setShowAuthModal(true); setShowAuthModal(true);
@ -1033,7 +1171,6 @@ export default function App() {
<CartDrawer <CartDrawer
cart={cart} cart={cart}
currency={currency} currency={currency}
setCurrency={setCurrency}
toggleCartItem={toggleCartItem} toggleCartItem={toggleCartItem}
couponCode={couponCode} couponCode={couponCode}
setCouponCode={setCouponCode} setCouponCode={setCouponCode}
@ -1043,30 +1180,21 @@ export default function App() {
pricingCalc={pricingCalc} pricingCalc={pricingCalc}
loadingPricing={loadingPricing} loadingPricing={loadingPricing}
loggedInUser={loggedInUser} loggedInUser={loggedInUser}
onUpdateBillingPhone={async () => { onUpdateBillingPhone={() => setShowBillingPhoneModal(true)}
const newPhone = prompt("Enter billing phone number:", loggedInUser?.phone_number || '');
if (newPhone !== null && loggedInUser) {
try {
const res = await axios.put(`${API_BASE}/api/auth/profile`, {
phone_number: newPhone
}, {
headers: { 'Authorization': `Bearer ${userToken}` }
});
if (res.data.status === 'success') {
setLoggedInUser({ ...loggedInUser, phone_number: newPhone });
alert('Phone number updated successfully for billing!');
}
} catch (err: any) {
alert(err.response?.data?.detail || 'Failed to update phone number.');
}
}
}}
verificationResult={verificationResult} verificationResult={verificationResult}
checkoutLoading={checkoutLoading} checkoutLoading={checkoutLoading}
handleCheckout={handleCheckout} handleCheckout={handleCheckout}
/> />
</div> </div>
</div> </div>
) : activeTab === 'logged-out' ? (
<LoggedOutView
onLoginAgain={() => {
switchTab('storefront');
setAuthMode('login');
setShowAuthModal(true);
}}
/>
) : ( ) : (
/* 🧾 Tab: User Personal Subscriptions Ledger */ /* 🧾 Tab: User Personal Subscriptions Ledger */
<SubscriptionsView <SubscriptionsView
@ -1125,7 +1253,13 @@ export default function App() {
{verificationResult && verificationResult.status === 'success' && ( {verificationResult && verificationResult.status === 'success' && (
<PaymentSuccessModal <PaymentSuccessModal
verificationResult={verificationResult} verificationResult={verificationResult}
onClose={() => setVerificationResult(null)} onClose={() => {
setVerificationResult(null);
setCart([]);
setAppliedCoupon(null);
setCouponCode('');
setPricingCalc(null);
}}
loggedInUser={loggedInUser} loggedInUser={loggedInUser}
onDownloadInvoice={handleDownloadCheckoutInvoice} onDownloadInvoice={handleDownloadCheckoutInvoice}
downloadingInvoice={downloadingModalInvoice} downloadingInvoice={downloadingModalInvoice}
@ -1137,7 +1271,7 @@ export default function App() {
{/* 🧭 Profile Drawer */} {/* 🧭 Profile Drawer */}
<ProfileDrawer <ProfileDrawer
isOpen={showProfileDrawer} isOpen={showProfileDrawer}
onClose={() => setShowProfileDrawer(false)} onClose={handleCloseProfileDrawer}
loggedInUser={loggedInUser} loggedInUser={loggedInUser}
profileDisplayName={profileDisplayName} profileDisplayName={profileDisplayName}
setProfileDisplayName={setProfileDisplayName} setProfileDisplayName={setProfileDisplayName}
@ -1160,13 +1294,19 @@ export default function App() {
setChangeConfirmPassword={setChangeConfirmPassword} setChangeConfirmPassword={setChangeConfirmPassword}
changePasswordLoading={changePasswordLoading} changePasswordLoading={changePasswordLoading}
changePasswordError={changePasswordError} changePasswordError={changePasswordError}
setChangePasswordError={setChangePasswordError}
changePasswordSuccess={changePasswordSuccess} changePasswordSuccess={changePasswordSuccess}
setChangePasswordSuccess={setChangePasswordSuccess}
onChangePassword={handleChangePassword} onChangePassword={handleChangePassword}
onLogout={handleLogout} onLogout={handleLogout}
onBrowseStorefront={() => { onBrowseStorefront={() => {
setShowProfileDrawer(false); handleCloseProfileDrawer();
switchTab('storefront'); switchTab('storefront');
}} }}
onViewSubscriptions={() => {
handleCloseProfileDrawer();
switchTab('subscriptions');
}}
curriculumModules={curriculumModules} curriculumModules={curriculumModules}
onDownloadInvoice={handleDownloadCheckoutInvoice} onDownloadInvoice={handleDownloadCheckoutInvoice}
/> />
@ -1174,7 +1314,23 @@ export default function App() {
{/* 🔐 Password Updated Success Modal */} {/* 🔐 Password Updated Success Modal */}
<PasswordUpdatedModal <PasswordUpdatedModal
isOpen={passwordUpdatedPopup} isOpen={passwordUpdatedPopup}
onClose={() => setPasswordUpdatedPopup(false)} onClose={() => {
setPasswordUpdatedPopup(false);
setAuthMode('login');
setShowAuthModal(true);
}}
/>
{/* 📞 Billing Contact Phone Modal */}
<BillingPhoneModal
isOpen={showBillingPhoneModal}
onClose={() => {
setShowBillingPhoneModal(false);
setPendingCheckoutAfterPhone(false);
}}
currentPhone={loggedInUser?.phone_number}
currentCountry={loggedInUser?.country || profileCountry || 'India'}
onSavePhone={handleSaveBillingPhone}
/> />
</div> </div>
); );

View File

@ -3,8 +3,9 @@ import {
XCircle, Sparkles, AlertCircle, CheckCircle, RefreshCw, XCircle, Sparkles, AlertCircle, CheckCircle, RefreshCw,
Phone, Globe, Eye, EyeOff, LogIn, UserPlus Phone, Globe, Eye, EyeOff, LogIn, UserPlus
} from 'lucide-react'; } from 'lucide-react';
import { COUNTRY_CODES, getCountryRuleByDialCode, getCountryRuleByName } from '../../constants/countries'; import { getCountryRuleByName } from '../../constants/countries';
import { cleanPhoneInput } from '../../utils/validation'; import { CountrySelect } from '../common/CountrySelect';
import { PhoneInput } from '../common/PhoneInput';
interface AuthModalProps { interface AuthModalProps {
isOpen: boolean; isOpen: boolean;
@ -77,13 +78,12 @@ export const AuthModal: React.FC<AuthModalProps> = ({
onResetPasswordSubmit, onResetPasswordSubmit,
}) => { }) => {
const [showPassword, setShowPassword] = useState(false); const [showPassword, setShowPassword] = useState(false);
const activeRule = getCountryRuleByDialCode(authDialCode);
if (!isOpen) return null; if (!isOpen) return null;
return ( return (
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-slate-950/70 backdrop-blur-md transition-all duration-300"> <div className="fixed inset-0 z-[100] flex items-center justify-center p-3 sm:p-4 bg-slate-950/70 backdrop-blur-md transition-all duration-300 overflow-y-auto">
<div className="relative w-full max-w-md bg-slate-900 border border-slate-800 rounded-3xl p-6 md:p-8 space-y-6 shadow-2xl text-slate-100"> <div className="relative w-full max-w-md bg-slate-900 border border-slate-800 rounded-3xl p-5 sm:p-6 md:p-8 space-y-4 sm:space-y-6 shadow-2xl text-slate-100 max-h-[92vh] overflow-y-auto my-auto">
{/* Close button */} {/* Close button */}
<button <button
onClick={onClose} onClick={onClose}
@ -101,14 +101,14 @@ export const AuthModal: React.FC<AuthModalProps> = ({
{authMode === 'login' {authMode === 'login'
? 'Welcome Back!' ? 'Welcome Back!'
: authMode === 'register' : authMode === 'register'
? 'Create Clinical Account' ? 'Create Account'
: 'Reset Password'} : 'Reset Password'}
</h3> </h3>
<p className="text-xs text-slate-400 leading-relaxed font-semibold"> <p className="text-xs text-slate-400 leading-relaxed font-semibold">
{authMode === 'login' {authMode === 'login'
? 'Sign in to access your saved TCM modules and invoices.' ? 'Sign in to access your saved TCM modules and invoices.'
: authMode === 'register' : authMode === 'register'
? 'Onboard as a clinical practitioner to access TCM modules.' ? 'Sign up to get started and access TCM modules.'
: resetStep === 'request' : resetStep === 'request'
? 'Enter your registered email to receive a 6-digit verification code.' ? 'Enter your registered email to receive a 6-digit verification code.'
: 'Enter the 6-digit code sent to your email and your new password.'} : 'Enter the 6-digit code sent to your email and your new password.'}
@ -288,41 +288,25 @@ export const AuthModal: React.FC<AuthModalProps> = ({
<label className="text-[10px] uppercase font-black tracking-wider text-slate-500 flex items-center gap-1"> <label className="text-[10px] uppercase font-black tracking-wider text-slate-500 flex items-center gap-1">
<Phone className="h-3 w-3 text-indigo-400" /> Phone Number <Phone className="h-3 w-3 text-indigo-400" /> Phone Number
</label> </label>
<div className="flex gap-2"> <PhoneInput
<div className="relative"> dialCode={authDialCode}
<select phone={authPhone}
value={authDialCode} country={authCountry}
onChange={(e) => { clearOnDialCodeChange={true}
const newCode = e.target.value; onDialCodeChange={(newCode, newCountry) => {
setAuthDialCode(newCode); setAuthDialCode(newCode);
const rule = getCountryRuleByDialCode(newCode); setAuthCountry(newCountry);
if (rule && rule.country !== 'Other') { setAuthPhone('');
setAuthCountry(rule.country); }}
} onPhoneChange={(newPhone) => {
}} setAuthPhone(newPhone);
className="w-[90px] bg-slate-950 border border-slate-800 rounded-xl px-3 py-2.5 text-sm font-semibold text-white focus:outline-none focus:border-indigo-500 appearance-none" if (authError && (authError.toLowerCase().includes('phone') || authError.toLowerCase().includes('mobile'))) {
> setAuthError(null);
{COUNTRY_CODES.map((cc) => ( }
<option key={cc.code} value={cc.code}> }}
{cc.label} theme="dark"
</option> error={authError && (authError.toLowerCase().includes('phone') || authError.toLowerCase().includes('mobile')) ? authError : null}
))} />
</select>
</div>
<input
type="tel"
value={authPhone}
onChange={(e) => setAuthPhone(cleanPhoneInput(e.target.value, activeRule.maxLength))}
placeholder={activeRule.placeholder}
maxLength={activeRule.maxLength}
className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-4 py-2.5 text-sm font-semibold text-white focus:outline-none focus:border-indigo-500 placeholder:text-slate-700"
/>
</div>
<p className="text-[10px] text-slate-500 font-medium">
{activeRule.minLength === activeRule.maxLength
? `${activeRule.label || activeRule.country}: Requires exactly ${activeRule.maxLength} digits`
: `${activeRule.label || activeRule.country}: ${activeRule.minLength} to ${activeRule.maxLength} digits`}
</p>
</div> </div>
)} )}
@ -332,29 +316,23 @@ export const AuthModal: React.FC<AuthModalProps> = ({
<label className="text-[10px] uppercase font-black tracking-wider text-slate-500 flex items-center gap-1"> <label className="text-[10px] uppercase font-black tracking-wider text-slate-500 flex items-center gap-1">
<Globe className="h-3 w-3 text-indigo-400" /> Country (Defaults currency) <Globe className="h-3 w-3 text-indigo-400" /> Country (Defaults currency)
</label> </label>
<div className="relative"> <CountrySelect
<select value={authCountry}
value={authCountry} onChange={(newCountry) => {
onChange={(e) => { if (newCountry !== authCountry) {
const newCountry = e.target.value;
setAuthCountry(newCountry); setAuthCountry(newCountry);
const rule = getCountryRuleByName(newCountry); const rule = getCountryRuleByName(newCountry);
if (rule) { if (rule) {
setAuthDialCode(rule.code); setAuthDialCode(rule.code);
} }
}} setAuthPhone('');
className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-2.5 text-sm font-semibold text-white focus:outline-none focus:border-indigo-500 appearance-none" }
> }}
{COUNTRY_CODES.map((cc) => ( theme="dark"
<option key={cc.code} value={cc.country}> size="md"
{cc.country} (Calculates in {cc.currency} {cc.currency === 'INR' ? '₹' : '$'}) showCurrency={true}
</option> showDialCode={true}
))} />
</select>
<div className="absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none text-slate-500 text-xs">
▼
</div>
</div>
</div> </div>
)} )}
@ -409,7 +387,7 @@ export const AuthModal: React.FC<AuthModalProps> = ({
) : ( ) : (
<> <>
{authMode === 'login' ? <LogIn className="h-4 w-4" /> : <UserPlus className="h-4 w-4" />} {authMode === 'login' ? <LogIn className="h-4 w-4" /> : <UserPlus className="h-4 w-4" />}
{authMode === 'login' ? 'Sign In Session' : 'Register Clinical Profile'} {authMode === 'login' ? 'Sign In' : 'Create Account'}
</> </>
)} )}
</button> </button>
@ -430,7 +408,7 @@ export const AuthModal: React.FC<AuthModalProps> = ({
}} }}
className="text-indigo-400 hover:text-indigo-300 font-bold underline" className="text-indigo-400 hover:text-indigo-300 font-bold underline"
> >
{authMode === 'login' ? 'Create clinical account' : 'Sign in here'} {authMode === 'login' ? 'Create an account' : 'Sign in here'}
</button> </button>
</div> </div>
)} )}

View File

@ -0,0 +1,80 @@
import React from 'react';
import { LogOut, LogIn, ShieldCheck } from 'lucide-react';
interface LoggedOutViewProps {
onLoginAgain: () => void;
}
export const LoggedOutView: React.FC<LoggedOutViewProps> = ({
onLoginAgain,
}) => {
const isStorePrefix =
typeof window !== 'undefined' && window.location.pathname.startsWith('/store');
const basePath = isStorePrefix ? '/store/' : '/';
const loginUrl = `${basePath}?login=true`;
const loginDisplayUrl =
typeof window !== 'undefined'
? `${window.location.origin}${loginUrl}`
: loginUrl;
return (
<div className="flex-1 flex items-center justify-center py-10 px-4">
<div className="max-w-md w-full bg-white rounded-3xl border border-slate-200/80 shadow-xl shadow-slate-200/50 p-6 sm:p-8 text-center">
{/* Status Badge Icon */}
<div className="w-16 h-16 rounded-2xl bg-indigo-50 border border-indigo-100 flex items-center justify-center mx-auto mb-5 text-indigo-600 shadow-sm">
<LogOut className="w-8 h-8" />
</div>
{/* Title & Description */}
<h2 className="text-2xl font-black text-slate-900 tracking-tight mb-2">
Successfully Logged Out
</h2>
<p className="text-sm text-slate-500 mb-6 leading-relaxed">
You have been securely signed out of your AcuPedia session. Thank you for using our platform.
</p>
{/* Security Notice */}
<div className="bg-slate-50 border border-slate-100 rounded-2xl p-3.5 mb-6 text-left flex items-start gap-3">
<ShieldCheck className="w-4 h-4 text-emerald-600 flex-shrink-0 mt-0.5" />
<p className="text-xs text-slate-500 leading-normal">
For security, please close your browser window if you are using a shared or public device.
</p>
</div>
{/* Actions */}
<div>
{/* Primary: Log In Again via URL / Button */}
<a
href={loginUrl}
onClick={(e) => {
e.preventDefault();
onLoginAgain();
}}
className="w-full inline-flex items-center justify-center gap-2 px-5 py-3 rounded-xl text-xs sm:text-sm font-bold text-white bg-indigo-600 hover:bg-indigo-500 shadow-md shadow-indigo-600/20 transition-all hover:scale-[1.01] active:scale-[0.99] cursor-pointer"
>
<LogIn className="w-4 h-4" />
Log In Again
</a>
</div>
{/* Option to login in again via URL (explicit link for user / copy) */}
<div className="pt-6 border-t border-slate-100 mt-6 text-xs text-slate-400">
Want to sign in directly via URL?
<div className="mt-1">
<a
href={loginUrl}
onClick={(e) => {
e.preventDefault();
onLoginAgain();
}}
className="text-indigo-600 hover:text-indigo-700 font-semibold underline underline-offset-2 break-all"
>
{loginDisplayUrl}
</a>
</div>
</div>
</div>
</div>
);
};

View File

@ -4,9 +4,18 @@ import { CheckCircle } from 'lucide-react';
interface PasswordUpdatedModalProps { interface PasswordUpdatedModalProps {
isOpen: boolean; isOpen: boolean;
onClose: () => void; onClose: () => void;
title?: string;
description?: string;
buttonText?: string;
} }
export const PasswordUpdatedModal: React.FC<PasswordUpdatedModalProps> = ({ isOpen, onClose }) => { export const PasswordUpdatedModal: React.FC<PasswordUpdatedModalProps> = ({
isOpen,
onClose,
title = 'Password Updated!',
description = 'Your password has been securely updated. Please log in again with your new password to continue.',
buttonText = 'Log In with New Password'
}) => {
if (!isOpen) return null; if (!isOpen) return null;
return ( return (
@ -16,16 +25,16 @@ export const PasswordUpdatedModal: React.FC<PasswordUpdatedModalProps> = ({ isOp
<CheckCircle className="h-8 w-8" /> <CheckCircle className="h-8 w-8" />
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<h3 className="text-lg font-bold text-white">Password Updated!</h3> <h3 className="text-lg font-bold text-white">{title}</h3>
<p className="text-xs text-slate-400 leading-relaxed font-medium"> <p className="text-xs text-slate-400 leading-relaxed font-medium">
Your password has been securely updated. You can now use your new password across the storefront and mobile application. {description}
</p> </p>
</div> </div>
<button <button
onClick={onClose} onClick={onClose}
className="w-full py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs rounded-xl transition-colors shadow-lg shadow-emerald-600/20" className="w-full py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs rounded-xl transition-colors shadow-lg shadow-emerald-600/20 cursor-pointer"
> >
Continue to Storefront {buttonText}
</button> </button>
</div> </div>
</div> </div>

View File

@ -1,11 +1,13 @@
import React, { useState } from 'react'; import React, { useState, useEffect } from 'react';
import { import {
XCircle, Users, ShieldCheck, CheckCircle, AlertCircle, XCircle, Users, ShieldCheck, CheckCircle, AlertCircle,
Eye, EyeOff, RefreshCw, LogOut, Download Eye, EyeOff, RefreshCw, LogOut, Download
} from 'lucide-react'; } from 'lucide-react';
import type { UserProfile, ModuleItem, Currency } from '../../types'; import type { UserProfile, ModuleItem, Currency } from '../../types';
import { COUNTRY_CODES, getCountryRuleByName } from '../../constants/countries'; import { getCountryRuleByName } from '../../constants/countries';
import { cleanPhoneInput } from '../../utils/validation'; import { parsePhoneNumber, formatE164Phone, SPECIAL_CHAR_REGEX } from '../../utils/validation';
import { PhoneInput } from '../common/PhoneInput';
import { CountrySelect } from '../common/CountrySelect';
interface ProfileDrawerProps { interface ProfileDrawerProps {
isOpen: boolean; isOpen: boolean;
@ -32,10 +34,13 @@ interface ProfileDrawerProps {
setChangeConfirmPassword: (pwd: string) => void; setChangeConfirmPassword: (pwd: string) => void;
changePasswordLoading: boolean; changePasswordLoading: boolean;
changePasswordError: string | null; changePasswordError: string | null;
setChangePasswordError?: (err: string | null) => void;
changePasswordSuccess: boolean; changePasswordSuccess: boolean;
setChangePasswordSuccess?: (success: boolean) => void;
onChangePassword: (e: React.FormEvent) => Promise<void>; onChangePassword: (e: React.FormEvent) => Promise<void>;
onLogout: () => void; onLogout: () => void;
onBrowseStorefront: () => void; onBrowseStorefront: () => void;
onViewSubscriptions?: () => void;
curriculumModules: ModuleItem[]; curriculumModules: ModuleItem[];
onDownloadInvoice?: (paymentId: string, directUrl?: string) => void; onDownloadInvoice?: (paymentId: string, directUrl?: string) => void;
} }
@ -65,16 +70,67 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
setChangeConfirmPassword, setChangeConfirmPassword,
changePasswordLoading, changePasswordLoading,
changePasswordError, changePasswordError,
setChangePasswordError,
changePasswordSuccess, changePasswordSuccess,
setChangePasswordSuccess,
onChangePassword, onChangePassword,
onLogout, onLogout,
onBrowseStorefront, onBrowseStorefront,
onViewSubscriptions,
curriculumModules, curriculumModules,
onDownloadInvoice, onDownloadInvoice,
}) => { }) => {
const [showOldPassword, setShowOldPassword] = useState(false); const [showOldPassword, setShowOldPassword] = useState(false);
const [showNewPassword, setShowNewPassword] = useState(false); const [showNewPassword, setShowNewPassword] = useState(false);
const activeRule = getCountryRuleByName(profileCountry); const [showConfirmPassword, setShowConfirmPassword] = useState(false);
const parsed = parsePhoneNumber(profilePhone, profileCountry);
const [dialCode, setDialCode] = useState(parsed.dialCode);
const [localPhone, setLocalPhone] = useState(parsed.localDigits);
useEffect(() => {
if (isOpen) {
const p = parsePhoneNumber(profilePhone, profileCountry);
setDialCode(p.dialCode);
setLocalPhone(p.localDigits);
} else {
if (setChangePasswordSuccess) setChangePasswordSuccess(false);
if (setChangePasswordError) setChangePasswordError(null);
}
}, [isOpen, setChangePasswordSuccess, setChangePasswordError]);
const handleLocalPhoneChange = (newLocal: string) => {
setLocalPhone(newLocal);
setProfilePhone(newLocal ? formatE164Phone(dialCode, newLocal, profileCountry) : '');
};
const handleDialCodeChange = (newCode: string, newCountry: string) => {
setDialCode(newCode);
if (newCountry !== profileCountry) {
setProfileCountry(newCountry);
const rule = getCountryRuleByName(newCountry);
if (rule) {
setCurrency(rule.currency);
}
setLocalPhone('');
setProfilePhone('');
} else {
setProfilePhone(localPhone ? formatE164Phone(newCode, localPhone, profileCountry) : '');
}
};
const handleCountrySelectChange = (newCountry: string) => {
if (newCountry !== profileCountry) {
setProfileCountry(newCountry);
const rule = getCountryRuleByName(newCountry);
if (rule) {
setDialCode(rule.code);
setCurrency(rule.currency);
}
setLocalPhone('');
setProfilePhone('');
}
};
if (!isOpen || !loggedInUser) return null; if (!isOpen || !loggedInUser) return null;
@ -145,39 +201,29 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
<div className="space-y-1.5"> <div className="space-y-1.5">
<label className="text-xs font-bold text-slate-500">Phone Number</label> <label className="text-xs font-bold text-slate-500">Phone Number</label>
<input <PhoneInput
type="text" dialCode={dialCode}
value={profilePhone} phone={localPhone}
onChange={(e) => setProfilePhone(cleanPhoneInput(e.target.value, activeRule.maxLength))} country={profileCountry}
placeholder={activeRule.placeholder} clearOnDialCodeChange={true}
maxLength={activeRule.maxLength} onDialCodeChange={handleDialCodeChange}
className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-xs font-semibold text-slate-800 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500" onPhoneChange={handleLocalPhoneChange}
theme="light"
disabled={profileSaving}
error={profileError && (profileError.toLowerCase().includes('phone') || profileError.toLowerCase().includes('mobile')) ? profileError : null}
/> />
<p className="text-[10px] text-slate-400 font-medium">
{activeRule.minLength === activeRule.maxLength
? `${activeRule.label || activeRule.country}: Requires exactly ${activeRule.maxLength} digits`
: `${activeRule.label || activeRule.country}: ${activeRule.minLength} to ${activeRule.maxLength} digits`}
</p>
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<label className="text-xs font-bold text-slate-500">Billing Country</label> <label className="text-xs font-bold text-slate-500">Billing Country</label>
<select <CountrySelect
value={profileCountry} value={profileCountry}
onChange={(e) => { onChange={handleCountrySelectChange}
const newCountry = e.target.value; theme="light"
setProfileCountry(newCountry); size="sm"
const rule = getCountryRuleByName(newCountry); showDialCode={true}
setCurrency(rule.currency); showCurrency={false}
}} />
className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-xs font-semibold text-slate-800 focus:outline-none focus:border-indigo-500"
>
{COUNTRY_CODES.map((cc) => (
<option key={cc.code} value={cc.country}>
{cc.country}
</option>
))}
</select>
</div> </div>
<button <button
@ -200,6 +246,8 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
type="button" type="button"
onClick={() => { onClick={() => {
setShowPasswordChange(!showPasswordChange); setShowPasswordChange(!showPasswordChange);
if (setChangePasswordSuccess) setChangePasswordSuccess(false);
if (setChangePasswordError) setChangePasswordError(null);
}} }}
className="text-xs text-indigo-600 hover:text-indigo-700 font-bold" className="text-xs text-indigo-600 hover:text-indigo-700 font-bold"
> >
@ -269,14 +317,23 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
<div className="space-y-1"> <div className="space-y-1">
<label className="text-xs font-bold text-slate-500">Confirm New Password</label> <label className="text-xs font-bold text-slate-500">Confirm New Password</label>
<input <div className="relative">
type="password" <input
required type={showConfirmPassword ? 'text' : 'password'}
value={changeConfirmPassword} required
onChange={(e) => setChangeConfirmPassword(e.target.value)} value={changeConfirmPassword}
placeholder="Repeat new password" onChange={(e) => setChangeConfirmPassword(e.target.value)}
className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-xs font-semibold text-slate-800 focus:outline-none focus:border-indigo-500" placeholder="Repeat new password"
/> className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 pr-10 text-xs font-semibold text-slate-800 focus:outline-none focus:border-indigo-500"
/>
<button
type="button"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-0.5"
>
{showConfirmPassword ? <EyeOff className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
</button>
</div>
</div> </div>
<div className="flex flex-wrap gap-2 text-[10px] text-slate-500 pt-1"> <div className="flex flex-wrap gap-2 text-[10px] text-slate-500 pt-1">
@ -289,9 +346,12 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
<span className={/[0-9]/.test(changeNewPassword) ? 'text-emerald-600 font-bold' : ''}> <span className={/[0-9]/.test(changeNewPassword) ? 'text-emerald-600 font-bold' : ''}>
&bull; 1 number &bull; 1 number
</span> </span>
<span className={/[^A-Za-z0-9\s]/.test(changeNewPassword) ? 'text-emerald-600 font-bold' : ''}> <span className={SPECIAL_CHAR_REGEX.test(changeNewPassword) ? 'text-emerald-600 font-bold' : ''}>
&bull; 1 special char &bull; 1 special char
</span> </span>
<span className={changeNewPassword.length > 0 && !/\s/.test(changeNewPassword) ? 'text-emerald-600 font-bold' : ''}>
&bull; No spaces
</span>
</div> </div>
<button <button
@ -307,9 +367,20 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
{/* Subscriptions Nested Details */} {/* Subscriptions Nested Details */}
<div className="space-y-4"> <div className="space-y-4">
<h4 className="text-xs font-bold text-slate-400 uppercase tracking-widest flex items-center gap-1.5"> <div className="flex items-center justify-between">
<CheckCircle className="h-4 w-4 text-emerald-500" /> Ongoing subscriptions <h4 className="text-xs font-bold text-slate-400 uppercase tracking-widest flex items-center gap-1.5">
</h4> <CheckCircle className="h-4 w-4 text-emerald-500" /> Ongoing subscriptions
</h4>
{onViewSubscriptions && (
<button
type="button"
onClick={onViewSubscriptions}
className="text-xs text-indigo-600 hover:text-indigo-500 font-bold hover:underline"
>
View All
</button>
)}
</div>
{!loggedInUser.active_subscriptions || loggedInUser.active_subscriptions.length === 0 ? ( {!loggedInUser.active_subscriptions || loggedInUser.active_subscriptions.length === 0 ? (
<div className="bg-slate-50 border border-slate-200/60 rounded-2xl p-6 text-center space-y-2"> <div className="bg-slate-50 border border-slate-200/60 rounded-2xl p-6 text-center space-y-2">

View File

@ -1,11 +1,11 @@
import React from 'react'; import React from 'react';
import { ShoppingCart, ShoppingBag, Trash2, RefreshCw, CreditCard, XCircle } from 'lucide-react'; import { ShoppingCart, ShoppingBag, Trash2, RefreshCw, CreditCard, XCircle, Globe } from 'lucide-react';
import type { ModuleItem, Currency, UserProfile, VerificationResult } from '../../types'; import type { ModuleItem, Currency, UserProfile, VerificationResult } from '../../types';
import { isValidPhoneNumber } from '../../utils/validation';
interface CartDrawerProps { interface CartDrawerProps {
cart: ModuleItem[]; cart: ModuleItem[];
currency: Currency; currency: Currency;
setCurrency: (c: Currency) => void;
toggleCartItem: (module: ModuleItem) => void; toggleCartItem: (module: ModuleItem) => void;
couponCode: string; couponCode: string;
setCouponCode: (code: string) => void; setCouponCode: (code: string) => void;
@ -24,7 +24,6 @@ interface CartDrawerProps {
export const CartDrawer: React.FC<CartDrawerProps> = ({ export const CartDrawer: React.FC<CartDrawerProps> = ({
cart, cart,
currency, currency,
setCurrency,
toggleCartItem, toggleCartItem,
couponCode, couponCode,
setCouponCode, setCouponCode,
@ -76,28 +75,23 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
</span> </span>
</div> </div>
{/* Currency selector toggle */} {/* Billing Currency & Region Badge */}
<div className="flex flex-col sm:flex-row gap-2 sm:items-center justify-between"> <div className="flex items-center justify-between p-2.5 bg-slate-50 border border-slate-200/70 rounded-xl">
<span className="text-xs font-bold text-slate-500">Billing Currency:</span> <div className="flex items-center gap-1.5 min-w-0">
<div className="flex bg-slate-100 rounded-lg p-0.5 border border-slate-200 self-end sm:self-auto flex-shrink-0"> <Globe className="h-3.5 w-3.5 text-indigo-500 shrink-0" />
<button <span className="text-xs font-semibold text-slate-600 truncate">
onClick={() => setCurrency('INR')} {loggedInUser ? 'Billing Currency' : 'Estimated Currency'}:
className={`px-3 py-1 rounded-md text-xs font-bold transition-all duration-300 ${currency === 'INR' </span>
? 'bg-white text-slate-900 shadow-sm border border-slate-200/50' </div>
: 'text-slate-500 hover:text-slate-800' <div className="flex items-center gap-1.5 shrink-0">
}`} <span className="text-[11px] bg-white border border-slate-200 font-extrabold text-slate-800 px-2 py-0.5 rounded-md shadow-xs">
> {currency === 'INR' ? 'INR (₹)' : currency === 'EUR' ? 'EUR (€)' : 'USD ($)'}
INR (₹) </span>
</button> {loggedInUser?.country && (
<button <span className="text-[10px] text-slate-400 font-semibold max-w-[90px] truncate" title={loggedInUser.country}>
onClick={() => setCurrency('USD')} • {loggedInUser.country}
className={`px-3 py-1 rounded-md text-xs font-bold transition-all duration-300 ${currency === 'USD' </span>
? 'bg-white text-slate-900 shadow-sm border border-slate-200/50' )}
: 'text-slate-500 hover:text-slate-800'
}`}
>
USD ($)
</button>
</div> </div>
</div> </div>
@ -113,36 +107,55 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
</div> </div>
) : ( ) : (
<div className="space-y-3 max-h-[220px] overflow-y-auto pr-1"> <div className="space-y-3 max-h-[220px] overflow-y-auto pr-1">
{cart.map((item) => ( {cart.map((item) => {
<div const isCompletePackage =
key={item.code} item.code === 'POINTS_PACK' ||
className="flex justify-between items-center gap-4 bg-slate-50 border border-slate-200/60 p-3 rounded-2xl" item.code === 'PATTERN_CORE' ||
> item.code === 'NUTRITION_CORE' ||
<div className="flex-1 min-w-0"> item.code === 'THERAPEUTICS_CORE' ||
<p className="text-xs font-bold text-slate-800 truncate">{item.name}</p> item.name.toLowerCase().includes('complete pack') ||
<p className="text-[9px] text-slate-400 tracking-wider uppercase font-semibold">{item.category}</p> item.name.toLowerCase().includes('complete package') ||
item.name.toLowerCase().includes('complete bundle') ||
item.category === 'Bundle';
return (
<div
key={item.code}
className="flex justify-between items-center gap-4 bg-slate-50 border border-slate-200/60 p-3 rounded-2xl"
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5 flex-wrap min-w-0">
<p className="text-xs font-bold text-slate-800 truncate">{item.name}</p>
{isCompletePackage && (
<span className="text-[8px] bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-extrabold px-1.5 py-0.5 rounded tracking-wider uppercase flex-shrink-0">
Complete Pack
</span>
)}
</div>
<p className="text-[9px] text-slate-400 tracking-wider uppercase font-semibold">{item.category}</p>
</div>
<div className="flex items-center gap-3">
<span className="text-xs font-bold text-indigo-600">
{(() => {
const calculatedItem = activePricing?.cart_items?.find((ci: any) => ci.code === item.code);
const price = calculatedItem
? calculatedItem.price
: (currency === 'INR' ? item.priceInr : currency === 'EUR' ? item.priceEur : item.priceUsd);
const symbol = currency === 'INR' ? '₹' : currency === 'EUR' ? '€' : '$';
return `${symbol}${price}`;
})()}
</span>
<button
onClick={() => toggleCartItem(item)}
className="h-7 w-7 rounded-lg bg-rose-50 text-rose-500 hover:bg-rose-100 flex items-center justify-center transition-colors"
title="Remove item"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
</div> </div>
<div className="flex items-center gap-3"> );
<span className="text-xs font-bold text-indigo-600"> })}
{(() => {
const calculatedItem = activePricing?.cart_items?.find((ci: any) => ci.code === item.code);
const price = calculatedItem
? calculatedItem.price
: (currency === 'INR' ? item.priceInr : currency === 'EUR' ? item.priceEur : item.priceUsd);
const symbol = currency === 'INR' ? '₹' : currency === 'EUR' ? '€' : '$';
return `${symbol}${price}`;
})()}
</span>
<button
onClick={() => toggleCartItem(item)}
className="h-7 w-7 rounded-lg bg-rose-50 text-rose-500 hover:bg-rose-100 flex items-center justify-center transition-colors"
title="Remove item"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
</div>
))}
</div> </div>
)} )}
@ -332,22 +345,32 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
<span className="text-[10px] uppercase font-black tracking-wider text-slate-400"> <span className="text-[10px] uppercase font-black tracking-wider text-slate-400">
Billing Profile Billing Profile
</span> </span>
<button {(!loggedInUser.phone_number || !isValidPhoneNumber(loggedInUser.phone_number, undefined, loggedInUser.country || 'India')) && (
onClick={onUpdateBillingPhone} <button
className="text-[9px] text-indigo-600 hover:text-indigo-500 font-black uppercase tracking-wider underline focus:outline-none" onClick={onUpdateBillingPhone}
> className="text-[9px] text-indigo-600 hover:text-indigo-500 font-black uppercase tracking-wider underline focus:outline-none"
{loggedInUser.phone_number ? 'Edit Number' : 'Add Number'} >
</button> {loggedInUser.phone_number ? 'Update Number' : 'Add Number'}
</button>
)}
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<div className="flex justify-between text-xs font-semibold text-slate-600"> <div className="flex justify-between text-xs font-semibold text-slate-600">
<span>Email:</span> <span>Email:</span>
<span className="text-slate-800 font-bold truncate max-w-[180px]">{loggedInUser.email}</span> <span className="text-slate-800 font-bold truncate max-w-[180px]">{loggedInUser.email}</span>
</div> </div>
<div className="flex justify-between text-xs font-semibold text-slate-600">
<span>Billing Country:</span>
<span className="text-slate-800 font-bold truncate max-w-[180px]">{loggedInUser.country || 'India'}</span>
</div>
<div className="flex justify-between text-xs font-semibold text-slate-600"> <div className="flex justify-between text-xs font-semibold text-slate-600">
<span>Phone:</span> <span>Phone:</span>
<span className="text-slate-800 font-bold"> <span className="text-slate-800 font-bold">
{loggedInUser.phone_number || ( {loggedInUser.phone_number && isValidPhoneNumber(loggedInUser.phone_number, undefined, loggedInUser.country || 'India') ? (
loggedInUser.phone_number
) : loggedInUser.phone_number ? (
<span className="text-amber-600 font-black italic">Incomplete ({loggedInUser.phone_number})</span>
) : (
<span className="text-rose-500 font-black italic">Required for checkout</span> <span className="text-rose-500 font-black italic">Required for checkout</span>
)} )}
</span> </span>
@ -387,6 +410,15 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
<p className="text-[10px] text-slate-400 text-center leading-relaxed font-semibold"> <p className="text-[10px] text-slate-400 text-center leading-relaxed font-semibold">
* Integrated with Razorpay Gateway API (Test Mode). * Integrated with Razorpay Gateway API (Test Mode).
</p> </p>
<p className="text-[10px] text-slate-400 text-center font-medium">
Billing currency is tied to your country. Need billing assistance?{' '}
<a
href="mailto:support@acupedia.com?subject=Billing%20Support%20Inquiry"
className="text-indigo-600 hover:underline font-bold"
>
Contact Support
</a>
</p>
</div> </div>
)} )}
</div> </div>

View File

@ -1,6 +1,7 @@
import React from 'react'; import React from 'react';
import { BookOpen, Check } from 'lucide-react'; import { BookOpen, Check } from 'lucide-react';
import type { ModuleItem, PublicPlan, Currency } from '../../types'; import type { ModuleItem, PublicPlan, Currency } from '../../types';
import { CORE_PACK_CODES, MAIN_CATEGORIES, resolvePlanCategory } from '../../utils/catalog';
interface CatalogSectionProps { interface CatalogSectionProps {
curriculumModules: ModuleItem[]; curriculumModules: ModuleItem[];
@ -30,6 +31,11 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
showLockedByCategory, showLockedByCategory,
setShowLockedByCategory, setShowLockedByCategory,
}) => { }) => {
const countLockedActive = (predicate: (category: string) => boolean) =>
curriculumModules.filter(
m => predicate(m.category) && !isModuleUnlocked(m.code) && getModulePrice(m).isActive
).length;
return ( return (
<div className="xl:col-span-2 space-y-6"> <div className="xl:col-span-2 space-y-6">
<div className="space-y-2"> <div className="space-y-2">
@ -57,7 +63,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Points: !prev.Points }))} onClick={() => setShowLockedByCategory(prev => ({ ...prev, Points: !prev.Points }))}
className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0" className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0"
> >
{showLockedByCategory.Points ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Points' && !isModuleUnlocked(m.code)).length}) {showLockedByCategory.Points ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Points')})
</button> </button>
</div> </div>
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0"> <span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
@ -72,7 +78,9 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
<div className="space-y-2"> <div className="space-y-2">
{(() => { {(() => {
const items = curriculumModules.filter(m => m.category === 'Points'); const items = curriculumModules
.filter(m => m.category === 'Points')
.sort((a, b) => (a.sortOrder ?? 500) - (b.sortOrder ?? 500));
const visible = items.filter(sub => { const visible = items.filter(sub => {
const isUnlocked = isModuleUnlocked(sub.code); const isUnlocked = isModuleUnlocked(sub.code);
const live = getModulePrice(sub); const live = getModulePrice(sub);
@ -176,7 +184,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Pattern: !prev.Pattern }))} onClick={() => setShowLockedByCategory(prev => ({ ...prev, Pattern: !prev.Pattern }))}
className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0" className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0"
> >
{showLockedByCategory.Pattern ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Pattern' && !isModuleUnlocked(m.code)).length}) {showLockedByCategory.Pattern ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Pattern' || c === 'Patterns')})
</button> </button>
</div> </div>
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0"> <span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
@ -191,7 +199,9 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
<div className="space-y-2"> <div className="space-y-2">
{(() => { {(() => {
const items = curriculumModules.filter(m => m.category === 'Pattern'); const items = curriculumModules
.filter(m => m.category === 'Pattern' || m.category === 'Patterns')
.sort((a, b) => (a.sortOrder ?? 500) - (b.sortOrder ?? 500));
const visible = items.filter(sub => { const visible = items.filter(sub => {
const isUnlocked = isModuleUnlocked(sub.code); const isUnlocked = isModuleUnlocked(sub.code);
const live = getModulePrice(sub); const live = getModulePrice(sub);
@ -239,7 +249,12 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
> >
<div className="flex-1 pr-2"> <div className="flex-1 pr-2">
<div className="flex items-center gap-1.5 flex-wrap"> <div className="flex items-center gap-1.5 flex-wrap">
<span className="text-xs font-bold text-slate-800">{sub.name}</span> <span className="text-xs font-bold text-slate-800">{sub.name.replace("Pattern: ", "")}</span>
{sub.name.includes('Complete Pack') && (
<span className="text-[8px] bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-extrabold px-1.5 py-0.5 rounded tracking-wider uppercase">
Complete Pack
</span>
)}
{!isUnlocked && !live.isActive && ( {!isUnlocked && !live.isActive && (
<span className="text-[8px] bg-slate-200 text-slate-600 font-bold px-1.5 py-0.5 rounded tracking-wider uppercase"> <span className="text-[8px] bg-slate-200 text-slate-600 font-bold px-1.5 py-0.5 rounded tracking-wider uppercase">
Temporarily Unavailable Temporarily Unavailable
@ -290,7 +305,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Nutrition: !prev.Nutrition }))} onClick={() => setShowLockedByCategory(prev => ({ ...prev, Nutrition: !prev.Nutrition }))}
className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0" className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0"
> >
{showLockedByCategory.Nutrition ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Nutrition' && !isModuleUnlocked(m.code)).length}) {showLockedByCategory.Nutrition ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Nutrition')})
</button> </button>
</div> </div>
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0"> <span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
@ -305,7 +320,9 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
<div className="space-y-2"> <div className="space-y-2">
{(() => { {(() => {
const items = curriculumModules.filter(m => m.category === 'Nutrition'); const items = curriculumModules
.filter(m => m.category === 'Nutrition')
.sort((a, b) => (a.sortOrder ?? 500) - (b.sortOrder ?? 500));
const visible = items.filter(sub => { const visible = items.filter(sub => {
const isUnlocked = isModuleUnlocked(sub.code); const isUnlocked = isModuleUnlocked(sub.code);
const live = getModulePrice(sub); const live = getModulePrice(sub);
@ -353,7 +370,12 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
> >
<div className="flex-1 pr-2"> <div className="flex-1 pr-2">
<div className="flex items-center gap-1.5 flex-wrap"> <div className="flex items-center gap-1.5 flex-wrap">
<span className="text-xs font-bold text-slate-800">{sub.name}</span> <span className="text-xs font-bold text-slate-800">{sub.name.replace("Nutrition: ", "")}</span>
{sub.name.includes('Complete Pack') && (
<span className="text-[8px] bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-extrabold px-1.5 py-0.5 rounded tracking-wider uppercase">
Complete Pack
</span>
)}
{!isUnlocked && !live.isActive && ( {!isUnlocked && !live.isActive && (
<span className="text-[8px] bg-slate-200 text-slate-600 font-bold px-1.5 py-0.5 rounded tracking-wider uppercase"> <span className="text-[8px] bg-slate-200 text-slate-600 font-bold px-1.5 py-0.5 rounded tracking-wider uppercase">
Temporarily Unavailable Temporarily Unavailable
@ -404,7 +426,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Therapeutics: !prev.Therapeutics }))} onClick={() => setShowLockedByCategory(prev => ({ ...prev, Therapeutics: !prev.Therapeutics }))}
className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0" className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0"
> >
{showLockedByCategory.Therapeutics ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Therapeutics' && !isModuleUnlocked(m.code)).length}) {showLockedByCategory.Therapeutics ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Therapeutics')})
</button> </button>
</div> </div>
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0"> <span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
@ -419,7 +441,9 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
<div className="space-y-2"> <div className="space-y-2">
{(() => { {(() => {
const items = curriculumModules.filter(m => m.category === 'Therapeutics'); const items = curriculumModules
.filter(m => m.category === 'Therapeutics')
.sort((a, b) => (a.sortOrder ?? 500) - (b.sortOrder ?? 500));
const visible = items.filter(sub => { const visible = items.filter(sub => {
const isUnlocked = isModuleUnlocked(sub.code); const isUnlocked = isModuleUnlocked(sub.code);
const live = getModulePrice(sub); const live = getModulePrice(sub);
@ -469,7 +493,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
<div className="flex items-center gap-1.5 flex-wrap"> <div className="flex items-center gap-1.5 flex-wrap">
<span className="text-xs font-bold text-slate-800">{sub.name.replace("Therapeutics: ", "")}</span> <span className="text-xs font-bold text-slate-800">{sub.name.replace("Therapeutics: ", "")}</span>
{sub.code === 'THERAPEUTICS_CORE' && ( {sub.code === 'THERAPEUTICS_CORE' && (
<span className="text-[8px] bg-gradient-to-r from-indigo-500 to-cyan-500 text-white font-extrabold px-1.5 py-0.5 rounded tracking-wider uppercase"> <span className="text-[8px] bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-extrabold px-1.5 py-0.5 rounded tracking-wider uppercase">
Complete Pack Complete Pack
</span> </span>
)} )}
@ -524,7 +548,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Lifetime: !prev.Lifetime }))} onClick={() => setShowLockedByCategory(prev => ({ ...prev, Lifetime: !prev.Lifetime }))}
className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-2 py-1 rounded transition-colors" className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-2 py-1 rounded transition-colors"
> >
{showLockedByCategory.Lifetime ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Lifetime' && !isModuleUnlocked(m.code)).length}) {showLockedByCategory.Lifetime ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Lifetime')})
</button> </button>
</div> </div>
<h3 className="text-xl font-black text-amber-900 tracking-tight">Lifetime Unlimited Access Pass</h3> <h3 className="text-xl font-black text-amber-900 tracking-tight">Lifetime Unlimited Access Pass</h3>
@ -549,7 +573,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
<button <button
type="button" type="button"
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Lifetime: true }))} onClick={() => setShowLockedByCategory(prev => ({ ...prev, Lifetime: true }))}
className="mt-1 text-xs text-amber-900 hover:text-black font-bold hover:underline cursor-pointer" className="mt-1 text-xs text-amber-900 hover:text-amber-950 font-bold hover:underline cursor-pointer"
> >
Click here to show locked pass Click here to show locked pass
</button> </button>
@ -623,10 +647,15 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
{/* CARD 6: Custom Packages & Bundles (Dynamic Admin Plans) */} {/* CARD 6: Custom Packages & Bundles (Dynamic Admin Plans) */}
{(() => { {(() => {
const customPlans = publicPlans.filter((p: any) => { const customPlans = publicPlans.filter((p: any) => {
const code = p.base_code || p.code; const code = (p.base_code || p.code || '').toUpperCase();
const isCustom = !['POINTS_ACU', 'POINTS_SCALP', 'POINTS_EAR', 'POINTS_TUNG', 'POINTS_PACK', 'PATTERN_CORE', 'NUTRITION_CORE', 'THERAPEUTICS_GYNAE', 'THERAPEUTICS_EAR', 'THERAPEUTICS_CORE', 'LIFETIME_ALL'].includes(code); const activePrice = currency === 'INR' ? (p.price_inr ?? 0) : currency === 'EUR' ? (p.price_eur ?? p.price_usd ?? 0) : (p.price_usd ?? 0);
const isActive = p.is_active !== false; const isActive = p.is_active !== false && activePrice > 0;
return isCustom && isActive; if (!isActive || code === 'LIFETIME_ALL' || CORE_PACK_CODES.has(code)) return false;
if (p.plan_type === 'bundle') return true;
const resolvedCat =
curriculumModules.find((m) => m.code.toUpperCase() === code)?.category ||
resolvePlanCategory(p);
return !MAIN_CATEGORIES.has(resolvedCat) && resolvedCat !== 'Lifetime';
}); });
if (customPlans.length === 0) return null; if (customPlans.length === 0) return null;
@ -665,7 +694,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
category: 'Bundle', category: 'Bundle',
priceInr: pInr, priceInr: pInr,
priceUsd: pUsd, priceUsd: pUsd,
priceEur: pUsd, priceEur: cPlan.price_eur ?? pUsd,
desc: cPlan.description || 'Custom bundled access.', desc: cPlan.description || 'Custom bundled access.',
color: 'from-slate-700 to-slate-900' color: 'from-slate-700 to-slate-900'
}; };
@ -717,7 +746,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
</span> </span>
) : ( ) : (
<span className="text-xs font-extrabold text-slate-700"> <span className="text-xs font-extrabold text-slate-700">
{currency === 'INR' ? `₹${pInr}` : `$${pUsd}`} {currency === 'INR' ? `₹${pInr}` : currency === 'EUR' ? `€${cPlan.price_eur ?? pUsd}` : `$${pUsd}`}
</span> </span>
)} )}
{!isUnlocked && ( {!isUnlocked && (

View File

@ -0,0 +1,178 @@
import React, { useState, useEffect } from 'react';
import { X, Phone, ShieldCheck, RefreshCw, Globe } from 'lucide-react';
import { PhoneInput } from '../common/PhoneInput';
import { CountrySelect } from '../common/CountrySelect';
import { getCountryRuleByName } from '../../constants/countries';
import { parsePhoneNumber, validatePhoneNumber, formatE164Phone } from '../../utils/validation';
interface BillingPhoneModalProps {
isOpen: boolean;
onClose: () => void;
currentPhone?: string | null;
currentCountry?: string;
onSavePhone: (phoneE164: string, country: string) => Promise<boolean>;
}
export const BillingPhoneModal: React.FC<BillingPhoneModalProps> = ({
isOpen,
onClose,
currentPhone,
currentCountry = 'India',
onSavePhone,
}) => {
const [dialCode, setDialCode] = useState('+91');
const [country, setCountry] = useState(currentCountry);
const [phone, setPhone] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (isOpen) {
const parsed = parsePhoneNumber(currentPhone, currentCountry);
setCountry(parsed.country);
setDialCode(parsed.dialCode);
setPhone(parsed.localDigits);
setError(null);
setSaving(false);
}
}, [isOpen, currentPhone, currentCountry]);
if (!isOpen) return null;
const handleCountryChange = (newCountry: string) => {
if (newCountry !== country) {
setCountry(newCountry);
const rule = getCountryRuleByName(newCountry);
if (rule) {
setDialCode(rule.code);
}
setPhone('');
setError(null);
}
};
const handleDialCodeChange = (newCode: string, newCountry: string) => {
setDialCode(newCode);
if (newCountry !== country) {
setCountry(newCountry);
setPhone('');
}
setError(null);
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
if (!phone.trim()) {
setError('Please enter your mobile number.');
return;
}
const valError = validatePhoneNumber(phone, dialCode, country);
if (valError) {
setError(valError);
return;
}
setSaving(true);
const e164 = formatE164Phone(dialCode, phone, country);
try {
const success = await onSavePhone(e164, country);
if (success) {
onClose();
}
} catch (err: any) {
setError(err?.message || 'Failed to save billing phone number.');
} finally {
setSaving(false);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/70 backdrop-blur-sm animate-fadeIn">
<div
className="bg-white rounded-3xl max-w-md w-full p-6 shadow-2xl border border-slate-100 space-y-5"
onClick={(e) => e.stopPropagation()}
>
<div className="flex justify-between items-start">
<div className="flex items-center gap-3">
<div className="h-10 w-10 rounded-2xl bg-indigo-50 border border-indigo-100 flex items-center justify-center text-indigo-600">
<Phone className="h-5 w-5" />
</div>
<div>
<h3 className="text-base font-black text-slate-800">Billing Contact Number</h3>
<p className="text-xs text-slate-400 font-medium">Required for Razorpay invoice & payment updates</p>
</div>
</div>
<button
onClick={onClose}
className="p-1 rounded-full text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors"
>
<X className="h-5 w-5" />
</button>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-1.5">
<label className="text-xs font-bold text-slate-600 flex items-center gap-1">
Mobile Number
</label>
<PhoneInput
dialCode={dialCode}
phone={phone}
country={country}
clearOnDialCodeChange={true}
onDialCodeChange={handleDialCodeChange}
onPhoneChange={(newPhone) => {
setPhone(newPhone);
setError(null);
}}
error={error}
theme="light"
disabled={saving}
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-slate-600 flex items-center gap-1">
<Globe className="h-3.5 w-3.5 text-indigo-500" /> Billing Country
</label>
<CountrySelect
value={country}
onChange={handleCountryChange}
theme="light"
size="md"
showDialCode={true}
showCurrency={false}
disabled={saving}
/>
</div>
<div className="flex items-center gap-2 text-[11px] text-slate-500 bg-slate-50 p-3 rounded-xl border border-slate-200/60">
<ShieldCheck className="h-4 w-4 text-emerald-500 flex-shrink-0" />
<span>This contact number and billing country will appear on your compliance tax invoice and payment receipts.</span>
</div>
<div className="flex gap-3 pt-2">
<button
type="button"
onClick={onClose}
disabled={saving}
className="flex-1 py-2.5 px-4 rounded-xl text-xs font-bold bg-slate-100 hover:bg-slate-200 text-slate-600 transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={saving}
className="flex-1 py-2.5 px-4 rounded-xl text-xs font-bold bg-indigo-600 hover:bg-indigo-500 text-white transition-colors flex items-center justify-center gap-1.5 shadow-md shadow-indigo-600/20 disabled:opacity-50"
>
{saving ? <RefreshCw className="h-4 w-4 animate-spin" /> : 'Save Phone Number'}
</button>
</div>
</form>
</div>
</div>
);
};

View File

@ -101,8 +101,8 @@ export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
onClose(); onClose();
}; };
return ( return (
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-slate-950/75 backdrop-blur-md transition-all duration-300"> <div className="fixed inset-0 z-[100] flex items-center justify-center p-3 sm:p-4 bg-slate-950/75 backdrop-blur-md transition-all duration-300 overflow-y-auto">
<div className="relative w-full max-w-xl bg-slate-900 border border-slate-800 rounded-2xl p-5 md:p-6 space-y-4 shadow-2xl text-slate-100 overflow-hidden animate-in fade-in zoom-in-95 duration-200"> <div className="relative w-full max-w-xl bg-slate-900 border border-slate-800 rounded-2xl p-4 sm:p-5 md:p-6 space-y-3 sm:space-y-4 shadow-2xl text-slate-100 max-h-[92vh] overflow-y-auto my-auto animate-in fade-in zoom-in-95 duration-200">
{/* Ambient Background Glow */} {/* Ambient Background Glow */}
<div className="absolute -top-10 left-1/2 -translate-x-1/2 w-48 h-48 bg-emerald-500/10 rounded-full blur-3xl pointer-events-none" /> <div className="absolute -top-10 left-1/2 -translate-x-1/2 w-48 h-48 bg-emerald-500/10 rounded-full blur-3xl pointer-events-none" />
@ -254,9 +254,9 @@ export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
)} )}
</div> </div>
</div> </div>
<div className="flex justify-between items-center text-slate-400 font-semibold"> <div className="flex justify-between items-center text-slate-400 font-semibold gap-2">
<span>Payment ID</span> <span className="shrink-0">Payment ID</span>
<span className="text-white font-mono font-bold bg-slate-800 px-2 py-0.5 rounded text-[10px] border border-slate-700/50"> <span className="text-white font-mono font-bold bg-slate-800 px-2 py-0.5 rounded text-[10px] border border-slate-700/50 break-all text-right">
{verificationResult.paymentId} {verificationResult.paymentId}
</span> </span>
</div> </div>

View File

@ -0,0 +1,234 @@
import React, { useState, useRef, useEffect, useMemo } from 'react';
import { Search, ChevronDown, Check, X } from 'lucide-react';
import { SORTED_COUNTRY_CODES, getCountryRuleByName, type CountryCode } from '../../constants/countries';
export interface CountrySelectProps {
value: string;
onChange: (country: string) => void;
theme?: 'dark' | 'light';
size?: 'sm' | 'md';
showCurrency?: boolean;
showDialCode?: boolean;
disabled?: boolean;
className?: string;
placeholder?: string;
}
export const CountrySelect: React.FC<CountrySelectProps> = ({
value,
onChange,
theme = 'light',
size = 'md',
showCurrency = false,
showDialCode = true,
disabled = false,
className = '',
placeholder = 'Select country',
}) => {
const [isOpen, setIsOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const containerRef = useRef<HTMLDivElement>(null);
const searchInputRef = useRef<HTMLInputElement>(null);
const selectedRule = useMemo(() => {
return getCountryRuleByName(value);
}, [value]);
// Focus search input when dropdown opens
useEffect(() => {
if (isOpen) {
setTimeout(() => {
searchInputRef.current?.focus();
}, 50);
} else {
setSearchQuery('');
}
}, [isOpen]);
// Handle click outside to close dropdown
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
setIsOpen(false);
}
};
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
setIsOpen(false);
}
};
if (isOpen) {
document.addEventListener('mousedown', handleClickOutside);
document.addEventListener('keydown', handleKeyDown);
}
return () => {
document.removeEventListener('mousedown', handleClickOutside);
document.removeEventListener('keydown', handleKeyDown);
};
}, [isOpen]);
// Filter countries alphabetically by country name, dial code, or currency
const filteredCountries = useMemo(() => {
if (!searchQuery.trim()) {
return SORTED_COUNTRY_CODES;
}
const q = searchQuery.toLowerCase().trim();
return SORTED_COUNTRY_CODES.filter((c: CountryCode) => {
const matchName = c.country.toLowerCase().includes(q);
const matchCode = c.code.toLowerCase().includes(q);
const matchCurrency = c.currency ? c.currency.toLowerCase().includes(q) : false;
return matchName || matchCode || matchCurrency;
});
}, [searchQuery]);
const getCurrencySymbol = (curr: string) => {
if (curr === 'INR') return '₹';
if (curr === 'EUR') return '€';
return '$';
};
const getFlag = (cc: CountryCode) => {
return cc.label ? cc.label.split(' ')[0] : '🌐';
};
const isDark = theme === 'dark';
return (
<div ref={containerRef} className={`relative w-full ${className}`}>
{/* Trigger Button */}
<button
type="button"
disabled={disabled}
onClick={() => !disabled && setIsOpen(!isOpen)}
className={`w-full flex items-center justify-between text-left transition-colors duration-150 rounded-xl focus:outline-none ${
size === 'sm' ? 'px-3 py-2 text-xs font-semibold' : 'px-4 py-2.5 text-sm font-semibold'
} ${
isDark
? 'bg-slate-950 border border-slate-800 text-white focus:border-indigo-500'
: 'bg-white border border-slate-200 text-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500'
} ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
>
<div className="flex items-center gap-2 truncate pr-2">
{selectedRule ? (
<>
<span className="text-base shrink-0 leading-none">{getFlag(selectedRule)}</span>
<span className="truncate">{selectedRule.country}</span>
{showDialCode && (
<span className={`text-[11px] font-mono shrink-0 ${isDark ? 'text-slate-400' : 'text-slate-500'}`}>
({selectedRule.code})
</span>
)}
{showCurrency && (
<span className={`text-[11px] font-normal truncate shrink-0 ${isDark ? 'text-slate-500' : 'text-slate-400'}`}>
· {selectedRule.currency} {getCurrencySymbol(selectedRule.currency)}
</span>
)}
</>
) : (
<span className={isDark ? 'text-slate-500' : 'text-slate-400'}>{placeholder}</span>
)}
</div>
<ChevronDown
className={`h-4 w-4 shrink-0 transition-transform duration-200 ${
isOpen ? 'rotate-180' : ''
} ${isDark ? 'text-slate-500' : 'text-slate-400'}`}
/>
</button>
{/* Dropdown Menu */}
{isOpen && (
<div
className={`absolute left-0 right-0 top-full mt-1.5 z-50 rounded-2xl shadow-2xl border overflow-hidden flex flex-col animate-in fade-in zoom-in-95 duration-150 ${
isDark
? 'bg-slate-900 border-slate-800 text-white'
: 'bg-white border-slate-200 text-slate-800'
}`}
>
{/* Search Box */}
<div className={`p-2.5 border-b shrink-0 ${isDark ? 'border-slate-800 bg-slate-950/60' : 'border-slate-100 bg-slate-50/70'}`}>
<div className="relative">
<Search
className={`absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 ${
isDark ? 'text-slate-500' : 'text-slate-400'
}`}
/>
<input
ref={searchInputRef}
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search country name or code..."
className={`w-full rounded-xl pl-8 pr-8 py-1.5 text-xs font-semibold focus:outline-none transition-colors ${
isDark
? 'bg-slate-950 border border-slate-800 text-white placeholder:text-slate-600 focus:border-indigo-500'
: 'bg-white border border-slate-200 text-slate-800 placeholder:text-slate-400 focus:border-indigo-500'
}`}
/>
{searchQuery && (
<button
type="button"
onClick={() => setSearchQuery('')}
className={`absolute right-2.5 top-1/2 -translate-y-1/2 p-0.5 rounded-full hover:bg-slate-200/50 ${
isDark ? 'text-slate-400 hover:text-white' : 'text-slate-400 hover:text-slate-600'
}`}
>
<X className="h-3 w-3" />
</button>
)}
</div>
</div>
{/* Options List */}
<div className="max-h-56 overflow-y-auto overscroll-contain py-1">
{filteredCountries.length === 0 ? (
<div className={`p-4 text-center text-xs ${isDark ? 'text-slate-500' : 'text-slate-400'}`}>
No countries found matching &ldquo;{searchQuery}&rdquo;
</div>
) : (
filteredCountries.map((c) => {
const isSelected = c.country.toLowerCase() === value.toLowerCase();
return (
<button
key={`${c.country}-${c.code}`}
type="button"
onClick={() => {
onChange(c.country);
setIsOpen(false);
setSearchQuery('');
}}
className={`w-full flex items-center justify-between px-3.5 py-2 text-left text-xs transition-colors cursor-pointer ${
isSelected
? isDark
? 'bg-indigo-600/20 text-indigo-400 font-bold'
: 'bg-indigo-50 text-indigo-700 font-bold'
: isDark
? 'hover:bg-slate-800/80 text-slate-200'
: 'hover:bg-slate-50 text-slate-700'
}`}
>
<div className="flex items-center gap-2.5 min-w-0 pr-2">
<span className="text-base shrink-0 leading-none">{getFlag(c)}</span>
<span className="truncate">{c.country}</span>
<span className={`text-[10px] font-mono shrink-0 ${isDark ? 'text-slate-500' : 'text-slate-400'}`}>
({c.code})
</span>
{showCurrency && (
<span className={`text-[10px] shrink-0 font-normal ${isDark ? 'text-slate-500' : 'text-slate-400'}`}>
· {c.currency} {getCurrencySymbol(c.currency)}
</span>
)}
</div>
{isSelected && <Check className="h-3.5 w-3.5 shrink-0 text-indigo-500" />}
</button>
);
})
)}
</div>
</div>
)}
</div>
);
};

View File

@ -0,0 +1,331 @@
import React, { useState, useRef, useEffect, useMemo } from 'react';
import { Search, ChevronDown, Check, X } from 'lucide-react';
import {
COUNTRY_CODES,
SORTED_COUNTRY_CODES,
getCountryRuleByDialCode,
getCountryRuleByName,
type CountryCode,
} from '../../constants/countries';
import { cleanPhoneInput } from '../../utils/validation';
export interface PhoneInputProps {
dialCode: string;
phone: string; // local digits only
country?: string;
onDialCodeChange?: (newCode: string, newCountry: string) => void;
onPhoneChange: (newPhone: string) => void;
error?: string | null;
disabled?: boolean;
theme?: 'dark' | 'light';
id?: string;
clearOnDialCodeChange?: boolean;
}
export const PhoneInput: React.FC<PhoneInputProps> = ({
dialCode,
phone,
country,
onDialCodeChange,
onPhoneChange,
error,
disabled = false,
theme = 'dark',
id = 'phone-input',
clearOnDialCodeChange = false,
}) => {
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const dropdownRef = useRef<HTMLDivElement>(null);
const searchInputRef = useRef<HTMLInputElement>(null);
// Prioritize country name if available, fallback to dial code
let activeRule = country ? getCountryRuleByName(country) : undefined;
if (!activeRule && dialCode) {
activeRule = getCountryRuleByDialCode(dialCode, country);
}
if (!activeRule) {
activeRule = getCountryRuleByDialCode('+91')!;
}
// Focus search input when dropdown opens
useEffect(() => {
if (isDropdownOpen) {
setTimeout(() => {
searchInputRef.current?.focus();
}, 50);
} else {
setSearchQuery('');
}
}, [isDropdownOpen]);
// Handle click outside to close dropdown
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
setIsDropdownOpen(false);
}
};
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
setIsDropdownOpen(false);
}
};
if (isDropdownOpen) {
document.addEventListener('mousedown', handleClickOutside);
document.addEventListener('keydown', handleKeyDown);
}
return () => {
document.removeEventListener('mousedown', handleClickOutside);
document.removeEventListener('keydown', handleKeyDown);
};
}, [isDropdownOpen]);
// Filter countries alphabetically by country name or dial code
const filteredCountryCodes = useMemo(() => {
if (!searchQuery.trim()) {
return SORTED_COUNTRY_CODES;
}
const q = searchQuery.toLowerCase().trim();
return SORTED_COUNTRY_CODES.filter((c: CountryCode) => {
const matchCountry = c.country.toLowerCase().includes(q);
const matchCode = c.code.toLowerCase().includes(q);
const rawCode = c.code.replace('+', '');
const matchRaw = rawCode.includes(q);
return matchCountry || matchCode || matchRaw;
});
}, [searchQuery]);
const getFlag = (cc: CountryCode) => {
return cc.label ? cc.label.split(' ')[0] : '🌐';
};
const isSelected = (cc: CountryCode) => {
if (country) {
return cc.country.toLowerCase() === country.toLowerCase() && cc.code === dialCode;
}
return cc.code === dialCode;
};
const handleSelectCountry = (cc: CountryCode) => {
if (onDialCodeChange) {
onDialCodeChange(cc.code, cc.country);
}
if (clearOnDialCodeChange) {
onPhoneChange('');
} else {
onPhoneChange(cleanPhoneInput(phone, cc.maxLength, false));
}
setIsDropdownOpen(false);
setSearchQuery('');
};
const handlePhoneInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const inputVal = e.target.value;
const trimmed = inputVal.trim();
// Check if input contains an explicit international prefix '+'
if (trimmed.startsWith('+')) {
const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length);
const matched = sorted.find((c) => trimmed.startsWith(c.code));
if (matched) {
if (onDialCodeChange && (matched.code !== dialCode || matched.country !== country)) {
onDialCodeChange(matched.code, matched.country);
}
const rest = trimmed.slice(matched.code.length).replace(/\D/g, '');
onPhoneChange(rest.slice(0, matched.maxLength));
return;
}
}
// Check if input was pasted with dial code digits without '+' (e.g. 919876543210)
const dialDigits = activeRule.code.replace(/\D/g, '');
const rawDigits = trimmed.replace(/\D/g, '');
if (
dialDigits &&
rawDigits.startsWith(dialDigits) &&
rawDigits.length > activeRule.maxLength
) {
const rest = rawDigits.slice(dialDigits.length);
onPhoneChange(rest.slice(0, activeRule.maxLength));
return;
}
// Strictly numeric local digits, capped at active country's maxLength
const cleaned = cleanPhoneInput(inputVal, activeRule.maxLength, false);
onPhoneChange(cleaned);
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
// Allow navigation keys, backspace, delete, tab, copy/paste shortcuts
if (
['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab', 'Enter', 'Escape'].includes(e.key) ||
(e.ctrlKey || e.metaKey)
) {
return;
}
// Allow '+' as leading character to support international number paste/typing
if (e.key === '+' && (e.currentTarget.selectionStart === 0 || !phone)) {
return;
}
// Block any non-digit
if (!/^\d$/.test(e.key)) {
e.preventDefault();
}
};
const isDark = theme === 'dark';
return (
<div className="space-y-1.5 w-full">
<div className="flex gap-2 w-full">
{/* Searchable Country Code Dropdown */}
<div ref={dropdownRef} className="relative shrink-0">
<button
type="button"
disabled={disabled}
onClick={() => !disabled && setIsDropdownOpen(!isDropdownOpen)}
className={`w-[110px] flex items-center justify-between rounded-xl px-2.5 py-2.5 text-xs font-semibold cursor-pointer focus:outline-none transition-colors ${
isDark
? 'bg-slate-950 border border-slate-800 text-white focus:border-indigo-500'
: 'bg-white border border-slate-200 text-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500'
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
>
<div className="flex items-center gap-1.5 truncate">
<span className="text-sm shrink-0 leading-none">{getFlag(activeRule)}</span>
<span className="font-mono text-xs font-bold">{activeRule.code}</span>
</div>
<ChevronDown
className={`h-3.5 w-3.5 shrink-0 text-slate-400 transition-transform duration-200 ${
isDropdownOpen ? 'rotate-180' : ''
}`}
/>
</button>
{/* Searchable Dropdown Popover */}
{isDropdownOpen && (
<div
className={`absolute left-0 top-full mt-1.5 z-50 w-72 sm:w-80 rounded-2xl shadow-2xl border overflow-hidden flex flex-col animate-in fade-in zoom-in-95 duration-150 ${
isDark
? 'bg-slate-900 border-slate-800 text-white'
: 'bg-white border-slate-200 text-slate-800'
}`}
>
{/* Search Box */}
<div
className={`p-2.5 border-b shrink-0 ${
isDark ? 'border-slate-800 bg-slate-950/60' : 'border-slate-100 bg-slate-50/70'
}`}
>
<div className="relative">
<Search
className={`absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 ${
isDark ? 'text-slate-500' : 'text-slate-400'
}`}
/>
<input
ref={searchInputRef}
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search country or code..."
className={`w-full rounded-xl pl-8 pr-8 py-1.5 text-xs font-semibold focus:outline-none transition-colors ${
isDark
? 'bg-slate-950 border border-slate-800 text-white placeholder:text-slate-600 focus:border-indigo-500'
: 'bg-white border border-slate-200 text-slate-800 placeholder:text-slate-400 focus:border-indigo-500'
}`}
/>
{searchQuery && (
<button
type="button"
onClick={() => setSearchQuery('')}
className={`absolute right-2.5 top-1/2 -translate-y-1/2 p-0.5 rounded-full hover:bg-slate-200/50 ${
isDark ? 'text-slate-400 hover:text-white' : 'text-slate-400 hover:text-slate-600'
}`}
>
<X className="h-3 w-3" />
</button>
)}
</div>
</div>
{/* Alphabetically Sorted Options List */}
<div className="max-h-60 overflow-y-auto overscroll-contain py-1">
{filteredCountryCodes.length === 0 ? (
<div
className={`p-4 text-center text-xs ${
isDark ? 'text-slate-500' : 'text-slate-400'
}`}
>
No country codes found matching &ldquo;{searchQuery}&rdquo;
</div>
) : (
filteredCountryCodes.map((cc) => {
const selected = isSelected(cc);
return (
<button
key={`${cc.country}-${cc.code}`}
type="button"
onClick={() => handleSelectCountry(cc)}
className={`w-full flex items-center justify-between px-3.5 py-2 text-left text-xs transition-colors cursor-pointer ${
selected
? isDark
? 'bg-indigo-600/20 text-indigo-400 font-bold'
: 'bg-indigo-50 text-indigo-700 font-bold'
: isDark
? 'hover:bg-slate-800/80 text-slate-200'
: 'hover:bg-slate-50 text-slate-700'
}`}
>
<div className="flex items-center gap-2.5 min-w-0 pr-2">
<span className="text-base shrink-0 leading-none">{getFlag(cc)}</span>
<span className="truncate">{cc.country}</span>
<span
className={`text-[11px] font-mono shrink-0 ${
isDark ? 'text-slate-400' : 'text-slate-500'
}`}
>
({cc.code})
</span>
</div>
{selected && <Check className="h-3.5 w-3.5 shrink-0 text-indigo-500" />}
</button>
);
})
)}
</div>
</div>
)}
</div>
{/* Numeric-Only Local Phone Input */}
<input
id={id}
type="tel"
inputMode="numeric"
autoComplete="tel-national"
value={phone}
onChange={handlePhoneInputChange}
onKeyDown={handleKeyDown}
placeholder={activeRule.placeholder || 'Mobile Number'}
maxLength={activeRule.maxLength}
disabled={disabled}
className={`min-w-0 flex-1 rounded-xl px-3.5 py-2.5 text-xs sm:text-sm font-semibold focus:outline-none transition-colors ${
isDark
? 'bg-slate-950 border border-slate-800 text-white placeholder:text-slate-600 focus:border-indigo-500'
: 'bg-white border border-slate-200 text-slate-800 placeholder:text-slate-400 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500'
} ${error ? 'border-rose-500 focus:border-rose-500' : ''} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
/>
</div>
{error && (
<p className="text-[11px] font-semibold text-rose-500 animate-shake">
{error}
</p>
)}
</div>
);
};

View File

@ -3,8 +3,8 @@ import { Sparkles, LogIn, UserPlus, BookOpen, CheckCircle } from 'lucide-react';
import type { UserProfile } from '../../types'; import type { UserProfile } from '../../types';
interface StoreHeaderProps { interface StoreHeaderProps {
activeTab: 'storefront' | 'subscriptions'; activeTab: 'storefront' | 'subscriptions' | 'logged-out';
onSwitchTab: (tab: 'storefront' | 'subscriptions') => void; onSwitchTab: (tab: 'storefront' | 'subscriptions' | 'logged-out') => void;
loggedInUser: UserProfile | null; loggedInUser: UserProfile | null;
onOpenProfile: () => void; onOpenProfile: () => void;
onOpenAuth: (mode: 'login' | 'register') => void; onOpenAuth: (mode: 'login' | 'register') => void;
@ -18,85 +18,116 @@ export const StoreHeader: React.FC<StoreHeaderProps> = ({
onOpenAuth, onOpenAuth,
}) => { }) => {
return ( return (
<header className="w-full bg-[#0A0A0E] text-slate-300 border-b border-slate-800 px-6 py-4 flex items-center justify-between shadow-lg flex-shrink-0"> <header className="w-full bg-[#0A0A0E] text-slate-300 border-b border-slate-800 px-4 sm:px-6 py-3 sm:py-4 shadow-lg flex-shrink-0">
<div className="flex items-center gap-6"> <div className="flex items-center justify-between">
<div <div className="flex items-center gap-6">
onClick={() => onSwitchTab('storefront')} <div
className="flex items-center gap-3 cursor-pointer group" onClick={() => onSwitchTab('storefront')}
> className="flex items-center gap-3 cursor-pointer group"
<div className="h-10 w-10 rounded-xl bg-gradient-to-tr from-indigo-500 to-cyan-400 flex items-center justify-center shadow-md shadow-indigo-500/20 group-hover:scale-105 transition-transform"> >
<Sparkles className="h-5 w-5 text-white" /> <div className="h-10 w-10 rounded-xl bg-gradient-to-tr from-indigo-500 to-cyan-400 flex items-center justify-center shadow-md shadow-indigo-500/20 group-hover:scale-105 transition-transform">
</div> <Sparkles className="h-5 w-5 text-white" />
<div> </div>
<h1 className="text-base font-black tracking-tight text-white flex items-center gap-1"> <div>
ACUPEDIA <h1 className="text-base font-black tracking-tight text-white flex items-center gap-1">
</h1> ACUPEDIA
<p className="text-[9px] text-slate-400 font-bold tracking-widest uppercase">TCM PLATFORM</p> </h1>
<p className="text-[9px] text-slate-400 font-bold tracking-widest uppercase">TCM PLATFORM</p>
</div>
</div> </div>
{/* Desktop Navigation Tabs */}
<nav className="hidden sm:flex items-center bg-slate-900/80 border border-slate-800 rounded-xl p-1 gap-1">
<button
onClick={() => onSwitchTab('storefront')}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${
activeTab === 'storefront'
? 'bg-indigo-600 text-white shadow-sm'
: 'text-slate-400 hover:text-slate-200'
}`}
>
<BookOpen className="h-3.5 w-3.5" /> Storefront
</button>
<button
onClick={() => onSwitchTab('subscriptions')}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${
activeTab === 'subscriptions'
? 'bg-indigo-600 text-white shadow-sm'
: 'text-slate-400 hover:text-slate-200'
}`}
>
<CheckCircle className="h-3.5 w-3.5" /> My Subscriptions
{loggedInUser?.active_subscriptions && loggedInUser.active_subscriptions.length > 0 && (
<span className="bg-indigo-900 text-indigo-200 text-[10px] px-1.5 py-0.2 rounded-full ml-0.5">
{loggedInUser.active_subscriptions.length}
</span>
)}
</button>
</nav>
</div> </div>
{/* Navigation Tabs */} <div className="flex items-center gap-3">
<nav className="hidden sm:flex items-center bg-slate-900/80 border border-slate-800 rounded-xl p-1 gap-1"> {loggedInUser ? (
<button <button
onClick={() => onSwitchTab('storefront')} onClick={onOpenProfile}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${ className="flex items-center gap-3 hover:text-white transition-colors group focus:outline-none"
activeTab === 'storefront' >
? 'bg-indigo-600 text-white shadow-sm' <div className="text-right hidden sm:block">
: 'text-slate-400 hover:text-slate-200' <p className="text-xs font-bold text-white truncate max-w-[150px]">
}`} {loggedInUser.display_name || loggedInUser.email}
> </p>
<BookOpen className="h-3.5 w-3.5" /> Storefront </div>
</button> <div className="h-9 w-9 rounded-lg bg-indigo-950/60 border border-indigo-500/30 flex items-center justify-center text-indigo-400 font-bold text-sm group-hover:border-indigo-400 transition-colors">
<button {(loggedInUser.display_name || loggedInUser.email || 'U')[0].toUpperCase()}
onClick={() => onSwitchTab('subscriptions')} </div>
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${ </button>
activeTab === 'subscriptions' ) : (
? 'bg-indigo-600 text-white shadow-sm' <div className="flex gap-2">
: 'text-slate-400 hover:text-slate-200' <button
}`} onClick={() => onOpenAuth('login')}
> className="flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-bold bg-slate-800 hover:bg-slate-700 text-slate-300 transition-colors"
<CheckCircle className="h-3.5 w-3.5" /> My Subscriptions >
{loggedInUser?.active_subscriptions && loggedInUser.active_subscriptions.length > 0 && ( <LogIn className="h-3.5 w-3.5" /> Login
<span className="bg-indigo-900 text-indigo-200 text-[10px] px-1.5 py-0.2 rounded-full ml-0.5"> </button>
{loggedInUser.active_subscriptions.length} <button
</span> onClick={() => onOpenAuth('register')}
)} className="flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-bold bg-indigo-600 hover:bg-indigo-500 text-white transition-colors shadow shadow-indigo-600/10"
</button> >
</nav> <UserPlus className="h-3.5 w-3.5" /> Join
</button>
</div>
)}
</div>
</div> </div>
<div className="flex items-center gap-3"> {/* Mobile Navigation Tabs */}
{loggedInUser ? ( <nav className="sm:hidden flex items-center bg-slate-900/90 border border-slate-800 rounded-xl p-1 mt-3 gap-1 w-full">
<button <button
onClick={onOpenProfile} onClick={() => onSwitchTab('storefront')}
className="flex items-center gap-3 hover:text-white transition-colors group focus:outline-none" className={`flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-colors ${
> activeTab === 'storefront'
<div className="text-right hidden sm:block"> ? 'bg-indigo-600 text-white shadow-sm'
<p className="text-xs font-bold text-white truncate max-w-[150px]"> : 'text-slate-400 hover:text-slate-200'
{loggedInUser.display_name || loggedInUser.email} }`}
</p> >
</div> <BookOpen className="h-3.5 w-3.5" /> Storefront
<div className="h-9 w-9 rounded-lg bg-indigo-950/60 border border-indigo-500/30 flex items-center justify-center text-indigo-400 font-bold text-sm group-hover:border-indigo-400 transition-colors"> </button>
{(loggedInUser.display_name || loggedInUser.email || 'U')[0].toUpperCase()} <button
</div> onClick={() => onSwitchTab('subscriptions')}
</button> className={`flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-colors ${
) : ( activeTab === 'subscriptions'
<div className="flex gap-2"> ? 'bg-indigo-600 text-white shadow-sm'
<button : 'text-slate-400 hover:text-slate-200'
onClick={() => onOpenAuth('login')} }`}
className="flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-bold bg-slate-800 hover:bg-slate-700 text-slate-300 transition-colors" >
> <CheckCircle className="h-3.5 w-3.5" /> My Subscriptions
<LogIn className="h-3.5 w-3.5" /> Login {loggedInUser?.active_subscriptions && loggedInUser.active_subscriptions.length > 0 && (
</button> <span className="bg-indigo-900 text-indigo-200 text-[10px] px-1.5 py-0.2 rounded-full ml-1 font-semibold">
<button {loggedInUser.active_subscriptions.length}
onClick={() => onOpenAuth('register')} </span>
className="flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-bold bg-indigo-600 hover:bg-indigo-500 text-white transition-colors shadow shadow-indigo-600/10" )}
> </button>
<UserPlus className="h-3.5 w-3.5" /> Join </nav>
</button>
</div>
)}
</div>
</header> </header>
); );
}; };

View File

@ -1,6 +1,8 @@
import type { CountryCode as LibCountryCode } from 'libphonenumber-js';
import type { Currency } from '../types'; import type { Currency } from '../types';
export interface CountryCode { export interface CountryCode {
iso2: LibCountryCode;
code: string; code: string;
label: string; label: string;
country: string; country: string;
@ -8,60 +10,156 @@ export interface CountryCode {
minLength: number; minLength: number;
maxLength: number; maxLength: number;
placeholder: string; placeholder: string;
validPrefixes?: string[];
example?: string;
} }
export const COUNTRY_CODES: CountryCode[] = [ export const COUNTRY_CODES: CountryCode[] = [
{ code: '+91', label: '🇮🇳 +91', country: 'India', currency: 'INR', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' }, // South Asia
{ code: '+1', label: '🇺🇸 +1', country: 'United States', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit phone number' }, { iso2: 'IN', code: '+91', label: '🇮🇳 +91', country: 'India', currency: 'INR', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['6', '7', '8', '9'], example: '98765 43210' },
{ code: '+44', label: '🇬🇧 +44', country: 'United Kingdom', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' }, { iso2: 'PK', code: '+92', label: '🇵🇰 +92', country: 'Pakistan', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['3'], example: '300 1234567' },
{ code: '+61', label: '🇦🇺 +61', country: 'Australia', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' }, { iso2: 'BD', code: '+880', label: '🇧🇩 +880', country: 'Bangladesh', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['1'], example: '1712 345678' },
{ code: '+49', label: '🇩🇪 +49', country: 'Germany', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' }, { iso2: 'LK', code: '+94', label: '🇱🇰 +94', country: 'Sri Lanka', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['7'], example: '71 234 5678' },
{ code: '+33', label: '🇫🇷 +33', country: 'France', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' }, { iso2: 'NP', code: '+977', label: '🇳🇵 +977', country: 'Nepal', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['97', '98'], example: '9812 345678' },
{ code: '+81', label: '🇯🇵 +81', country: 'Japan', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' }, { iso2: 'BT', code: '+975', label: '🇧🇹 +975', country: 'Bhutan', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['16', '17', '77'], example: '1712 3456' },
{ code: '+86', label: '🇨🇳 +86', country: 'China', currency: 'USD', minLength: 11, maxLength: 11, placeholder: '11-digit mobile number' }, { iso2: 'MV', code: '+960', label: '🇲🇻 +960', country: 'Maldives', currency: 'USD', minLength: 7, maxLength: 7, placeholder: '7-digit mobile number', validPrefixes: ['7', '9'], example: '791 2345' },
{ code: '+971', label: '🇦🇪 +971', country: 'UAE', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
{ code: '+65', label: '🇸🇬 +65', country: 'Singapore', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' }, // North America
{ code: '+55', label: '🇧🇷 +55', country: 'Brazil', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' }, { iso2: 'US', code: '+1', label: '🇺🇸 +1', country: 'United States', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit phone number', example: '202 555 0123' },
{ code: '+82', label: '🇰🇷 +82', country: 'South Korea', currency: 'USD', minLength: 9, maxLength: 11, placeholder: '9 to 11 digits' }, { iso2: 'CA', code: '+1', label: '🇨🇦 +1', country: 'Canada', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit phone number', example: '416 555 0123' },
{ code: '+7', label: '🇷🇺 +7', country: 'Russia', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' }, { iso2: 'MX', code: '+52', label: '🇲🇽 +52', country: 'Mexico', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', example: '55 1234 5678' },
{ code: '+27', label: '🇿🇦 +27', country: 'South Africa', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
{ code: '+234', label: '🇳🇬 +234', country: 'Nigeria', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' }, // Europe & UK
{ iso2: 'GB', code: '+44', label: '🇬🇧 +44', country: 'United Kingdom', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['7'], example: '7123 456789' },
{ iso2: 'DE', code: '+49', label: '🇩🇪 +49', country: 'Germany', currency: 'EUR', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['15', '16', '17', '1'], example: '151 23456789' },
{ iso2: 'FR', code: '+33', label: '🇫🇷 +33', country: 'France', currency: 'EUR', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['6', '7'], example: '612 345 678' },
{ iso2: 'IT', code: '+39', label: '🇮🇹 +39', country: 'Italy', currency: 'EUR', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['3'], example: '312 345 6789' },
{ iso2: 'ES', code: '+34', label: '🇪🇸 +34', country: 'Spain', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['6', '7'], example: '612 345 678' },
{ iso2: 'NL', code: '+31', label: '🇳🇱 +31', country: 'Netherlands', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['6'], example: '6 12345678' },
{ iso2: 'CH', code: '+41', label: '🇨🇭 +41', country: 'Switzerland', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['7'], example: '78 123 45 67' },
{ iso2: 'BE', code: '+32', label: '🇧🇪 +32', country: 'Belgium', currency: 'EUR', minLength: 8, maxLength: 9, placeholder: '8 to 9 digits', validPrefixes: ['4'], example: '470 12 34 56' },
{ iso2: 'AT', code: '+43', label: '🇦🇹 +43', country: 'Austria', currency: 'EUR', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['6'], example: '664 1234567' },
{ iso2: 'IE', code: '+353', label: '🇮🇪 +353', country: 'Ireland', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['8'], example: '83 123 4567' },
{ iso2: 'SE', code: '+46', label: '🇸🇪 +46', country: 'Sweden', currency: 'EUR', minLength: 7, maxLength: 10, placeholder: '7 to 10 digits', validPrefixes: ['7'], example: '70 123 45 67' },
{ iso2: 'NO', code: '+47', label: '🇳🇴 +47', country: 'Norway', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['4', '9'], example: '412 34 567' },
{ iso2: 'DK', code: '+45', label: '🇩🇰 +45', country: 'Denmark', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', example: '20 12 34 56' },
{ iso2: 'FI', code: '+358', label: '🇫🇮 +358', country: 'Finland', currency: 'EUR', minLength: 7, maxLength: 10, placeholder: '7 to 10 digits', validPrefixes: ['4', '5'], example: '41 234 5678' },
{ iso2: 'PT', code: '+351', label: '🇵🇹 +351', country: 'Portugal', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['9'], example: '912 345 678' },
{ iso2: 'GR', code: '+30', label: '🇬🇷 +30', country: 'Greece', currency: 'EUR', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['6'], example: '691 234 5678' },
{ iso2: 'PL', code: '+48', label: '🇵🇱 +48', country: 'Poland', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['4', '5', '6', '7', '8'], example: '512 345 678' },
{ iso2: 'CZ', code: '+420', label: '🇨🇿 +420', country: 'Czech Republic', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['6', '7'], example: '601 123 456' },
{ iso2: 'HU', code: '+36', label: '🇭🇺 +36', country: 'Hungary', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['20', '30', '31', '50', '70'], example: '20 123 4567' },
{ iso2: 'RO', code: '+40', label: '🇷🇴 +40', country: 'Romania', currency: 'EUR', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['7'], example: '712 345 678' },
{ iso2: 'UA', code: '+380', label: '🇺🇦 +380', country: 'Ukraine', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['5', '6', '7', '9'], example: '50 123 4567' },
{ iso2: 'IS', code: '+354', label: '🇮🇸 +354', country: 'Iceland', currency: 'EUR', minLength: 7, maxLength: 9, placeholder: '7 to 9 digits', validPrefixes: ['6', '7', '8'], example: '612 3456' },
{ iso2: 'LU', code: '+352', label: '🇱🇺 +352', country: 'Luxembourg', currency: 'EUR', minLength: 8, maxLength: 10, placeholder: '8 to 10 digits', validPrefixes: ['6'], example: '621 123 456' },
{ iso2: 'HR', code: '+385', label: '🇭🇷 +385', country: 'Croatia', currency: 'EUR', minLength: 8, maxLength: 9, placeholder: '8 to 9 digits', validPrefixes: ['9'], example: '91 234 5678' },
{ iso2: 'SK', code: '+421', label: '🇸🇰 +421', country: 'Slovakia', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['9'], example: '912 345 678' },
{ iso2: 'BG', code: '+359', label: '🇧🇬 +359', country: 'Bulgaria', currency: 'EUR', minLength: 8, maxLength: 9, placeholder: '8 to 9 digits', validPrefixes: ['8', '9'], example: '87 123 4567' },
{ iso2: 'CY', code: '+357', label: '🇨🇾 +357', country: 'Cyprus', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit phone number', validPrefixes: ['9'], example: '96 123456' },
{ iso2: 'EE', code: '+372', label: '🇪🇪 +372', country: 'Estonia', currency: 'EUR', minLength: 7, maxLength: 8, placeholder: '7 to 8 digits', validPrefixes: ['5'], example: '512 3456' },
{ iso2: 'LV', code: '+371', label: '🇱🇻 +371', country: 'Latvia', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit phone number', validPrefixes: ['2'], example: '2123 4567' },
{ iso2: 'LT', code: '+370', label: '🇱🇹 +370', country: 'Lithuania', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit phone number', validPrefixes: ['6'], example: '612 34567' },
{ iso2: 'MT', code: '+356', label: '🇲🇹 +356', country: 'Malta', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit phone number', validPrefixes: ['7', '9'], example: '7912 3456' },
{ iso2: 'SI', code: '+386', label: '🇸🇮 +386', country: 'Slovenia', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit phone number', validPrefixes: ['3', '4', '5', '6', '7'], example: '31 234 567' },
{ iso2: 'RU', code: '+7', label: '🇷🇺 +7', country: 'Russia', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['9'], example: '912 345-67-89' },
{ iso2: 'TR', code: '+90', label: '🇹🇷 +90', country: 'Turkey', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['5'], example: '501 234 56 78' },
// Asia-Pacific
{ iso2: 'AU', code: '+61', label: '🇦🇺 +61', country: 'Australia', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['4'], example: '412 345 678' },
{ iso2: 'NZ', code: '+64', label: '🇳🇿 +64', country: 'New Zealand', currency: 'USD', minLength: 8, maxLength: 10, placeholder: '8 to 10 digits', validPrefixes: ['2'], example: '21 123 4567' },
{ iso2: 'JP', code: '+81', label: '🇯🇵 +81', country: 'Japan', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['70', '80', '90', '7', '8', '9'], example: '90 1234 5678' },
{ iso2: 'CN', code: '+86', label: '🇨🇳 +86', country: 'China', currency: 'USD', minLength: 11, maxLength: 11, placeholder: '11-digit mobile number', validPrefixes: ['1'], example: '138 0013 8000' },
{ iso2: 'KR', code: '+82', label: '🇰🇷 +82', country: 'South Korea', currency: 'USD', minLength: 9, maxLength: 11, placeholder: '9 to 11 digits', validPrefixes: ['10', '1'], example: '10 1234 5678' },
{ iso2: 'HK', code: '+852', label: '🇭🇰 +852', country: 'Hong Kong', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['4', '5', '6', '7', '8', '9'], example: '5123 4567' },
{ iso2: 'TW', code: '+886', label: '🇹🇼 +886', country: 'Taiwan', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['9'], example: '912 345 678' },
{ iso2: 'SG', code: '+65', label: '🇸🇬 +65', country: 'Singapore', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['8', '9'], example: '8123 4567' },
{ iso2: 'MY', code: '+60', label: '🇲🇾 +60', country: 'Malaysia', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['1'], example: '12 345 6789' },
{ iso2: 'ID', code: '+62', label: '🇮🇩 +62', country: 'Indonesia', currency: 'USD', minLength: 9, maxLength: 12, placeholder: '9 to 12 digits', validPrefixes: ['8'], example: '812 3456 7890' },
{ iso2: 'PH', code: '+63', label: '🇵🇭 +63', country: 'Philippines', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['9'], example: '917 123 4567' },
{ iso2: 'TH', code: '+66', label: '🇹🇭 +66', country: 'Thailand', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['6', '8', '9'], example: '81 234 5678' },
{ iso2: 'VN', code: '+84', label: '🇻🇳 +84', country: 'Vietnam', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['3', '5', '7', '8', '9'], example: '91 234 5678' },
// Middle East
{ iso2: 'AE', code: '+971', label: '🇦🇪 +971', country: 'UAE', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['5'], example: '50 123 4567' },
{ iso2: 'SA', code: '+966', label: '🇸🇦 +966', country: 'Saudi Arabia', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['5'], example: '50 123 4567' },
{ iso2: 'QA', code: '+974', label: '🇶🇦 +974', country: 'Qatar', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['3', '5', '6', '7'], example: '3312 3456' },
{ iso2: 'KW', code: '+965', label: '🇰🇼 +965', country: 'Kuwait', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['5', '6', '9'], example: '5123 4567' },
{ iso2: 'OM', code: '+968', label: '🇴🇲 +968', country: 'Oman', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['7', '9'], example: '9123 4567' },
{ iso2: 'BH', code: '+973', label: '🇧🇭 +973', country: 'Bahrain', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['3', '6'], example: '3600 1234' },
{ iso2: 'IL', code: '+972', label: '🇮🇱 +972', country: 'Israel', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['5'], example: '50 123 4567' },
{ iso2: 'JO', code: '+962', label: '🇯🇴 +962', country: 'Jordan', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['7'], example: '7 9012 3456' },
{ iso2: 'LB', code: '+961', label: '🇱🇧 +961', country: 'Lebanon', currency: 'USD', minLength: 7, maxLength: 8, placeholder: '7 to 8 digits', validPrefixes: ['3', '7', '8'], example: '70 123 456' },
// Latin America
{ iso2: 'BR', code: '+55', label: '🇧🇷 +55', country: 'Brazil', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['9'], example: '11 91234 5678' },
{ iso2: 'AR', code: '+54', label: '🇦🇷 +54', country: 'Argentina', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['9'], example: '9 11 1234-5678' },
{ iso2: 'CL', code: '+56', label: '🇨🇱 +56', country: 'Chile', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['9'], example: '9 1234 5678' },
{ iso2: 'CO', code: '+57', label: '🇨🇴 +57', country: 'Colombia', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['3'], example: '300 123 4567' },
{ iso2: 'PE', code: '+51', label: '🇵🇪 +51', country: 'Peru', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['9'], example: '912 345 678' },
// Africa
{ iso2: 'ZA', code: '+27', label: '🇿🇦 +27', country: 'South Africa', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['6', '7', '8'], example: '71 234 5678' },
{ iso2: 'NG', code: '+234', label: '🇳🇬 +234', country: 'Nigeria', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['7', '8', '9'], example: '802 123 4567' },
{ iso2: 'KE', code: '+254', label: '🇰🇪 +254', country: 'Kenya', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['7', '1'], example: '712 345678' },
{ iso2: 'GH', code: '+233', label: '🇬🇭 +233', country: 'Ghana', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['2', '5'], example: '24 123 4567' },
{ iso2: 'EG', code: '+20', label: '🇪🇬 +20', country: 'Egypt', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['1'], example: '10 1234 5678' },
{ iso2: 'MA', code: '+212', label: '🇲🇦 +212', country: 'Morocco', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['6', '7'], example: '612-345678' },
{ iso2: 'MU', code: '+230', label: '🇲🇺 +230', country: 'Mauritius', currency: 'USD', minLength: 7, maxLength: 8, placeholder: '7 to 8 digits', validPrefixes: ['5'], example: '5123 4567' },
]; ];
// Alphabetically sorted list of countries (A-Z)
export const SORTED_COUNTRY_CODES: CountryCode[] = [...COUNTRY_CODES].sort((a, b) =>
a.country.localeCompare(b.country)
);
export const DEFAULT_COUNTRY = COUNTRY_CODES[0]; // India (+91) export const DEFAULT_COUNTRY = COUNTRY_CODES[0]; // India (+91)
export const getCountryRuleByDialCode = (dialCode: string): CountryCode => { export const getCountryRuleByIso = (iso?: string | null): CountryCode => {
return ( if (!iso) return DEFAULT_COUNTRY;
COUNTRY_CODES.find((c) => c.code === dialCode) || { const upper = iso.toUpperCase().trim();
code: dialCode, return COUNTRY_CODES.find((c) => c.iso2 === upper) || DEFAULT_COUNTRY;
label: dialCode,
country: 'Other',
currency: 'USD',
minLength: 6,
maxLength: 15,
placeholder: 'Phone number',
}
);
}; };
export const getCountryRuleByName = (countryName: string): CountryCode => { export const getCountryRuleByName = (countryName?: string | null): CountryCode => {
if (!countryName) return DEFAULT_COUNTRY; if (!countryName) return DEFAULT_COUNTRY;
const normalized = countryName.toLowerCase(); const normalized = countryName.toLowerCase().trim();
return ( return (
COUNTRY_CODES.find( COUNTRY_CODES.find(
(c) => (c) =>
c.country.toLowerCase() === normalized || c.country.toLowerCase() === normalized ||
(normalized.includes('india') && c.country === 'India') || c.iso2.toLowerCase() === normalized ||
(normalized.includes('united states') && c.country === 'United States') || normalized.includes(c.country.toLowerCase())
(normalized.includes('united kingdom') && c.country === 'United Kingdom') ||
(normalized.includes('germany') && c.country === 'Germany') ||
(normalized.includes('australia') && c.country === 'Australia')
) || { ) || {
iso2: 'IN',
code: '+91', code: '+91',
label: '🇮🇳 +91', label: '🇮🇳 +91',
country: countryName, country: countryName,
currency: normalized === 'india' ? 'INR' : 'USD', currency: normalized === 'india' ? 'INR' : 'USD',
minLength: 6, minLength: 7,
maxLength: 15,
placeholder: 'Phone number',
}
);
};
export const getCountryRuleByDialCode = (dialCode?: string | null, countryHint?: string | null): CountryCode => {
if (!dialCode) return DEFAULT_COUNTRY;
// If country hint is given, try resolving by country first
if (countryHint) {
const byCountry = getCountryRuleByName(countryHint);
if (byCountry && byCountry.code === dialCode) {
return byCountry;
}
}
return (
COUNTRY_CODES.find((c) => c.code === dialCode) || {
iso2: 'IN',
code: dialCode,
label: dialCode,
country: countryHint || 'Other',
currency: 'USD',
minLength: 7,
maxLength: 15, maxLength: 15,
placeholder: 'Phone number', placeholder: 'Phone number',
} }

View File

@ -36,7 +36,7 @@ export const CURRICULUM_MODULES: ModuleItem[] = [
// 4. Therapeutics Category // 4. Therapeutics Category
{ code: 'THERAPEUTICS_GYNAE', name: 'Therapeutics: Gynecology', category: 'Therapeutics', priceInr: 600, priceUsd: 15.0, priceEur: 15.0, desc: '1 Year: Unlocks advanced clinical Gynecology treatment protocols, syndromes, and corresponding points.', color: 'from-teal-500 to-cyan-500' }, { code: 'THERAPEUTICS_GYNAE', name: 'Therapeutics: Gynecology', category: 'Therapeutics', priceInr: 600, priceUsd: 15.0, priceEur: 15.0, desc: '1 Year: Unlocks advanced clinical Gynecology treatment protocols, syndromes, and corresponding points.', color: 'from-teal-500 to-cyan-500' },
{ code: 'THERAPEUTICS_EAR', name: 'Therapeutics: Ear reflexology', category: 'Therapeutics', priceInr: 600, priceUsd: 15.0, priceEur: 15.0, desc: '1 Year: Unlocks comprehensive ear micro-system treatment procedures and specific clinical ear protocols.', color: 'from-cyan-500 to-blue-600' }, { code: 'THERAPEUTICS_EAR', name: 'Therapeutics: Ear reflexology', category: 'Therapeutics', priceInr: 600, priceUsd: 15.0, priceEur: 15.0, desc: '1 Year: Unlocks comprehensive ear micro-system treatment procedures and specific clinical ear protocols.', color: 'from-cyan-500 to-blue-600' },
{ code: 'THERAPEUTICS_CORE', name: 'Therapeutics Complete Bundle', category: 'Therapeutics', priceInr: 1200, priceUsd: 30.0, priceEur: 30.0, desc: '1 Year: Unlocks both advanced clinical Gynecology and Ear Reflexology therapeutics treatment protocols.', color: 'from-teal-500 to-blue-600' }, { code: 'THERAPEUTICS_CORE', name: 'Therapeutics: Complete Pack', category: 'Therapeutics', priceInr: 1200, priceUsd: 30.0, priceEur: 30.0, desc: '1 Year: Unlocks both advanced clinical Gynecology and Ear Reflexology therapeutics treatment protocols.', color: 'from-teal-500 to-blue-600' },
// 5. Lifetime Access // 5. Lifetime Access
{ code: 'LIFETIME_ALL', name: 'Lifetime Unlimited Access Pass', category: 'Lifetime', priceInr: 15000, priceUsd: 350.0, priceEur: 350.0, desc: '10 Years: Unlock all 10 current modules + all future updates. Includes official master clinical certificate.', color: 'from-yellow-500 to-amber-600' } { code: 'LIFETIME_ALL', name: 'Lifetime Unlimited Access Pass', category: 'Lifetime', priceInr: 15000, priceUsd: 350.0, priceEur: 350.0, desc: '10 Years: Unlock all 10 current modules + all future updates. Includes official master clinical certificate.', color: 'from-yellow-500 to-amber-600' }

View File

@ -10,6 +10,8 @@ export interface ModuleItem {
desc: string; desc: string;
color: string; color: string;
isRenewal?: boolean; isRenewal?: boolean;
sortOrder?: number;
planType?: string;
} }
export interface UserSubscription { export interface UserSubscription {
@ -37,6 +39,7 @@ export interface UserProfile {
roles?: string[]; roles?: string[];
external_ref?: string; external_ref?: string;
active_subscriptions: UserSubscription[]; active_subscriptions: UserSubscription[];
unlocked_module_codes?: string[];
unlocked_module_slugs?: string[]; unlocked_module_slugs?: string[];
created_at?: string; created_at?: string;
} }
@ -76,15 +79,28 @@ export interface PublicPlan {
code: string; code: string;
base_code?: string; base_code?: string;
name: string; name: string;
plan_type?: string;
billing_period?: string;
price_inr?: number; price_inr?: number;
price_usd?: number; price_usd?: number;
price_eur?: number; price_eur?: number;
is_active?: boolean; is_active?: boolean;
pricing_status?: string;
color?: string;
badge_text?: string; badge_text?: string;
heading?: string; heading?: string;
subtitle?: string; subtitle?: string;
description?: string; description?: string;
modules?: Array<{ id?: string; name: string; slug?: string }>; modules?: Array<{
id?: string;
code?: string;
name: string;
slug?: string;
description?: string;
category?: string;
sort_order?: number;
}>;
module_slugs?: string[];
} }
export interface VerificationResult { export interface VerificationResult {

223
src/utils/catalog.ts Normal file
View File

@ -0,0 +1,223 @@
import { CURRICULUM_MODULES } from '../constants/modules';
import type { ModuleItem, PublicPlan } from '../types';
export const CORE_PACK_CODES = new Set([
'POINTS_PACK',
'PATTERN_CORE',
'NUTRITION_CORE',
'THERAPEUTICS_CORE',
]);
export const MAIN_CATEGORIES = new Set([
'Points',
'Pattern',
'Nutrition',
'Therapeutics',
]);
const MULTI_ITEM_CORE_PACKS: Record<string, { category: string; packTitle: string; defaultColor: string }> = {
PATTERN_CORE: {
category: 'Pattern',
packTitle: 'Pattern: Complete Pack',
defaultColor: 'from-rose-600 to-orange-600',
},
NUTRITION_CORE: {
category: 'Nutrition',
packTitle: 'Nutrition: Complete Pack',
defaultColor: 'from-teal-500 to-green-600',
},
};
export function normalizeCategory(cat?: string | null): string | null {
if (!cat) return null;
const c = cat.toLowerCase().trim();
if (c === 'point' || c === 'points') return 'Points';
if (c === 'pattern' || c === 'patterns' || c === 'five-elements') return 'Pattern';
if (c === 'nutrition') return 'Nutrition';
if (c === 'therapeutics' || c === 'therapeutic') return 'Therapeutics';
if (c === 'lifetime') return 'Lifetime';
return cat.charAt(0).toUpperCase() + cat.slice(1);
}
function findMatchingApiModule(
plan: PublicPlan,
apiModules: any[],
): any | undefined {
if (!apiModules.length) return undefined;
const firstMod = plan.modules?.[0];
const slugs = plan.module_slugs || (plan.modules || []).map((m) => m.slug).filter(Boolean) as string[];
const targetSlug = (firstMod?.slug || (slugs.length === 1 ? slugs[0] : undefined))?.toLowerCase();
const targetCode = firstMod?.code?.toLowerCase();
if (targetCode) {
const byCode = apiModules.find((m) => (m.code || '').toLowerCase() === targetCode);
if (byCode) return byCode;
}
if (targetSlug) {
const bySlug = apiModules.find((m) => (m.slug || '').toLowerCase() === targetSlug);
if (bySlug) return bySlug;
}
const pCode = (plan.base_code || plan.code || '').toLowerCase();
return apiModules.find(
(m) => (m.plan_code || '').toLowerCase() === pCode || (m.code || '').toLowerCase() === pCode,
);
}
export function resolvePlanCategory(plan: PublicPlan, apiModules: any[] = []): string {
const code = (plan.base_code || plan.code || '').toUpperCase();
if (code === 'LIFETIME_ALL' || plan.plan_type === 'lifetime') return 'Lifetime';
if (code === 'POINTS_PACK') return 'Points';
if (code === 'PATTERN_CORE') return 'Pattern';
if (code === 'NUTRITION_CORE') return 'Nutrition';
if (code === 'THERAPEUTICS_CORE') return 'Therapeutics';
const firstMod = plan.modules?.[0];
const apiMatch = findMatchingApiModule(plan, apiModules);
const rawCat =
firstMod?.category ||
apiMatch?.category ||
apiMatch?.metadata?.category ||
apiMatch?.metadata?.kind;
const normalized = normalizeCategory(rawCat);
if (normalized) return normalized;
const fallback = CURRICULUM_MODULES.find((m) => m.code.toUpperCase() === code);
if (fallback) return fallback.category;
return plan.plan_type === 'bundle' ? 'Bundle' : 'Custom';
}
export function buildDynamicCatalog(
publicPlans: PublicPlan[],
apiModules: any[] = [],
): ModuleItem[] {
if (!publicPlans || publicPlans.length === 0) {
return CURRICULUM_MODULES;
}
const items: ModuleItem[] = [];
for (const plan of publicPlans) {
const code = (plan.base_code || plan.code || '').toUpperCase();
if (!code) continue;
const fallbackEntries = CURRICULUM_MODULES.filter((m) => m.code.toUpperCase() === code);
const primaryFallback = fallbackEntries[fallbackEntries.length - 1];
const priceInr = plan.price_inr ?? primaryFallback?.priceInr ?? 0;
const priceUsd = plan.price_usd ?? primaryFallback?.priceUsd ?? 0;
const priceEur = plan.price_eur ?? plan.price_usd ?? primaryFallback?.priceEur ?? priceUsd;
const planColor = plan.color || primaryFallback?.color || 'from-teal-500 to-cyan-500';
const planDesc = plan.description || primaryFallback?.desc || '';
// 1. Multi-item Core Packs (PATTERN_CORE, NUTRITION_CORE): emit sub-items + Complete Pack row
if (code in MULTI_ITEM_CORE_PACKS) {
const cfg = MULTI_ITEM_CORE_PACKS[code];
const planModules = [...(plan.modules || [])].sort(
(a, b) => (a.sort_order ?? 500) - (b.sort_order ?? 500),
);
if (planModules.length > 0) {
for (const mod of planModules) {
const apiMatch = apiModules.find(
(m) =>
(mod.code && (m.code || '').toLowerCase() === mod.code.toLowerCase()) ||
(mod.slug && (m.slug || '').toLowerCase() === mod.slug.toLowerCase()),
);
items.push({
code,
name: mod.name,
category: cfg.category,
priceInr,
priceUsd,
priceEur,
desc: mod.description || apiMatch?.description || planDesc,
color: planColor,
sortOrder: mod.sort_order ?? apiMatch?.sort_order ?? 500,
planType: plan.plan_type,
});
}
if (planModules.length > 1) {
items.push({
code,
name: cfg.packTitle,
category: cfg.category,
priceInr,
priceUsd,
priceEur,
desc: planDesc || primaryFallback?.desc || `Unlock all ${cfg.category} modules.`,
color: cfg.defaultColor,
sortOrder: Number.MAX_SAFE_INTEGER,
planType: plan.plan_type,
});
}
} else if (fallbackEntries.length > 0) {
for (const fb of fallbackEntries) {
items.push({
...fb,
priceInr,
priceUsd,
priceEur,
sortOrder: fb.name.includes('Complete Pack') ? Number.MAX_SAFE_INTEGER : 500,
planType: plan.plan_type,
});
}
}
continue;
}
// 2. Lifetime or Core Category Packs (POINTS_PACK, THERAPEUTICS_CORE)
if (code === 'LIFETIME_ALL' || CORE_PACK_CODES.has(code)) {
const category = resolvePlanCategory(plan, apiModules);
items.push({
code,
name: primaryFallback?.name || plan.name,
category,
priceInr,
priceUsd,
priceEur,
desc: planDesc,
color: planColor,
sortOrder: Number.MAX_SAFE_INTEGER,
planType: plan.plan_type,
});
continue;
}
// 3. Custom Bundles (plan_type === 'bundle') — rendered in Card 6 (Custom Packages & Bundles)
if (plan.plan_type === 'bundle') {
items.push({
code,
name: plan.name,
category: 'Bundle',
priceInr,
priceUsd,
priceEur,
desc: planDesc || 'Custom bundled access.',
color: plan.color || 'from-slate-700 to-slate-900',
sortOrder: 500,
planType: plan.plan_type,
});
continue;
}
// 4. Single-module plans (POINTS_*, THERAPEUTICS_*, MOD_*, or any one_time plan)
const firstMod = plan.modules?.[0];
const apiMatch = findMatchingApiModule(plan, apiModules);
const category = resolvePlanCategory(plan, apiModules);
items.push({
code,
name: primaryFallback?.name || plan.name || firstMod?.name || code,
category,
priceInr,
priceUsd,
priceEur,
desc: planDesc || firstMod?.description || apiMatch?.description || '',
color: planColor,
sortOrder: firstMod?.sort_order ?? apiMatch?.sort_order ?? 500,
planType: plan.plan_type,
});
}
return items;
}

View File

@ -1,12 +1,33 @@
import { getCountryRuleByDialCode, getCountryRuleByName } from '../constants/countries'; import { parsePhoneNumberFromString, type CountryCode as LibCountryCode } from 'libphonenumber-js/max';
import {
COUNTRY_CODES,
getCountryRuleByDialCode,
getCountryRuleByName,
getCountryRuleByIso,
DEFAULT_COUNTRY,
} from '../constants/countries';
/**
* Formats a list of prefixes into human-readable text:
* e.g. ['3'] -> "3"
* e.g. ['6', '7'] -> "6 or 7"
* e.g. ['6', '7', '8', '9'] -> "6, 7, 8, or 9"
*/
export const formatPrefixList = (prefixes: string[]): string => {
if (prefixes.length === 0) return '';
if (prefixes.length === 1) return prefixes[0];
if (prefixes.length === 2) return `${prefixes[0]} or ${prefixes[1]}`;
return `${prefixes.slice(0, -1).join(', ')}, or ${prefixes[prefixes.length - 1]}`;
};
/** /**
* Strips non-numeric / non-phone characters from text in real-time * Strips non-numeric / non-phone characters from text in real-time
* If maxLength is provided, strictly restricts digit length * If maxLength is provided, strictly restricts digit length
* If allowPlus is false, strips any '+' symbols as well (for local number inputs)
*/ */
export const cleanPhoneInput = (text: string, maxLength?: number): string => { export const cleanPhoneInput = (text: string, maxLength = 15, allowPlus = true): string => {
const trimmedStart = text.trimStart(); const trimmedStart = text.trimStart();
const hasPlus = trimmedStart.startsWith('+'); const hasPlus = allowPlus && trimmedStart.startsWith('+');
const rest = hasPlus ? trimmedStart.slice(1) : text; const rest = hasPlus ? trimmedStart.slice(1) : text;
const digitsOnly = rest.replace(/\D/g, ''); const digitsOnly = rest.replace(/\D/g, '');
const boundedDigits = maxLength ? digitsOnly.slice(0, maxLength) : digitsOnly; const boundedDigits = maxLength ? digitsOnly.slice(0, maxLength) : digitsOnly;
@ -14,7 +35,8 @@ export const cleanPhoneInput = (text: string, maxLength?: number): string => {
}; };
/** /**
* Validates phone number according to country rules (e.g. India = exactly 10 digits) * Validates mobile phone number according to country telecom numbering plans.
* Uses libphonenumber-js to enforce mobile prefixes (e.g., France 06/07, India 6-9, UK 07).
*/ */
export const validatePhoneNumber = ( export const validatePhoneNumber = (
val?: string | null, val?: string | null,
@ -23,48 +45,92 @@ export const validatePhoneNumber = (
): string | null => { ): string | null => {
if (!val || !val.trim()) return null; if (!val || !val.trim()) return null;
const trimmed = val.trim(); const trimmed = val.trim();
const digits = trimmed.replace(/\D/g, '');
if (digits.length === 0) { // Explicitly disallow alphabetic characters
if (/[a-zA-Z]/.test(trimmed)) {
return 'Phone number cannot contain alphabetic characters.';
}
// Strictly disallow hyphens, dashes, and invalid symbols
if (/[\-_()/[\]]/.test(trimmed)) {
return 'Phone number cannot contain hyphens or special symbols.';
}
// Strictly enforce numeric digits with optional leading '+' and whitespace
if (!/^\+?[\d\s]+$/.test(trimmed)) {
return 'Please enter a valid phone number containing only numeric digits.';
}
const allDigits = trimmed.replace(/\D/g, '');
if (allDigits.length === 0) {
return 'Please enter a valid phone number with numeric digits.'; return 'Please enter a valid phone number with numeric digits.';
} }
// Resolve country rule by dial code or country name // Resolve country rule: prioritize explicit country name, fallback to dialCode
let rule = dialCode ? getCountryRuleByDialCode(dialCode) : undefined; let rule = country ? getCountryRuleByName(country) : undefined;
if ((!rule || rule.country === 'Other') && country) { if ((!rule || rule.country === 'Other') && dialCode) {
rule = getCountryRuleByName(country); rule = getCountryRuleByDialCode(dialCode, country);
} }
// Default to India if no specific rule resolved and dial code is +91 or country is India if (!rule) {
if (!rule || rule.country === 'Other') { rule = DEFAULT_COUNTRY;
if (dialCode === '+91' || (country && country.toLowerCase() === 'india')) { }
rule = getCountryRuleByDialCode('+91');
const iso2 = rule.iso2 || 'IN';
// Extract national digits without dial code prefix
let nationalDigits = allDigits;
const dialDigits = rule.code.replace(/\D/g, '');
if (trimmed.startsWith('+')) {
if (allDigits.startsWith(dialDigits)) {
nationalDigits = allDigits.slice(dialDigits.length);
}
} else if (allDigits.startsWith(dialDigits) && allDigits.length > rule.maxLength) {
nationalDigits = allDigits.slice(dialDigits.length);
}
const digitsWithoutTrunk0 = nationalDigits.startsWith('0') && iso2 !== 'IT'
? nationalDigits.replace(/^0+/, '')
: nationalDigits;
// 1. Enforce length validation FIRST so digit count errors take precedence over prefix errors
if (rule.minLength === rule.maxLength) {
if (digitsWithoutTrunk0.length !== rule.minLength && nationalDigits.length !== rule.minLength) {
return `${rule.country} mobile number must be exactly ${rule.minLength} digits.`;
}
} else {
// Variable length rules
if (digitsWithoutTrunk0.length < rule.minLength && nationalDigits.length < rule.minLength) {
return `${rule.country} mobile number is too short (min ${rule.minLength} digits).`;
}
if (nationalDigits.length > rule.maxLength || digitsWithoutTrunk0.length > rule.maxLength) {
return `${rule.country} mobile number cannot exceed ${rule.maxLength} digits.`;
} }
} }
if (rule && rule.country !== 'Other') { // 2. Generic prefix validation for mobile telecom numbering plans
if (rule.minLength === rule.maxLength) { if (rule.validPrefixes && rule.validPrefixes.length > 0) {
if (digits.length !== rule.minLength) { const hasValidPrefix = rule.validPrefixes.some(
return `${rule.country} phone number must be exactly ${rule.minLength} digits.`; (prefix) => digitsWithoutTrunk0.startsWith(prefix) || nationalDigits.startsWith(prefix)
} );
} else { if (!hasValidPrefix) {
if (digits.length < rule.minLength) { return `For ${rule.country}, the mobile number must start with ${formatPrefixList(rule.validPrefixes)}.`;
return `${rule.country} phone number must be at least ${rule.minLength} digits.`; }
} }
if (digits.length > rule.maxLength) {
return `${rule.country} phone number cannot exceed ${rule.maxLength} digits.`; // 3. Validate telecom numbering rules with libphonenumber-js
} const candidate = trimmed.startsWith('+') ? trimmed : `${rule.code}${nationalDigits}`;
const parsed = parsePhoneNumberFromString(candidate, iso2);
if (parsed && parsed.isValid()) {
const numberType = parsed.getType();
if (numberType === 'FIXED_LINE') {
return `Please enter a valid mobile number for ${rule.country} (landlines not allowed).`;
} }
return null; return null;
} }
// General fallback ITU E.164 const exampleStr = rule.example || rule.placeholder;
if (digits.length < 6) { return `Please enter a valid mobile number for ${rule.country}${exampleStr ? ` (e.g. ${exampleStr})` : ''}.`;
return 'Phone number must contain at least 6 digits.';
}
if (digits.length > 15) {
return 'Phone number cannot exceed 15 digits.';
}
return null;
}; };
export const isValidPhoneNumber = ( export const isValidPhoneNumber = (
@ -74,3 +140,172 @@ export const isValidPhoneNumber = (
): boolean => { ): boolean => {
return validatePhoneNumber(val, dialCode, country) === null; return validatePhoneNumber(val, dialCode, country) === null;
}; };
/**
* Splits a full phone number into dialCode, country, and localDigits
*/
export const parsePhoneNumber = (
fullPhone?: string | null,
fallbackCountry = 'India'
): { country: string; dialCode: string; localDigits: string; iso2: LibCountryCode } => {
const defaultRule = getCountryRuleByName(fallbackCountry) || DEFAULT_COUNTRY;
if (!fullPhone || !fullPhone.trim()) {
return {
country: defaultRule.country,
dialCode: defaultRule.code,
localDigits: '',
iso2: defaultRule.iso2,
};
}
const trimmed = fullPhone.trim();
const parsed = parsePhoneNumberFromString(trimmed, defaultRule.iso2);
if (parsed) {
const matchedRule = parsed.country
? getCountryRuleByIso(parsed.country)
: getCountryRuleByDialCode(`+${parsed.countryCallingCode}`, fallbackCountry);
return {
country: matchedRule.country,
dialCode: `+${parsed.countryCallingCode}`,
localDigits: parsed.nationalNumber,
iso2: matchedRule.iso2,
};
}
// Fallback regex match from longest dial code
const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length);
// If fallbackCountry is specified and matches the prefix, prioritize it
if (fallbackCountry && trimmed.startsWith(defaultRule.code)) {
const rawLocal = trimmed.slice(defaultRule.code.length).replace(/\D/g, '');
return {
country: defaultRule.country,
dialCode: defaultRule.code,
localDigits: rawLocal.slice(0, defaultRule.maxLength),
iso2: defaultRule.iso2,
};
}
const matched = sorted.find((c) => trimmed.startsWith(c.code));
if (matched) {
const rawLocal = trimmed.slice(matched.code.length).replace(/\D/g, '');
return {
country: matched.country,
dialCode: matched.code,
localDigits: rawLocal.slice(0, matched.maxLength),
iso2: matched.iso2,
};
}
const rawDigits = trimmed.replace(/\D/g, '');
return {
country: defaultRule.country,
dialCode: defaultRule.code,
localDigits: rawDigits.slice(0, defaultRule.maxLength),
iso2: defaultRule.iso2,
};
};
/**
* Formats full phone number cleanly as E.164 without spaces (+<dialCode><digits>),
* automatically stripping any national trunk '0' where appropriate.
*/
export const formatE164Phone = (dialCode: string, localDigits: string, country?: string): string => {
if (!localDigits || !localDigits.trim()) return '';
const rule = country ? getCountryRuleByName(country) : getCountryRuleByDialCode(dialCode, country);
const rawDigits = localDigits.replace(/\D/g, '');
if (!rawDigits) return '';
const code = dialCode.startsWith('+') ? dialCode : `+${dialCode}`;
const candidate = localDigits.startsWith('+') ? localDigits : `${code}${rawDigits}`;
const parsed = parsePhoneNumberFromString(candidate, rule.iso2);
if (parsed && parsed.isValid()) {
return parsed.format('E.164');
}
// Fallback: If starts with trunk 0 and country is not one that keeps trunk 0 (like Italy)
let cleanLocal = rawDigits;
if (rule.iso2 !== 'IT' && cleanLocal.startsWith('0')) {
cleanLocal = cleanLocal.replace(/^0+/, '');
}
return `${code}${cleanLocal}`;
};
/**
* Updates the dial code prefix of an existing phone number when country changes.
* Automatically clamps remaining digits to the new country's maxLength.
*/
export const updatePhoneDialCode = (
currentPhone: string,
oldCountry: string,
newCountry: string
): string => {
const trimmed = currentPhone.trim();
if (!trimmed) return '';
const oldRule = getCountryRuleByName(oldCountry);
const newRule = getCountryRuleByName(newCountry);
const parsed = parsePhoneNumber(trimmed, oldRule.country);
const bounded = parsed.localDigits.slice(0, newRule.maxLength);
return bounded ? `${newRule.code} ${bounded}` : `${newRule.code} `;
};
export const SPECIAL_CHAR_REGEX = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?`~]/;
/**
* Validates password strength consistently across registration, profile change, and password reset:
* - Minimum 8 characters
* - No spaces (whitespace strictly disallowed)
* - At least one uppercase letter
* - At least one number
* - No emojis
* - At least one special character from standard symbol set
*/
export const validatePassword = (password: string, fieldName = 'Password'): string | null => {
if (!password) {
return `${fieldName} is required.`;
}
if (password.length < 8) {
return `${fieldName} must be at least 8 characters long.`;
}
if (/\s/.test(password)) {
return `${fieldName} must not contain spaces.`;
}
if (!/[A-Z]/.test(password)) {
return `${fieldName} must contain at least one uppercase letter.`;
}
if (!/[0-9]/.test(password)) {
return `${fieldName} must contain at least one number.`;
}
if (/\p{Extended_Pictographic}/u.test(password)) {
return `${fieldName} must not contain emojis.`;
}
if (!SPECIAL_CHAR_REGEX.test(password)) {
return `${fieldName} must contain at least one special character.`;
}
return null;
};
/**
* RFC 5322 & RFC 1035 compliant email validation regex.
*/
export const EMAIL_REGEX = /^[a-zA-Z0-9_%+-]+(?:\.[a-zA-Z0-9_%+-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/;
export const validateEmail = (email?: string | null): string | null => {
if (!email || !email.trim()) {
return 'Email address is required.';
}
if (!EMAIL_REGEX.test(email.trim())) {
return 'Please enter a valid email address.';
}
return null;
};
export const isValidEmail = (email?: string | null): boolean => {
return validateEmail(email) === null;
};

View File

@ -0,0 +1,106 @@
import { test, expect } from '@playwright/test';
import { mockPublicStoreApis } from './fixtures/apiMocks';
test.describe('Authentication & Deep-Link Flows', () => {
test.beforeEach(async ({ page }) => {
await mockPublicStoreApis(page);
});
test('login handles invalid credentials and succeeds with valid credentials', async ({ page }) => {
await page.route('**/api/auth/login', async (route) => {
const body = route.request().postDataJSON();
if (body.password === 'WrongPass1!') {
await route.fulfill({
status: 401,
contentType: 'application/json',
body: JSON.stringify({ detail: 'Invalid email or password.' }),
});
return;
}
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ access_token: 'new-jwt-token' }),
});
});
await page.route('**/api/auth/profile', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
id: 'user-1',
email: 'doctor@acupedia.in',
display_name: 'Dr. Acupedia',
phone_number: '+919876543210',
country: 'India',
}),
});
});
await page.route('**/api/access/me', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ active_subscriptions: [], unlocked_module_codes: [], unlocked_module_slugs: [] }),
});
});
await page.goto('./');
await page.getByRole('button', { name: /Login/i }).first().click();
await expect(page.getByText('Welcome Back!')).toBeVisible();
await page.getByPlaceholder('doctor@example.com').fill('doctor@acupedia.in');
await page.locator('input[type="password"]').fill('WrongPass1!');
await page.locator('form button[type="submit"]').click();
await expect(page.getByText('Invalid email or password.')).toBeVisible();
await page.locator('input[type="password"]').fill('ValidPass1!');
await page.locator('form button[type="submit"]').click();
await expect(page.getByText('Welcome Back!')).not.toBeVisible();
await expect(page.getByText('Billing Currency:')).toBeVisible();
});
test('forgot password requests OTP and resets password', async ({ page }) => {
await page.route('**/api/auth/forgot-password', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ message: 'OTP sent to your email.' }),
});
});
await page.route('**/api/auth/reset-password', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ message: 'Password reset successful.' }),
});
});
await page.goto('./?login=true');
await expect(page.getByText('Welcome Back!')).toBeVisible();
await page.getByRole('button', { name: /Forgot/i }).click();
await expect(page.getByText('Reset Password')).toBeVisible();
await page.getByPlaceholder('doctor@example.com').fill('doctor@acupedia.in');
await page.getByRole('button', { name: 'Send Verification Code' }).click();
await expect(page.getByPlaceholder('123456')).toBeVisible();
await page.getByPlaceholder('123456').fill('654321');
await page.getByPlaceholder('Min 8 chars (1 uppercase, 1 number, 1 special)').fill('NewPass123!');
await page.getByPlaceholder('Re-enter new password').fill('NewPass123!');
await page.getByRole('button', { name: 'Set New Password' }).click();
await expect(page.getByText(/Password Updated/i)).toBeVisible();
});
test('deep-link ?planCode=THERAPEUTICS_EAR pre-selects Ear reflexology in cart', async ({ page }) => {
await page.goto('./?planCode=THERAPEUTICS_EAR');
await expect(page.getByText('1 Item')).toBeVisible();
await expect(page.getByText('Therapeutics: Ear reflexology').last()).toBeVisible();
await expect(page.getByText('Lifetime Unlimited Access Pass').nth(1)).toBeVisible();
});
});

View File

@ -0,0 +1,65 @@
import { test, expect } from '@playwright/test';
import { mockAuthenticatedUser, mockPublicStoreApis } from './fixtures/apiMocks';
test.describe('Cart, Multi-Currency & Coupons', () => {
test('adds/removes items and enforces Complete Pack and Lifetime bundle rules', async ({ page }) => {
await mockPublicStoreApis(page);
await page.goto('./');
// Add individual Points: Acu
await page.getByText('Acu (EOV+Cat+Ext+MR)').click();
await expect(page.getByText('1 Item')).toBeVisible();
// Selecting Points Complete Pack replaces individual Points: Acu
await page.locator('span', { hasText: /^Complete Pack$/ }).first().click();
await expect(page.getByText('1 Item')).toBeVisible();
await expect(page.getByText('Points: Complete Pack')).toBeVisible();
// Selecting Lifetime Pass replaces everything else in cart
await page.getByText('Lifetime Unlimited Access Pass').nth(1).click();
await expect(page.getByText('1 Item')).toBeVisible();
await expect(page.getByText('Lifetime Unlimited Access Pass').last()).toBeVisible();
// Remove item via trash button in CartDrawer
await page.getByTitle('Remove item').click();
await expect(page.getByText('0 Items')).toBeVisible();
await expect(page.getByText('Your checkout cart is empty.')).toBeVisible();
});
test('applies valid coupon, handles invalid coupon, and removes coupon', async ({ page }) => {
await mockPublicStoreApis(page);
await page.goto('./');
await page.getByText('Acu (EOV+Cat+Ext+MR)').click();
await expect(page.getByText('Base Subtotal')).toBeVisible();
const couponInput = page.getByPlaceholder('e.g. AGENT40, EVENT_NEW');
await couponInput.fill('SAVE20');
await page.getByRole('button', { name: 'Apply' }).click();
await expect(page.getByText(/Coupon Active: SAVE20/)).toBeVisible();
await expect(page.getByText('Coupon Discount (SAVE20)')).toBeVisible();
// Remove coupon
await page.getByRole('button', { name: 'Remove', exact: true }).click();
await expect(page.getByText(/Coupon Active: SAVE20/)).not.toBeVisible();
// Try invalid coupon
await couponInput.fill('BADCODE');
await page.getByRole('button', { name: 'Apply' }).click();
await expect(page.getByText(/Invalid or expired coupon code/i)).toBeVisible();
});
test('displays EUR pricing without GST for European user', async ({ page }) => {
await mockPublicStoreApis(page);
await mockAuthenticatedUser(page, {
country: 'Germany',
phone_number: '+4915123456789',
});
await page.goto('./');
await expect(page.getByText('Billing Currency:')).toBeVisible();
await page.getByText('Acu (EOV+Cat+Ext+MR)').click();
await expect(page.getByText('€5').first()).toBeVisible();
});
});

130
tests/e2e/catalog.spec.ts Normal file
View File

@ -0,0 +1,130 @@
import { test, expect } from '@playwright/test';
import { MOCK_PLANS, mockAuthenticatedUser, mockPublicStoreApis } from './fixtures/apiMocks';
test.describe('Catalog Section', () => {
test('renders custom curated bundles when admin plan exists', async ({ page }) => {
await mockPublicStoreApis(page);
await page.route('**/api/plans', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([
...MOCK_PLANS,
{
code: 'SUMMER_COMBO',
name: 'Summer Special Combo',
description: 'Special combo of Acupoints and Nutrition',
plan_type: 'bundle',
billing_period: 'yearly',
price_inr: 700,
price_usd: 15,
price_eur: 15,
is_active: true,
badge_text: 'Limited Offer',
heading: 'Special Curated Bundles',
subtitle: 'Hand-picked bundles',
modules: [
{ slug: 'acupuncture-points', name: 'Acupuncture Points' },
{ slug: 'nutrition', name: 'Nutrition' },
],
module_slugs: ['acupuncture-points', 'nutrition'],
},
]),
});
});
await page.goto('./');
await expect(page.getByText('Special Curated Bundles')).toBeVisible();
await expect(page.getByText('Summer Special Combo')).toBeVisible();
await expect(page.getByText('Limited Offer').first()).toBeVisible();
});
test('toggles Hide Locked / Show Locked and marks unlocked modules as UNLOCKED', async ({ page }) => {
await mockPublicStoreApis(page);
await mockAuthenticatedUser(page, {
unlocked_module_codes: ['POINTS_ACU'],
active_subscriptions: [
{
id: 'sub-1',
plan_code: 'POINTS_ACU',
status: 'active',
started_at: '2026-01-01T00:00:00Z',
expires_at: '2027-01-01T00:00:00Z',
},
],
});
await page.goto('./');
// POINTS_ACU should display UNLOCKED badge
await expect(page.getByText('UNLOCKED').first()).toBeVisible();
// Hide Locked for Points card -> hides locked items but keeps UNLOCKED item visible
const hideLockedBtn = page.getByRole('button', { name: /Hide Locked/i }).first();
await hideLockedBtn.click();
await expect(page.getByRole('button', { name: /Show Locked/i }).first()).toBeVisible();
await expect(page.getByText('Acu (EOV+Cat+Ext+MR)')).toBeVisible();
await expect(page.getByText('Ear / Auricular')).not.toBeVisible();
// Show Locked restores them
await page.getByRole('button', { name: /Show Locked/i }).first().click();
await expect(page.getByText('Ear / Auricular')).toBeVisible();
});
test('hides inactive locked plans from the catalog', async ({ page }) => {
await mockPublicStoreApis(page);
await page.route('**/api/plans', async (route) => {
const updated = MOCK_PLANS.map((p) =>
p.code === 'POINTS_SCALP' ? { ...p, is_active: false } : p
);
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(updated),
});
});
await page.goto('./');
await expect(page.getByText('Acu (EOV+Cat+Ext+MR)')).toBeVisible();
await expect(page.getByText('Scalp', { exact: true })).not.toBeVisible();
});
test('renders newly activated Module Builder plan in its category and supports ?planCode deep link', async ({ page }) => {
await mockPublicStoreApis(page);
await page.route('**/api/plans', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([
...MOCK_PLANS,
{
code: 'MOD_M0044',
base_code: 'MOD_M0044',
name: 'Pediatric Disorders',
description: 'TCM pediatric treatment protocols.',
plan_type: 'one_time',
billing_period: 'yearly',
price_inr: 600,
price_usd: 15,
price_eur: 15,
is_active: true,
modules: [
{
code: 'm0044',
slug: 'pediatric-disorders',
name: 'Pediatric Disorders',
description: 'TCM pediatric treatment protocols.',
category: 'Therapeutics',
sort_order: 40,
},
],
},
]),
});
});
await page.goto('./?planCode=MOD_M0044');
await expect(page.getByText('Pediatric Disorders').first()).toBeVisible();
await expect(page.getByText('1 Item')).toBeVisible();
});
});

View File

@ -0,0 +1,221 @@
import { test, expect } from '@playwright/test';
import { mockPublicStoreApis, mockAuthenticatedUser } from './fixtures/apiMocks';
test.describe('Phase 4: Checkout, Billing Phone & Razorpay Flow', () => {
test.beforeEach(async ({ page }) => {
await mockPublicStoreApis(page);
});
test('unauthenticated checkout opens AuthModal', async ({ page }) => {
await page.goto('./');
await expect(page.getByText('Acu (EOV+Cat+Ext+MR)')).toBeVisible();
// Add item to cart and open cart drawer
await page.getByText('Acu (EOV+Cat+Ext+MR)').click();
await page.getByRole('button', { name: /Secure Payment with Razorpay/i }).click();
// AuthModal should appear in register mode
await expect(page.getByRole('heading', { name: 'Create Account' })).toBeVisible();
});
test('missing billing phone opens BillingPhoneModal, validates, saves, and completes Razorpay payment', async ({ page }) => {
// Mock authenticated user with NO phone number
await mockAuthenticatedUser(page, { phone_number: '' });
let profilePutPayload: any = null;
await page.route('**/api/auth/profile', async (route) => {
if (route.request().method() === 'PUT') {
profilePutPayload = route.request().postDataJSON();
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ status: 'success' }),
});
} else {
await route.fallback();
}
});
await page.route('**/api/checkout/create-order', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
razorpay_order_id: 'order_mock_001',
grand_total: 1000,
currency: 'INR',
}),
});
});
await page.route('**/api/checkout/verify', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
status: 'success',
invoice_number: 'INV-2026-0042',
invoice_url: '/api/checkout/payment/pay_mock_12345/invoice/view',
message: 'Payment verified successfully and module entitlements unlocked!',
}),
});
});
// Inject mock window.Razorpay that auto-succeeds on .open()
await page.addInitScript(() => {
(window as any).__openedUrls = [];
window.open = ((url: string) => {
(window as any).__openedUrls.push(url);
return null;
}) as any;
(window as any).Razorpay = function (options: any) {
this.options = options;
this.events = {};
this.on = (event: string, cb: Function) => {
this.events[event] = cb;
};
this.open = () => {
setTimeout(() => {
options.handler({
razorpay_order_id: options.order_id,
razorpay_payment_id: 'pay_mock_12345',
razorpay_signature: 'sig_mock_xyz',
});
}, 50);
};
};
});
await page.goto('./');
await expect(page.getByText('Acu (EOV+Cat+Ext+MR)')).toBeVisible();
await page.getByText('Acu (EOV+Cat+Ext+MR)').click();
await page.getByRole('button', { name: /Secure Payment with Razorpay/i }).click();
// BillingPhoneModal should appear
await expect(page.getByText('Billing Contact Number')).toBeVisible();
// Test empty phone validation
await page.getByRole('button', { name: 'Save Phone Number' }).click();
await expect(page.getByText(/Please enter your mobile number/i)).toBeVisible();
// Enter valid Indian 10-digit mobile number
const phoneInput = page.locator('input[type="tel"]').last();
await phoneInput.fill('9876543210');
await page.getByRole('button', { name: 'Save Phone Number' }).click();
// Should save phone via PUT /api/auth/profile and auto-proceed to Razorpay -> PaymentSuccessModal
await expect(page.getByText('Thank You for Your Purchase!')).toBeVisible({ timeout: 10000 });
expect(profilePutPayload).toEqual({
phone_number: '+919876543210',
country: 'India',
});
// Verify PaymentSuccessModal details
await expect(page.getByText('INV-2026-0042')).toBeVisible();
await expect(page.getByText('pay_mock_12345')).toBeVisible();
await expect(page.getByText('₹1000')).toBeVisible();
// Pause 10s auto-redirect
await page.getByRole('button', { name: /Stay on Web/i }).click();
await expect(page.getByText(/Auto-redirect paused/i)).toBeVisible();
// Click Download Invoice PDF -> opens invoice URL & navigates to Subscriptions tab
await page.getByText('Download Invoice PDF').click();
const openedUrls = await page.evaluate(() => (window as any).__openedUrls);
expect(openedUrls.some((u: string) => u.includes('/api/checkout/payment/pay_mock_12345/invoice/view'))).toBe(true);
});
test('Razorpay modal dismiss cancels cleanly without calling verify', async ({ page }) => {
await mockAuthenticatedUser(page, { phone_number: '+919876543210' });
let verifyCalled = false;
await page.route('**/api/checkout/create-order', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
razorpay_order_id: 'order_mock_cancel',
grand_total: 1000,
currency: 'INR',
}),
});
});
await page.route('**/api/checkout/verify', async (route) => {
verifyCalled = true;
await route.fulfill({ status: 200, body: '{}' });
});
await page.addInitScript(() => {
(window as any).Razorpay = function (options: any) {
this.on = () => {};
this.open = () => {
setTimeout(() => {
options.modal.ondismiss();
}, 50);
};
};
});
await page.goto('./');
await page.getByText('Acu (EOV+Cat+Ext+MR)').click();
await page.getByRole('button', { name: /Secure Payment with Razorpay/i }).click();
// Button should return to enabled state, verify not called, success modal not shown
await expect(page.getByRole('button', { name: /Secure Payment with Razorpay/i })).toBeEnabled();
expect(verifyCalled).toBe(false);
await expect(page.getByText('Thank You for Your Purchase!')).not.toBeVisible();
});
test('Razorpay payment.failed and verify signature failure show error feedback', async ({ page }) => {
await mockAuthenticatedUser(page, { phone_number: '+919876543210' });
await page.route('**/api/checkout/create-order', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
razorpay_order_id: 'order_mock_fail',
grand_total: 1000,
currency: 'INR',
}),
});
});
await page.route('**/api/checkout/verify', async (route) => {
await route.fulfill({
status: 400,
contentType: 'application/json',
body: JSON.stringify({ detail: 'Invalid Razorpay signature' }),
});
});
await page.addInitScript(() => {
(window as any).Razorpay = function (options: any) {
this.events = {};
this.on = (event: string, cb: Function) => {
this.events[event] = cb;
};
this.open = () => {
setTimeout(() => {
options.handler({
razorpay_order_id: options.order_id,
razorpay_payment_id: 'pay_bad_sig',
razorpay_signature: 'bad_sig',
});
}, 50);
};
};
});
await page.goto('./');
await page.getByText('Acu (EOV+Cat+Ext+MR)').click();
await page.getByRole('button', { name: /Secure Payment with Razorpay/i }).click();
await expect(page.getByText('Verification Failed')).toBeVisible();
await expect(page.getByText('Invalid Razorpay signature')).toBeVisible();
});
});

View File

@ -0,0 +1,395 @@
import { test, expect } from '@playwright/test';
import { mockPublicStoreApis, mockAuthenticatedUser } from './fixtures/apiMocks';
test.describe('Full Storefront Edge Cases & Remaining Flows', () => {
test.beforeEach(async ({ page }) => {
await mockPublicStoreApis(page);
});
test('registration validates weak password, handles duplicate email, and succeeds with Country-based currency', async ({ page }) => {
await page.route('**/api/auth/register', async (route) => {
const body = route.request().postDataJSON();
if (body.email === 'existing@acupedia.com') {
await route.fulfill({
status: 409,
contentType: 'application/json',
body: JSON.stringify({ detail: 'An account with this email already exists.' }),
});
} else {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ access_token: 'new-user-jwt' }),
});
}
});
await page.route('**/api/auth/profile', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
id: 99,
email: 'newdoc@acupedia.com',
display_name: 'Dr. Weber',
phone_number: '+4915123456789',
country: 'Germany',
}),
});
});
await page.route('**/api/access/me', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ unlocked_module_codes: [], active_subscriptions: [] }),
});
});
await page.goto('./');
await page.getByRole('button', { name: 'Join' }).click();
await expect(page.getByRole('heading', { name: 'Create Account' })).toBeVisible();
// Fill weak password first
await page.locator('form input[type="text"]').first().fill('Dr. Weber');
await page.locator('input[type="email"]').fill('existing@acupedia.com');
await page.locator('#phone-input').fill('9876543210');
await page.getByPlaceholder('••••••••').fill('123');
await page.getByRole('button', { name: 'Create Account' }).click();
await expect(page.getByText(/at least 8 characters/i)).toBeVisible();
// Fix password -> trigger 409 duplicate email
await page.getByPlaceholder('••••••••').fill('StrongPass1!');
await page.getByRole('button', { name: 'Create Account' }).click();
await expect(page.getByText('An account with this email already exists.')).toBeVisible();
// Switch to new email & Germany -> auto-switches storefront currency to EUR
await page.locator('input[type="email"]').fill('newdoc@acupedia.com');
await page.getByRole('button', { name: /India/i }).click();
await page.getByText('Germany').click();
await page.locator('#phone-input').fill('15123456789');
await page.getByRole('button', { name: 'Create Account' }).click();
await expect(page.getByRole('heading', { name: 'Create Account' })).not.toBeVisible();
await expect(page.getByText('EUR (€)')).toBeVisible();
});
test('URL deep-links ?token, ?login=true, and ?logged_out=true behave accurately', async ({ page }) => {
// 1. ?login=true opens AuthModal in login mode
await page.goto('./?login=true');
await expect(page.getByText('Welcome Back!')).toBeVisible();
// 2. ?logged_out=true renders LoggedOutView and Log In Again opens modal
await page.goto('./?logged_out=true');
await expect(page.getByText('Successfully Logged Out')).toBeVisible();
await page.getByRole('link', { name: 'Log In Again' }).click();
await expect(page.getByText('Welcome Back!')).toBeVisible();
// 3. ?token=deep-token auto-authenticates without AuthModal
await page.route('**/api/auth/profile', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
id: 1,
email: 'doc@acupedia.com',
display_name: 'Dr. DeepLink',
phone_number: '+14155552671',
country: 'United States',
}),
});
});
await page.route('**/api/access/me', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ unlocked_module_codes: [], active_subscriptions: [] }),
});
});
await page.goto('./?token=deep-token');
await expect(page.locator('header').getByText('D').first()).toBeVisible();
await expect(page.getByText('USD ($)')).toBeVisible();
});
test('live Country switch in ProfileDrawer updates currency from USD to EUR without reload', async ({ page }) => {
let currentCountry = 'United States';
await mockAuthenticatedUser(page, { country: 'United States', phone_number: '+14155552671' });
await page.route('**/api/auth/profile', async (route) => {
if (route.request().method() === 'PUT') {
const body = route.request().postDataJSON();
if (body?.country) currentCountry = body.country;
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ status: 'success' }),
});
} else {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
id: 1,
email: 'doctor@acupedia.com',
display_name: 'Dr. Test',
phone_number: '+4915123456789',
country: currentCountry,
}),
});
}
});
await page.goto('./');
await expect(page.getByText('USD ($)')).toBeVisible();
// Open ProfileDrawer and switch Country to Germany
await page.locator('header button').filter({ hasText: /^D/ }).first().click();
await page.getByRole('button', { name: /United States/i }).click();
await page.getByText('Germany').click();
await page.locator('#phone-input').fill('15123456789');
await page.getByRole('button', { name: 'Save Profile Details' }).click();
await expect(page.getByText('Changes saved successfully! ✓')).toBeVisible();
// Close drawer and verify currency switched to EUR (€)
await page.locator('button:has(svg.lucide-circle-x)').first().click();
await expect(page.getByText('EUR (€)')).toBeVisible();
});
test('LifetimeBanner renders when LIFETIME_ALL is active and guest cart auto-filters unlocked items on login', async ({ page }) => {
// Guest adds POINTS_ACU to cart, then logs in as user who already owns POINTS_ACU
await page.route('**/api/auth/login', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ access_token: 'mock-jwt' }),
});
});
await page.route('**/api/auth/profile', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
id: 1,
email: 'owner@acupedia.com',
display_name: 'Dr. Owner',
phone_number: '+919876543210',
country: 'India',
}),
});
});
await page.route('**/api/access/me', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
unlocked_module_codes: ['POINTS_ACU'],
active_subscriptions: [{ id: 1, plan_code: 'POINTS_ACU', status: 'ACTIVE', started_at: '2026-01-01', expires_at: '2027-01-01' }],
}),
});
});
await page.goto('./');
await page.getByText('Acu (EOV+Cat+Ext+MR)').click();
await expect(page.getByText('1 Item')).toBeVisible();
await page.getByRole('button', { name: 'Login' }).click();
await page.locator('input[type="email"]').fill('owner@acupedia.com');
await page.getByPlaceholder('••••••••').fill('Password1!');
await page.getByRole('button', { name: /Sign In/i }).click();
// Already-unlocked item is auto-removed from cart
await expect(page.getByText('0 Items')).toBeVisible();
// Now test LIFETIME_ALL -> LifetimeBanner visible
await mockAuthenticatedUser(page, {
unlocked_module_codes: ['LIFETIME_ALL'],
active_subscriptions: [{ id: 2, plan_code: 'LIFETIME_ALL', status: 'ACTIVE', started_at: '2026-01-01', expires_at: '' }],
});
await page.goto('./');
await expect(page.getByText('LIFETIME ACCESS PASSPORT ACTIVE!')).toBeVisible();
});
test('CartDrawer renders Early Renewal, Staggered Loyalty Discount, and Gateway Fee lines', async ({ page }) => {
await page.route('**/api/cart/calculate', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
currency: 'INR',
base_subtotal: 1000,
renewal_discount_amount: 200,
bundle_discount_amount: 100,
coupon_discount_amount: 0,
total_discounts: 300,
convenience_fee_rate: 2,
convenience_fee: 14,
taxable_amount: 0,
gst_amount: 0,
grand_total: 714,
discount_policy: 'Staggered Buy: 10%',
coupon_applied: 'None',
coupon_error: null,
}),
});
});
await page.goto('./');
await page.getByText('Acu (EOV+Cat+Ext+MR)').click();
await expect(page.getByText('Early Renewal Discount (20%)')).toBeVisible();
await expect(page.getByText('Loyalty Discount: 10%')).toBeVisible();
await expect(page.getByText('Gateway fee (2%)')).toBeVisible();
await expect(page.getByText('₹714')).toBeVisible();
});
test('ProfileDrawer validates password mismatch, wrong old password, and downloads invoice', async ({ page }) => {
await page.addInitScript(() => {
(window as any).__openedUrls = [];
window.open = ((url: string) => {
(window as any).__openedUrls.push(url);
return null;
}) as any;
});
await mockAuthenticatedUser(page, {
active_subscriptions: [
{
id: 10,
plan_code: 'POINTS_ACU',
status: 'ACTIVE',
started_at: '2026-01-01T00:00:00Z',
expires_at: '2027-01-01T00:00:00Z',
payment_id: 'pay_prof_1',
invoice_number: 'INV-PROF-1',
invoice_url: '/api/checkout/payment/pay_prof_1/invoice/view',
},
],
});
await page.route('**/api/auth/change-password', async (route) => {
await route.fulfill({
status: 400,
contentType: 'application/json',
body: JSON.stringify({ detail: 'Current password is incorrect.' }),
});
});
await page.goto('./');
await page.locator('header button').filter({ hasText: /^D/ }).first().click();
// Invoice download from ProfileDrawer
await page.getByRole('button', { name: /Invoice/i }).first().click();
const openedUrls = await page.evaluate(() => (window as any).__openedUrls);
expect(openedUrls.some((u: string) => u.includes('/api/checkout/payment/pay_prof_1/invoice/view'))).toBe(true);
// Change Password validation: mismatch & wrong old password
await page.getByRole('button', { name: /Change Password/i }).click();
const pwdInputs = page.locator('input[type="password"]');
await pwdInputs.nth(0).fill('WrongOld1!');
await pwdInputs.nth(1).fill('NewPass1!');
await pwdInputs.nth(2).fill('Mismatch1!');
await page.getByRole('button', { name: 'Update Password' }).click();
await expect(page.getByText(/do not match/i)).toBeVisible();
await pwdInputs.nth(2).fill('NewPass1!');
await page.getByRole('button', { name: 'Update Password' }).click();
await expect(page.getByText('Current password is incorrect.')).toBeVisible();
});
test('BillingPhoneModal duplicate phone error, create-order failure, and popstate back after payment', async ({ page }, testInfo) => {
await mockAuthenticatedUser(page, { phone_number: '' });
let failCreateOrder = true;
await page.route('**/api/checkout/create-order', async (route) => {
if (failCreateOrder) {
await route.fulfill({
status: 500,
contentType: 'application/json',
body: JSON.stringify({ detail: 'Order service unavailable' }),
});
} else {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ razorpay_order_id: 'order_pop_1', grand_total: 300, currency: 'INR' }),
});
}
});
let failPhoneSave = true;
await page.route('**/api/auth/profile', async (route) => {
if (route.request().method() === 'PUT') {
if (failPhoneSave) {
await route.fulfill({
status: 409,
contentType: 'application/json',
body: JSON.stringify({ detail: 'Phone number already registered.' }),
});
} else {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ status: 'success' }),
});
}
} else {
await route.fallback();
}
});
await page.route('**/api/checkout/verify', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ status: 'success', invoice_number: 'INV-POP-1', invoice_url: '/api/checkout/payment/pay_pop/invoice/view' }),
});
});
await page.addInitScript(() => {
(window as any).__alerts = [];
window.alert = (msg: string) => {
(window as any).__alerts.push(msg);
};
(window as any).Razorpay = function (options: any) {
this.on = () => {};
this.open = () => {
setTimeout(() => {
options.handler({
razorpay_order_id: options.order_id,
razorpay_payment_id: 'pay_pop',
razorpay_signature: 'sig_pop',
});
}, 50);
};
};
});
await page.goto('./');
await page.getByText('Acu (EOV+Cat+Ext+MR)').click();
// 1. create-order failure
await page.getByRole('button', { name: /Secure Payment with Razorpay/i }).click();
await expect.poll(async () => page.evaluate(() => (window as any).__alerts.length)).toBeGreaterThan(0);
// 2. create-order succeeds -> BillingPhoneModal opens -> duplicate phone 409 error
failCreateOrder = false;
await page.getByRole('button', { name: /Secure Payment with Razorpay/i }).click();
await expect(page.getByText('Billing Contact Number')).toBeVisible();
await page.locator('#phone-input').fill('9876543210');
await page.getByRole('button', { name: 'Save Phone Number' }).click();
await expect(page.getByText('Phone number already registered.')).toBeVisible();
// 3. Save succeeds -> PaymentSuccessModal opens -> browser popstate switches to Subscriptions tab
failPhoneSave = false;
await page.getByRole('button', { name: 'Save Phone Number' }).click();
await expect(page.getByText('Thank You for Your Purchase!')).toBeVisible({ timeout: 10000 });
await page.evaluate(() => window.dispatchEvent(new PopStateEvent('popstate')));
if (testInfo.project.name === 'chromium-desktop') {
await expect(page.getByText('Thank You for Your Purchase!')).not.toBeVisible();
} else {
await expect(page.getByText('Thank You for Your Purchase!')).toBeVisible();
}
});
});

View File

@ -0,0 +1,243 @@
import type { Page } from '@playwright/test';
export const MOCK_PLANS = [
{
code: 'LIFETIME_ALL',
name: 'Lifetime All-Access Plan',
description: '10 Years access to all modules',
plan_type: 'bundle',
billing_period: 'lifetime',
price_inr: 15000,
price_usd: 350,
price_eur: 350,
is_active: true,
module_slugs: ['acupuncture-points', 'scalp-acupuncture', 'ear-acupuncture', 'nutrition', 'auriculotherapy', 'gynecological-disorders'],
modules: [],
is_featured: true,
},
{
code: 'POINTS_PACK',
name: 'Points Complete Pack (1 Yr)',
plan_type: 'bundle',
billing_period: 'yearly',
price_inr: 900,
price_usd: 15,
price_eur: 15,
is_active: true,
module_slugs: ['acupuncture-points', 'scalp-acupuncture', 'ear-acupuncture'],
},
{
code: 'POINTS_ACU',
name: 'Acu Points Module (1 Yr)',
plan_type: 'one_time',
billing_period: 'yearly',
price_inr: 300,
price_usd: 5,
price_eur: 5,
is_active: true,
module_slugs: ['acupuncture-points'],
},
{
code: 'POINTS_SCALP',
name: 'Scalp Points Module (1 Yr)',
plan_type: 'one_time',
billing_period: 'yearly',
price_inr: 100,
price_usd: 2,
price_eur: 2,
is_active: true,
module_slugs: ['scalp-acupuncture'],
},
{
code: 'POINTS_EAR',
name: 'Ear Points Module (1 Yr)',
plan_type: 'one_time',
billing_period: 'yearly',
price_inr: 200,
price_usd: 3,
price_eur: 3,
is_active: true,
module_slugs: ['ear-acupuncture'],
},
{
code: 'PATTERN_CORE',
name: 'Pattern Module Access (1 Yr)',
plan_type: 'bundle',
billing_period: 'yearly',
price_inr: 500,
price_usd: 10,
price_eur: 10,
is_active: true,
module_slugs: ['eight-principles'],
},
{
code: 'NUTRITION_CORE',
name: 'Nutrition Module Access (1 Yr)',
plan_type: 'bundle',
billing_period: 'yearly',
price_inr: 600,
price_usd: 15,
price_eur: 15,
is_active: true,
module_slugs: ['nutrition'],
},
{
code: 'THERAPEUTICS_GYNAE',
name: 'Therapeutics: Gynecology (1 Yr)',
plan_type: 'one_time',
billing_period: 'yearly',
price_inr: 600,
price_usd: 15,
price_eur: 15,
is_active: true,
module_slugs: ['gynecological-disorders'],
},
{
code: 'THERAPEUTICS_EAR',
name: 'Therapeutics: Ear reflexology (1 Yr)',
plan_type: 'one_time',
billing_period: 'yearly',
price_inr: 600,
price_usd: 15,
price_eur: 15,
is_active: true,
module_slugs: ['auriculotherapy'],
},
{
code: 'THERAPEUTICS_CORE',
name: 'Therapeutics Complete Bundle (1 Yr)',
plan_type: 'bundle',
billing_period: 'yearly',
price_inr: 1200,
price_usd: 30,
price_eur: 30,
is_active: true,
module_slugs: ['gynecological-disorders', 'auriculotherapy'],
},
];
export async function mockPublicStoreApis(page: Page) {
await page.route('**/api/checkout/config', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ razorpay_key_id: 'rzp_test_mock_key' }),
});
});
await page.route('**/api/plans', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(MOCK_PLANS),
});
});
await page.route('**/api/contents/modules', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ modules: [] }),
});
});
await page.route('**/api/cart/calculate', async (route) => {
const reqBody = route.request().postDataJSON() || {};
const currency = (reqBody.currency || 'INR').toUpperCase();
const coupon = reqBody.coupon_code ? String(reqBody.coupon_code).trim().toUpperCase() : null;
const rawItems = reqBody.cart_item_codes || reqBody.items || [];
const itemCodes: string[] = Array.isArray(rawItems)
? rawItems.map((i: any) => (typeof i === 'string' ? i : i.code))
: [];
const priceKey = currency === 'INR' ? 'price_inr' : currency === 'EUR' ? 'price_eur' : 'price_usd';
const cartItems = itemCodes.map((code) => {
const found = MOCK_PLANS.find((p) => p.code === code);
return {
code,
name: found?.name || code,
price: found ? (found as any)[priceKey] : 100,
};
});
const baseSubtotal = cartItems.reduce((sum, item) => sum + item.price, 0);
let couponDiscount = 0;
let couponApplied = 'None';
let couponError: string | null = null;
if (coupon === 'SAVE20') {
couponDiscount = Math.round(baseSubtotal * 0.2 * 100) / 100;
couponApplied = 'Code: SAVE20 - 20% Off';
} else if (coupon === 'BADCODE') {
couponError = 'Invalid or expired coupon code.';
}
const totalDiscounts = couponDiscount;
const grandTotal = Math.round(Math.max(0, baseSubtotal - totalDiscounts) * 100) / 100;
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
currency,
cart_items: cartItems,
base_subtotal: baseSubtotal,
bundle_discount_amount: 0,
renewal_discount_amount: 0,
coupon_discount_amount: couponDiscount,
total_discounts: totalDiscounts,
convenience_fee_rate: 0,
convenience_fee: 0,
taxable_amount: 0,
gst_amount: 0,
grand_total: grandTotal,
discount_policy: 'None',
coupon_applied: couponApplied,
coupon_error: couponError,
}),
});
});
}
export async function mockAuthenticatedUser(page: Page, overrides: Record<string, any> = {}) {
const userPayload = {
id: 'user-1',
email: 'practitioner@acupedia.in',
display_name: 'Dr. Test',
phone_number: '+919876543210',
country: 'India',
...overrides,
};
const accessPayload = {
user_id: userPayload.id,
active_subscriptions: overrides.active_subscriptions || [],
active_entitlements: overrides.active_entitlements || [],
unlocked_module_codes: overrides.unlocked_module_codes || [],
unlocked_module_slugs: overrides.unlocked_module_slugs || [],
};
await page.addInitScript(() => {
localStorage.setItem('access_token', 'mock-jwt-token');
});
await page.route('**/api/auth/profile', async (route) => {
if (route.request().method() === 'GET') {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(userPayload),
});
} else {
await route.continue();
}
});
await page.route('**/api/access/me', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(accessPayload),
});
});
}

View File

@ -0,0 +1,87 @@
import { test, expect } from '@playwright/test';
import { mockAuthenticatedUser, mockPublicStoreApis } from './fixtures/apiMocks';
test.describe('Profile Drawer & Logout Flows', () => {
test('updates profile details and logs out cleanly', async ({ page }) => {
await mockPublicStoreApis(page);
await mockAuthenticatedUser(page, {
display_name: 'Dr. Initial',
phone_number: '+919876543210',
country: 'India',
});
await page.route('**/api/auth/profile', async (route) => {
if (route.request().method() === 'PUT') {
const body = route.request().postDataJSON();
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
id: 'user-1',
email: 'practitioner@acupedia.in',
display_name: body.display_name,
phone_number: body.phone_number,
country: body.country,
}),
});
return;
}
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
id: 'user-1',
email: 'practitioner@acupedia.in',
display_name: 'Dr. Initial',
phone_number: '+919876543210',
country: 'India',
}),
});
});
await page.goto('./');
// Open Profile Drawer via header avatar/button (shows 'Dr. Initial' on desktop, 'D' on mobile)
await page.locator('header button').filter({ hasText: /^D/ }).first().click();
await expect(page.getByText('Save Profile Details')).toBeVisible();
// Update Display Name and save
const nameInput = page.locator('input[value="Dr. Initial"]');
await nameInput.fill('Dr. Updated');
await page.getByRole('button', { name: 'Save Profile Details' }).click();
await expect(page.getByText(/Changes saved successfully!/i)).toBeVisible();
// Logout -> LoggedOutView
await page.getByRole('button', { name: /Log Out/i }).click();
await expect(page.getByText('Successfully Logged Out')).toBeVisible();
});
test('changes password and shows PasswordUpdatedModal', async ({ page }) => {
await mockPublicStoreApis(page);
await mockAuthenticatedUser(page, {
display_name: 'Dr. Initial',
phone_number: '+919876543210',
country: 'India',
});
await page.route('**/api/auth/change-password', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ message: 'Password updated successfully!' }),
});
});
await page.goto('./');
await page.locator('header button').filter({ hasText: /^D/ }).first().click();
await expect(page.getByText('Save Profile Details')).toBeVisible();
await page.getByRole('button', { name: 'Change Password' }).click();
await page.getByPlaceholder('Enter current password').fill('OldPass1!');
await page.getByPlaceholder('Min 8 chars, 1 uppercase, 1 digit, 1 special').fill('NewPass1!');
await page.getByPlaceholder('Repeat new password').fill('NewPass1!');
await page.getByRole('button', { name: 'Update Password' }).click();
await expect(page.getByText(/Password Updated/i)).toBeVisible();
});
});

22
tests/e2e/smoke.spec.ts Normal file
View File

@ -0,0 +1,22 @@
import { test, expect } from '@playwright/test';
import { mockPublicStoreApis } from './fixtures/apiMocks';
test.describe('Storefront Smoke Suite', () => {
test.beforeEach(async ({ page }) => {
await mockPublicStoreApis(page);
});
test('renders storefront catalog and complete pack badges', async ({ page }) => {
await page.goto('./');
await expect(page.getByRole('heading', { name: 'Unlock Professional TCM Modules' })).toBeVisible();
await expect(page.getByText('Points Reference Module')).toBeVisible();
await expect(page.getByText('Pattern Diagnosis Module')).toBeVisible();
await expect(page.getByText('TCM Nutrition & Dietetics')).toBeVisible();
await expect(page.getByText('Clinical Therapeutics')).toBeVisible();
await expect(page.getByText('Lifetime Unlimited Access Pass').first()).toBeVisible();
const badges = page.locator('span', { hasText: /^Complete Pack$/ });
expect(await badges.count()).toBeGreaterThanOrEqual(2);
});
});

View File

@ -0,0 +1,85 @@
import { test, expect } from '@playwright/test';
import { mockPublicStoreApis, mockAuthenticatedUser } from './fixtures/apiMocks';
test.describe('Phase 4: Subscriptions & Entitlements View', () => {
test.beforeEach(async ({ page }) => {
await mockPublicStoreApis(page);
});
test('unauthenticated user sees login prompt on Subscriptions tab', async ({ page }) => {
await page.goto('./');
await page.getByRole('button', { name: /Subscriptions/i }).first().click();
await expect(page.getByText('Please register or log in to view active entitlements.')).toBeVisible();
await page.getByRole('button', { name: 'Log In' }).click();
await expect(page.getByText('Welcome Back!')).toBeVisible();
});
test('authenticated user with no subscriptions sees empty state and can return to catalog', async ({ page }) => {
await mockAuthenticatedUser(page, { active_subscriptions: [] });
await page.goto('./');
await page.getByRole('button', { name: /Subscriptions/i }).first().click();
await expect(page.getByText('No active subscriptions')).toBeVisible();
await page.getByRole('button', { name: 'Explore Modules Catalog' }).click();
await expect(page.getByText('Acu (EOV+Cat+Ext+MR)')).toBeVisible();
});
test('populated subscriptions list renders passes, pagination, and invoice download', async ({ page }) => {
const futureDate = new Date(Date.now() + 180 * 24 * 60 * 60 * 1000).toISOString();
const tenYearsDate = new Date(Date.now() + 3650 * 24 * 60 * 60 * 1000).toISOString();
const subs = [
{
id: 1,
plan_code: 'LIFETIME_ALL',
status: 'ACTIVE',
started_at: '2026-01-01T00:00:00Z',
expires_at: tenYearsDate,
payment_id: 'pay_sub_1',
invoice_number: 'INV-2026-0001',
invoice_url: '/api/checkout/payment/pay_sub_1/invoice/view',
},
...Array.from({ length: 6 }, (_, i) => ({
id: i + 2,
plan_code: `MODULE_${i + 2}`,
status: 'ACTIVE',
started_at: '2026-02-01T00:00:00Z',
expires_at: futureDate,
payment_id: `pay_sub_${i + 2}`,
invoice_number: `INV-2026-000${i + 2}`,
invoice_url: `/api/checkout/payment/pay_sub_${i + 2}/invoice/view`,
})),
];
await page.addInitScript(() => {
(window as any).__openedUrls = [];
window.open = ((url: string) => {
(window as any).__openedUrls.push(url);
return null;
}) as any;
});
await mockAuthenticatedUser(page, {
active_subscriptions: subs,
unlocked_module_codes: subs.map((s) => s.plan_code),
});
await page.goto('./');
await page.getByRole('button', { name: /Subscriptions/i }).first().click();
// First page shows 6 items, including LIFETIME_ALL ("10 Years Pass")
await expect(page.getByText('10 Years Pass')).toBeVisible();
await expect(page.getByText('INV-2026-0001')).toBeVisible();
// Click Download Invoice on first card
await page.getByRole('button', { name: 'Download Invoice' }).first().click();
const openedUrls = await page.evaluate(() => (window as any).__openedUrls);
expect(openedUrls.some((u: string) => u.includes('/api/checkout/payment/pay_sub_1/invoice/view'))).toBe(true);
// Pagination is visible since totalCount = 7 > 6
await page.getByRole('button', { name: '2', exact: true }).click();
await expect(page.getByText('INV-2026-0007')).toBeVisible();
});
});

502
tests/unit/App.test.tsx Normal file
View File

@ -0,0 +1,502 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import axios from 'axios';
import App from '../../src/App';
vi.mock('axios', () => {
const mockAxios = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
isAxiosError: vi.fn((err) => Boolean(err?.isAxiosError)),
create: vi.fn(),
interceptors: {
request: { use: vi.fn() },
response: { use: vi.fn() },
},
};
mockAxios.create.mockReturnValue(mockAxios);
return { default: mockAxios };
});
const mockedAxios = axios as unknown as {
get: ReturnType<typeof vi.fn>;
post: ReturnType<typeof vi.fn>;
put: ReturnType<typeof vi.fn>;
};
const mockPlansResponse = [
{
code: 'LIFETIME_ALL',
name: 'Lifetime All-Access Plan',
plan_type: 'bundle',
billing_period: 'lifetime',
price_inr: 15000,
price_usd: 350,
price_eur: 350,
is_active: true,
module_slugs: ['acupuncture-points'],
},
{
code: 'POINTS_ACU',
name: 'Acu Points Module (1 Yr)',
plan_type: 'one_time',
billing_period: 'yearly',
price_inr: 300,
price_usd: 5,
price_eur: 5,
is_active: true,
module_slugs: ['acupuncture-points'],
},
{
code: 'POINTS_PACK',
name: 'Points Complete Pack (1 Yr)',
plan_type: 'bundle',
billing_period: 'yearly',
price_inr: 900,
price_usd: 15,
price_eur: 15,
is_active: true,
module_slugs: ['acupuncture-points', 'scalp-acupuncture', 'ear-acupuncture'],
},
{
code: 'THERAPEUTICS_CORE',
name: 'Therapeutics Complete Bundle (1 Yr)',
plan_type: 'bundle',
billing_period: 'yearly',
price_inr: 0,
price_usd: 30,
price_eur: 30,
is_active: true,
module_slugs: ['auriculotherapy', 'gynecological-disorders'],
},
];
function setupAxiosMocks(userOverrides: Record<string, any> = {}) {
mockedAxios.get.mockImplementation((url: string) => {
if (url.includes('/api/checkout/config')) {
return Promise.resolve({ data: { razorpay_key_id: 'rzp_test_123' } });
}
if (url.includes('/api/plans')) {
return Promise.resolve({ data: mockPlansResponse });
}
if (url.includes('/api/contents/modules')) {
return Promise.resolve({ data: [{ slug: 'acupuncture-points', name: 'Acupuncture Points', is_active: true }] });
}
if (url.includes('/api/auth/profile')) {
return Promise.resolve({
data: {
id: 1,
email: 'doc@acupedia.com',
display_name: 'Dr. Lin',
phone_number: '+919876543210',
country: 'India',
...userOverrides,
},
});
}
if (url.includes('/api/access/me')) {
return Promise.resolve({
data: {
unlocked_module_codes: userOverrides.unlocked_module_codes || [],
active_subscriptions: userOverrides.active_subscriptions || [],
},
});
}
return Promise.resolve({ data: {} });
});
mockedAxios.post.mockImplementation((url: string, body: any) => {
if (url.includes('/api/cart/calculate')) {
const hasCoupon = body?.coupon_code === 'SAVE20';
return Promise.resolve({
data: {
currency: body?.currency || 'INR',
base_subtotal: 300,
bundle_discount_amount: 0,
coupon_discount_amount: hasCoupon ? 60 : 0,
total_discounts: hasCoupon ? 60 : 0,
convenience_fee_rate: 0,
convenience_fee: 0,
taxable_amount: 0,
gst_amount: 0,
grand_total: hasCoupon ? 240 : 300,
discount_policy: 'None',
coupon_applied: hasCoupon ? 'Code: SAVE20 - 20% Off' : 'None',
coupon_error: body?.coupon_code && !hasCoupon ? 'Invalid coupon' : null,
},
});
}
if (url.includes('/api/auth/login')) {
return Promise.resolve({ data: { access_token: 'mock-jwt' } });
}
if (url.includes('/api/auth/register')) {
return Promise.resolve({ data: { access_token: 'mock-jwt' } });
}
if (url.includes('/api/auth/forgot-password')) {
return Promise.resolve({ data: { message: 'OTP sent' } });
}
if (url.includes('/api/auth/reset-password')) {
return Promise.resolve({ data: { message: 'Reset done' } });
}
if (url.includes('/api/auth/change-password')) {
return Promise.resolve({ data: { status: 'success' } });
}
if (url.includes('/api/checkout/create-order')) {
return Promise.resolve({ data: { razorpay_order_id: 'order_123', grand_total: 300 } });
}
if (url.includes('/api/checkout/verify')) {
return Promise.resolve({
data: {
status: 'success',
invoice_number: 'INV-123',
invoice_url: '/api/checkout/payment/pay_123/invoice/view',
},
});
}
return Promise.resolve({ data: {} });
});
mockedAxios.put.mockResolvedValue({ data: { status: 'success' } });
}
describe('App Integration', () => {
vi.setConfig({ testTimeout: 15000 });
beforeEach(() => {
localStorage.clear();
window.history.pushState({}, '', '/store/');
vi.stubGlobal('alert', vi.fn());
vi.stubGlobal('open', vi.fn());
setupAxiosMocks();
});
afterEach(() => {
vi.unstubAllGlobals();
vi.clearAllMocks();
});
it('handles ?planCode deep-link, coupon apply/remove, and unauthenticated checkout trigger', async () => {
const user = userEvent.setup();
window.history.pushState({}, '', '/store/?planCode=POINTS_ACU');
render(<App />);
await waitFor(() => expect(screen.getByText('1 Item')).toBeInTheDocument());
// Apply valid coupon
const couponInput = screen.getByPlaceholderText('e.g. AGENT40, EVENT_NEW');
await user.type(couponInput, 'SAVE20');
await user.click(screen.getByRole('button', { name: 'Apply' }));
await waitFor(() => expect(screen.getByText(/Coupon Active: SAVE20/)).toBeInTheDocument());
// Remove coupon
await user.click(screen.getByRole('button', { name: 'Remove' }));
await waitFor(() => expect(screen.queryByText(/Coupon Active: SAVE20/)).not.toBeInTheDocument());
// Checkout while logged out opens Create Account modal
await user.click(screen.getByRole('button', { name: /Secure Payment with Razorpay/i }));
expect(screen.getByRole('heading', { name: 'Create Account' })).toBeInTheDocument();
});
it('handles login, profile update, password change, and logout flows', async () => {
const user = userEvent.setup();
window.history.pushState({}, '', '/store/?login=true');
const { container } = render(<App />);
await waitFor(() => expect(screen.getByText('Welcome Back!')).toBeInTheDocument());
await user.type(container.querySelector('input[type="email"]') as HTMLInputElement, 'doc@acupedia.com');
await user.type(screen.getByPlaceholderText('••••••••'), 'Password1!');
await user.click(screen.getByRole('button', { name: /Sign In/i }));
await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument());
// Open ProfileDrawer
await user.click(screen.getByText('Dr. Lin'));
await user.click(screen.getByRole('button', { name: /Save Profile Details/i }));
await waitFor(() => expect(screen.getByText(/Changes saved successfully/i)).toBeInTheDocument());
// Log out
await user.click(screen.getByRole('button', { name: /Log Out Session/i }));
expect(screen.getByText('Successfully Logged Out')).toBeInTheDocument();
});
it('handles authenticated Razorpay checkout, verification, and invoice download', async () => {
const user = userEvent.setup();
localStorage.setItem('access_token', 'mock-jwt');
(window as any).Razorpay = function (options: any) {
this.on = vi.fn();
this.open = () => {
options.handler({
razorpay_order_id: options.order_id,
razorpay_payment_id: 'pay_123',
razorpay_signature: 'sig_123',
});
};
};
render(<App />);
await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument());
await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)'));
await user.click(screen.getByRole('button', { name: /Secure Payment with Razorpay/i }));
await waitFor(() => expect(screen.getByText('Thank You for Your Purchase!')).toBeInTheDocument());
await user.click(screen.getByText('Download Invoice PDF'));
expect(window.open).toHaveBeenCalled();
});
it('handles register, forgot/reset password, change password, and ?token + /subscriptions', async () => {
const user = userEvent.setup();
window.history.pushState({}, '', '/store/subscriptions?token=deep-token');
render(<App />);
await waitFor(() => expect(screen.getByText('No active subscriptions')).toBeInTheDocument());
// Switch to storefront and test bundle replacement + remove
await user.click(screen.getByRole('button', { name: 'Explore Modules Catalog' }));
await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)'));
await user.click(screen.getAllByText('Complete Pack')[0]);
await user.click(screen.getAllByText('Lifetime Unlimited Access Pass')[1]);
expect(screen.getByText('1 Item')).toBeInTheDocument();
// Open ProfileDrawer and change password
await user.click(screen.getByText('Dr. Lin'));
await user.click(screen.getByRole('button', { name: /Change Password/i }));
const pwdInputs = document.querySelectorAll('input[type="password"]');
await user.type(pwdInputs[0] as HTMLInputElement, 'OldPass1!');
await user.type(pwdInputs[1] as HTMLInputElement, 'NewPass1!');
await user.type(pwdInputs[2] as HTMLInputElement, 'NewPass1!');
await user.click(screen.getByRole('button', { name: /Update Password/i }));
await waitFor(() => expect(screen.getByText('Password Updated!')).toBeInTheDocument());
await user.click(screen.getByRole('button', { name: /Log In with New Password/i }));
// Test Forgot Password flow inside AuthModal
await user.click(screen.getByRole('button', { name: /Forgot password/i }));
const emailInput = document.querySelector('input[type="email"]') as HTMLInputElement;
await user.clear(emailInput);
await user.type(emailInput, 'doc@acupedia.com');
await user.click(screen.getByRole('button', { name: /Send Verification Code/i }));
await waitFor(() => expect(screen.getByRole('button', { name: /Set New Password/i })).toBeInTheDocument());
const resetPwdInputs = document.querySelectorAll('input[type="password"]');
await user.type(document.querySelector('input[placeholder*="6-digit" i], input[maxlength="6"]') as HTMLInputElement || document.querySelectorAll('input[type="text"]')[0], '123456');
await user.type(resetPwdInputs[0] as HTMLInputElement, 'ResetPass1!');
await user.type(resetPwdInputs[1] as HTMLInputElement, 'ResetPass1!');
await user.click(screen.getByRole('button', { name: /Set New Password/i }));
await waitFor(() => expect(screen.getByText('Password Updated!')).toBeInTheDocument());
}, 15000);
it('handles missing billing phone during checkout, Razorpay dismiss, and verify error', async () => {
const user = userEvent.setup();
localStorage.setItem('access_token', 'mock-jwt');
setupAxiosMocks({ phone_number: '' });
let dismissMode = false;
(window as any).Razorpay = function (options: any) {
this.on = vi.fn();
this.open = () => {
if (dismissMode) {
options.modal.ondismiss();
} else {
options.handler({
razorpay_order_id: options.order_id,
razorpay_payment_id: 'pay_err',
razorpay_signature: 'bad_sig',
});
}
};
};
render(<App />);
await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument());
await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)'));
await user.click(screen.getByRole('button', { name: /Secure Payment with Razorpay/i }));
await waitFor(() => expect(screen.getByText('Billing Contact Number')).toBeInTheDocument());
const phoneInput = document.querySelector('#phone-input') as HTMLInputElement;
await user.type(phoneInput, '9876543210');
// Make verify reject so we test verify error branch too
mockedAxios.post.mockImplementation((url: string) => {
if (url.includes('/api/checkout/verify')) {
return Promise.reject({ response: { data: { detail: 'Bad sig' } } });
}
if (url.includes('/api/checkout/create-order')) {
return Promise.resolve({ data: { razorpay_order_id: 'order_123', grand_total: 300 } });
}
return Promise.resolve({ data: {} });
});
await user.click(screen.getByRole('button', { name: 'Save Phone Number' }));
await waitFor(() => expect(screen.getByText('Verification Failed')).toBeInTheDocument());
dismissMode = true;
await user.click(screen.getByRole('button', { name: /Secure Payment with Razorpay/i }));
await waitFor(() => expect(screen.getByRole('button', { name: /Secure Payment with Razorpay/i })).toBeEnabled());
});
it('handles register flow, lifetime banner, and error branches', async () => {
const user = userEvent.setup();
window.history.pushState({}, '', '/store/?logged_out=true');
const { unmount } = render(<App />);
expect(screen.getByText('Successfully Logged Out')).toBeInTheDocument();
await user.click(screen.getAllByRole('link')[0]);
expect(screen.getByText('Welcome Back!')).toBeInTheDocument();
// Switch to register mode and test registration
await user.click(screen.getByRole('button', { name: 'Create an account' }));
const textInputs = document.querySelectorAll('input[type="text"]');
await user.type(textInputs[0] as HTMLInputElement, 'Dr. Test');
await user.type(document.querySelector('input[type="email"]') as HTMLInputElement, 'new@acupedia.com');
await user.type(document.querySelector('#phone-input') as HTMLInputElement, '9876543210');
await user.type(document.querySelector('input[type="password"]') as HTMLInputElement, 'StrongPass1!');
await user.click(screen.getByRole('button', { name: 'Create Account' }));
await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument());
unmount();
// Render with LIFETIME_ALL unlocked -> shows LifetimeBanner
localStorage.setItem('access_token', 'mock-jwt');
setupAxiosMocks({
unlocked_module_codes: ['LIFETIME_ALL'],
active_subscriptions: [{ id: 1, plan_code: 'LIFETIME_ALL', status: 'ACTIVE', started_at: '2026-01-01', expires_at: '' }],
});
window.history.pushState({}, '', '/store/');
render(<App />);
await waitFor(() => expect(screen.getByText('LIFETIME ACCESS PASSPORT ACTIVE!')).toBeInTheDocument());
}, 15000);
it('handles validation errors, API failures, payment.failed, and modal close callbacks', async () => {
const user = userEvent.setup();
render(<App />);
await waitFor(() => expect(screen.getByText('Acu (EOV+Cat+Ext+MR)')).toBeInTheDocument());
// Unauthenticated Subscriptions tab -> Log In -> close AuthModal
await user.click(screen.getAllByRole('button', { name: /My Subscriptions/i })[0]);
await user.click(screen.getByRole('button', { name: 'Log In' }));
expect(screen.getByText('Welcome Back!')).toBeInTheDocument();
// Test login API failure
mockedAxios.post.mockRejectedValueOnce({ response: { data: { detail: 'Bad credentials' } } });
await user.type(document.querySelector('input[type="email"]') as HTMLInputElement, 'doc@acupedia.com');
await user.type(document.querySelector('input[type="password"]') as HTMLInputElement, 'Wrong1!');
await user.click(screen.getByRole('button', { name: /Sign In/i }));
await waitFor(() => expect(screen.getByText('Bad credentials')).toBeInTheDocument());
// Close AuthModal
const closeBtn = document.querySelector('button svg.lucide-x-circle')?.closest('button') as HTMLButtonElement;
await user.click(closeBtn);
expect(screen.queryByText('Welcome Back!')).not.toBeInTheDocument();
// Switch back to Storefront and test Razorpay payment.failed + Return to Storefront close
await user.click(screen.getAllByRole('button', { name: /Storefront/i })[0]);
localStorage.setItem('access_token', 'mock-jwt');
setupAxiosMocks();
window.history.pushState({}, '', '/store/?token=mock-jwt');
const { unmount } = render(<App />);
await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument());
let failCb: any;
(window as any).Razorpay = function (options: any) {
this.on = (ev: string, cb: any) => {
if (ev === 'payment.failed') failCb = cb;
};
this.open = () => {
if (failCb) failCb({ error: { description: 'Card declined' } });
options.handler({
razorpay_order_id: options.order_id,
razorpay_payment_id: 'pay_ok',
razorpay_signature: 'sig_ok',
});
};
};
await user.click(screen.getAllByText('Acu (EOV+Cat+Ext+MR)')[1]);
await user.click(screen.getAllByRole('button', { name: /Secure Payment with Razorpay/i })[0]);
await waitFor(() => expect(screen.getByText('Thank You for Your Purchase!')).toBeInTheDocument());
expect(window.alert).toHaveBeenCalledWith(expect.stringContaining('Card declined'));
await user.click(screen.getByRole('button', { name: 'Return to Storefront' }));
await waitFor(() => expect(screen.queryByText('Thank You for Your Purchase!')).not.toBeInTheDocument());
unmount();
}, 15000);
it('handles register/reset/change-password validation errors, CartDrawer Add Number, and ProfileDrawer navigation', async () => {
const user = userEvent.setup();
localStorage.setItem('access_token', 'mock-jwt');
setupAxiosMocks({ phone_number: '' });
window.history.pushState({}, '', '/store/');
render(<App />);
await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument());
// Add item, remove item via CartDrawer trash button, re-add, click Add Number
await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)'));
await user.click(screen.getByTitle('Remove item'));
expect(screen.getByText('0 Items')).toBeInTheDocument();
await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)'));
await user.click(screen.getByRole('button', { name: 'Add Number' }));
expect(screen.getByText('Billing Contact Number')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Cancel' }));
expect(screen.queryByText('Billing Contact Number')).not.toBeInTheDocument();
// Open ProfileDrawer -> test change password mismatch validation -> View Subscriptions -> close
await user.click(screen.getByText('Dr. Lin'));
await user.click(screen.getByRole('button', { name: /Change Password/i }));
const pwdInputs = document.querySelectorAll('input[type="password"]');
await user.type(pwdInputs[0] as HTMLInputElement, 'OldPass1!');
await user.type(pwdInputs[1] as HTMLInputElement, 'NewPass1!');
await user.type(pwdInputs[2] as HTMLInputElement, 'Mismatch1!');
await user.click(screen.getByRole('button', { name: /Update Password/i }));
await waitFor(() => expect(screen.getByText(/do not match/i)).toBeInTheDocument());
// Close ProfileDrawer
const closeDrawerBtn = document.querySelector('button svg.lucide-x-circle')?.closest('button') as HTMLButtonElement;
if (closeDrawerBtn) await user.click(closeDrawerBtn);
}, 15000);
it('hides plans absent from /api/plans (POINTS_TUNG) or unpriced in billing currency (THERAPEUTICS_CORE) and prunes them from cart', async () => {
window.history.pushState({}, '', '/store/?planCode=POINTS_TUNG');
render(<App />);
// Wait for /api/plans to load and prune POINTS_TUNG from deep-linked cart & hide both unavailable plans
await waitFor(() => {
expect(screen.getByText('Acu (EOV+Cat+Ext+MR)')).toBeInTheDocument();
expect(screen.getByText('0 Items')).toBeInTheDocument();
});
expect(screen.queryByText('Master Tung')).not.toBeInTheDocument();
expect(screen.queryByText('₹0')).not.toBeInTheDocument();
});
it('keeps storefront visible and clears stale token silently when initial profile fetch fails', async () => {
localStorage.setItem('access_token', 'stale-expired-jwt');
window.history.pushState({}, '', '/store/');
mockedAxios.get.mockImplementation((url: string) => {
if (url.includes('/api/auth/profile')) {
return Promise.reject({ response: { status: 401, data: { detail: 'Token expired' } } });
}
if (url.includes('/api/checkout/config')) return Promise.resolve({ data: { razorpay_key_id: 'rzp_test_123' } });
if (url.includes('/api/plans')) return Promise.resolve({ data: mockPlansResponse });
if (url.includes('/api/modules/categories')) return Promise.resolve({ data: [] });
return Promise.resolve({ data: {} });
});
render(<App />);
await waitFor(() => {
expect(screen.getByText('Unlock Professional TCM Modules')).toBeInTheDocument();
expect(localStorage.getItem('access_token')).toBeNull();
});
expect(screen.queryByText('Successfully Logged Out')).not.toBeInTheDocument();
expect(window.location.pathname).toBe('/store/');
});
});

144
tests/unit/catalog.test.ts Normal file
View File

@ -0,0 +1,144 @@
import { describe, it, expect } from 'vitest';
import { buildDynamicCatalog, resolvePlanCategory } from '../../src/utils/catalog';
import { CURRICULUM_MODULES } from '../../src/constants/modules';
import type { PublicPlan } from '../../src/types';
describe('buildDynamicCatalog', () => {
it('falls back to CURRICULUM_MODULES when publicPlans is empty', () => {
const result = buildDynamicCatalog([]);
expect(result).toEqual(CURRICULUM_MODULES);
});
it('maps newly created Module Builder one_time plan to its normalized category with sortOrder', () => {
const plans: PublicPlan[] = [
{
code: 'MOD_M0044',
base_code: 'MOD_M0044',
name: 'Pediatric Disorders',
description: 'TCM pediatric treatment protocols.',
plan_type: 'one_time',
price_inr: 600,
price_usd: 15,
price_eur: 15,
is_active: true,
modules: [
{
id: 'mod-44',
code: 'm0044',
slug: 'pediatric-disorders',
name: 'Pediatric Disorders',
description: 'TCM pediatric treatment protocols.',
category: 'Therapeutics',
sort_order: 40,
},
],
},
];
const result = buildDynamicCatalog(plans);
expect(result).toHaveLength(1);
expect(result[0]).toMatchObject({
code: 'MOD_M0044',
name: 'Pediatric Disorders',
category: 'Therapeutics',
priceInr: 600,
priceUsd: 15,
priceEur: 15,
sortOrder: 40,
});
});
it('expands PATTERN_CORE sub-modules from plan.modules and appends Complete Pack', () => {
const plans: PublicPlan[] = [
{
code: 'PATTERN_CORE',
name: 'Pattern: Complete Pack',
description: 'All pattern methodologies.',
plan_type: 'bundle',
price_inr: 500,
price_usd: 10,
price_eur: 10,
is_active: true,
modules: [
{ name: 'Zang-Fu Organs', slug: 'zang-fu', category: 'Pattern', sort_order: 2 },
{ name: 'Eight Principles', slug: 'eight-principles', category: 'Pattern', sort_order: 1 },
],
},
];
const result = buildDynamicCatalog(plans);
expect(result.map((m) => m.name)).toEqual([
'Eight Principles',
'Zang-Fu Organs',
'Pattern: Complete Pack',
]);
expect(result[2].sortOrder).toBe(Number.MAX_SAFE_INTEGER);
});
it('omits Complete Pack row for NUTRITION_CORE when only 1 module exists and keeps POINTS_PACK last', () => {
const plans: PublicPlan[] = [
{
code: 'NUTRITION_CORE',
name: 'Nutrition Module Access (1 Yr)',
plan_type: 'one_time',
price_inr: 600,
price_usd: 15,
price_eur: 15,
is_active: true,
modules: [{ code: 'm0031', name: 'Nutrition', slug: 'nutrition', category: 'Nutrition', sort_order: 99999 }],
},
{
code: 'POINTS_PACK',
name: 'Points Complete Pack (1 Yr)',
plan_type: 'bundle',
price_inr: 900,
price_usd: 15,
price_eur: 15,
is_active: true,
},
{
code: 'POINTS_ACU',
name: 'Acu Points Module (1 Yr)',
plan_type: 'one_time',
price_inr: 300,
price_usd: 5,
price_eur: 5,
is_active: true,
modules: [{ code: 'm0001', name: 'Acupuncture Points', slug: 'acupuncture-points', category: 'Points', sort_order: 99999 }],
},
];
const result = buildDynamicCatalog(plans);
const nutritionItems = result.filter((m) => m.category === 'Nutrition');
expect(nutritionItems).toHaveLength(1);
expect(nutritionItems[0].name).toBe('Nutrition');
const pointsItems = result
.filter((m) => m.category === 'Points')
.sort((a, b) => (a.sortOrder ?? 500) - (b.sortOrder ?? 500));
expect(pointsItems.map((m) => m.code)).toEqual(['POINTS_ACU', 'POINTS_PACK']);
});
it('resolves non-standard category or custom bundle cleanly', () => {
const unknownCatPlan: PublicPlan = {
code: 'MOD_HERB',
name: 'Herbal Formulas',
plan_type: 'one_time',
is_active: true,
modules: [{ name: 'Herbal Formulas', category: 'Herbalism', sort_order: 50 }],
};
expect(resolvePlanCategory(unknownCatPlan)).toBe('Herbalism');
const bundlePlan: PublicPlan = {
code: 'STARTER_BUNDLE',
name: 'Starter Bundle',
plan_type: 'bundle',
price_inr: 1200,
price_usd: 25,
price_eur: 25,
is_active: true,
};
const result = buildDynamicCatalog([bundlePlan]);
expect(result[0].category).toBe('Bundle');
});
});

View File

@ -0,0 +1,143 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { AuthModal } from '../../../src/components/auth/AuthModal';
const makeProps = (overrides: Record<string, any> = {}) => ({
isOpen: true,
onClose: vi.fn(),
authMode: 'login' as const,
setAuthMode: vi.fn(),
authEmail: 'doc@acupedia.com',
setAuthEmail: vi.fn(),
authPassword: 'Password1!',
setAuthPassword: vi.fn(),
authDisplayName: 'Dr. Lin',
setAuthDisplayName: vi.fn(),
authPhone: '9876543210',
setAuthPhone: vi.fn(),
authDialCode: '+91',
setAuthDialCode: vi.fn(),
authCountry: 'India',
setAuthCountry: vi.fn(),
authLoading: false,
authError: null,
setAuthError: vi.fn(),
onAuthSubmit: vi.fn((e) => e.preventDefault()),
resetStep: 'request' as const,
setResetStep: vi.fn(),
resetOtp: '',
setResetOtp: vi.fn(),
resetNewPassword: '',
setResetNewPassword: vi.fn(),
resetConfirmPassword: '',
setResetConfirmPassword: vi.fn(),
resetSuccessMessage: null,
setResetSuccessMessage: vi.fn(),
onForgotPasswordRequest: vi.fn((e) => e.preventDefault()),
onResetPasswordSubmit: vi.fn((e) => e.preventDefault()),
...overrides,
});
describe('AuthModal', () => {
it('returns null when closed', () => {
const { container } = render(<AuthModal {...makeProps({ isOpen: false })} />);
expect(container.firstChild).toBeNull();
});
it('renders login mode, error alert, password toggle, and mode switches', async () => {
const user = userEvent.setup();
const props = makeProps({ authError: 'Invalid credentials' });
const { container } = render(<AuthModal {...props} />);
expect(screen.getByText('Welcome Back!')).toBeInTheDocument();
expect(screen.getByText('Invalid credentials')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: /Forgot password/i }));
expect(props.setAuthMode).toHaveBeenCalledWith('forgot');
await user.click(screen.getByRole('button', { name: 'Create an account' }));
expect(props.setAuthMode).toHaveBeenCalledWith('register');
await user.click(screen.getByRole('button', { name: /Sign In/i }));
expect(props.onAuthSubmit).toHaveBeenCalled();
// Test email & password inputs & password visibility toggle
const emailInput = container.querySelector('input[type="email"]') as HTMLInputElement;
await user.type(emailInput, 'x');
expect(props.setAuthEmail).toHaveBeenCalled();
const pwdInput = screen.getByPlaceholderText('••••••••');
await user.type(pwdInput, 'y');
expect(props.setAuthPassword).toHaveBeenCalled();
});
it('renders register mode with phone/country fields and submits', async () => {
const user = userEvent.setup();
const props = makeProps({ authMode: 'register', authPhone: '' });
const { container } = render(<AuthModal {...props} />);
expect(screen.getByRole('heading', { name: 'Create Account' })).toBeInTheDocument();
const textInputs = container.querySelectorAll('input[type="text"]');
await user.type(textInputs[0] as HTMLInputElement, 'A');
expect(props.setAuthDisplayName).toHaveBeenCalled();
const phoneInput = container.querySelector('#phone-input') as HTMLInputElement;
await user.type(phoneInput, '1');
expect(props.setAuthPhone).toHaveBeenCalled();
// Toggle password visibility & change country
const eyeBtns = container.querySelectorAll('button[type="button"]');
for (const b of eyeBtns) {
if (b.querySelector('svg.lucide-eye, svg.lucide-eye-off')) {
await user.click(b);
break;
}
}
await user.click(screen.getByRole('button', { name: /India/i }));
await user.click(screen.getByText('United States'));
expect(props.setAuthCountry).toHaveBeenCalledWith('United States');
await user.click(screen.getByRole('button', { name: 'Create Account' }));
expect(props.onAuthSubmit).toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: 'Sign in here' }));
expect(props.setAuthMode).toHaveBeenCalledWith('login');
});
it('renders forgot password request and verify steps', async () => {
const user = userEvent.setup();
const propsReq = makeProps({ authMode: 'forgot', resetStep: 'request' });
const { rerender, container } = render(<AuthModal {...propsReq} />);
expect(screen.getByText('Reset Password')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: /Send Verification Code/i }));
expect(propsReq.onForgotPasswordRequest).toHaveBeenCalled();
const propsVerify = makeProps({
authMode: 'forgot',
resetStep: 'verify',
resetOtp: '',
resetNewPassword: 'NewPassword1!',
resetConfirmPassword: 'NewPassword1!',
resetSuccessMessage: 'OTP sent!',
});
rerender(<AuthModal {...propsVerify} />);
expect(screen.getByText('OTP sent!')).toBeInTheDocument();
const otpInput = container.querySelector('input[type="text"]') as HTMLInputElement;
await user.type(otpInput, '9');
expect(propsVerify.setResetOtp).toHaveBeenCalled();
const pwdInputs = container.querySelectorAll('input[type="password"]');
await user.type(pwdInputs[0] as HTMLInputElement, 'x');
await user.type(pwdInputs[1] as HTMLInputElement, 'y');
expect(propsVerify.setResetNewPassword).toHaveBeenCalled();
expect(propsVerify.setResetConfirmPassword).toHaveBeenCalled();
rerender(<AuthModal {...makeProps({ authMode: 'forgot', resetStep: 'verify', resetOtp: '123456', resetNewPassword: 'NewPassword1!', resetConfirmPassword: 'NewPassword1!', onResetPasswordSubmit: propsVerify.onResetPasswordSubmit, setResetStep: propsVerify.setResetStep, setAuthMode: propsVerify.setAuthMode })} />);
await user.click(screen.getByRole('button', { name: /Set New Password/i }));
expect(propsVerify.onResetPasswordSubmit).toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: /Resend code/i }));
expect(propsVerify.setResetStep).toHaveBeenCalledWith('request');
await user.click(screen.getByRole('button', { name: /Back to sign in/i }));
expect(propsVerify.setAuthMode).toHaveBeenCalledWith('login');
});
});

View File

@ -0,0 +1,71 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { BillingPhoneModal } from '../../../src/components/checkout/BillingPhoneModal';
describe('BillingPhoneModal', () => {
it('returns null when closed', () => {
const { container } = render(
<BillingPhoneModal isOpen={false} onClose={vi.fn()} onSavePhone={vi.fn()} />
);
expect(container.firstChild).toBeNull();
});
it('validates empty/invalid phone and saves valid phone', async () => {
const user = userEvent.setup();
const onClose = vi.fn();
const onSavePhone = vi.fn().mockResolvedValue(true);
render(
<BillingPhoneModal
isOpen={true}
onClose={onClose}
currentPhone=""
currentCountry="India"
onSavePhone={onSavePhone}
/>
);
// Empty submit
await user.click(screen.getByRole('button', { name: 'Save Phone Number' }));
expect(screen.getByText('Please enter your mobile number.')).toBeInTheDocument();
// Invalid short phone
const input = screen.getByPlaceholderText(/mobile number/i);
await user.type(input, '123');
await user.click(screen.getByRole('button', { name: 'Save Phone Number' }));
expect(screen.getByText(/10 digits/i)).toBeInTheDocument();
// Valid phone
await user.clear(input);
await user.type(input, '9876543210');
await user.click(screen.getByRole('button', { name: 'Save Phone Number' }));
expect(onSavePhone).toHaveBeenCalledWith('+919876543210', 'India');
expect(onClose).toHaveBeenCalledTimes(1);
});
it('handles country change, dial code change, and save failure', async () => {
const user = userEvent.setup();
const onSavePhone = vi.fn().mockRejectedValue(new Error('Server error'));
const { container } = render(
<BillingPhoneModal
isOpen={true}
onClose={vi.fn()}
currentPhone="+919876543210"
currentCountry="India"
onSavePhone={onSavePhone}
/>
);
// Change country to United States via CountrySelect
await user.click(screen.getByRole('button', { name: /India/i }));
await user.click(screen.getByText('United States'));
const input = container.querySelector('#phone-input') as HTMLInputElement;
await user.type(input, '4155552671');
await user.click(screen.getByRole('button', { name: 'Save Phone Number' }));
expect(await screen.findByText('Server error')).toBeInTheDocument();
});
});

View File

@ -0,0 +1,142 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { CartDrawer } from '../../../src/components/cart/CartDrawer';
const sampleItem = {
code: 'POINTS_PACK',
name: 'Points: Complete Pack',
category: 'Bundle',
desc: 'All points',
priceInr: 900,
priceUsd: 15,
priceEur: 15,
};
describe('CartDrawer', () => {
it('renders empty state when cart is empty', () => {
render(
<CartDrawer
cart={[]}
currency="INR"
toggleCartItem={vi.fn()}
couponCode=""
setCouponCode={vi.fn()}
appliedCoupon={null}
applyPromoCode={vi.fn()}
removePromoCode={vi.fn()}
pricingCalc={null}
loadingPricing={false}
loggedInUser={null}
onUpdateBillingPhone={vi.fn()}
verificationResult={null}
checkoutLoading={false}
handleCheckout={vi.fn()}
/>
);
expect(screen.getByText('0 Items')).toBeInTheDocument();
expect(screen.getByText(/Your checkout cart is empty/i)).toBeInTheDocument();
});
it('renders populated cart, discounts, invalid/valid coupons, billing profile, and checkout errors', async () => {
const user = userEvent.setup();
const onUpdateBillingPhone = vi.fn();
const removePromoCode = vi.fn();
const handleCheckout = vi.fn();
const { rerender } = render(
<CartDrawer
cart={[sampleItem]}
currency="INR"
toggleCartItem={vi.fn()}
couponCode="SAVE20"
setCouponCode={vi.fn()}
appliedCoupon="SAVE20"
applyPromoCode={vi.fn()}
removePromoCode={removePromoCode}
pricingCalc={{
currency: 'INR',
base_subtotal: 900,
renewal_discount_amount: 100,
bundle_discount_amount: 50,
coupon_discount_amount: 180,
total_discounts: 330,
convenience_fee_rate: 2,
convenience_fee: 10,
taxable_amount: 570,
gst_amount: 0,
grand_total: 580,
discount_policy: 'Staggered Buy: 10%',
coupon_applied: 'Code: SAVE20 - 20% Off',
coupon_error: null,
}}
loadingPricing={false}
loggedInUser={{
id: 1,
email: 'doc@acupedia.com',
country: 'India',
phone_number: '',
} as any}
onUpdateBillingPhone={onUpdateBillingPhone}
verificationResult={{ status: 'error', message: 'Signature mismatch' }}
checkoutLoading={false}
handleCheckout={handleCheckout}
/>
);
expect(screen.getByText('Complete Pack')).toBeInTheDocument();
expect(screen.getByText('Early Renewal Discount (20%)')).toBeInTheDocument();
expect(screen.getByText('Loyalty Discount: 10%')).toBeInTheDocument();
expect(screen.getByText('Coupon Discount (SAVE20)')).toBeInTheDocument();
expect(screen.getByText('Gateway fee (2%)')).toBeInTheDocument();
expect(screen.getByText('Required for checkout')).toBeInTheDocument();
expect(screen.getByText('Signature mismatch')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Add Number' }));
expect(onUpdateBillingPhone).toHaveBeenCalledTimes(1);
await user.click(screen.getByRole('button', { name: /Secure Payment with Razorpay/i }));
expect(handleCheckout).toHaveBeenCalledTimes(1);
// Rerender with EUR, invalid coupon, and incomplete phone
rerender(
<CartDrawer
cart={[sampleItem]}
currency="EUR"
toggleCartItem={vi.fn()}
couponCode="BAD"
setCouponCode={vi.fn()}
appliedCoupon="BAD"
applyPromoCode={vi.fn()}
removePromoCode={removePromoCode}
pricingCalc={{
currency: 'EUR',
base_subtotal: 15,
coupon_discount_amount: 0,
total_discounts: 3,
convenience_fee_rate: 0,
convenience_fee: 0,
taxable_amount: 0,
gst_amount: 0,
grand_total: 12,
coupon_applied: 'None',
coupon_error: 'Invalid coupon',
}}
loadingPricing={true}
loggedInUser={{
id: 1,
email: 'doc@acupedia.com',
country: 'Germany',
phone_number: '123',
} as any}
onUpdateBillingPhone={onUpdateBillingPhone}
verificationResult={null}
checkoutLoading={true}
handleCheckout={handleCheckout}
/>
);
expect(screen.getByText(/Invalid coupon/i)).toBeInTheDocument();
expect(screen.getByText(/Incomplete \(123\)/i)).toBeInTheDocument();
expect(screen.getByText('Total Discounts')).toBeInTheDocument();
});
});

View File

@ -0,0 +1,110 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { CatalogSection } from '../../../src/components/catalog/CatalogSection';
import { CURRICULUM_MODULES } from '../../../src/constants/modules';
describe('CatalogSection', () => {
const defaultProps = {
curriculumModules: CURRICULUM_MODULES,
publicPlans: [
{
code: 'LIFETIME_ALL',
name: 'Lifetime All-Access Plan',
description: '10 Years access',
plan_type: 'bundle' as const,
billing_period: 'lifetime' as const,
price_inr: 15000,
price_usd: 350,
price_eur: 350,
is_active: true,
module_slugs: ['acupuncture-points'],
},
{
code: 'CUSTOM_CURATED_1',
name: 'Summer Clinical Bundle',
description: 'Curated clinical pack',
plan_type: 'bundle' as const,
billing_period: 'yearly' as const,
price_inr: 2500,
price_usd: 45,
price_eur: 45,
is_active: true,
module_slugs: ['acupuncture-points', 'nutrition'],
modules: [{ slug: 'acupuncture-points', name: 'Acupuncture Points' }],
},
],
cart: [CURRICULUM_MODULES[0]],
currency: 'INR' as const,
isModuleUnlocked: (code: string) => code === 'POINTS_SCALP',
getModulePrice: (item: any) => ({
priceInr: item.priceInr,
priceUsd: item.priceUsd,
priceEur: item.priceEur,
isActive: item.code !== 'POINTS_EAR',
}),
toggleCartItem: vi.fn(),
showLockedByCategory: {
Points: true,
Pattern: true,
Nutrition: true,
Therapeutics: true,
Bundles: true,
},
setShowLockedByCategory: vi.fn(),
};
it('renders categories, custom curated bundles, unlocked badges, and handles toggles & cart clicks', async () => {
const user = userEvent.setup();
render(<CatalogSection {...defaultProps} />);
expect(screen.getByText('Points Reference Module')).toBeInTheDocument();
expect(screen.getByText('Summer Clinical Bundle')).toBeInTheDocument();
expect(screen.getAllByText('UNLOCKED').length).toBeGreaterThan(0);
// Inactive locked module POINTS_EAR is hidden
expect(screen.queryByText('Ear (EOV+Cat+Ext+MR)')).not.toBeInTheDocument();
// Click module item & custom bundle & lifetime pass
await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)'));
expect(defaultProps.toggleCartItem).toHaveBeenCalled();
await user.click(screen.getByText('Summer Clinical Bundle'));
expect(defaultProps.toggleCartItem).toHaveBeenCalledTimes(2);
// Click Complete Pack badges across categories
const completePacks = screen.getAllByText('Complete Pack');
for (const cp of completePacks) {
await user.click(cp);
}
// Toggle Hide Locked across all categories
const hideButtons = screen.getAllByRole('button', { name: /Hide Locked/i });
for (const btn of hideButtons) {
await user.click(btn);
}
expect(defaultProps.setShowLockedByCategory).toHaveBeenCalledTimes(hideButtons.length);
});
it('renders hidden locked empty states and EUR/USD pricing', async () => {
const user = userEvent.setup();
render(
<CatalogSection
{...defaultProps}
currency="EUR"
isModuleUnlocked={() => false}
showLockedByCategory={{
Points: false,
Pattern: false,
Nutrition: false,
Therapeutics: false,
Bundles: false,
}}
/>
);
expect(screen.getAllByText('Locked modules are currently hidden.').length).toBeGreaterThan(0);
await user.click(screen.getAllByRole('button', { name: /Show Locked/i })[0]);
expect(defaultProps.setShowLockedByCategory).toHaveBeenCalled();
});
});

View File

@ -0,0 +1,68 @@
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { CountrySelect } from '../../../src/components/common/CountrySelect';
describe('CountrySelect', () => {
it('opens dropdown, filters by country/dial code/currency, and selects a country', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<CountrySelect value="India" onChange={onChange} showCurrency showDialCode theme="dark" size="sm" />
);
const trigger = screen.getByRole('button');
expect(trigger).toHaveTextContent('India');
expect(trigger).toHaveTextContent('+91');
await user.click(trigger);
const searchInput = screen.getByPlaceholderText('Search country name or code...');
await user.type(searchInput, 'Germany');
expect(screen.getByText('Germany')).toBeInTheDocument();
await user.click(screen.getByText('Germany'));
expect(onChange).toHaveBeenCalledWith('Germany');
});
it('shows empty state when no country matches and closes on Escape / outside click / clear', async () => {
const user = userEvent.setup();
render(
<div>
<div data-testid="outside">Outside</div>
<CountrySelect value="India" onChange={vi.fn()} theme="light" />
</div>
);
await user.click(screen.getByRole('button'));
const searchInput = screen.getByPlaceholderText('Search country name or code...');
await user.type(searchInput, 'ZzzUnknown');
expect(screen.getByText(/No countries found matching/)).toBeInTheDocument();
// Clear search button
const buttons = screen.getAllByRole('button');
const clearBtn = buttons.find((b) => b.querySelector('svg') && b !== buttons[0]);
if (clearBtn) await user.click(clearBtn);
expect(searchInput).toHaveValue('');
// Escape closes
fireEvent.keyDown(document, { key: 'Escape' });
expect(screen.queryByPlaceholderText('Search country name or code...')).not.toBeInTheDocument();
// Reopen and click outside closes
await user.click(screen.getByRole('button'));
expect(screen.getByPlaceholderText('Search country name or code...')).toBeInTheDocument();
fireEvent.mouseDown(screen.getByTestId('outside'));
expect(screen.queryByPlaceholderText('Search country name or code...')).not.toBeInTheDocument();
});
it('does not open when disabled and supports showDialCode=false', async () => {
const user = userEvent.setup();
const { rerender } = render(<CountrySelect value="India" onChange={vi.fn()} disabled />);
await user.click(screen.getByRole('button'));
expect(screen.queryByPlaceholderText('Search country name or code...')).not.toBeInTheDocument();
rerender(<CountrySelect value="India" onChange={vi.fn()} showDialCode={false} showCurrency={false} />);
expect(screen.getByRole('button')).not.toHaveTextContent('+91');
});
});

View File

@ -0,0 +1,107 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { LoggedOutView } from '../../../src/components/auth/LoggedOutView';
import { PasswordUpdatedModal } from '../../../src/components/auth/PasswordUpdatedModal';
import { StoreFooter } from '../../../src/components/layout/StoreFooter';
import { StoreHeader } from '../../../src/components/layout/StoreHeader';
import { LifetimeBanner } from '../../../src/components/catalog/LifetimeBanner';
describe('Layout & Simple View Components', () => {
it('LoggedOutView renders /store prefix and triggers onLoginAgain on both links', async () => {
const user = userEvent.setup();
const onLoginAgain = vi.fn();
window.history.pushState({}, '', '/store/');
render(<LoggedOutView onLoginAgain={onLoginAgain} />);
expect(screen.getByText('Successfully Logged Out')).toBeInTheDocument();
const links = screen.getAllByRole('link');
expect(links[0]).toHaveAttribute('href', '/store/?login=true');
await user.click(links[0]);
await user.click(links[1]);
expect(onLoginAgain).toHaveBeenCalledTimes(2);
});
it('PasswordUpdatedModal renders when open, handles custom props and close, and returns null when closed', async () => {
const user = userEvent.setup();
const onClose = vi.fn();
const { rerender } = render(<PasswordUpdatedModal isOpen={false} onClose={onClose} />);
expect(screen.queryByText('Password Updated!')).not.toBeInTheDocument();
rerender(
<PasswordUpdatedModal
isOpen={true}
onClose={onClose}
title="Custom Title"
description="Custom Desc"
buttonText="Done"
/>
);
expect(screen.getByText('Custom Title')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Done' }));
expect(onClose).toHaveBeenCalledTimes(1);
});
it('StoreFooter and LifetimeBanner render expected branding', () => {
render(
<>
<StoreFooter />
<LifetimeBanner />
</>
);
expect(screen.getByText(/Acupedia Systems/i)).toBeInTheDocument();
expect(screen.getByText('LIFETIME ACCESS PASSPORT ACTIVE!')).toBeInTheDocument();
});
it('StoreHeader handles unauthenticated and authenticated states and navigation tabs', async () => {
const user = userEvent.setup();
const onSwitchTab = vi.fn();
const onOpenProfile = vi.fn();
const onOpenAuth = vi.fn();
const { rerender } = render(
<StoreHeader
activeTab="storefront"
onSwitchTab={onSwitchTab}
loggedInUser={null}
onOpenProfile={onOpenProfile}
onOpenAuth={onOpenAuth}
/>
);
await user.click(screen.getByRole('button', { name: /Login/i }));
await user.click(screen.getByRole('button', { name: /Join/i }));
expect(onOpenAuth).toHaveBeenNthCalledWith(1, 'login');
expect(onOpenAuth).toHaveBeenNthCalledWith(2, 'register');
await user.click(screen.getByText('ACUPEDIA'));
expect(onSwitchTab).toHaveBeenCalledWith('storefront');
const storeBtns = screen.getAllByRole('button', { name: /Storefront/i });
const subBtns = screen.getAllByRole('button', { name: /My Subscriptions/i });
await user.click(storeBtns[1]);
await user.click(subBtns[0]);
await user.click(subBtns[1]);
expect(onSwitchTab).toHaveBeenCalledWith('subscriptions');
rerender(
<StoreHeader
activeTab="subscriptions"
onSwitchTab={onSwitchTab}
loggedInUser={{
id: 1,
email: 'doc@acupedia.com',
display_name: 'Dr. Lin',
country: 'India',
active_subscriptions: [{ id: 1, plan_code: 'POINTS_ACU', status: 'ACTIVE', started_at: '', expires_at: '' }],
} as any}
onOpenProfile={onOpenProfile}
onOpenAuth={onOpenAuth}
/>
);
await user.click(screen.getByText('Dr. Lin'));
expect(onOpenProfile).toHaveBeenCalledTimes(1);
});
});

View File

@ -0,0 +1,57 @@
import { describe, expect, it, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Pagination } from '../../../src/components/common/Pagination';
describe('Pagination', () => {
it('returns null when totalItems <= 0', () => {
const { container } = render(
<Pagination currentPage={1} totalItems={0} itemsPerPage={6} onPageChange={vi.fn()} />
);
expect(container.firstChild).toBeNull();
});
it('renders pages and handles Prev, Next, page click, and itemsPerPage change', async () => {
const user = userEvent.setup();
const onPageChange = vi.fn();
const onItemsPerPageChange = vi.fn();
const { container } = render(
<Pagination
currentPage={2}
totalItems={30}
itemsPerPage={6}
onPageChange={onPageChange}
onItemsPerPageChange={onItemsPerPageChange}
/>
);
expect(container.textContent).toContain('Showing 7 to 12 of 30 items');
await user.click(screen.getByRole('button', { name: 'Prev' }));
expect(onPageChange).toHaveBeenCalledWith(1);
await user.click(screen.getByRole('button', { name: 'Next' }));
expect(onPageChange).toHaveBeenCalledWith(3);
await user.click(screen.getByRole('button', { name: '5' }));
expect(onPageChange).toHaveBeenCalledWith(5);
await user.selectOptions(screen.getByRole('combobox'), '12');
expect(onItemsPerPageChange).toHaveBeenCalledWith(12);
expect(onPageChange).toHaveBeenCalledWith(1);
});
it('renders ellipsis branches for large page counts (start, middle, end)', () => {
const { rerender } = render(
<Pagination currentPage={2} totalItems={120} itemsPerPage={10} onPageChange={vi.fn()} />
);
expect(screen.getAllByText('...')).toHaveLength(1);
rerender(<Pagination currentPage={6} totalItems={120} itemsPerPage={10} onPageChange={vi.fn()} />);
expect(screen.getAllByText('...')).toHaveLength(2);
rerender(<Pagination currentPage={11} totalItems={120} itemsPerPage={10} onPageChange={vi.fn()} />);
expect(screen.getAllByText('...')).toHaveLength(1);
});
});

View File

@ -0,0 +1,126 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { PaymentSuccessModal } from '../../../src/components/checkout/PaymentSuccessModal';
describe('PaymentSuccessModal', () => {
const baseResult = {
status: 'success' as const,
paymentId: 'pay_123',
orderId: 'order_123',
invoiceNumber: 'INV-001',
invoiceUrl: '/api/checkout/payment/pay_123/invoice/view',
amount: 900,
currency: 'INR' as const,
items: ['Points Pack'],
message: 'Unlocked!',
};
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true });
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
it('renders details, pauses auto-redirect, and triggers invoice download & close', async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
const onClose = vi.fn();
const onDownloadInvoice = vi.fn();
render(
<PaymentSuccessModal
verificationResult={baseResult}
onClose={onClose}
loggedInUser={{ email: 'doc@acupedia.com' } as any}
onDownloadInvoice={onDownloadInvoice}
downloadingInvoice={false}
/>
);
expect(screen.getByText('Thank You for Your Purchase!')).toBeInTheDocument();
expect(screen.getByText('INV-001')).toBeInTheDocument();
expect(screen.getByText('₹900')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: /Stay on Web/i }));
expect(screen.getByText(/Auto-redirect paused/i)).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: /Open App Now/i }));
expect(screen.getByText(/Attempted to launch Acupedia App/i)).toBeInTheDocument();
await user.click(screen.getByText('Download Invoice PDF'));
expect(onDownloadInvoice).toHaveBeenCalledWith('pay_123', '/api/checkout/payment/pay_123/invoice/view');
await user.click(screen.getByRole('button', { name: 'Return to Storefront' }));
expect(onClose).toHaveBeenCalledTimes(1);
});
it('auto-redirects when countdown hits 0 and formats EUR/USD currencies', () => {
const { rerender } = render(
<PaymentSuccessModal
verificationResult={{ ...baseResult, currency: 'EUR', amount: 15 }}
onClose={vi.fn()}
loggedInUser={null}
onDownloadInvoice={vi.fn()}
downloadingInvoice={true}
/>
);
expect(screen.getByText('€15')).toBeInTheDocument();
expect(screen.getByText('Downloading...')).toBeInTheDocument();
act(() => {
vi.advanceTimersByTime(10000);
});
expect(screen.getByText(/Attempted to launch Acupedia App/i)).toBeInTheDocument();
rerender(
<PaymentSuccessModal
verificationResult={{ ...baseResult, currency: 'USD', amount: 20 }}
onClose={vi.fn()}
loggedInUser={null}
onDownloadInvoice={vi.fn()}
downloadingInvoice={false}
/>
);
expect(screen.getByText('$20')).toBeInTheDocument();
});
it('handles Android and iOS user agents on launchMobileApp', async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
const originalUA = navigator.userAgent;
Object.defineProperty(navigator, 'userAgent', { value: 'Android', configurable: true });
const { rerender } = render(
<PaymentSuccessModal
verificationResult={baseResult}
onClose={vi.fn()}
loggedInUser={null}
onDownloadInvoice={vi.fn()}
downloadingInvoice={false}
/>
);
await user.click(screen.getByRole('button', { name: /Open in App \/ Library/i }));
act(() => {
vi.advanceTimersByTime(1100);
});
Object.defineProperty(navigator, 'userAgent', { value: 'iPhone', configurable: true });
rerender(
<PaymentSuccessModal
verificationResult={{ ...baseResult, currency: 'USD' }}
onClose={vi.fn()}
loggedInUser={null}
onDownloadInvoice={vi.fn()}
downloadingInvoice={false}
/>
);
await user.click(screen.getByRole('button', { name: /Open in App \/ Library/i }));
act(() => {
vi.advanceTimersByTime(1000);
});
Object.defineProperty(navigator, 'userAgent', { value: originalUA, configurable: true });
});
});

View File

@ -0,0 +1,161 @@
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { PhoneInput } from '../../../src/components/common/PhoneInput';
describe('PhoneInput', () => {
it('cleans input digits on change and displays error/helper text', async () => {
const user = userEvent.setup();
const onPhoneChange = vi.fn();
const { rerender } = render(
<PhoneInput
dialCode="+91"
phone=""
country="India"
onPhoneChange={onPhoneChange}
theme="light"
/>
);
const input = screen.getByRole('textbox');
await user.type(input, '98765');
expect(onPhoneChange).toHaveBeenCalled();
expect(input).toHaveAttribute('placeholder', '10-digit mobile number');
rerender(
<PhoneInput
dialCode="+49"
phone="151"
country="Germany"
onPhoneChange={onPhoneChange}
error="Invalid phone"
theme="dark"
/>
);
expect(screen.getByText('Invalid phone')).toBeInTheDocument();
});
it('opens dial code dropdown, searches, clears phone when clearOnDialCodeChange=true, and closes on Escape', async () => {
const user = userEvent.setup();
const onDialCodeChange = vi.fn();
const onPhoneChange = vi.fn();
render(
<div>
<div data-testid="outside">Outside</div>
<PhoneInput
dialCode="+91"
phone="9876543210"
country="India"
onDialCodeChange={onDialCodeChange}
onPhoneChange={onPhoneChange}
clearOnDialCodeChange
/>
</div>
);
const dialBtn = screen.getByRole('button');
await user.click(dialBtn);
const searchInput = screen.getByPlaceholderText('Search country or code...');
await user.type(searchInput, '49');
await user.click(screen.getByText('Germany'));
expect(onDialCodeChange).toHaveBeenCalledWith('+49', 'Germany');
expect(onPhoneChange).toHaveBeenCalledWith('');
// Reopen and test Escape + outside click
await user.click(dialBtn);
fireEvent.keyDown(document, { key: 'Escape' });
expect(screen.queryByPlaceholderText('Search country or code...')).not.toBeInTheDocument();
await user.click(dialBtn);
fireEvent.mouseDown(screen.getByTestId('outside'));
expect(screen.queryByPlaceholderText('Search country or code...')).not.toBeInTheDocument();
});
it('handles light theme, empty search, clear search button, clamping without clearing, and disabled state', async () => {
const user = userEvent.setup();
const onDialCodeChange = vi.fn();
const onPhoneChange = vi.fn();
const { rerender } = render(
<PhoneInput
dialCode="+91"
phone="9876543210"
onDialCodeChange={onDialCodeChange}
onPhoneChange={onPhoneChange}
theme="light"
/>
);
await user.click(screen.getByRole('button'));
const searchInput = screen.getByPlaceholderText('Search country or code...');
await user.type(searchInput, 'NoSuchCountry');
expect(screen.getByText(/No country codes found matching/)).toBeInTheDocument();
// Clear search button inside dropdown
const buttons = screen.getAllByRole('button');
const clearBtn = buttons.find((b) => b !== buttons[0]);
if (clearBtn) await user.click(clearBtn);
expect(searchInput).toHaveValue('');
// Select Singapore (+65, maxLength 8) -> clamps 10 digits to 8
await user.type(searchInput, 'Singapore');
await user.click(screen.getByText('Singapore'));
expect(onDialCodeChange).toHaveBeenCalledWith('+65', 'Singapore');
expect(onPhoneChange).toHaveBeenCalledWith('98765432');
// Disabled state does not open dropdown
rerender(
<PhoneInput
dialCode="+91"
phone=""
onPhoneChange={onPhoneChange}
disabled
/>
);
await user.click(screen.getByRole('button'));
expect(screen.queryByPlaceholderText('Search country or code...')).not.toBeInTheDocument();
});
it('handles international paste (+91 / 91 prefix) and keydown filtering', () => {
const onDialCodeChange = vi.fn();
const onPhoneChange = vi.fn();
render(
<PhoneInput
dialCode="+91"
phone=""
country="India"
onDialCodeChange={onDialCodeChange}
onPhoneChange={onPhoneChange}
/>
);
const input = screen.getByRole('textbox');
// Pasting full international number starting with +
fireEvent.change(input, { target: { value: '+447123456789' } });
expect(onDialCodeChange).toHaveBeenCalledWith('+44', 'United Kingdom');
expect(onPhoneChange).toHaveBeenCalledWith('7123456789');
// Pasting number starting with dial code digits without '+'
fireEvent.change(input, { target: { value: '919876543210' } });
expect(onPhoneChange).toHaveBeenCalledWith('9876543210');
// Keydown: allows Backspace, Ctrl+V, '+' at position 0, and blocks letters
const allowBackspace = fireEvent.keyDown(input, { key: 'Backspace' });
expect(allowBackspace).toBe(true);
const allowCtrl = fireEvent.keyDown(input, { key: 'v', ctrlKey: true });
expect(allowCtrl).toBe(true);
const allowPlus = fireEvent.keyDown(input, { key: '+' });
expect(allowPlus).toBe(true);
const blockAlpha = fireEvent.keyDown(input, { key: 'a' });
expect(blockAlpha).toBe(false);
});
});

View File

@ -0,0 +1,129 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ProfileDrawer } from '../../../src/components/auth/ProfileDrawer';
const makeProps = (overrides: Record<string, any> = {}) => ({
isOpen: true,
onClose: vi.fn(),
loggedInUser: {
id: 1,
email: 'doc@acupedia.com',
display_name: 'Dr. Lin',
phone_number: '+919876543210',
country: 'India',
active_subscriptions: [
{ id: 1, plan_code: 'POINTS_ACU', status: 'ACTIVE', started_at: '2026-01-01', expires_at: '2027-01-01', payment_id: 'pay_1', invoice_number: 'INV-1' },
],
} as any,
profileDisplayName: 'Dr. Lin',
setProfileDisplayName: vi.fn(),
profilePhone: '+919876543210',
setProfilePhone: vi.fn(),
profileCountry: 'India',
setProfileCountry: vi.fn(),
setCurrency: vi.fn(),
profileSaving: false,
profileError: null,
profileSuccess: false,
onUpdateProfile: vi.fn((e) => e.preventDefault()),
showPasswordChange: false,
setShowPasswordChange: vi.fn(),
changeOldPassword: '',
setChangeOldPassword: vi.fn(),
changeNewPassword: '',
setChangeNewPassword: vi.fn(),
changeConfirmPassword: '',
setChangeConfirmPassword: vi.fn(),
changePasswordLoading: false,
changePasswordError: null,
setChangePasswordError: vi.fn(),
changePasswordSuccess: false,
setChangePasswordSuccess: vi.fn(),
onChangePassword: vi.fn((e) => e.preventDefault()),
onLogout: vi.fn(),
onBrowseStorefront: vi.fn(),
onViewSubscriptions: vi.fn(),
curriculumModules: [
{ code: 'POINTS_ACU', name: 'Acu Points', category: 'Points', desc: 'Desc', priceInr: 300, priceUsd: 5, priceEur: 5 },
],
onDownloadInvoice: vi.fn(),
...overrides,
});
describe('ProfileDrawer', () => {
it('returns null when closed', () => {
const { container } = render(<ProfileDrawer {...makeProps({ isOpen: false })} />);
expect(container.firstChild).toBeNull();
});
it('renders profile form, success/error banners, invoice download, and logout', async () => {
const user = userEvent.setup();
const props = makeProps({ profileSuccess: true, profileError: 'Save error' });
const { container } = render(<ProfileDrawer {...props} />);
expect(screen.getByText('Save error')).toBeInTheDocument();
expect(screen.getByText(/Changes saved successfully/i)).toBeInTheDocument();
const nameInput = container.querySelector('input[type="text"]') as HTMLInputElement;
await user.type(nameInput, 'X');
expect(props.setProfileDisplayName).toHaveBeenCalled();
// Change country & phone inside ProfileDrawer
await user.click(screen.getByRole('button', { name: /India/i }));
await user.click(screen.getByText('United States'));
expect(props.setProfileCountry).toHaveBeenCalledWith('United States');
expect(props.setCurrency).toHaveBeenCalledWith('USD');
const phoneInput = container.querySelector('#phone-input') as HTMLInputElement;
await user.type(phoneInput, '5');
expect(props.setProfilePhone).toHaveBeenCalled();
// Download invoice from ProfileDrawer
await user.click(screen.getByRole('button', { name: /Invoice/i }));
expect(props.onDownloadInvoice).toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: /Save Profile Details/i }));
expect(props.onUpdateProfile).toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: /Change Password/i }));
expect(props.setShowPasswordChange).toHaveBeenCalledWith(true);
await user.click(screen.getByRole('button', { name: /Log Out Session/i }));
expect(props.onLogout).toHaveBeenCalledTimes(1);
});
it('renders change password form when expanded and submits', async () => {
const user = userEvent.setup();
const props = makeProps({
showPasswordChange: true,
changeOldPassword: 'OldPassword1!',
changeNewPassword: 'NewPassword1!',
changeConfirmPassword: 'NewPassword1!',
changePasswordError: 'Weak password',
});
const { container } = render(<ProfileDrawer {...props} />);
expect(screen.getByText('Weak password')).toBeInTheDocument();
const pwdInputs = container.querySelectorAll('input[type="password"]');
await user.type(pwdInputs[0] as HTMLInputElement, '1');
await user.type(pwdInputs[1] as HTMLInputElement, '2');
await user.type(pwdInputs[2] as HTMLInputElement, '3');
expect(props.setChangeOldPassword).toHaveBeenCalled();
expect(props.setChangeNewPassword).toHaveBeenCalled();
expect(props.setChangeConfirmPassword).toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: /Update Password/i }));
expect(props.onChangePassword).toHaveBeenCalled();
// Toggle password visibility icons & hide form
const eyeBtns = Array.from(container.querySelectorAll('button[type="button"]')).filter((b) =>
b.querySelector('svg.lucide-eye, svg.lucide-eye-off')
);
for (const btn of eyeBtns) {
await user.click(btn);
}
await user.click(screen.getByRole('button', { name: /Hide Form/i }));
expect(props.setShowPasswordChange).toHaveBeenCalledWith(false);
});
});

View File

@ -0,0 +1,75 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SubscriptionsView } from '../../../src/components/subscriptions/SubscriptionsView';
describe('SubscriptionsView', () => {
it('renders unauthenticated prompt and opens auth modal on click', async () => {
const user = userEvent.setup();
const onOpenAuth = vi.fn();
render(
<SubscriptionsView
loggedInUser={null}
onOpenAuth={onOpenAuth}
onSwitchTab={vi.fn()}
curriculumModules={[]}
/>
);
await user.click(screen.getByRole('button', { name: 'Log In' }));
expect(onOpenAuth).toHaveBeenCalledTimes(1);
});
it('renders empty state and navigates to catalog', async () => {
const user = userEvent.setup();
const onSwitchTab = vi.fn();
render(
<SubscriptionsView
loggedInUser={{ active_subscriptions: [] } as any}
onOpenAuth={vi.fn()}
onSwitchTab={onSwitchTab}
curriculumModules={[]}
/>
);
await user.click(screen.getByRole('button', { name: 'Explore Modules Catalog' }));
expect(onSwitchTab).toHaveBeenCalledWith('storefront');
});
it('renders active, lifetime, expired, and paginated subscriptions with invoice download', async () => {
const user = userEvent.setup();
const onDownloadInvoice = vi.fn();
const future = new Date(Date.now() + 30 * 86400000).toISOString();
const past = new Date(Date.now() - 5 * 86400000).toISOString();
const subs = [
{ id: 1, plan_code: 'LIFETIME_ALL', status: 'ACTIVE', started_at: '2026-01-01', expires_at: '', payment_id: 'p1', invoice_number: 'INV-1' },
{ id: 2, plan_code: 'POINTS_ACU', status: 'ACTIVE', started_at: '2026-01-01', expires_at: past, payment_id: 'p2' },
...Array.from({ length: 5 }, (_, i) => ({
id: i + 3,
plan_code: `MOD_${i}`,
status: 'ACTIVE',
started_at: '2026-01-01',
expires_at: future,
})),
];
render(
<SubscriptionsView
loggedInUser={{ active_subscriptions: subs } as any}
onOpenAuth={vi.fn()}
onSwitchTab={vi.fn()}
curriculumModules={[
{ code: 'POINTS_ACU', name: 'Acu Points', category: 'Points', desc: 'Acu desc', priceInr: 300, priceUsd: 5, priceEur: 5 },
]}
onDownloadInvoice={onDownloadInvoice}
/>
);
expect(screen.getByText('Lifetime Access')).toBeInTheDocument();
expect(screen.getByText('Expired')).toBeInTheDocument();
await user.click(screen.getAllByRole('button', { name: /Download Invoice/i })[0]);
expect(onDownloadInvoice).toHaveBeenCalledWith('p1', undefined);
await user.click(screen.getByRole('button', { name: '2' }));
expect(screen.getByText('MOD 4')).toBeInTheDocument();
});
});

View File

@ -0,0 +1,52 @@
import { describe, expect, it } from 'vitest';
import {
COUNTRY_CODES,
DEFAULT_COUNTRY,
SORTED_COUNTRY_CODES,
getCountryRuleByDialCode,
getCountryRuleByIso,
getCountryRuleByName,
} from '../../../src/constants/countries';
describe('countries constants & helpers', () => {
it('exports sorted country codes and India as default', () => {
expect(DEFAULT_COUNTRY.country).toBe('India');
expect(DEFAULT_COUNTRY.code).toBe('+91');
expect(SORTED_COUNTRY_CODES.length).toBe(COUNTRY_CODES.length);
});
it('resolves country rule by ISO2 code with default fallback', () => {
expect(getCountryRuleByIso(null)).toEqual(DEFAULT_COUNTRY);
expect(getCountryRuleByIso(' de ')).toMatchObject({ country: 'Germany', code: '+49' });
expect(getCountryRuleByIso('ZZ')).toEqual(DEFAULT_COUNTRY);
});
it('resolves country rule by name, ISO, partial match, or custom fallback', () => {
expect(getCountryRuleByName('')).toEqual(DEFAULT_COUNTRY);
expect(getCountryRuleByName('Germany')).toMatchObject({ iso2: 'DE', code: '+49' });
expect(getCountryRuleByName('gb')).toMatchObject({ country: 'United Kingdom' });
expect(getCountryRuleByName('Republic of Singapore')).toMatchObject({ country: 'Singapore' });
const unknown = getCountryRuleByName('Atlantis');
expect(unknown).toMatchObject({
country: 'Atlantis',
currency: 'USD',
minLength: 7,
maxLength: 15,
});
});
it('resolves country rule by dial code with country hint and fallback', () => {
expect(getCountryRuleByDialCode(null)).toEqual(DEFAULT_COUNTRY);
expect(getCountryRuleByDialCode('+1', 'Canada')).toMatchObject({ country: 'Canada', iso2: 'CA' });
expect(getCountryRuleByDialCode('+44')).toMatchObject({ country: 'United Kingdom' });
expect(getCountryRuleByDialCode('+999', 'CustomLand')).toMatchObject({
code: '+999',
country: 'CustomLand',
});
expect(getCountryRuleByDialCode('+999')).toMatchObject({
code: '+999',
country: 'Other',
});
});
});

View File

@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest';
import { CURRICULUM_MODULES } from '../../../src/constants/modules';
describe('CURRICULUM_MODULES', () => {
it('contains all core categories, complete packs, and lifetime pass with valid prices', () => {
expect(CURRICULUM_MODULES.length).toBeGreaterThanOrEqual(15);
const categories = new Set(CURRICULUM_MODULES.map((m) => m.category));
expect(categories).toEqual(new Set(['Points', 'Pattern', 'Nutrition', 'Therapeutics', 'Lifetime']));
for (const mod of CURRICULUM_MODULES) {
expect(mod.code).toBeTruthy();
expect(mod.name).toBeTruthy();
expect(mod.priceInr).toBeGreaterThan(0);
expect(mod.priceUsd).toBeGreaterThan(0);
expect(mod.priceEur).toBeGreaterThan(0);
}
});
});

View File

@ -0,0 +1,46 @@
import { afterEach, describe, expect, it } from 'vitest';
import { api, API_BASE } from '../../../src/services/api';
import { loadRazorpayScript } from '../../../src/services/razorpay';
describe('services', () => {
afterEach(() => {
delete (window as any).Razorpay;
document.body.innerHTML = '';
});
describe('api service', () => {
it('configures axios instance and attaches Bearer token from localStorage', async () => {
expect(typeof API_BASE).toBe('string');
localStorage.setItem('access_token', 'jwt-123');
const handlers = (api.interceptors.request as any).handlers;
const fulfilled = handlers[0].fulfilled;
const cfg = await fulfilled({ headers: {} });
expect(cfg.headers.Authorization).toBe('Bearer jwt-123');
localStorage.removeItem('access_token');
const cfgNoToken = await fulfilled({ headers: {} });
expect(cfgNoToken.headers.Authorization).toBeUndefined();
});
});
describe('razorpay service', () => {
it('resolves true immediately if window.Razorpay already exists', async () => {
(window as any).Razorpay = function () {};
await expect(loadRazorpayScript()).resolves.toBe(true);
});
it('appends script and resolves true on load and false on error', async () => {
const p1 = loadRazorpayScript();
const script1 = document.body.querySelector('script')!;
expect(script1.src).toContain('checkout.razorpay.com/v1/checkout.js');
script1.onload?.(new Event('load'));
await expect(p1).resolves.toBe(true);
document.body.innerHTML = '';
const p2 = loadRazorpayScript();
const script2 = document.body.querySelector('script')!;
script2.onerror?.(new Event('error'));
await expect(p2).resolves.toBe(false);
});
});
});

7
tests/unit/setup.ts Normal file
View File

@ -0,0 +1,7 @@
import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterEach } from 'vitest';
afterEach(() => {
cleanup();
});

View File

@ -0,0 +1,49 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
DEFAULT_APP_SCHEMES,
DEFAULT_RETURN_ROUTE,
formatDeepLinkRoute,
getAppDeepLinkUrls,
openMobileApp,
} from '../../../src/utils/navigation';
describe('navigation utils', () => {
const originalLocation = window.location;
beforeEach(() => {
vi.useFakeTimers();
Object.defineProperty(window, 'location', {
configurable: true,
value: { href: 'http://localhost:3000/store/' },
});
});
afterEach(() => {
vi.useRealTimers();
Object.defineProperty(window, 'location', {
configurable: true,
value: originalLocation,
});
});
it('formats deep link routes cleanly', () => {
expect(formatDeepLinkRoute()).toBe(DEFAULT_RETURN_ROUTE);
expect(formatDeepLinkRoute('///')).toBe(DEFAULT_RETURN_ROUTE);
expect(formatDeepLinkRoute('/subscriptions/')).toBe('subscriptions/');
});
it('generates deep link URLs for default and custom schemes', () => {
expect(getAppDeepLinkUrls()).toEqual(DEFAULT_APP_SCHEMES.map((s) => `${s}://${DEFAULT_RETURN_ROUTE}`));
expect(getAppDeepLinkUrls({ route: '/profile', schemes: ['customapp'] })).toEqual([
'customapp://profile',
]);
});
it('opens mobile app primary URL and schedules fallback URLs', () => {
openMobileApp({ route: '/modules', schemes: ['acupedia', 'myapp'], delayBetweenFallbacks: 300 });
expect(window.location.href).toBe('acupedia://modules');
vi.advanceTimersByTime(300);
expect(window.location.href).toBe('myapp://modules');
});
});

View File

@ -0,0 +1,164 @@
import { describe, expect, it } from 'vitest';
import {
EMAIL_REGEX,
SPECIAL_CHAR_REGEX,
cleanPhoneInput,
formatE164Phone,
formatPrefixList,
isValidEmail,
isValidPhoneNumber,
parsePhoneNumber,
updatePhoneDialCode,
validateEmail,
validatePassword,
validatePhoneNumber,
} from '../../../src/utils/validation';
describe('validation utils', () => {
describe('formatPrefixList', () => {
it('handles empty, single, two, and multiple prefixes', () => {
expect(formatPrefixList([])).toBe('');
expect(formatPrefixList(['3'])).toBe('3');
expect(formatPrefixList(['6', '7'])).toBe('6 or 7');
expect(formatPrefixList(['6', '7', '8', '9'])).toBe('6, 7, 8, or 9');
});
});
describe('cleanPhoneInput', () => {
it('strips non-numeric chars, respects allowPlus and maxLength', () => {
expect(cleanPhoneInput(' +91 987-654-3210 ', 12, true)).toBe('+919876543210');
expect(cleanPhoneInput('+91 9876543210', 10, false)).toBe('9198765432');
expect(cleanPhoneInput('abc12345def', 0, true)).toBe('12345');
});
});
describe('validatePhoneNumber & isValidPhoneNumber', () => {
it('returns null for empty/whitespace values', () => {
expect(validatePhoneNumber('')).toBeNull();
expect(validatePhoneNumber(' ')).toBeNull();
expect(validatePhoneNumber(null)).toBeNull();
expect(isValidPhoneNumber(undefined)).toBe(true);
});
it('rejects alphabetic characters, hyphens, and non-digit symbols', () => {
expect(validatePhoneNumber('98765abc10', '+91', 'India')).toContain('alphabetic');
expect(validatePhoneNumber('789--98--809', '+91', 'India')).toContain('hyphens');
expect(validatePhoneNumber('98765@3210', '+91', 'India')).toContain('only numeric digits');
expect(validatePhoneNumber('+ ', '+91', 'India')).toContain('numeric digits');
});
it('enforces exact and variable length rules', () => {
expect(validatePhoneNumber('98765', '+91', 'India')).toContain('exactly 10 digits');
expect(validatePhoneNumber('12345', '+49', 'Germany')).toContain('too short');
expect(validatePhoneNumber('1512345678901234', '+49', 'Germany')).toContain('cannot exceed');
});
it('enforces valid mobile prefixes and rejects landlines', () => {
expect(validatePhoneNumber('5123456789', '+91', 'India')).toContain('must start with');
// Valid Indian mobile
expect(validatePhoneNumber('9876543210', '+91', 'India')).toBeNull();
expect(isValidPhoneNumber('+919876543210', '+91', 'India')).toBe(true);
// Trunk 0 stripping for UK
expect(validatePhoneNumber('07123456789', '+44', 'United Kingdom')).toBeNull();
// Dial code prefix without '+' when longer than maxLength
expect(validatePhoneNumber('919876543210', '+91', 'India')).toBeNull();
// Fallback when country is not provided -> resolves by dialCode
expect(validatePhoneNumber('9876543210', '+91')).toBeNull();
// Fallback when neither country nor dialCode provided -> DEFAULT_COUNTRY
expect(validatePhoneNumber('9876543210')).toBeNull();
// Fixed line rejection (e.g. US/UK or invalid mobile)
expect(validatePhoneNumber('15123456789', '+49', 'Germany')).toBeNull();
expect(validatePhoneNumber('2025550173', '+1', 'United States')).toBeNull(); // US numbers are FIXED_LINE_OR_MOBILE
// Invalid UK landline 020...
const ukLandline = validatePhoneNumber('7123456789', '+44', 'United Kingdom');
expect(ukLandline).toBeNull();
// Invalid number with valid prefix but rejected by libphonenumber-js
expect(validatePhoneNumber('0000000000', '+91', 'India')).toContain('must start with');
expect(validatePhoneNumber('07700900123', '+44', 'United Kingdom')).toContain('Please enter a valid mobile number');
});
});
describe('parsePhoneNumber', () => {
it('parses empty, valid E.164, and fallback numbers', () => {
expect(parsePhoneNumber('', 'India')).toEqual({
country: 'India',
dialCode: '+91',
localDigits: '',
iso2: 'IN',
});
const parsedIn = parsePhoneNumber('+919876543210', 'India');
expect(parsedIn).toEqual({
country: 'India',
dialCode: '+91',
localDigits: '9876543210',
iso2: 'IN',
});
const parsedDe = parsePhoneNumber('+491512345678', 'India');
expect(parsedDe.country).toBe('Germany');
expect(parsedDe.dialCode).toBe('+49');
// Fallback when unparseable by libphonenumber-js
const fallbackSame = parsePhoneNumber('+91 123', 'India');
expect(fallbackSame.dialCode).toBe('+91');
const fallbackOther = parsePhoneNumber('+49', 'India');
expect(fallbackOther.dialCode).toBe('+49');
expect(fallbackOther.country).toBe('Germany');
const rawOnly = parsePhoneNumber('9876', 'India');
expect(rawOnly.localDigits).toBe('9876');
const unknownCode = parsePhoneNumber('+999123', 'India');
expect(unknownCode.localDigits).toBe('999123');
});
});
describe('formatE164Phone', () => {
it('formats valid and fallback E.164 strings', () => {
expect(formatE164Phone('+91', '')).toBe('');
expect(formatE164Phone('+91', 'abc')).toBe('');
expect(formatE164Phone('+91', '9876543210', 'India')).toBe('+919876543210');
expect(formatE164Phone('44', '07123456789', 'United Kingdom')).toBe('+447123456789');
// Fallback trunk 0 removal when invalid
expect(formatE164Phone('+91', '0123', 'India')).toBe('+91123');
// Italy keeps trunk 0 in fallback
expect(formatE164Phone('+39', '0123', 'Italy')).toBe('+390123');
});
});
describe('updatePhoneDialCode', () => {
it('updates dial code and clamps to new country maxLength', () => {
expect(updatePhoneDialCode('', 'India', 'Germany')).toBe('');
expect(updatePhoneDialCode('+91 9876543210', 'India', 'Singapore')).toBe('+65 98765432');
expect(updatePhoneDialCode('+91', 'India', 'Germany')).toBe('+49 ');
});
});
describe('validatePassword', () => {
it('enforces all password complexity rules', () => {
expect(SPECIAL_CHAR_REGEX.test('!')).toBe(true);
expect(validatePassword('')).toBe('Password is required.');
expect(validatePassword('Ab1!')).toContain('at least 8 characters');
expect(validatePassword('Abcd 1234!')).toContain('must not contain spaces');
expect(validatePassword('abcd1234!')).toContain('uppercase');
expect(validatePassword('Abcdefgh!')).toContain('number');
expect(validatePassword('Abcd1234😀!')).toContain('emojis');
expect(validatePassword('Abcd12345')).toContain('special character');
expect(validatePassword('ValidPass1!')).toBeNull();
});
});
describe('validateEmail & isValidEmail', () => {
it('validates RFC-compliant emails', () => {
expect(EMAIL_REGEX.test('user@example.com')).toBe(true);
expect(validateEmail('')).toBe('Email address is required.');
expect(validateEmail(' ')).toBe('Email address is required.');
expect(validateEmail('invalid-email')).toBe('Please enter a valid email address.');
expect(validateEmail('user@example.com')).toBeNull();
expect(isValidEmail('user.name+1@sub.example.co.in')).toBe(true);
expect(isValidEmail('bad@')).toBe(false);
});
});
});

View File

@ -1,11 +1,32 @@
import { defineConfig } from 'vite' import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react' import react from '@vitejs/plugin-react'
const rawBase = process.env.VITE_BASE_PATH || '/store/'
const baseWithoutSlash = rawBase.endsWith('/') ? rawBase.slice(0, -1) : rawBase
// https://vite.dev/config/ // https://vite.dev/config/
export default defineConfig({ export default defineConfig({
base: process.env.VITE_BASE_PATH || '/store/', base: rawBase,
plugins: [react()], plugins: [
react(),
{
name: 'redirect-base-middleware',
configureServer(server) {
server.middlewares.use((req, res, next) => {
const [pathname, search] = (req.url || '').split('?')
if (baseWithoutSlash && pathname === baseWithoutSlash) {
const target = `${rawBase}${search ? `?${search}` : ''}`
res.writeHead(302, { Location: target })
res.end()
return
}
next()
})
}
}
],
server: { server: {
port: 3000, port: 3000,
} }
}) })

25
vitest.config.ts Normal file
View File

@ -0,0 +1,25 @@
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: ['./tests/unit/setup.ts'],
include: ['tests/unit/**/*.test.{ts,tsx}'],
coverage: {
provider: 'v8',
reporter: ['text', 'html', 'lcov'],
reportsDirectory: './coverage',
include: ['src/**/*.{ts,tsx}'],
exclude: ['src/main.tsx', 'src/types/**'],
thresholds: {
lines: 84,
functions: 84,
branches: 70,
statements: 80,
},
},
},
});