Compare commits

..

No commits in common. "50550e17039de62f1f06829f565d423b34b6c93d" and "2013659a20e180010fcd46e2bb6015638b62a5cd" have entirely different histories.

3 changed files with 27 additions and 117 deletions

View File

@ -181,14 +181,12 @@ export default function App() {
const [publicPlans, setPublicPlans] = useState<PublicPlan[]>([]); const [publicPlans, setPublicPlans] = useState<PublicPlan[]>([]);
const [apiModules, setApiModules] = useState<any[]>([]); const [apiModules, setApiModules] = useState<any[]>([]);
const [pendingUrlPlanCode, setPendingUrlPlanCode] = useState<string | null>(null); const [pendingUrlPlanCode, setPendingUrlPlanCode] = useState<string | null>(null);
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);
} }
} catch (err) { } catch (err) {
console.error('Failed to load public plans:', err); console.error('Failed to load public plans:', err);
@ -239,27 +237,18 @@ 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,
// Require active flag and a positive price in the user's billing currency isActive: livePlan.is_active !== undefined ? livePlan.is_active : true,
isActive: planIsActive && activeCurrencyPrice > 0,
}; };
} }
return { return {
priceInr: item.priceInr, priceInr: item.priceInr,
priceUsd: item.priceUsd, priceUsd: item.priceUsd,
priceEur: item.priceEur, priceEur: item.priceEur,
// Once /api/plans has loaded, catalog plans absent from it are inactive in the DB isActive: true,
isActive: !plansLoaded,
}; };
}; };
@ -381,8 +370,7 @@ 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);
// Clear invalid/stale token silently so expired storage does not hijack initial storefront load into /logged-out. handleLogout();
resetAuthSession();
} }
}; };
@ -396,7 +384,7 @@ export default function App() {
setChangeConfirmPassword(''); setChangeConfirmPassword('');
}; };
const resetAuthSession = () => { const handleLogout = () => {
localStorage.removeItem('access_token'); localStorage.removeItem('access_token');
setUserToken(null); setUserToken(null);
setLoggedInUser(null); setLoggedInUser(null);
@ -412,10 +400,6 @@ 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');
}; };
@ -616,8 +600,8 @@ export default function App() {
const userEmail = loggedInUser?.email || authEmail; const userEmail = loggedInUser?.email || authEmail;
// Invalidate active session without navigating to the logged-out screen so user stays in place for re-auth // Invalidate active session so re-authentication is required
resetAuthSession(); handleLogout();
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
@ -708,40 +692,22 @@ export default function App() {
} }
}; };
// Keep cart synced with live plans: refresh prices and prune inactive/currency-unavailable plans // Keep cart items dynamic prices updated when publicPlans are loaded
useEffect(() => { useEffect(() => {
if (!plansLoaded || cart.length === 0) return; if (publicPlans.length > 0 && cart.length > 0) {
setCart(prev =>
const nextCart: ModuleItem[] = []; prev.map(item => {
for (const item of cart) { const live = getModulePrice(item);
const live = getModulePrice(item); return {
if (!live.isActive) continue; ...item,
nextCart.push({ priceInr: live.priceInr,
...item, priceUsd: live.priceUsd,
priceInr: live.priceInr, priceEur: live.priceEur,
priceUsd: live.priceUsd, };
priceEur: live.priceEur, })
});
}
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]); }, [publicPlans]);
const calculatePricing = async () => { const calculatePricing = async () => {
setLoadingPricing(true); setLoadingPricing(true);

View File

@ -31,11 +31,6 @@ 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">
@ -63,7 +58,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'} ({countLockedActive(c => c === 'Points')}) {showLockedByCategory.Points ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Points' && !isModuleUnlocked(m.code)).length})
</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">
@ -184,7 +179,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'} ({countLockedActive(c => c === 'Pattern' || c === 'Patterns')}) {showLockedByCategory.Pattern ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => (m.category === 'Pattern' || m.category === 'Patterns') && !isModuleUnlocked(m.code)).length})
</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">
@ -305,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'} ({countLockedActive(c => c === 'Nutrition')}) {showLockedByCategory.Nutrition ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Nutrition' && !isModuleUnlocked(m.code)).length})
</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">
@ -426,7 +421,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'} ({countLockedActive(c => c === 'Therapeutics')}) {showLockedByCategory.Therapeutics ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Therapeutics' && !isModuleUnlocked(m.code)).length})
</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">
@ -548,7 +543,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'} ({countLockedActive(c => c === 'Lifetime')}) {showLockedByCategory.Lifetime ? 'Hide Locked' : 'Show Locked'} ({curriculumModules.filter(m => m.category === 'Lifetime' && !isModuleUnlocked(m.code)).length})
</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>
@ -648,8 +643,7 @@ 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 || '').toUpperCase(); const code = (p.base_code || p.code || '').toUpperCase();
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;
const isActive = p.is_active !== false && activePrice > 0;
if (!isActive || code === 'LIFETIME_ALL' || CORE_PACK_CODES.has(code)) return false; if (!isActive || code === 'LIFETIME_ALL' || CORE_PACK_CODES.has(code)) return false;
if (p.plan_type === 'bundle') return true; if (p.plan_type === 'bundle') return true;
const resolvedCat = const resolvedCat =

View File

@ -51,25 +51,14 @@ const mockPlansResponse = [
}, },
{ {
code: 'POINTS_PACK', code: 'POINTS_PACK',
name: 'Points Complete Pack (1 Yr)', name: 'Points: Complete Pack',
plan_type: 'bundle', plan_type: 'bundle',
billing_period: 'yearly', billing_period: 'yearly',
price_inr: 900, price_inr: 900,
price_usd: 15, price_usd: 15,
price_eur: 15, price_eur: 15,
is_active: true, is_active: true,
module_slugs: ['acupuncture-points', 'scalp-acupuncture', 'ear-acupuncture'], module_slugs: ['acupuncture-points'],
},
{
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'],
}, },
]; ];
@ -460,43 +449,4 @@ 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/');
});
}); });