Compare commits
No commits in common. "main" and "plan-access-update" have entirely different histories.
main
...
plan-acces
|
|
@ -1,8 +0,0 @@
|
||||||
node_modules
|
|
||||||
dist
|
|
||||||
.git
|
|
||||||
.env
|
|
||||||
.env.local
|
|
||||||
npm-debug.log*
|
|
||||||
yarn-debug.log*
|
|
||||||
yarn-error.log*
|
|
||||||
|
|
@ -1,2 +0,0 @@
|
||||||
Branch: phone-code
|
|
||||||
Commit: 57cf92f4a68510b598927e96163f4cce5d75c309
|
|
||||||
|
|
@ -27,12 +27,3 @@ dist-ssr
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
|
|
||||||
# Generated Git Info
|
|
||||||
.git_*_info
|
|
||||||
|
|
||||||
# Playwright & Coverage
|
|
||||||
playwright-report/
|
|
||||||
test-results/
|
|
||||||
coverage/
|
|
||||||
|
|
||||||
|
|
|
||||||
37
Dockerfile
37
Dockerfile
|
|
@ -1,37 +0,0 @@
|
||||||
# ============================================================
|
|
||||||
# Panacea Storefront — Frontend Dockerfile
|
|
||||||
# Multi-stage: Node 22 build → Nginx alpine runtime
|
|
||||||
# ============================================================
|
|
||||||
|
|
||||||
FROM node:22-alpine AS builder
|
|
||||||
|
|
||||||
WORKDIR /app
|
|
||||||
|
|
||||||
# Copy package files and install dependencies
|
|
||||||
COPY package.json package-lock.json ./
|
|
||||||
RUN npm ci
|
|
||||||
|
|
||||||
# Copy store frontend source files
|
|
||||||
COPY . ./
|
|
||||||
|
|
||||||
ARG VITE_API_BASE=""
|
|
||||||
ENV VITE_API_BASE=${VITE_API_BASE}
|
|
||||||
ARG VITE_BASE_PATH="/store/"
|
|
||||||
ENV VITE_BASE_PATH=${VITE_BASE_PATH}
|
|
||||||
|
|
||||||
RUN npm run build
|
|
||||||
|
|
||||||
FROM nginx:1.27-alpine AS runtime
|
|
||||||
|
|
||||||
RUN rm /etc/nginx/conf.d/default.conf
|
|
||||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
|
||||||
COPY --from=builder /app/dist /usr/share/nginx/html
|
|
||||||
|
|
||||||
# Copy git info metadata if generated on host
|
|
||||||
COPY .git_store_info* /app/.git_store_info
|
|
||||||
|
|
||||||
RUN ln -sf /usr/share/nginx/html /usr/share/nginx/html/store
|
|
||||||
|
|
||||||
EXPOSE 80
|
|
||||||
|
|
||||||
CMD ["nginx", "-g", "daemon off;"]
|
|
||||||
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
|
|
||||||
```
|
|
||||||
56
nginx.conf
56
nginx.conf
|
|
@ -1,56 +0,0 @@
|
||||||
# ============================================================
|
|
||||||
# Panacea Storefront — Nginx Configuration (Port 3000)
|
|
||||||
# Serves storefront static files at /store + reverse proxies /api
|
|
||||||
# ============================================================
|
|
||||||
|
|
||||||
server {
|
|
||||||
listen 80;
|
|
||||||
server_name _;
|
|
||||||
|
|
||||||
root /usr/share/nginx/html;
|
|
||||||
index index.html;
|
|
||||||
|
|
||||||
gzip on;
|
|
||||||
gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript image/svg+xml;
|
|
||||||
gzip_min_length 256;
|
|
||||||
|
|
||||||
# Reverse proxy — Route /api requests to FastAPI backend
|
|
||||||
location /api/ {
|
|
||||||
proxy_pass http://backend:8000;
|
|
||||||
proxy_set_header Host $host;
|
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
|
||||||
|
|
||||||
proxy_http_version 1.1;
|
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
|
||||||
proxy_set_header Connection "upgrade";
|
|
||||||
|
|
||||||
proxy_connect_timeout 60s;
|
|
||||||
proxy_send_timeout 120s;
|
|
||||||
proxy_read_timeout 120s;
|
|
||||||
}
|
|
||||||
|
|
||||||
# Handle /store subpath
|
|
||||||
location ^~ /store {
|
|
||||||
rewrite ^/store/?(.*)$ /$1 break;
|
|
||||||
try_files $uri $uri/ /index.html;
|
|
||||||
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
|
||||||
add_header Pragma "no-cache";
|
|
||||||
add_header Expires 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
# Root fallback
|
|
||||||
location / {
|
|
||||||
try_files $uri $uri/ /index.html;
|
|
||||||
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
|
||||||
add_header Pragma "no-cache";
|
|
||||||
add_header Expires 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
# Cache static assets
|
|
||||||
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
|
|
||||||
expires 30d;
|
|
||||||
add_header Cache-Control "public, immutable";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
771
src/App.tsx
771
src/App.tsx
File diff suppressed because it is too large
Load Diff
|
|
@ -3,9 +3,7 @@ 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 } from '../../constants/countries';
|
||||||
import { CountrySelect } from '../common/CountrySelect';
|
|
||||||
import { PhoneInput } from '../common/PhoneInput';
|
|
||||||
|
|
||||||
interface AuthModalProps {
|
interface AuthModalProps {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
|
|
@ -82,8 +80,8 @@ export const AuthModal: React.FC<AuthModalProps> = ({
|
||||||
if (!isOpen) return null;
|
if (!isOpen) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-[100] flex items-center justify-center p-3 sm:p-4 bg-slate-950/70 backdrop-blur-md transition-all duration-300 overflow-y-auto">
|
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-slate-950/70 backdrop-blur-md transition-all duration-300">
|
||||||
<div className="relative w-full max-w-md bg-slate-900 border border-slate-800 rounded-3xl p-5 sm:p-6 md:p-8 space-y-4 sm:space-y-6 shadow-2xl text-slate-100 max-h-[92vh] overflow-y-auto my-auto">
|
<div className="relative w-full max-w-md bg-slate-900 border border-slate-800 rounded-3xl p-6 md:p-8 space-y-6 shadow-2xl text-slate-100">
|
||||||
{/* Close button */}
|
{/* Close button */}
|
||||||
<button
|
<button
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
|
|
@ -101,14 +99,14 @@ export const AuthModal: React.FC<AuthModalProps> = ({
|
||||||
{authMode === 'login'
|
{authMode === 'login'
|
||||||
? 'Welcome Back!'
|
? 'Welcome Back!'
|
||||||
: authMode === 'register'
|
: authMode === 'register'
|
||||||
? 'Create Account'
|
? 'Create Clinical Account'
|
||||||
: 'Reset Password'}
|
: 'Reset Password'}
|
||||||
</h3>
|
</h3>
|
||||||
<p className="text-xs text-slate-400 leading-relaxed font-semibold">
|
<p className="text-xs text-slate-400 leading-relaxed font-semibold">
|
||||||
{authMode === 'login'
|
{authMode === 'login'
|
||||||
? 'Sign in to access your saved TCM modules and invoices.'
|
? 'Sign in to access your saved TCM modules and invoices.'
|
||||||
: authMode === 'register'
|
: authMode === 'register'
|
||||||
? 'Sign up to get started and access TCM modules.'
|
? 'Onboard as a clinical practitioner to access TCM modules.'
|
||||||
: resetStep === 'request'
|
: resetStep === 'request'
|
||||||
? 'Enter your registered email to receive a 6-digit verification code.'
|
? 'Enter your registered email to receive a 6-digit verification code.'
|
||||||
: 'Enter the 6-digit code sent to your email and your new password.'}
|
: 'Enter the 6-digit code sent to your email and your new password.'}
|
||||||
|
|
@ -134,7 +132,7 @@ export const AuthModal: React.FC<AuthModalProps> = ({
|
||||||
{/* Forgot Password Flow */}
|
{/* Forgot Password Flow */}
|
||||||
{authMode === 'forgot' ? (
|
{authMode === 'forgot' ? (
|
||||||
resetStep === 'request' ? (
|
resetStep === 'request' ? (
|
||||||
<form onSubmit={onForgotPasswordRequest} noValidate className="space-y-4 text-left">
|
<form onSubmit={onForgotPasswordRequest} className="space-y-4 text-left">
|
||||||
<div className="space-y-1.5">
|
<div className="space-y-1.5">
|
||||||
<label className="text-[10px] uppercase font-black tracking-wider text-slate-500">
|
<label className="text-[10px] uppercase font-black tracking-wider text-slate-500">
|
||||||
Registered Email Address
|
Registered Email Address
|
||||||
|
|
@ -171,7 +169,7 @@ export const AuthModal: React.FC<AuthModalProps> = ({
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
) : (
|
) : (
|
||||||
<form onSubmit={onResetPasswordSubmit} noValidate className="space-y-4 text-left">
|
<form onSubmit={onResetPasswordSubmit} className="space-y-4 text-left">
|
||||||
<div className="space-y-1.5">
|
<div className="space-y-1.5">
|
||||||
<label className="text-[10px] uppercase font-black tracking-wider text-slate-500">
|
<label className="text-[10px] uppercase font-black tracking-wider text-slate-500">
|
||||||
6-Digit Verification Code (OTP)
|
6-Digit Verification Code (OTP)
|
||||||
|
|
@ -249,7 +247,7 @@ export const AuthModal: React.FC<AuthModalProps> = ({
|
||||||
)
|
)
|
||||||
) : (
|
) : (
|
||||||
/* Standard Login & Register Form */
|
/* Standard Login & Register Form */
|
||||||
<form onSubmit={onAuthSubmit} noValidate className="space-y-4 text-left">
|
<form onSubmit={onAuthSubmit} className="space-y-4 text-left">
|
||||||
{/* Common: Email */}
|
{/* Common: Email */}
|
||||||
<div className="space-y-1.5">
|
<div className="space-y-1.5">
|
||||||
<label className="text-[10px] uppercase font-black tracking-wider text-slate-500">
|
<label className="text-[10px] uppercase font-black tracking-wider text-slate-500">
|
||||||
|
|
@ -288,26 +286,29 @@ 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">
|
||||||
dialCode={authDialCode}
|
<div className="relative">
|
||||||
phone={authPhone}
|
<select
|
||||||
country={authCountry}
|
value={authDialCode}
|
||||||
clearOnDialCodeChange={true}
|
onChange={(e) => setAuthDialCode(e.target.value)}
|
||||||
onDialCodeChange={(newCode, newCountry) => {
|
className="w-[90px] bg-slate-950 border border-slate-800 rounded-xl px-3 py-2.5 text-sm font-semibold text-white focus:outline-none focus:border-indigo-500 appearance-none"
|
||||||
setAuthDialCode(newCode);
|
>
|
||||||
setAuthCountry(newCountry);
|
{COUNTRY_CODES.map((cc) => (
|
||||||
setAuthPhone('');
|
<option key={cc.code} value={cc.code}>
|
||||||
}}
|
{cc.label}
|
||||||
onPhoneChange={(newPhone) => {
|
</option>
|
||||||
setAuthPhone(newPhone);
|
))}
|
||||||
if (authError && (authError.toLowerCase().includes('phone') || authError.toLowerCase().includes('mobile'))) {
|
</select>
|
||||||
setAuthError(null);
|
</div>
|
||||||
}
|
<input
|
||||||
}}
|
type="tel"
|
||||||
theme="dark"
|
value={authPhone}
|
||||||
error={authError && (authError.toLowerCase().includes('phone') || authError.toLowerCase().includes('mobile')) ? authError : null}
|
onChange={(e) => setAuthPhone(e.target.value)}
|
||||||
|
placeholder="9876543210"
|
||||||
|
className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-4 py-2.5 text-sm font-semibold text-white focus:outline-none focus:border-indigo-500 placeholder:text-slate-700"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Register exclusive: Country */}
|
{/* Register exclusive: Country */}
|
||||||
|
|
@ -316,23 +317,22 @@ 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">
|
||||||
|
<select
|
||||||
value={authCountry}
|
value={authCountry}
|
||||||
onChange={(newCountry) => {
|
onChange={(e) => setAuthCountry(e.target.value)}
|
||||||
if (newCountry !== authCountry) {
|
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"
|
||||||
setAuthCountry(newCountry);
|
>
|
||||||
const rule = getCountryRuleByName(newCountry);
|
<option value="India">India (Calculates in INR ₹)</option>
|
||||||
if (rule) {
|
<option value="United States">United States (Calculates in USD $)</option>
|
||||||
setAuthDialCode(rule.code);
|
<option value="United Kingdom">United Kingdom (Calculates in USD $)</option>
|
||||||
}
|
<option value="Germany">Germany (Calculates in USD $)</option>
|
||||||
setAuthPhone('');
|
<option value="Australia">Australia (Calculates in USD $)</option>
|
||||||
}
|
</select>
|
||||||
}}
|
<div className="absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none text-slate-500 text-xs">
|
||||||
theme="dark"
|
▼
|
||||||
size="md"
|
</div>
|
||||||
showCurrency={true}
|
</div>
|
||||||
showDialCode={true}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
@ -387,7 +387,7 @@ export const AuthModal: React.FC<AuthModalProps> = ({
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
{authMode === 'login' ? <LogIn className="h-4 w-4" /> : <UserPlus className="h-4 w-4" />}
|
{authMode === 'login' ? <LogIn className="h-4 w-4" /> : <UserPlus className="h-4 w-4" />}
|
||||||
{authMode === 'login' ? 'Sign In' : 'Create Account'}
|
{authMode === 'login' ? 'Sign In Session' : 'Register Clinical Profile'}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
|
|
@ -408,7 +408,7 @@ export const AuthModal: React.FC<AuthModalProps> = ({
|
||||||
}}
|
}}
|
||||||
className="text-indigo-400 hover:text-indigo-300 font-bold underline"
|
className="text-indigo-400 hover:text-indigo-300 font-bold underline"
|
||||||
>
|
>
|
||||||
{authMode === 'login' ? 'Create an account' : 'Sign in here'}
|
{authMode === 'login' ? 'Create clinical account' : 'Sign in here'}
|
||||||
</button>
|
</button>
|
||||||
</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>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
@ -4,18 +4,9 @@ import { CheckCircle } from 'lucide-react';
|
||||||
interface PasswordUpdatedModalProps {
|
interface PasswordUpdatedModalProps {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
title?: string;
|
|
||||||
description?: string;
|
|
||||||
buttonText?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PasswordUpdatedModal: React.FC<PasswordUpdatedModalProps> = ({
|
export const PasswordUpdatedModal: React.FC<PasswordUpdatedModalProps> = ({ isOpen, onClose }) => {
|
||||||
isOpen,
|
|
||||||
onClose,
|
|
||||||
title = 'Password Updated!',
|
|
||||||
description = 'Your password has been securely updated. Please log in again with your new password to continue.',
|
|
||||||
buttonText = 'Log In with New Password'
|
|
||||||
}) => {
|
|
||||||
if (!isOpen) return null;
|
if (!isOpen) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
@ -25,16 +16,16 @@ export const PasswordUpdatedModal: React.FC<PasswordUpdatedModalProps> = ({
|
||||||
<CheckCircle className="h-8 w-8" />
|
<CheckCircle className="h-8 w-8" />
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-1.5">
|
<div className="space-y-1.5">
|
||||||
<h3 className="text-lg font-bold text-white">{title}</h3>
|
<h3 className="text-lg font-bold text-white">Password Updated!</h3>
|
||||||
<p className="text-xs text-slate-400 leading-relaxed font-medium">
|
<p className="text-xs text-slate-400 leading-relaxed font-medium">
|
||||||
{description}
|
Your password has been securely updated. You can now use your new password across the storefront and mobile application.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
className="w-full py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs rounded-xl transition-colors shadow-lg shadow-emerald-600/20 cursor-pointer"
|
className="w-full py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs rounded-xl transition-colors shadow-lg shadow-emerald-600/20"
|
||||||
>
|
>
|
||||||
{buttonText}
|
Continue to Storefront
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,9 @@
|
||||||
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
|
||||||
} 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 { parsePhoneNumber, formatE164Phone, SPECIAL_CHAR_REGEX } from '../../utils/validation';
|
|
||||||
import { PhoneInput } from '../common/PhoneInput';
|
|
||||||
import { CountrySelect } from '../common/CountrySelect';
|
|
||||||
|
|
||||||
interface ProfileDrawerProps {
|
interface ProfileDrawerProps {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
|
|
@ -34,15 +30,11 @@ 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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
|
export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
|
||||||
|
|
@ -70,67 +62,14 @@ 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,
|
|
||||||
}) => {
|
}) => {
|
||||||
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 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 +140,40 @@ 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="text"
|
||||||
phone={localPhone}
|
value={profilePhone}
|
||||||
country={profileCountry}
|
onChange={(e) => setProfilePhone(e.target.value)}
|
||||||
clearOnDialCodeChange={true}
|
placeholder="+919876543210"
|
||||||
onDialCodeChange={handleDialCodeChange}
|
className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-xs font-semibold text-slate-800 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
|
||||||
onPhoneChange={handleLocalPhoneChange}
|
|
||||||
theme="light"
|
|
||||||
disabled={profileSaving}
|
|
||||||
error={profileError && (profileError.toLowerCase().includes('phone') || profileError.toLowerCase().includes('mobile')) ? profileError : null}
|
|
||||||
/>
|
/>
|
||||||
</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"
|
setProfileCountry(e.target.value);
|
||||||
size="sm"
|
if (e.target.value === 'India') {
|
||||||
showDialCode={true}
|
setCurrency('INR');
|
||||||
showCurrency={false}
|
} else {
|
||||||
/>
|
setCurrency('USD');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
<option value="India">India</option>
|
||||||
|
<option value="United States">United States</option>
|
||||||
|
<option value="United Kingdom">United Kingdom</option>
|
||||||
|
<option value="Australia">Australia</option>
|
||||||
|
<option value="Germany">Germany</option>
|
||||||
|
<option value="France">France</option>
|
||||||
|
<option value="Japan">Japan</option>
|
||||||
|
<option value="China">China</option>
|
||||||
|
<option value="Singapore">Singapore</option>
|
||||||
|
<option value="Canada">Canada</option>
|
||||||
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
|
|
@ -246,8 +196,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 +265,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={showConfirmPassword ? 'text' : 'password'}
|
type="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 pr-10 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 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">
|
||||||
|
|
@ -346,12 +285,9 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
|
||||||
<span className={/[0-9]/.test(changeNewPassword) ? 'text-emerald-600 font-bold' : ''}>
|
<span className={/[0-9]/.test(changeNewPassword) ? 'text-emerald-600 font-bold' : ''}>
|
||||||
• 1 number
|
• 1 number
|
||||||
</span>
|
</span>
|
||||||
<span className={SPECIAL_CHAR_REGEX.test(changeNewPassword) ? 'text-emerald-600 font-bold' : ''}>
|
<span className={/[^A-Za-z0-9]/.test(changeNewPassword) ? 'text-emerald-600 font-bold' : ''}>
|
||||||
• 1 special char
|
• 1 special char
|
||||||
</span>
|
</span>
|
||||||
<span className={changeNewPassword.length > 0 && !/\s/.test(changeNewPassword) ? 'text-emerald-600 font-bold' : ''}>
|
|
||||||
• No spaces
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
|
|
@ -367,20 +303,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">
|
||||||
|
|
@ -453,23 +378,6 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{(sub.payment_id || sub.invoice_url) && onDownloadInvoice && (
|
|
||||||
<div className="pt-2 border-t border-slate-200/60 flex items-center justify-between">
|
|
||||||
<span className="text-[9px] font-mono text-slate-500 font-semibold truncate">
|
|
||||||
{sub.invoice_number ? `INV: ${sub.invoice_number}` : 'Official Invoice'}
|
|
||||||
</span>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => onDownloadInvoice(sub.payment_id || '', sub.invoice_url)}
|
|
||||||
className="inline-flex items-center gap-1 text-[10px] font-bold text-indigo-600 hover:text-indigo-700 bg-indigo-50 hover:bg-indigo-100 px-2 py-1 rounded-md border border-indigo-200 transition-colors cursor-pointer"
|
|
||||||
title="Download Tax Invoice"
|
|
||||||
>
|
|
||||||
<Download className="h-2.5 w-2.5" />
|
|
||||||
<span>Invoice</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
|
||||||
|
|
@ -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,
|
||||||
|
|
@ -38,30 +39,6 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
|
||||||
checkoutLoading,
|
checkoutLoading,
|
||||||
handleCheckout,
|
handleCheckout,
|
||||||
}) => {
|
}) => {
|
||||||
const fallbackCalc = cart.length > 0 ? (() => {
|
|
||||||
const subtotal = cart.reduce((acc, item) => {
|
|
||||||
const price = currency === 'INR' ? item.priceInr : currency === 'EUR' ? item.priceEur : item.priceUsd;
|
|
||||||
return acc + (Number(price) || 0);
|
|
||||||
}, 0);
|
|
||||||
return {
|
|
||||||
currency,
|
|
||||||
base_subtotal: subtotal,
|
|
||||||
bundle_discount_amount: 0,
|
|
||||||
coupon_discount_amount: 0,
|
|
||||||
total_discounts: 0,
|
|
||||||
convenience_fee_rate: 0,
|
|
||||||
convenience_fee: 0,
|
|
||||||
taxable_amount: 0,
|
|
||||||
gst_amount: 0,
|
|
||||||
grand_total: subtotal,
|
|
||||||
discount_policy: 'None',
|
|
||||||
coupon_applied: 'None',
|
|
||||||
coupon_error: null,
|
|
||||||
};
|
|
||||||
})() : null;
|
|
||||||
|
|
||||||
const activePricing = (pricingCalc && pricingCalc.currency === currency) ? pricingCalc : fallbackCalc;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="xl:col-span-1">
|
<div className="xl:col-span-1">
|
||||||
<div className="sticky top-12 bg-white border border-slate-200 rounded-3xl p-6 shadow-xl space-y-6">
|
<div className="sticky top-12 bg-white border border-slate-200 rounded-3xl p-6 shadow-xl space-y-6">
|
||||||
|
|
@ -75,23 +52,30 @@ 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 ${
|
||||||
</div>
|
currency === 'INR'
|
||||||
<div className="flex items-center gap-1.5 shrink-0">
|
? 'bg-white text-slate-900 shadow-sm border border-slate-200/50'
|
||||||
<span className="text-[11px] bg-white border border-slate-200 font-extrabold text-slate-800 px-2 py-0.5 rounded-md shadow-xs">
|
: 'text-slate-500 hover:text-slate-800'
|
||||||
{currency === 'INR' ? 'INR (₹)' : currency === 'EUR' ? 'EUR (€)' : 'USD ($)'}
|
}`}
|
||||||
</span>
|
>
|
||||||
{loggedInUser?.country && (
|
INR (₹)
|
||||||
<span className="text-[10px] text-slate-400 font-semibold max-w-[90px] truncate" title={loggedInUser.country}>
|
</button>
|
||||||
• {loggedInUser.country}
|
<button
|
||||||
</span>
|
onClick={() => setCurrency('USD')}
|
||||||
)}
|
className={`px-3 py-1 rounded-md text-xs font-bold transition-all duration-300 ${
|
||||||
|
currency === 'USD'
|
||||||
|
? 'bg-white text-slate-900 shadow-sm border border-slate-200/50'
|
||||||
|
: 'text-slate-500 hover:text-slate-800'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
USD ($)
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
@ -107,43 +91,22 @@ 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 =
|
|
||||||
item.code === 'POINTS_PACK' ||
|
|
||||||
item.code === 'PATTERN_CORE' ||
|
|
||||||
item.code === 'NUTRITION_CORE' ||
|
|
||||||
item.code === 'THERAPEUTICS_CORE' ||
|
|
||||||
item.name.toLowerCase().includes('complete pack') ||
|
|
||||||
item.name.toLowerCase().includes('complete package') ||
|
|
||||||
item.name.toLowerCase().includes('complete bundle') ||
|
|
||||||
item.category === 'Bundle';
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
<div
|
||||||
key={item.code}
|
key={item.code}
|
||||||
className="flex justify-between items-center gap-4 bg-slate-50 border border-slate-200/60 p-3 rounded-2xl"
|
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-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>
|
<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>
|
<p className="text-[9px] text-slate-400 tracking-wider uppercase font-semibold">{item.category}</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<span className="text-xs font-bold text-indigo-600">
|
<span className="text-xs font-bold text-indigo-600">
|
||||||
{(() => {
|
{currency === 'INR'
|
||||||
const calculatedItem = activePricing?.cart_items?.find((ci: any) => ci.code === item.code);
|
? `₹${item.priceInr}`
|
||||||
const price = calculatedItem
|
: currency === 'EUR'
|
||||||
? calculatedItem.price
|
? `€${item.priceEur}`
|
||||||
: (currency === 'INR' ? item.priceInr : currency === 'EUR' ? item.priceEur : item.priceUsd);
|
: `$${item.priceUsd}`}
|
||||||
const symbol = currency === 'INR' ? '₹' : currency === 'EUR' ? '€' : '$';
|
|
||||||
return `${symbol}${price}`;
|
|
||||||
})()}
|
|
||||||
</span>
|
</span>
|
||||||
<button
|
<button
|
||||||
onClick={() => toggleCartItem(item)}
|
onClick={() => toggleCartItem(item)}
|
||||||
|
|
@ -154,8 +117,7 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
))}
|
||||||
})}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
@ -179,11 +141,9 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{appliedCoupon &&
|
{appliedCoupon &&
|
||||||
(pricingCalc?.coupon_error || !pricingCalc?.coupon_applied || pricingCalc?.coupon_applied === 'None' || (pricingCalc?.coupon_discount_amount !== undefined && pricingCalc?.coupon_discount_amount <= 0) ? (
|
(pricingCalc?.coupon_error ? (
|
||||||
<div className="flex justify-between items-center bg-rose-50 border border-rose-200 text-rose-700 text-xs px-3 py-2 rounded-xl font-bold">
|
<div className="flex justify-between items-center bg-rose-50 border border-rose-200 text-rose-700 text-xs px-3 py-2 rounded-xl font-bold">
|
||||||
<span className="flex items-center gap-1">
|
<span className="flex items-center gap-1">⚠️ {pricingCalc.coupon_error}</span>
|
||||||
⚠️ {pricingCalc?.coupon_error || 'Invalid or expired coupon code.'}
|
|
||||||
</span>
|
|
||||||
<button
|
<button
|
||||||
onClick={removePromoCode}
|
onClick={removePromoCode}
|
||||||
className="text-rose-700 hover:text-rose-900 font-bold ml-2 cursor-pointer"
|
className="text-rose-700 hover:text-rose-900 font-bold ml-2 cursor-pointer"
|
||||||
|
|
@ -211,113 +171,62 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Checkout Summary Calculations */}
|
{/* Checkout Summary Calculations */}
|
||||||
{loadingPricing && (!pricingCalc || pricingCalc.currency !== currency) && (
|
{pricingCalc && cart.length > 0 && (
|
||||||
<div className="flex items-center justify-center p-6 bg-slate-50 border border-slate-200/60 rounded-2xl gap-2 text-xs font-semibold text-slate-500">
|
|
||||||
<RefreshCw className="h-4 w-4 animate-spin text-indigo-600" />
|
|
||||||
<span>Calculating {currency} pricing...</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{activePricing && cart.length > 0 && (
|
|
||||||
<div className="space-y-3 bg-slate-50 border border-slate-200/60 p-4 rounded-2xl">
|
<div className="space-y-3 bg-slate-50 border border-slate-200/60 p-4 rounded-2xl">
|
||||||
<div className="flex justify-between text-xs text-slate-600 font-bold">
|
<div className="flex justify-between text-xs text-slate-600 font-bold">
|
||||||
<span>Base Subtotal</span>
|
<span>Base Subtotal</span>
|
||||||
<span>
|
<span>
|
||||||
{currency === 'INR'
|
{currency === 'INR'
|
||||||
? `₹${activePricing.base_subtotal}`
|
? `₹${pricingCalc.base_subtotal}`
|
||||||
: currency === 'EUR'
|
: currency === 'EUR'
|
||||||
? `€${activePricing.base_subtotal}`
|
? `€${pricingCalc.base_subtotal}`
|
||||||
: `$${activePricing.base_subtotal}`}
|
: `$${pricingCalc.base_subtotal}`}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{activePricing.renewal_discount_amount > 0 && (
|
{pricingCalc.total_discounts > 0 && (
|
||||||
<div className="flex justify-between text-xs text-emerald-700 font-bold">
|
|
||||||
<span>Early Renewal Discount (20%)</span>
|
|
||||||
<span>
|
|
||||||
-{currency === 'INR'
|
|
||||||
? `₹${activePricing.renewal_discount_amount}`
|
|
||||||
: currency === 'EUR'
|
|
||||||
? `€${activePricing.renewal_discount_amount}`
|
|
||||||
: `$${activePricing.renewal_discount_amount}`}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{activePricing.bundle_discount_amount > 0 && (
|
|
||||||
<div className="flex justify-between text-xs text-emerald-700 font-bold">
|
|
||||||
<span>
|
|
||||||
{activePricing.discount_policy && activePricing.discount_policy !== 'None'
|
|
||||||
? (activePricing.discount_policy.startsWith('Staggered Buy:')
|
|
||||||
? activePricing.discount_policy.replace('Staggered Buy:', 'Loyalty Discount:')
|
|
||||||
: activePricing.discount_policy)
|
|
||||||
: 'Loyalty Discount'}
|
|
||||||
</span>
|
|
||||||
<span>
|
|
||||||
-{currency === 'INR'
|
|
||||||
? `₹${activePricing.bundle_discount_amount}`
|
|
||||||
: currency === 'EUR'
|
|
||||||
? `€${activePricing.bundle_discount_amount}`
|
|
||||||
: `$${activePricing.bundle_discount_amount}`}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{activePricing.coupon_discount_amount > 0 && (
|
|
||||||
<div className="flex justify-between text-xs text-emerald-700 font-bold">
|
|
||||||
<span>Coupon Discount ({appliedCoupon})</span>
|
|
||||||
<span>
|
|
||||||
-{currency === 'INR'
|
|
||||||
? `₹${activePricing.coupon_discount_amount}`
|
|
||||||
: currency === 'EUR'
|
|
||||||
? `€${activePricing.coupon_discount_amount}`
|
|
||||||
: `$${activePricing.coupon_discount_amount}`}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{activePricing.total_discounts > 0 &&
|
|
||||||
!activePricing.renewal_discount_amount &&
|
|
||||||
!activePricing.bundle_discount_amount &&
|
|
||||||
!activePricing.coupon_discount_amount && (
|
|
||||||
<div className="flex justify-between text-xs text-emerald-700 font-bold">
|
<div className="flex justify-between text-xs text-emerald-700 font-bold">
|
||||||
<span>Total Discounts</span>
|
<span>Total Discounts</span>
|
||||||
<span>
|
<span>
|
||||||
-{currency === 'INR'
|
-{currency === 'INR'
|
||||||
? `₹${activePricing.total_discounts}`
|
? `₹${pricingCalc.total_discounts}`
|
||||||
: currency === 'EUR'
|
: currency === 'EUR'
|
||||||
? `€${activePricing.total_discounts}`
|
? `€${pricingCalc.total_discounts}`
|
||||||
: `$${activePricing.total_discounts}`}
|
: `$${pricingCalc.total_discounts}`}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{activePricing.convenience_fee > 0 && (
|
{pricingCalc.convenience_fee > 0 && (
|
||||||
<div className="flex justify-between text-xs text-slate-600 font-bold">
|
<div className="flex justify-between text-xs text-slate-600 font-bold">
|
||||||
<span>Gateway fee ({activePricing.convenience_fee_rate}%)</span>
|
<span>Gateway fee ({pricingCalc.convenience_fee_rate}%)</span>
|
||||||
<span>
|
<span>
|
||||||
{currency === 'INR'
|
{currency === 'INR'
|
||||||
? `₹${activePricing.convenience_fee}`
|
? `₹${pricingCalc.convenience_fee}`
|
||||||
: currency === 'EUR'
|
: currency === 'EUR'
|
||||||
? `€${activePricing.convenience_fee}`
|
? `€${pricingCalc.convenience_fee}`
|
||||||
: `$${activePricing.convenience_fee}`}
|
: `$${pricingCalc.convenience_fee}`}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{activePricing.gst_amount > 0 && (
|
{pricingCalc.gst_amount > 0 && (
|
||||||
<div className="space-y-0.5">
|
<div className="space-y-0.5">
|
||||||
<div className="flex justify-between text-xs text-slate-600 font-bold">
|
<div className="flex justify-between text-xs text-slate-600 font-bold">
|
||||||
<span>GST (18%)</span>
|
<span>GST (18%)</span>
|
||||||
<span>
|
<span>
|
||||||
{currency === 'INR'
|
{currency === 'INR'
|
||||||
? `₹${activePricing.gst_amount}`
|
? `₹${pricingCalc.gst_amount}`
|
||||||
: currency === 'EUR'
|
: currency === 'EUR'
|
||||||
? `€${activePricing.gst_amount}`
|
? `€${pricingCalc.gst_amount}`
|
||||||
: `$${activePricing.gst_amount}`}
|
: `$${pricingCalc.gst_amount}`}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between text-[10px] text-slate-400 font-semibold italic">
|
<div className="flex justify-between text-[10px] text-slate-400 font-semibold italic">
|
||||||
<span>
|
<span>
|
||||||
(Taxable Amount:{' '}
|
(Taxable Amount:{' '}
|
||||||
{currency === 'INR'
|
{currency === 'INR'
|
||||||
? `₹${activePricing.taxable_amount}`
|
? `₹${pricingCalc.taxable_amount}`
|
||||||
: currency === 'EUR'
|
: currency === 'EUR'
|
||||||
? `€${activePricing.taxable_amount}`
|
? `€${pricingCalc.taxable_amount}`
|
||||||
: `$${activePricing.taxable_amount}`}
|
: `$${pricingCalc.taxable_amount}`}
|
||||||
)
|
)
|
||||||
</span>
|
</span>
|
||||||
<span></span>
|
<span></span>
|
||||||
|
|
@ -329,10 +238,10 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
|
||||||
<span>Total Chargeable</span>
|
<span>Total Chargeable</span>
|
||||||
<span className="text-indigo-600 text-lg font-extrabold">
|
<span className="text-indigo-600 text-lg font-extrabold">
|
||||||
{currency === 'INR'
|
{currency === 'INR'
|
||||||
? `₹${activePricing.grand_total}`
|
? `₹${pricingCalc.grand_total}`
|
||||||
: currency === 'EUR'
|
: currency === 'EUR'
|
||||||
? `€${activePricing.grand_total}`
|
? `€${pricingCalc.grand_total}`
|
||||||
: `$${activePricing.grand_total}`}
|
: `$${pricingCalc.grand_total}`}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -345,32 +254,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 ? 'Update Number' : 'Add Number'}
|
{loggedInUser.phone_number ? 'Edit 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 +309,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,7 +1,6 @@
|
||||||
import React, { useState, useEffect } from 'react';
|
import React from 'react';
|
||||||
import { XCircle, CheckCircle, Check, Download, RefreshCw, Smartphone, PauseCircle } from 'lucide-react';
|
import { XCircle, CheckCircle, Check, Download, RefreshCw, Smartphone } from 'lucide-react';
|
||||||
import type { VerificationResult, UserProfile } from '../../types';
|
import type { VerificationResult, UserProfile } from '../../types';
|
||||||
import { formatDeepLinkRoute } from '../../utils/navigation';
|
|
||||||
|
|
||||||
interface PaymentSuccessModalProps {
|
interface PaymentSuccessModalProps {
|
||||||
verificationResult: VerificationResult;
|
verificationResult: VerificationResult;
|
||||||
|
|
@ -9,8 +8,6 @@ interface PaymentSuccessModalProps {
|
||||||
loggedInUser: UserProfile | null;
|
loggedInUser: UserProfile | null;
|
||||||
onDownloadInvoice: (paymentId: string, invoiceUrl?: string) => void;
|
onDownloadInvoice: (paymentId: string, invoiceUrl?: string) => void;
|
||||||
downloadingInvoice: boolean;
|
downloadingInvoice: boolean;
|
||||||
returnRoute?: string;
|
|
||||||
appScheme?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
|
export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
|
||||||
|
|
@ -19,96 +16,16 @@ export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
|
||||||
loggedInUser,
|
loggedInUser,
|
||||||
onDownloadInvoice,
|
onDownloadInvoice,
|
||||||
downloadingInvoice,
|
downloadingInvoice,
|
||||||
returnRoute,
|
|
||||||
appScheme,
|
|
||||||
}) => {
|
}) => {
|
||||||
const [desktopNotice, setDesktopNotice] = useState(false);
|
|
||||||
const [countdown, setCountdown] = useState<number>(10);
|
|
||||||
const [isRedirectCancelled, setIsRedirectCancelled] = useState<boolean>(false);
|
|
||||||
const [isRedirecting, setIsRedirecting] = useState<boolean>(false);
|
|
||||||
|
|
||||||
// Enable 10-second auto-redirect countdown tile across all devices (iOS, Android, and web testing)
|
|
||||||
const showCountdown = true;
|
|
||||||
const route = formatDeepLinkRoute(returnRoute || 'modules');
|
|
||||||
|
|
||||||
// Launch mobile app across iOS, Android, and Desktop
|
|
||||||
const launchMobileApp = () => {
|
|
||||||
setIsRedirecting(true);
|
|
||||||
const userAgent = navigator.userAgent || '';
|
|
||||||
const isAndroid = /Android/i.test(userAgent);
|
|
||||||
const isIOS = /iPhone|iPad|iPod/i.test(userAgent);
|
|
||||||
|
|
||||||
if (isAndroid) {
|
|
||||||
// Android Intent format for Chrome / modern Android browsers
|
|
||||||
const intentUrl = `intent://${route}#Intent;scheme=acupedia;package=com.anonymous.acupedia;end`;
|
|
||||||
window.location.href = intentUrl;
|
|
||||||
|
|
||||||
setTimeout(() => {
|
|
||||||
window.location.href = `acupedia://${route}`;
|
|
||||||
}, 500);
|
|
||||||
setTimeout(() => {
|
|
||||||
window.location.href = `myapp://${route}`;
|
|
||||||
}, 1000);
|
|
||||||
} else if (isIOS) {
|
|
||||||
// iOS Safari and Chrome handle custom URI schemes directly
|
|
||||||
const primaryScheme = appScheme || 'acupedia';
|
|
||||||
window.location.href = `${primaryScheme}://${route}`;
|
|
||||||
|
|
||||||
// Fallback in case alternate scheme was registered in Expo
|
|
||||||
setTimeout(() => {
|
|
||||||
window.location.href = `acupedia://${route}`;
|
|
||||||
}, 400);
|
|
||||||
setTimeout(() => {
|
|
||||||
window.location.href = `myapp://${route}`;
|
|
||||||
}, 900);
|
|
||||||
} else {
|
|
||||||
// Desktop
|
|
||||||
window.location.href = `acupedia://${route}`;
|
|
||||||
setDesktopNotice(true);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// 10-second auto-redirect countdown for mobile & web app testing
|
|
||||||
useEffect(() => {
|
|
||||||
if (!showCountdown || isRedirectCancelled || isRedirecting) return;
|
|
||||||
|
|
||||||
if (countdown <= 0) {
|
|
||||||
launchMobileApp();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const timer = setInterval(() => {
|
|
||||||
setCountdown((prev) => {
|
|
||||||
if (prev <= 1) {
|
|
||||||
clearInterval(timer);
|
|
||||||
launchMobileApp();
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
return prev - 1;
|
|
||||||
});
|
|
||||||
}, 1000);
|
|
||||||
|
|
||||||
return () => clearInterval(timer);
|
|
||||||
}, [countdown, showCountdown, isRedirectCancelled, isRedirecting]);
|
|
||||||
|
|
||||||
const handleDownloadInvoiceClick = () => {
|
|
||||||
setIsRedirectCancelled(true);
|
|
||||||
onDownloadInvoice(verificationResult.paymentId || '', verificationResult.invoiceUrl);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleClose = () => {
|
|
||||||
setIsRedirectCancelled(true);
|
|
||||||
onClose();
|
|
||||||
};
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-[100] flex items-center justify-center p-3 sm:p-4 bg-slate-950/75 backdrop-blur-md transition-all duration-300 overflow-y-auto">
|
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-slate-950/75 backdrop-blur-md transition-all duration-300">
|
||||||
<div className="relative w-full max-w-xl bg-slate-900 border border-slate-800 rounded-2xl p-4 sm:p-5 md:p-6 space-y-3 sm:space-y-4 shadow-2xl text-slate-100 max-h-[92vh] overflow-y-auto my-auto animate-in fade-in zoom-in-95 duration-200">
|
<div className="relative w-full max-w-xl bg-slate-900 border border-slate-800 rounded-2xl p-5 md:p-6 space-y-4 shadow-2xl text-slate-100 overflow-hidden animate-in fade-in zoom-in-95 duration-200">
|
||||||
{/* Ambient Background Glow */}
|
{/* Ambient Background Glow */}
|
||||||
<div className="absolute -top-10 left-1/2 -translate-x-1/2 w-48 h-48 bg-emerald-500/10 rounded-full blur-3xl pointer-events-none" />
|
<div className="absolute -top-10 left-1/2 -translate-x-1/2 w-48 h-48 bg-emerald-500/10 rounded-full blur-3xl pointer-events-none" />
|
||||||
|
|
||||||
{/* Close button */}
|
{/* Close button */}
|
||||||
<button
|
<button
|
||||||
onClick={handleClose}
|
onClick={onClose}
|
||||||
className="absolute top-3 right-3 h-7 w-7 rounded-full bg-slate-800 hover:bg-slate-700/80 flex items-center justify-center text-slate-400 hover:text-slate-200 transition-colors"
|
className="absolute top-3 right-3 h-7 w-7 rounded-full bg-slate-800 hover:bg-slate-700/80 flex items-center justify-center text-slate-400 hover:text-slate-200 transition-colors"
|
||||||
>
|
>
|
||||||
<XCircle className="h-4 w-4" />
|
<XCircle className="h-4 w-4" />
|
||||||
|
|
@ -130,67 +47,8 @@ export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 📱 10-Second Auto-Redirect Tile */}
|
|
||||||
{showCountdown && !isRedirectCancelled && (
|
|
||||||
<div className="bg-gradient-to-r from-indigo-950/90 via-slate-900 to-indigo-950/90 border border-indigo-500/40 rounded-xl p-3 space-y-2 relative z-10 shadow-lg shadow-indigo-950/40 animate-in fade-in slide-in-from-top-2 duration-300">
|
|
||||||
<div className="flex items-center justify-between gap-2.5">
|
|
||||||
<div className="flex items-center gap-2.5 min-w-0">
|
|
||||||
<div className="h-8 w-8 rounded-lg bg-indigo-500/20 border border-indigo-500/40 flex items-center justify-center text-indigo-400 flex-shrink-0">
|
|
||||||
<Smartphone className="h-4 w-4 animate-pulse" />
|
|
||||||
</div>
|
|
||||||
<div className="min-w-0 text-left">
|
|
||||||
<p className="text-xs font-bold text-white flex items-center gap-1.5">
|
|
||||||
<span>Returning to Acupedia App</span>
|
|
||||||
<span className="inline-flex items-center justify-center bg-indigo-600 text-white font-mono text-[10px] font-extrabold px-1.5 py-0.5 rounded-md min-w-[22px]">
|
|
||||||
{countdown}s
|
|
||||||
</span>
|
|
||||||
</p>
|
|
||||||
<p className="text-[10px] text-slate-400 font-medium">
|
|
||||||
Redirecting automatically if no action taken
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setIsRedirectCancelled(true)}
|
|
||||||
className="flex-shrink-0 px-2.5 py-1 bg-slate-800 hover:bg-slate-700/80 border border-slate-600/80 hover:border-slate-500 text-slate-200 hover:text-white text-[11px] font-bold rounded-lg transition-colors cursor-pointer flex items-center gap-1"
|
|
||||||
title="Pause redirect and stay on page"
|
|
||||||
>
|
|
||||||
<PauseCircle className="h-3 w-3 text-indigo-400" />
|
|
||||||
<span>Stay on Web</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Countdown progress bar */}
|
|
||||||
<div className="w-full h-1.5 bg-slate-800/80 rounded-full overflow-hidden">
|
|
||||||
<div
|
|
||||||
className="h-full bg-gradient-to-r from-indigo-500 to-emerald-400 rounded-full transition-all duration-1000 ease-linear"
|
|
||||||
style={{ width: `${(countdown / 10) * 100}%` }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Banner shown if redirect is cancelled */}
|
|
||||||
{showCountdown && isRedirectCancelled && (
|
|
||||||
<div className="bg-slate-950/70 border border-slate-800 rounded-xl px-3 py-2 flex items-center justify-between text-[11px] text-slate-400 relative z-10 animate-in fade-in duration-200">
|
|
||||||
<span className="flex items-center gap-1.5">
|
|
||||||
<span className="h-1.5 w-1.5 rounded-full bg-amber-400" />
|
|
||||||
Auto-redirect paused. Take your time to download your invoice.
|
|
||||||
</span>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={launchMobileApp}
|
|
||||||
className="text-emerald-400 hover:text-emerald-300 font-bold ml-2 underline cursor-pointer flex-shrink-0"
|
|
||||||
>
|
|
||||||
Open App Now
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Content: Mobile App Access Onboarding */}
|
{/* Content: Mobile App Access Onboarding */}
|
||||||
<div className="bg-slate-950 border border-slate-800/80 rounded-xl p-3.5 space-y-2.5 relative z-10">
|
<div className="bg-slate-950 border border-slate-800/80 rounded-xl p-4 space-y-3 relative z-10">
|
||||||
<p className="text-[11px] text-slate-300 leading-relaxed font-semibold text-center">
|
<p className="text-[11px] text-slate-300 leading-relaxed font-semibold text-center">
|
||||||
Your subscription entitlements are active! Access your content inside the{' '}
|
Your subscription entitlements are active! Access your content inside the{' '}
|
||||||
<span className="text-indigo-400 font-bold">Acupedia Mobile App</span>. Log in with:{' '}
|
<span className="text-indigo-400 font-bold">Acupedia Mobile App</span>. Log in with:{' '}
|
||||||
|
|
@ -206,14 +64,14 @@ export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
|
||||||
<a
|
<a
|
||||||
href="#appstore"
|
href="#appstore"
|
||||||
onClick={(e) => e.preventDefault()}
|
onClick={(e) => e.preventDefault()}
|
||||||
className="flex items-center gap-2 bg-slate-900 hover:bg-slate-800 text-white px-3 py-1.5 rounded-lg border border-slate-800 hover:border-slate-700 transition-all duration-300 shadow-sm group"
|
className="flex items-center gap-2 bg-slate-900 hover:bg-slate-800 text-white px-3.5 py-2 rounded-lg border border-slate-800 hover:border-slate-700 transition-all duration-300 shadow-sm group"
|
||||||
>
|
>
|
||||||
<svg className="w-3.5 h-3.5 fill-current text-slate-300 group-hover:text-white transition-colors" viewBox="0 0 24 24">
|
<svg className="w-4 h-4 fill-current text-slate-300 group-hover:text-white transition-colors" viewBox="0 0 24 24">
|
||||||
<path d="M18.71,19.5 C17.88,20.74 17,21.95 15.66,21.97 C14.32,22 13.89,21.18 12.37,21.18 C10.84,21.18 10.37,21.95 9.1,22 C7.79,22.05 6.8,20.68 5.96,19.48 C4.25,17 2.94,12.45 4.7,9.39 C5.57,7.87 7.13,6.91 8.82,6.88 C10.1,6.86 11.32,7.75 12.11,7.75 C12.89,7.75 14.37,6.68 15.92,6.84 C16.57,6.87 18.39,7.1 19.56,8.82 C19.47,8.88 17.39,10.1 17.41,12.63 C17.44,15.65 20.06,16.66 20.1,16.67 C20.08,16.74 19.67,18.11 18.71,19.5 M15.97,4.17 C16.63,3.37 17.07,2.28 16.95,1 C16,1.04 14.9,1.6 14.24,2.38 C13.68,3.04 13.19,4.14 13.34,5.39 C14.39,5.47 15.4,4.88 15.97,4.17 Z" />
|
<path d="M18.71,19.5 C17.88,20.74 17,21.95 15.66,21.97 C14.32,22 13.89,21.18 12.37,21.18 C10.84,21.18 10.37,21.95 9.1,22 C7.79,22.05 6.8,20.68 5.96,19.48 C4.25,17 2.94,12.45 4.7,9.39 C5.57,7.87 7.13,6.91 8.82,6.88 C10.1,6.86 11.32,7.75 12.11,7.75 C12.89,7.75 14.37,6.68 15.92,6.84 C16.57,6.87 18.39,7.1 19.56,8.82 C19.47,8.88 17.39,10.1 17.41,12.63 C17.44,15.65 20.06,16.66 20.1,16.67 C20.08,16.74 19.67,18.11 18.71,19.5 M15.97,4.17 C16.63,3.37 17.07,2.28 16.95,1 C16,1.04 14.9,1.6 14.24,2.38 C13.68,3.04 13.19,4.14 13.34,5.39 C14.39,5.47 15.4,4.88 15.97,4.17 Z" />
|
||||||
</svg>
|
</svg>
|
||||||
<div className="text-left leading-none">
|
<div className="text-left leading-none">
|
||||||
<p className="text-[7px] text-slate-400 font-bold uppercase tracking-wider mb-0.5">Download on the</p>
|
<p className="text-[8px] text-slate-400 font-bold uppercase tracking-wider mb-0.5">Download on the</p>
|
||||||
<p className="text-[11px] font-black text-slate-200 group-hover:text-white transition-colors">App Store</p>
|
<p className="text-xs font-black text-slate-200 group-hover:text-white transition-colors">App Store</p>
|
||||||
</div>
|
</div>
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
|
|
@ -221,14 +79,14 @@ export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
|
||||||
<a
|
<a
|
||||||
href="#playstore"
|
href="#playstore"
|
||||||
onClick={(e) => e.preventDefault()}
|
onClick={(e) => e.preventDefault()}
|
||||||
className="flex items-center gap-2 bg-slate-900 hover:bg-slate-800 text-white px-3 py-1.5 rounded-lg border border-slate-800 hover:border-slate-700 transition-all duration-300 shadow-sm group"
|
className="flex items-center gap-2 bg-slate-900 hover:bg-slate-800 text-white px-3.5 py-2 rounded-lg border border-slate-800 hover:border-slate-700 transition-all duration-300 shadow-sm group"
|
||||||
>
|
>
|
||||||
<svg className="w-3.5 h-3.5 fill-current text-slate-300 group-hover:text-white transition-colors" viewBox="0 0 24 24">
|
<svg className="w-4 h-4 fill-current text-slate-300 group-hover:text-white transition-colors" viewBox="0 0 24 24">
|
||||||
<path d="M3,5.27V18.73L16.55,12L3,5.27M17.87,11.33L21,12.92C21.67,13.25 21.67,13.75 21,14.08L17.87,15.67L15,12L17.87,11.33M3,3C3.58,3 4.2,3.22 4.67,3.58L16,11.08L13.13,12L3,3M3,21L13.13,12L16,12.92L4.67,20.42C4.2,20.78 3.58,21 3,21Z" />
|
<path d="M3,5.27V18.73L16.55,12L3,5.27M17.87,11.33L21,12.92C21.67,13.25 21.67,13.75 21,14.08L17.87,15.67L15,12L17.87,11.33M3,3C3.58,3 4.2,3.22 4.67,3.58L16,11.08L13.13,12L3,3M3,21L13.13,12L16,12.92L4.67,20.42C4.2,20.78 3.58,21 3,21Z" />
|
||||||
</svg>
|
</svg>
|
||||||
<div className="text-left leading-none">
|
<div className="text-left leading-none">
|
||||||
<p className="text-[7px] text-slate-400 font-bold uppercase tracking-wider mb-0.5">Get it on</p>
|
<p className="text-[8px] text-slate-400 font-bold uppercase tracking-wider mb-0.5">Get it on</p>
|
||||||
<p className="text-[11px] font-black text-slate-200 group-hover:text-white transition-colors">Google Play</p>
|
<p className="text-xs font-black text-slate-200 group-hover:text-white transition-colors">Google Play</p>
|
||||||
</div>
|
</div>
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -244,9 +102,14 @@ export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
|
||||||
</span>
|
</span>
|
||||||
{verificationResult.invoiceNumber && (
|
{verificationResult.invoiceNumber && (
|
||||||
<button
|
<button
|
||||||
onClick={handleDownloadInvoiceClick}
|
onClick={() =>
|
||||||
|
onDownloadInvoice(
|
||||||
|
verificationResult.paymentId || '',
|
||||||
|
verificationResult.invoiceUrl
|
||||||
|
)
|
||||||
|
}
|
||||||
disabled={downloadingInvoice}
|
disabled={downloadingInvoice}
|
||||||
className="text-indigo-400 hover:text-indigo-300 transition-colors p-0.5 cursor-pointer"
|
className="text-indigo-400 hover:text-indigo-300 transition-colors p-0.5"
|
||||||
title="Download Invoice PDF"
|
title="Download Invoice PDF"
|
||||||
>
|
>
|
||||||
<Download className="h-3 w-3" />
|
<Download className="h-3 w-3" />
|
||||||
|
|
@ -254,9 +117,9 @@ export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between items-center text-slate-400 font-semibold gap-2">
|
<div className="flex justify-between items-center text-slate-400 font-semibold">
|
||||||
<span className="shrink-0">Payment ID</span>
|
<span>Payment ID</span>
|
||||||
<span className="text-white font-mono font-bold bg-slate-800 px-2 py-0.5 rounded text-[10px] border border-slate-700/50 break-all text-right">
|
<span className="text-white font-mono font-bold bg-slate-800 px-2 py-0.5 rounded text-[10px] border border-slate-700/50">
|
||||||
{verificationResult.paymentId}
|
{verificationResult.paymentId}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -294,9 +157,14 @@ export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
|
||||||
<div className="space-y-2 relative z-10 mt-2">
|
<div className="space-y-2 relative z-10 mt-2">
|
||||||
{verificationResult.invoiceNumber && (
|
{verificationResult.invoiceNumber && (
|
||||||
<button
|
<button
|
||||||
onClick={handleDownloadInvoiceClick}
|
onClick={() =>
|
||||||
|
onDownloadInvoice(
|
||||||
|
verificationResult.paymentId || '',
|
||||||
|
verificationResult.invoiceUrl
|
||||||
|
)
|
||||||
|
}
|
||||||
disabled={downloadingInvoice}
|
disabled={downloadingInvoice}
|
||||||
className="w-full h-9 bg-slate-800 hover:bg-slate-700/80 border border-slate-700 text-white font-bold text-xs rounded-lg transition-all duration-300 flex items-center justify-center gap-2 shadow-md cursor-pointer"
|
className="w-full h-9 bg-slate-800 hover:bg-slate-700/80 border border-slate-700 text-white font-bold text-xs rounded-lg transition-all duration-300 flex items-center justify-center gap-2 shadow-md"
|
||||||
>
|
>
|
||||||
{downloadingInvoice ? (
|
{downloadingInvoice ? (
|
||||||
<RefreshCw className="h-3.5 w-3.5 animate-spin text-indigo-400" />
|
<RefreshCw className="h-3.5 w-3.5 animate-spin text-indigo-400" />
|
||||||
|
|
@ -307,26 +175,17 @@ export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Open in App Button */}
|
<a
|
||||||
<button
|
href="acupedia://"
|
||||||
onClick={launchMobileApp}
|
className="w-full h-9 bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs rounded-lg transition-all duration-300 flex items-center justify-center gap-2 shadow-md shadow-emerald-600/10 no-underline decoration-0"
|
||||||
className="w-full h-9 bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs rounded-lg transition-all duration-300 flex items-center justify-center gap-2 shadow-md shadow-emerald-600/10 cursor-pointer"
|
|
||||||
>
|
>
|
||||||
<Smartphone className="h-3.5 w-3.5 text-emerald-200" />
|
<Smartphone className="h-3.5 w-3.5 text-emerald-200" />
|
||||||
Open in App / Library
|
Open Acupedia Mobile App
|
||||||
</button>
|
</a>
|
||||||
|
|
||||||
{desktopNotice && (
|
|
||||||
<div className="p-2.5 bg-slate-950 border border-emerald-900/40 rounded-lg text-center animate-in fade-in duration-200">
|
|
||||||
<p className="text-[11px] text-emerald-400 font-medium">
|
|
||||||
📱 Attempted to launch Acupedia App. If you are on desktop, please open the Acupedia App on your mobile device to view your unlocked content.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={handleClose}
|
onClick={onClose}
|
||||||
className="w-full h-9 bg-indigo-600 hover:bg-indigo-500 text-white font-bold text-xs rounded-lg transition-all duration-300 flex items-center justify-center gap-2 shadow-md shadow-indigo-600/10 cursor-pointer"
|
className="w-full h-9 bg-indigo-600 hover:bg-indigo-500 text-white font-bold text-xs rounded-lg transition-all duration-300 flex items-center justify-center gap-2 shadow-md shadow-indigo-600/10"
|
||||||
>
|
>
|
||||||
Return to Storefront
|
Return to Storefront
|
||||||
</button>
|
</button>
|
||||||
|
|
|
||||||
|
|
@ -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,8 +18,7 @@ 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')}
|
||||||
|
|
@ -36,7 +35,7 @@ export const StoreHeader: React.FC<StoreHeaderProps> = ({
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Desktop Navigation Tabs */}
|
{/* Navigation Tabs */}
|
||||||
<nav className="hidden sm:flex items-center bg-slate-900/80 border border-slate-800 rounded-xl p-1 gap-1">
|
<nav className="hidden sm:flex items-center bg-slate-900/80 border border-slate-800 rounded-xl p-1 gap-1">
|
||||||
<button
|
<button
|
||||||
onClick={() => onSwitchTab('storefront')}
|
onClick={() => onSwitchTab('storefront')}
|
||||||
|
|
@ -98,36 +97,6 @@ export const StoreHeader: React.FC<StoreHeaderProps> = ({
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Mobile Navigation Tabs */}
|
|
||||||
<nav className="sm:hidden flex items-center bg-slate-900/90 border border-slate-800 rounded-xl p-1 mt-3 gap-1 w-full">
|
|
||||||
<button
|
|
||||||
onClick={() => onSwitchTab('storefront')}
|
|
||||||
className={`flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-colors ${
|
|
||||||
activeTab === 'storefront'
|
|
||||||
? '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-1 flex items-center justify-center gap-1.5 px-3 py-2 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-1 font-semibold">
|
|
||||||
{loggedInUser.active_subscriptions.length}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
</nav>
|
|
||||||
</header>
|
</header>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { CheckCircle, Download } from 'lucide-react';
|
import { CheckCircle } from 'lucide-react';
|
||||||
import { Pagination } from '../common/Pagination';
|
import { Pagination } from '../common/Pagination';
|
||||||
import type { UserProfile, ModuleItem } from '../../types';
|
import type { UserProfile, ModuleItem } from '../../types';
|
||||||
|
|
||||||
|
|
@ -8,7 +8,6 @@ interface SubscriptionsViewProps {
|
||||||
onOpenAuth: (mode: 'login') => void;
|
onOpenAuth: (mode: 'login') => void;
|
||||||
onSwitchTab: (tab: 'storefront') => void;
|
onSwitchTab: (tab: 'storefront') => void;
|
||||||
curriculumModules: ModuleItem[];
|
curriculumModules: ModuleItem[];
|
||||||
onDownloadInvoice?: (paymentId: string, directUrl?: string) => void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const SubscriptionsView: React.FC<SubscriptionsViewProps> = ({
|
export const SubscriptionsView: React.FC<SubscriptionsViewProps> = ({
|
||||||
|
|
@ -16,7 +15,6 @@ export const SubscriptionsView: React.FC<SubscriptionsViewProps> = ({
|
||||||
onOpenAuth,
|
onOpenAuth,
|
||||||
onSwitchTab,
|
onSwitchTab,
|
||||||
curriculumModules,
|
curriculumModules,
|
||||||
onDownloadInvoice,
|
|
||||||
}) => {
|
}) => {
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
const [pageSize, setPageSize] = useState(6);
|
const [pageSize, setPageSize] = useState(6);
|
||||||
|
|
@ -149,28 +147,6 @@ export const SubscriptionsView: React.FC<SubscriptionsViewProps> = ({
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{(sub.payment_id || sub.invoice_url) && onDownloadInvoice && (
|
|
||||||
<div className="mt-1 pt-3 border-t border-slate-100 flex items-center justify-between gap-2">
|
|
||||||
{sub.invoice_number ? (
|
|
||||||
<div className="text-[11px] font-mono text-slate-500 font-medium truncate">
|
|
||||||
<span className="text-slate-400 mr-1">Invoice:</span>
|
|
||||||
<span className="text-slate-800 font-bold">{sub.invoice_number}</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<span className="text-[11px] text-slate-400 font-medium">Tax Invoice</span>
|
|
||||||
)}
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => onDownloadInvoice(sub.payment_id || '', sub.invoice_url)}
|
|
||||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-indigo-50 hover:bg-indigo-100 border border-indigo-200 text-indigo-700 font-bold text-xs rounded-xl transition-colors duration-200 shadow-sm flex-shrink-0 cursor-pointer"
|
|
||||||
title="Download Tax Invoice PDF"
|
|
||||||
>
|
|
||||||
<Download className="h-3.5 w-3.5" />
|
|
||||||
<span>Download Invoice</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -1,167 +1,23 @@
|
||||||
import type { CountryCode as LibCountryCode } from 'libphonenumber-js';
|
|
||||||
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;
|
||||||
currency: Currency;
|
|
||||||
minLength: number;
|
|
||||||
maxLength: number;
|
|
||||||
placeholder: string;
|
|
||||||
validPrefixes?: string[];
|
|
||||||
example?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const COUNTRY_CODES: CountryCode[] = [
|
export const COUNTRY_CODES: CountryCode[] = [
|
||||||
// South Asia
|
{ code: '+91', label: '🇮🇳 +91', country: 'India' },
|
||||||
{ 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: '+1', label: '🇺🇸 +1', country: 'US' },
|
||||||
{ 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: '+44', label: '🇬🇧 +44', country: 'UK' },
|
||||||
{ 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: '+61', label: '🇦🇺 +61', country: 'AU' },
|
||||||
{ 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: '+49', label: '🇩🇪 +49', country: 'DE' },
|
||||||
{ 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: '+33', label: '🇫🇷 +33', country: 'FR' },
|
||||||
{ 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: '+81', label: '🇯🇵 +81', country: 'JP' },
|
||||||
{ 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: '+86', label: '🇨🇳 +86', country: 'CN' },
|
||||||
|
{ code: '+971', label: '🇦🇪 +971', country: 'UAE' },
|
||||||
// North America
|
{ code: '+65', label: '🇸🇬 +65', country: 'SG' },
|
||||||
{ 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: '+55', label: '🇧🇷 +55', country: 'BR' },
|
||||||
{ iso2: 'CA', code: '+1', label: '🇨🇦 +1', country: 'Canada', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit phone number', example: '416 555 0123' },
|
{ code: '+82', label: '🇰🇷 +82', country: 'KR' },
|
||||||
{ iso2: 'MX', code: '+52', label: '🇲🇽 +52', country: 'Mexico', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', example: '55 1234 5678' },
|
{ code: '+7', label: '🇷🇺 +7', country: 'RU' },
|
||||||
|
{ code: '+27', label: '🇿🇦 +27', country: 'ZA' },
|
||||||
// Europe & UK
|
{ code: '+234', label: '🇳🇬 +234', country: 'NG' },
|
||||||
{ iso2: 'GB', code: '+44', label: '🇬🇧 +44', country: 'United Kingdom', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['7'], example: '7123 456789' },
|
|
||||||
{ iso2: 'DE', code: '+49', label: '🇩🇪 +49', country: 'Germany', currency: 'EUR', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['15', '16', '17', '1'], example: '151 23456789' },
|
|
||||||
{ iso2: 'FR', code: '+33', label: '🇫🇷 +33', country: 'France', currency: 'EUR', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['6', '7'], example: '612 345 678' },
|
|
||||||
{ iso2: 'IT', code: '+39', label: '🇮🇹 +39', country: 'Italy', currency: 'EUR', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['3'], example: '312 345 6789' },
|
|
||||||
{ iso2: 'ES', code: '+34', label: '🇪🇸 +34', country: 'Spain', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['6', '7'], example: '612 345 678' },
|
|
||||||
{ iso2: 'NL', code: '+31', label: '🇳🇱 +31', country: 'Netherlands', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['6'], example: '6 12345678' },
|
|
||||||
{ iso2: 'CH', code: '+41', label: '🇨🇭 +41', country: 'Switzerland', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['7'], example: '78 123 45 67' },
|
|
||||||
{ iso2: 'BE', code: '+32', label: '🇧🇪 +32', country: 'Belgium', currency: 'EUR', minLength: 8, maxLength: 9, placeholder: '8 to 9 digits', validPrefixes: ['4'], example: '470 12 34 56' },
|
|
||||||
{ iso2: 'AT', code: '+43', label: '🇦🇹 +43', country: 'Austria', currency: 'EUR', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['6'], example: '664 1234567' },
|
|
||||||
{ iso2: 'IE', code: '+353', label: '🇮🇪 +353', country: 'Ireland', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['8'], example: '83 123 4567' },
|
|
||||||
{ iso2: 'SE', code: '+46', label: '🇸🇪 +46', country: 'Sweden', currency: 'EUR', minLength: 7, maxLength: 10, placeholder: '7 to 10 digits', validPrefixes: ['7'], example: '70 123 45 67' },
|
|
||||||
{ iso2: 'NO', code: '+47', label: '🇳🇴 +47', country: 'Norway', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['4', '9'], example: '412 34 567' },
|
|
||||||
{ iso2: 'DK', code: '+45', label: '🇩🇰 +45', country: 'Denmark', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', example: '20 12 34 56' },
|
|
||||||
{ iso2: 'FI', code: '+358', label: '🇫🇮 +358', country: 'Finland', currency: 'EUR', minLength: 7, maxLength: 10, placeholder: '7 to 10 digits', validPrefixes: ['4', '5'], example: '41 234 5678' },
|
|
||||||
{ iso2: 'PT', code: '+351', label: '🇵🇹 +351', country: 'Portugal', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['9'], example: '912 345 678' },
|
|
||||||
{ iso2: 'GR', code: '+30', label: '🇬🇷 +30', country: 'Greece', currency: 'EUR', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['6'], example: '691 234 5678' },
|
|
||||||
{ iso2: 'PL', code: '+48', label: '🇵🇱 +48', country: 'Poland', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['4', '5', '6', '7', '8'], example: '512 345 678' },
|
|
||||||
{ iso2: 'CZ', code: '+420', label: '🇨🇿 +420', country: 'Czech Republic', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['6', '7'], example: '601 123 456' },
|
|
||||||
{ iso2: 'HU', code: '+36', label: '🇭🇺 +36', country: 'Hungary', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['20', '30', '31', '50', '70'], example: '20 123 4567' },
|
|
||||||
{ iso2: 'RO', code: '+40', label: '🇷🇴 +40', country: 'Romania', currency: 'EUR', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['7'], example: '712 345 678' },
|
|
||||||
{ iso2: 'UA', code: '+380', label: '🇺🇦 +380', country: 'Ukraine', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['5', '6', '7', '9'], example: '50 123 4567' },
|
|
||||||
{ iso2: 'IS', code: '+354', label: '🇮🇸 +354', country: 'Iceland', currency: 'EUR', minLength: 7, maxLength: 9, placeholder: '7 to 9 digits', validPrefixes: ['6', '7', '8'], example: '612 3456' },
|
|
||||||
{ iso2: 'LU', code: '+352', label: '🇱🇺 +352', country: 'Luxembourg', currency: 'EUR', minLength: 8, maxLength: 10, placeholder: '8 to 10 digits', validPrefixes: ['6'], example: '621 123 456' },
|
|
||||||
{ iso2: 'HR', code: '+385', label: '🇭🇷 +385', country: 'Croatia', currency: 'EUR', minLength: 8, maxLength: 9, placeholder: '8 to 9 digits', validPrefixes: ['9'], example: '91 234 5678' },
|
|
||||||
{ iso2: 'SK', code: '+421', label: '🇸🇰 +421', country: 'Slovakia', currency: 'EUR', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['9'], example: '912 345 678' },
|
|
||||||
{ iso2: 'BG', code: '+359', label: '🇧🇬 +359', country: 'Bulgaria', currency: 'EUR', minLength: 8, maxLength: 9, placeholder: '8 to 9 digits', validPrefixes: ['8', '9'], example: '87 123 4567' },
|
|
||||||
{ iso2: 'CY', code: '+357', label: '🇨🇾 +357', country: 'Cyprus', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit phone number', validPrefixes: ['9'], example: '96 123456' },
|
|
||||||
{ iso2: 'EE', code: '+372', label: '🇪🇪 +372', country: 'Estonia', currency: 'EUR', minLength: 7, maxLength: 8, placeholder: '7 to 8 digits', validPrefixes: ['5'], example: '512 3456' },
|
|
||||||
{ iso2: 'LV', code: '+371', label: '🇱🇻 +371', country: 'Latvia', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit phone number', validPrefixes: ['2'], example: '2123 4567' },
|
|
||||||
{ iso2: 'LT', code: '+370', label: '🇱🇹 +370', country: 'Lithuania', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit phone number', validPrefixes: ['6'], example: '612 34567' },
|
|
||||||
{ iso2: 'MT', code: '+356', label: '🇲🇹 +356', country: 'Malta', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit phone number', validPrefixes: ['7', '9'], example: '7912 3456' },
|
|
||||||
{ iso2: 'SI', code: '+386', label: '🇸🇮 +386', country: 'Slovenia', currency: 'EUR', minLength: 8, maxLength: 8, placeholder: '8-digit phone number', validPrefixes: ['3', '4', '5', '6', '7'], example: '31 234 567' },
|
|
||||||
{ iso2: 'RU', code: '+7', label: '🇷🇺 +7', country: 'Russia', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['9'], example: '912 345-67-89' },
|
|
||||||
{ iso2: 'TR', code: '+90', label: '🇹🇷 +90', country: 'Turkey', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['5'], example: '501 234 56 78' },
|
|
||||||
|
|
||||||
// Asia-Pacific
|
|
||||||
{ iso2: 'AU', code: '+61', label: '🇦🇺 +61', country: 'Australia', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['4'], example: '412 345 678' },
|
|
||||||
{ iso2: 'NZ', code: '+64', label: '🇳🇿 +64', country: 'New Zealand', currency: 'USD', minLength: 8, maxLength: 10, placeholder: '8 to 10 digits', validPrefixes: ['2'], example: '21 123 4567' },
|
|
||||||
{ iso2: 'JP', code: '+81', label: '🇯🇵 +81', country: 'Japan', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['70', '80', '90', '7', '8', '9'], example: '90 1234 5678' },
|
|
||||||
{ iso2: 'CN', code: '+86', label: '🇨🇳 +86', country: 'China', currency: 'USD', minLength: 11, maxLength: 11, placeholder: '11-digit mobile number', validPrefixes: ['1'], example: '138 0013 8000' },
|
|
||||||
{ iso2: 'KR', code: '+82', label: '🇰🇷 +82', country: 'South Korea', currency: 'USD', minLength: 9, maxLength: 11, placeholder: '9 to 11 digits', validPrefixes: ['10', '1'], example: '10 1234 5678' },
|
|
||||||
{ iso2: 'HK', code: '+852', label: '🇭🇰 +852', country: 'Hong Kong', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['4', '5', '6', '7', '8', '9'], example: '5123 4567' },
|
|
||||||
{ iso2: 'TW', code: '+886', label: '🇹🇼 +886', country: 'Taiwan', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['9'], example: '912 345 678' },
|
|
||||||
{ iso2: 'SG', code: '+65', label: '🇸🇬 +65', country: 'Singapore', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['8', '9'], example: '8123 4567' },
|
|
||||||
{ iso2: 'MY', code: '+60', label: '🇲🇾 +60', country: 'Malaysia', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['1'], example: '12 345 6789' },
|
|
||||||
{ iso2: 'ID', code: '+62', label: '🇮🇩 +62', country: 'Indonesia', currency: 'USD', minLength: 9, maxLength: 12, placeholder: '9 to 12 digits', validPrefixes: ['8'], example: '812 3456 7890' },
|
|
||||||
{ iso2: 'PH', code: '+63', label: '🇵🇭 +63', country: 'Philippines', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['9'], example: '917 123 4567' },
|
|
||||||
{ iso2: 'TH', code: '+66', label: '🇹🇭 +66', country: 'Thailand', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['6', '8', '9'], example: '81 234 5678' },
|
|
||||||
{ iso2: 'VN', code: '+84', label: '🇻🇳 +84', country: 'Vietnam', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['3', '5', '7', '8', '9'], example: '91 234 5678' },
|
|
||||||
|
|
||||||
// Middle East
|
|
||||||
{ iso2: 'AE', code: '+971', label: '🇦🇪 +971', country: 'UAE', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['5'], example: '50 123 4567' },
|
|
||||||
{ iso2: 'SA', code: '+966', label: '🇸🇦 +966', country: 'Saudi Arabia', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['5'], example: '50 123 4567' },
|
|
||||||
{ iso2: 'QA', code: '+974', label: '🇶🇦 +974', country: 'Qatar', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['3', '5', '6', '7'], example: '3312 3456' },
|
|
||||||
{ iso2: 'KW', code: '+965', label: '🇰🇼 +965', country: 'Kuwait', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['5', '6', '9'], example: '5123 4567' },
|
|
||||||
{ iso2: 'OM', code: '+968', label: '🇴🇲 +968', country: 'Oman', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['7', '9'], example: '9123 4567' },
|
|
||||||
{ iso2: 'BH', code: '+973', label: '🇧🇭 +973', country: 'Bahrain', currency: 'USD', minLength: 8, maxLength: 8, placeholder: '8-digit mobile number', validPrefixes: ['3', '6'], example: '3600 1234' },
|
|
||||||
{ iso2: 'IL', code: '+972', label: '🇮🇱 +972', country: 'Israel', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['5'], example: '50 123 4567' },
|
|
||||||
{ iso2: 'JO', code: '+962', label: '🇯🇴 +962', country: 'Jordan', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['7'], example: '7 9012 3456' },
|
|
||||||
{ iso2: 'LB', code: '+961', label: '🇱🇧 +961', country: 'Lebanon', currency: 'USD', minLength: 7, maxLength: 8, placeholder: '7 to 8 digits', validPrefixes: ['3', '7', '8'], example: '70 123 456' },
|
|
||||||
|
|
||||||
// Latin America
|
|
||||||
{ iso2: 'BR', code: '+55', label: '🇧🇷 +55', country: 'Brazil', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['9'], example: '11 91234 5678' },
|
|
||||||
{ iso2: 'AR', code: '+54', label: '🇦🇷 +54', country: 'Argentina', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['9'], example: '9 11 1234-5678' },
|
|
||||||
{ iso2: 'CL', code: '+56', label: '🇨🇱 +56', country: 'Chile', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['9'], example: '9 1234 5678' },
|
|
||||||
{ iso2: 'CO', code: '+57', label: '🇨🇴 +57', country: 'Colombia', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['3'], example: '300 123 4567' },
|
|
||||||
{ iso2: 'PE', code: '+51', label: '🇵🇪 +51', country: 'Peru', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['9'], example: '912 345 678' },
|
|
||||||
|
|
||||||
// Africa
|
|
||||||
{ iso2: 'ZA', code: '+27', label: '🇿🇦 +27', country: 'South Africa', currency: 'USD', minLength: 9, maxLength: 10, placeholder: '9 to 10 digits', validPrefixes: ['6', '7', '8'], example: '71 234 5678' },
|
|
||||||
{ iso2: 'NG', code: '+234', label: '🇳🇬 +234', country: 'Nigeria', currency: 'USD', minLength: 10, maxLength: 11, placeholder: '10 to 11 digits', validPrefixes: ['7', '8', '9'], example: '802 123 4567' },
|
|
||||||
{ iso2: 'KE', code: '+254', label: '🇰🇪 +254', country: 'Kenya', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['7', '1'], example: '712 345678' },
|
|
||||||
{ iso2: 'GH', code: '+233', label: '🇬🇭 +233', country: 'Ghana', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['2', '5'], example: '24 123 4567' },
|
|
||||||
{ iso2: 'EG', code: '+20', label: '🇪🇬 +20', country: 'Egypt', currency: 'USD', minLength: 10, maxLength: 10, placeholder: '10-digit mobile number', validPrefixes: ['1'], example: '10 1234 5678' },
|
|
||||||
{ iso2: 'MA', code: '+212', label: '🇲🇦 +212', country: 'Morocco', currency: 'USD', minLength: 9, maxLength: 9, placeholder: '9-digit mobile number', validPrefixes: ['6', '7'], example: '612-345678' },
|
|
||||||
{ iso2: 'MU', code: '+230', label: '🇲🇺 +230', country: 'Mauritius', currency: 'USD', minLength: 7, maxLength: 8, placeholder: '7 to 8 digits', validPrefixes: ['5'], example: '5123 4567' },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
// Alphabetically sorted list of countries (A-Z)
|
|
||||||
export const SORTED_COUNTRY_CODES: CountryCode[] = [...COUNTRY_CODES].sort((a, b) =>
|
|
||||||
a.country.localeCompare(b.country)
|
|
||||||
);
|
|
||||||
|
|
||||||
export const DEFAULT_COUNTRY = COUNTRY_CODES[0]; // India (+91)
|
|
||||||
|
|
||||||
export const getCountryRuleByIso = (iso?: string | null): CountryCode => {
|
|
||||||
if (!iso) return DEFAULT_COUNTRY;
|
|
||||||
const upper = iso.toUpperCase().trim();
|
|
||||||
return COUNTRY_CODES.find((c) => c.iso2 === upper) || DEFAULT_COUNTRY;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getCountryRuleByName = (countryName?: string | null): CountryCode => {
|
|
||||||
if (!countryName) return DEFAULT_COUNTRY;
|
|
||||||
const normalized = countryName.toLowerCase().trim();
|
|
||||||
return (
|
|
||||||
COUNTRY_CODES.find(
|
|
||||||
(c) =>
|
|
||||||
c.country.toLowerCase() === normalized ||
|
|
||||||
c.iso2.toLowerCase() === normalized ||
|
|
||||||
normalized.includes(c.country.toLowerCase())
|
|
||||||
) || {
|
|
||||||
iso2: 'IN',
|
|
||||||
code: '+91',
|
|
||||||
label: '🇮🇳 +91',
|
|
||||||
country: countryName,
|
|
||||||
currency: normalized === 'india' ? 'INR' : 'USD',
|
|
||||||
minLength: 7,
|
|
||||||
maxLength: 15,
|
|
||||||
placeholder: 'Phone number',
|
|
||||||
}
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getCountryRuleByDialCode = (dialCode?: string | null, countryHint?: string | null): CountryCode => {
|
|
||||||
if (!dialCode) return DEFAULT_COUNTRY;
|
|
||||||
// If country hint is given, try resolving by country first
|
|
||||||
if (countryHint) {
|
|
||||||
const byCountry = getCountryRuleByName(countryHint);
|
|
||||||
if (byCountry && byCountry.code === dialCode) {
|
|
||||||
return byCountry;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
COUNTRY_CODES.find((c) => c.code === dialCode) || {
|
|
||||||
iso2: 'IN',
|
|
||||||
code: dialCode,
|
|
||||||
label: dialCode,
|
|
||||||
country: countryHint || 'Other',
|
|
||||||
currency: 'USD',
|
|
||||||
minLength: 7,
|
|
||||||
maxLength: 15,
|
|
||||||
placeholder: 'Phone number',
|
|
||||||
}
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
|
||||||
|
|
@ -11,33 +11,33 @@ export interface ModuleItem {
|
||||||
|
|
||||||
export const CURRICULUM_MODULES: ModuleItem[] = [
|
export const CURRICULUM_MODULES: ModuleItem[] = [
|
||||||
// 1. Points Category
|
// 1. Points Category
|
||||||
{ code: 'POINTS_ACU', name: 'Points: Acu (EOV+Cat+Ext+MR)', category: 'Points', priceInr: 300, priceUsd: 5.0, priceEur: 5.0, desc: '1 Year: Unlocks Master Acupuncture Points, Extraordinary Vessels, Category/Extension Rules, and Meridian Stimulations.', color: 'from-blue-500 to-indigo-600' },
|
{ code: 'POINTS_ACU', name: 'Points: Acu (EOV+Cat+Ext+MR)', category: 'Points', priceInr: 1, priceUsd: 1.0, priceEur: 1.0, desc: '1 Year: Unlocks Master Acupuncture Points, Extraordinary Vessels, Category/Extension Rules, and Meridian Stimulations.', color: 'from-blue-500 to-indigo-600' },
|
||||||
{ code: 'POINTS_SCALP', name: 'Points: Scalp', category: 'Points', priceInr: 100, priceUsd: 2.0, priceEur: 2.0, desc: '1 Year: Unlocks High-Performance Scalp Acupuncture Mapping for specialized clinical neurological disorders.', color: 'from-indigo-500 to-purple-600' },
|
{ code: 'POINTS_SCALP', name: 'Points: Scalp', category: 'Points', priceInr: 1, priceUsd: 1.0, priceEur: 1.0, desc: '1 Year: Unlocks High-Performance Scalp Acupuncture Mapping for specialized clinical neurological disorders.', color: 'from-indigo-500 to-purple-600' },
|
||||||
{ code: 'POINTS_EAR', name: 'Points: Ear / Auricular', category: 'Points', priceInr: 200, priceUsd: 3.0, priceEur: 3.0, desc: '1 Year: Unlocks specialized Ear Micro-System Reflex stimulations, anatomy mapping, and reflexes.', color: 'from-purple-500 to-pink-600' },
|
{ code: 'POINTS_EAR', name: 'Points: Ear / Auricular', category: 'Points', priceInr: 1, priceUsd: 1.0, priceEur: 1.0, desc: '1 Year: Unlocks specialized Ear Micro-System Reflex stimulations, anatomy mapping, and reflexes.', color: 'from-purple-500 to-pink-600' },
|
||||||
{ code: 'POINTS_TUNG', name: 'Master Tung', category: 'Points', priceInr: 300, priceUsd: 5.0, priceEur: 5.0, desc: '1 Year: Unlocks Master Tung\'s legendary extra points, clinical distals, and unique point properties.', color: 'from-pink-500 to-rose-600' },
|
{ code: 'POINTS_TUNG', name: 'Master Tung', category: 'Points', priceInr: 1, priceUsd: 1.0, priceEur: 1.0, desc: '1 Year: Unlocks Master Tung\'s legendary extra points, clinical distals, and unique point properties.', color: 'from-pink-500 to-rose-600' },
|
||||||
{ code: 'POINTS_PACK', name: 'Points: Complete Pack', category: 'Points', priceInr: 900, priceUsd: 15.0, priceEur: 15.0, desc: '1 Year: Unlock all 4 Points modules (Acu, Scalp, Ear, and Master Tung) at once for ultimate master-level access.', color: 'from-indigo-600 to-pink-600' },
|
{ code: 'POINTS_PACK', name: 'Points: Complete Pack', category: 'Points', priceInr: 2, priceUsd: 2.0, priceEur: 2.0, desc: '1 Year: Unlock all 4 Points modules (Acu, Scalp, Ear, and Master Tung) at once for ultimate master-level access.', color: 'from-indigo-600 to-pink-600' },
|
||||||
|
|
||||||
// 2. Pattern Category — Individual sub-modules (all map to PATTERN_CORE plan)
|
// 2. Pattern Category — Individual sub-modules (all map to PATTERN_CORE plan)
|
||||||
{ code: 'PATTERN_CORE', name: 'Eight Principles', category: 'Pattern', priceInr: 500, priceUsd: 10.0, priceEur: 10.0, desc: '1 Year: Exterior/Interior, Cold/Heat, Deficiency/Excess, Yin/Yang pattern differentiation.', color: 'from-violet-500 to-purple-600' },
|
{ code: 'PATTERN_CORE', name: 'Eight Principles', category: 'Pattern', priceInr: 1, priceUsd: 1.0, priceEur: 1.0, desc: '1 Year: Exterior/Interior, Cold/Heat, Deficiency/Excess, Yin/Yang pattern differentiation.', color: 'from-violet-500 to-purple-600' },
|
||||||
{ code: 'PATTERN_CORE', name: 'Zang-Fu Organs', category: 'Pattern', priceInr: 500, priceUsd: 10.0, priceEur: 10.0, desc: '1 Year: Zangfu organ and channel identification across 12 organ systems.', color: 'from-cyan-500 to-blue-600' },
|
{ code: 'PATTERN_CORE', name: 'Zang-Fu Organs', category: 'Pattern', priceInr: 1, priceUsd: 1.0, priceEur: 1.0, desc: '1 Year: Zangfu organ and channel identification across 12 organ systems.', color: 'from-cyan-500 to-blue-600' },
|
||||||
{ code: 'PATTERN_CORE', name: 'Qi, Blood & Body Fluids', category: 'Pattern', priceInr: 500, priceUsd: 10.0, priceEur: 10.0, desc: '1 Year: Qi, Blood, and Body Fluid identification of pathological patterns.', color: 'from-blue-500 to-indigo-600' },
|
{ code: 'PATTERN_CORE', name: 'Qi, Blood & Body Fluids', category: 'Pattern', priceInr: 1, priceUsd: 1.0, priceEur: 1.0, desc: '1 Year: Qi, Blood, and Body Fluid identification of pathological patterns.', color: 'from-blue-500 to-indigo-600' },
|
||||||
{ code: 'PATTERN_CORE', name: 'Pathogenic Factors', category: 'Pattern', priceInr: 500, priceUsd: 10.0, priceEur: 10.0, desc: '1 Year: Wind, Cold, Summer-Heat, Dampness, Dryness, Fire pattern identification.', color: 'from-amber-500 to-orange-600' },
|
{ code: 'PATTERN_CORE', name: 'Pathogenic Factors', category: 'Pattern', priceInr: 1, priceUsd: 1.0, priceEur: 1.0, desc: '1 Year: Wind, Cold, Summer-Heat, Dampness, Dryness, Fire pattern identification.', color: 'from-amber-500 to-orange-600' },
|
||||||
{ code: 'PATTERN_CORE', name: 'Six Stages', category: 'Pattern', priceInr: 500, priceUsd: 10.0, priceEur: 10.0, desc: '1 Year: Tai Yang, Yang Ming, Shao Yang, Tai Yin, Shao Yin, Jue Yin stage differentiation.', color: 'from-emerald-500 to-green-600' },
|
{ code: 'PATTERN_CORE', name: 'Six Stages', category: 'Pattern', priceInr: 1, priceUsd: 1.0, priceEur: 1.0, desc: '1 Year: Tai Yang, Yang Ming, Shao Yang, Tai Yin, Shao Yin, Jue Yin stage differentiation.', color: 'from-emerald-500 to-green-600' },
|
||||||
{ code: 'PATTERN_CORE', name: 'Four Levels', category: 'Pattern', priceInr: 500, priceUsd: 10.0, priceEur: 10.0, desc: '1 Year: Wei, Qi, Ying, Xue level pattern identification for warm diseases.', color: 'from-red-500 to-rose-600' },
|
{ code: 'PATTERN_CORE', name: 'Four Levels', category: 'Pattern', priceInr: 1, priceUsd: 1.0, priceEur: 1.0, desc: '1 Year: Wei, Qi, Ying, Xue level pattern identification for warm diseases.', color: 'from-red-500 to-rose-600' },
|
||||||
{ code: 'PATTERN_CORE', name: 'Three Burners', category: 'Pattern', priceInr: 500, priceUsd: 10.0, priceEur: 10.0, desc: '1 Year: Upper, Middle, and Lower Burner (San Jiao) pattern identification.', color: 'from-pink-500 to-fuchsia-600' },
|
{ code: 'PATTERN_CORE', name: 'Three Burners', category: 'Pattern', priceInr: 1, priceUsd: 1.0, priceEur: 1.0, desc: '1 Year: Upper, Middle, and Lower Burner (San Jiao) pattern identification.', color: 'from-pink-500 to-fuchsia-600' },
|
||||||
{ code: 'PATTERN_CORE', name: 'Five Elements', category: 'Pattern', priceInr: 500, priceUsd: 10.0, priceEur: 10.0, desc: '1 Year: Wood, Fire, Earth, Metal, Water relationships and clinical patterns.', color: 'from-indigo-500 to-violet-600' },
|
{ code: 'PATTERN_CORE', name: 'Five Elements', category: 'Pattern', priceInr: 1, priceUsd: 1.0, priceEur: 1.0, desc: '1 Year: Wood, Fire, Earth, Metal, Water relationships and clinical patterns.', color: 'from-indigo-500 to-violet-600' },
|
||||||
{ code: 'PATTERN_CORE', name: 'Pattern: Complete Pack', category: 'Pattern', priceInr: 500, priceUsd: 10.0, priceEur: 10.0, desc: '1 Year: Unlock all 8 Pattern Diagnosis methodologies at once for complete syndrome differentiation mastery.', color: 'from-rose-600 to-orange-600' },
|
{ code: 'PATTERN_CORE', name: 'Pattern: Complete Pack', category: 'Pattern', priceInr: 2, priceUsd: 2.0, priceEur: 2.0, desc: '1 Year: Unlock all 8 Pattern Diagnosis methodologies at once for complete syndrome differentiation mastery.', color: 'from-rose-600 to-orange-600' },
|
||||||
|
|
||||||
// 3. Nutrition Category — Individual sub-modules (all map to NUTRITION_CORE plan)
|
// 3. Nutrition Category — Individual sub-modules (all map to NUTRITION_CORE plan)
|
||||||
{ code: 'NUTRITION_CORE', name: 'Food Categories', category: 'Nutrition', priceInr: 600, priceUsd: 15.0, priceEur: 15.0, desc: '1 Year: Nutritional food category classifications, thermal properties, and dietetic groupings.', color: 'from-emerald-500 to-teal-600' },
|
{ code: 'NUTRITION_CORE', name: 'Food Categories', category: 'Nutrition', priceInr: 1, priceUsd: 1.0, priceEur: 1.0, desc: '1 Year: Nutritional food category classifications, thermal properties, and dietetic groupings.', color: 'from-emerald-500 to-teal-600' },
|
||||||
{ code: 'NUTRITION_CORE', name: 'Food Items', category: 'Nutrition', priceInr: 600, priceUsd: 15.0, priceEur: 15.0, desc: '1 Year: Individual food item properties, indications, and therapeutic applications.', color: 'from-green-500 to-emerald-600' },
|
{ code: 'NUTRITION_CORE', name: 'Food Items', category: 'Nutrition', priceInr: 1, priceUsd: 1.0, priceEur: 1.0, desc: '1 Year: Individual food item properties, indications, and therapeutic applications.', color: 'from-green-500 to-emerald-600' },
|
||||||
{ code: 'NUTRITION_CORE', name: 'Nutrition: Complete Pack', category: 'Nutrition', priceInr: 600, priceUsd: 15.0, priceEur: 15.0, desc: '1 Year: Unlock all Nutrition & Dietetics modules for complete clinical dietary therapy mastery.', color: 'from-teal-500 to-green-600' },
|
{ code: 'NUTRITION_CORE', name: 'Nutrition: Complete Pack', category: 'Nutrition', priceInr: 2, priceUsd: 2.0, priceEur: 2.0, desc: '1 Year: Unlock all Nutrition & Dietetics modules for complete clinical dietary therapy mastery.', color: 'from-teal-500 to-green-600' },
|
||||||
|
|
||||||
// 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: 1, priceUsd: 1.0, priceEur: 1.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: 1, priceUsd: 1.0, priceEur: 1.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: 2, priceUsd: 2.0, priceEur: 2.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: 2, priceUsd: 2.0, priceEur: 2.0, desc: '10 Years: Unlock all 10 current modules + all future updates. Includes official master clinical certificate.', color: 'from-yellow-500 to-amber-600' }
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -9,9 +9,6 @@ export interface ModuleItem {
|
||||||
priceEur: number;
|
priceEur: number;
|
||||||
desc: string;
|
desc: string;
|
||||||
color: string;
|
color: string;
|
||||||
isRenewal?: boolean;
|
|
||||||
sortOrder?: number;
|
|
||||||
planType?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserSubscription {
|
export interface UserSubscription {
|
||||||
|
|
@ -23,8 +20,6 @@ export interface UserSubscription {
|
||||||
expires_at?: string;
|
expires_at?: string;
|
||||||
is_active: boolean;
|
is_active: boolean;
|
||||||
payment_id?: string;
|
payment_id?: string;
|
||||||
invoice_number?: string;
|
|
||||||
invoice_url?: string;
|
|
||||||
metadata?: Record<string, any>;
|
metadata?: Record<string, any>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -39,18 +34,12 @@ 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[];
|
|
||||||
created_at?: string;
|
created_at?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PricingCalculation {
|
export interface PricingCalculation {
|
||||||
base_subtotal?: number;
|
|
||||||
original_price: number;
|
original_price: number;
|
||||||
discount_amount: number;
|
discount_amount: number;
|
||||||
discount_policy?: string;
|
|
||||||
bundle_discount_amount?: number;
|
|
||||||
total_discounts?: number;
|
|
||||||
taxable_amount: number;
|
taxable_amount: number;
|
||||||
gst_amount: number;
|
gst_amount: number;
|
||||||
convenience_fee?: number;
|
convenience_fee?: number;
|
||||||
|
|
@ -58,10 +47,6 @@ export interface PricingCalculation {
|
||||||
grand_total: number;
|
grand_total: number;
|
||||||
total_amount?: number;
|
total_amount?: number;
|
||||||
currency: Currency;
|
currency: Currency;
|
||||||
renewal_discount_amount?: number;
|
|
||||||
coupon_applied?: string;
|
|
||||||
coupon_discount_amount?: number;
|
|
||||||
coupon_error?: string | null;
|
|
||||||
applied_coupon?: {
|
applied_coupon?: {
|
||||||
code: string;
|
code: string;
|
||||||
discount_type: 'percentage' | 'fixed';
|
discount_type: 'percentage' | 'fixed';
|
||||||
|
|
@ -79,28 +64,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,46 +0,0 @@
|
||||||
/**
|
|
||||||
* Generic Navigation & Deep-Linking Utility for Acupedia Storefront
|
|
||||||
*/
|
|
||||||
|
|
||||||
export const DEFAULT_APP_SCHEMES = ['acupedia', 'myapp'];
|
|
||||||
export const DEFAULT_RETURN_ROUTE = 'modules';
|
|
||||||
|
|
||||||
export interface MobileAppLaunchOptions {
|
|
||||||
route?: string;
|
|
||||||
schemes?: string[];
|
|
||||||
delayBetweenFallbacks?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cleanly format route for custom URI scheme (e.g. "/modules" -> "modules")
|
|
||||||
*/
|
|
||||||
export function formatDeepLinkRoute(route?: string): string {
|
|
||||||
if (!route) return DEFAULT_RETURN_ROUTE;
|
|
||||||
return route.replace(/^\/+/, '').trim() || DEFAULT_RETURN_ROUTE;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Generate full deep-link URLs for supported schemes
|
|
||||||
*/
|
|
||||||
export function getAppDeepLinkUrls(options: MobileAppLaunchOptions = {}): string[] {
|
|
||||||
const route = formatDeepLinkRoute(options.route);
|
|
||||||
const schemes = options.schemes && options.schemes.length > 0 ? options.schemes : DEFAULT_APP_SCHEMES;
|
|
||||||
return schemes.map((scheme) => `${scheme}://${route}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Generic function to launch the mobile app with progressive fallback across supported schemes
|
|
||||||
*/
|
|
||||||
export function openMobileApp(options: MobileAppLaunchOptions = {}): void {
|
|
||||||
const urls = getAppDeepLinkUrls(options);
|
|
||||||
if (urls.length === 0) return;
|
|
||||||
|
|
||||||
const [primaryUrl, ...fallbackUrls] = urls;
|
|
||||||
window.location.href = primaryUrl;
|
|
||||||
|
|
||||||
fallbackUrls.forEach((url, idx) => {
|
|
||||||
setTimeout(() => {
|
|
||||||
window.location.href = url;
|
|
||||||
}, (idx + 1) * (options.delayBetweenFallbacks || 500));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
@ -1,311 +0,0 @@
|
||||||
import { parsePhoneNumberFromString, type CountryCode as LibCountryCode } from 'libphonenumber-js/max';
|
|
||||||
import {
|
|
||||||
COUNTRY_CODES,
|
|
||||||
getCountryRuleByDialCode,
|
|
||||||
getCountryRuleByName,
|
|
||||||
getCountryRuleByIso,
|
|
||||||
DEFAULT_COUNTRY,
|
|
||||||
} from '../constants/countries';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Formats a list of prefixes into human-readable text:
|
|
||||||
* e.g. ['3'] -> "3"
|
|
||||||
* e.g. ['6', '7'] -> "6 or 7"
|
|
||||||
* e.g. ['6', '7', '8', '9'] -> "6, 7, 8, or 9"
|
|
||||||
*/
|
|
||||||
export const formatPrefixList = (prefixes: string[]): string => {
|
|
||||||
if (prefixes.length === 0) return '';
|
|
||||||
if (prefixes.length === 1) return prefixes[0];
|
|
||||||
if (prefixes.length === 2) return `${prefixes[0]} or ${prefixes[1]}`;
|
|
||||||
return `${prefixes.slice(0, -1).join(', ')}, or ${prefixes[prefixes.length - 1]}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Strips non-numeric / non-phone characters from text in real-time
|
|
||||||
* If maxLength is provided, strictly restricts digit length
|
|
||||||
* If allowPlus is false, strips any '+' symbols as well (for local number inputs)
|
|
||||||
*/
|
|
||||||
export const cleanPhoneInput = (text: string, maxLength = 15, allowPlus = true): string => {
|
|
||||||
const trimmedStart = text.trimStart();
|
|
||||||
const hasPlus = allowPlus && trimmedStart.startsWith('+');
|
|
||||||
const rest = hasPlus ? trimmedStart.slice(1) : text;
|
|
||||||
const digitsOnly = rest.replace(/\D/g, '');
|
|
||||||
const boundedDigits = maxLength ? digitsOnly.slice(0, maxLength) : digitsOnly;
|
|
||||||
return hasPlus ? `+${boundedDigits}` : boundedDigits;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validates mobile phone number according to country telecom numbering plans.
|
|
||||||
* Uses libphonenumber-js to enforce mobile prefixes (e.g., France 06/07, India 6-9, UK 07).
|
|
||||||
*/
|
|
||||||
export const validatePhoneNumber = (
|
|
||||||
val?: string | null,
|
|
||||||
dialCode?: string,
|
|
||||||
country?: string
|
|
||||||
): string | null => {
|
|
||||||
if (!val || !val.trim()) return null;
|
|
||||||
const trimmed = val.trim();
|
|
||||||
|
|
||||||
// Explicitly disallow alphabetic characters
|
|
||||||
if (/[a-zA-Z]/.test(trimmed)) {
|
|
||||||
return 'Phone number cannot contain alphabetic characters.';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Strictly disallow hyphens, dashes, and invalid symbols
|
|
||||||
if (/[\-_()/[\]]/.test(trimmed)) {
|
|
||||||
return 'Phone number cannot contain hyphens or special symbols.';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Strictly enforce numeric digits with optional leading '+' and whitespace
|
|
||||||
if (!/^\+?[\d\s]+$/.test(trimmed)) {
|
|
||||||
return 'Please enter a valid phone number containing only numeric digits.';
|
|
||||||
}
|
|
||||||
|
|
||||||
const allDigits = trimmed.replace(/\D/g, '');
|
|
||||||
if (allDigits.length === 0) {
|
|
||||||
return 'Please enter a valid phone number with numeric digits.';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Resolve country rule: prioritize explicit country name, fallback to dialCode
|
|
||||||
let rule = country ? getCountryRuleByName(country) : undefined;
|
|
||||||
if ((!rule || rule.country === 'Other') && dialCode) {
|
|
||||||
rule = getCountryRuleByDialCode(dialCode, country);
|
|
||||||
}
|
|
||||||
if (!rule) {
|
|
||||||
rule = DEFAULT_COUNTRY;
|
|
||||||
}
|
|
||||||
|
|
||||||
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.validPrefixes && rule.validPrefixes.length > 0) {
|
|
||||||
const hasValidPrefix = rule.validPrefixes.some(
|
|
||||||
(prefix) => digitsWithoutTrunk0.startsWith(prefix) || nationalDigits.startsWith(prefix)
|
|
||||||
);
|
|
||||||
if (!hasValidPrefix) {
|
|
||||||
return `For ${rule.country}, the mobile number must start with ${formatPrefixList(rule.validPrefixes)}.`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Validate telecom numbering rules with libphonenumber-js
|
|
||||||
const candidate = trimmed.startsWith('+') ? trimmed : `${rule.code}${nationalDigits}`;
|
|
||||||
const parsed = parsePhoneNumberFromString(candidate, iso2);
|
|
||||||
|
|
||||||
if (parsed && parsed.isValid()) {
|
|
||||||
const numberType = parsed.getType();
|
|
||||||
if (numberType === 'FIXED_LINE') {
|
|
||||||
return `Please enter a valid mobile number for ${rule.country} (landlines not allowed).`;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const exampleStr = rule.example || rule.placeholder;
|
|
||||||
return `Please enter a valid mobile number for ${rule.country}${exampleStr ? ` (e.g. ${exampleStr})` : ''}.`;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const isValidPhoneNumber = (
|
|
||||||
val?: string | null,
|
|
||||||
dialCode?: string,
|
|
||||||
country?: string
|
|
||||||
): boolean => {
|
|
||||||
return validatePhoneNumber(val, dialCode, country) === null;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Splits a full phone number into dialCode, country, and localDigits
|
|
||||||
*/
|
|
||||||
export const parsePhoneNumber = (
|
|
||||||
fullPhone?: string | null,
|
|
||||||
fallbackCountry = 'India'
|
|
||||||
): { country: string; dialCode: string; localDigits: string; iso2: LibCountryCode } => {
|
|
||||||
const defaultRule = getCountryRuleByName(fallbackCountry) || DEFAULT_COUNTRY;
|
|
||||||
if (!fullPhone || !fullPhone.trim()) {
|
|
||||||
return {
|
|
||||||
country: defaultRule.country,
|
|
||||||
dialCode: defaultRule.code,
|
|
||||||
localDigits: '',
|
|
||||||
iso2: defaultRule.iso2,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const trimmed = fullPhone.trim();
|
|
||||||
const parsed = parsePhoneNumberFromString(trimmed, defaultRule.iso2);
|
|
||||||
|
|
||||||
if (parsed) {
|
|
||||||
const matchedRule = parsed.country
|
|
||||||
? getCountryRuleByIso(parsed.country)
|
|
||||||
: getCountryRuleByDialCode(`+${parsed.countryCallingCode}`, fallbackCountry);
|
|
||||||
|
|
||||||
return {
|
|
||||||
country: matchedRule.country,
|
|
||||||
dialCode: `+${parsed.countryCallingCode}`,
|
|
||||||
localDigits: parsed.nationalNumber,
|
|
||||||
iso2: matchedRule.iso2,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback regex match from longest dial code
|
|
||||||
const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length);
|
|
||||||
|
|
||||||
// If fallbackCountry is specified and matches the prefix, prioritize it
|
|
||||||
if (fallbackCountry && trimmed.startsWith(defaultRule.code)) {
|
|
||||||
const rawLocal = trimmed.slice(defaultRule.code.length).replace(/\D/g, '');
|
|
||||||
return {
|
|
||||||
country: defaultRule.country,
|
|
||||||
dialCode: defaultRule.code,
|
|
||||||
localDigits: rawLocal.slice(0, defaultRule.maxLength),
|
|
||||||
iso2: defaultRule.iso2,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const matched = sorted.find((c) => trimmed.startsWith(c.code));
|
|
||||||
if (matched) {
|
|
||||||
const rawLocal = trimmed.slice(matched.code.length).replace(/\D/g, '');
|
|
||||||
return {
|
|
||||||
country: matched.country,
|
|
||||||
dialCode: matched.code,
|
|
||||||
localDigits: rawLocal.slice(0, matched.maxLength),
|
|
||||||
iso2: matched.iso2,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const rawDigits = trimmed.replace(/\D/g, '');
|
|
||||||
return {
|
|
||||||
country: defaultRule.country,
|
|
||||||
dialCode: defaultRule.code,
|
|
||||||
localDigits: rawDigits.slice(0, defaultRule.maxLength),
|
|
||||||
iso2: defaultRule.iso2,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Formats full phone number cleanly as E.164 without spaces (+<dialCode><digits>),
|
|
||||||
* automatically stripping any national trunk '0' where appropriate.
|
|
||||||
*/
|
|
||||||
export const formatE164Phone = (dialCode: string, localDigits: string, country?: string): string => {
|
|
||||||
if (!localDigits || !localDigits.trim()) return '';
|
|
||||||
const rule = country ? getCountryRuleByName(country) : getCountryRuleByDialCode(dialCode, country);
|
|
||||||
const rawDigits = localDigits.replace(/\D/g, '');
|
|
||||||
if (!rawDigits) return '';
|
|
||||||
|
|
||||||
const code = dialCode.startsWith('+') ? dialCode : `+${dialCode}`;
|
|
||||||
const candidate = localDigits.startsWith('+') ? localDigits : `${code}${rawDigits}`;
|
|
||||||
|
|
||||||
const parsed = parsePhoneNumberFromString(candidate, rule.iso2);
|
|
||||||
if (parsed && parsed.isValid()) {
|
|
||||||
return parsed.format('E.164');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: If starts with trunk 0 and country is not one that keeps trunk 0 (like Italy)
|
|
||||||
let cleanLocal = rawDigits;
|
|
||||||
if (rule.iso2 !== 'IT' && cleanLocal.startsWith('0')) {
|
|
||||||
cleanLocal = cleanLocal.replace(/^0+/, '');
|
|
||||||
}
|
|
||||||
|
|
||||||
return `${code}${cleanLocal}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates the dial code prefix of an existing phone number when country changes.
|
|
||||||
* Automatically clamps remaining digits to the new country's maxLength.
|
|
||||||
*/
|
|
||||||
export const updatePhoneDialCode = (
|
|
||||||
currentPhone: string,
|
|
||||||
oldCountry: string,
|
|
||||||
newCountry: string
|
|
||||||
): string => {
|
|
||||||
const trimmed = currentPhone.trim();
|
|
||||||
if (!trimmed) return '';
|
|
||||||
|
|
||||||
const oldRule = getCountryRuleByName(oldCountry);
|
|
||||||
const newRule = getCountryRuleByName(newCountry);
|
|
||||||
|
|
||||||
const parsed = parsePhoneNumber(trimmed, oldRule.country);
|
|
||||||
const bounded = parsed.localDigits.slice(0, newRule.maxLength);
|
|
||||||
return bounded ? `${newRule.code} ${bounded}` : `${newRule.code} `;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const SPECIAL_CHAR_REGEX = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?`~]/;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validates password strength consistently across registration, profile change, and password reset:
|
|
||||||
* - Minimum 8 characters
|
|
||||||
* - No spaces (whitespace strictly disallowed)
|
|
||||||
* - At least one uppercase letter
|
|
||||||
* - At least one number
|
|
||||||
* - No emojis
|
|
||||||
* - At least one special character from standard symbol set
|
|
||||||
*/
|
|
||||||
export const validatePassword = (password: string, fieldName = 'Password'): string | null => {
|
|
||||||
if (!password) {
|
|
||||||
return `${fieldName} is required.`;
|
|
||||||
}
|
|
||||||
if (password.length < 8) {
|
|
||||||
return `${fieldName} must be at least 8 characters long.`;
|
|
||||||
}
|
|
||||||
if (/\s/.test(password)) {
|
|
||||||
return `${fieldName} must not contain spaces.`;
|
|
||||||
}
|
|
||||||
if (!/[A-Z]/.test(password)) {
|
|
||||||
return `${fieldName} must contain at least one uppercase letter.`;
|
|
||||||
}
|
|
||||||
if (!/[0-9]/.test(password)) {
|
|
||||||
return `${fieldName} must contain at least one number.`;
|
|
||||||
}
|
|
||||||
if (/\p{Extended_Pictographic}/u.test(password)) {
|
|
||||||
return `${fieldName} must not contain emojis.`;
|
|
||||||
}
|
|
||||||
if (!SPECIAL_CHAR_REGEX.test(password)) {
|
|
||||||
return `${fieldName} must contain at least one special character.`;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* RFC 5322 & RFC 1035 compliant email validation regex.
|
|
||||||
*/
|
|
||||||
export const EMAIL_REGEX = /^[a-zA-Z0-9_%+-]+(?:\.[a-zA-Z0-9_%+-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/;
|
|
||||||
|
|
||||||
export const validateEmail = (email?: string | null): string | null => {
|
|
||||||
if (!email || !email.trim()) {
|
|
||||||
return 'Email address is required.';
|
|
||||||
}
|
|
||||||
if (!EMAIL_REGEX.test(email.trim())) {
|
|
||||||
return 'Please enter a valid email address.';
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const isValidEmail = (email?: string | null): boolean => {
|
|
||||||
return validateEmail(email) === null;
|
|
||||||
};
|
|
||||||
|
|
@ -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