From a0c5a2d6fccec67643ee69af239e49753c2fa498 Mon Sep 17 00:00:00 2001 From: Urvish Date: Thu, 5 Nov 2026 12:42:33 +0530 Subject: [PATCH 1/6] fix(store): standardize phone number input, validation, and billing modal --- src/App.tsx | 138 ++++++++--------- src/components/auth/AuthModal.tsx | 60 +++----- src/components/auth/ProfileDrawer.tsx | 93 ++++++++---- src/components/checkout/BillingPhoneModal.tsx | 139 ++++++++++++++++++ src/components/common/PhoneInput.tsx | 136 +++++++++++++++++ src/utils/validation.ts | 48 ++++++ 6 files changed, 478 insertions(+), 136 deletions(-) create mode 100644 src/components/checkout/BillingPhoneModal.tsx create mode 100644 src/components/common/PhoneInput.tsx 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. From 79cb96ae5e549a6f25fcb131cafb3bf0624f9b07 Mon Sep 17 00:00:00 2001 From: Urvish Date: Thu, 5 Nov 2026 12:54:58 +0530 Subject: [PATCH 2/6] fix(store): enforce Indian mobile prefix and ensure exact razorpay contact prefill --- src/App.tsx | 9 +++------ src/utils/validation.ts | 8 ++++++++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index 6b50def..f8b6c95 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -889,11 +889,9 @@ export default function App() { 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; + // Sanitize contact for Razorpay: strictly E.164 (+) + const parsedContact = parsePhoneNumber(loggedInUser?.phone_number, loggedInUser?.country || 'India'); + const sanitizedContact = formatE164Phone(parsedContact.dialCode, parsedContact.localDigits); const rzpOptions = { key: razorpayKeyId, @@ -902,7 +900,6 @@ export default function App() { name: 'Acupedia', description: cart.map(c => c.name).join(', '), order_id: razorpay_order_id, - customer_id: loggedInUser?.external_ref || undefined, prefill: { name: loggedInUser?.display_name || '', email: loggedInUser?.email || '', diff --git a/src/utils/validation.ts b/src/utils/validation.ts index 8c97ac3..65af684 100644 --- a/src/utils/validation.ts +++ b/src/utils/validation.ts @@ -83,6 +83,14 @@ export const validatePhoneNumber = ( return `${rule.country} phone number cannot exceed ${rule.maxLength} digits.`; } } + + // Specific country telecom prefix rules + if (dialDigits === '91' || rule.country === 'India') { + if (!/^[6-9]/.test(localDigits)) { + return 'India mobile number must begin with 6, 7, 8, or 9.'; + } + } + return null; } From b865f57e4d3c7b496628c86f4d161b2cd7320134 Mon Sep 17 00:00:00 2001 From: Urvish Date: Thu, 5 Nov 2026 13:06:11 +0530 Subject: [PATCH 3/6] fix(store): lock billing profile phone number to registration and disallow editing --- src/components/cart/CartDrawer.tsx | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/components/cart/CartDrawer.tsx b/src/components/cart/CartDrawer.tsx index 9fc9ae2..7bf8cc7 100644 --- a/src/components/cart/CartDrawer.tsx +++ b/src/components/cart/CartDrawer.tsx @@ -332,12 +332,14 @@ export const CartDrawer: React.FC = ({ Billing Profile - + {!loggedInUser.phone_number && ( + + )}
From 874221fdd8bb5e3f412715ec1f095a37f3afa006 Mon Sep 17 00:00:00 2001 From: ShivaniKhaire Date: Sat, 7 Nov 2026 15:46:46 +0530 Subject: [PATCH 4/6] fix(store): ensure trailing slash on storefront routing and redirect /store to prevent blank page on reload (#83) --- src/App.tsx | 16 ++++++++++++---- vite.config.ts | 25 +++++++++++++++++++++++-- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index 9dfc89b..b3c36d0 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -36,8 +36,8 @@ export default function App() { setActiveTab(tab); if (typeof window !== 'undefined') { const isStorePrefix = window.location.pathname.startsWith('/store'); - const basePath = isStorePrefix ? '/store' : ''; - const newPath = tab === 'storefront' ? (basePath || '/') : (basePath + '/' + tab); + const basePath = isStorePrefix ? '/store/' : '/'; + const newPath = tab === 'storefront' ? basePath : `${basePath}${tab}`; if (window.location.pathname !== newPath) { window.history.pushState({ tab }, '', newPath); } @@ -235,6 +235,12 @@ export default function App() { // Load configuration & user profile on startup useEffect(() => { + // Normalize URL if opened at /store without trailing slash + if (typeof window !== 'undefined' && window.location.pathname === '/store') { + const normalizedPath = '/store/' + (window.location.search || '') + (window.location.hash || ''); + window.history.replaceState(window.history.state, document.title, normalizedPath); + } + const params = new URLSearchParams(window.location.search); const urlToken = params.get('token'); const urlPlanCode = params.get('planCode'); @@ -269,8 +275,10 @@ export default function App() { } if (urlToken || urlPlanCode) { - const newUrl = window.location.pathname; - window.history.replaceState({}, document.title, newUrl); + const isStorePrefix = window.location.pathname.startsWith('/store'); + const basePath = isStorePrefix ? '/store/' : '/'; + const cleanPath = activeTab === 'subscriptions' ? `${basePath}subscriptions` : basePath; + window.history.replaceState({}, document.title, cleanPath); } // Fetch public Razorpay Config diff --git a/vite.config.ts b/vite.config.ts index 0d9f089..198efe6 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,11 +1,32 @@ import { defineConfig } from 'vite' 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/ export default defineConfig({ - base: process.env.VITE_BASE_PATH || '/store/', - plugins: [react()], + base: rawBase, + plugins: [ + 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: { port: 3000, } }) + From 7e2f3ed92731d22fac2a2513af0e4acdbf99d389 Mon Sep 17 00:00:00 2001 From: Urvish Date: Wed, 11 Nov 2026 12:04:25 +0530 Subject: [PATCH 5/6] fix(cart): standardize complete package badge and UI layout in cart drawer --- src/components/cart/CartDrawer.tsx | 77 +++++++++++++++++++----------- 1 file changed, 48 insertions(+), 29 deletions(-) diff --git a/src/components/cart/CartDrawer.tsx b/src/components/cart/CartDrawer.tsx index 9fc9ae2..4f4b86a 100644 --- a/src/components/cart/CartDrawer.tsx +++ b/src/components/cart/CartDrawer.tsx @@ -113,36 +113,55 @@ export const CartDrawer: React.FC = ({
) : (
- {cart.map((item) => ( -
-
-

{item.name}

-

{item.category}

+ {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 ( +
+
+
+

{item.name}

+ {isCompletePackage && ( + + Complete Pack + + )} +
+

{item.category}

+
+
+ + {(() => { + const calculatedItem = activePricing?.cart_items?.find((ci: any) => ci.code === item.code); + const price = calculatedItem + ? calculatedItem.price + : (currency === 'INR' ? item.priceInr : currency === 'EUR' ? item.priceEur : item.priceUsd); + const symbol = currency === 'INR' ? '₹' : currency === 'EUR' ? '€' : '$'; + return `${symbol}${price}`; + })()} + + +
-
- - {(() => { - const calculatedItem = activePricing?.cart_items?.find((ci: any) => ci.code === item.code); - const price = calculatedItem - ? calculatedItem.price - : (currency === 'INR' ? item.priceInr : currency === 'EUR' ? item.priceEur : item.priceUsd); - const symbol = currency === 'INR' ? '₹' : currency === 'EUR' ? '€' : '$'; - return `${symbol}${price}`; - })()} - - -
-
- ))} + ); + })}
)} From 2513c854117f0641569d2b8acea4a4aa25f186aa Mon Sep 17 00:00:00 2001 From: Urvish Date: Wed, 11 Nov 2026 13:21:45 +0530 Subject: [PATCH 6/6] fix(auth): enforce strict national phone length and prevent country code combining --- src/components/auth/ProfileDrawer.tsx | 3 ++- src/components/cart/CartDrawer.tsx | 11 +++++--- src/components/common/PhoneInput.tsx | 38 +++++++++++++++++++++++++-- src/utils/validation.ts | 27 +++++++++++++------ 4 files changed, 65 insertions(+), 14 deletions(-) diff --git a/src/components/auth/ProfileDrawer.tsx b/src/components/auth/ProfileDrawer.tsx index ce10da9..b243f48 100644 --- a/src/components/auth/ProfileDrawer.tsx +++ b/src/components/auth/ProfileDrawer.tsx @@ -92,7 +92,7 @@ export const ProfileDrawer: React.FC = ({ const handleLocalPhoneChange = (newLocal: string) => { setLocalPhone(newLocal); - setProfilePhone(formatE164Phone(dialCode, newLocal)); + setProfilePhone(newLocal ? formatE164Phone(dialCode, newLocal) : ''); }; const handleDialCodeChange = (newCode: string, newCountry: string) => { @@ -192,6 +192,7 @@ export const ProfileDrawer: React.FC = ({ onPhoneChange={handleLocalPhoneChange} theme="light" disabled={profileSaving} + error={profileError && profileError.toLowerCase().includes('phone') ? profileError : null} />
diff --git a/src/components/cart/CartDrawer.tsx b/src/components/cart/CartDrawer.tsx index 845920f..e936b21 100644 --- a/src/components/cart/CartDrawer.tsx +++ b/src/components/cart/CartDrawer.tsx @@ -1,6 +1,7 @@ import React from 'react'; import { ShoppingCart, ShoppingBag, Trash2, RefreshCw, CreditCard, XCircle } from 'lucide-react'; import type { ModuleItem, Currency, UserProfile, VerificationResult } from '../../types'; +import { isValidPhoneNumber } from '../../utils/validation'; interface CartDrawerProps { cart: ModuleItem[]; @@ -351,12 +352,12 @@ export const CartDrawer: React.FC = ({ Billing Profile - {!loggedInUser.phone_number && ( + {(!loggedInUser.phone_number || !isValidPhoneNumber(loggedInUser.phone_number, undefined, loggedInUser.country || 'India')) && ( )}
@@ -368,7 +369,11 @@ export const CartDrawer: React.FC = ({
Phone: - {loggedInUser.phone_number || ( + {loggedInUser.phone_number && isValidPhoneNumber(loggedInUser.phone_number, undefined, loggedInUser.country || 'India') ? ( + loggedInUser.phone_number + ) : loggedInUser.phone_number ? ( + Incomplete ({loggedInUser.phone_number}) + ) : ( Required for checkout )} diff --git a/src/components/common/PhoneInput.tsx b/src/components/common/PhoneInput.tsx index 9cb7dd3..311cddb 100644 --- a/src/components/common/PhoneInput.tsx +++ b/src/components/common/PhoneInput.tsx @@ -50,8 +50,38 @@ export const PhoneInput: React.FC = ({ }; const handlePhoneInputChange = (e: React.ChangeEvent) => { - // Strictly numeric, capped at maxLength - const cleaned = cleanPhoneInput(e.target.value, activeRule.maxLength, false); + 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) { + 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); }; @@ -63,6 +93,10 @@ export const PhoneInput: React.FC = ({ ) { 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(); diff --git a/src/utils/validation.ts b/src/utils/validation.ts index cf26d48..0e904b0 100644 --- a/src/utils/validation.ts +++ b/src/utils/validation.ts @@ -51,6 +51,11 @@ export const validatePhoneNumber = ( if ((!rule || rule.country === 'Other') && country) { rule = getCountryRuleByName(country); } + // If still not found and input starts with '+', match from COUNTRY_CODES + if (!rule && trimmed.startsWith('+')) { + const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length); + rule = sorted.find((c) => trimmed.startsWith(c.code)); + } // Default to India if no specific rule resolved and dial code is +91 or country is India if (!rule || rule.country === 'Other') { if (dialCode === '+91' || (country && country.toLowerCase() === 'india')) { @@ -62,12 +67,14 @@ export const validatePhoneNumber = ( const dialDigits = rule.code.replace(/\D/g, ''); let localDigits = allDigits; - // If formatted with country code (e.g. +919876543210 or 919876543210 where total length > rule.maxLength), strip country prefix - if ( - (trimmed.startsWith('+') || allDigits.length > rule.maxLength) && - allDigits.startsWith(dialDigits) && - allDigits.length === dialDigits.length + rule.minLength - ) { + if (trimmed.startsWith('+')) { + // Input includes country code prefix (e.g. +919876543210 or +9198765432) + // Must strip the dial code to extract the actual local number + if (allDigits.startsWith(dialDigits)) { + localDigits = allDigits.slice(dialDigits.length); + } + } else if (allDigits.length > rule.maxLength && allDigits.startsWith(dialDigits)) { + // Input was formatted with dial digits without '+' and exceeds local maxLength (e.g. 919876543210) localDigits = allDigits.slice(dialDigits.length); } @@ -137,11 +144,15 @@ export const parsePhoneNumber = ( }; } - // If no '+' prefix, check if digits start with fallback country dial digits + // If no '+' prefix, check if digits start with fallback country dial digits and exceed national length const dialDigits = defaultRule.code.replace(/\D/g, ''); const rawDigits = trimmed.replace(/\D/g, ''); let local = rawDigits; - if (rawDigits.startsWith(dialDigits) && rawDigits.length > dialDigits.length) { + if ( + dialDigits && + rawDigits.startsWith(dialDigits) && + rawDigits.length > defaultRule.maxLength + ) { local = rawDigits.slice(dialDigits.length); } return {