diff --git a/src/App.tsx b/src/App.tsx index 4d0b556..0eebea9 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -2,9 +2,11 @@ import { useState, useEffect } from 'react'; import axios from 'axios'; import { CURRICULUM_MODULES } from './constants/modules'; +import { getCountryRuleByName } from './constants/countries'; import type { ModuleItem, Currency, UserProfile, VerificationResult, PublicPlan } from './types'; import { API_BASE } from './services/api'; import { loadRazorpayScript } from './services/razorpay'; +import { cleanPhoneInput, validatePhoneNumber } from './utils/validation'; // Modular Subcomponents import { StoreHeader } from './components/layout/StoreHeader'; @@ -211,14 +213,12 @@ export default function App() { calculatePricing(); }, [cart, appliedCoupon, currency]); - // Update currency automatically on country selection during registration + // Update currency and dial code automatically on country selection during registration useEffect(() => { if (authMode === 'register') { - if (authCountry === 'India') { - setCurrency('INR'); - } else { - setCurrency('USD'); - } + const rule = getCountryRuleByName(authCountry); + setCurrency(rule.currency); + setAuthDialCode(rule.code); } }, [authCountry, authMode]); @@ -240,11 +240,8 @@ export default function App() { setProfileDisplayName(profileRes.data.display_name || ''); setProfilePhone(profileRes.data.phone_number || ''); setProfileCountry(profileRes.data.country || 'India'); - if (profileRes.data.country === 'India') { - setCurrency('INR'); - } else { - setCurrency('USD'); - } + const countryRule = getCountryRuleByName(profileRes.data.country || 'India'); + setCurrency(countryRule.currency); } catch (err) { console.error('Failed to fetch user profile:', err); handleLogout(); @@ -273,6 +270,15 @@ export default function App() { setProfileError(null); setProfileSuccess(false); + if (profilePhone && profilePhone.trim()) { + const phoneError = validatePhoneNumber(profilePhone, undefined, profileCountry); + if (phoneError) { + setProfileError(phoneError); + setProfileSaving(false); + return; + } + } + try { await axios.put(`${API_BASE}/api/auth/profile`, { full_name: profileDisplayName, @@ -299,6 +305,7 @@ export default function App() { setAuthError(null); const trimmedEmail = authEmail.trim(); + if (!trimmedEmail) { setAuthError('Email address is required.'); setAuthLoading(false); @@ -324,7 +331,40 @@ export default function App() { return; } + if (authMode === 'register' && authPhone && authPhone.trim()) { + const phoneError = validatePhoneNumber(authPhone, authDialCode, authCountry); + if (phoneError) { + setAuthError(phoneError); + setAuthLoading(false); + return; + } + } + const endpoint = authMode === 'login' ? '/api/auth/login' : '/api/auth/register'; + + if (authMode === 'register') { + if (authPassword.length < 8) { + setAuthError('Password must be at least 8 characters long.'); + setAuthLoading(false); + return; + } + if (!/[A-Z]/.test(authPassword)) { + setAuthError('Password must contain at least one uppercase letter.'); + setAuthLoading(false); + return; + } + if (!/[0-9]/.test(authPassword)) { + setAuthError('Password must contain at least one number.'); + setAuthLoading(false); + return; + } + if (!/[^A-Za-z0-9\s]/.test(authPassword)) { + setAuthError('Password must contain at least one special character.'); + setAuthLoading(false); + return; + } + } + const fullPhone = authPhone ? `${authDialCode}${authPhone}` : undefined; const payload = authMode === 'login' ? { email: trimmedEmail, password: authPassword } @@ -378,7 +418,7 @@ export default function App() { setChangePasswordError('New password must contain at least one number.'); return; } - if (!/[^A-Za-z0-9]/.test(changeNewPassword)) { + if (!/[^A-Za-z0-9\s]/.test(changeNewPassword)) { setChangePasswordError('New password must contain at least one special character.'); return; } @@ -463,7 +503,7 @@ export default function App() { setAuthLoading(false); return; } - if (!/[^A-Za-z0-9]/.test(resetNewPassword)) { + if (!/[^A-Za-z0-9\s]/.test(resetNewPassword)) { setAuthError('New password must contain at least one special character.'); setAuthLoading(false); return; @@ -506,9 +546,18 @@ export default function App() { currency: currency }, { headers }); - setPricingCalc(res.data); - } catch (err) { + const calcData = res.data; + if (appliedCoupon && (!calcData.coupon_applied || calcData.coupon_applied === 'None')) { + calcData.coupon_error = calcData.coupon_error || 'Invalid or expired coupon code.'; + } + setPricingCalc(calcData); + } catch (err: any) { console.error('Pricing engine calculation error:', err); + const errorMsg = err.response?.data?.detail || 'Invalid or expired coupon code.'; + setPricingCalc((prev: any) => ({ + ...(prev || {}), + coupon_error: errorMsg + })); } finally { setLoadingPricing(false); } @@ -565,6 +614,7 @@ export default function App() { const removePromoCode = () => { setAppliedCoupon(null); setCouponCode(''); + setPricingCalc((prev: any) => (prev ? { ...prev, coupon_error: null } : null)); }; const isModuleUnlocked = (code: string) => { @@ -614,10 +664,17 @@ export default function App() { setCheckoutLoading(true); setVerificationResult(null); + const isCouponValid = Boolean( + pricingCalc && + pricingCalc.coupon_applied && + pricingCalc.coupon_applied !== 'None' && + !pricingCalc.coupon_error + ); + try { const orderRes = await axios.post(`${API_BASE}/api/checkout/create-order`, { cart_item_codes: cart.map(item => item.code), - coupon_code: appliedCoupon || undefined, + coupon_code: isCouponValid ? appliedCoupon : undefined, currency: currency }, { headers: { 'Authorization': `Bearer ${userToken}` } @@ -644,9 +701,16 @@ export default function App() { setCheckoutLoading(false); return; } + const cleanedPhone = cleanPhoneInput(inputPhone); + const phoneError = validatePhoneNumber(cleanedPhone, undefined, loggedInUser?.country || 'India'); + if (phoneError) { + alert(phoneError); + setCheckoutLoading(false); + return; + } try { const res = await axios.put(`${API_BASE}/api/auth/profile`, { - phone_number: inputPhone + phone_number: cleanedPhone }, { headers: { 'Authorization': `Bearer ${userToken}` } }); @@ -661,6 +725,9 @@ export default function App() { } } + let isPaymentCancelled = false; + let isPaymentCompleted = false; + const rzpOptions = { key: razorpayKeyId, amount: Math.round(grand_total * 100), @@ -674,7 +741,25 @@ export default function App() { email: loggedInUser?.email || '', contact: loggedInUser?.phone_number || loggedInUser?.phone || '' }, + modal: { + confirm_close: true, + escape: true, + backdropclose: false, + ondismiss: function () { + if (!isPaymentCompleted) { + isPaymentCancelled = true; + setCheckoutLoading(false); + console.log('Razorpay payment modal dismissed / cancelled by user.'); + } + } + }, handler: async function (response: any) { + if (isPaymentCancelled) { + console.warn('Payment was cancelled by the user. Verification ignored.'); + setCheckoutLoading(false); + return; + } + isPaymentCompleted = true; setCheckoutLoading(true); try { const verifyRes = await axios.post(`${API_BASE}/api/checkout/verify`, { @@ -698,9 +783,18 @@ export default function App() { message: verifyRes.data.message || 'Payment verified successfully and module entitlements unlocked!' }); + // If on mobile browser, automatically attempt to redirect to mobile app after successful payment if (/Android|iPhone|iPad|iPod/i.test(navigator.userAgent)) { setTimeout(() => { - window.location.href = 'acupedia://'; + if (/Android/i.test(navigator.userAgent)) { + // Use Android Intent format to avoid blocked navigation in Android Chrome + window.location.href = 'intent://#Intent;scheme=acupedia;package=com.anonymous.acupedia;end'; + setTimeout(() => { + window.location.href = 'acupedia://'; + }, 500); + } else { + window.location.href = 'acupedia://'; + } }, 1500); } @@ -723,6 +817,7 @@ export default function App() { const razorpayInstance = new (window as any).Razorpay(rzpOptions); razorpayInstance.on('payment.failed', function (resp: any) { + setCheckoutLoading(false); alert(`Payment failed! Reason: ${resp.error.description}`); }); razorpayInstance.open(); diff --git a/src/components/auth/AuthModal.tsx b/src/components/auth/AuthModal.tsx index 1eeccc8..7c8fe9b 100644 --- a/src/components/auth/AuthModal.tsx +++ b/src/components/auth/AuthModal.tsx @@ -3,7 +3,8 @@ import { XCircle, Sparkles, AlertCircle, CheckCircle, RefreshCw, Phone, Globe, Eye, EyeOff, LogIn, UserPlus } from 'lucide-react'; -import { COUNTRY_CODES } from '../../constants/countries'; +import { COUNTRY_CODES, getCountryRuleByDialCode, getCountryRuleByName } from '../../constants/countries'; +import { cleanPhoneInput } from '../../utils/validation'; interface AuthModalProps { isOpen: boolean; @@ -76,6 +77,7 @@ export const AuthModal: React.FC = ({ onResetPasswordSubmit, }) => { const [showPassword, setShowPassword] = useState(false); + const activeRule = getCountryRuleByDialCode(authDialCode); if (!isOpen) return null; @@ -290,7 +292,14 @@ export const AuthModal: React.FC = ({
setAuthPhone(e.target.value)} - placeholder="9876543210" + onChange={(e) => setAuthPhone(cleanPhoneInput(e.target.value, activeRule.maxLength))} + placeholder={activeRule.placeholder} + maxLength={activeRule.maxLength} className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-4 py-2.5 text-sm font-semibold text-white focus:outline-none focus:border-indigo-500 placeholder:text-slate-700" />
+

