diff --git a/src/App.tsx b/src/App.tsx index 9dfc89b..abbac9e 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, validateEmail } from './utils/validation'; +import { validatePhoneNumber, isValidPhoneNumber, validatePassword, parsePhoneNumber, formatE164Phone, validateEmail } 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' => { @@ -36,8 +37,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); } @@ -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([]); @@ -235,6 +240,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 +280,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 @@ -365,20 +378,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 +408,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); @@ -831,39 +873,22 @@ 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 E.164 (+) + const parsedContact = parsePhoneNumber(loggedInUser?.phone_number, loggedInUser?.country || 'India'); + const sanitizedContact = formatE164Phone(parsedContact.dialCode, parsedContact.localDigits); + const rzpOptions = { key: razorpayKeyId, amount: Math.round(grand_total * 100), @@ -871,11 +896,10 @@ 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 || '', - contact: loggedInUser?.phone_number || loggedInUser?.phone || '' + contact: sanitizedContact }, readonly: { contact: true, @@ -1038,34 +1062,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} @@ -1195,6 +1192,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 3b394d4..38b0528 100644 --- a/src/components/auth/AuthModal.tsx +++ b/src/components/auth/AuthModal.tsx @@ -3,9 +3,9 @@ import { XCircle, Sparkles, AlertCircle, CheckCircle, RefreshCw, Phone, Globe, Eye, EyeOff, LogIn, UserPlus } from 'lucide-react'; -import { SORTED_COUNTRY_CODES, getCountryRuleByDialCode, getCountryRuleByName } from '../../constants/countries'; -import { cleanPhoneInput } from '../../utils/validation'; +import { getCountryRuleByName } from '../../constants/countries'; import { CountrySelect } from '../common/CountrySelect'; +import { PhoneInput } from '../common/PhoneInput'; interface AuthModalProps { isOpen: boolean; @@ -78,7 +78,6 @@ export const AuthModal: React.FC = ({ onResetPasswordSubmit, }) => { const [showPassword, setShowPassword] = useState(false); - const activeRule = getCountryRuleByDialCode(authDialCode); if (!isOpen) return null; @@ -289,47 +288,25 @@ 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); + setAuthPhone(''); + }} + 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 d333435..9ee04e9 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 { 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'; import { CountrySelect } from '../common/CountrySelect'; interface ProfileDrawerProps { @@ -77,7 +78,43 @@ export const ProfileDrawer: React.FC = ({ }) => { 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(newLocal ? 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; @@ -148,34 +185,23 @@ 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`} -

{ - if (newCountry !== profileCountry) { - const updatedPhone = updatePhoneDialCode(profilePhone, profileCountry, newCountry); - setProfilePhone(updatedPhone); - setProfileCountry(newCountry); - const rule = getCountryRuleByName(newCountry); - setCurrency(rule.currency); - } - }} + onChange={handleCountrySelectChange} theme="light" size="sm" showDialCode={true} diff --git a/src/components/cart/CartDrawer.tsx b/src/components/cart/CartDrawer.tsx index 9fc9ae2..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[]; @@ -113,36 +114,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}`; - })()} - - -
-
- ))} + ); + })}
)} @@ -332,12 +352,14 @@ export const CartDrawer: React.FC = ({ Billing Profile - + {(!loggedInUser.phone_number || !isValidPhoneNumber(loggedInUser.phone_number, undefined, loggedInUser.country || 'India')) && ( + + )}
@@ -347,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/checkout/BillingPhoneModal.tsx b/src/components/checkout/BillingPhoneModal.tsx new file mode 100644 index 0000000..db4637a --- /dev/null +++ b/src/components/checkout/BillingPhoneModal.tsx @@ -0,0 +1,139 @@ +import React, { useState, useEffect } from 'react'; +import { X, Phone, ShieldCheck, RefreshCw } from 'lucide-react'; +import { PhoneInput } from '../common/PhoneInput'; +import { parsePhoneNumber, validatePhoneNumber, formatE164Phone } from '../../utils/validation'; + +interface BillingPhoneModalProps { + isOpen: boolean; + onClose: () => void; + currentPhone?: string | null; + currentCountry?: string; + onSavePhone: (phoneE164: string, country: string) => Promise; +} + +export const BillingPhoneModal: React.FC = ({ + 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(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 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); + const success = await onSavePhone(e164, country); + setSaving(false); + if (success) { + onClose(); + } + }; + + return ( +
+
e.stopPropagation()} + > +
+
+
+ +
+
+

Billing Contact Number

+

Required for Razorpay invoice & payment updates

+
+
+ +
+ +
+
+ + { + setDialCode(newCode); + setCountry(newCountry); + setError(null); + }} + onPhoneChange={(newPhone) => { + setPhone(newPhone); + setError(null); + }} + error={error} + theme="light" + disabled={saving} + /> +
+ +
+ + This contact number will appear on your compliance tax invoice and payment receipts. +
+ +
+ + +
+
+
+
+ ); +}; + diff --git a/src/components/common/PhoneInput.tsx b/src/components/common/PhoneInput.tsx new file mode 100644 index 0000000..311cddb --- /dev/null +++ b/src/components/common/PhoneInput.tsx @@ -0,0 +1,173 @@ +import React from 'react'; +import { COUNTRY_CODES, getCountryRuleByDialCode, getCountryRuleByName } 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 = ({ + dialCode, + phone, + country, + onDialCodeChange, + onPhoneChange, + error, + disabled = false, + theme = 'dark', + id = 'phone-input', + clearOnDialCodeChange = false, +}) => { + let activeRule = getCountryRuleByDialCode(dialCode); + if (!activeRule && country) { + activeRule = getCountryRuleByName(country); + } + if (!activeRule) { + activeRule = getCountryRuleByDialCode('+91')!; + } + + const handleDialCodeSelect = (e: React.ChangeEvent) => { + const newCode = e.target.value; + const rule = getCountryRuleByDialCode(newCode); + const newCountry = rule ? rule.country : (country || 'India'); + if (onDialCodeChange) { + onDialCodeChange(newCode, newCountry); + } + if (clearOnDialCodeChange) { + onPhoneChange(''); + } else if (rule) { + onPhoneChange(cleanPhoneInput(phone, rule.maxLength, false)); + } + }; + + const handlePhoneInputChange = (e: React.ChangeEvent) => { + 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); + }; + + const handleKeyDown = (e: React.KeyboardEvent) => { + // 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 ( +
+
+ {/* Country Code Dropdown */} +
+ +
+ â–¼ +
+
+ + {/* 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 9f9bb44..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); } @@ -83,6 +90,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; } @@ -104,6 +119,58 @@ 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 and exceed national length + const dialDigits = defaultRule.code.replace(/\D/g, ''); + const rawDigits = trimmed.replace(/\D/g, ''); + let local = rawDigits; + if ( + dialDigits && + rawDigits.startsWith(dialDigits) && + rawDigits.length > defaultRule.maxLength + ) { + 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. 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, } }) +