diff --git a/src/App.tsx b/src/App.tsx index 6007e6a..6b50def 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -6,7 +6,7 @@ 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, validatePassword } from './utils/validation'; +import { validatePhoneNumber, isValidPhoneNumber, validatePassword, parsePhoneNumber, formatE164Phone } from './utils/validation'; // Modular Subcomponents import { StoreHeader } from './components/layout/StoreHeader'; @@ -19,6 +19,7 @@ import { AuthModal } from './components/auth/AuthModal'; import { ProfileDrawer } from './components/auth/ProfileDrawer'; import { PaymentSuccessModal } from './components/checkout/PaymentSuccessModal'; import { PasswordUpdatedModal } from './components/auth/PasswordUpdatedModal'; +import { BillingPhoneModal } from './components/checkout/BillingPhoneModal'; import { openMobileApp, DEFAULT_RETURN_ROUTE } from './utils/navigation'; const getInitialTab = (): 'storefront' | 'subscriptions' => { @@ -136,6 +137,10 @@ export default function App() { const [profileError, setProfileError] = useState(null); const [profileSuccess, setProfileSuccess] = useState(false); + // Billing Contact Phone Modal State + const [showBillingPhoneModal, setShowBillingPhoneModal] = useState(false); + const [pendingCheckoutAfterPhone, setPendingCheckoutAfterPhone] = useState(false); + // Dynamic Public Storefront Plans const [publicPlans, setPublicPlans] = useState([]); @@ -365,20 +370,14 @@ export default function App() { let cleanedPhoneToSave: string | null = null; if (profilePhone && profilePhone.trim()) { - const phoneError = validatePhoneNumber(profilePhone, undefined, profileCountry); + const parsed = parsePhoneNumber(profilePhone, profileCountry); + const phoneError = validatePhoneNumber(parsed.localDigits, parsed.dialCode, profileCountry); if (phoneError) { setProfileError(phoneError); setProfileSaving(false); return; } - const rule = getCountryRuleByName(profileCountry); - const digitsOnly = profilePhone.trim().replace(/\D/g, ''); - const dialDigits = rule.code.replace(/\D/g, ''); - let localDigits = digitsOnly; - if (digitsOnly.startsWith(dialDigits) && digitsOnly.length > dialDigits.length) { - localDigits = digitsOnly.slice(dialDigits.length); - } - cleanedPhoneToSave = `${rule.code}${localDigits}`; + cleanedPhoneToSave = formatE164Phone(parsed.dialCode, parsed.localDigits); } try { @@ -401,6 +400,41 @@ export default function App() { } }; + const handleSaveBillingPhone = async (phoneE164: string, country: string): Promise => { + if (!userToken) return false; + try { + const res = await axios.put(`${API_BASE}/api/auth/profile`, { + phone_number: phoneE164, + country: country, + }, { + headers: { 'Authorization': `Bearer ${userToken}` } + }); + if (res.data.status === 'success') { + if (loggedInUser) { + loggedInUser.phone_number = phoneE164; + loggedInUser.country = country; + setLoggedInUser({ ...loggedInUser }); + } + setProfilePhone(phoneE164); + setProfileCountry(country); + const countryRule = getCountryRuleByName(country); + setCurrency(countryRule.currency); + setShowBillingPhoneModal(false); + if (pendingCheckoutAfterPhone) { + setPendingCheckoutAfterPhone(false); + setTimeout(() => { + handleCheckout(); + }, 200); + } + return true; + } + return false; + } catch (err: any) { + alert(err.response?.data?.detail || 'Failed to save billing phone number.'); + return false; + } + }; + const handleAuthSubmit = async (e: React.FormEvent) => { e.preventDefault(); setAuthLoading(true); @@ -843,39 +877,24 @@ export default function App() { return; } - if (!loggedInUser?.phone_number) { - const inputPhone = prompt("A billing phone number is required for Razorpay checkout. Please enter your contact number:"); - if (!inputPhone) { - setCheckoutLoading(false); - return; - } - const cleanedPhone = cleanPhoneInput(inputPhone, 16, true); - const phoneError = validatePhoneNumber(cleanedPhone, undefined, loggedInUser?.country || 'India'); - if (phoneError) { - alert(phoneError); - setCheckoutLoading(false); - return; - } - try { - const res = await axios.put(`${API_BASE}/api/auth/profile`, { - phone_number: cleanedPhone - }, { - headers: { 'Authorization': `Bearer ${userToken}` } - }); - if (res.data.status === 'success') { - loggedInUser.phone_number = cleanedPhone; - setLoggedInUser({ ...loggedInUser }); - } - } catch (err: any) { - alert("Failed to save phone number: " + (err.response?.data?.detail || err.message)); - setCheckoutLoading(false); - return; - } + // Ensure the user has a valid billing contact phone number before opening Razorpay + const hasValidPhone = loggedInUser?.phone_number && isValidPhoneNumber(loggedInUser.phone_number, undefined, loggedInUser.country || 'India'); + if (!hasValidPhone) { + setPendingCheckoutAfterPhone(true); + setShowBillingPhoneModal(true); + setCheckoutLoading(false); + return; } let isPaymentCancelled = false; let isPaymentCompleted = false; + // Sanitize contact for Razorpay: strictly digits with leading + (no spaces/dashes) + const rawContactDigits = (loggedInUser?.phone_number || '').replace(/\D/g, ''); + const sanitizedContact = (loggedInUser?.phone_number || '').startsWith('+') + ? `+${rawContactDigits}` + : rawContactDigits; + const rzpOptions = { key: razorpayKeyId, amount: Math.round(grand_total * 100), @@ -887,7 +906,7 @@ export default function App() { prefill: { name: loggedInUser?.display_name || '', email: loggedInUser?.email || '', - contact: loggedInUser?.phone_number || loggedInUser?.phone || '' + contact: sanitizedContact }, readonly: { contact: true, @@ -1050,34 +1069,7 @@ export default function App() { pricingCalc={pricingCalc} loadingPricing={loadingPricing} loggedInUser={loggedInUser} - onUpdateBillingPhone={async () => { - const inputPhone = prompt("Enter billing phone number:", loggedInUser?.phone_number || ''); - if (inputPhone === null || !loggedInUser) return; - const trimmed = inputPhone.trim(); - if (!trimmed) { - alert("A billing phone number is required."); - return; - } - const cleanedPhone = cleanPhoneInput(trimmed, 16, true); - const phoneError = validatePhoneNumber(cleanedPhone, undefined, loggedInUser.country || 'India'); - if (phoneError) { - alert(phoneError); - return; - } - try { - const res = await axios.put(`${API_BASE}/api/auth/profile`, { - phone_number: cleanedPhone - }, { - headers: { 'Authorization': `Bearer ${userToken}` } - }); - if (res.data.status === 'success') { - setLoggedInUser({ ...loggedInUser, phone_number: cleanedPhone }); - alert('Phone number updated successfully for billing!'); - } - } catch (err: any) { - alert(err.response?.data?.detail || 'Failed to update phone number.'); - } - }} + onUpdateBillingPhone={() => setShowBillingPhoneModal(true)} verificationResult={verificationResult} checkoutLoading={checkoutLoading} handleCheckout={handleCheckout} @@ -1203,6 +1195,18 @@ export default function App() { setShowAuthModal(true); }} /> + + {/* 📞 Billing Contact Phone Modal */} + { + setShowBillingPhoneModal(false); + setPendingCheckoutAfterPhone(false); + }} + currentPhone={loggedInUser?.phone_number} + currentCountry={loggedInUser?.country || profileCountry || 'India'} + onSavePhone={handleSaveBillingPhone} + /> ); } diff --git a/src/components/auth/AuthModal.tsx b/src/components/auth/AuthModal.tsx index ec92ce0..e501cc3 100644 --- a/src/components/auth/AuthModal.tsx +++ b/src/components/auth/AuthModal.tsx @@ -3,8 +3,9 @@ import { XCircle, Sparkles, AlertCircle, CheckCircle, RefreshCw, Phone, Globe, Eye, EyeOff, LogIn, UserPlus } from 'lucide-react'; -import { COUNTRY_CODES, getCountryRuleByDialCode, getCountryRuleByName } from '../../constants/countries'; +import { COUNTRY_CODES, getCountryRuleByName } from '../../constants/countries'; import { cleanPhoneInput } from '../../utils/validation'; +import { PhoneInput } from '../common/PhoneInput'; interface AuthModalProps { isOpen: boolean; @@ -77,7 +78,6 @@ export const AuthModal: React.FC = ({ onResetPasswordSubmit, }) => { const [showPassword, setShowPassword] = useState(false); - const activeRule = getCountryRuleByDialCode(authDialCode); if (!isOpen) return null; @@ -288,45 +288,23 @@ export const AuthModal: React.FC = ({ -
-
- -
- â–¼ -
-
- setAuthPhone(cleanPhoneInput(e.target.value, activeRule.maxLength, false))} - placeholder={activeRule.placeholder} - maxLength={activeRule.maxLength} - className="min-w-0 flex-1 bg-slate-950 border border-slate-800 rounded-xl px-3 sm:px-4 py-2.5 text-xs sm:text-sm font-semibold text-white focus:outline-none focus:border-indigo-500 placeholder:text-slate-700" - /> -
-

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

