diff --git a/src/App.tsx b/src/App.tsx index 99d035b..56e53f9 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -181,12 +181,14 @@ export default function App() { const [publicPlans, setPublicPlans] = useState([]); const [apiModules, setApiModules] = useState([]); const [pendingUrlPlanCode, setPendingUrlPlanCode] = useState(null); + 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); } } catch (err) { console.error('Failed to load public plans:', err); @@ -237,18 +239,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, }; }; @@ -370,7 +381,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(); } }; @@ -384,7 +396,7 @@ export default function App() { setChangeConfirmPassword(''); }; - const handleLogout = () => { + const resetAuthSession = () => { localStorage.removeItem('access_token'); setUserToken(null); setLoggedInUser(null); @@ -400,6 +412,10 @@ export default function App() { setProfileError(null); setProfileSuccess(false); setShowAuthModal(false); + }; + + const handleLogout = () => { + resetAuthSession(); switchTab('logged-out'); }; @@ -600,8 +616,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 @@ -692,22 +708,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 d3c0761..b2f7a9c 100644 --- a/src/components/catalog/CatalogSection.tsx +++ b/src/components/catalog/CatalogSection.tsx @@ -31,6 +31,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 (
@@ -58,7 +63,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')})
@@ -179,7 +184,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')})
@@ -300,7 +305,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')}) @@ -421,7 +426,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')}) @@ -543,7 +548,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

@@ -643,7 +648,8 @@ export const CatalogSection: React.FC = ({ {(() => { const customPlans = publicPlans.filter((p: any) => { const code = (p.base_code || p.code || '').toUpperCase(); - 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; if (!isActive || code === 'LIFETIME_ALL' || CORE_PACK_CODES.has(code)) return false; if (p.plan_type === 'bundle') return true; const resolvedCat = diff --git a/tests/unit/App.test.tsx b/tests/unit/App.test.tsx index a31b677..c0cc830 100644 --- a/tests/unit/App.test.tsx +++ b/tests/unit/App.test.tsx @@ -51,14 +51,25 @@ const mockPlansResponse = [ }, { code: 'POINTS_PACK', - name: 'Points: Complete 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'], + 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'], }, ]; @@ -449,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/'); + }); });