fix(storefront): keep storefront visible on stale token and filter unavailable plans #123
74
src/App.tsx
74
src/App.tsx
|
|
@ -178,12 +178,14 @@ export default function App() {
|
||||||
|
|
||||||
// Dynamic Public Storefront Plans
|
// Dynamic Public Storefront Plans
|
||||||
const [publicPlans, setPublicPlans] = useState<PublicPlan[]>([]);
|
const [publicPlans, setPublicPlans] = useState<PublicPlan[]>([]);
|
||||||
|
const [plansLoaded, setPlansLoaded] = useState<boolean>(false);
|
||||||
|
|
||||||
const fetchPublicPlans = async () => {
|
const fetchPublicPlans = async () => {
|
||||||
try {
|
try {
|
||||||
const res = await axios.get(`${API_BASE}/api/plans`);
|
const res = await axios.get(`${API_BASE}/api/plans`);
|
||||||
if (Array.isArray(res.data)) {
|
if (Array.isArray(res.data)) {
|
||||||
setPublicPlans(res.data);
|
setPublicPlans(res.data);
|
||||||
|
setPlansLoaded(true);
|
||||||
fetchModuleCategories(res.data);
|
fetchModuleCategories(res.data);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|
@ -287,18 +289,27 @@ export default function App() {
|
||||||
const getModulePrice = (item: ModuleItem) => {
|
const getModulePrice = (item: ModuleItem) => {
|
||||||
const livePlan = getLivePlan(item.code);
|
const livePlan = getLivePlan(item.code);
|
||||||
if (livePlan) {
|
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 {
|
return {
|
||||||
priceInr: livePlan.price_inr ?? item.priceInr,
|
priceInr: livePlan.price_inr ?? item.priceInr,
|
||||||
priceUsd: livePlan.price_usd ?? item.priceUsd,
|
priceUsd: livePlan.price_usd ?? item.priceUsd,
|
||||||
priceEur: livePlan.price_eur ?? livePlan.price_usd ?? item.priceEur,
|
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 {
|
return {
|
||||||
priceInr: item.priceInr,
|
priceInr: item.priceInr,
|
||||||
priceUsd: item.priceUsd,
|
priceUsd: item.priceUsd,
|
||||||
priceEur: item.priceEur,
|
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);
|
setCurrency(countryRule.currency);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to fetch user profile:', 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('');
|
setChangeConfirmPassword('');
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleLogout = () => {
|
const resetAuthSession = () => {
|
||||||
localStorage.removeItem('access_token');
|
localStorage.removeItem('access_token');
|
||||||
setUserToken(null);
|
setUserToken(null);
|
||||||
setLoggedInUser(null);
|
setLoggedInUser(null);
|
||||||
|
|
@ -447,6 +459,10 @@ export default function App() {
|
||||||
setProfileError(null);
|
setProfileError(null);
|
||||||
setProfileSuccess(false);
|
setProfileSuccess(false);
|
||||||
setShowAuthModal(false);
|
setShowAuthModal(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleLogout = () => {
|
||||||
|
resetAuthSession();
|
||||||
switchTab('logged-out');
|
switchTab('logged-out');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -647,8 +663,8 @@ export default function App() {
|
||||||
|
|
||||||
const userEmail = loggedInUser?.email || authEmail;
|
const userEmail = loggedInUser?.email || authEmail;
|
||||||
|
|
||||||
// Invalidate active session so re-authentication is required
|
// Invalidate active session without navigating to the logged-out screen so user stays in place for re-auth
|
||||||
handleLogout();
|
resetAuthSession();
|
||||||
setShowProfileDrawer(false);
|
setShowProfileDrawer(false);
|
||||||
|
|
||||||
// Pre-fill email and set auth mode to login for seamless re-auth
|
// 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(() => {
|
useEffect(() => {
|
||||||
if (publicPlans.length > 0 && cart.length > 0) {
|
if (!plansLoaded || cart.length === 0) return;
|
||||||
setCart(prev =>
|
|
||||||
prev.map(item => {
|
const nextCart: ModuleItem[] = [];
|
||||||
const live = getModulePrice(item);
|
for (const item of cart) {
|
||||||
return {
|
const live = getModulePrice(item);
|
||||||
...item,
|
if (!live.isActive) continue;
|
||||||
priceInr: live.priceInr,
|
nextCart.push({
|
||||||
priceUsd: live.priceUsd,
|
...item,
|
||||||
priceEur: live.priceEur,
|
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 () => {
|
const calculatePricing = async () => {
|
||||||
setLoadingPricing(true);
|
setLoadingPricing(true);
|
||||||
|
|
|
||||||
|
|
@ -30,6 +30,11 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
showLockedByCategory,
|
showLockedByCategory,
|
||||||
setShowLockedByCategory,
|
setShowLockedByCategory,
|
||||||
}) => {
|
}) => {
|
||||||
|
const countLockedActive = (predicate: (category: string) => boolean) =>
|
||||||
|
curriculumModules.filter(
|
||||||
|
m => predicate(m.category) && !isModuleUnlocked(m.code) && getModulePrice(m).isActive
|
||||||
|
).length;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="xl:col-span-2 space-y-6">
|
<div className="xl:col-span-2 space-y-6">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
|
|
@ -57,7 +62,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Points: !prev.Points }))}
|
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"
|
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')})
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
||||||
|
|
@ -176,7 +181,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Pattern: !prev.Pattern }))}
|
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"
|
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')})
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
||||||
|
|
@ -295,7 +300,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Nutrition: !prev.Nutrition }))}
|
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"
|
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')})
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
||||||
|
|
@ -414,7 +419,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Therapeutics: !prev.Therapeutics }))}
|
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"
|
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')})
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
<span className="text-[10px] bg-slate-100/80 text-slate-500 border border-slate-200/70 font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md whitespace-nowrap shrink-0">
|
||||||
|
|
@ -534,7 +539,7 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
onClick={() => setShowLockedByCategory(prev => ({ ...prev, Lifetime: !prev.Lifetime }))}
|
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"
|
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')})
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<h3 className="text-xl font-black text-amber-900 tracking-tight">Lifetime Unlimited Access Pass</h3>
|
<h3 className="text-xl font-black text-amber-900 tracking-tight">Lifetime Unlimited Access Pass</h3>
|
||||||
|
|
@ -635,7 +640,8 @@ export const CatalogSection: React.FC<CatalogSectionProps> = ({
|
||||||
const customPlans = publicPlans.filter((p: any) => {
|
const customPlans = publicPlans.filter((p: any) => {
|
||||||
const code = p.base_code || p.code;
|
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 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;
|
return isCustom && isActive;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -49,6 +49,28 @@ const mockPlansResponse = [
|
||||||
is_active: true,
|
is_active: true,
|
||||||
module_slugs: ['acupuncture-points'],
|
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<string, any> = {}) {
|
function setupAxiosMocks(userOverrides: Record<string, any> = {}) {
|
||||||
|
|
@ -438,4 +460,43 @@ describe('App Integration', () => {
|
||||||
const closeDrawerBtn = document.querySelector('button svg.lucide-x-circle')?.closest('button') as HTMLButtonElement;
|
const closeDrawerBtn = document.querySelector('button svg.lucide-x-circle')?.closest('button') as HTMLButtonElement;
|
||||||
if (closeDrawerBtn) await user.click(closeDrawerBtn);
|
if (closeDrawerBtn) await user.click(closeDrawerBtn);
|
||||||
}, 15000);
|
}, 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(<App />);
|
||||||
|
|
||||||
|
// 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(<App />);
|
||||||
|
|
||||||
|
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/');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue