Compare commits
36 Commits
fix/issue-
...
main
| Author | SHA1 | Date |
|---|---|---|
|
|
0e9d779c91 | |
|
|
50550e1703 | |
|
|
36dc2afc00 | |
|
|
0f9212563f | |
|
|
2013659a20 | |
|
|
d5fa9ad00d | |
|
|
49a5ccbf54 | |
|
|
723bf72570 | |
|
|
f8aa89d21b | |
|
|
227bbd6550 | |
|
|
3371c4a3e5 | |
|
|
fc7660e672 | |
|
|
4356f8321f | |
|
|
25594ec512 | |
|
|
caa60c68fb | |
|
|
75525b17ea | |
|
|
08dd2325dc | |
|
|
5241396999 | |
|
|
1f11874755 | |
|
|
b7cd62519d | |
|
|
dc55ab4acf | |
|
|
342ca856d9 | |
|
|
9af7a9ad33 | |
|
|
551631773e | |
|
|
38d5149114 | |
|
|
aa4e1f0831 | |
|
|
a21a910d24 | |
|
|
eea2853d5d | |
|
|
2aceec4c37 | |
|
|
70b9e7146e | |
|
|
41e885a7c9 | |
|
|
1567a96c54 | |
|
|
a4e7c169a3 | |
|
|
3d2c9c3c78 | |
|
|
1dd80f23ba | |
|
|
841f9a86a5 |
|
|
@ -31,3 +31,8 @@ dist-ssr
|
|||
# Generated Git Info
|
||||
.git_*_info
|
||||
|
||||
# Playwright & Coverage
|
||||
playwright-report/
|
||||
test-results/
|
||||
coverage/
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
```
|
||||
File diff suppressed because it is too large
Load Diff
19
package.json
19
package.json
|
|
@ -7,30 +7,45 @@
|
|||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"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": {
|
||||
"axios": "^1.7.0",
|
||||
"libphonenumber-js": "^1.13.16",
|
||||
"lucide-react": "^0.460.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.0.0",
|
||||
"@playwright/test": "^1.65.1",
|
||||
"@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/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^4.3.0",
|
||||
"@vitest/coverage-v8": "^5.1.2",
|
||||
"autoprefixer": "^10.4.0",
|
||||
"eslint": "^9.0.0",
|
||||
"eslint-plugin-react-hooks": "^5.0.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.0",
|
||||
"globals": "^15.0.0",
|
||||
"jsdom": "^31.0.1",
|
||||
"postcss": "^8.4.0",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "^5.8.0",
|
||||
"typescript-eslint": "^8.0.0",
|
||||
"vite": "^6.0.0"
|
||||
"vite": "^6.0.0",
|
||||
"vitest": "^5.1.2"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
},
|
||||
});
|
||||
358
src/App.tsx
358
src/App.tsx
|
|
@ -1,7 +1,8 @@
|
|||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import axios from 'axios';
|
||||
|
||||
import { CURRICULUM_MODULES } from './constants/modules';
|
||||
import { buildDynamicCatalog } from './utils/catalog';
|
||||
import { getCountryRuleByName } from './constants/countries';
|
||||
import type { ModuleItem, Currency, UserProfile, VerificationResult, PublicPlan } from './types';
|
||||
import { API_BASE } from './services/api';
|
||||
|
|
@ -20,20 +21,44 @@ import { ProfileDrawer } from './components/auth/ProfileDrawer';
|
|||
import { PaymentSuccessModal } from './components/checkout/PaymentSuccessModal';
|
||||
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';
|
||||
|
||||
const getInitialTab = (): 'storefront' | 'subscriptions' => {
|
||||
const getInitialTab = (): 'storefront' | 'subscriptions' | 'logged-out' => {
|
||||
if (typeof window !== 'undefined') {
|
||||
const path = window.location.pathname.toLowerCase();
|
||||
if (path.includes('/logged-out')) return 'logged-out';
|
||||
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';
|
||||
};
|
||||
|
||||
export default function App() {
|
||||
const [activeTab, setActiveTab] = useState<'storefront' | 'subscriptions'>(getInitialTab);
|
||||
const getInitialRegion = (): { currency: Currency; country: string; dialCode: string } => {
|
||||
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);
|
||||
if (typeof window !== 'undefined') {
|
||||
const isStorePrefix = window.location.pathname.startsWith('/store');
|
||||
|
|
@ -45,7 +70,8 @@ export default function App() {
|
|||
}
|
||||
};
|
||||
|
||||
const [currency, setCurrency] = useState<Currency>('INR');
|
||||
const initialRegion = useMemo(getInitialRegion, []);
|
||||
const [currency, setCurrency] = useState<Currency>(initialRegion.currency);
|
||||
|
||||
// Auth state
|
||||
const [userToken, setUserToken] = useState<string | null>(localStorage.getItem('access_token'));
|
||||
|
|
@ -68,13 +94,23 @@ export default function App() {
|
|||
const [changePasswordError, setChangePasswordError] = useState<string | null>(null);
|
||||
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
|
||||
const [authEmail, setAuthEmail] = useState('');
|
||||
const [authPassword, setAuthPassword] = useState('');
|
||||
const [authDisplayName, setAuthDisplayName] = useState('');
|
||||
const [authPhone, setAuthPhone] = useState('');
|
||||
const [authDialCode, setAuthDialCode] = useState('+91');
|
||||
const [authCountry, setAuthCountry] = useState('India');
|
||||
const [authDialCode, setAuthDialCode] = useState(initialRegion.dialCode);
|
||||
const [authCountry, setAuthCountry] = useState(initialRegion.country);
|
||||
const [authLoading, setAuthLoading] = useState(false);
|
||||
const [authError, setAuthError] = useState<string | null>(null);
|
||||
|
||||
|
|
@ -141,109 +177,60 @@ export default function App() {
|
|||
const [showBillingPhoneModal, setShowBillingPhoneModal] = useState<boolean>(false);
|
||||
const [pendingCheckoutAfterPhone, setPendingCheckoutAfterPhone] = useState<boolean>(false);
|
||||
|
||||
// Dynamic Public Storefront Plans
|
||||
// Dynamic Public Storefront Plans & Modules
|
||||
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 () => {
|
||||
try {
|
||||
const res = await axios.get(`${API_BASE}/api/plans`);
|
||||
if (Array.isArray(res.data)) {
|
||||
setPublicPlans(res.data);
|
||||
fetchModuleCategories(res.data);
|
||||
setPlansLoaded(true);
|
||||
}
|
||||
} catch (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 fetchModuleCategories = async (plansList?: PublicPlan[]) => {
|
||||
const fetchModuleCategories = async () => {
|
||||
try {
|
||||
const res = await axios.get(`${API_BASE}/api/contents/modules`);
|
||||
const apiModules: any[] = res.data?.modules || [];
|
||||
const currentPlans = plansList && plansList.length > 0 ? plansList : publicPlans;
|
||||
if (apiModules.length > 0) {
|
||||
const normalizeCategory = (cat?: string): 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);
|
||||
};
|
||||
|
||||
setCurriculumModules((prev) =>
|
||||
prev.map((item) => {
|
||||
// 1. If item maps directly to a plan with single module slug, match by that slug
|
||||
const matchedPlan = currentPlans.find((p) => p.code === item.code || p.base_code === item.code);
|
||||
let matched: any = null;
|
||||
if (matchedPlan) {
|
||||
const slugs: string[] = matchedPlan.module_slugs || (matchedPlan.modules || []).map((m: any) => m.slug).filter(Boolean);
|
||||
if (slugs.length === 1) {
|
||||
const targetSlug = slugs[0].toLowerCase();
|
||||
matched = apiModules.find((m) => (m.slug || '').toLowerCase() === targetSlug);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Direct code match
|
||||
if (!matched) {
|
||||
const iCode = (item.code || '').toLowerCase();
|
||||
matched = apiModules.find((m) => (m.code || '').toLowerCase() === iCode);
|
||||
}
|
||||
|
||||
// 3. Normalized semantic match without collisions
|
||||
if (!matched) {
|
||||
const iName = item.name.toLowerCase();
|
||||
const cleanI = iName.replace('points:', '').replace('therapeutics:', '').split('(')[0].trim();
|
||||
|
||||
matched = apiModules.find((m) => {
|
||||
const mSlug = (m.slug || '').toLowerCase();
|
||||
const mName = (m.name || '').toLowerCase();
|
||||
const cleanM = mName.replace('points:', '').replace('therapeutics:', '').split('(')[0].trim();
|
||||
|
||||
if (cleanI.includes('scalp') && (cleanM.includes('scalp') || mSlug.includes('scalp'))) return true;
|
||||
|
||||
// Disambiguate Ear Reflexology / Auriculotherapy vs Ear Acupuncture
|
||||
if (cleanI.includes('reflexology') || item.code === 'THERAPEUTICS_EAR') {
|
||||
return mSlug.includes('auriculo') || cleanM.includes('reflexology') || mSlug.includes('reflexology');
|
||||
}
|
||||
if (cleanI.includes('ear') || item.code === 'POINTS_EAR') {
|
||||
return mSlug.includes('ear-acupuncture') || (cleanM.includes('ear') && !mSlug.includes('auriculo') && !cleanM.includes('reflexology'));
|
||||
}
|
||||
|
||||
if (cleanI.includes('acu') && cleanM.includes('acupuncture') && !cleanI.includes('scalp') && !cleanI.includes('ear')) return true;
|
||||
if (cleanI.includes('gyneco') && mSlug.includes('gyneco')) return true;
|
||||
if (cleanI.includes('eight') && mSlug.includes('eight')) return true;
|
||||
if (cleanI.includes('zang') && mSlug.includes('tcm-pattern')) return true;
|
||||
if (cleanI.includes('qi') && mSlug.includes('qi')) return true;
|
||||
if (cleanI.includes('pathogenic') && mSlug.includes('pathogenic')) return true;
|
||||
if (cleanI.includes('six') && mSlug.includes('six')) return true;
|
||||
if (cleanI.includes('four') && mSlug.includes('four')) return true;
|
||||
if (cleanI.includes('three') && mSlug.includes('three')) return true;
|
||||
if (cleanI.includes('five') && mSlug.includes('five')) return true;
|
||||
if (cleanI.includes('food') && mSlug.includes('nutrition')) return true;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
const rawCat = matched?.category || matched?.metadata?.category || matched?.metadata?.kind;
|
||||
const updatedCat = normalizeCategory(rawCat);
|
||||
if (updatedCat) {
|
||||
return { ...item, category: updatedCat };
|
||||
}
|
||||
return item;
|
||||
})
|
||||
);
|
||||
const mods: any[] = Array.isArray(res.data) ? res.data : (res.data?.modules || []);
|
||||
if (mods.length > 0) {
|
||||
setApiModules(mods);
|
||||
}
|
||||
} catch (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) => {
|
||||
return publicPlans.find(p => p.code === code || p.base_code === code);
|
||||
|
|
@ -252,18 +239,27 @@ export default function App() {
|
|||
const getModulePrice = (item: ModuleItem) => {
|
||||
const livePlan = getLivePlan(item.code);
|
||||
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 {
|
||||
priceInr: livePlan.price_inr ?? item.priceInr,
|
||||
priceUsd: livePlan.price_usd ?? item.priceUsd,
|
||||
priceEur: item.priceEur,
|
||||
isActive: livePlan.is_active !== undefined ? livePlan.is_active : true,
|
||||
priceEur: livePlan.price_eur ?? livePlan.price_usd ?? item.priceEur,
|
||||
// Require active flag and a positive price in the user's billing currency
|
||||
isActive: planIsActive && activeCurrencyPrice > 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
priceInr: item.priceInr,
|
||||
priceUsd: item.priceUsd,
|
||||
priceEur: item.priceEur,
|
||||
isActive: true,
|
||||
// Once /api/plans has loaded, catalog plans absent from it are inactive in the DB
|
||||
isActive: !plansLoaded,
|
||||
};
|
||||
};
|
||||
|
||||
|
|
@ -280,6 +276,12 @@ export default function App() {
|
|||
const urlPlanCode = params.get('planCode');
|
||||
const urlReturnRoute = params.get('returnRoute') || params.get('redirectPath') || params.get('redirect');
|
||||
const urlScheme = params.get('scheme');
|
||||
const shouldOpenLogin = params.get('login') === 'true' || params.get('auth') === 'login';
|
||||
|
||||
if (shouldOpenLogin) {
|
||||
setAuthMode('login');
|
||||
setShowAuthModal(true);
|
||||
}
|
||||
|
||||
if (urlReturnRoute) {
|
||||
setReturnRoute(urlReturnRoute);
|
||||
|
|
@ -308,13 +310,20 @@ export default function App() {
|
|||
...prev,
|
||||
[targetModule.category]: true
|
||||
}));
|
||||
} else {
|
||||
setPendingUrlPlanCode(normalizedPlanCode);
|
||||
}
|
||||
}
|
||||
|
||||
if (urlToken || urlPlanCode) {
|
||||
if (urlToken || urlPlanCode || shouldOpenLogin) {
|
||||
const isStorePrefix = window.location.pathname.startsWith('/store');
|
||||
const basePath = isStorePrefix ? '/store/' : '/';
|
||||
const cleanPath = activeTab === 'subscriptions' ? `${basePath}subscriptions` : basePath;
|
||||
const cleanPath =
|
||||
activeTab === 'subscriptions'
|
||||
? `${basePath}subscriptions`
|
||||
: activeTab === 'logged-out'
|
||||
? `${basePath}logged-out`
|
||||
: basePath;
|
||||
window.history.replaceState({}, document.title, cleanPath);
|
||||
}
|
||||
|
||||
|
|
@ -360,6 +369,7 @@ export default function App() {
|
|||
const mergedUser = {
|
||||
...profileRes.data,
|
||||
active_subscriptions: accessRes.data.active_subscriptions || [],
|
||||
unlocked_module_codes: accessRes.data.unlocked_module_codes || [],
|
||||
unlocked_module_slugs: accessRes.data.unlocked_module_slugs || [],
|
||||
};
|
||||
|
||||
|
|
@ -371,11 +381,22 @@ export default function App() {
|
|||
setCurrency(countryRule.currency);
|
||||
} catch (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');
|
||||
setUserToken(null);
|
||||
setLoggedInUser(null);
|
||||
|
|
@ -383,13 +404,19 @@ export default function App() {
|
|||
setAppliedCoupon(null);
|
||||
setCouponCode('');
|
||||
setPricingCalc(null);
|
||||
switchTab('storefront');
|
||||
setShowProfileDrawer(false);
|
||||
handleCloseProfileDrawer();
|
||||
setProfileDisplayName('');
|
||||
setProfilePhone('');
|
||||
setProfileCountry('India');
|
||||
setProfileCountry(initialRegion.country);
|
||||
setCurrency(initialRegion.currency);
|
||||
setProfileError(null);
|
||||
setProfileSuccess(false);
|
||||
setShowAuthModal(false);
|
||||
};
|
||||
|
||||
const handleLogout = () => {
|
||||
resetAuthSession();
|
||||
switchTab('logged-out');
|
||||
};
|
||||
|
||||
const handleUpdateProfile = async (e: React.FormEvent) => {
|
||||
|
|
@ -408,7 +435,7 @@ export default function App() {
|
|||
setProfileSaving(false);
|
||||
return;
|
||||
}
|
||||
cleanedPhoneToSave = formatE164Phone(parsed.dialCode, parsed.localDigits);
|
||||
cleanedPhoneToSave = formatE164Phone(parsed.dialCode, parsed.localDigits, profileCountry);
|
||||
}
|
||||
|
||||
try {
|
||||
|
|
@ -501,8 +528,7 @@ export default function App() {
|
|||
setAuthLoading(false);
|
||||
return;
|
||||
}
|
||||
const rawDigits = authPhone.replace(/\D/g, '');
|
||||
fullPhone = `${authDialCode}${rawDigits}`;
|
||||
fullPhone = formatE164Phone(authDialCode, authPhone, authCountry);
|
||||
}
|
||||
|
||||
const endpoint = authMode === 'login' ? '/api/auth/login' : '/api/auth/register';
|
||||
|
|
@ -539,6 +565,15 @@ export default function App() {
|
|||
setAuthEmail('');
|
||||
setAuthDisplayName('');
|
||||
setAuthPhone('');
|
||||
if (activeTab === 'logged-out') {
|
||||
switchTab('storefront');
|
||||
}
|
||||
setShowPasswordChange(false);
|
||||
setChangeOldPassword('');
|
||||
setChangeNewPassword('');
|
||||
setChangeConfirmPassword('');
|
||||
setChangePasswordError(null);
|
||||
setChangePasswordSuccess(false);
|
||||
} catch (err: any) {
|
||||
setAuthError(err.response?.data?.detail || 'Authentication failed. Please check credentials.');
|
||||
} finally {
|
||||
|
|
@ -581,8 +616,8 @@ export default function App() {
|
|||
|
||||
const userEmail = loggedInUser?.email || authEmail;
|
||||
|
||||
// Invalidate active session so re-authentication is required
|
||||
handleLogout();
|
||||
// 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
|
||||
|
|
@ -595,7 +630,8 @@ export default function App() {
|
|||
setChangeNewPassword('');
|
||||
setChangeConfirmPassword('');
|
||||
setShowPasswordChange(false);
|
||||
setChangePasswordSuccess(true);
|
||||
setChangePasswordSuccess(false);
|
||||
setChangePasswordError(null);
|
||||
setPasswordUpdatedPopup(true);
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
|
|
@ -672,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(() => {
|
||||
if (publicPlans.length > 0 && cart.length > 0) {
|
||||
setCart(prev =>
|
||||
prev.map(item => {
|
||||
const live = getModulePrice(item);
|
||||
return {
|
||||
...item,
|
||||
priceInr: live.priceInr,
|
||||
priceUsd: live.priceUsd,
|
||||
};
|
||||
})
|
||||
);
|
||||
if (!plansLoaded || cart.length === 0) return;
|
||||
|
||||
const nextCart: ModuleItem[] = [];
|
||||
for (const item of cart) {
|
||||
const live = getModulePrice(item);
|
||||
if (!live.isActive) continue;
|
||||
nextCart.push({
|
||||
...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 () => {
|
||||
setLoadingPricing(true);
|
||||
|
|
@ -762,6 +817,7 @@ export default function App() {
|
|||
...module,
|
||||
priceInr: live.priceInr,
|
||||
priceUsd: live.priceUsd,
|
||||
priceEur: live.priceEur,
|
||||
};
|
||||
|
||||
const exists = cart.find(item => item.code === module.code);
|
||||
|
|
@ -817,25 +873,60 @@ export default function App() {
|
|||
if (!loggedInUser?.active_subscriptions) return false;
|
||||
|
||||
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;
|
||||
|
||||
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') {
|
||||
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 (code === 'THERAPEUTICS_GYNAE' || code === 'THERAPEUTICS_EAR') {
|
||||
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;
|
||||
}
|
||||
|
||||
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
|
||||
|
|
@ -911,7 +1002,7 @@ export default function App() {
|
|||
|
||||
// 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);
|
||||
const sanitizedContact = formatE164Phone(parsedContact.dialCode, parsedContact.localDigits, loggedInUser?.country || 'India');
|
||||
|
||||
const rzpOptions = {
|
||||
key: razorpayKeyId,
|
||||
|
|
@ -1044,7 +1135,11 @@ export default function App() {
|
|||
activeTab={activeTab}
|
||||
onSwitchTab={switchTab}
|
||||
loggedInUser={loggedInUser}
|
||||
onOpenProfile={() => setShowProfileDrawer(true)}
|
||||
onOpenProfile={() => {
|
||||
setChangePasswordSuccess(false);
|
||||
setChangePasswordError(null);
|
||||
setShowProfileDrawer(true);
|
||||
}}
|
||||
onOpenAuth={(mode) => {
|
||||
setAuthMode(mode);
|
||||
setShowAuthModal(true);
|
||||
|
|
@ -1076,7 +1171,6 @@ export default function App() {
|
|||
<CartDrawer
|
||||
cart={cart}
|
||||
currency={currency}
|
||||
setCurrency={setCurrency}
|
||||
toggleCartItem={toggleCartItem}
|
||||
couponCode={couponCode}
|
||||
setCouponCode={setCouponCode}
|
||||
|
|
@ -1093,6 +1187,14 @@ export default function App() {
|
|||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : activeTab === 'logged-out' ? (
|
||||
<LoggedOutView
|
||||
onLoginAgain={() => {
|
||||
switchTab('storefront');
|
||||
setAuthMode('login');
|
||||
setShowAuthModal(true);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
/* 🧾 Tab: User Personal Subscriptions Ledger */
|
||||
<SubscriptionsView
|
||||
|
|
@ -1169,7 +1271,7 @@ export default function App() {
|
|||
{/* 🧭 Profile Drawer */}
|
||||
<ProfileDrawer
|
||||
isOpen={showProfileDrawer}
|
||||
onClose={() => setShowProfileDrawer(false)}
|
||||
onClose={handleCloseProfileDrawer}
|
||||
loggedInUser={loggedInUser}
|
||||
profileDisplayName={profileDisplayName}
|
||||
setProfileDisplayName={setProfileDisplayName}
|
||||
|
|
@ -1192,15 +1294,17 @@ export default function App() {
|
|||
setChangeConfirmPassword={setChangeConfirmPassword}
|
||||
changePasswordLoading={changePasswordLoading}
|
||||
changePasswordError={changePasswordError}
|
||||
setChangePasswordError={setChangePasswordError}
|
||||
changePasswordSuccess={changePasswordSuccess}
|
||||
setChangePasswordSuccess={setChangePasswordSuccess}
|
||||
onChangePassword={handleChangePassword}
|
||||
onLogout={handleLogout}
|
||||
onBrowseStorefront={() => {
|
||||
setShowProfileDrawer(false);
|
||||
handleCloseProfileDrawer();
|
||||
switchTab('storefront');
|
||||
}}
|
||||
onViewSubscriptions={() => {
|
||||
setShowProfileDrawer(false);
|
||||
handleCloseProfileDrawer();
|
||||
switchTab('subscriptions');
|
||||
}}
|
||||
curriculumModules={curriculumModules}
|
||||
|
|
|
|||
|
|
@ -300,12 +300,12 @@ export const AuthModal: React.FC<AuthModalProps> = ({
|
|||
}}
|
||||
onPhoneChange={(newPhone) => {
|
||||
setAuthPhone(newPhone);
|
||||
if (authError && authError.toLowerCase().includes('phone')) {
|
||||
if (authError && (authError.toLowerCase().includes('phone') || authError.toLowerCase().includes('mobile'))) {
|
||||
setAuthError(null);
|
||||
}
|
||||
}}
|
||||
theme="dark"
|
||||
error={authError && authError.toLowerCase().includes('phone') ? authError : null}
|
||||
error={authError && (authError.toLowerCase().includes('phone') || authError.toLowerCase().includes('mobile')) ? authError : null}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
};
|
||||
|
||||
|
|
@ -5,7 +5,7 @@ import {
|
|||
} from 'lucide-react';
|
||||
import type { UserProfile, ModuleItem, Currency } from '../../types';
|
||||
import { getCountryRuleByName } from '../../constants/countries';
|
||||
import { cleanPhoneInput, parsePhoneNumber, formatE164Phone, SPECIAL_CHAR_REGEX } from '../../utils/validation';
|
||||
import { parsePhoneNumber, formatE164Phone, SPECIAL_CHAR_REGEX } from '../../utils/validation';
|
||||
import { PhoneInput } from '../common/PhoneInput';
|
||||
import { CountrySelect } from '../common/CountrySelect';
|
||||
|
||||
|
|
@ -34,7 +34,9 @@ interface ProfileDrawerProps {
|
|||
setChangeConfirmPassword: (pwd: string) => void;
|
||||
changePasswordLoading: boolean;
|
||||
changePasswordError: string | null;
|
||||
setChangePasswordError?: (err: string | null) => void;
|
||||
changePasswordSuccess: boolean;
|
||||
setChangePasswordSuccess?: (success: boolean) => void;
|
||||
onChangePassword: (e: React.FormEvent) => Promise<void>;
|
||||
onLogout: () => void;
|
||||
onBrowseStorefront: () => void;
|
||||
|
|
@ -68,7 +70,9 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
|
|||
setChangeConfirmPassword,
|
||||
changePasswordLoading,
|
||||
changePasswordError,
|
||||
setChangePasswordError,
|
||||
changePasswordSuccess,
|
||||
setChangePasswordSuccess,
|
||||
onChangePassword,
|
||||
onLogout,
|
||||
onBrowseStorefront,
|
||||
|
|
@ -89,32 +93,43 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
|
|||
const p = parsePhoneNumber(profilePhone, profileCountry);
|
||||
setDialCode(p.dialCode);
|
||||
setLocalPhone(p.localDigits);
|
||||
} else {
|
||||
if (setChangePasswordSuccess) setChangePasswordSuccess(false);
|
||||
if (setChangePasswordError) setChangePasswordError(null);
|
||||
}
|
||||
}, [profilePhone, profileCountry, isOpen]);
|
||||
}, [isOpen, setChangePasswordSuccess, setChangePasswordError]);
|
||||
|
||||
const handleLocalPhoneChange = (newLocal: string) => {
|
||||
setLocalPhone(newLocal);
|
||||
setProfilePhone(newLocal ? formatE164Phone(dialCode, newLocal) : '');
|
||||
setProfilePhone(newLocal ? formatE164Phone(dialCode, newLocal, profileCountry) : '');
|
||||
};
|
||||
|
||||
const handleDialCodeChange = (newCode: string, newCountry: string) => {
|
||||
setDialCode(newCode);
|
||||
setProfileCountry(newCountry);
|
||||
const rule = getCountryRuleByName(newCountry);
|
||||
setCurrency(rule.currency);
|
||||
const clamped = cleanPhoneInput(localPhone, rule.maxLength, false);
|
||||
setLocalPhone(clamped);
|
||||
setProfilePhone(formatE164Phone(newCode, clamped));
|
||||
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) => {
|
||||
setProfileCountry(newCountry);
|
||||
const rule = getCountryRuleByName(newCountry);
|
||||
setDialCode(rule.code);
|
||||
setCurrency(rule.currency);
|
||||
const clamped = cleanPhoneInput(localPhone, rule.maxLength, false);
|
||||
setLocalPhone(clamped);
|
||||
setProfilePhone(formatE164Phone(rule.code, clamped));
|
||||
if (newCountry !== profileCountry) {
|
||||
setProfileCountry(newCountry);
|
||||
const rule = getCountryRuleByName(newCountry);
|
||||
if (rule) {
|
||||
setDialCode(rule.code);
|
||||
setCurrency(rule.currency);
|
||||
}
|
||||
setLocalPhone('');
|
||||
setProfilePhone('');
|
||||
}
|
||||
};
|
||||
|
||||
if (!isOpen || !loggedInUser) return null;
|
||||
|
|
@ -190,11 +205,12 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
|
|||
dialCode={dialCode}
|
||||
phone={localPhone}
|
||||
country={profileCountry}
|
||||
clearOnDialCodeChange={true}
|
||||
onDialCodeChange={handleDialCodeChange}
|
||||
onPhoneChange={handleLocalPhoneChange}
|
||||
theme="light"
|
||||
disabled={profileSaving}
|
||||
error={profileError && profileError.toLowerCase().includes('phone') ? profileError : null}
|
||||
error={profileError && (profileError.toLowerCase().includes('phone') || profileError.toLowerCase().includes('mobile')) ? profileError : null}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
|
@ -230,6 +246,8 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
|
|||
type="button"
|
||||
onClick={() => {
|
||||
setShowPasswordChange(!showPasswordChange);
|
||||
if (setChangePasswordSuccess) setChangePasswordSuccess(false);
|
||||
if (setChangePasswordError) setChangePasswordError(null);
|
||||
}}
|
||||
className="text-xs text-indigo-600 hover:text-indigo-700 font-bold"
|
||||
>
|
||||
|
|
|
|||
|
|
@ -1,12 +1,11 @@
|
|||
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 { isValidPhoneNumber } from '../../utils/validation';
|
||||
|
||||
interface CartDrawerProps {
|
||||
cart: ModuleItem[];
|
||||
currency: Currency;
|
||||
setCurrency: (c: Currency) => void;
|
||||
toggleCartItem: (module: ModuleItem) => void;
|
||||
couponCode: string;
|
||||
setCouponCode: (code: string) => void;
|
||||
|
|
@ -25,7 +24,6 @@ interface CartDrawerProps {
|
|||
export const CartDrawer: React.FC<CartDrawerProps> = ({
|
||||
cart,
|
||||
currency,
|
||||
setCurrency,
|
||||
toggleCartItem,
|
||||
couponCode,
|
||||
setCouponCode,
|
||||
|
|
@ -77,28 +75,23 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
|
|||
</span>
|
||||
</div>
|
||||
|
||||
{/* Currency selector toggle */}
|
||||
<div className="flex flex-col sm:flex-row gap-2 sm:items-center justify-between">
|
||||
<span className="text-xs font-bold text-slate-500">Billing Currency:</span>
|
||||
<div className="flex bg-slate-100 rounded-lg p-0.5 border border-slate-200 self-end sm:self-auto flex-shrink-0">
|
||||
<button
|
||||
onClick={() => setCurrency('INR')}
|
||||
className={`px-3 py-1 rounded-md text-xs font-bold transition-all duration-300 ${currency === 'INR'
|
||||
? 'bg-white text-slate-900 shadow-sm border border-slate-200/50'
|
||||
: 'text-slate-500 hover:text-slate-800'
|
||||
}`}
|
||||
>
|
||||
INR (₹)
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setCurrency('USD')}
|
||||
className={`px-3 py-1 rounded-md text-xs font-bold transition-all duration-300 ${currency === 'USD'
|
||||
? 'bg-white text-slate-900 shadow-sm border border-slate-200/50'
|
||||
: 'text-slate-500 hover:text-slate-800'
|
||||
}`}
|
||||
>
|
||||
USD ($)
|
||||
</button>
|
||||
{/* Billing Currency & Region Badge */}
|
||||
<div className="flex items-center justify-between p-2.5 bg-slate-50 border border-slate-200/70 rounded-xl">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<Globe className="h-3.5 w-3.5 text-indigo-500 shrink-0" />
|
||||
<span className="text-xs font-semibold text-slate-600 truncate">
|
||||
{loggedInUser ? 'Billing Currency' : 'Estimated Currency'}:
|
||||
</span>
|
||||
</div>
|
||||
<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 ($)'}
|
||||
</span>
|
||||
{loggedInUser?.country && (
|
||||
<span className="text-[10px] text-slate-400 font-semibold max-w-[90px] truncate" title={loggedInUser.country}>
|
||||
• {loggedInUser.country}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -366,6 +359,10 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
|
|||
<span>Email:</span>
|
||||
<span className="text-slate-800 font-bold truncate max-w-[180px]">{loggedInUser.email}</span>
|
||||
</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">
|
||||
<span>Phone:</span>
|
||||
<span className="text-slate-800 font-bold">
|
||||
|
|
@ -413,6 +410,15 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
|
|||
<p className="text-[10px] text-slate-400 text-center leading-relaxed font-semibold">
|
||||
* Integrated with Razorpay Gateway API (Test Mode).
|
||||
</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>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import React from 'react';
|
||||
import { BookOpen, Check } from 'lucide-react';
|
||||
import type { ModuleItem, PublicPlan, Currency } from '../../types';
|
||||
import { CORE_PACK_CODES, MAIN_CATEGORIES, resolvePlanCategory } from '../../utils/catalog';
|
||||
|
||||
interface CatalogSectionProps {
|
||||
curriculumModules: ModuleItem[];
|
||||
|
|
@ -30,6 +31,11 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
showLockedByCategory,
|
||||
setShowLockedByCategory,
|
||||
}) => {
|
||||
const countLockedActive = (predicate: (category: string) => boolean) =>
|
||||
curriculumModules.filter(
|
||||
m => predicate(m.category) && !isModuleUnlocked(m.code) && getModulePrice(m).isActive
|
||||
).length;
|
||||
|
||||
return (
|
||||
<div className="xl:col-span-2 space-y-6">
|
||||
<div className="space-y-2">
|
||||
|
|
@ -57,7 +63,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
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"
|
||||
>
|
||||
{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>
|
||||
</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">
|
||||
|
|
@ -72,7 +78,9 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
|
||||
<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 isUnlocked = isModuleUnlocked(sub.code);
|
||||
const live = getModulePrice(sub);
|
||||
|
|
@ -176,7 +184,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
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"
|
||||
>
|
||||
{showLockedByCategory.Pattern ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => (m.category === 'Pattern' || m.category === 'Patterns') && !isModuleUnlocked(m.code)).length})
|
||||
{showLockedByCategory.Pattern ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Pattern' || c === 'Patterns')})
|
||||
</button>
|
||||
</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">
|
||||
|
|
@ -191,7 +199,9 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
|
||||
<div className="space-y-2">
|
||||
{(() => {
|
||||
const items = curriculumModules.filter(m => m.category === 'Pattern' || m.category === 'Patterns');
|
||||
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 isUnlocked = isModuleUnlocked(sub.code);
|
||||
const live = getModulePrice(sub);
|
||||
|
|
@ -239,7 +249,12 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
>
|
||||
<div className="flex-1 pr-2">
|
||||
<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 && (
|
||||
<span className="text-[8px] bg-slate-200 text-slate-600 font-bold px-1.5 py-0.5 rounded tracking-wider uppercase">
|
||||
Temporarily Unavailable
|
||||
|
|
@ -290,7 +305,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
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"
|
||||
>
|
||||
{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>
|
||||
</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">
|
||||
|
|
@ -305,7 +320,9 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
|
||||
<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 isUnlocked = isModuleUnlocked(sub.code);
|
||||
const live = getModulePrice(sub);
|
||||
|
|
@ -353,7 +370,12 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
>
|
||||
<div className="flex-1 pr-2">
|
||||
<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 && (
|
||||
<span className="text-[8px] bg-slate-200 text-slate-600 font-bold px-1.5 py-0.5 rounded tracking-wider uppercase">
|
||||
Temporarily Unavailable
|
||||
|
|
@ -404,7 +426,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
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"
|
||||
>
|
||||
{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>
|
||||
</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">
|
||||
|
|
@ -419,7 +441,9 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
|
||||
<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 isUnlocked = isModuleUnlocked(sub.code);
|
||||
const live = getModulePrice(sub);
|
||||
|
|
@ -469,7 +493,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
<div className="flex items-center gap-1.5 flex-wrap">
|
||||
<span className="text-xs font-bold text-slate-800">{sub.name.replace("Therapeutics: ", "")}</span>
|
||||
{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
|
||||
</span>
|
||||
)}
|
||||
|
|
@ -524,7 +548,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
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"
|
||||
>
|
||||
{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>
|
||||
</div>
|
||||
<h3 className="text-xl font-black text-amber-900 tracking-tight">Lifetime Unlimited Access Pass</h3>
|
||||
|
|
@ -623,10 +647,15 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
{/* CARD 6: Custom Packages & Bundles (Dynamic Admin Plans) */}
|
||||
{(() => {
|
||||
const customPlans = publicPlans.filter((p: any) => {
|
||||
const code = p.base_code || p.code;
|
||||
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 isActive = p.is_active !== false;
|
||||
return isCustom && isActive;
|
||||
const code = (p.base_code || p.code || '').toUpperCase();
|
||||
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 && activePrice > 0;
|
||||
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;
|
||||
|
|
@ -665,7 +694,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
category: 'Bundle',
|
||||
priceInr: pInr,
|
||||
priceUsd: pUsd,
|
||||
priceEur: pUsd,
|
||||
priceEur: cPlan.price_eur ?? pUsd,
|
||||
desc: cPlan.description || 'Custom bundled access.',
|
||||
color: 'from-slate-700 to-slate-900'
|
||||
};
|
||||
|
|
@ -717,7 +746,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
|||
</span>
|
||||
) : (
|
||||
<span className="text-xs font-extrabold text-slate-700">
|
||||
{currency === 'INR' ? `₹${pInr}` : `$${pUsd}`}
|
||||
{currency === 'INR' ? `₹${pInr}` : currency === 'EUR' ? `€${cPlan.price_eur ?? pUsd}` : `$${pUsd}`}
|
||||
</span>
|
||||
)}
|
||||
{!isUnlocked && (
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import React, { useState, useEffect } from 'react';
|
||||
import { X, Phone, ShieldCheck, RefreshCw } from 'lucide-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 {
|
||||
|
|
@ -37,6 +39,27 @@ export const BillingPhoneModal: React.FC<BillingPhoneModalProps> = ({
|
|||
|
||||
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);
|
||||
|
|
@ -53,7 +76,7 @@ export const BillingPhoneModal: React.FC<BillingPhoneModalProps> = ({
|
|||
}
|
||||
|
||||
setSaving(true);
|
||||
const e164 = formatE164Phone(dialCode, phone);
|
||||
const e164 = formatE164Phone(dialCode, phone, country);
|
||||
try {
|
||||
const success = await onSavePhone(e164, country);
|
||||
if (success) {
|
||||
|
|
@ -99,11 +122,8 @@ export const BillingPhoneModal: React.FC<BillingPhoneModalProps> = ({
|
|||
dialCode={dialCode}
|
||||
phone={phone}
|
||||
country={country}
|
||||
onDialCodeChange={(newCode, newCountry) => {
|
||||
setDialCode(newCode);
|
||||
setCountry(newCountry);
|
||||
setError(null);
|
||||
}}
|
||||
clearOnDialCodeChange={true}
|
||||
onDialCodeChange={handleDialCodeChange}
|
||||
onPhoneChange={(newPhone) => {
|
||||
setPhone(newPhone);
|
||||
setError(null);
|
||||
|
|
@ -114,9 +134,24 @@ export const BillingPhoneModal: React.FC<BillingPhoneModalProps> = ({
|
|||
/>
|
||||
</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 will appear on your compliance tax invoice and payment receipts.</span>
|
||||
<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">
|
||||
|
|
@ -141,4 +176,3 @@ export const BillingPhoneModal: React.FC<BillingPhoneModalProps> = ({
|
|||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,12 @@
|
|||
import React from 'react';
|
||||
import { COUNTRY_CODES, getCountryRuleByDialCode, getCountryRuleByName } from '../../constants/countries';
|
||||
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 {
|
||||
|
|
@ -27,26 +34,93 @@ export const PhoneInput: React.FC<PhoneInputProps> = ({
|
|||
id = 'phone-input',
|
||||
clearOnDialCodeChange = false,
|
||||
}) => {
|
||||
let activeRule = getCountryRuleByDialCode(dialCode);
|
||||
if (!activeRule && country) {
|
||||
activeRule = getCountryRuleByName(country);
|
||||
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')!;
|
||||
}
|
||||
|
||||
const handleDialCodeSelect = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
const newCode = e.target.value;
|
||||
const rule = getCountryRuleByDialCode(newCode);
|
||||
const newCountry = rule ? rule.country : (country || 'India');
|
||||
// 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(newCode, newCountry);
|
||||
onDialCodeChange(cc.code, cc.country);
|
||||
}
|
||||
if (clearOnDialCodeChange) {
|
||||
onPhoneChange('');
|
||||
} else if (rule) {
|
||||
onPhoneChange(cleanPhoneInput(phone, rule.maxLength, false));
|
||||
} else {
|
||||
onPhoneChange(cleanPhoneInput(phone, cc.maxLength, false));
|
||||
}
|
||||
setIsDropdownOpen(false);
|
||||
setSearchQuery('');
|
||||
};
|
||||
|
||||
const handlePhoneInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
|
|
@ -58,7 +132,7 @@ export const PhoneInput: React.FC<PhoneInputProps> = ({
|
|||
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) {
|
||||
if (onDialCodeChange && (matched.code !== dialCode || matched.country !== country)) {
|
||||
onDialCodeChange(matched.code, matched.country);
|
||||
}
|
||||
const rest = trimmed.slice(matched.code.length).replace(/\D/g, '');
|
||||
|
|
@ -108,27 +182,123 @@ export const PhoneInput: React.FC<PhoneInputProps> = ({
|
|||
return (
|
||||
<div className="space-y-1.5 w-full">
|
||||
<div className="flex gap-2 w-full">
|
||||
{/* Country Code Dropdown */}
|
||||
<div className="relative shrink-0 w-[105px]">
|
||||
<select
|
||||
value={dialCode}
|
||||
onChange={handleDialCodeSelect}
|
||||
{/* Searchable Country Code Dropdown */}
|
||||
<div ref={dropdownRef} className="relative shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
className={`w-full rounded-xl px-2.5 py-2.5 text-xs font-semibold appearance-none pr-6 cursor-pointer focus:outline-none transition-colors ${
|
||||
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' : ''}`}
|
||||
>
|
||||
{COUNTRY_CODES.map((cc) => (
|
||||
<option key={`${cc.country}-${cc.code}`} value={cc.code}>
|
||||
{cc.label} ({cc.country})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="absolute right-2.5 top-1/2 -translate-y-1/2 pointer-events-none text-slate-400 text-[10px]">
|
||||
▼
|
||||
</div>
|
||||
<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 “{searchQuery}”
|
||||
</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 */}
|
||||
|
|
@ -151,23 +321,11 @@ export const PhoneInput: React.FC<PhoneInputProps> = ({
|
|||
/>
|
||||
</div>
|
||||
|
||||
{/* Helper text or Error message */}
|
||||
<div className="flex justify-between items-center text-[10px] px-0.5">
|
||||
{error ? (
|
||||
<p className="text-rose-500 font-bold">{error}</p>
|
||||
) : (
|
||||
<p className={isDark ? 'text-slate-400 font-medium' : 'text-slate-500 font-medium'}>
|
||||
{activeRule.label || activeRule.country}:{' '}
|
||||
{activeRule.minLength === activeRule.maxLength
|
||||
? `Requires exactly ${activeRule.maxLength} digits`
|
||||
: `${activeRule.minLength} to ${activeRule.maxLength} digits`}
|
||||
</p>
|
||||
)}
|
||||
<span className={`font-mono font-semibold ${phone.length === activeRule.maxLength ? 'text-emerald-500' : isDark ? 'text-slate-500' : 'text-slate-400'}`}>
|
||||
{phone.length}/{activeRule.maxLength}
|
||||
</span>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="text-[11px] font-semibold text-rose-500 animate-shake">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@ import { Sparkles, LogIn, UserPlus, BookOpen, CheckCircle } from 'lucide-react';
|
|||
import type { UserProfile } from '../../types';
|
||||
|
||||
interface StoreHeaderProps {
|
||||
activeTab: 'storefront' | 'subscriptions';
|
||||
onSwitchTab: (tab: 'storefront' | 'subscriptions') => void;
|
||||
activeTab: 'storefront' | 'subscriptions' | 'logged-out';
|
||||
onSwitchTab: (tab: 'storefront' | 'subscriptions' | 'logged-out') => void;
|
||||
loggedInUser: UserProfile | null;
|
||||
onOpenProfile: () => void;
|
||||
onOpenAuth: (mode: 'login' | 'register') => void;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import type { CountryCode as LibCountryCode } from 'libphonenumber-js';
|
||||
import type { Currency } from '../types';
|
||||
|
||||
export interface CountryCode {
|
||||
iso2: LibCountryCode;
|
||||
code: string;
|
||||
label: string;
|
||||
country: string;
|
||||
|
|
@ -8,94 +10,102 @@ export interface CountryCode {
|
|||
minLength: number;
|
||||
maxLength: number;
|
||||
placeholder: string;
|
||||
validPrefixes?: string[];
|
||||
example?: string;
|
||||
}
|
||||
|
||||
export const COUNTRY_CODES: CountryCode[] = [
|
||||
// South Asia
|
||||
{ code: '+91', label: '🇮🇳 +91', country: 'India', currency: 'INR', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||
{ code: '+92', label: '🇵🇰 +92', country: 'Pakistan', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||
{ code: '+880', label: '🇧🇩 +880', country: 'Bangladesh', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||
{ code: '+94', label: '🇱🇰 +94', country: 'Sri Lanka', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+977', label: '🇳🇵 +977', country: 'Nepal', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||
{ code: '+975', label: '🇧🇹 +975', country: 'Bhutan', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||
{ code: '+960', label: '🇲🇻 +960', country: 'Maldives', currency: 'USD', minLength: 7, maxLength: 7, placeholder: '7-digit mobile 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' },
|
||||
{ iso2: 'PK', code: '+92', label: '🇵🇰 +92', country: 'Pakistan', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['3'], example: '300 1234567' },
|
||||
{ iso2: 'BD', code: '+880', label: '🇧🇩 +880', country: 'Bangladesh', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['1'], example: '1712 345678' },
|
||||
{ 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' },
|
||||
{ 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' },
|
||||
{ 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' },
|
||||
{ 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' },
|
||||
|
||||
// North America
|
||||
{ code: '+1', label: '🇺🇸 +1', country: 'United States', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit phone number' },
|
||||
{ code: '+1', label: '🇨🇦 +1', country: 'Canada', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit phone number' },
|
||||
{ code: '+52', label: '🇲🇽 +52', country: 'Mexico', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||
{ iso2: 'US', code: '+1', label: '🇺🇸 +1', country: 'United States', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit phone number', example: '202 555 0123' },
|
||||
{ iso2: 'CA', code: '+1', label: '🇨🇦 +1', country: 'Canada', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit phone number', example: '416 555 0123' },
|
||||
{ iso2: 'MX', code: '+52', label: '🇲🇽 +52', country: 'Mexico', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', example: '55 1234 5678' },
|
||||
|
||||
// Europe & UK
|
||||
{ code: '+44', label: '🇬🇧 +44', country: 'United Kingdom', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
|
||||
{ code: '+49', label: '🇩🇪 +49', country: 'Germany', currency: 'EUR', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
|
||||
{ code: '+33', label: '🇫🇷 +33', country: 'France', currency: 'EUR', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
|
||||
{ code: '+39', label: '🇮🇹 +39', country: 'Italy', currency: 'EUR', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
|
||||
{ code: '+34', label: '🇪🇸 +34', country: 'Spain', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+31', label: '🇳🇱 +31', country: 'Netherlands', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+41', label: '🇨🇭 +41', country: 'Switzerland', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+32', label: '🇧🇪 +32', country: 'Belgium', currency: 'EUR', minLength: 8, maxLength: 9, placeholder: '8 to 9 digits' },
|
||||
{ code: '+43', label: '🇦🇹 +43', country: 'Austria', currency: 'EUR', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
|
||||
{ code: '+353', label: '🇮🇪 +353', country: 'Ireland', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+46', label: '🇸🇪 +46', country: 'Sweden', currency: 'EUR', minLength: 7, maxLength: 10, placeholder: '7 to 10 digits' },
|
||||
{ code: '+47', label: '🇳🇴 +47', country: 'Norway', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||
{ code: '+45', label: '🇩🇰 +45', country: 'Denmark', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||
{ code: '+358', label: '🇫🇮 +358', country: 'Finland', currency: 'EUR', minLength: 7, maxLength: 10, placeholder: '7 to 10 digits' },
|
||||
{ code: '+351', label: '🇵🇹 +351', country: 'Portugal', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+30', label: '🇬🇷 +30', country: 'Greece', currency: 'EUR', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||
{ code: '+48', label: '🇵🇱 +48', country: 'Poland', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+420', label: '🇨🇿 +420', country: 'Czech Republic', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+36', label: '🇭🇺 +36', country: 'Hungary', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+40', label: '🇷🇴 +40', country: 'Romania', currency: 'EUR', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
|
||||
{ code: '+380', label: '🇺🇦 +380', country: 'Ukraine', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+354', label: '🇮🇸 +354', country: 'Iceland', currency: 'EUR', minLength: 7, maxLength: 9, placeholder: '7 to 9 digits' },
|
||||
{ code: '+352', label: '🇱🇺 +352', country: 'Luxembourg', currency: 'EUR', minLength: 8, maxLength: 10, placeholder: '8 to 10 digits' },
|
||||
{ code: '+385', label: '🇭🇷 +385', country: 'Croatia', currency: 'EUR', minLength: 8, maxLength: 9, placeholder: '8 to 9 digits' },
|
||||
{ code: '+421', label: '🇸🇰 +421', country: 'Slovakia', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+359', label: '🇧🇬 +359', country: 'Bulgaria', currency: 'EUR', minLength: 8, maxLength: 9, placeholder: '8 to 9 digits' },
|
||||
{ code: '+7', label: '🇷🇺 +7', country: 'Russia', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||
{ code: '+90', label: '🇹🇷 +90', country: 'Turkey', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||
{ 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
|
||||
{ code: '+61', label: '🇦🇺 +61', country: 'Australia', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
|
||||
{ code: '+64', label: '🇳🇿 +64', country: 'New Zealand', currency: 'USD', minLength: 8, maxLength: 10, placeholder: '8 to 10 digits' },
|
||||
{ code: '+81', label: '🇯🇵 +81', country: 'Japan', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
|
||||
{ code: '+86', label: '🇨🇳 +86', country: 'China', currency: 'USD', minLength: 11, maxLength: 11, placeholder: '11-digit mobile number' },
|
||||
{ code: '+82', label: '🇰🇷 +82', country: 'South Korea', currency: 'USD', minLength: 9, maxLength: 11, placeholder: '9 to 11 digits' },
|
||||
{ code: '+852', label: '🇭🇰 +852', country: 'Hong Kong', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||
{ code: '+886', label: '🇹🇼 +886', country: 'Taiwan', 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' },
|
||||
{ code: '+60', label: '🇲🇾 +60', country: 'Malaysia', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
|
||||
{ code: '+62', label: '🇮🇩 +62', country: 'Indonesia', currency: 'USD', minLength: 9, maxLength: 12, placeholder: '9 to 12 digits' },
|
||||
{ code: '+63', label: '🇵🇭 +63', country: 'Philippines', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||
{ code: '+66', label: '🇹🇭 +66', country: 'Thailand', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+84', label: '🇻🇳 +84', country: 'Vietnam', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
|
||||
{ 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
|
||||
{ code: '+971', label: '🇦🇪 +971', country: 'UAE', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+966', label: '🇸🇦 +966', country: 'Saudi Arabia', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+974', label: '🇶🇦 +974', country: 'Qatar', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||
{ code: '+965', label: '🇰🇼 +965', country: 'Kuwait', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||
{ code: '+968', label: '🇴🇲 +968', country: 'Oman', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||
{ code: '+973', label: '🇧🇭 +973', country: 'Bahrain', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||
{ code: '+972', label: '🇮🇱 +972', country: 'Israel', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+962', label: '🇯🇴 +962', country: 'Jordan', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+961', label: '🇱🇧 +961', country: 'Lebanon', currency: 'USD', minLength: 7, maxLength: 8, placeholder: '7 to 8 digits' },
|
||||
{ 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
|
||||
{ code: '+55', label: '🇧🇷 +55', country: 'Brazil', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
|
||||
{ code: '+54', label: '🇦🇷 +54', country: 'Argentina', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
|
||||
{ code: '+56', label: '🇨🇱 +56', country: 'Chile', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+57', label: '🇨🇴 +57', country: 'Colombia', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||
{ code: '+51', label: '🇵🇪 +51', country: 'Peru', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ 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
|
||||
{ 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' },
|
||||
{ code: '+254', label: '🇰🇪 +254', country: 'Kenya', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+233', label: '🇬🇭 +233', country: 'Ghana', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+20', label: '🇪🇬 +20', country: 'Egypt', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||
{ code: '+212', label: '🇲🇦 +212', country: 'Morocco', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||
{ code: '+230', label: '🇲🇺 +230', country: 'Mauritius', currency: 'USD', minLength: 7, maxLength: 8, placeholder: '7 to 8 digits' },
|
||||
{ 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)
|
||||
|
|
@ -105,29 +115,23 @@ export const SORTED_COUNTRY_CODES: CountryCode[] = [...COUNTRY_CODES].sort((a, b
|
|||
|
||||
export const DEFAULT_COUNTRY = COUNTRY_CODES[0]; // India (+91)
|
||||
|
||||
export const getCountryRuleByDialCode = (dialCode: string): CountryCode => {
|
||||
return (
|
||||
COUNTRY_CODES.find((c) => c.code === dialCode) || {
|
||||
code: dialCode,
|
||||
label: dialCode,
|
||||
country: 'Other',
|
||||
currency: 'USD',
|
||||
minLength: 7,
|
||||
maxLength: 15,
|
||||
placeholder: 'Phone number',
|
||||
}
|
||||
);
|
||||
export const getCountryRuleByIso = (iso?: string | null): CountryCode => {
|
||||
if (!iso) return DEFAULT_COUNTRY;
|
||||
const upper = iso.toUpperCase().trim();
|
||||
return COUNTRY_CODES.find((c) => c.iso2 === upper) || DEFAULT_COUNTRY;
|
||||
};
|
||||
|
||||
export const getCountryRuleByName = (countryName: string): CountryCode => {
|
||||
export const getCountryRuleByName = (countryName?: string | null): CountryCode => {
|
||||
if (!countryName) return DEFAULT_COUNTRY;
|
||||
const normalized = countryName.toLowerCase().trim();
|
||||
return (
|
||||
COUNTRY_CODES.find(
|
||||
(c) =>
|
||||
c.country.toLowerCase() === normalized ||
|
||||
c.iso2.toLowerCase() === normalized ||
|
||||
normalized.includes(c.country.toLowerCase())
|
||||
) || {
|
||||
iso2: 'IN',
|
||||
code: '+91',
|
||||
label: '🇮🇳 +91',
|
||||
country: countryName,
|
||||
|
|
@ -138,3 +142,26 @@ export const getCountryRuleByName = (countryName: string): CountryCode => {
|
|||
}
|
||||
);
|
||||
};
|
||||
|
||||
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,
|
||||
placeholder: 'Phone number',
|
||||
}
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ export const CURRICULUM_MODULES: ModuleItem[] = [
|
|||
// 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_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
|
||||
{ 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' }
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ export interface ModuleItem {
|
|||
desc: string;
|
||||
color: string;
|
||||
isRenewal?: boolean;
|
||||
sortOrder?: number;
|
||||
planType?: string;
|
||||
}
|
||||
|
||||
export interface UserSubscription {
|
||||
|
|
@ -37,6 +39,7 @@ export interface UserProfile {
|
|||
roles?: string[];
|
||||
external_ref?: string;
|
||||
active_subscriptions: UserSubscription[];
|
||||
unlocked_module_codes?: string[];
|
||||
unlocked_module_slugs?: string[];
|
||||
created_at?: string;
|
||||
}
|
||||
|
|
@ -76,15 +79,27 @@ export interface PublicPlan {
|
|||
code: string;
|
||||
base_code?: string;
|
||||
name: string;
|
||||
plan_type?: string;
|
||||
billing_period?: string;
|
||||
price_inr?: number;
|
||||
price_usd?: number;
|
||||
price_eur?: number;
|
||||
is_active?: boolean;
|
||||
pricing_status?: string;
|
||||
color?: string;
|
||||
badge_text?: string;
|
||||
heading?: string;
|
||||
subtitle?: 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[];
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -1,4 +1,24 @@
|
|||
import { COUNTRY_CODES, 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
|
||||
|
|
@ -15,8 +35,8 @@ export const cleanPhoneInput = (text: string, maxLength = 15, allowPlus = true):
|
|||
};
|
||||
|
||||
/**
|
||||
* Validates phone number according to country rules (e.g. India = exactly 10 digits)
|
||||
* Strictly disallows alphabetic characters and invalid symbols
|
||||
* 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 = (
|
||||
val?: string | null,
|
||||
|
|
@ -31,8 +51,8 @@ export const validatePhoneNumber = (
|
|||
return 'Phone number cannot contain alphabetic characters.';
|
||||
}
|
||||
|
||||
// Strictly disallow hyphens, dashes, and invalid characters
|
||||
if (/[\-()_]/.test(trimmed)) {
|
||||
// Strictly disallow hyphens, dashes, and invalid symbols
|
||||
if (/[\-_()/[\]]/.test(trimmed)) {
|
||||
return 'Phone number cannot contain hyphens or special symbols.';
|
||||
}
|
||||
|
||||
|
|
@ -46,69 +66,71 @@ export const validatePhoneNumber = (
|
|||
return 'Please enter a valid phone number with numeric digits.';
|
||||
}
|
||||
|
||||
// Resolve country rule by dial code or country name
|
||||
let rule = dialCode ? getCountryRuleByDialCode(dialCode) : undefined;
|
||||
if ((!rule || rule.country === 'Other') && country) {
|
||||
rule = getCountryRuleByName(country);
|
||||
// Resolve country rule: prioritize explicit country name, fallback to dialCode
|
||||
let rule = country ? getCountryRuleByName(country) : undefined;
|
||||
if ((!rule || rule.country === 'Other') && dialCode) {
|
||||
rule = getCountryRuleByDialCode(dialCode, country);
|
||||
}
|
||||
// If still not found and input starts with '+', match from COUNTRY_CODES
|
||||
if (!rule && trimmed.startsWith('+')) {
|
||||
const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length);
|
||||
rule = sorted.find((c) => trimmed.startsWith(c.code));
|
||||
if (!rule) {
|
||||
rule = DEFAULT_COUNTRY;
|
||||
}
|
||||
// Default to India if no specific rule resolved and dial code is +91 or country is India
|
||||
if (!rule || rule.country === 'Other') {
|
||||
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') {
|
||||
const dialDigits = rule.code.replace(/\D/g, '');
|
||||
let localDigits = allDigits;
|
||||
|
||||
if (trimmed.startsWith('+')) {
|
||||
// Input includes country code prefix (e.g. +919876543210 or +9198765432)
|
||||
// Must strip the dial code to extract the actual local number
|
||||
if (allDigits.startsWith(dialDigits)) {
|
||||
localDigits = allDigits.slice(dialDigits.length);
|
||||
}
|
||||
} else if (allDigits.length > rule.maxLength && allDigits.startsWith(dialDigits)) {
|
||||
// Input was formatted with dial digits without '+' and exceeds local maxLength (e.g. 919876543210)
|
||||
localDigits = allDigits.slice(dialDigits.length);
|
||||
// 2. Generic prefix validation for mobile telecom numbering plans
|
||||
if (rule.validPrefixes && rule.validPrefixes.length > 0) {
|
||||
const hasValidPrefix = rule.validPrefixes.some(
|
||||
(prefix) => digitsWithoutTrunk0.startsWith(prefix) || nationalDigits.startsWith(prefix)
|
||||
);
|
||||
if (!hasValidPrefix) {
|
||||
return `For ${rule.country}, the mobile number must start with ${formatPrefixList(rule.validPrefixes)}.`;
|
||||
}
|
||||
}
|
||||
|
||||
if (rule.minLength === rule.maxLength) {
|
||||
if (localDigits.length !== rule.minLength) {
|
||||
return `${rule.country} phone number must be exactly ${rule.minLength} digits.`;
|
||||
}
|
||||
} else {
|
||||
if (localDigits.length < rule.minLength) {
|
||||
return `${rule.country} phone number must be at least ${rule.minLength} digits.`;
|
||||
}
|
||||
if (localDigits.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).`;
|
||||
}
|
||||
|
||||
// Specific country telecom prefix rules
|
||||
if (dialDigits === '91' || rule.country === 'India') {
|
||||
if (!/^[6-9]/.test(localDigits)) {
|
||||
return 'India mobile number must begin with 6, 7, 8, or 9.';
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// General fallback ITU E.164
|
||||
if (allDigits.length < 7) {
|
||||
return 'Phone number must contain at least 7 digits.';
|
||||
}
|
||||
if (allDigits.length > 15) {
|
||||
return 'Phone number cannot exceed 15 digits.';
|
||||
}
|
||||
return null;
|
||||
const exampleStr = rule.example || rule.placeholder;
|
||||
return `Please enter a valid mobile number for ${rule.country}${exampleStr ? ` (e.g. ${exampleStr})` : ''}.`;
|
||||
};
|
||||
|
||||
export const isValidPhoneNumber = (
|
||||
|
|
@ -125,15 +147,47 @@ export const isValidPhoneNumber = (
|
|||
export const parsePhoneNumber = (
|
||||
fullPhone?: string | null,
|
||||
fallbackCountry = 'India'
|
||||
): { country: string; dialCode: string; localDigits: string } => {
|
||||
const defaultRule = getCountryRuleByName(fallbackCountry) || getCountryRuleByDialCode('+91')!;
|
||||
): { 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: '' };
|
||||
return {
|
||||
country: defaultRule.country,
|
||||
dialCode: defaultRule.code,
|
||||
localDigits: '',
|
||||
iso2: defaultRule.iso2,
|
||||
};
|
||||
}
|
||||
const trimmed = fullPhone.trim();
|
||||
|
||||
// Try matching dial code prefixes from longest to shortest
|
||||
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, '');
|
||||
|
|
@ -141,34 +195,44 @@ export const parsePhoneNumber = (
|
|||
country: matched.country,
|
||||
dialCode: matched.code,
|
||||
localDigits: rawLocal.slice(0, matched.maxLength),
|
||||
iso2: matched.iso2,
|
||||
};
|
||||
}
|
||||
|
||||
// If no '+' prefix, check if digits start with fallback country dial digits and exceed national length
|
||||
const dialDigits = defaultRule.code.replace(/\D/g, '');
|
||||
const rawDigits = trimmed.replace(/\D/g, '');
|
||||
let local = rawDigits;
|
||||
if (
|
||||
dialDigits &&
|
||||
rawDigits.startsWith(dialDigits) &&
|
||||
rawDigits.length > defaultRule.maxLength
|
||||
) {
|
||||
local = rawDigits.slice(dialDigits.length);
|
||||
}
|
||||
return {
|
||||
country: defaultRule.country,
|
||||
dialCode: defaultRule.code,
|
||||
localDigits: local.slice(0, defaultRule.maxLength),
|
||||
localDigits: rawDigits.slice(0, defaultRule.maxLength),
|
||||
iso2: defaultRule.iso2,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Formats full phone number cleanly as E.164 without spaces (+<dialCode><digits>)
|
||||
* 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): string => {
|
||||
const digits = localDigits.replace(/\D/g, '');
|
||||
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}`;
|
||||
return digits ? `${code}${digits}` : '';
|
||||
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}`;
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
@ -186,27 +250,8 @@ export const updatePhoneDialCode = (
|
|||
const oldRule = getCountryRuleByName(oldCountry);
|
||||
const newRule = getCountryRuleByName(newCountry);
|
||||
|
||||
let nationalDigits = '';
|
||||
if (trimmed.startsWith('+')) {
|
||||
const matched = [...COUNTRY_CODES]
|
||||
.sort((a, b) => b.code.length - a.code.length)
|
||||
.find((c) => trimmed.startsWith(c.code));
|
||||
if (matched) {
|
||||
nationalDigits = trimmed.slice(matched.code.length).replace(/\D/g, '');
|
||||
} else {
|
||||
nationalDigits = trimmed.replace(/^\+/, '').replace(/\D/g, '');
|
||||
}
|
||||
} else {
|
||||
const oldDialDigits = oldRule.code.replace(/\D/g, '');
|
||||
const rawDigits = trimmed.replace(/\D/g, '');
|
||||
if (oldDialDigits && rawDigits.startsWith(oldDialDigits) && rawDigits.length > oldDialDigits.length) {
|
||||
nationalDigits = rawDigits.slice(oldDialDigits.length);
|
||||
} else {
|
||||
nationalDigits = rawDigits;
|
||||
}
|
||||
}
|
||||
|
||||
const bounded = nationalDigits.slice(0, newRule.maxLength);
|
||||
const parsed = parsePhoneNumber(trimmed, oldRule.country);
|
||||
const bounded = parsed.localDigits.slice(0, newRule.maxLength);
|
||||
return bounded ? `${newRule.code} ${bounded}` : `${newRule.code} `;
|
||||
};
|
||||
|
||||
|
|
@ -248,8 +293,6 @@ export const validatePassword = (password: string, fieldName = 'Password'): stri
|
|||
|
||||
/**
|
||||
* RFC 5322 & RFC 1035 compliant email validation regex.
|
||||
* Disallows invalid domain characters (e.g. + in domain like +gmail+.com, consecutive dots, leading/trailing hyphens)
|
||||
* while properly accepting plus-addressing in local-part (e.g. sanskar+sarak@gmail.com).
|
||||
*/
|
||||
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,}$/;
|
||||
|
||||
|
|
@ -266,4 +309,3 @@ export const validateEmail = (email?: string | null): string | null => {
|
|||
export const isValidEmail = (email?: string | null): boolean => {
|
||||
return validateEmail(email) === null;
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -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),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
@ -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/');
|
||||
});
|
||||
});
|
||||
|
|
@ -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');
|
||||
});
|
||||
});
|
||||
|
|
@ -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');
|
||||
});
|
||||
});
|
||||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
@ -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');
|
||||
});
|
||||
});
|
||||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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 });
|
||||
});
|
||||
});
|
||||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
@ -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',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -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);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import '@testing-library/jest-dom/vitest';
|
||||
import { cleanup } from '@testing-library/react';
|
||||
import { afterEach } from 'vitest';
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
|
@ -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');
|
||||
});
|
||||
});
|
||||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -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,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
Loading…
Reference in New Issue