From 0f9212563f51fcde1c279220cddcc00cfb996ea6 Mon Sep 17 00:00:00 2001 From: ShivaniKhaire Date: Wed, 2 Dec 2026 16:40:58 +0530 Subject: [PATCH] fix(storefront): keep storefront visible on stale token and filter unavailable plans --- src/App.tsx | 74 +++++++++++++++++------ src/components/catalog/CatalogSection.tsx | 18 ++++-- tests/unit/App.test.tsx | 61 +++++++++++++++++++ 3 files changed, 127 insertions(+), 26 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index c9f2129..2429cf3 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -178,12 +178,14 @@ export default function App() { // Dynamic Public Storefront Plans const [publicPlans, setPublicPlans] = useState([]); + const [plansLoaded, setPlansLoaded] = useState(false); const fetchPublicPlans = async () => { try { const res = await axios.get(`${API_BASE}/api/plans`); if (Array.isArray(res.data)) { setPublicPlans(res.data); + setPlansLoaded(true); fetchModuleCategories(res.data); } } catch (err) { @@ -287,18 +289,27 @@ export default function App() { const getModulePrice = (item: ModuleItem) => { const livePlan = getLivePlan(item.code); if (livePlan) { + const priceInr = livePlan.price_inr ?? 0; + const priceUsd = livePlan.price_usd ?? 0; + const priceEur = livePlan.price_eur ?? livePlan.price_usd ?? 0; + const activeCurrencyPrice = + currency === 'INR' ? priceInr : currency === 'EUR' ? priceEur : priceUsd; + const planIsActive = livePlan.is_active !== undefined ? livePlan.is_active : true; + return { priceInr: livePlan.price_inr ?? item.priceInr, priceUsd: livePlan.price_usd ?? item.priceUsd, priceEur: livePlan.price_eur ?? livePlan.price_usd ?? item.priceEur, - isActive: livePlan.is_active !== undefined ? livePlan.is_active : true, + // Require active flag and a positive price in the user's billing currency + isActive: planIsActive && activeCurrencyPrice > 0, }; } return { priceInr: item.priceInr, priceUsd: item.priceUsd, priceEur: item.priceEur, - isActive: true, + // Once /api/plans has loaded, catalog plans absent from it are inactive in the DB + isActive: !plansLoaded, }; }; @@ -417,7 +428,8 @@ export default function App() { setCurrency(countryRule.currency); } catch (err) { console.error('Failed to fetch user profile:', err); - handleLogout(); + // Clear invalid/stale token silently so expired storage does not hijack initial storefront load into /logged-out. + resetAuthSession(); } }; @@ -431,7 +443,7 @@ export default function App() { setChangeConfirmPassword(''); }; - const handleLogout = () => { + const resetAuthSession = () => { localStorage.removeItem('access_token'); setUserToken(null); setLoggedInUser(null); @@ -447,6 +459,10 @@ export default function App() { setProfileError(null); setProfileSuccess(false); setShowAuthModal(false); + }; + + const handleLogout = () => { + resetAuthSession(); switchTab('logged-out'); }; @@ -647,8 +663,8 @@ export default function App() { const userEmail = loggedInUser?.email || authEmail; - // Invalidate active session so re-authentication is required - handleLogout(); + // Invalidate active session without navigating to the logged-out screen so user stays in place for re-auth + resetAuthSession(); setShowProfileDrawer(false); // Pre-fill email and set auth mode to login for seamless re-auth @@ -739,22 +755,40 @@ export default function App() { } }; - // Keep cart items dynamic prices updated when publicPlans are loaded + // Keep cart synced with live plans: refresh prices and prune inactive/currency-unavailable plans useEffect(() => { - if (publicPlans.length > 0 && cart.length > 0) { - setCart(prev => - prev.map(item => { - const live = getModulePrice(item); - return { - ...item, - priceInr: live.priceInr, - priceUsd: live.priceUsd, - priceEur: live.priceEur, - }; - }) - ); + if (!plansLoaded || cart.length === 0) return; + + const nextCart: ModuleItem[] = []; + for (const item of cart) { + const live = getModulePrice(item); + if (!live.isActive) continue; + nextCart.push({ + ...item, + priceInr: live.priceInr, + priceUsd: live.priceUsd, + priceEur: live.priceEur, + }); } - }, [publicPlans]); + + const changed = + nextCart.length !== cart.length || + nextCart.some( + (n, idx) => + n.priceInr !== cart[idx].priceInr || + n.priceUsd !== cart[idx].priceUsd || + n.priceEur !== cart[idx].priceEur + ); + + if (changed) { + setCart(nextCart); + if (nextCart.length === 0) { + setAppliedCoupon(null); + setCouponCode(''); + setPricingCalc(null); + } + } + }, [publicPlans, plansLoaded, currency, cart]); const calculatePricing = async () => { setLoadingPricing(true); diff --git a/src/components/catalog/CatalogSection.tsx b/src/components/catalog/CatalogSection.tsx index 22414fd..410cab3 100644 --- a/src/components/catalog/CatalogSection.tsx +++ b/src/components/catalog/CatalogSection.tsx @@ -30,6 +30,11 @@ export const CatalogSection: React.FC = ({ showLockedByCategory, setShowLockedByCategory, }) => { + const countLockedActive = (predicate: (category: string) => boolean) => + curriculumModules.filter( + m => predicate(m.category) && !isModuleUnlocked(m.code) && getModulePrice(m).isActive + ).length; + return (
@@ -57,7 +62,7 @@ export const CatalogSection: React.FC = ({ onClick={() => setShowLockedByCategory(prev => ({ ...prev, Points: !prev.Points }))} className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0" > - {showLockedByCategory.Points ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Points' && !isModuleUnlocked(m.code)).length}) + {showLockedByCategory.Points ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Points')})
@@ -176,7 +181,7 @@ export const CatalogSection: React.FC = ({ onClick={() => setShowLockedByCategory(prev => ({ ...prev, Pattern: !prev.Pattern }))} className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0" > - {showLockedByCategory.Pattern ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => (m.category === 'Pattern' || m.category === 'Patterns') && !isModuleUnlocked(m.code)).length}) + {showLockedByCategory.Pattern ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Pattern' || c === 'Patterns')})
@@ -295,7 +300,7 @@ export const CatalogSection: React.FC = ({ onClick={() => setShowLockedByCategory(prev => ({ ...prev, Nutrition: !prev.Nutrition }))} className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0" > - {showLockedByCategory.Nutrition ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Nutrition' && !isModuleUnlocked(m.code)).length}) + {showLockedByCategory.Nutrition ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Nutrition')}) @@ -414,7 +419,7 @@ export const CatalogSection: React.FC = ({ onClick={() => setShowLockedByCategory(prev => ({ ...prev, Therapeutics: !prev.Therapeutics }))} className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-1.5 py-0.5 rounded transition-colors whitespace-nowrap shrink-0" > - {showLockedByCategory.Therapeutics ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Therapeutics' && !isModuleUnlocked(m.code)).length}) + {showLockedByCategory.Therapeutics ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Therapeutics')}) @@ -534,7 +539,7 @@ export const CatalogSection: React.FC = ({ onClick={() => setShowLockedByCategory(prev => ({ ...prev, Lifetime: !prev.Lifetime }))} className="text-[9px] bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold px-2 py-1 rounded transition-colors" > - {showLockedByCategory.Lifetime ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Lifetime' && !isModuleUnlocked(m.code)).length}) + {showLockedByCategory.Lifetime ? 'Hide Locked' : 'Show Locked'} ({countLockedActive(c => c === 'Lifetime')})

Lifetime Unlimited Access Pass

@@ -635,7 +640,8 @@ export const CatalogSection: React.FC = ({ const customPlans = publicPlans.filter((p: any) => { const code = p.base_code || p.code; const isCustom = !['POINTS_ACU', 'POINTS_SCALP', 'POINTS_EAR', 'POINTS_TUNG', 'POINTS_PACK', 'PATTERN_CORE', 'NUTRITION_CORE', 'THERAPEUTICS_GYNAE', 'THERAPEUTICS_EAR', 'THERAPEUTICS_CORE', 'LIFETIME_ALL'].includes(code); - const isActive = p.is_active !== false; + const activePrice = currency === 'INR' ? (p.price_inr ?? 0) : currency === 'EUR' ? (p.price_eur ?? p.price_usd ?? 0) : (p.price_usd ?? 0); + const isActive = p.is_active !== false && activePrice > 0; return isCustom && isActive; }); diff --git a/tests/unit/App.test.tsx b/tests/unit/App.test.tsx index 89ce227..c0cc830 100644 --- a/tests/unit/App.test.tsx +++ b/tests/unit/App.test.tsx @@ -49,6 +49,28 @@ const mockPlansResponse = [ is_active: true, module_slugs: ['acupuncture-points'], }, + { + code: 'POINTS_PACK', + name: 'Points Complete Pack (1 Yr)', + plan_type: 'bundle', + billing_period: 'yearly', + price_inr: 900, + price_usd: 15, + price_eur: 15, + is_active: true, + module_slugs: ['acupuncture-points', 'scalp-acupuncture', 'ear-acupuncture'], + }, + { + code: 'THERAPEUTICS_CORE', + name: 'Therapeutics Complete Bundle (1 Yr)', + plan_type: 'bundle', + billing_period: 'yearly', + price_inr: 0, + price_usd: 30, + price_eur: 30, + is_active: true, + module_slugs: ['auriculotherapy', 'gynecological-disorders'], + }, ]; function setupAxiosMocks(userOverrides: Record = {}) { @@ -438,4 +460,43 @@ describe('App Integration', () => { const closeDrawerBtn = document.querySelector('button svg.lucide-x-circle')?.closest('button') as HTMLButtonElement; if (closeDrawerBtn) await user.click(closeDrawerBtn); }, 15000); + + it('hides plans absent from /api/plans (POINTS_TUNG) or unpriced in billing currency (THERAPEUTICS_CORE) and prunes them from cart', async () => { + window.history.pushState({}, '', '/store/?planCode=POINTS_TUNG'); + + render(); + + // Wait for /api/plans to load and prune POINTS_TUNG from deep-linked cart & hide both unavailable plans + await waitFor(() => { + expect(screen.getByText('Acu (EOV+Cat+Ext+MR)')).toBeInTheDocument(); + expect(screen.getByText('0 Items')).toBeInTheDocument(); + }); + + expect(screen.queryByText('Master Tung')).not.toBeInTheDocument(); + expect(screen.queryByText('₹0')).not.toBeInTheDocument(); + }); + + it('keeps storefront visible and clears stale token silently when initial profile fetch fails', async () => { + localStorage.setItem('access_token', 'stale-expired-jwt'); + window.history.pushState({}, '', '/store/'); + mockedAxios.get.mockImplementation((url: string) => { + if (url.includes('/api/auth/profile')) { + return Promise.reject({ response: { status: 401, data: { detail: 'Token expired' } } }); + } + if (url.includes('/api/checkout/config')) return Promise.resolve({ data: { razorpay_key_id: 'rzp_test_123' } }); + if (url.includes('/api/plans')) return Promise.resolve({ data: mockPlansResponse }); + if (url.includes('/api/modules/categories')) return Promise.resolve({ data: [] }); + return Promise.resolve({ data: {} }); + }); + + render(); + + await waitFor(() => { + expect(screen.getByText('Unlock Professional TCM Modules')).toBeInTheDocument(); + expect(localStorage.getItem('access_token')).toBeNull(); + }); + + expect(screen.queryByText('Successfully Logged Out')).not.toBeInTheDocument(); + expect(window.location.pathname).toBe('/store/'); + }); }); -- 2.34.1