+ { + setAuthDialCode(newCode); + setAuthCountry(newCountry); + }} + onPhoneChange={(newPhone) => { + setAuthPhone(newPhone); + if (authError && authError.toLowerCase().includes('phone')) { + setAuthError(null); + } + }} + theme="dark" + error={authError && authError.toLowerCase().includes('phone') ? authError : null} + /> )} diff --git a/src/components/auth/ProfileDrawer.tsx b/src/components/auth/ProfileDrawer.tsx index 3937cfb..ce10da9 100644 --- a/src/components/auth/ProfileDrawer.tsx +++ b/src/components/auth/ProfileDrawer.tsx @@ -1,11 +1,12 @@ -import React, { useState } from 'react'; +import React, { useState, useEffect } from 'react'; import { XCircle, Users, ShieldCheck, CheckCircle, AlertCircle, Eye, EyeOff, RefreshCw, LogOut, Download } from 'lucide-react'; import type { UserProfile, ModuleItem, Currency } from '../../types'; import { COUNTRY_CODES, getCountryRuleByName } from '../../constants/countries'; -import { cleanPhoneInput, updatePhoneDialCode, SPECIAL_CHAR_REGEX } from '../../utils/validation'; +import { cleanPhoneInput, parsePhoneNumber, formatE164Phone, SPECIAL_CHAR_REGEX } from '../../utils/validation'; +import { PhoneInput } from '../common/PhoneInput'; interface ProfileDrawerProps { isOpen: boolean; @@ -36,6 +37,7 @@ interface ProfileDrawerProps { onChangePassword: (e: React.FormEvent) => Promise; onLogout: () => void; onBrowseStorefront: () => void; + onViewSubscriptions?: () => void; curriculumModules: ModuleItem[]; onDownloadInvoice?: (paymentId: string, directUrl?: string) => void; } @@ -69,12 +71,49 @@ export const ProfileDrawer: React.FC = ({ onChangePassword, onLogout, onBrowseStorefront, + onViewSubscriptions, curriculumModules, onDownloadInvoice, }) => { const [showOldPassword, setShowOldPassword] = useState(false); const [showNewPassword, setShowNewPassword] = useState(false); - const activeRule = getCountryRuleByName(profileCountry); + + const parsed = parsePhoneNumber(profilePhone, profileCountry); + const [dialCode, setDialCode] = useState(parsed.dialCode); + const [localPhone, setLocalPhone] = useState(parsed.localDigits); + + useEffect(() => { + if (isOpen) { + const p = parsePhoneNumber(profilePhone, profileCountry); + setDialCode(p.dialCode); + setLocalPhone(p.localDigits); + } + }, [profilePhone, profileCountry, isOpen]); + + const handleLocalPhoneChange = (newLocal: string) => { + setLocalPhone(newLocal); + setProfilePhone(formatE164Phone(dialCode, newLocal)); + }; + + const handleDialCodeChange = (newCode: string, newCountry: string) => { + setDialCode(newCode); + setProfileCountry(newCountry); + const rule = getCountryRuleByName(newCountry); + setCurrency(rule.currency); + const clamped = cleanPhoneInput(localPhone, rule.maxLength, false); + setLocalPhone(clamped); + setProfilePhone(formatE164Phone(newCode, clamped)); + }; + + const handleCountrySelectChange = (newCountry: string) => { + setProfileCountry(newCountry); + const rule = getCountryRuleByName(newCountry); + setDialCode(rule.code); + setCurrency(rule.currency); + const clamped = cleanPhoneInput(localPhone, rule.maxLength, false); + setLocalPhone(clamped); + setProfilePhone(formatE164Phone(rule.code, clamped)); + }; if (!isOpen || !loggedInUser) return null; @@ -145,35 +184,22 @@ export const ProfileDrawer: React.FC = ({
- setProfilePhone(cleanPhoneInput(e.target.value, activeRule.maxLength + activeRule.code.length + 1, true))} - placeholder={activeRule.placeholder ? `e.g. ${activeRule.code} ${activeRule.placeholder}` : `e.g. ${activeRule.code} 9876543210`} - maxLength={activeRule.maxLength + activeRule.code.length + 2} - 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`} -

+ {COUNTRY_CODES.map((cc) => ( + + ))} + +
+ â–¼ +
+
+ + {/* Numeric-Only Local Phone Input */} + + + + {/* Helper text or Error message */} +
+ {error ? ( +

{error}

+ ) : ( +

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

+ )} + + {phone.length}/{activeRule.maxLength} + +
+ + ); +}; + diff --git a/src/utils/validation.ts b/src/utils/validation.ts index bcfa008..8c97ac3 100644 --- a/src/utils/validation.ts +++ b/src/utils/validation.ts @@ -104,6 +104,54 @@ export const isValidPhoneNumber = ( 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 } => { + const defaultRule = getCountryRuleByName(fallbackCountry) || getCountryRuleByDialCode('+91')!; + if (!fullPhone || !fullPhone.trim()) { + return { country: defaultRule.country, dialCode: defaultRule.code, localDigits: '' }; + } + const trimmed = fullPhone.trim(); + + // Try matching dial code prefixes from longest to shortest + const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length); + 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), + }; + } + + // If no '+' prefix, check if digits start with fallback country dial digits + const dialDigits = defaultRule.code.replace(/\D/g, ''); + const rawDigits = trimmed.replace(/\D/g, ''); + let local = rawDigits; + if (rawDigits.startsWith(dialDigits) && rawDigits.length > dialDigits.length) { + local = rawDigits.slice(dialDigits.length); + } + return { + country: defaultRule.country, + dialCode: defaultRule.code, + localDigits: local.slice(0, defaultRule.maxLength), + }; +}; + +/** + * Formats full phone number cleanly as E.164 without spaces (+) + */ +export const formatE164Phone = (dialCode: string, localDigits: string): string => { + const digits = localDigits.replace(/\D/g, ''); + const code = dialCode.startsWith('+') ? dialCode : `+${dialCode}`; + return digits ? `${code}${digits}` : ''; +}; + /** * Updates the dial code prefix of an existing phone number when country changes. * Automatically clamps remaining digits to the new country's maxLength.