+ {activeRule.minLength === activeRule.maxLength + ? `${activeRule.label || activeRule.country}: Requires exactly ${activeRule.maxLength} digits` + : `${activeRule.label || activeRule.country}: ${activeRule.minLength} to ${activeRule.maxLength} digits`} +

)} @@ -320,14 +335,21 @@ export const AuthModal: React.FC = ({
▼ diff --git a/src/components/auth/ProfileDrawer.tsx b/src/components/auth/ProfileDrawer.tsx index 47f2754..39cbd10 100644 --- a/src/components/auth/ProfileDrawer.tsx +++ b/src/components/auth/ProfileDrawer.tsx @@ -4,6 +4,8 @@ import { Eye, EyeOff, RefreshCw, LogOut } from 'lucide-react'; import type { UserProfile, ModuleItem, Currency } from '../../types'; +import { COUNTRY_CODES, getCountryRuleByName } from '../../constants/countries'; +import { cleanPhoneInput } from '../../utils/validation'; interface ProfileDrawerProps { isOpen: boolean; @@ -70,6 +72,7 @@ export const ProfileDrawer: React.FC = ({ }) => { const [showOldPassword, setShowOldPassword] = useState(false); const [showNewPassword, setShowNewPassword] = useState(false); + const activeRule = getCountryRuleByName(profileCountry); if (!isOpen || !loggedInUser) return null; @@ -143,10 +146,16 @@ export const ProfileDrawer: React.FC = ({ setProfilePhone(e.target.value)} - placeholder="+919876543210" + onChange={(e) => setProfilePhone(cleanPhoneInput(e.target.value, activeRule.maxLength))} + placeholder={activeRule.placeholder} + maxLength={activeRule.maxLength} 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" /> +

+ {activeRule.minLength === activeRule.maxLength + ? `${activeRule.label || activeRule.country}: Requires exactly ${activeRule.maxLength} digits` + : `${activeRule.label || activeRule.country}: ${activeRule.minLength} to ${activeRule.maxLength} digits`} +

@@ -154,25 +163,18 @@ export const ProfileDrawer: React.FC = ({
@@ -285,7 +287,7 @@ export const ProfileDrawer: React.FC = ({ • 1 number - + • 1 special char
diff --git a/src/components/cart/CartDrawer.tsx b/src/components/cart/CartDrawer.tsx index 5c49f3f..ec6398a 100644 --- a/src/components/cart/CartDrawer.tsx +++ b/src/components/cart/CartDrawer.tsx @@ -141,9 +141,11 @@ export const CartDrawer: React.FC = ({ {appliedCoupon && - (pricingCalc?.coupon_error ? ( + (pricingCalc?.coupon_error || !pricingCalc?.coupon_applied || pricingCalc?.coupon_applied === 'None' ? (
- ⚠️ {pricingCalc.coupon_error} + + ⚠️ {pricingCalc?.coupon_error || 'Invalid or expired coupon code.'} +
- {pricingCalc.total_discounts > 0 && ( + {pricingCalc.bundle_discount_amount > 0 && (
- Total Discounts + Bundle Discount -{currency === 'INR' - ? `₹${pricingCalc.total_discounts}` + ? `₹${pricingCalc.bundle_discount_amount}` : currency === 'EUR' - ? `€${pricingCalc.total_discounts}` - : `$${pricingCalc.total_discounts}`} + ? `€${pricingCalc.bundle_discount_amount}` + : `$${pricingCalc.bundle_discount_amount}`}
)} + {pricingCalc.coupon_discount_amount > 0 && ( +
+ Coupon Discount ({appliedCoupon}) + + -{currency === 'INR' + ? `₹${pricingCalc.coupon_discount_amount}` + : currency === 'EUR' + ? `€${pricingCalc.coupon_discount_amount}` + : `$${pricingCalc.coupon_discount_amount}`} + +
+ )} + {pricingCalc.total_discounts > 0 && + !pricingCalc.bundle_discount_amount && + !pricingCalc.coupon_discount_amount && ( +
+ Total Discounts + + -{currency === 'INR' + ? `₹${pricingCalc.total_discounts}` + : currency === 'EUR' + ? `€${pricingCalc.total_discounts}` + : `$${pricingCalc.total_discounts}`} + +
+ )} {pricingCalc.convenience_fee > 0 && (
Gateway fee ({pricingCalc.convenience_fee_rate}%) diff --git a/src/components/checkout/PaymentSuccessModal.tsx b/src/components/checkout/PaymentSuccessModal.tsx index f665a26..234bbfe 100644 --- a/src/components/checkout/PaymentSuccessModal.tsx +++ b/src/components/checkout/PaymentSuccessModal.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useState } from 'react'; import { XCircle, CheckCircle, Check, Download, RefreshCw, Smartphone } from 'lucide-react'; import type { VerificationResult, UserProfile } from '../../types'; @@ -17,6 +17,42 @@ export const PaymentSuccessModal: React.FC = ({ onDownloadInvoice, downloadingInvoice, }) => { + const [desktopNotice, setDesktopNotice] = useState(false); + + // Handler to reliably launch the Acupedia Mobile App across platforms (Android, iOS, and Desktop) + const handleOpenApp = (e: React.MouseEvent) => { + e.preventDefault(); + const userAgent = navigator.userAgent || ''; + const isAndroid = /Android/i.test(userAgent); + const isIOS = /iPhone|iPad|iPod/i.test(userAgent); + + if (isAndroid) { + // Android Chrome requires an Intent URI format to launch apps by package and scheme reliably + const intentUrl = 'intent://#Intent;scheme=acupedia;package=com.anonymous.acupedia;end'; + window.location.href = intentUrl; + + // Fallback to custom URI schemes in case intent fails or Expo uses alternate scheme + setTimeout(() => { + window.location.href = 'acupedia://'; + }, 500); + setTimeout(() => { + window.location.href = 'myapp://'; + }, 1000); + } else if (isIOS) { + // iOS Safari and Chrome handle custom URI schemes directly + window.location.href = 'acupedia://'; + + // Fallback in case Expo uses default 'myapp://' scheme + setTimeout(() => { + window.location.href = 'myapp://'; + }, 500); + } else { + // On desktop browsers, try opening the registered custom scheme + window.location.href = 'acupedia://'; + // Show helpful desktop feedback informing the user how to access content on mobile + setDesktopNotice(true); + } + }; return (
@@ -175,14 +211,25 @@ export const PaymentSuccessModal: React.FC = ({ )} + {/* Open in App Button */} - Open Acupedia Mobile App + Open in App + {desktopNotice && ( +
+

+ 📱 Attempted to launch Acupedia App. If you are on desktop, please open the Acupedia App on your mobile device to view your unlocked content. +

+
+ )} +