Compare commits
No commits in common. "main" and "fix/email-format-validation" have entirely different histories.
main
...
fix/email-
|
|
@ -31,8 +31,3 @@ dist-ssr
|
||||||
# Generated Git Info
|
# Generated Git Info
|
||||||
.git_*_info
|
.git_*_info
|
||||||
|
|
||||||
# Playwright & Coverage
|
|
||||||
playwright-report/
|
|
||||||
test-results/
|
|
||||||
coverage/
|
|
||||||
|
|
||||||
|
|
|
||||||
53
TESTING.md
53
TESTING.md
|
|
@ -1,53 +0,0 @@
|
||||||
# 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,45 +7,30 @@
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "tsc -b && vite build",
|
"build": "tsc -b && vite build",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview"
|
||||||
"test": "vitest run",
|
|
||||||
"test:watch": "vitest",
|
|
||||||
"test:coverage": "vitest run --coverage",
|
|
||||||
"test:e2e": "playwright test",
|
|
||||||
"test:e2e:ui": "playwright test --ui",
|
|
||||||
"test:e2e:headed": "playwright test --headed",
|
|
||||||
"test:e2e:report": "playwright show-report"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^1.7.0",
|
"axios": "^1.7.0",
|
||||||
"libphonenumber-js": "^1.13.16",
|
|
||||||
"lucide-react": "^0.460.0",
|
"lucide-react": "^0.460.0",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0"
|
"react-dom": "^19.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.0.0",
|
"@eslint/js": "^9.0.0",
|
||||||
"@playwright/test": "^1.65.1",
|
|
||||||
"@tailwindcss/postcss": "^4.0.0",
|
"@tailwindcss/postcss": "^4.0.0",
|
||||||
"@testing-library/jest-dom": "^8.0.0",
|
|
||||||
"@testing-library/react": "^16.3.3",
|
|
||||||
"@testing-library/user-event": "^14.6.13",
|
|
||||||
"@types/node": "^22.0.0",
|
"@types/node": "^22.0.0",
|
||||||
"@types/react": "^19.0.0",
|
"@types/react": "^19.0.0",
|
||||||
"@types/react-dom": "^19.0.0",
|
"@types/react-dom": "^19.0.0",
|
||||||
"@vitejs/plugin-react": "^4.3.0",
|
"@vitejs/plugin-react": "^4.3.0",
|
||||||
"@vitest/coverage-v8": "^5.1.2",
|
|
||||||
"autoprefixer": "^10.4.0",
|
"autoprefixer": "^10.4.0",
|
||||||
"eslint": "^9.0.0",
|
"eslint": "^9.0.0",
|
||||||
"eslint-plugin-react-hooks": "^5.0.0",
|
"eslint-plugin-react-hooks": "^5.0.0",
|
||||||
"eslint-plugin-react-refresh": "^0.4.0",
|
"eslint-plugin-react-refresh": "^0.4.0",
|
||||||
"globals": "^15.0.0",
|
"globals": "^15.0.0",
|
||||||
"jsdom": "^31.0.1",
|
|
||||||
"postcss": "^8.4.0",
|
"postcss": "^8.4.0",
|
||||||
"tailwindcss": "^4.0.0",
|
"tailwindcss": "^4.0.0",
|
||||||
"typescript": "^5.8.0",
|
"typescript": "^5.8.0",
|
||||||
"typescript-eslint": "^8.0.0",
|
"typescript-eslint": "^8.0.0",
|
||||||
"vite": "^6.0.0",
|
"vite": "^6.0.0"
|
||||||
"vitest": "^5.1.2"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
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,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
495
src/App.tsx
495
src/App.tsx
|
|
@ -1,13 +1,12 @@
|
||||||
import { useState, useEffect, useMemo } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
|
|
||||||
import { CURRICULUM_MODULES } from './constants/modules';
|
import { CURRICULUM_MODULES } from './constants/modules';
|
||||||
import { buildDynamicCatalog } from './utils/catalog';
|
|
||||||
import { getCountryRuleByName } from './constants/countries';
|
import { getCountryRuleByName } from './constants/countries';
|
||||||
import type { ModuleItem, Currency, UserProfile, VerificationResult, PublicPlan } from './types';
|
import type { ModuleItem, Currency, UserProfile, VerificationResult, PublicPlan } from './types';
|
||||||
import { API_BASE } from './services/api';
|
import { API_BASE } from './services/api';
|
||||||
import { loadRazorpayScript } from './services/razorpay';
|
import { loadRazorpayScript } from './services/razorpay';
|
||||||
import { validatePhoneNumber, isValidPhoneNumber, validatePassword, parsePhoneNumber, formatE164Phone, validateEmail } from './utils/validation';
|
import { cleanPhoneInput, validatePhoneNumber, validatePassword, validateEmail } from './utils/validation';
|
||||||
|
|
||||||
// Modular Subcomponents
|
// Modular Subcomponents
|
||||||
import { StoreHeader } from './components/layout/StoreHeader';
|
import { StoreHeader } from './components/layout/StoreHeader';
|
||||||
|
|
@ -20,58 +19,32 @@ import { AuthModal } from './components/auth/AuthModal';
|
||||||
import { ProfileDrawer } from './components/auth/ProfileDrawer';
|
import { ProfileDrawer } from './components/auth/ProfileDrawer';
|
||||||
import { PaymentSuccessModal } from './components/checkout/PaymentSuccessModal';
|
import { PaymentSuccessModal } from './components/checkout/PaymentSuccessModal';
|
||||||
import { PasswordUpdatedModal } from './components/auth/PasswordUpdatedModal';
|
import { PasswordUpdatedModal } from './components/auth/PasswordUpdatedModal';
|
||||||
import { BillingPhoneModal } from './components/checkout/BillingPhoneModal';
|
|
||||||
import { LoggedOutView } from './components/auth/LoggedOutView';
|
|
||||||
import { openMobileApp, DEFAULT_RETURN_ROUTE } from './utils/navigation';
|
import { openMobileApp, DEFAULT_RETURN_ROUTE } from './utils/navigation';
|
||||||
|
|
||||||
const getInitialTab = (): 'storefront' | 'subscriptions' | 'logged-out' => {
|
const getInitialTab = (): 'storefront' | 'subscriptions' => {
|
||||||
if (typeof window !== 'undefined') {
|
if (typeof window !== 'undefined') {
|
||||||
const path = window.location.pathname.toLowerCase();
|
const path = window.location.pathname.toLowerCase();
|
||||||
if (path.includes('/logged-out')) return 'logged-out';
|
|
||||||
if (path.includes('/subscriptions')) return 'subscriptions';
|
if (path.includes('/subscriptions')) return 'subscriptions';
|
||||||
|
|
||||||
const params = new URLSearchParams(window.location.search);
|
|
||||||
if (params.get('logged_out') === 'true' || params.get('status') === 'logged-out') {
|
|
||||||
return 'logged-out';
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return 'storefront';
|
return 'storefront';
|
||||||
};
|
};
|
||||||
|
|
||||||
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' };
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
const [activeTab, setActiveTab] = useState<'storefront' | 'subscriptions' | 'logged-out'>(getInitialTab);
|
const [activeTab, setActiveTab] = useState<'storefront' | 'subscriptions'>(getInitialTab);
|
||||||
|
|
||||||
const switchTab = (tab: 'storefront' | 'subscriptions' | 'logged-out') => {
|
const switchTab = (tab: 'storefront' | 'subscriptions') => {
|
||||||
setActiveTab(tab);
|
setActiveTab(tab);
|
||||||
if (typeof window !== 'undefined') {
|
if (typeof window !== 'undefined') {
|
||||||
const isStorePrefix = window.location.pathname.startsWith('/store');
|
const isStorePrefix = window.location.pathname.startsWith('/store');
|
||||||
const basePath = isStorePrefix ? '/store/' : '/';
|
const basePath = isStorePrefix ? '/store' : '';
|
||||||
const newPath = tab === 'storefront' ? basePath : `${basePath}${tab}`;
|
const newPath = tab === 'storefront' ? (basePath || '/') : (basePath + '/' + tab);
|
||||||
if (window.location.pathname !== newPath) {
|
if (window.location.pathname !== newPath) {
|
||||||
window.history.pushState({ tab }, '', newPath);
|
window.history.pushState({ tab }, '', newPath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const initialRegion = useMemo(getInitialRegion, []);
|
const [currency, setCurrency] = useState<Currency>('INR');
|
||||||
const [currency, setCurrency] = useState<Currency>(initialRegion.currency);
|
|
||||||
|
|
||||||
// Auth state
|
// Auth state
|
||||||
const [userToken, setUserToken] = useState<string | null>(localStorage.getItem('access_token'));
|
const [userToken, setUserToken] = useState<string | null>(localStorage.getItem('access_token'));
|
||||||
|
|
@ -94,23 +67,13 @@ export default function App() {
|
||||||
const [changePasswordError, setChangePasswordError] = useState<string | null>(null);
|
const [changePasswordError, setChangePasswordError] = useState<string | null>(null);
|
||||||
const [changePasswordSuccess, setChangePasswordSuccess] = useState<boolean>(false);
|
const [changePasswordSuccess, setChangePasswordSuccess] = useState<boolean>(false);
|
||||||
|
|
||||||
// Auto-clear change password success banner after 4 seconds
|
|
||||||
useEffect(() => {
|
|
||||||
if (changePasswordSuccess) {
|
|
||||||
const timer = setTimeout(() => {
|
|
||||||
setChangePasswordSuccess(false);
|
|
||||||
}, 4000);
|
|
||||||
return () => clearTimeout(timer);
|
|
||||||
}
|
|
||||||
}, [changePasswordSuccess]);
|
|
||||||
|
|
||||||
// Auth Form State
|
// Auth Form State
|
||||||
const [authEmail, setAuthEmail] = useState('');
|
const [authEmail, setAuthEmail] = useState('');
|
||||||
const [authPassword, setAuthPassword] = useState('');
|
const [authPassword, setAuthPassword] = useState('');
|
||||||
const [authDisplayName, setAuthDisplayName] = useState('');
|
const [authDisplayName, setAuthDisplayName] = useState('');
|
||||||
const [authPhone, setAuthPhone] = useState('');
|
const [authPhone, setAuthPhone] = useState('');
|
||||||
const [authDialCode, setAuthDialCode] = useState(initialRegion.dialCode);
|
const [authDialCode, setAuthDialCode] = useState('+91');
|
||||||
const [authCountry, setAuthCountry] = useState(initialRegion.country);
|
const [authCountry, setAuthCountry] = useState('India');
|
||||||
const [authLoading, setAuthLoading] = useState(false);
|
const [authLoading, setAuthLoading] = useState(false);
|
||||||
const [authError, setAuthError] = useState<string | null>(null);
|
const [authError, setAuthError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
|
@ -173,64 +136,80 @@ export default function App() {
|
||||||
const [profileError, setProfileError] = useState<string | null>(null);
|
const [profileError, setProfileError] = useState<string | null>(null);
|
||||||
const [profileSuccess, setProfileSuccess] = useState<boolean>(false);
|
const [profileSuccess, setProfileSuccess] = useState<boolean>(false);
|
||||||
|
|
||||||
// Billing Contact Phone Modal State
|
// Dynamic Public Storefront Plans
|
||||||
const [showBillingPhoneModal, setShowBillingPhoneModal] = useState<boolean>(false);
|
|
||||||
const [pendingCheckoutAfterPhone, setPendingCheckoutAfterPhone] = useState<boolean>(false);
|
|
||||||
|
|
||||||
// Dynamic Public Storefront Plans & Modules
|
|
||||||
const [publicPlans, setPublicPlans] = useState<PublicPlan[]>([]);
|
const [publicPlans, setPublicPlans] = useState<PublicPlan[]>([]);
|
||||||
const [apiModules, setApiModules] = useState<any[]>([]);
|
|
||||||
const [pendingUrlPlanCode, setPendingUrlPlanCode] = useState<string | null>(null);
|
|
||||||
const [plansLoaded, setPlansLoaded] = useState<boolean>(false);
|
|
||||||
|
|
||||||
const fetchPublicPlans = async () => {
|
const fetchPublicPlans = async () => {
|
||||||
try {
|
try {
|
||||||
const res = await axios.get(`${API_BASE}/api/plans`);
|
const res = await axios.get(`${API_BASE}/api/plans`);
|
||||||
if (Array.isArray(res.data)) {
|
if (Array.isArray(res.data)) {
|
||||||
setPublicPlans(res.data);
|
setPublicPlans(res.data);
|
||||||
setPlansLoaded(true);
|
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to load public plans:', err);
|
console.error('Failed to load public plans:', err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Dynamic Curriculum Modules derived from /api/plans + /api/contents/modules
|
// Dynamic Curriculum Modules with Live Categories
|
||||||
const [curriculumModules, setCurriculumModules] = useState<ModuleItem[]>(CURRICULUM_MODULES);
|
const [curriculumModules, setCurriculumModules] = useState<ModuleItem[]>(CURRICULUM_MODULES);
|
||||||
|
|
||||||
const fetchModuleCategories = async () => {
|
const fetchModuleCategories = async () => {
|
||||||
try {
|
try {
|
||||||
const res = await axios.get(`${API_BASE}/api/contents/modules`);
|
const res = await axios.get(`${API_BASE}/api/contents/modules`);
|
||||||
const mods: any[] = Array.isArray(res.data) ? res.data : (res.data?.modules || []);
|
const apiModules: any[] = res.data?.modules || [];
|
||||||
if (mods.length > 0) {
|
if (apiModules.length > 0) {
|
||||||
setApiModules(mods);
|
const normalizeCategory = (cat?: string) => {
|
||||||
|
if (!cat) return null;
|
||||||
|
const c = cat.toLowerCase();
|
||||||
|
if (c === 'point' || c === 'points') return 'Points';
|
||||||
|
if (c === 'pattern' || c === 'patterns') return 'Pattern';
|
||||||
|
if (c === 'nutrition') return 'Nutrition';
|
||||||
|
if (c === 'therapeutics' || c === 'therapeutic') return 'Therapeutics';
|
||||||
|
return cat;
|
||||||
|
};
|
||||||
|
|
||||||
|
setCurriculumModules((prev) =>
|
||||||
|
prev.map((item) => {
|
||||||
|
const matched = apiModules.find((m) => {
|
||||||
|
const mCode = (m.code || '').toLowerCase();
|
||||||
|
const iCode = (item.code || '').toLowerCase();
|
||||||
|
if (mCode && iCode && mCode === iCode) return true;
|
||||||
|
const slug = (m.slug || '').toLowerCase();
|
||||||
|
const mName = (m.name || '').toLowerCase();
|
||||||
|
const iName = item.name.toLowerCase();
|
||||||
|
|
||||||
|
const cleanI = iName.replace('points:', '').replace('therapeutics:', '').split('(')[0].trim();
|
||||||
|
const cleanM = mName.replace('points:', '').replace('therapeutics:', '').split('(')[0].trim();
|
||||||
|
|
||||||
|
if (cleanI.includes('acu') && cleanM.includes('acupuncture') && !cleanI.includes('scalp') && !cleanI.includes('ear')) return true;
|
||||||
|
if (cleanI.includes('scalp') && cleanM.includes('scalp')) return true;
|
||||||
|
if (cleanI.includes('ear') && (cleanM.includes('ear') || slug.includes('auriculo'))) return true;
|
||||||
|
if (cleanI.includes('gyneco') && slug.includes('gyneco')) return true;
|
||||||
|
if (cleanI.includes('eight') && slug.includes('eight')) return true;
|
||||||
|
if (cleanI.includes('zang') && slug.includes('tcm-pattern')) return true;
|
||||||
|
if (cleanI.includes('qi') && slug.includes('qi')) return true;
|
||||||
|
if (cleanI.includes('pathogenic') && slug.includes('pathogenic')) return true;
|
||||||
|
if (cleanI.includes('six') && slug.includes('six')) return true;
|
||||||
|
if (cleanI.includes('four') && slug.includes('four')) return true;
|
||||||
|
if (cleanI.includes('three') && slug.includes('three')) return true;
|
||||||
|
if (cleanI.includes('five') && slug.includes('five')) return true;
|
||||||
|
if (cleanI.includes('food') && slug.includes('nutrition')) return true;
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
|
||||||
|
const updatedCat = normalizeCategory(matched?.metadata?.category || matched?.category);
|
||||||
|
if (updatedCat) {
|
||||||
|
return { ...item, category: updatedCat };
|
||||||
|
}
|
||||||
|
return item;
|
||||||
|
})
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to load module categories:', err);
|
console.error('Failed to load module categories:', err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (publicPlans.length > 0) {
|
|
||||||
setCurriculumModules(buildDynamicCatalog(publicPlans, apiModules));
|
|
||||||
}
|
|
||||||
}, [publicPlans, apiModules]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!pendingUrlPlanCode) return;
|
|
||||||
const targetModule = curriculumModules.find(
|
|
||||||
(m) => m.code.toUpperCase() === pendingUrlPlanCode,
|
|
||||||
);
|
|
||||||
if (targetModule) {
|
|
||||||
setCart([targetModule]);
|
|
||||||
setShowLockedByCategory((prev) => ({
|
|
||||||
...prev,
|
|
||||||
[targetModule.category]: true,
|
|
||||||
}));
|
|
||||||
setPendingUrlPlanCode(null);
|
|
||||||
}
|
|
||||||
}, [pendingUrlPlanCode, curriculumModules]);
|
|
||||||
|
|
||||||
|
|
||||||
const getLivePlan = (code: string) => {
|
const getLivePlan = (code: string) => {
|
||||||
return publicPlans.find(p => p.code === code || p.base_code === code);
|
return publicPlans.find(p => p.code === code || p.base_code === code);
|
||||||
|
|
@ -239,49 +218,28 @@ export default function App() {
|
||||||
const getModulePrice = (item: ModuleItem) => {
|
const getModulePrice = (item: ModuleItem) => {
|
||||||
const livePlan = getLivePlan(item.code);
|
const livePlan = getLivePlan(item.code);
|
||||||
if (livePlan) {
|
if (livePlan) {
|
||||||
const priceInr = livePlan.price_inr ?? 0;
|
|
||||||
const priceUsd = livePlan.price_usd ?? 0;
|
|
||||||
const priceEur = livePlan.price_eur ?? livePlan.price_usd ?? 0;
|
|
||||||
const activeCurrencyPrice =
|
|
||||||
currency === 'INR' ? priceInr : currency === 'EUR' ? priceEur : priceUsd;
|
|
||||||
const planIsActive = livePlan.is_active !== undefined ? livePlan.is_active : true;
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
priceInr: livePlan.price_inr ?? item.priceInr,
|
priceInr: livePlan.price_inr ?? item.priceInr,
|
||||||
priceUsd: livePlan.price_usd ?? item.priceUsd,
|
priceUsd: livePlan.price_usd ?? item.priceUsd,
|
||||||
priceEur: livePlan.price_eur ?? livePlan.price_usd ?? item.priceEur,
|
priceEur: item.priceEur,
|
||||||
// Require active flag and a positive price in the user's billing currency
|
isActive: livePlan.is_active !== undefined ? livePlan.is_active : true,
|
||||||
isActive: planIsActive && activeCurrencyPrice > 0,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
priceInr: item.priceInr,
|
priceInr: item.priceInr,
|
||||||
priceUsd: item.priceUsd,
|
priceUsd: item.priceUsd,
|
||||||
priceEur: item.priceEur,
|
priceEur: item.priceEur,
|
||||||
// Once /api/plans has loaded, catalog plans absent from it are inactive in the DB
|
isActive: true,
|
||||||
isActive: !plansLoaded,
|
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
// Load configuration & user profile on startup
|
// Load configuration & user profile on startup
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Normalize URL if opened at /store without trailing slash
|
|
||||||
if (typeof window !== 'undefined' && window.location.pathname === '/store') {
|
|
||||||
const normalizedPath = '/store/' + (window.location.search || '') + (window.location.hash || '');
|
|
||||||
window.history.replaceState(window.history.state, document.title, normalizedPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
const params = new URLSearchParams(window.location.search);
|
const params = new URLSearchParams(window.location.search);
|
||||||
const urlToken = params.get('token');
|
const urlToken = params.get('token');
|
||||||
const urlPlanCode = params.get('planCode');
|
const urlPlanCode = params.get('planCode');
|
||||||
const urlReturnRoute = params.get('returnRoute') || params.get('redirectPath') || params.get('redirect');
|
const urlReturnRoute = params.get('returnRoute') || params.get('redirectPath') || params.get('redirect');
|
||||||
const urlScheme = params.get('scheme');
|
const urlScheme = params.get('scheme');
|
||||||
const shouldOpenLogin = params.get('login') === 'true' || params.get('auth') === 'login';
|
|
||||||
|
|
||||||
if (shouldOpenLogin) {
|
|
||||||
setAuthMode('login');
|
|
||||||
setShowAuthModal(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (urlReturnRoute) {
|
if (urlReturnRoute) {
|
||||||
setReturnRoute(urlReturnRoute);
|
setReturnRoute(urlReturnRoute);
|
||||||
|
|
@ -290,41 +248,29 @@ export default function App() {
|
||||||
setAppScheme(urlScheme);
|
setAppScheme(urlScheme);
|
||||||
}
|
}
|
||||||
|
|
||||||
let activeToken = urlToken || localStorage.getItem('access_token');
|
let activeToken = userToken;
|
||||||
|
|
||||||
if (urlToken) {
|
if (urlToken) {
|
||||||
localStorage.setItem('access_token', urlToken);
|
localStorage.setItem('access_token', urlToken);
|
||||||
setUserToken(urlToken);
|
setUserToken(urlToken);
|
||||||
|
activeToken = urlToken;
|
||||||
fetchUserProfile(urlToken);
|
fetchUserProfile(urlToken);
|
||||||
setShowAuthModal(false);
|
|
||||||
} else if (activeToken) {
|
|
||||||
fetchUserProfile(activeToken);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (urlPlanCode) {
|
if (urlPlanCode) {
|
||||||
const normalizedPlanCode = urlPlanCode.trim().toUpperCase();
|
const targetModule = curriculumModules.find(m => m.code === urlPlanCode);
|
||||||
const targetModule = curriculumModules.find(m => m.code.toUpperCase() === normalizedPlanCode);
|
|
||||||
if (targetModule) {
|
if (targetModule) {
|
||||||
setCart([targetModule]);
|
setCart([targetModule]);
|
||||||
setShowLockedByCategory(prev => ({
|
setShowLockedByCategory(prev => ({
|
||||||
...prev,
|
...prev,
|
||||||
[targetModule.category]: true
|
[targetModule.category]: true
|
||||||
}));
|
}));
|
||||||
} else {
|
|
||||||
setPendingUrlPlanCode(normalizedPlanCode);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (urlToken || urlPlanCode || shouldOpenLogin) {
|
if (urlToken || urlPlanCode) {
|
||||||
const isStorePrefix = window.location.pathname.startsWith('/store');
|
const newUrl = window.location.pathname;
|
||||||
const basePath = isStorePrefix ? '/store/' : '/';
|
window.history.replaceState({}, document.title, newUrl);
|
||||||
const cleanPath =
|
|
||||||
activeTab === 'subscriptions'
|
|
||||||
? `${basePath}subscriptions`
|
|
||||||
: activeTab === 'logged-out'
|
|
||||||
? `${basePath}logged-out`
|
|
||||||
: basePath;
|
|
||||||
window.history.replaceState({}, document.title, cleanPath);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch public Razorpay Config
|
// Fetch public Razorpay Config
|
||||||
|
|
@ -338,7 +284,16 @@ export default function App() {
|
||||||
|
|
||||||
fetchPublicPlans();
|
fetchPublicPlans();
|
||||||
fetchModuleCategories();
|
fetchModuleCategories();
|
||||||
}, []);
|
|
||||||
|
if (activeToken && !urlToken) {
|
||||||
|
fetchUserProfile(activeToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!activeToken && !urlToken) {
|
||||||
|
setAuthMode('login');
|
||||||
|
setShowAuthModal(true);
|
||||||
|
}
|
||||||
|
}, [userToken]);
|
||||||
|
|
||||||
// Recalculate price whenever cart, coupon, currency, or logged-in user changes
|
// Recalculate price whenever cart, coupon, currency, or logged-in user changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
@ -369,7 +324,6 @@ export default function App() {
|
||||||
const mergedUser = {
|
const mergedUser = {
|
||||||
...profileRes.data,
|
...profileRes.data,
|
||||||
active_subscriptions: accessRes.data.active_subscriptions || [],
|
active_subscriptions: accessRes.data.active_subscriptions || [],
|
||||||
unlocked_module_codes: accessRes.data.unlocked_module_codes || [],
|
|
||||||
unlocked_module_slugs: accessRes.data.unlocked_module_slugs || [],
|
unlocked_module_slugs: accessRes.data.unlocked_module_slugs || [],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -381,22 +335,11 @@ export default function App() {
|
||||||
setCurrency(countryRule.currency);
|
setCurrency(countryRule.currency);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to fetch user profile:', err);
|
console.error('Failed to fetch user profile:', err);
|
||||||
// Clear invalid/stale token silently so expired storage does not hijack initial storefront load into /logged-out.
|
handleLogout();
|
||||||
resetAuthSession();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCloseProfileDrawer = () => {
|
const handleLogout = () => {
|
||||||
setShowProfileDrawer(false);
|
|
||||||
setShowPasswordChange(false);
|
|
||||||
setChangePasswordError(null);
|
|
||||||
setChangePasswordSuccess(false);
|
|
||||||
setChangeOldPassword('');
|
|
||||||
setChangeNewPassword('');
|
|
||||||
setChangeConfirmPassword('');
|
|
||||||
};
|
|
||||||
|
|
||||||
const resetAuthSession = () => {
|
|
||||||
localStorage.removeItem('access_token');
|
localStorage.removeItem('access_token');
|
||||||
setUserToken(null);
|
setUserToken(null);
|
||||||
setLoggedInUser(null);
|
setLoggedInUser(null);
|
||||||
|
|
@ -404,19 +347,13 @@ export default function App() {
|
||||||
setAppliedCoupon(null);
|
setAppliedCoupon(null);
|
||||||
setCouponCode('');
|
setCouponCode('');
|
||||||
setPricingCalc(null);
|
setPricingCalc(null);
|
||||||
handleCloseProfileDrawer();
|
switchTab('storefront');
|
||||||
|
setShowProfileDrawer(false);
|
||||||
setProfileDisplayName('');
|
setProfileDisplayName('');
|
||||||
setProfilePhone('');
|
setProfilePhone('');
|
||||||
setProfileCountry(initialRegion.country);
|
setProfileCountry('India');
|
||||||
setCurrency(initialRegion.currency);
|
|
||||||
setProfileError(null);
|
setProfileError(null);
|
||||||
setProfileSuccess(false);
|
setProfileSuccess(false);
|
||||||
setShowAuthModal(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleLogout = () => {
|
|
||||||
resetAuthSession();
|
|
||||||
switchTab('logged-out');
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleUpdateProfile = async (e: React.FormEvent) => {
|
const handleUpdateProfile = async (e: React.FormEvent) => {
|
||||||
|
|
@ -428,14 +365,20 @@ export default function App() {
|
||||||
|
|
||||||
let cleanedPhoneToSave: string | null = null;
|
let cleanedPhoneToSave: string | null = null;
|
||||||
if (profilePhone && profilePhone.trim()) {
|
if (profilePhone && profilePhone.trim()) {
|
||||||
const parsed = parsePhoneNumber(profilePhone, profileCountry);
|
const phoneError = validatePhoneNumber(profilePhone, undefined, profileCountry);
|
||||||
const phoneError = validatePhoneNumber(parsed.localDigits, parsed.dialCode, profileCountry);
|
|
||||||
if (phoneError) {
|
if (phoneError) {
|
||||||
setProfileError(phoneError);
|
setProfileError(phoneError);
|
||||||
setProfileSaving(false);
|
setProfileSaving(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
cleanedPhoneToSave = formatE164Phone(parsed.dialCode, parsed.localDigits, profileCountry);
|
const rule = getCountryRuleByName(profileCountry);
|
||||||
|
const digitsOnly = profilePhone.trim().replace(/\D/g, '');
|
||||||
|
const dialDigits = rule.code.replace(/\D/g, '');
|
||||||
|
let localDigits = digitsOnly;
|
||||||
|
if (digitsOnly.startsWith(dialDigits) && digitsOnly.length > dialDigits.length) {
|
||||||
|
localDigits = digitsOnly.slice(dialDigits.length);
|
||||||
|
}
|
||||||
|
cleanedPhoneToSave = `${rule.code}${localDigits}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
@ -458,42 +401,6 @@ export default function App() {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSaveBillingPhone = async (phoneE164: string, country: string): Promise<boolean> => {
|
|
||||||
if (!userToken) return false;
|
|
||||||
try {
|
|
||||||
const res = await axios.put(`${API_BASE}/api/auth/profile`, {
|
|
||||||
phone_number: phoneE164,
|
|
||||||
country: country,
|
|
||||||
}, {
|
|
||||||
headers: { 'Authorization': `Bearer ${userToken}` }
|
|
||||||
});
|
|
||||||
if (res.data.status === 'success') {
|
|
||||||
if (loggedInUser) {
|
|
||||||
loggedInUser.phone_number = phoneE164;
|
|
||||||
loggedInUser.country = country;
|
|
||||||
setLoggedInUser({ ...loggedInUser });
|
|
||||||
}
|
|
||||||
setProfilePhone(phoneE164);
|
|
||||||
setProfileCountry(country);
|
|
||||||
const countryRule = getCountryRuleByName(country);
|
|
||||||
setCurrency(countryRule.currency);
|
|
||||||
setShowBillingPhoneModal(false);
|
|
||||||
if (pendingCheckoutAfterPhone) {
|
|
||||||
setPendingCheckoutAfterPhone(false);
|
|
||||||
setTimeout(() => {
|
|
||||||
handleCheckout();
|
|
||||||
}, 200);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
} catch (err: any) {
|
|
||||||
const errorMsg = err.response?.data?.detail || 'Failed to save billing phone number.';
|
|
||||||
alert(errorMsg);
|
|
||||||
throw new Error(errorMsg);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleAuthSubmit = async (e: React.FormEvent) => {
|
const handleAuthSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setAuthLoading(true);
|
setAuthLoading(true);
|
||||||
|
|
@ -528,7 +435,8 @@ export default function App() {
|
||||||
setAuthLoading(false);
|
setAuthLoading(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
fullPhone = formatE164Phone(authDialCode, authPhone, authCountry);
|
const rawDigits = authPhone.replace(/\D/g, '');
|
||||||
|
fullPhone = `${authDialCode}${rawDigits}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const endpoint = authMode === 'login' ? '/api/auth/login' : '/api/auth/register';
|
const endpoint = authMode === 'login' ? '/api/auth/login' : '/api/auth/register';
|
||||||
|
|
@ -565,15 +473,6 @@ export default function App() {
|
||||||
setAuthEmail('');
|
setAuthEmail('');
|
||||||
setAuthDisplayName('');
|
setAuthDisplayName('');
|
||||||
setAuthPhone('');
|
setAuthPhone('');
|
||||||
if (activeTab === 'logged-out') {
|
|
||||||
switchTab('storefront');
|
|
||||||
}
|
|
||||||
setShowPasswordChange(false);
|
|
||||||
setChangeOldPassword('');
|
|
||||||
setChangeNewPassword('');
|
|
||||||
setChangeConfirmPassword('');
|
|
||||||
setChangePasswordError(null);
|
|
||||||
setChangePasswordSuccess(false);
|
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setAuthError(err.response?.data?.detail || 'Authentication failed. Please check credentials.');
|
setAuthError(err.response?.data?.detail || 'Authentication failed. Please check credentials.');
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -601,7 +500,7 @@ export default function App() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (changeNewPassword !== changeConfirmPassword) {
|
if (changeNewPassword !== changeConfirmPassword) {
|
||||||
setChangePasswordError('Confirm password do not match.');
|
setChangePasswordError('New passwords do not match.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -616,8 +515,8 @@ export default function App() {
|
||||||
|
|
||||||
const userEmail = loggedInUser?.email || authEmail;
|
const userEmail = loggedInUser?.email || authEmail;
|
||||||
|
|
||||||
// Invalidate active session without navigating to the logged-out screen so user stays in place for re-auth
|
// Invalidate active session so re-authentication is required
|
||||||
resetAuthSession();
|
handleLogout();
|
||||||
setShowProfileDrawer(false);
|
setShowProfileDrawer(false);
|
||||||
|
|
||||||
// Pre-fill email and set auth mode to login for seamless re-auth
|
// Pre-fill email and set auth mode to login for seamless re-auth
|
||||||
|
|
@ -630,8 +529,7 @@ export default function App() {
|
||||||
setChangeNewPassword('');
|
setChangeNewPassword('');
|
||||||
setChangeConfirmPassword('');
|
setChangeConfirmPassword('');
|
||||||
setShowPasswordChange(false);
|
setShowPasswordChange(false);
|
||||||
setChangePasswordSuccess(false);
|
setChangePasswordSuccess(true);
|
||||||
setChangePasswordError(null);
|
|
||||||
setPasswordUpdatedPopup(true);
|
setPasswordUpdatedPopup(true);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
|
@ -708,40 +606,21 @@ export default function App() {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Keep cart synced with live plans: refresh prices and prune inactive/currency-unavailable plans
|
// Keep cart items dynamic prices updated when publicPlans are loaded
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!plansLoaded || cart.length === 0) return;
|
if (publicPlans.length > 0 && cart.length > 0) {
|
||||||
|
setCart(prev =>
|
||||||
const nextCart: ModuleItem[] = [];
|
prev.map(item => {
|
||||||
for (const item of cart) {
|
const live = getModulePrice(item);
|
||||||
const live = getModulePrice(item);
|
return {
|
||||||
if (!live.isActive) continue;
|
...item,
|
||||||
nextCart.push({
|
priceInr: live.priceInr,
|
||||||
...item,
|
priceUsd: live.priceUsd,
|
||||||
priceInr: live.priceInr,
|
};
|
||||||
priceUsd: live.priceUsd,
|
})
|
||||||
priceEur: live.priceEur,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
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]);
|
}, [publicPlans]);
|
||||||
|
|
||||||
const calculatePricing = async () => {
|
const calculatePricing = async () => {
|
||||||
setLoadingPricing(true);
|
setLoadingPricing(true);
|
||||||
|
|
@ -817,7 +696,6 @@ export default function App() {
|
||||||
...module,
|
...module,
|
||||||
priceInr: live.priceInr,
|
priceInr: live.priceInr,
|
||||||
priceUsd: live.priceUsd,
|
priceUsd: live.priceUsd,
|
||||||
priceEur: live.priceEur,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const exists = cart.find(item => item.code === module.code);
|
const exists = cart.find(item => item.code === module.code);
|
||||||
|
|
@ -873,60 +751,25 @@ export default function App() {
|
||||||
if (!loggedInUser?.active_subscriptions) return false;
|
if (!loggedInUser?.active_subscriptions) return false;
|
||||||
|
|
||||||
const hasLifetime = loggedInUser.active_subscriptions.some((sub: any) =>
|
const hasLifetime = loggedInUser.active_subscriptions.some((sub: any) =>
|
||||||
sub.plan_code === 'LIFETIME_ALL' ||
|
sub.plan_code === 'LIFETIME_ALL' || sub.plan_code === 'LIFETIME_ALL_USD'
|
||||||
sub.plan_code === 'LIFETIME_ALL_USD' ||
|
|
||||||
sub.plan_code === 'LIFETIME_ALL_EUR'
|
|
||||||
);
|
);
|
||||||
if (hasLifetime) return true;
|
if (hasLifetime) return true;
|
||||||
|
|
||||||
const hasDirectSub = loggedInUser.active_subscriptions.some(
|
|
||||||
(sub: any) =>
|
|
||||||
sub.plan_code === code ||
|
|
||||||
sub.plan_code === `${code}_USD` ||
|
|
||||||
sub.plan_code === `${code}_EUR`
|
|
||||||
);
|
|
||||||
if (hasDirectSub) return true;
|
|
||||||
|
|
||||||
// Dynamic unlock check via /api/access/me unlocked_module_codes / unlocked_module_slugs
|
|
||||||
const unlockedCodes = new Set(
|
|
||||||
(loggedInUser.unlocked_module_codes || []).map((c: string) => c.toLowerCase()),
|
|
||||||
);
|
|
||||||
const unlockedSlugs = new Set(
|
|
||||||
(loggedInUser.unlocked_module_slugs || []).map((s: string) => s.toLowerCase()),
|
|
||||||
);
|
|
||||||
if (unlockedCodes.size > 0 || unlockedSlugs.size > 0) {
|
|
||||||
const matchedPlan = getLivePlan(code);
|
|
||||||
const planModules = matchedPlan?.modules || [];
|
|
||||||
if (planModules.length > 0) {
|
|
||||||
const allModulesUnlocked = planModules.every(
|
|
||||||
(m: any) =>
|
|
||||||
(m.code && unlockedCodes.has(String(m.code).toLowerCase())) ||
|
|
||||||
(m.slug && unlockedSlugs.has(String(m.slug).toLowerCase())),
|
|
||||||
);
|
|
||||||
if (allModulesUnlocked) return true;
|
|
||||||
}
|
|
||||||
const planSlugs = matchedPlan?.module_slugs || [];
|
|
||||||
if (planSlugs.length > 0 && planSlugs.every((s: string) => unlockedSlugs.has(s.toLowerCase()))) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Legacy fallback when publicPlans lacks module lists
|
|
||||||
if (code === 'POINTS_ACU' || code === 'POINTS_SCALP' || code === 'POINTS_EAR' || code === 'POINTS_TUNG') {
|
if (code === 'POINTS_ACU' || code === 'POINTS_SCALP' || code === 'POINTS_EAR' || code === 'POINTS_TUNG') {
|
||||||
const hasPointsPack = loggedInUser.active_subscriptions.some((sub: any) =>
|
const hasPointsPack = loggedInUser.active_subscriptions.some((sub: any) =>
|
||||||
sub.plan_code === 'POINTS_PACK' || sub.plan_code === 'POINTS_PACK_USD' || sub.plan_code === 'POINTS_PACK_EUR'
|
sub.plan_code === 'POINTS_PACK' || sub.plan_code === 'POINTS_PACK_USD'
|
||||||
);
|
);
|
||||||
if (hasPointsPack) return true;
|
if (hasPointsPack) return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (code === 'THERAPEUTICS_GYNAE' || code === 'THERAPEUTICS_EAR') {
|
if (code === 'THERAPEUTICS_GYNAE' || code === 'THERAPEUTICS_EAR') {
|
||||||
const hasTherapeuticsPack = loggedInUser.active_subscriptions.some((sub: any) =>
|
const hasTherapeuticsPack = loggedInUser.active_subscriptions.some((sub: any) =>
|
||||||
sub.plan_code === 'THERAPEUTICS_CORE' || sub.plan_code === 'THERAPEUTICS_CORE_USD' || sub.plan_code === 'THERAPEUTICS_CORE_EUR'
|
sub.plan_code === 'THERAPEUTICS_CORE' || sub.plan_code === 'THERAPEUTICS_CORE_USD'
|
||||||
);
|
);
|
||||||
if (hasTherapeuticsPack) return true;
|
if (hasTherapeuticsPack) return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return loggedInUser.active_subscriptions.some((sub: any) => sub.plan_code === code || sub.plan_code === `${code}_USD`);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Automatically remove already unlocked modules from the cart
|
// Automatically remove already unlocked modules from the cart
|
||||||
|
|
@ -988,22 +831,39 @@ export default function App() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure the user has a valid billing contact phone number before opening Razorpay
|
if (!loggedInUser?.phone_number) {
|
||||||
const hasValidPhone = loggedInUser?.phone_number && isValidPhoneNumber(loggedInUser.phone_number, undefined, loggedInUser.country || 'India');
|
const inputPhone = prompt("A billing phone number is required for Razorpay checkout. Please enter your contact number:");
|
||||||
if (!hasValidPhone) {
|
if (!inputPhone) {
|
||||||
setPendingCheckoutAfterPhone(true);
|
setCheckoutLoading(false);
|
||||||
setShowBillingPhoneModal(true);
|
return;
|
||||||
setCheckoutLoading(false);
|
}
|
||||||
return;
|
const cleanedPhone = cleanPhoneInput(inputPhone, 16, true);
|
||||||
|
const phoneError = validatePhoneNumber(cleanedPhone, undefined, loggedInUser?.country || 'India');
|
||||||
|
if (phoneError) {
|
||||||
|
alert(phoneError);
|
||||||
|
setCheckoutLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const res = await axios.put(`${API_BASE}/api/auth/profile`, {
|
||||||
|
phone_number: cleanedPhone
|
||||||
|
}, {
|
||||||
|
headers: { 'Authorization': `Bearer ${userToken}` }
|
||||||
|
});
|
||||||
|
if (res.data.status === 'success') {
|
||||||
|
loggedInUser.phone_number = cleanedPhone;
|
||||||
|
setLoggedInUser({ ...loggedInUser });
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
alert("Failed to save phone number: " + (err.response?.data?.detail || err.message));
|
||||||
|
setCheckoutLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let isPaymentCancelled = false;
|
let isPaymentCancelled = false;
|
||||||
let isPaymentCompleted = false;
|
let isPaymentCompleted = false;
|
||||||
|
|
||||||
// Sanitize contact for Razorpay: strictly E.164 (+<dialCode><digits>)
|
|
||||||
const parsedContact = parsePhoneNumber(loggedInUser?.phone_number, loggedInUser?.country || 'India');
|
|
||||||
const sanitizedContact = formatE164Phone(parsedContact.dialCode, parsedContact.localDigits, loggedInUser?.country || 'India');
|
|
||||||
|
|
||||||
const rzpOptions = {
|
const rzpOptions = {
|
||||||
key: razorpayKeyId,
|
key: razorpayKeyId,
|
||||||
amount: Math.round(grand_total * 100),
|
amount: Math.round(grand_total * 100),
|
||||||
|
|
@ -1011,10 +871,11 @@ export default function App() {
|
||||||
name: 'Acupedia',
|
name: 'Acupedia',
|
||||||
description: cart.map(c => c.name).join(', '),
|
description: cart.map(c => c.name).join(', '),
|
||||||
order_id: razorpay_order_id,
|
order_id: razorpay_order_id,
|
||||||
|
customer_id: loggedInUser?.external_ref || undefined,
|
||||||
prefill: {
|
prefill: {
|
||||||
name: loggedInUser?.display_name || '',
|
name: loggedInUser?.display_name || '',
|
||||||
email: loggedInUser?.email || '',
|
email: loggedInUser?.email || '',
|
||||||
contact: sanitizedContact
|
contact: loggedInUser?.phone_number || loggedInUser?.phone || ''
|
||||||
},
|
},
|
||||||
readonly: {
|
readonly: {
|
||||||
contact: true,
|
contact: true,
|
||||||
|
|
@ -1135,11 +996,7 @@ export default function App() {
|
||||||
activeTab={activeTab}
|
activeTab={activeTab}
|
||||||
onSwitchTab={switchTab}
|
onSwitchTab={switchTab}
|
||||||
loggedInUser={loggedInUser}
|
loggedInUser={loggedInUser}
|
||||||
onOpenProfile={() => {
|
onOpenProfile={() => setShowProfileDrawer(true)}
|
||||||
setChangePasswordSuccess(false);
|
|
||||||
setChangePasswordError(null);
|
|
||||||
setShowProfileDrawer(true);
|
|
||||||
}}
|
|
||||||
onOpenAuth={(mode) => {
|
onOpenAuth={(mode) => {
|
||||||
setAuthMode(mode);
|
setAuthMode(mode);
|
||||||
setShowAuthModal(true);
|
setShowAuthModal(true);
|
||||||
|
|
@ -1171,6 +1028,7 @@ export default function App() {
|
||||||
<CartDrawer
|
<CartDrawer
|
||||||
cart={cart}
|
cart={cart}
|
||||||
currency={currency}
|
currency={currency}
|
||||||
|
setCurrency={setCurrency}
|
||||||
toggleCartItem={toggleCartItem}
|
toggleCartItem={toggleCartItem}
|
||||||
couponCode={couponCode}
|
couponCode={couponCode}
|
||||||
setCouponCode={setCouponCode}
|
setCouponCode={setCouponCode}
|
||||||
|
|
@ -1180,21 +1038,40 @@ export default function App() {
|
||||||
pricingCalc={pricingCalc}
|
pricingCalc={pricingCalc}
|
||||||
loadingPricing={loadingPricing}
|
loadingPricing={loadingPricing}
|
||||||
loggedInUser={loggedInUser}
|
loggedInUser={loggedInUser}
|
||||||
onUpdateBillingPhone={() => setShowBillingPhoneModal(true)}
|
onUpdateBillingPhone={async () => {
|
||||||
|
const inputPhone = prompt("Enter billing phone number:", loggedInUser?.phone_number || '');
|
||||||
|
if (inputPhone === null || !loggedInUser) return;
|
||||||
|
const trimmed = inputPhone.trim();
|
||||||
|
if (!trimmed) {
|
||||||
|
alert("A billing phone number is required.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const cleanedPhone = cleanPhoneInput(trimmed, 16, true);
|
||||||
|
const phoneError = validatePhoneNumber(cleanedPhone, undefined, loggedInUser.country || 'India');
|
||||||
|
if (phoneError) {
|
||||||
|
alert(phoneError);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const res = await axios.put(`${API_BASE}/api/auth/profile`, {
|
||||||
|
phone_number: cleanedPhone
|
||||||
|
}, {
|
||||||
|
headers: { 'Authorization': `Bearer ${userToken}` }
|
||||||
|
});
|
||||||
|
if (res.data.status === 'success') {
|
||||||
|
setLoggedInUser({ ...loggedInUser, phone_number: cleanedPhone });
|
||||||
|
alert('Phone number updated successfully for billing!');
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
alert(err.response?.data?.detail || 'Failed to update phone number.');
|
||||||
|
}
|
||||||
|
}}
|
||||||
verificationResult={verificationResult}
|
verificationResult={verificationResult}
|
||||||
checkoutLoading={checkoutLoading}
|
checkoutLoading={checkoutLoading}
|
||||||
handleCheckout={handleCheckout}
|
handleCheckout={handleCheckout}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : activeTab === 'logged-out' ? (
|
|
||||||
<LoggedOutView
|
|
||||||
onLoginAgain={() => {
|
|
||||||
switchTab('storefront');
|
|
||||||
setAuthMode('login');
|
|
||||||
setShowAuthModal(true);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
) : (
|
) : (
|
||||||
/* 🧾 Tab: User Personal Subscriptions Ledger */
|
/* 🧾 Tab: User Personal Subscriptions Ledger */
|
||||||
<SubscriptionsView
|
<SubscriptionsView
|
||||||
|
|
@ -1271,7 +1148,7 @@ export default function App() {
|
||||||
{/* 🧭 Profile Drawer */}
|
{/* 🧭 Profile Drawer */}
|
||||||
<ProfileDrawer
|
<ProfileDrawer
|
||||||
isOpen={showProfileDrawer}
|
isOpen={showProfileDrawer}
|
||||||
onClose={handleCloseProfileDrawer}
|
onClose={() => setShowProfileDrawer(false)}
|
||||||
loggedInUser={loggedInUser}
|
loggedInUser={loggedInUser}
|
||||||
profileDisplayName={profileDisplayName}
|
profileDisplayName={profileDisplayName}
|
||||||
setProfileDisplayName={setProfileDisplayName}
|
setProfileDisplayName={setProfileDisplayName}
|
||||||
|
|
@ -1294,19 +1171,13 @@ export default function App() {
|
||||||
setChangeConfirmPassword={setChangeConfirmPassword}
|
setChangeConfirmPassword={setChangeConfirmPassword}
|
||||||
changePasswordLoading={changePasswordLoading}
|
changePasswordLoading={changePasswordLoading}
|
||||||
changePasswordError={changePasswordError}
|
changePasswordError={changePasswordError}
|
||||||
setChangePasswordError={setChangePasswordError}
|
|
||||||
changePasswordSuccess={changePasswordSuccess}
|
changePasswordSuccess={changePasswordSuccess}
|
||||||
setChangePasswordSuccess={setChangePasswordSuccess}
|
|
||||||
onChangePassword={handleChangePassword}
|
onChangePassword={handleChangePassword}
|
||||||
onLogout={handleLogout}
|
onLogout={handleLogout}
|
||||||
onBrowseStorefront={() => {
|
onBrowseStorefront={() => {
|
||||||
handleCloseProfileDrawer();
|
setShowProfileDrawer(false);
|
||||||
switchTab('storefront');
|
switchTab('storefront');
|
||||||
}}
|
}}
|
||||||
onViewSubscriptions={() => {
|
|
||||||
handleCloseProfileDrawer();
|
|
||||||
switchTab('subscriptions');
|
|
||||||
}}
|
|
||||||
curriculumModules={curriculumModules}
|
curriculumModules={curriculumModules}
|
||||||
onDownloadInvoice={handleDownloadCheckoutInvoice}
|
onDownloadInvoice={handleDownloadCheckoutInvoice}
|
||||||
/>
|
/>
|
||||||
|
|
@ -1320,18 +1191,6 @@ export default function App() {
|
||||||
setShowAuthModal(true);
|
setShowAuthModal(true);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* 📞 Billing Contact Phone Modal */}
|
|
||||||
<BillingPhoneModal
|
|
||||||
isOpen={showBillingPhoneModal}
|
|
||||||
onClose={() => {
|
|
||||||
setShowBillingPhoneModal(false);
|
|
||||||
setPendingCheckoutAfterPhone(false);
|
|
||||||
}}
|
|
||||||
currentPhone={loggedInUser?.phone_number}
|
|
||||||
currentCountry={loggedInUser?.country || profileCountry || 'India'}
|
|
||||||
onSavePhone={handleSaveBillingPhone}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,8 @@ import {
|
||||||
XCircle, Sparkles, AlertCircle, CheckCircle, RefreshCw,
|
XCircle, Sparkles, AlertCircle, CheckCircle, RefreshCw,
|
||||||
Phone, Globe, Eye, EyeOff, LogIn, UserPlus
|
Phone, Globe, Eye, EyeOff, LogIn, UserPlus
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { getCountryRuleByName } from '../../constants/countries';
|
import { COUNTRY_CODES, getCountryRuleByDialCode, getCountryRuleByName } from '../../constants/countries';
|
||||||
import { CountrySelect } from '../common/CountrySelect';
|
import { cleanPhoneInput } from '../../utils/validation';
|
||||||
import { PhoneInput } from '../common/PhoneInput';
|
|
||||||
|
|
||||||
interface AuthModalProps {
|
interface AuthModalProps {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
|
|
@ -78,6 +77,7 @@ export const AuthModal: React.FC<AuthModalProps> = ({
|
||||||
onResetPasswordSubmit,
|
onResetPasswordSubmit,
|
||||||
}) => {
|
}) => {
|
||||||
const [showPassword, setShowPassword] = useState(false);
|
const [showPassword, setShowPassword] = useState(false);
|
||||||
|
const activeRule = getCountryRuleByDialCode(authDialCode);
|
||||||
|
|
||||||
if (!isOpen) return null;
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
|
@ -288,25 +288,45 @@ export const AuthModal: React.FC<AuthModalProps> = ({
|
||||||
<label className="text-[10px] uppercase font-black tracking-wider text-slate-500 flex items-center gap-1">
|
<label className="text-[10px] uppercase font-black tracking-wider text-slate-500 flex items-center gap-1">
|
||||||
<Phone className="h-3 w-3 text-indigo-400" /> Phone Number
|
<Phone className="h-3 w-3 text-indigo-400" /> Phone Number
|
||||||
</label>
|
</label>
|
||||||
<PhoneInput
|
<div className="flex gap-2 w-full">
|
||||||
dialCode={authDialCode}
|
<div className="relative shrink-0 w-[95px]">
|
||||||
phone={authPhone}
|
<select
|
||||||
country={authCountry}
|
value={authDialCode}
|
||||||
clearOnDialCodeChange={true}
|
onChange={(e) => {
|
||||||
onDialCodeChange={(newCode, newCountry) => {
|
const newCode = e.target.value;
|
||||||
setAuthDialCode(newCode);
|
setAuthDialCode(newCode);
|
||||||
setAuthCountry(newCountry);
|
const rule = getCountryRuleByDialCode(newCode);
|
||||||
setAuthPhone('');
|
if (rule && rule.country !== 'Other') {
|
||||||
}}
|
setAuthCountry(rule.country);
|
||||||
onPhoneChange={(newPhone) => {
|
setAuthPhone(cleanPhoneInput(authPhone, rule.maxLength, false));
|
||||||
setAuthPhone(newPhone);
|
}
|
||||||
if (authError && (authError.toLowerCase().includes('phone') || authError.toLowerCase().includes('mobile'))) {
|
}}
|
||||||
setAuthError(null);
|
className="w-full bg-slate-950 border border-slate-800 rounded-xl px-2.5 py-2.5 text-xs sm:text-sm font-semibold text-white focus:outline-none focus:border-indigo-500 appearance-none pr-6"
|
||||||
}
|
>
|
||||||
}}
|
{COUNTRY_CODES.map((cc) => (
|
||||||
theme="dark"
|
<option key={`${cc.country}-${cc.code}`} value={cc.code}>
|
||||||
error={authError && (authError.toLowerCase().includes('phone') || authError.toLowerCase().includes('mobile')) ? authError : null}
|
{cc.label} ({cc.country})
|
||||||
/>
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<div className="absolute right-2.5 top-1/2 -translate-y-1/2 pointer-events-none text-slate-500 text-[10px]">
|
||||||
|
▼
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type="tel"
|
||||||
|
value={authPhone}
|
||||||
|
onChange={(e) => setAuthPhone(cleanPhoneInput(e.target.value, activeRule.maxLength, false))}
|
||||||
|
placeholder={activeRule.placeholder}
|
||||||
|
maxLength={activeRule.maxLength}
|
||||||
|
className="min-w-0 flex-1 bg-slate-950 border border-slate-800 rounded-xl px-3 sm:px-4 py-2.5 text-xs sm:text-sm font-semibold text-white focus:outline-none focus:border-indigo-500 placeholder:text-slate-700"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="text-[10px] text-slate-500 font-medium">
|
||||||
|
{activeRule.minLength === activeRule.maxLength
|
||||||
|
? `${activeRule.label || activeRule.country}: Requires exactly ${activeRule.maxLength} digits`
|
||||||
|
: `${activeRule.label || activeRule.country}: ${activeRule.minLength} to ${activeRule.maxLength} digits`}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
@ -316,23 +336,30 @@ export const AuthModal: React.FC<AuthModalProps> = ({
|
||||||
<label className="text-[10px] uppercase font-black tracking-wider text-slate-500 flex items-center gap-1">
|
<label className="text-[10px] uppercase font-black tracking-wider text-slate-500 flex items-center gap-1">
|
||||||
<Globe className="h-3 w-3 text-indigo-400" /> Country (Defaults currency)
|
<Globe className="h-3 w-3 text-indigo-400" /> Country (Defaults currency)
|
||||||
</label>
|
</label>
|
||||||
<CountrySelect
|
<div className="relative">
|
||||||
value={authCountry}
|
<select
|
||||||
onChange={(newCountry) => {
|
value={authCountry}
|
||||||
if (newCountry !== authCountry) {
|
onChange={(e) => {
|
||||||
|
const newCountry = e.target.value;
|
||||||
setAuthCountry(newCountry);
|
setAuthCountry(newCountry);
|
||||||
const rule = getCountryRuleByName(newCountry);
|
const rule = getCountryRuleByName(newCountry);
|
||||||
if (rule) {
|
if (rule) {
|
||||||
setAuthDialCode(rule.code);
|
setAuthDialCode(rule.code);
|
||||||
|
setAuthPhone(cleanPhoneInput(authPhone, rule.maxLength, false));
|
||||||
}
|
}
|
||||||
setAuthPhone('');
|
}}
|
||||||
}
|
className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-2.5 text-sm font-semibold text-white focus:outline-none focus:border-indigo-500 appearance-none"
|
||||||
}}
|
>
|
||||||
theme="dark"
|
{COUNTRY_CODES.map((cc) => (
|
||||||
size="md"
|
<option key={cc.country} value={cc.country}>
|
||||||
showCurrency={true}
|
{cc.country} (Calculates in {cc.currency} {cc.currency === 'INR' ? '₹' : cc.currency === 'EUR' ? '€' : '$'})
|
||||||
showDialCode={true}
|
</option>
|
||||||
/>
|
))}
|
||||||
|
</select>
|
||||||
|
<div className="absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none text-slate-500 text-xs">
|
||||||
|
▼
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,80 +0,0 @@
|
||||||
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>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
@ -1,13 +1,11 @@
|
||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState } from 'react';
|
||||||
import {
|
import {
|
||||||
XCircle, Users, ShieldCheck, CheckCircle, AlertCircle,
|
XCircle, Users, ShieldCheck, CheckCircle, AlertCircle,
|
||||||
Eye, EyeOff, RefreshCw, LogOut, Download
|
Eye, EyeOff, RefreshCw, LogOut, Download
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import type { UserProfile, ModuleItem, Currency } from '../../types';
|
import type { UserProfile, ModuleItem, Currency } from '../../types';
|
||||||
import { getCountryRuleByName } from '../../constants/countries';
|
import { COUNTRY_CODES, getCountryRuleByName } from '../../constants/countries';
|
||||||
import { parsePhoneNumber, formatE164Phone, SPECIAL_CHAR_REGEX } from '../../utils/validation';
|
import { cleanPhoneInput, updatePhoneDialCode, SPECIAL_CHAR_REGEX } from '../../utils/validation';
|
||||||
import { PhoneInput } from '../common/PhoneInput';
|
|
||||||
import { CountrySelect } from '../common/CountrySelect';
|
|
||||||
|
|
||||||
interface ProfileDrawerProps {
|
interface ProfileDrawerProps {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
|
|
@ -34,13 +32,10 @@ interface ProfileDrawerProps {
|
||||||
setChangeConfirmPassword: (pwd: string) => void;
|
setChangeConfirmPassword: (pwd: string) => void;
|
||||||
changePasswordLoading: boolean;
|
changePasswordLoading: boolean;
|
||||||
changePasswordError: string | null;
|
changePasswordError: string | null;
|
||||||
setChangePasswordError?: (err: string | null) => void;
|
|
||||||
changePasswordSuccess: boolean;
|
changePasswordSuccess: boolean;
|
||||||
setChangePasswordSuccess?: (success: boolean) => void;
|
|
||||||
onChangePassword: (e: React.FormEvent) => Promise<void>;
|
onChangePassword: (e: React.FormEvent) => Promise<void>;
|
||||||
onLogout: () => void;
|
onLogout: () => void;
|
||||||
onBrowseStorefront: () => void;
|
onBrowseStorefront: () => void;
|
||||||
onViewSubscriptions?: () => void;
|
|
||||||
curriculumModules: ModuleItem[];
|
curriculumModules: ModuleItem[];
|
||||||
onDownloadInvoice?: (paymentId: string, directUrl?: string) => void;
|
onDownloadInvoice?: (paymentId: string, directUrl?: string) => void;
|
||||||
}
|
}
|
||||||
|
|
@ -70,67 +65,16 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
|
||||||
setChangeConfirmPassword,
|
setChangeConfirmPassword,
|
||||||
changePasswordLoading,
|
changePasswordLoading,
|
||||||
changePasswordError,
|
changePasswordError,
|
||||||
setChangePasswordError,
|
|
||||||
changePasswordSuccess,
|
changePasswordSuccess,
|
||||||
setChangePasswordSuccess,
|
|
||||||
onChangePassword,
|
onChangePassword,
|
||||||
onLogout,
|
onLogout,
|
||||||
onBrowseStorefront,
|
onBrowseStorefront,
|
||||||
onViewSubscriptions,
|
|
||||||
curriculumModules,
|
curriculumModules,
|
||||||
onDownloadInvoice,
|
onDownloadInvoice,
|
||||||
}) => {
|
}) => {
|
||||||
const [showOldPassword, setShowOldPassword] = useState(false);
|
const [showOldPassword, setShowOldPassword] = useState(false);
|
||||||
const [showNewPassword, setShowNewPassword] = useState(false);
|
const [showNewPassword, setShowNewPassword] = useState(false);
|
||||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
const activeRule = getCountryRuleByName(profileCountry);
|
||||||
|
|
||||||
const parsed = parsePhoneNumber(profilePhone, profileCountry);
|
|
||||||
const [dialCode, setDialCode] = useState(parsed.dialCode);
|
|
||||||
const [localPhone, setLocalPhone] = useState(parsed.localDigits);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (isOpen) {
|
|
||||||
const p = parsePhoneNumber(profilePhone, profileCountry);
|
|
||||||
setDialCode(p.dialCode);
|
|
||||||
setLocalPhone(p.localDigits);
|
|
||||||
} else {
|
|
||||||
if (setChangePasswordSuccess) setChangePasswordSuccess(false);
|
|
||||||
if (setChangePasswordError) setChangePasswordError(null);
|
|
||||||
}
|
|
||||||
}, [isOpen, setChangePasswordSuccess, setChangePasswordError]);
|
|
||||||
|
|
||||||
const handleLocalPhoneChange = (newLocal: string) => {
|
|
||||||
setLocalPhone(newLocal);
|
|
||||||
setProfilePhone(newLocal ? formatE164Phone(dialCode, newLocal, profileCountry) : '');
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDialCodeChange = (newCode: string, newCountry: string) => {
|
|
||||||
setDialCode(newCode);
|
|
||||||
if (newCountry !== profileCountry) {
|
|
||||||
setProfileCountry(newCountry);
|
|
||||||
const rule = getCountryRuleByName(newCountry);
|
|
||||||
if (rule) {
|
|
||||||
setCurrency(rule.currency);
|
|
||||||
}
|
|
||||||
setLocalPhone('');
|
|
||||||
setProfilePhone('');
|
|
||||||
} else {
|
|
||||||
setProfilePhone(localPhone ? formatE164Phone(newCode, localPhone, profileCountry) : '');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCountrySelectChange = (newCountry: string) => {
|
|
||||||
if (newCountry !== profileCountry) {
|
|
||||||
setProfileCountry(newCountry);
|
|
||||||
const rule = getCountryRuleByName(newCountry);
|
|
||||||
if (rule) {
|
|
||||||
setDialCode(rule.code);
|
|
||||||
setCurrency(rule.currency);
|
|
||||||
}
|
|
||||||
setLocalPhone('');
|
|
||||||
setProfilePhone('');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!isOpen || !loggedInUser) return null;
|
if (!isOpen || !loggedInUser) return null;
|
||||||
|
|
||||||
|
|
@ -201,29 +145,43 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
|
||||||
|
|
||||||
<div className="space-y-1.5">
|
<div className="space-y-1.5">
|
||||||
<label className="text-xs font-bold text-slate-500">Phone Number</label>
|
<label className="text-xs font-bold text-slate-500">Phone Number</label>
|
||||||
<PhoneInput
|
<input
|
||||||
dialCode={dialCode}
|
type="tel"
|
||||||
phone={localPhone}
|
value={profilePhone}
|
||||||
country={profileCountry}
|
onChange={(e) => setProfilePhone(cleanPhoneInput(e.target.value, activeRule.maxLength + activeRule.code.length + 1, true))}
|
||||||
clearOnDialCodeChange={true}
|
placeholder={activeRule.placeholder ? `e.g. ${activeRule.code} ${activeRule.placeholder}` : `e.g. ${activeRule.code} 9876543210`}
|
||||||
onDialCodeChange={handleDialCodeChange}
|
maxLength={activeRule.maxLength + activeRule.code.length + 2}
|
||||||
onPhoneChange={handleLocalPhoneChange}
|
className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-xs font-semibold text-slate-800 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
|
||||||
theme="light"
|
|
||||||
disabled={profileSaving}
|
|
||||||
error={profileError && (profileError.toLowerCase().includes('phone') || profileError.toLowerCase().includes('mobile')) ? profileError : null}
|
|
||||||
/>
|
/>
|
||||||
|
<p className="text-[10px] text-slate-400 font-medium">
|
||||||
|
{activeRule.minLength === activeRule.maxLength
|
||||||
|
? `${activeRule.label || activeRule.country}: Requires exactly ${activeRule.maxLength} digits`
|
||||||
|
: `${activeRule.label || activeRule.country}: ${activeRule.minLength} to ${activeRule.maxLength} digits`}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-1.5">
|
<div className="space-y-1.5">
|
||||||
<label className="text-xs font-bold text-slate-500">Billing Country</label>
|
<label className="text-xs font-bold text-slate-500">Billing Country</label>
|
||||||
<CountrySelect
|
<select
|
||||||
value={profileCountry}
|
value={profileCountry}
|
||||||
onChange={handleCountrySelectChange}
|
onChange={(e) => {
|
||||||
theme="light"
|
const newCountry = e.target.value;
|
||||||
size="sm"
|
if (newCountry !== profileCountry) {
|
||||||
showDialCode={true}
|
const updatedPhone = updatePhoneDialCode(profilePhone, profileCountry, newCountry);
|
||||||
showCurrency={false}
|
setProfilePhone(updatedPhone);
|
||||||
/>
|
setProfileCountry(newCountry);
|
||||||
|
const rule = getCountryRuleByName(newCountry);
|
||||||
|
setCurrency(rule.currency);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-xs font-semibold text-slate-800 focus:outline-none focus:border-indigo-500"
|
||||||
|
>
|
||||||
|
{COUNTRY_CODES.map((cc) => (
|
||||||
|
<option key={cc.country} value={cc.country}>
|
||||||
|
{cc.country}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
|
|
@ -246,8 +204,6 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setShowPasswordChange(!showPasswordChange);
|
setShowPasswordChange(!showPasswordChange);
|
||||||
if (setChangePasswordSuccess) setChangePasswordSuccess(false);
|
|
||||||
if (setChangePasswordError) setChangePasswordError(null);
|
|
||||||
}}
|
}}
|
||||||
className="text-xs text-indigo-600 hover:text-indigo-700 font-bold"
|
className="text-xs text-indigo-600 hover:text-indigo-700 font-bold"
|
||||||
>
|
>
|
||||||
|
|
@ -317,23 +273,14 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
|
||||||
|
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<label className="text-xs font-bold text-slate-500">Confirm New Password</label>
|
<label className="text-xs font-bold text-slate-500">Confirm New Password</label>
|
||||||
<div className="relative">
|
<input
|
||||||
<input
|
type="password"
|
||||||
type={showConfirmPassword ? 'text' : 'password'}
|
required
|
||||||
required
|
value={changeConfirmPassword}
|
||||||
value={changeConfirmPassword}
|
onChange={(e) => setChangeConfirmPassword(e.target.value)}
|
||||||
onChange={(e) => setChangeConfirmPassword(e.target.value)}
|
placeholder="Repeat new password"
|
||||||
placeholder="Repeat new password"
|
className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-xs font-semibold text-slate-800 focus:outline-none focus:border-indigo-500"
|
||||||
className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 pr-10 text-xs font-semibold text-slate-800 focus:outline-none focus:border-indigo-500"
|
/>
|
||||||
/>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
|
||||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-0.5"
|
|
||||||
>
|
|
||||||
{showConfirmPassword ? <EyeOff className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-wrap gap-2 text-[10px] text-slate-500 pt-1">
|
<div className="flex flex-wrap gap-2 text-[10px] text-slate-500 pt-1">
|
||||||
|
|
@ -367,20 +314,9 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
|
||||||
|
|
||||||
{/* Subscriptions Nested Details */}
|
{/* Subscriptions Nested Details */}
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="flex items-center justify-between">
|
<h4 className="text-xs font-bold text-slate-400 uppercase tracking-widest flex items-center gap-1.5">
|
||||||
<h4 className="text-xs font-bold text-slate-400 uppercase tracking-widest flex items-center gap-1.5">
|
<CheckCircle className="h-4 w-4 text-emerald-500" /> Ongoing subscriptions
|
||||||
<CheckCircle className="h-4 w-4 text-emerald-500" /> Ongoing subscriptions
|
</h4>
|
||||||
</h4>
|
|
||||||
{onViewSubscriptions && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onViewSubscriptions}
|
|
||||||
className="text-xs text-indigo-600 hover:text-indigo-500 font-bold hover:underline"
|
|
||||||
>
|
|
||||||
View All
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{!loggedInUser.active_subscriptions || loggedInUser.active_subscriptions.length === 0 ? (
|
{!loggedInUser.active_subscriptions || loggedInUser.active_subscriptions.length === 0 ? (
|
||||||
<div className="bg-slate-50 border border-slate-200/60 rounded-2xl p-6 text-center space-y-2">
|
<div className="bg-slate-50 border border-slate-200/60 rounded-2xl p-6 text-center space-y-2">
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,11 @@
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { ShoppingCart, ShoppingBag, Trash2, RefreshCw, CreditCard, XCircle, Globe } from 'lucide-react';
|
import { ShoppingCart, ShoppingBag, Trash2, RefreshCw, CreditCard, XCircle } from 'lucide-react';
|
||||||
import type { ModuleItem, Currency, UserProfile, VerificationResult } from '../../types';
|
import type { ModuleItem, Currency, UserProfile, VerificationResult } from '../../types';
|
||||||
import { isValidPhoneNumber } from '../../utils/validation';
|
|
||||||
|
|
||||||
interface CartDrawerProps {
|
interface CartDrawerProps {
|
||||||
cart: ModuleItem[];
|
cart: ModuleItem[];
|
||||||
currency: Currency;
|
currency: Currency;
|
||||||
|
setCurrency: (c: Currency) => void;
|
||||||
toggleCartItem: (module: ModuleItem) => void;
|
toggleCartItem: (module: ModuleItem) => void;
|
||||||
couponCode: string;
|
couponCode: string;
|
||||||
setCouponCode: (code: string) => void;
|
setCouponCode: (code: string) => void;
|
||||||
|
|
@ -24,6 +24,7 @@ interface CartDrawerProps {
|
||||||
export const CartDrawer: React.FC<CartDrawerProps> = ({
|
export const CartDrawer: React.FC<CartDrawerProps> = ({
|
||||||
cart,
|
cart,
|
||||||
currency,
|
currency,
|
||||||
|
setCurrency,
|
||||||
toggleCartItem,
|
toggleCartItem,
|
||||||
couponCode,
|
couponCode,
|
||||||
setCouponCode,
|
setCouponCode,
|
||||||
|
|
@ -75,23 +76,28 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Billing Currency & Region Badge */}
|
{/* Currency selector toggle */}
|
||||||
<div className="flex items-center justify-between p-2.5 bg-slate-50 border border-slate-200/70 rounded-xl">
|
<div className="flex flex-col sm:flex-row gap-2 sm:items-center justify-between">
|
||||||
<div className="flex items-center gap-1.5 min-w-0">
|
<span className="text-xs font-bold text-slate-500">Billing Currency:</span>
|
||||||
<Globe className="h-3.5 w-3.5 text-indigo-500 shrink-0" />
|
<div className="flex bg-slate-100 rounded-lg p-0.5 border border-slate-200 self-end sm:self-auto flex-shrink-0">
|
||||||
<span className="text-xs font-semibold text-slate-600 truncate">
|
<button
|
||||||
{loggedInUser ? 'Billing Currency' : 'Estimated Currency'}:
|
onClick={() => setCurrency('INR')}
|
||||||
</span>
|
className={`px-3 py-1 rounded-md text-xs font-bold transition-all duration-300 ${currency === 'INR'
|
||||||
</div>
|
? 'bg-white text-slate-900 shadow-sm border border-slate-200/50'
|
||||||
<div className="flex items-center gap-1.5 shrink-0">
|
: 'text-slate-500 hover:text-slate-800'
|
||||||
<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>
|
INR (₹)
|
||||||
{loggedInUser?.country && (
|
</button>
|
||||||
<span className="text-[10px] text-slate-400 font-semibold max-w-[90px] truncate" title={loggedInUser.country}>
|
<button
|
||||||
• {loggedInUser.country}
|
onClick={() => setCurrency('USD')}
|
||||||
</span>
|
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>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
@ -107,55 +113,36 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-3 max-h-[220px] overflow-y-auto pr-1">
|
<div className="space-y-3 max-h-[220px] overflow-y-auto pr-1">
|
||||||
{cart.map((item) => {
|
{cart.map((item) => (
|
||||||
const isCompletePackage =
|
<div
|
||||||
item.code === 'POINTS_PACK' ||
|
key={item.code}
|
||||||
item.code === 'PATTERN_CORE' ||
|
className="flex justify-between items-center gap-4 bg-slate-50 border border-slate-200/60 p-3 rounded-2xl"
|
||||||
item.code === 'NUTRITION_CORE' ||
|
>
|
||||||
item.code === 'THERAPEUTICS_CORE' ||
|
<div className="flex-1 min-w-0">
|
||||||
item.name.toLowerCase().includes('complete pack') ||
|
<p className="text-xs font-bold text-slate-800 truncate">{item.name}</p>
|
||||||
item.name.toLowerCase().includes('complete package') ||
|
<p className="text-[9px] text-slate-400 tracking-wider uppercase font-semibold">{item.category}</p>
|
||||||
item.name.toLowerCase().includes('complete bundle') ||
|
|
||||||
item.category === 'Bundle';
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={item.code}
|
|
||||||
className="flex justify-between items-center gap-4 bg-slate-50 border border-slate-200/60 p-3 rounded-2xl"
|
|
||||||
>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-center gap-1.5 flex-wrap min-w-0">
|
|
||||||
<p className="text-xs font-bold text-slate-800 truncate">{item.name}</p>
|
|
||||||
{isCompletePackage && (
|
|
||||||
<span className="text-[8px] bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-extrabold px-1.5 py-0.5 rounded tracking-wider uppercase flex-shrink-0">
|
|
||||||
Complete Pack
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<p className="text-[9px] text-slate-400 tracking-wider uppercase font-semibold">{item.category}</p>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<span className="text-xs font-bold text-indigo-600">
|
|
||||||
{(() => {
|
|
||||||
const calculatedItem = activePricing?.cart_items?.find((ci: any) => ci.code === item.code);
|
|
||||||
const price = calculatedItem
|
|
||||||
? calculatedItem.price
|
|
||||||
: (currency === 'INR' ? item.priceInr : currency === 'EUR' ? item.priceEur : item.priceUsd);
|
|
||||||
const symbol = currency === 'INR' ? '₹' : currency === 'EUR' ? '€' : '$';
|
|
||||||
return `${symbol}${price}`;
|
|
||||||
})()}
|
|
||||||
</span>
|
|
||||||
<button
|
|
||||||
onClick={() => toggleCartItem(item)}
|
|
||||||
className="h-7 w-7 rounded-lg bg-rose-50 text-rose-500 hover:bg-rose-100 flex items-center justify-center transition-colors"
|
|
||||||
title="Remove item"
|
|
||||||
>
|
|
||||||
<Trash2 className="h-3.5 w-3.5" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
<div className="flex items-center gap-3">
|
||||||
})}
|
<span className="text-xs font-bold text-indigo-600">
|
||||||
|
{(() => {
|
||||||
|
const calculatedItem = activePricing?.cart_items?.find((ci: any) => ci.code === item.code);
|
||||||
|
const price = calculatedItem
|
||||||
|
? calculatedItem.price
|
||||||
|
: (currency === 'INR' ? item.priceInr : currency === 'EUR' ? item.priceEur : item.priceUsd);
|
||||||
|
const symbol = currency === 'INR' ? '₹' : currency === 'EUR' ? '€' : '$';
|
||||||
|
return `${symbol}${price}`;
|
||||||
|
})()}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => toggleCartItem(item)}
|
||||||
|
className="h-7 w-7 rounded-lg bg-rose-50 text-rose-500 hover:bg-rose-100 flex items-center justify-center transition-colors"
|
||||||
|
title="Remove item"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
@ -345,32 +332,22 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
|
||||||
<span className="text-[10px] uppercase font-black tracking-wider text-slate-400">
|
<span className="text-[10px] uppercase font-black tracking-wider text-slate-400">
|
||||||
Billing Profile
|
Billing Profile
|
||||||
</span>
|
</span>
|
||||||
{(!loggedInUser.phone_number || !isValidPhoneNumber(loggedInUser.phone_number, undefined, loggedInUser.country || 'India')) && (
|
<button
|
||||||
<button
|
onClick={onUpdateBillingPhone}
|
||||||
onClick={onUpdateBillingPhone}
|
className="text-[9px] text-indigo-600 hover:text-indigo-500 font-black uppercase tracking-wider underline focus:outline-none"
|
||||||
className="text-[9px] text-indigo-600 hover:text-indigo-500 font-black uppercase tracking-wider underline focus:outline-none"
|
>
|
||||||
>
|
{loggedInUser.phone_number ? 'Edit Number' : 'Add Number'}
|
||||||
{loggedInUser.phone_number ? 'Update Number' : 'Add Number'}
|
</button>
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<div className="flex justify-between text-xs font-semibold text-slate-600">
|
<div className="flex justify-between text-xs font-semibold text-slate-600">
|
||||||
<span>Email:</span>
|
<span>Email:</span>
|
||||||
<span className="text-slate-800 font-bold truncate max-w-[180px]">{loggedInUser.email}</span>
|
<span className="text-slate-800 font-bold truncate max-w-[180px]">{loggedInUser.email}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between text-xs font-semibold text-slate-600">
|
|
||||||
<span>Billing Country:</span>
|
|
||||||
<span className="text-slate-800 font-bold truncate max-w-[180px]">{loggedInUser.country || 'India'}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex justify-between text-xs font-semibold text-slate-600">
|
<div className="flex justify-between text-xs font-semibold text-slate-600">
|
||||||
<span>Phone:</span>
|
<span>Phone:</span>
|
||||||
<span className="text-slate-800 font-bold">
|
<span className="text-slate-800 font-bold">
|
||||||
{loggedInUser.phone_number && isValidPhoneNumber(loggedInUser.phone_number, undefined, loggedInUser.country || 'India') ? (
|
{loggedInUser.phone_number || (
|
||||||
loggedInUser.phone_number
|
|
||||||
) : loggedInUser.phone_number ? (
|
|
||||||
<span className="text-amber-600 font-black italic">Incomplete ({loggedInUser.phone_number})</span>
|
|
||||||
) : (
|
|
||||||
<span className="text-rose-500 font-black italic">Required for checkout</span>
|
<span className="text-rose-500 font-black italic">Required for checkout</span>
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
|
|
@ -410,15 +387,6 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
|
||||||
<p className="text-[10px] text-slate-400 text-center leading-relaxed font-semibold">
|
<p className="text-[10px] text-slate-400 text-center leading-relaxed font-semibold">
|
||||||
* Integrated with Razorpay Gateway API (Test Mode).
|
* Integrated with Razorpay Gateway API (Test Mode).
|
||||||
</p>
|
</p>
|
||||||
<p className="text-[10px] text-slate-400 text-center font-medium">
|
|
||||||
Billing currency is tied to your country. Need billing assistance?{' '}
|
|
||||||
<a
|
|
||||||
href="mailto:support@acupedia.com?subject=Billing%20Support%20Inquiry"
|
|
||||||
className="text-indigo-600 hover:underline font-bold"
|
|
||||||
>
|
|
||||||
Contact Support
|
|
||||||
</a>
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { BookOpen, Check } from 'lucide-react';
|
import { BookOpen, Check } from 'lucide-react';
|
||||||
import type { ModuleItem, PublicPlan, Currency } from '../../types';
|
import type { ModuleItem, PublicPlan, Currency } from '../../types';
|
||||||
import { CORE_PACK_CODES, MAIN_CATEGORIES, resolvePlanCategory } from '../../utils/catalog';
|
|
||||||
|
|
||||||
interface CatalogSectionProps {
|
interface CatalogSectionProps {
|
||||||
curriculumModules: ModuleItem[];
|
curriculumModules: ModuleItem[];
|
||||||
|
|
@ -31,11 +30,6 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
showLockedByCategory,
|
showLockedByCategory,
|
||||||
setShowLockedByCategory,
|
setShowLockedByCategory,
|
||||||
}) => {
|
}) => {
|
||||||
const countLockedActive = (predicate: (category: string) => boolean) =>
|
|
||||||
curriculumModules.filter(
|
|
||||||
m => predicate(m.category) && !isModuleUnlocked(m.code) && getModulePrice(m).isActive
|
|
||||||
).length;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="xl:col-span-2 space-y-6">
|
<div className="xl:col-span-2 space-y-6">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
|
|
@ -63,7 +57,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Points: !prev.Points }))}
|
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Points: !prev.Points }))}
|
||||||
className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0"
|
className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0"
|
||||||
>
|
>
|
||||||
{showLockedByCategory.Points ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Points')})
|
{showLockedByCategory.Points ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Points' && !isModuleUnlocked(m.code)).length})
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
||||||
|
|
@ -78,9 +72,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
{(() => {
|
{(() => {
|
||||||
const items = curriculumModules
|
const items = curriculumModules.filter(m => m.category === 'Points');
|
||||||
.filter(m => m.category === 'Points')
|
|
||||||
.sort((a, b) => (a.sortOrder ?? 500) - (b.sortOrder ?? 500));
|
|
||||||
const visible = items.filter(sub => {
|
const visible = items.filter(sub => {
|
||||||
const isUnlocked = isModuleUnlocked(sub.code);
|
const isUnlocked = isModuleUnlocked(sub.code);
|
||||||
const live = getModulePrice(sub);
|
const live = getModulePrice(sub);
|
||||||
|
|
@ -184,7 +176,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Pattern: !prev.Pattern }))}
|
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Pattern: !prev.Pattern }))}
|
||||||
className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0"
|
className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0"
|
||||||
>
|
>
|
||||||
{showLockedByCategory.Pattern ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Pattern' || c === 'Patterns')})
|
{showLockedByCategory.Pattern ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Pattern' && !isModuleUnlocked(m.code)).length})
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
||||||
|
|
@ -199,9 +191,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
{(() => {
|
{(() => {
|
||||||
const items = curriculumModules
|
const items = curriculumModules.filter(m => m.category === 'Pattern');
|
||||||
.filter(m => m.category === 'Pattern' || m.category === 'Patterns')
|
|
||||||
.sort((a, b) => (a.sortOrder ?? 500) - (b.sortOrder ?? 500));
|
|
||||||
const visible = items.filter(sub => {
|
const visible = items.filter(sub => {
|
||||||
const isUnlocked = isModuleUnlocked(sub.code);
|
const isUnlocked = isModuleUnlocked(sub.code);
|
||||||
const live = getModulePrice(sub);
|
const live = getModulePrice(sub);
|
||||||
|
|
@ -249,12 +239,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
>
|
>
|
||||||
<div className="flex-1 pr-2">
|
<div className="flex-1 pr-2">
|
||||||
<div className="flex items-center gap-1.5 flex-wrap">
|
<div className="flex items-center gap-1.5 flex-wrap">
|
||||||
<span className="text-xs font-bold text-slate-800">{sub.name.replace("Pattern: ", "")}</span>
|
<span className="text-xs font-bold text-slate-800">{sub.name}</span>
|
||||||
{sub.name.includes('Complete Pack') && (
|
|
||||||
<span className="text-[8px] bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-extrabold px-1.5 py-0.5 rounded tracking-wider uppercase">
|
|
||||||
Complete Pack
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
{!isUnlocked && !live.isActive && (
|
{!isUnlocked && !live.isActive && (
|
||||||
<span className="text-[8px] bg-slate-200 text-slate-600 font-bold px-1.5 py-0.5 rounded tracking-wider uppercase">
|
<span className="text-[8px] bg-slate-200 text-slate-600 font-bold px-1.5 py-0.5 rounded tracking-wider uppercase">
|
||||||
Temporarily Unavailable
|
Temporarily Unavailable
|
||||||
|
|
@ -305,7 +290,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Nutrition: !prev.Nutrition }))}
|
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Nutrition: !prev.Nutrition }))}
|
||||||
className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0"
|
className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0"
|
||||||
>
|
>
|
||||||
{showLockedByCategory.Nutrition ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Nutrition')})
|
{showLockedByCategory.Nutrition ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Nutrition' && !isModuleUnlocked(m.code)).length})
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
||||||
|
|
@ -320,9 +305,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
{(() => {
|
{(() => {
|
||||||
const items = curriculumModules
|
const items = curriculumModules.filter(m => m.category === 'Nutrition');
|
||||||
.filter(m => m.category === 'Nutrition')
|
|
||||||
.sort((a, b) => (a.sortOrder ?? 500) - (b.sortOrder ?? 500));
|
|
||||||
const visible = items.filter(sub => {
|
const visible = items.filter(sub => {
|
||||||
const isUnlocked = isModuleUnlocked(sub.code);
|
const isUnlocked = isModuleUnlocked(sub.code);
|
||||||
const live = getModulePrice(sub);
|
const live = getModulePrice(sub);
|
||||||
|
|
@ -370,12 +353,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
>
|
>
|
||||||
<div className="flex-1 pr-2">
|
<div className="flex-1 pr-2">
|
||||||
<div className="flex items-center gap-1.5 flex-wrap">
|
<div className="flex items-center gap-1.5 flex-wrap">
|
||||||
<span className="text-xs font-bold text-slate-800">{sub.name.replace("Nutrition: ", "")}</span>
|
<span className="text-xs font-bold text-slate-800">{sub.name}</span>
|
||||||
{sub.name.includes('Complete Pack') && (
|
|
||||||
<span className="text-[8px] bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-extrabold px-1.5 py-0.5 rounded tracking-wider uppercase">
|
|
||||||
Complete Pack
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
{!isUnlocked && !live.isActive && (
|
{!isUnlocked && !live.isActive && (
|
||||||
<span className="text-[8px] bg-slate-200 text-slate-600 font-bold px-1.5 py-0.5 rounded tracking-wider uppercase">
|
<span className="text-[8px] bg-slate-200 text-slate-600 font-bold px-1.5 py-0.5 rounded tracking-wider uppercase">
|
||||||
Temporarily Unavailable
|
Temporarily Unavailable
|
||||||
|
|
@ -426,7 +404,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Therapeutics: !prev.Therapeutics }))}
|
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Therapeutics: !prev.Therapeutics }))}
|
||||||
className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0"
|
className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0"
|
||||||
>
|
>
|
||||||
{showLockedByCategory.Therapeutics ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Therapeutics')})
|
{showLockedByCategory.Therapeutics ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Therapeutics' && !isModuleUnlocked(m.code)).length})
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
||||||
|
|
@ -441,9 +419,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
{(() => {
|
{(() => {
|
||||||
const items = curriculumModules
|
const items = curriculumModules.filter(m => m.category === 'Therapeutics');
|
||||||
.filter(m => m.category === 'Therapeutics')
|
|
||||||
.sort((a, b) => (a.sortOrder ?? 500) - (b.sortOrder ?? 500));
|
|
||||||
const visible = items.filter(sub => {
|
const visible = items.filter(sub => {
|
||||||
const isUnlocked = isModuleUnlocked(sub.code);
|
const isUnlocked = isModuleUnlocked(sub.code);
|
||||||
const live = getModulePrice(sub);
|
const live = getModulePrice(sub);
|
||||||
|
|
@ -493,7 +469,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
<div className="flex items-center gap-1.5 flex-wrap">
|
<div className="flex items-center gap-1.5 flex-wrap">
|
||||||
<span className="text-xs font-bold text-slate-800">{sub.name.replace("Therapeutics: ", "")}</span>
|
<span className="text-xs font-bold text-slate-800">{sub.name.replace("Therapeutics: ", "")}</span>
|
||||||
{sub.code === 'THERAPEUTICS_CORE' && (
|
{sub.code === 'THERAPEUTICS_CORE' && (
|
||||||
<span className="text-[8px] bg-gradient-to-r from-indigo-500 to-purple-600 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-cyan-500 text-white font-extrabold px-1.5 py-0.5 rounded tracking-wider uppercase">
|
||||||
Complete Pack
|
Complete Pack
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
|
@ -548,7 +524,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Lifetime: !prev.Lifetime }))}
|
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Lifetime: !prev.Lifetime }))}
|
||||||
className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-2 py-1 rounded transition-colors"
|
className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-2 py-1 rounded transition-colors"
|
||||||
>
|
>
|
||||||
{showLockedByCategory.Lifetime ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Lifetime')})
|
{showLockedByCategory.Lifetime ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Lifetime' && !isModuleUnlocked(m.code)).length})
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<h3 className="text-xl font-black text-amber-900 tracking-tight">Lifetime Unlimited Access Pass</h3>
|
<h3 className="text-xl font-black text-amber-900 tracking-tight">Lifetime Unlimited Access Pass</h3>
|
||||||
|
|
@ -573,7 +549,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Lifetime: true }))}
|
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Lifetime: true }))}
|
||||||
className="mt-1 text-xs text-amber-900 hover:text-amber-950 font-bold hover:underline cursor-pointer"
|
className="mt-1 text-xs text-amber-900 hover:text-black font-bold hover:underline cursor-pointer"
|
||||||
>
|
>
|
||||||
Click here to show locked pass
|
Click here to show locked pass
|
||||||
</button>
|
</button>
|
||||||
|
|
@ -647,15 +623,10 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
{/* CARD 6: Custom Packages & Bundles (Dynamic Admin Plans) */}
|
{/* CARD 6: Custom Packages & Bundles (Dynamic Admin Plans) */}
|
||||||
{(() => {
|
{(() => {
|
||||||
const customPlans = publicPlans.filter((p: any) => {
|
const customPlans = publicPlans.filter((p: any) => {
|
||||||
const code = (p.base_code || p.code || '').toUpperCase();
|
const code = p.base_code || p.code;
|
||||||
const activePrice = currency === 'INR' ? (p.price_inr ?? 0) : currency === 'EUR' ? (p.price_eur ?? p.price_usd ?? 0) : (p.price_usd ?? 0);
|
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 && activePrice > 0;
|
const isActive = p.is_active !== false;
|
||||||
if (!isActive || code === 'LIFETIME_ALL' || CORE_PACK_CODES.has(code)) return false;
|
return isCustom && isActive;
|
||||||
if (p.plan_type === 'bundle') return true;
|
|
||||||
const resolvedCat =
|
|
||||||
curriculumModules.find((m) => m.code.toUpperCase() === code)?.category ||
|
|
||||||
resolvePlanCategory(p);
|
|
||||||
return !MAIN_CATEGORIES.has(resolvedCat) && resolvedCat !== 'Lifetime';
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (customPlans.length === 0) return null;
|
if (customPlans.length === 0) return null;
|
||||||
|
|
@ -694,7 +665,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
category: 'Bundle',
|
category: 'Bundle',
|
||||||
priceInr: pInr,
|
priceInr: pInr,
|
||||||
priceUsd: pUsd,
|
priceUsd: pUsd,
|
||||||
priceEur: cPlan.price_eur ?? pUsd,
|
priceEur: pUsd,
|
||||||
desc: cPlan.description || 'Custom bundled access.',
|
desc: cPlan.description || 'Custom bundled access.',
|
||||||
color: 'from-slate-700 to-slate-900'
|
color: 'from-slate-700 to-slate-900'
|
||||||
};
|
};
|
||||||
|
|
@ -746,7 +717,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
</span>
|
</span>
|
||||||
) : (
|
) : (
|
||||||
<span className="text-xs font-extrabold text-slate-700">
|
<span className="text-xs font-extrabold text-slate-700">
|
||||||
{currency === 'INR' ? `₹${pInr}` : currency === 'EUR' ? `€${cPlan.price_eur ?? pUsd}` : `$${pUsd}`}
|
{currency === 'INR' ? `₹${pInr}` : `$${pUsd}`}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
{!isUnlocked && (
|
{!isUnlocked && (
|
||||||
|
|
|
||||||
|
|
@ -1,178 +0,0 @@
|
||||||
import React, { useState, useEffect } from 'react';
|
|
||||||
import { X, Phone, ShieldCheck, RefreshCw, Globe } from 'lucide-react';
|
|
||||||
import { PhoneInput } from '../common/PhoneInput';
|
|
||||||
import { CountrySelect } from '../common/CountrySelect';
|
|
||||||
import { getCountryRuleByName } from '../../constants/countries';
|
|
||||||
import { parsePhoneNumber, validatePhoneNumber, formatE164Phone } from '../../utils/validation';
|
|
||||||
|
|
||||||
interface BillingPhoneModalProps {
|
|
||||||
isOpen: boolean;
|
|
||||||
onClose: () => void;
|
|
||||||
currentPhone?: string | null;
|
|
||||||
currentCountry?: string;
|
|
||||||
onSavePhone: (phoneE164: string, country: string) => Promise<boolean>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const BillingPhoneModal: React.FC<BillingPhoneModalProps> = ({
|
|
||||||
isOpen,
|
|
||||||
onClose,
|
|
||||||
currentPhone,
|
|
||||||
currentCountry = 'India',
|
|
||||||
onSavePhone,
|
|
||||||
}) => {
|
|
||||||
const [dialCode, setDialCode] = useState('+91');
|
|
||||||
const [country, setCountry] = useState(currentCountry);
|
|
||||||
const [phone, setPhone] = useState('');
|
|
||||||
const [saving, setSaving] = useState(false);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (isOpen) {
|
|
||||||
const parsed = parsePhoneNumber(currentPhone, currentCountry);
|
|
||||||
setCountry(parsed.country);
|
|
||||||
setDialCode(parsed.dialCode);
|
|
||||||
setPhone(parsed.localDigits);
|
|
||||||
setError(null);
|
|
||||||
setSaving(false);
|
|
||||||
}
|
|
||||||
}, [isOpen, currentPhone, currentCountry]);
|
|
||||||
|
|
||||||
if (!isOpen) return null;
|
|
||||||
|
|
||||||
const handleCountryChange = (newCountry: string) => {
|
|
||||||
if (newCountry !== country) {
|
|
||||||
setCountry(newCountry);
|
|
||||||
const rule = getCountryRuleByName(newCountry);
|
|
||||||
if (rule) {
|
|
||||||
setDialCode(rule.code);
|
|
||||||
}
|
|
||||||
setPhone('');
|
|
||||||
setError(null);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDialCodeChange = (newCode: string, newCountry: string) => {
|
|
||||||
setDialCode(newCode);
|
|
||||||
if (newCountry !== country) {
|
|
||||||
setCountry(newCountry);
|
|
||||||
setPhone('');
|
|
||||||
}
|
|
||||||
setError(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
if (!phone.trim()) {
|
|
||||||
setError('Please enter your mobile number.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const valError = validatePhoneNumber(phone, dialCode, country);
|
|
||||||
if (valError) {
|
|
||||||
setError(valError);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setSaving(true);
|
|
||||||
const e164 = formatE164Phone(dialCode, phone, country);
|
|
||||||
try {
|
|
||||||
const success = await onSavePhone(e164, country);
|
|
||||||
if (success) {
|
|
||||||
onClose();
|
|
||||||
}
|
|
||||||
} catch (err: any) {
|
|
||||||
setError(err?.message || 'Failed to save billing phone number.');
|
|
||||||
} finally {
|
|
||||||
setSaving(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/70 backdrop-blur-sm animate-fadeIn">
|
|
||||||
<div
|
|
||||||
className="bg-white rounded-3xl max-w-md w-full p-6 shadow-2xl border border-slate-100 space-y-5"
|
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
|
||||||
<div className="flex justify-between items-start">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<div className="h-10 w-10 rounded-2xl bg-indigo-50 border border-indigo-100 flex items-center justify-center text-indigo-600">
|
|
||||||
<Phone className="h-5 w-5" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h3 className="text-base font-black text-slate-800">Billing Contact Number</h3>
|
|
||||||
<p className="text-xs text-slate-400 font-medium">Required for Razorpay invoice & payment updates</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
onClick={onClose}
|
|
||||||
className="p-1 rounded-full text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors"
|
|
||||||
>
|
|
||||||
<X className="h-5 w-5" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-4">
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<label className="text-xs font-bold text-slate-600 flex items-center gap-1">
|
|
||||||
Mobile Number
|
|
||||||
</label>
|
|
||||||
<PhoneInput
|
|
||||||
dialCode={dialCode}
|
|
||||||
phone={phone}
|
|
||||||
country={country}
|
|
||||||
clearOnDialCodeChange={true}
|
|
||||||
onDialCodeChange={handleDialCodeChange}
|
|
||||||
onPhoneChange={(newPhone) => {
|
|
||||||
setPhone(newPhone);
|
|
||||||
setError(null);
|
|
||||||
}}
|
|
||||||
error={error}
|
|
||||||
theme="light"
|
|
||||||
disabled={saving}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<label className="text-xs font-bold text-slate-600 flex items-center gap-1">
|
|
||||||
<Globe className="h-3.5 w-3.5 text-indigo-500" /> Billing Country
|
|
||||||
</label>
|
|
||||||
<CountrySelect
|
|
||||||
value={country}
|
|
||||||
onChange={handleCountryChange}
|
|
||||||
theme="light"
|
|
||||||
size="md"
|
|
||||||
showDialCode={true}
|
|
||||||
showCurrency={false}
|
|
||||||
disabled={saving}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-2 text-[11px] text-slate-500 bg-slate-50 p-3 rounded-xl border border-slate-200/60">
|
|
||||||
<ShieldCheck className="h-4 w-4 text-emerald-500 flex-shrink-0" />
|
|
||||||
<span>This contact number and billing country will appear on your compliance tax invoice and payment receipts.</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex gap-3 pt-2">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onClose}
|
|
||||||
disabled={saving}
|
|
||||||
className="flex-1 py-2.5 px-4 rounded-xl text-xs font-bold bg-slate-100 hover:bg-slate-200 text-slate-600 transition-colors"
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={saving}
|
|
||||||
className="flex-1 py-2.5 px-4 rounded-xl text-xs font-bold bg-indigo-600 hover:bg-indigo-500 text-white transition-colors flex items-center justify-center gap-1.5 shadow-md shadow-indigo-600/20 disabled:opacity-50"
|
|
||||||
>
|
|
||||||
{saving ? <RefreshCw className="h-4 w-4 animate-spin" /> : 'Save Phone Number'}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
@ -1,234 +0,0 @@
|
||||||
import React, { useState, useRef, useEffect, useMemo } from 'react';
|
|
||||||
import { Search, ChevronDown, Check, X } from 'lucide-react';
|
|
||||||
import { SORTED_COUNTRY_CODES, getCountryRuleByName, type CountryCode } from '../../constants/countries';
|
|
||||||
|
|
||||||
export interface CountrySelectProps {
|
|
||||||
value: string;
|
|
||||||
onChange: (country: string) => void;
|
|
||||||
theme?: 'dark' | 'light';
|
|
||||||
size?: 'sm' | 'md';
|
|
||||||
showCurrency?: boolean;
|
|
||||||
showDialCode?: boolean;
|
|
||||||
disabled?: boolean;
|
|
||||||
className?: string;
|
|
||||||
placeholder?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const CountrySelect: React.FC<CountrySelectProps> = ({
|
|
||||||
value,
|
|
||||||
onChange,
|
|
||||||
theme = 'light',
|
|
||||||
size = 'md',
|
|
||||||
showCurrency = false,
|
|
||||||
showDialCode = true,
|
|
||||||
disabled = false,
|
|
||||||
className = '',
|
|
||||||
placeholder = 'Select country',
|
|
||||||
}) => {
|
|
||||||
const [isOpen, setIsOpen] = useState(false);
|
|
||||||
const [searchQuery, setSearchQuery] = useState('');
|
|
||||||
const containerRef = useRef<HTMLDivElement>(null);
|
|
||||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
|
||||||
|
|
||||||
const selectedRule = useMemo(() => {
|
|
||||||
return getCountryRuleByName(value);
|
|
||||||
}, [value]);
|
|
||||||
|
|
||||||
// Focus search input when dropdown opens
|
|
||||||
useEffect(() => {
|
|
||||||
if (isOpen) {
|
|
||||||
setTimeout(() => {
|
|
||||||
searchInputRef.current?.focus();
|
|
||||||
}, 50);
|
|
||||||
} else {
|
|
||||||
setSearchQuery('');
|
|
||||||
}
|
|
||||||
}, [isOpen]);
|
|
||||||
|
|
||||||
// Handle click outside to close dropdown
|
|
||||||
useEffect(() => {
|
|
||||||
const handleClickOutside = (event: MouseEvent) => {
|
|
||||||
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
|
|
||||||
setIsOpen(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleKeyDown = (event: KeyboardEvent) => {
|
|
||||||
if (event.key === 'Escape') {
|
|
||||||
setIsOpen(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (isOpen) {
|
|
||||||
document.addEventListener('mousedown', handleClickOutside);
|
|
||||||
document.addEventListener('keydown', handleKeyDown);
|
|
||||||
}
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
document.removeEventListener('mousedown', handleClickOutside);
|
|
||||||
document.removeEventListener('keydown', handleKeyDown);
|
|
||||||
};
|
|
||||||
}, [isOpen]);
|
|
||||||
|
|
||||||
// Filter countries alphabetically by country name, dial code, or currency
|
|
||||||
const filteredCountries = useMemo(() => {
|
|
||||||
if (!searchQuery.trim()) {
|
|
||||||
return SORTED_COUNTRY_CODES;
|
|
||||||
}
|
|
||||||
const q = searchQuery.toLowerCase().trim();
|
|
||||||
return SORTED_COUNTRY_CODES.filter((c: CountryCode) => {
|
|
||||||
const matchName = c.country.toLowerCase().includes(q);
|
|
||||||
const matchCode = c.code.toLowerCase().includes(q);
|
|
||||||
const matchCurrency = c.currency ? c.currency.toLowerCase().includes(q) : false;
|
|
||||||
return matchName || matchCode || matchCurrency;
|
|
||||||
});
|
|
||||||
}, [searchQuery]);
|
|
||||||
|
|
||||||
const getCurrencySymbol = (curr: string) => {
|
|
||||||
if (curr === 'INR') return '₹';
|
|
||||||
if (curr === 'EUR') return '€';
|
|
||||||
return '$';
|
|
||||||
};
|
|
||||||
|
|
||||||
const getFlag = (cc: CountryCode) => {
|
|
||||||
return cc.label ? cc.label.split(' ')[0] : '🌐';
|
|
||||||
};
|
|
||||||
|
|
||||||
const isDark = theme === 'dark';
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div ref={containerRef} className={`relative w-full ${className}`}>
|
|
||||||
{/* Trigger Button */}
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
disabled={disabled}
|
|
||||||
onClick={() => !disabled && setIsOpen(!isOpen)}
|
|
||||||
className={`w-full flex items-center justify-between text-left transition-colors duration-150 rounded-xl focus:outline-none ${
|
|
||||||
size === 'sm' ? 'px-3 py-2 text-xs font-semibold' : 'px-4 py-2.5 text-sm font-semibold'
|
|
||||||
} ${
|
|
||||||
isDark
|
|
||||||
? 'bg-slate-950 border border-slate-800 text-white focus:border-indigo-500'
|
|
||||||
: 'bg-white border border-slate-200 text-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500'
|
|
||||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-2 truncate pr-2">
|
|
||||||
{selectedRule ? (
|
|
||||||
<>
|
|
||||||
<span className="text-base shrink-0 leading-none">{getFlag(selectedRule)}</span>
|
|
||||||
<span className="truncate">{selectedRule.country}</span>
|
|
||||||
{showDialCode && (
|
|
||||||
<span className={`text-[11px] font-mono shrink-0 ${isDark ? 'text-slate-400' : 'text-slate-500'}`}>
|
|
||||||
({selectedRule.code})
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
{showCurrency && (
|
|
||||||
<span className={`text-[11px] font-normal truncate shrink-0 ${isDark ? 'text-slate-500' : 'text-slate-400'}`}>
|
|
||||||
· {selectedRule.currency} {getCurrencySymbol(selectedRule.currency)}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<span className={isDark ? 'text-slate-500' : 'text-slate-400'}>{placeholder}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<ChevronDown
|
|
||||||
className={`h-4 w-4 shrink-0 transition-transform duration-200 ${
|
|
||||||
isOpen ? 'rotate-180' : ''
|
|
||||||
} ${isDark ? 'text-slate-500' : 'text-slate-400'}`}
|
|
||||||
/>
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{/* Dropdown Menu */}
|
|
||||||
{isOpen && (
|
|
||||||
<div
|
|
||||||
className={`absolute left-0 right-0 top-full mt-1.5 z-50 rounded-2xl shadow-2xl border overflow-hidden flex flex-col animate-in fade-in zoom-in-95 duration-150 ${
|
|
||||||
isDark
|
|
||||||
? 'bg-slate-900 border-slate-800 text-white'
|
|
||||||
: 'bg-white border-slate-200 text-slate-800'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{/* Search Box */}
|
|
||||||
<div className={`p-2.5 border-b shrink-0 ${isDark ? 'border-slate-800 bg-slate-950/60' : 'border-slate-100 bg-slate-50/70'}`}>
|
|
||||||
<div className="relative">
|
|
||||||
<Search
|
|
||||||
className={`absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 ${
|
|
||||||
isDark ? 'text-slate-500' : 'text-slate-400'
|
|
||||||
}`}
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
ref={searchInputRef}
|
|
||||||
type="text"
|
|
||||||
value={searchQuery}
|
|
||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
|
||||||
placeholder="Search country name or code..."
|
|
||||||
className={`w-full rounded-xl pl-8 pr-8 py-1.5 text-xs font-semibold focus:outline-none transition-colors ${
|
|
||||||
isDark
|
|
||||||
? 'bg-slate-950 border border-slate-800 text-white placeholder:text-slate-600 focus:border-indigo-500'
|
|
||||||
: 'bg-white border border-slate-200 text-slate-800 placeholder:text-slate-400 focus:border-indigo-500'
|
|
||||||
}`}
|
|
||||||
/>
|
|
||||||
{searchQuery && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setSearchQuery('')}
|
|
||||||
className={`absolute right-2.5 top-1/2 -translate-y-1/2 p-0.5 rounded-full hover:bg-slate-200/50 ${
|
|
||||||
isDark ? 'text-slate-400 hover:text-white' : 'text-slate-400 hover:text-slate-600'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<X className="h-3 w-3" />
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Options List */}
|
|
||||||
<div className="max-h-56 overflow-y-auto overscroll-contain py-1">
|
|
||||||
{filteredCountries.length === 0 ? (
|
|
||||||
<div className={`p-4 text-center text-xs ${isDark ? 'text-slate-500' : 'text-slate-400'}`}>
|
|
||||||
No countries found matching “{searchQuery}”
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
filteredCountries.map((c) => {
|
|
||||||
const isSelected = c.country.toLowerCase() === value.toLowerCase();
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={`${c.country}-${c.code}`}
|
|
||||||
type="button"
|
|
||||||
onClick={() => {
|
|
||||||
onChange(c.country);
|
|
||||||
setIsOpen(false);
|
|
||||||
setSearchQuery('');
|
|
||||||
}}
|
|
||||||
className={`w-full flex items-center justify-between px-3.5 py-2 text-left text-xs transition-colors cursor-pointer ${
|
|
||||||
isSelected
|
|
||||||
? isDark
|
|
||||||
? 'bg-indigo-600/20 text-indigo-400 font-bold'
|
|
||||||
: 'bg-indigo-50 text-indigo-700 font-bold'
|
|
||||||
: isDark
|
|
||||||
? 'hover:bg-slate-800/80 text-slate-200'
|
|
||||||
: 'hover:bg-slate-50 text-slate-700'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-2.5 min-w-0 pr-2">
|
|
||||||
<span className="text-base shrink-0 leading-none">{getFlag(c)}</span>
|
|
||||||
<span className="truncate">{c.country}</span>
|
|
||||||
<span className={`text-[10px] font-mono shrink-0 ${isDark ? 'text-slate-500' : 'text-slate-400'}`}>
|
|
||||||
({c.code})
|
|
||||||
</span>
|
|
||||||
{showCurrency && (
|
|
||||||
<span className={`text-[10px] shrink-0 font-normal ${isDark ? 'text-slate-500' : 'text-slate-400'}`}>
|
|
||||||
· {c.currency} {getCurrencySymbol(c.currency)}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{isSelected && <Check className="h-3.5 w-3.5 shrink-0 text-indigo-500" />}
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
})
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
@ -1,331 +0,0 @@
|
||||||
import React, { useState, useRef, useEffect, useMemo } from 'react';
|
|
||||||
import { Search, ChevronDown, Check, X } from 'lucide-react';
|
|
||||||
import {
|
|
||||||
COUNTRY_CODES,
|
|
||||||
SORTED_COUNTRY_CODES,
|
|
||||||
getCountryRuleByDialCode,
|
|
||||||
getCountryRuleByName,
|
|
||||||
type CountryCode,
|
|
||||||
} from '../../constants/countries';
|
|
||||||
import { cleanPhoneInput } from '../../utils/validation';
|
|
||||||
|
|
||||||
export interface PhoneInputProps {
|
|
||||||
dialCode: string;
|
|
||||||
phone: string; // local digits only
|
|
||||||
country?: string;
|
|
||||||
onDialCodeChange?: (newCode: string, newCountry: string) => void;
|
|
||||||
onPhoneChange: (newPhone: string) => void;
|
|
||||||
error?: string | null;
|
|
||||||
disabled?: boolean;
|
|
||||||
theme?: 'dark' | 'light';
|
|
||||||
id?: string;
|
|
||||||
clearOnDialCodeChange?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const PhoneInput: React.FC<PhoneInputProps> = ({
|
|
||||||
dialCode,
|
|
||||||
phone,
|
|
||||||
country,
|
|
||||||
onDialCodeChange,
|
|
||||||
onPhoneChange,
|
|
||||||
error,
|
|
||||||
disabled = false,
|
|
||||||
theme = 'dark',
|
|
||||||
id = 'phone-input',
|
|
||||||
clearOnDialCodeChange = false,
|
|
||||||
}) => {
|
|
||||||
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
|
|
||||||
const [searchQuery, setSearchQuery] = useState('');
|
|
||||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
|
||||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
|
||||||
|
|
||||||
// Prioritize country name if available, fallback to dial code
|
|
||||||
let activeRule = country ? getCountryRuleByName(country) : undefined;
|
|
||||||
if (!activeRule && dialCode) {
|
|
||||||
activeRule = getCountryRuleByDialCode(dialCode, country);
|
|
||||||
}
|
|
||||||
if (!activeRule) {
|
|
||||||
activeRule = getCountryRuleByDialCode('+91')!;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Focus search input when dropdown opens
|
|
||||||
useEffect(() => {
|
|
||||||
if (isDropdownOpen) {
|
|
||||||
setTimeout(() => {
|
|
||||||
searchInputRef.current?.focus();
|
|
||||||
}, 50);
|
|
||||||
} else {
|
|
||||||
setSearchQuery('');
|
|
||||||
}
|
|
||||||
}, [isDropdownOpen]);
|
|
||||||
|
|
||||||
// Handle click outside to close dropdown
|
|
||||||
useEffect(() => {
|
|
||||||
const handleClickOutside = (event: MouseEvent) => {
|
|
||||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
|
||||||
setIsDropdownOpen(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleKeyDown = (event: KeyboardEvent) => {
|
|
||||||
if (event.key === 'Escape') {
|
|
||||||
setIsDropdownOpen(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (isDropdownOpen) {
|
|
||||||
document.addEventListener('mousedown', handleClickOutside);
|
|
||||||
document.addEventListener('keydown', handleKeyDown);
|
|
||||||
}
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
document.removeEventListener('mousedown', handleClickOutside);
|
|
||||||
document.removeEventListener('keydown', handleKeyDown);
|
|
||||||
};
|
|
||||||
}, [isDropdownOpen]);
|
|
||||||
|
|
||||||
// Filter countries alphabetically by country name or dial code
|
|
||||||
const filteredCountryCodes = useMemo(() => {
|
|
||||||
if (!searchQuery.trim()) {
|
|
||||||
return SORTED_COUNTRY_CODES;
|
|
||||||
}
|
|
||||||
const q = searchQuery.toLowerCase().trim();
|
|
||||||
return SORTED_COUNTRY_CODES.filter((c: CountryCode) => {
|
|
||||||
const matchCountry = c.country.toLowerCase().includes(q);
|
|
||||||
const matchCode = c.code.toLowerCase().includes(q);
|
|
||||||
const rawCode = c.code.replace('+', '');
|
|
||||||
const matchRaw = rawCode.includes(q);
|
|
||||||
return matchCountry || matchCode || matchRaw;
|
|
||||||
});
|
|
||||||
}, [searchQuery]);
|
|
||||||
|
|
||||||
const getFlag = (cc: CountryCode) => {
|
|
||||||
return cc.label ? cc.label.split(' ')[0] : '🌐';
|
|
||||||
};
|
|
||||||
|
|
||||||
const isSelected = (cc: CountryCode) => {
|
|
||||||
if (country) {
|
|
||||||
return cc.country.toLowerCase() === country.toLowerCase() && cc.code === dialCode;
|
|
||||||
}
|
|
||||||
return cc.code === dialCode;
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSelectCountry = (cc: CountryCode) => {
|
|
||||||
if (onDialCodeChange) {
|
|
||||||
onDialCodeChange(cc.code, cc.country);
|
|
||||||
}
|
|
||||||
if (clearOnDialCodeChange) {
|
|
||||||
onPhoneChange('');
|
|
||||||
} else {
|
|
||||||
onPhoneChange(cleanPhoneInput(phone, cc.maxLength, false));
|
|
||||||
}
|
|
||||||
setIsDropdownOpen(false);
|
|
||||||
setSearchQuery('');
|
|
||||||
};
|
|
||||||
|
|
||||||
const handlePhoneInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const inputVal = e.target.value;
|
|
||||||
const trimmed = inputVal.trim();
|
|
||||||
|
|
||||||
// Check if input contains an explicit international prefix '+'
|
|
||||||
if (trimmed.startsWith('+')) {
|
|
||||||
const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length);
|
|
||||||
const matched = sorted.find((c) => trimmed.startsWith(c.code));
|
|
||||||
if (matched) {
|
|
||||||
if (onDialCodeChange && (matched.code !== dialCode || matched.country !== country)) {
|
|
||||||
onDialCodeChange(matched.code, matched.country);
|
|
||||||
}
|
|
||||||
const rest = trimmed.slice(matched.code.length).replace(/\D/g, '');
|
|
||||||
onPhoneChange(rest.slice(0, matched.maxLength));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if input was pasted with dial code digits without '+' (e.g. 919876543210)
|
|
||||||
const dialDigits = activeRule.code.replace(/\D/g, '');
|
|
||||||
const rawDigits = trimmed.replace(/\D/g, '');
|
|
||||||
if (
|
|
||||||
dialDigits &&
|
|
||||||
rawDigits.startsWith(dialDigits) &&
|
|
||||||
rawDigits.length > activeRule.maxLength
|
|
||||||
) {
|
|
||||||
const rest = rawDigits.slice(dialDigits.length);
|
|
||||||
onPhoneChange(rest.slice(0, activeRule.maxLength));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Strictly numeric local digits, capped at active country's maxLength
|
|
||||||
const cleaned = cleanPhoneInput(inputVal, activeRule.maxLength, false);
|
|
||||||
onPhoneChange(cleaned);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
|
||||||
// Allow navigation keys, backspace, delete, tab, copy/paste shortcuts
|
|
||||||
if (
|
|
||||||
['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab', 'Enter', 'Escape'].includes(e.key) ||
|
|
||||||
(e.ctrlKey || e.metaKey)
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Allow '+' as leading character to support international number paste/typing
|
|
||||||
if (e.key === '+' && (e.currentTarget.selectionStart === 0 || !phone)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Block any non-digit
|
|
||||||
if (!/^\d$/.test(e.key)) {
|
|
||||||
e.preventDefault();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const isDark = theme === 'dark';
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-1.5 w-full">
|
|
||||||
<div className="flex gap-2 w-full">
|
|
||||||
{/* Searchable Country Code Dropdown */}
|
|
||||||
<div ref={dropdownRef} className="relative shrink-0">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
disabled={disabled}
|
|
||||||
onClick={() => !disabled && setIsDropdownOpen(!isDropdownOpen)}
|
|
||||||
className={`w-[110px] flex items-center justify-between rounded-xl px-2.5 py-2.5 text-xs font-semibold cursor-pointer focus:outline-none transition-colors ${
|
|
||||||
isDark
|
|
||||||
? 'bg-slate-950 border border-slate-800 text-white focus:border-indigo-500'
|
|
||||||
: 'bg-white border border-slate-200 text-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500'
|
|
||||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-1.5 truncate">
|
|
||||||
<span className="text-sm shrink-0 leading-none">{getFlag(activeRule)}</span>
|
|
||||||
<span className="font-mono text-xs font-bold">{activeRule.code}</span>
|
|
||||||
</div>
|
|
||||||
<ChevronDown
|
|
||||||
className={`h-3.5 w-3.5 shrink-0 text-slate-400 transition-transform duration-200 ${
|
|
||||||
isDropdownOpen ? 'rotate-180' : ''
|
|
||||||
}`}
|
|
||||||
/>
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{/* Searchable Dropdown Popover */}
|
|
||||||
{isDropdownOpen && (
|
|
||||||
<div
|
|
||||||
className={`absolute left-0 top-full mt-1.5 z-50 w-72 sm:w-80 rounded-2xl shadow-2xl border overflow-hidden flex flex-col animate-in fade-in zoom-in-95 duration-150 ${
|
|
||||||
isDark
|
|
||||||
? 'bg-slate-900 border-slate-800 text-white'
|
|
||||||
: 'bg-white border-slate-200 text-slate-800'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{/* Search Box */}
|
|
||||||
<div
|
|
||||||
className={`p-2.5 border-b shrink-0 ${
|
|
||||||
isDark ? 'border-slate-800 bg-slate-950/60' : 'border-slate-100 bg-slate-50/70'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<div className="relative">
|
|
||||||
<Search
|
|
||||||
className={`absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 ${
|
|
||||||
isDark ? 'text-slate-500' : 'text-slate-400'
|
|
||||||
}`}
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
ref={searchInputRef}
|
|
||||||
type="text"
|
|
||||||
value={searchQuery}
|
|
||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
|
||||||
placeholder="Search country or code..."
|
|
||||||
className={`w-full rounded-xl pl-8 pr-8 py-1.5 text-xs font-semibold focus:outline-none transition-colors ${
|
|
||||||
isDark
|
|
||||||
? 'bg-slate-950 border border-slate-800 text-white placeholder:text-slate-600 focus:border-indigo-500'
|
|
||||||
: 'bg-white border border-slate-200 text-slate-800 placeholder:text-slate-400 focus:border-indigo-500'
|
|
||||||
}`}
|
|
||||||
/>
|
|
||||||
{searchQuery && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setSearchQuery('')}
|
|
||||||
className={`absolute right-2.5 top-1/2 -translate-y-1/2 p-0.5 rounded-full hover:bg-slate-200/50 ${
|
|
||||||
isDark ? 'text-slate-400 hover:text-white' : 'text-slate-400 hover:text-slate-600'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<X className="h-3 w-3" />
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Alphabetically Sorted Options List */}
|
|
||||||
<div className="max-h-60 overflow-y-auto overscroll-contain py-1">
|
|
||||||
{filteredCountryCodes.length === 0 ? (
|
|
||||||
<div
|
|
||||||
className={`p-4 text-center text-xs ${
|
|
||||||
isDark ? 'text-slate-500' : 'text-slate-400'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
No country codes found matching “{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 */}
|
|
||||||
<input
|
|
||||||
id={id}
|
|
||||||
type="tel"
|
|
||||||
inputMode="numeric"
|
|
||||||
autoComplete="tel-national"
|
|
||||||
value={phone}
|
|
||||||
onChange={handlePhoneInputChange}
|
|
||||||
onKeyDown={handleKeyDown}
|
|
||||||
placeholder={activeRule.placeholder || 'Mobile Number'}
|
|
||||||
maxLength={activeRule.maxLength}
|
|
||||||
disabled={disabled}
|
|
||||||
className={`min-w-0 flex-1 rounded-xl px-3.5 py-2.5 text-xs sm:text-sm font-semibold focus:outline-none transition-colors ${
|
|
||||||
isDark
|
|
||||||
? 'bg-slate-950 border border-slate-800 text-white placeholder:text-slate-600 focus:border-indigo-500'
|
|
||||||
: 'bg-white border border-slate-200 text-slate-800 placeholder:text-slate-400 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500'
|
|
||||||
} ${error ? 'border-rose-500 focus:border-rose-500' : ''} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{error && (
|
|
||||||
<p className="text-[11px] font-semibold text-rose-500 animate-shake">
|
|
||||||
{error}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
@ -3,8 +3,8 @@ import { Sparkles, LogIn, UserPlus, BookOpen, CheckCircle } from 'lucide-react';
|
||||||
import type { UserProfile } from '../../types';
|
import type { UserProfile } from '../../types';
|
||||||
|
|
||||||
interface StoreHeaderProps {
|
interface StoreHeaderProps {
|
||||||
activeTab: 'storefront' | 'subscriptions' | 'logged-out';
|
activeTab: 'storefront' | 'subscriptions';
|
||||||
onSwitchTab: (tab: 'storefront' | 'subscriptions' | 'logged-out') => void;
|
onSwitchTab: (tab: 'storefront' | 'subscriptions') => void;
|
||||||
loggedInUser: UserProfile | null;
|
loggedInUser: UserProfile | null;
|
||||||
onOpenProfile: () => void;
|
onOpenProfile: () => void;
|
||||||
onOpenAuth: (mode: 'login' | 'register') => void;
|
onOpenAuth: (mode: 'login' | 'register') => void;
|
||||||
|
|
@ -18,116 +18,85 @@ export const StoreHeader: React.FC<StoreHeaderProps> = ({
|
||||||
onOpenAuth,
|
onOpenAuth,
|
||||||
}) => {
|
}) => {
|
||||||
return (
|
return (
|
||||||
<header className="w-full bg-[#0A0A0E] text-slate-300 border-b border-slate-800 px-4 sm:px-6 py-3 sm:py-4 shadow-lg flex-shrink-0">
|
<header className="w-full bg-[#0A0A0E] text-slate-300 border-b border-slate-800 px-6 py-4 flex items-center justify-between shadow-lg flex-shrink-0">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center gap-6">
|
||||||
<div className="flex items-center gap-6">
|
<div
|
||||||
<div
|
onClick={() => onSwitchTab('storefront')}
|
||||||
onClick={() => onSwitchTab('storefront')}
|
className="flex items-center gap-3 cursor-pointer group"
|
||||||
className="flex items-center gap-3 cursor-pointer group"
|
>
|
||||||
>
|
<div className="h-10 w-10 rounded-xl bg-gradient-to-tr from-indigo-500 to-cyan-400 flex items-center justify-center shadow-md shadow-indigo-500/20 group-hover:scale-105 transition-transform">
|
||||||
<div className="h-10 w-10 rounded-xl bg-gradient-to-tr from-indigo-500 to-cyan-400 flex items-center justify-center shadow-md shadow-indigo-500/20 group-hover:scale-105 transition-transform">
|
<Sparkles className="h-5 w-5 text-white" />
|
||||||
<Sparkles className="h-5 w-5 text-white" />
|
</div>
|
||||||
</div>
|
<div>
|
||||||
<div>
|
<h1 className="text-base font-black tracking-tight text-white flex items-center gap-1">
|
||||||
<h1 className="text-base font-black tracking-tight text-white flex items-center gap-1">
|
ACUPEDIA
|
||||||
ACUPEDIA
|
</h1>
|
||||||
</h1>
|
<p className="text-[9px] text-slate-400 font-bold tracking-widest uppercase">TCM PLATFORM</p>
|
||||||
<p className="text-[9px] text-slate-400 font-bold tracking-widest uppercase">TCM PLATFORM</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Desktop Navigation Tabs */}
|
|
||||||
<nav className="hidden sm:flex items-center bg-slate-900/80 border border-slate-800 rounded-xl p-1 gap-1">
|
|
||||||
<button
|
|
||||||
onClick={() => onSwitchTab('storefront')}
|
|
||||||
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${
|
|
||||||
activeTab === 'storefront'
|
|
||||||
? 'bg-indigo-600 text-white shadow-sm'
|
|
||||||
: 'text-slate-400 hover:text-slate-200'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<BookOpen className="h-3.5 w-3.5" /> Storefront
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => onSwitchTab('subscriptions')}
|
|
||||||
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${
|
|
||||||
activeTab === 'subscriptions'
|
|
||||||
? 'bg-indigo-600 text-white shadow-sm'
|
|
||||||
: 'text-slate-400 hover:text-slate-200'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<CheckCircle className="h-3.5 w-3.5" /> My Subscriptions
|
|
||||||
{loggedInUser?.active_subscriptions && loggedInUser.active_subscriptions.length > 0 && (
|
|
||||||
<span className="bg-indigo-900 text-indigo-200 text-[10px] px-1.5 py-0.2 rounded-full ml-0.5">
|
|
||||||
{loggedInUser.active_subscriptions.length}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
</nav>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
{/* Navigation Tabs */}
|
||||||
{loggedInUser ? (
|
<nav className="hidden sm:flex items-center bg-slate-900/80 border border-slate-800 rounded-xl p-1 gap-1">
|
||||||
<button
|
<button
|
||||||
onClick={onOpenProfile}
|
onClick={() => onSwitchTab('storefront')}
|
||||||
className="flex items-center gap-3 hover:text-white transition-colors group focus:outline-none"
|
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${
|
||||||
>
|
activeTab === 'storefront'
|
||||||
<div className="text-right hidden sm:block">
|
? 'bg-indigo-600 text-white shadow-sm'
|
||||||
<p className="text-xs font-bold text-white truncate max-w-[150px]">
|
: 'text-slate-400 hover:text-slate-200'
|
||||||
{loggedInUser.display_name || loggedInUser.email}
|
}`}
|
||||||
</p>
|
>
|
||||||
</div>
|
<BookOpen className="h-3.5 w-3.5" /> Storefront
|
||||||
<div className="h-9 w-9 rounded-lg bg-indigo-950/60 border border-indigo-500/30 flex items-center justify-center text-indigo-400 font-bold text-sm group-hover:border-indigo-400 transition-colors">
|
</button>
|
||||||
{(loggedInUser.display_name || loggedInUser.email || 'U')[0].toUpperCase()}
|
<button
|
||||||
</div>
|
onClick={() => onSwitchTab('subscriptions')}
|
||||||
</button>
|
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${
|
||||||
) : (
|
activeTab === 'subscriptions'
|
||||||
<div className="flex gap-2">
|
? 'bg-indigo-600 text-white shadow-sm'
|
||||||
<button
|
: 'text-slate-400 hover:text-slate-200'
|
||||||
onClick={() => onOpenAuth('login')}
|
}`}
|
||||||
className="flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-bold bg-slate-800 hover:bg-slate-700 text-slate-300 transition-colors"
|
>
|
||||||
>
|
<CheckCircle className="h-3.5 w-3.5" /> My Subscriptions
|
||||||
<LogIn className="h-3.5 w-3.5" /> Login
|
{loggedInUser?.active_subscriptions && loggedInUser.active_subscriptions.length > 0 && (
|
||||||
</button>
|
<span className="bg-indigo-900 text-indigo-200 text-[10px] px-1.5 py-0.2 rounded-full ml-0.5">
|
||||||
<button
|
{loggedInUser.active_subscriptions.length}
|
||||||
onClick={() => onOpenAuth('register')}
|
</span>
|
||||||
className="flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-bold bg-indigo-600 hover:bg-indigo-500 text-white transition-colors shadow shadow-indigo-600/10"
|
)}
|
||||||
>
|
</button>
|
||||||
<UserPlus className="h-3.5 w-3.5" /> Join
|
</nav>
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Mobile Navigation Tabs */}
|
<div className="flex items-center gap-3">
|
||||||
<nav className="sm:hidden flex items-center bg-slate-900/90 border border-slate-800 rounded-xl p-1 mt-3 gap-1 w-full">
|
{loggedInUser ? (
|
||||||
<button
|
<button
|
||||||
onClick={() => onSwitchTab('storefront')}
|
onClick={onOpenProfile}
|
||||||
className={`flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-colors ${
|
className="flex items-center gap-3 hover:text-white transition-colors group focus:outline-none"
|
||||||
activeTab === 'storefront'
|
>
|
||||||
? 'bg-indigo-600 text-white shadow-sm'
|
<div className="text-right hidden sm:block">
|
||||||
: 'text-slate-400 hover:text-slate-200'
|
<p className="text-xs font-bold text-white truncate max-w-[150px]">
|
||||||
}`}
|
{loggedInUser.display_name || loggedInUser.email}
|
||||||
>
|
</p>
|
||||||
<BookOpen className="h-3.5 w-3.5" /> Storefront
|
</div>
|
||||||
</button>
|
<div className="h-9 w-9 rounded-lg bg-indigo-950/60 border border-indigo-500/30 flex items-center justify-center text-indigo-400 font-bold text-sm group-hover:border-indigo-400 transition-colors">
|
||||||
<button
|
{(loggedInUser.display_name || loggedInUser.email || 'U')[0].toUpperCase()}
|
||||||
onClick={() => onSwitchTab('subscriptions')}
|
</div>
|
||||||
className={`flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-colors ${
|
</button>
|
||||||
activeTab === 'subscriptions'
|
) : (
|
||||||
? 'bg-indigo-600 text-white shadow-sm'
|
<div className="flex gap-2">
|
||||||
: 'text-slate-400 hover:text-slate-200'
|
<button
|
||||||
}`}
|
onClick={() => onOpenAuth('login')}
|
||||||
>
|
className="flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-bold bg-slate-800 hover:bg-slate-700 text-slate-300 transition-colors"
|
||||||
<CheckCircle className="h-3.5 w-3.5" /> My Subscriptions
|
>
|
||||||
{loggedInUser?.active_subscriptions && loggedInUser.active_subscriptions.length > 0 && (
|
<LogIn className="h-3.5 w-3.5" /> Login
|
||||||
<span className="bg-indigo-900 text-indigo-200 text-[10px] px-1.5 py-0.2 rounded-full ml-1 font-semibold">
|
</button>
|
||||||
{loggedInUser.active_subscriptions.length}
|
<button
|
||||||
</span>
|
onClick={() => onOpenAuth('register')}
|
||||||
)}
|
className="flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-bold bg-indigo-600 hover:bg-indigo-500 text-white transition-colors shadow shadow-indigo-600/10"
|
||||||
</button>
|
>
|
||||||
</nav>
|
<UserPlus className="h-3.5 w-3.5" /> Join
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</header>
|
</header>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,6 @@
|
||||||
import type { CountryCode as LibCountryCode } from 'libphonenumber-js';
|
|
||||||
import type { Currency } from '../types';
|
import type { Currency } from '../types';
|
||||||
|
|
||||||
export interface CountryCode {
|
export interface CountryCode {
|
||||||
iso2: LibCountryCode;
|
|
||||||
code: string;
|
code: string;
|
||||||
label: string;
|
label: string;
|
||||||
country: string;
|
country: string;
|
||||||
|
|
@ -10,128 +8,121 @@ export interface CountryCode {
|
||||||
minLength: number;
|
minLength: number;
|
||||||
maxLength: number;
|
maxLength: number;
|
||||||
placeholder: string;
|
placeholder: string;
|
||||||
validPrefixes?: string[];
|
|
||||||
example?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const COUNTRY_CODES: CountryCode[] = [
|
export const COUNTRY_CODES: CountryCode[] = [
|
||||||
// South Asia
|
// South Asia
|
||||||
{ iso2: 'IN', code: '+91', label: '🇮🇳 +91', country: 'India', currency: 'INR', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['6', '7', '8', '9'], example: '98765 43210' },
|
{ code: '+91', label: '🇮🇳 +91', country: 'India', currency: 'INR', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||||
{ iso2: 'PK', code: '+92', label: '🇵🇰 +92', country: 'Pakistan', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['3'], example: '300 1234567' },
|
{ code: '+92', label: '🇵🇰 +92', country: 'Pakistan', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||||
{ iso2: 'BD', code: '+880', label: '🇧🇩 +880', country: 'Bangladesh', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['1'], example: '1712 345678' },
|
{ code: '+880', label: '🇧🇩 +880', country: 'Bangladesh', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||||
{ iso2: 'LK', code: '+94', label: '🇱🇰 +94', country: 'Sri Lanka', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['7'], example: '71 234 5678' },
|
{ code: '+94', label: '🇱🇰 +94', country: 'Sri Lanka', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ iso2: 'NP', code: '+977', label: '🇳🇵 +977', country: 'Nepal', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['97', '98'], example: '9812 345678' },
|
{ code: '+977', label: '🇳🇵 +977', country: 'Nepal', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||||
{ iso2: 'BT', code: '+975', label: '🇧🇹 +975', country: 'Bhutan', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['16', '17', '77'], example: '1712 3456' },
|
{ code: '+975', label: '🇧🇹 +975', country: 'Bhutan', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||||
{ iso2: 'MV', code: '+960', label: '🇲🇻 +960', country: 'Maldives', currency: 'USD', minLength: 7, maxLength: 7, placeholder: '7-digit mobile number', validPrefixes: ['7', '9'], example: '791 2345' },
|
{ code: '+960', label: '🇲🇻 +960', country: 'Maldives', currency: 'USD', minLength: 7, maxLength: 7, placeholder: '7-digit mobile number' },
|
||||||
|
|
||||||
// North America
|
// North America
|
||||||
{ iso2: 'US', code: '+1', label: '🇺🇸 +1', country: 'United States', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit phone number', example: '202 555 0123' },
|
{ code: '+1', label: '🇺🇸 +1', country: 'United States', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit phone number' },
|
||||||
{ iso2: 'CA', code: '+1', label: '🇨🇦 +1', country: 'Canada', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit phone number', example: '416 555 0123' },
|
{ code: '+1', label: '🇨🇦 +1', country: 'Canada', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit phone number' },
|
||||||
{ iso2: 'MX', code: '+52', label: '🇲🇽 +52', country: 'Mexico', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', example: '55 1234 5678' },
|
{ code: '+52', label: '🇲🇽 +52', country: 'Mexico', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||||
|
|
||||||
// Europe & UK
|
// Europe & UK
|
||||||
{ iso2: 'GB', code: '+44', label: '🇬🇧 +44', country: 'United Kingdom', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['7'], example: '7123 456789' },
|
{ code: '+44', label: '🇬🇧 +44', country: 'United Kingdom', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
|
||||||
{ 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' },
|
{ code: '+49', label: '🇩🇪 +49', country: 'Germany', currency: 'EUR', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
|
||||||
{ 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' },
|
{ code: '+33', label: '🇫🇷 +33', country: 'France', currency: 'EUR', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
|
||||||
{ 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' },
|
{ code: '+39', label: '🇮🇹 +39', country: 'Italy', currency: 'EUR', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
|
||||||
{ 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' },
|
{ code: '+34', label: '🇪🇸 +34', country: 'Spain', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ iso2: 'NL', code: '+31', label: '🇳🇱 +31', country: 'Netherlands', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['6'], example: '6 12345678' },
|
{ code: '+31', label: '🇳🇱 +31', country: 'Netherlands', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+41', label: '🇨🇭 +41', country: 'Switzerland', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+32', label: '🇧🇪 +32', country: 'Belgium', currency: 'EUR', minLength: 8, maxLength: 9, placeholder: '8 to 9 digits' },
|
||||||
{ iso2: 'AT', code: '+43', label: '🇦🇹 +43', country: 'Austria', currency: 'EUR', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['6'], example: '664 1234567' },
|
{ code: '+43', label: '🇦🇹 +43', country: 'Austria', currency: 'EUR', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
|
||||||
{ 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' },
|
{ code: '+353', label: '🇮🇪 +353', country: 'Ireland', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+46', label: '🇸🇪 +46', country: 'Sweden', currency: 'EUR', minLength: 7, maxLength: 10, placeholder: '7 to 10 digits' },
|
||||||
{ 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' },
|
{ code: '+47', label: '🇳🇴 +47', country: 'Norway', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||||
{ iso2: 'DK', code: '+45', label: '🇩🇰 +45', country: 'Denmark', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', example: '20 12 34 56' },
|
{ code: '+45', label: '🇩🇰 +45', country: 'Denmark', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+358', label: '🇫🇮 +358', country: 'Finland', currency: 'EUR', minLength: 7, maxLength: 10, placeholder: '7 to 10 digits' },
|
||||||
{ 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' },
|
{ code: '+351', label: '🇵🇹 +351', country: 'Portugal', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+30', label: '🇬🇷 +30', country: 'Greece', currency: 'EUR', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+48', label: '🇵🇱 +48', country: 'Poland', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+420', label: '🇨🇿 +420', country: 'Czech Republic', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+36', label: '🇭🇺 +36', country: 'Hungary', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+40', label: '🇷🇴 +40', country: 'Romania', currency: 'EUR', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
|
||||||
{ 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' },
|
{ code: '+380', label: '🇺🇦 +380', country: 'Ukraine', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+354', label: '🇮🇸 +354', country: 'Iceland', currency: 'EUR', minLength: 7, maxLength: 9, placeholder: '7 to 9 digits' },
|
||||||
{ 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' },
|
{ code: '+352', label: '🇱🇺 +352', country: 'Luxembourg', currency: 'EUR', minLength: 8, maxLength: 10, placeholder: '8 to 10 digits' },
|
||||||
{ 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' },
|
{ code: '+385', label: '🇭🇷 +385', country: 'Croatia', currency: 'EUR', minLength: 8, maxLength: 9, placeholder: '8 to 9 digits' },
|
||||||
{ 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' },
|
{ code: '+421', label: '🇸🇰 +421', country: 'Slovakia', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+359', label: '🇧🇬 +359', country: 'Bulgaria', currency: 'EUR', minLength: 8, maxLength: 9, placeholder: '8 to 9 digits' },
|
||||||
{ iso2: 'CY', code: '+357', label: '🇨🇾 +357', country: 'Cyprus', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit phone number', validPrefixes: ['9'], example: '96 123456' },
|
{ code: '+7', label: '🇷🇺 +7', country: 'Russia', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||||
{ iso2: 'EE', code: '+372', label: '🇪🇪 +372', country: 'Estonia', currency: 'EUR', minLength: 7, maxLength: 8, placeholder: '7 to 8 digits', validPrefixes: ['5'], example: '512 3456' },
|
{ code: '+90', label: '🇹🇷 +90', country: 'Turkey', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||||
{ 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
|
// Asia-Pacific
|
||||||
{ iso2: 'AU', code: '+61', label: '🇦🇺 +61', country: 'Australia', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['4'], example: '412 345 678' },
|
{ code: '+61', label: '🇦🇺 +61', country: 'Australia', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
|
||||||
{ 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' },
|
{ code: '+64', label: '🇳🇿 +64', country: 'New Zealand', currency: 'USD', minLength: 8, maxLength: 10, placeholder: '8 to 10 digits' },
|
||||||
{ 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' },
|
{ code: '+81', label: '🇯🇵 +81', country: 'Japan', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
|
||||||
{ 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' },
|
{ code: '+86', label: '🇨🇳 +86', country: 'China', currency: 'USD', minLength: 11, maxLength: 11, placeholder: '11-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+82', label: '🇰🇷 +82', country: 'South Korea', currency: 'USD', minLength: 9, maxLength: 11, placeholder: '9 to 11 digits' },
|
||||||
{ 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' },
|
{ code: '+852', label: '🇭🇰 +852', country: 'Hong Kong', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+886', label: '🇹🇼 +886', country: 'Taiwan', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+65', label: '🇸🇬 +65', country: 'Singapore', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+60', label: '🇲🇾 +60', country: 'Malaysia', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
|
||||||
{ 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' },
|
{ code: '+62', label: '🇮🇩 +62', country: 'Indonesia', currency: 'USD', minLength: 9, maxLength: 12, placeholder: '9 to 12 digits' },
|
||||||
{ 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' },
|
{ code: '+63', label: '🇵🇭 +63', country: 'Philippines', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+66', label: '🇹🇭 +66', country: 'Thailand', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+84', label: '🇻🇳 +84', country: 'Vietnam', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
|
||||||
|
|
||||||
// Middle East
|
// Middle East
|
||||||
{ iso2: 'AE', code: '+971', label: '🇦🇪 +971', country: 'UAE', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['5'], example: '50 123 4567' },
|
{ code: '+971', label: '🇦🇪 +971', country: 'UAE', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+966', label: '🇸🇦 +966', country: 'Saudi Arabia', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+974', label: '🇶🇦 +974', country: 'Qatar', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+965', label: '🇰🇼 +965', country: 'Kuwait', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+968', label: '🇴🇲 +968', country: 'Oman', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+973', label: '🇧🇭 +973', country: 'Bahrain', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+972', label: '🇮🇱 +972', country: 'Israel', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+962', label: '🇯🇴 +962', country: 'Jordan', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+961', label: '🇱🇧 +961', country: 'Lebanon', currency: 'USD', minLength: 7, maxLength: 8, placeholder: '7 to 8 digits' },
|
||||||
|
|
||||||
// Latin America
|
// Latin America
|
||||||
{ iso2: 'BR', code: '+55', label: '🇧🇷 +55', country: 'Brazil', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['9'], example: '11 91234 5678' },
|
{ code: '+55', label: '🇧🇷 +55', country: 'Brazil', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
|
||||||
{ 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' },
|
{ code: '+54', label: '🇦🇷 +54', country: 'Argentina', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
|
||||||
{ 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' },
|
{ code: '+56', label: '🇨🇱 +56', country: 'Chile', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+57', label: '🇨🇴 +57', country: 'Colombia', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+51', label: '🇵🇪 +51', country: 'Peru', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
|
|
||||||
// Africa
|
// Africa
|
||||||
{ iso2: 'ZA', code: '+27', label: '🇿🇦 +27', country: 'South Africa', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['6', '7', '8'], example: '71 234 5678' },
|
{ code: '+27', label: '🇿🇦 +27', country: 'South Africa', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits' },
|
||||||
{ 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' },
|
{ code: '+234', label: '🇳🇬 +234', country: 'Nigeria', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits' },
|
||||||
{ 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' },
|
{ code: '+254', label: '🇰🇪 +254', country: 'Kenya', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+233', label: '🇬🇭 +233', country: 'Ghana', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+20', label: '🇪🇬 +20', country: 'Egypt', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number' },
|
||||||
{ 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' },
|
{ code: '+212', label: '🇲🇦 +212', country: 'Morocco', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number' },
|
||||||
{ iso2: 'MU', code: '+230', label: '🇲🇺 +230', country: 'Mauritius', currency: 'USD', minLength: 7, maxLength: 8, placeholder: '7 to 8 digits', validPrefixes: ['5'], example: '5123 4567' },
|
{ code: '+230', label: '🇲🇺 +230', country: 'Mauritius', currency: 'USD', minLength: 7, maxLength: 8, placeholder: '7 to 8 digits' },
|
||||||
];
|
];
|
||||||
|
|
||||||
// Alphabetically sorted list of countries (A-Z)
|
|
||||||
export const SORTED_COUNTRY_CODES: CountryCode[] = [...COUNTRY_CODES].sort((a, b) =>
|
|
||||||
a.country.localeCompare(b.country)
|
|
||||||
);
|
|
||||||
|
|
||||||
export const DEFAULT_COUNTRY = COUNTRY_CODES[0]; // India (+91)
|
export const DEFAULT_COUNTRY = COUNTRY_CODES[0]; // India (+91)
|
||||||
|
|
||||||
export const getCountryRuleByIso = (iso?: string | null): CountryCode => {
|
export const getCountryRuleByDialCode = (dialCode: string): CountryCode => {
|
||||||
if (!iso) return DEFAULT_COUNTRY;
|
return (
|
||||||
const upper = iso.toUpperCase().trim();
|
COUNTRY_CODES.find((c) => c.code === dialCode) || {
|
||||||
return COUNTRY_CODES.find((c) => c.iso2 === upper) || DEFAULT_COUNTRY;
|
code: dialCode,
|
||||||
|
label: dialCode,
|
||||||
|
country: 'Other',
|
||||||
|
currency: 'USD',
|
||||||
|
minLength: 7,
|
||||||
|
maxLength: 15,
|
||||||
|
placeholder: 'Phone number',
|
||||||
|
}
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getCountryRuleByName = (countryName?: string | null): CountryCode => {
|
export const getCountryRuleByName = (countryName: string): CountryCode => {
|
||||||
if (!countryName) return DEFAULT_COUNTRY;
|
if (!countryName) return DEFAULT_COUNTRY;
|
||||||
const normalized = countryName.toLowerCase().trim();
|
const normalized = countryName.toLowerCase().trim();
|
||||||
return (
|
return (
|
||||||
COUNTRY_CODES.find(
|
COUNTRY_CODES.find(
|
||||||
(c) =>
|
(c) =>
|
||||||
c.country.toLowerCase() === normalized ||
|
c.country.toLowerCase() === normalized ||
|
||||||
c.iso2.toLowerCase() === normalized ||
|
|
||||||
normalized.includes(c.country.toLowerCase())
|
normalized.includes(c.country.toLowerCase())
|
||||||
) || {
|
) || {
|
||||||
iso2: 'IN',
|
|
||||||
code: '+91',
|
code: '+91',
|
||||||
label: '🇮🇳 +91',
|
label: '🇮🇳 +91',
|
||||||
country: countryName,
|
country: countryName,
|
||||||
|
|
@ -142,26 +133,3 @@ export const getCountryRuleByName = (countryName?: string | null): 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
|
// 4. Therapeutics Category
|
||||||
{ code: 'THERAPEUTICS_GYNAE', name: 'Therapeutics: Gynecology', category: 'Therapeutics', priceInr: 600, priceUsd: 15.0, priceEur: 15.0, desc: '1 Year: Unlocks advanced clinical Gynecology treatment protocols, syndromes, and corresponding points.', color: 'from-teal-500 to-cyan-500' },
|
{ code: 'THERAPEUTICS_GYNAE', name: 'Therapeutics: Gynecology', category: 'Therapeutics', priceInr: 600, priceUsd: 15.0, priceEur: 15.0, desc: '1 Year: Unlocks advanced clinical Gynecology treatment protocols, syndromes, and corresponding points.', color: 'from-teal-500 to-cyan-500' },
|
||||||
{ code: 'THERAPEUTICS_EAR', name: 'Therapeutics: Ear reflexology', category: 'Therapeutics', priceInr: 600, priceUsd: 15.0, priceEur: 15.0, desc: '1 Year: Unlocks comprehensive ear micro-system treatment procedures and specific clinical ear protocols.', color: 'from-cyan-500 to-blue-600' },
|
{ code: 'THERAPEUTICS_EAR', name: 'Therapeutics: Ear reflexology', category: 'Therapeutics', priceInr: 600, priceUsd: 15.0, priceEur: 15.0, desc: '1 Year: Unlocks comprehensive ear micro-system treatment procedures and specific clinical ear protocols.', color: 'from-cyan-500 to-blue-600' },
|
||||||
{ code: 'THERAPEUTICS_CORE', name: 'Therapeutics: Complete 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' },
|
{ 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' },
|
||||||
|
|
||||||
// 5. Lifetime Access
|
// 5. Lifetime Access
|
||||||
{ code: 'LIFETIME_ALL', name: 'Lifetime Unlimited Access Pass', category: 'Lifetime', priceInr: 15000, priceUsd: 350.0, priceEur: 350.0, desc: '10 Years: Unlock all 10 current modules + all future updates. Includes official master clinical certificate.', color: 'from-yellow-500 to-amber-600' }
|
{ code: 'LIFETIME_ALL', name: 'Lifetime Unlimited Access Pass', category: 'Lifetime', priceInr: 15000, priceUsd: 350.0, priceEur: 350.0, desc: '10 Years: Unlock all 10 current modules + all future updates. Includes official master clinical certificate.', color: 'from-yellow-500 to-amber-600' }
|
||||||
|
|
|
||||||
|
|
@ -10,8 +10,6 @@ export interface ModuleItem {
|
||||||
desc: string;
|
desc: string;
|
||||||
color: string;
|
color: string;
|
||||||
isRenewal?: boolean;
|
isRenewal?: boolean;
|
||||||
sortOrder?: number;
|
|
||||||
planType?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserSubscription {
|
export interface UserSubscription {
|
||||||
|
|
@ -39,7 +37,6 @@ export interface UserProfile {
|
||||||
roles?: string[];
|
roles?: string[];
|
||||||
external_ref?: string;
|
external_ref?: string;
|
||||||
active_subscriptions: UserSubscription[];
|
active_subscriptions: UserSubscription[];
|
||||||
unlocked_module_codes?: string[];
|
|
||||||
unlocked_module_slugs?: string[];
|
unlocked_module_slugs?: string[];
|
||||||
created_at?: string;
|
created_at?: string;
|
||||||
}
|
}
|
||||||
|
|
@ -79,28 +76,15 @@ export interface PublicPlan {
|
||||||
code: string;
|
code: string;
|
||||||
base_code?: string;
|
base_code?: string;
|
||||||
name: string;
|
name: string;
|
||||||
plan_type?: string;
|
|
||||||
billing_period?: string;
|
|
||||||
price_inr?: number;
|
price_inr?: number;
|
||||||
price_usd?: number;
|
price_usd?: number;
|
||||||
price_eur?: number;
|
price_eur?: number;
|
||||||
is_active?: boolean;
|
is_active?: boolean;
|
||||||
pricing_status?: string;
|
|
||||||
color?: string;
|
|
||||||
badge_text?: string;
|
badge_text?: string;
|
||||||
heading?: string;
|
heading?: string;
|
||||||
subtitle?: string;
|
subtitle?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
modules?: Array<{
|
modules?: Array<{ id?: string; name: string; slug?: string }>;
|
||||||
id?: string;
|
|
||||||
code?: string;
|
|
||||||
name: string;
|
|
||||||
slug?: string;
|
|
||||||
description?: string;
|
|
||||||
category?: string;
|
|
||||||
sort_order?: number;
|
|
||||||
}>;
|
|
||||||
module_slugs?: string[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface VerificationResult {
|
export interface VerificationResult {
|
||||||
|
|
|
||||||
|
|
@ -1,223 +0,0 @@
|
||||||
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,24 +1,4 @@
|
||||||
import { parsePhoneNumberFromString, type CountryCode as LibCountryCode } from 'libphonenumber-js/max';
|
import { COUNTRY_CODES, getCountryRuleByDialCode, getCountryRuleByName } from '../constants/countries';
|
||||||
import {
|
|
||||||
COUNTRY_CODES,
|
|
||||||
getCountryRuleByDialCode,
|
|
||||||
getCountryRuleByName,
|
|
||||||
getCountryRuleByIso,
|
|
||||||
DEFAULT_COUNTRY,
|
|
||||||
} from '../constants/countries';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Formats a list of prefixes into human-readable text:
|
|
||||||
* e.g. ['3'] -> "3"
|
|
||||||
* e.g. ['6', '7'] -> "6 or 7"
|
|
||||||
* e.g. ['6', '7', '8', '9'] -> "6, 7, 8, or 9"
|
|
||||||
*/
|
|
||||||
export const formatPrefixList = (prefixes: string[]): string => {
|
|
||||||
if (prefixes.length === 0) return '';
|
|
||||||
if (prefixes.length === 1) return prefixes[0];
|
|
||||||
if (prefixes.length === 2) return `${prefixes[0]} or ${prefixes[1]}`;
|
|
||||||
return `${prefixes.slice(0, -1).join(', ')}, or ${prefixes[prefixes.length - 1]}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Strips non-numeric / non-phone characters from text in real-time
|
* Strips non-numeric / non-phone characters from text in real-time
|
||||||
|
|
@ -35,8 +15,8 @@ export const cleanPhoneInput = (text: string, maxLength = 15, allowPlus = true):
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates mobile phone number according to country telecom numbering plans.
|
* Validates phone number according to country rules (e.g. India = exactly 10 digits)
|
||||||
* Uses libphonenumber-js to enforce mobile prefixes (e.g., France 06/07, India 6-9, UK 07).
|
* Strictly disallows alphabetic characters and invalid symbols
|
||||||
*/
|
*/
|
||||||
export const validatePhoneNumber = (
|
export const validatePhoneNumber = (
|
||||||
val?: string | null,
|
val?: string | null,
|
||||||
|
|
@ -51,8 +31,8 @@ export const validatePhoneNumber = (
|
||||||
return 'Phone number cannot contain alphabetic characters.';
|
return 'Phone number cannot contain alphabetic characters.';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Strictly disallow hyphens, dashes, and invalid symbols
|
// Strictly disallow hyphens, dashes, and invalid characters
|
||||||
if (/[\-_()/[\]]/.test(trimmed)) {
|
if (/[\-()_]/.test(trimmed)) {
|
||||||
return 'Phone number cannot contain hyphens or special symbols.';
|
return 'Phone number cannot contain hyphens or special symbols.';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -66,71 +46,54 @@ export const validatePhoneNumber = (
|
||||||
return 'Please enter a valid phone number with numeric digits.';
|
return 'Please enter a valid phone number with numeric digits.';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resolve country rule: prioritize explicit country name, fallback to dialCode
|
// Resolve country rule by dial code or country name
|
||||||
let rule = country ? getCountryRuleByName(country) : undefined;
|
let rule = dialCode ? getCountryRuleByDialCode(dialCode) : undefined;
|
||||||
if ((!rule || rule.country === 'Other') && dialCode) {
|
if ((!rule || rule.country === 'Other') && country) {
|
||||||
rule = getCountryRuleByDialCode(dialCode, country);
|
rule = getCountryRuleByName(country);
|
||||||
}
|
}
|
||||||
if (!rule) {
|
// Default to India if no specific rule resolved and dial code is +91 or country is India
|
||||||
rule = DEFAULT_COUNTRY;
|
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.`;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Generic prefix validation for mobile telecom numbering plans
|
if (rule && rule.country !== 'Other') {
|
||||||
if (rule.validPrefixes && rule.validPrefixes.length > 0) {
|
const dialDigits = rule.code.replace(/\D/g, '');
|
||||||
const hasValidPrefix = rule.validPrefixes.some(
|
let localDigits = allDigits;
|
||||||
(prefix) => digitsWithoutTrunk0.startsWith(prefix) || nationalDigits.startsWith(prefix)
|
|
||||||
);
|
// If formatted with country code (e.g. +919876543210 or 919876543210 where total length > rule.maxLength), strip country prefix
|
||||||
if (!hasValidPrefix) {
|
if (
|
||||||
return `For ${rule.country}, the mobile number must start with ${formatPrefixList(rule.validPrefixes)}.`;
|
(trimmed.startsWith('+') || allDigits.length > rule.maxLength) &&
|
||||||
|
allDigits.startsWith(dialDigits) &&
|
||||||
|
allDigits.length === dialDigits.length + rule.minLength
|
||||||
|
) {
|
||||||
|
localDigits = allDigits.slice(dialDigits.length);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Validate telecom numbering rules with libphonenumber-js
|
if (rule.minLength === rule.maxLength) {
|
||||||
const candidate = trimmed.startsWith('+') ? trimmed : `${rule.code}${nationalDigits}`;
|
if (localDigits.length !== rule.minLength) {
|
||||||
const parsed = parsePhoneNumberFromString(candidate, iso2);
|
return `${rule.country} phone number must be exactly ${rule.minLength} digits.`;
|
||||||
|
}
|
||||||
if (parsed && parsed.isValid()) {
|
} else {
|
||||||
const numberType = parsed.getType();
|
if (localDigits.length < rule.minLength) {
|
||||||
if (numberType === 'FIXED_LINE') {
|
return `${rule.country} phone number must be at least ${rule.minLength} digits.`;
|
||||||
return `Please enter a valid mobile number for ${rule.country} (landlines not allowed).`;
|
}
|
||||||
|
if (localDigits.length > rule.maxLength) {
|
||||||
|
return `${rule.country} phone number cannot exceed ${rule.maxLength} digits.`;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const exampleStr = rule.example || rule.placeholder;
|
// General fallback ITU E.164
|
||||||
return `Please enter a valid mobile number for ${rule.country}${exampleStr ? ` (e.g. ${exampleStr})` : ''}.`;
|
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;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const isValidPhoneNumber = (
|
export const isValidPhoneNumber = (
|
||||||
|
|
@ -141,100 +104,6 @@ export const isValidPhoneNumber = (
|
||||||
return validatePhoneNumber(val, dialCode, country) === null;
|
return validatePhoneNumber(val, dialCode, country) === null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Splits a full phone number into dialCode, country, and localDigits
|
|
||||||
*/
|
|
||||||
export const parsePhoneNumber = (
|
|
||||||
fullPhone?: string | null,
|
|
||||||
fallbackCountry = 'India'
|
|
||||||
): { country: string; dialCode: string; localDigits: string; iso2: LibCountryCode } => {
|
|
||||||
const defaultRule = getCountryRuleByName(fallbackCountry) || DEFAULT_COUNTRY;
|
|
||||||
if (!fullPhone || !fullPhone.trim()) {
|
|
||||||
return {
|
|
||||||
country: defaultRule.country,
|
|
||||||
dialCode: defaultRule.code,
|
|
||||||
localDigits: '',
|
|
||||||
iso2: defaultRule.iso2,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const trimmed = fullPhone.trim();
|
|
||||||
const parsed = parsePhoneNumberFromString(trimmed, defaultRule.iso2);
|
|
||||||
|
|
||||||
if (parsed) {
|
|
||||||
const matchedRule = parsed.country
|
|
||||||
? getCountryRuleByIso(parsed.country)
|
|
||||||
: getCountryRuleByDialCode(`+${parsed.countryCallingCode}`, fallbackCountry);
|
|
||||||
|
|
||||||
return {
|
|
||||||
country: matchedRule.country,
|
|
||||||
dialCode: `+${parsed.countryCallingCode}`,
|
|
||||||
localDigits: parsed.nationalNumber,
|
|
||||||
iso2: matchedRule.iso2,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback regex match from longest dial code
|
|
||||||
const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length);
|
|
||||||
|
|
||||||
// If fallbackCountry is specified and matches the prefix, prioritize it
|
|
||||||
if (fallbackCountry && trimmed.startsWith(defaultRule.code)) {
|
|
||||||
const rawLocal = trimmed.slice(defaultRule.code.length).replace(/\D/g, '');
|
|
||||||
return {
|
|
||||||
country: defaultRule.country,
|
|
||||||
dialCode: defaultRule.code,
|
|
||||||
localDigits: rawLocal.slice(0, defaultRule.maxLength),
|
|
||||||
iso2: defaultRule.iso2,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const matched = sorted.find((c) => trimmed.startsWith(c.code));
|
|
||||||
if (matched) {
|
|
||||||
const rawLocal = trimmed.slice(matched.code.length).replace(/\D/g, '');
|
|
||||||
return {
|
|
||||||
country: matched.country,
|
|
||||||
dialCode: matched.code,
|
|
||||||
localDigits: rawLocal.slice(0, matched.maxLength),
|
|
||||||
iso2: matched.iso2,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const rawDigits = trimmed.replace(/\D/g, '');
|
|
||||||
return {
|
|
||||||
country: defaultRule.country,
|
|
||||||
dialCode: defaultRule.code,
|
|
||||||
localDigits: rawDigits.slice(0, defaultRule.maxLength),
|
|
||||||
iso2: defaultRule.iso2,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Formats full phone number cleanly as E.164 without spaces (+<dialCode><digits>),
|
|
||||||
* automatically stripping any national trunk '0' where appropriate.
|
|
||||||
*/
|
|
||||||
export const formatE164Phone = (dialCode: string, localDigits: string, country?: string): string => {
|
|
||||||
if (!localDigits || !localDigits.trim()) return '';
|
|
||||||
const rule = country ? getCountryRuleByName(country) : getCountryRuleByDialCode(dialCode, country);
|
|
||||||
const rawDigits = localDigits.replace(/\D/g, '');
|
|
||||||
if (!rawDigits) return '';
|
|
||||||
|
|
||||||
const code = dialCode.startsWith('+') ? dialCode : `+${dialCode}`;
|
|
||||||
const candidate = localDigits.startsWith('+') ? localDigits : `${code}${rawDigits}`;
|
|
||||||
|
|
||||||
const parsed = parsePhoneNumberFromString(candidate, rule.iso2);
|
|
||||||
if (parsed && parsed.isValid()) {
|
|
||||||
return parsed.format('E.164');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: If starts with trunk 0 and country is not one that keeps trunk 0 (like Italy)
|
|
||||||
let cleanLocal = rawDigits;
|
|
||||||
if (rule.iso2 !== 'IT' && cleanLocal.startsWith('0')) {
|
|
||||||
cleanLocal = cleanLocal.replace(/^0+/, '');
|
|
||||||
}
|
|
||||||
|
|
||||||
return `${code}${cleanLocal}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates the dial code prefix of an existing phone number when country changes.
|
* Updates the dial code prefix of an existing phone number when country changes.
|
||||||
* Automatically clamps remaining digits to the new country's maxLength.
|
* Automatically clamps remaining digits to the new country's maxLength.
|
||||||
|
|
@ -250,8 +119,27 @@ export const updatePhoneDialCode = (
|
||||||
const oldRule = getCountryRuleByName(oldCountry);
|
const oldRule = getCountryRuleByName(oldCountry);
|
||||||
const newRule = getCountryRuleByName(newCountry);
|
const newRule = getCountryRuleByName(newCountry);
|
||||||
|
|
||||||
const parsed = parsePhoneNumber(trimmed, oldRule.country);
|
let nationalDigits = '';
|
||||||
const bounded = parsed.localDigits.slice(0, newRule.maxLength);
|
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);
|
||||||
return bounded ? `${newRule.code} ${bounded}` : `${newRule.code} `;
|
return bounded ? `${newRule.code} ${bounded}` : `${newRule.code} `;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -293,6 +181,8 @@ export const validatePassword = (password: string, fieldName = 'Password'): stri
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* RFC 5322 & RFC 1035 compliant email validation regex.
|
* 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,}$/;
|
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,}$/;
|
||||||
|
|
||||||
|
|
@ -309,3 +199,4 @@ export const validateEmail = (email?: string | null): string | null => {
|
||||||
export const isValidEmail = (email?: string | null): boolean => {
|
export const isValidEmail = (email?: string | null): boolean => {
|
||||||
return validateEmail(email) === null;
|
return validateEmail(email) === null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,106 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,65 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,130 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,221 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,395 +0,0 @@
|
||||||
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();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,243 +0,0 @@
|
||||||
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),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
@ -1,87 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,85 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,502 +0,0 @@
|
||||||
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/');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,144 +0,0 @@
|
||||||
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');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,143 +0,0 @@
|
||||||
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');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,71 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,142 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,110 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,68 +0,0 @@
|
||||||
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');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,107 +0,0 @@
|
||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,57 +0,0 @@
|
||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,126 +0,0 @@
|
||||||
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 });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,161 +0,0 @@
|
||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,129 +0,0 @@
|
||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,75 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,52 +0,0 @@
|
||||||
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',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,18 +0,0 @@
|
||||||
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);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
import '@testing-library/jest-dom/vitest';
|
|
||||||
import { cleanup } from '@testing-library/react';
|
|
||||||
import { afterEach } from 'vitest';
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
cleanup();
|
|
||||||
});
|
|
||||||
|
|
@ -1,49 +0,0 @@
|
||||||
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');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,164 +0,0 @@
|
||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,32 +1,11 @@
|
||||||
import { defineConfig } from 'vite'
|
import { defineConfig } from 'vite'
|
||||||
import react from '@vitejs/plugin-react'
|
import react from '@vitejs/plugin-react'
|
||||||
|
|
||||||
const rawBase = process.env.VITE_BASE_PATH || '/store/'
|
|
||||||
const baseWithoutSlash = rawBase.endsWith('/') ? rawBase.slice(0, -1) : rawBase
|
|
||||||
|
|
||||||
// https://vite.dev/config/
|
// https://vite.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
base: rawBase,
|
base: process.env.VITE_BASE_PATH || '/store/',
|
||||||
plugins: [
|
plugins: [react()],
|
||||||
react(),
|
|
||||||
{
|
|
||||||
name: 'redirect-base-middleware',
|
|
||||||
configureServer(server) {
|
|
||||||
server.middlewares.use((req, res, next) => {
|
|
||||||
const [pathname, search] = (req.url || '').split('?')
|
|
||||||
if (baseWithoutSlash && pathname === baseWithoutSlash) {
|
|
||||||
const target = `${rawBase}${search ? `?${search}` : ''}`
|
|
||||||
res.writeHead(302, { Location: target })
|
|
||||||
res.end()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
next()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
],
|
|
||||||
server: {
|
server: {
|
||||||
port: 3000,
|
port: 3000,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,25 +0,0 @@
|
||||||
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