Merge branch 'main' into fix/change-password-confirm-visibility-and-error

This commit is contained in:
Urvish Prajapati 2026-11-12 11:11:07 +05:30
commit 1cd87a333d
8 changed files with 622 additions and 185 deletions

View File

@ -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<string | null>(null);
const [profileSuccess, setProfileSuccess] = useState<boolean>(false);
// Billing Contact Phone Modal State
const [showBillingPhoneModal, setShowBillingPhoneModal] = useState<boolean>(false);
const [pendingCheckoutAfterPhone, setPendingCheckoutAfterPhone] = useState<boolean>(false);
// Dynamic Public Storefront Plans
const [publicPlans, setPublicPlans] = useState<PublicPlan[]>([]);
@ -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<boolean> => {
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 (+<dialCode><digits>)
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 */}
<BillingPhoneModal
isOpen={showBillingPhoneModal}
onClose={() => {
setShowBillingPhoneModal(false);
setPendingCheckoutAfterPhone(false);
}}
currentPhone={loggedInUser?.phone_number}
currentCountry={loggedInUser?.country || profileCountry || 'India'}
onSavePhone={handleSaveBillingPhone}
/>
</div>
);
}

View File

@ -3,8 +3,8 @@ import {
XCircle, Sparkles, AlertCircle, CheckCircle, RefreshCw,
Phone, Globe, Eye, EyeOff, LogIn, UserPlus
} from 'lucide-react';
import { COUNTRY_CODES, getCountryRuleByDialCode, getCountryRuleByName } from '../../constants/countries';
import { cleanPhoneInput } from '../../utils/validation';
import { COUNTRY_CODES, getCountryRuleByName } from '../../constants/countries';
import { PhoneInput } from '../common/PhoneInput';
interface AuthModalProps {
isOpen: boolean;
@ -77,7 +77,6 @@ export const AuthModal: React.FC<AuthModalProps> = ({
onResetPasswordSubmit,
}) => {
const [showPassword, setShowPassword] = useState(false);
const activeRule = getCountryRuleByDialCode(authDialCode);
if (!isOpen) return null;
@ -288,47 +287,25 @@ export const AuthModal: React.FC<AuthModalProps> = ({
<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
</label>
<div className="flex gap-2 w-full">
<div className="relative shrink-0 w-[95px]">
<select
value={authDialCode}
onChange={(e) => {
const newCode = e.target.value;
if (newCode !== authDialCode) {
setAuthDialCode(newCode);
const rule = getCountryRuleByDialCode(newCode);
if (rule && rule.country !== 'Other') {
setAuthCountry(rule.country);
}
setAuthPhone('');
}
}}
className="w-full bg-slate-950 border border-slate-800 rounded-xl px-2.5 py-2.5 text-xs sm:text-sm font-semibold text-white focus:outline-none focus:border-indigo-500 appearance-none pr-6"
>
{COUNTRY_CODES.map((cc) => (
<option key={`${cc.country}-${cc.code}`} value={cc.code}>
{cc.label} ({cc.country})
</option>
))}
</select>
<div className="absolute right-2.5 top-1/2 -translate-y-1/2 pointer-events-none text-slate-500 text-[10px]">
▼
</div>
</div>
<input
type="tel"
value={authPhone}
onChange={(e) => 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"
/>
</div>
<p className="text-[10px] text-slate-500 font-medium">
{activeRule.minLength === activeRule.maxLength
? `${activeRule.label || activeRule.country}: Requires exactly ${activeRule.maxLength} digits`
: `${activeRule.label || activeRule.country}: ${activeRule.minLength} to ${activeRule.maxLength} digits`}
</p>
<PhoneInput
dialCode={authDialCode}
phone={authPhone}
country={authCountry}
clearOnDialCodeChange={true}
onDialCodeChange={(newCode, newCountry) => {
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}
/>
</div>
)}

View File

@ -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;
@ -77,7 +78,43 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
const [showOldPassword, setShowOldPassword] = useState(false);
const [showNewPassword, setShowNewPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = 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,35 +185,23 @@ export const ProfileDrawer: React.FC<ProfileDrawerProps> = ({
<div className="space-y-1.5">
<label className="text-xs font-bold text-slate-500">Phone Number</label>
<input
type="tel"
value={profilePhone}
onChange={(e) => 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"
<PhoneInput
dialCode={dialCode}
phone={localPhone}
country={profileCountry}
onDialCodeChange={handleDialCodeChange}
onPhoneChange={handleLocalPhoneChange}
theme="light"
disabled={profileSaving}
error={profileError && profileError.toLowerCase().includes('phone') ? profileError : null}
/>
<p className="text-[10px] text-slate-400 font-medium">
{activeRule.minLength === activeRule.maxLength
? `${activeRule.label || activeRule.country}: Requires exactly ${activeRule.maxLength} digits`
: `${activeRule.label || activeRule.country}: ${activeRule.minLength} to ${activeRule.maxLength} digits`}
</p>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-slate-500">Billing Country</label>
<select
value={profileCountry}
onChange={(e) => {
const newCountry = e.target.value;
if (newCountry !== profileCountry) {
const updatedPhone = updatePhoneDialCode(profilePhone, profileCountry, newCountry);
setProfilePhone(updatedPhone);
setProfileCountry(newCountry);
const rule = getCountryRuleByName(newCountry);
setCurrency(rule.currency);
}
}}
onChange={(e) => handleCountrySelectChange(e.target.value)}
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"
>
{COUNTRY_CODES.map((cc) => (

View File

@ -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<CartDrawerProps> = ({
</div>
) : (
<div className="space-y-3 max-h-[220px] overflow-y-auto pr-1">
{cart.map((item) => (
<div
key={item.code}
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">
<p className="text-xs font-bold text-slate-800 truncate">{item.name}</p>
<p className="text-[9px] text-slate-400 tracking-wider uppercase font-semibold">{item.category}</p>
{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
key={item.code}
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 items-center gap-1.5 flex-wrap min-w-0">
<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>
</div>
<div className="flex items-center gap-3">
<span className="text-xs font-bold text-indigo-600">
{(() => {
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}`;
})()}
</span>
<button
onClick={() => toggleCartItem(item)}
className="h-7 w-7 rounded-lg bg-rose-50 text-rose-500 hover:bg-rose-100 flex items-center justify-center transition-colors"
title="Remove item"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
</div>
<div className="flex items-center gap-3">
<span className="text-xs font-bold text-indigo-600">
{(() => {
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}`;
})()}
</span>
<button
onClick={() => toggleCartItem(item)}
className="h-7 w-7 rounded-lg bg-rose-50 text-rose-500 hover:bg-rose-100 flex items-center justify-center transition-colors"
title="Remove item"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
</div>
))}
);
})}
</div>
)}
@ -332,12 +352,14 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
<span className="text-[10px] uppercase font-black tracking-wider text-slate-400">
Billing Profile
</span>
<button
onClick={onUpdateBillingPhone}
className="text-[9px] text-indigo-600 hover:text-indigo-500 font-black uppercase tracking-wider underline focus:outline-none"
>
{loggedInUser.phone_number ? 'Edit Number' : 'Add Number'}
</button>
{(!loggedInUser.phone_number || !isValidPhoneNumber(loggedInUser.phone_number, undefined, loggedInUser.country || 'India')) && (
<button
onClick={onUpdateBillingPhone}
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'}
</button>
)}
</div>
<div className="space-y-1">
<div className="flex justify-between text-xs font-semibold text-slate-600">
@ -347,7 +369,11 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
<div className="flex justify-between text-xs font-semibold text-slate-600">
<span>Phone:</span>
<span className="text-slate-800 font-bold">
{loggedInUser.phone_number || (
{loggedInUser.phone_number && isValidPhoneNumber(loggedInUser.phone_number, undefined, loggedInUser.country || 'India') ? (
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>

View File

@ -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<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 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 (
<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}
onDialCodeChange={(newCode, newCountry) => {
setDialCode(newCode);
setCountry(newCountry);
setError(null);
}}
onPhoneChange={(newPhone) => {
setPhone(newPhone);
setError(null);
}}
error={error}
theme="light"
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 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>
);
};

View File

@ -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<PhoneInputProps> = ({
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<HTMLSelectElement>) => {
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<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) {
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">
{/* Country Code Dropdown */}
<div className="relative shrink-0 w-[105px]">
<select
value={dialCode}
onChange={handleDialCodeSelect}
disabled={disabled}
className={`w-full rounded-xl px-2.5 py-2.5 text-xs font-semibold appearance-none pr-6 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' : ''}`}
>
{COUNTRY_CODES.map((cc) => (
<option key={`${cc.country}-${cc.code}`} value={cc.code}>
{cc.label} ({cc.country})
</option>
))}
</select>
<div className="absolute right-2.5 top-1/2 -translate-y-1/2 pointer-events-none text-slate-400 text-[10px]">
▼
</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>
{/* Helper text or Error message */}
<div className="flex justify-between items-center text-[10px] px-0.5">
{error ? (
<p className="text-rose-500 font-bold">{error}</p>
) : (
<p className={isDark ? 'text-slate-400 font-medium' : 'text-slate-500 font-medium'}>
{activeRule.label || activeRule.country}:{' '}
{activeRule.minLength === activeRule.maxLength
? `Requires exactly ${activeRule.maxLength} digits`
: `${activeRule.minLength} to ${activeRule.maxLength} digits`}
</p>
)}
<span className={`font-mono font-semibold ${phone.length === activeRule.maxLength ? 'text-emerald-500' : isDark ? 'text-slate-500' : 'text-slate-400'}`}>
{phone.length}/{activeRule.maxLength}
</span>
</div>
</div>
);
};

View File

@ -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 (+<dialCode><digits>)
*/
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.

View File

@ -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,
}
})