Compare commits

..

No commits in common. "36dc2afc006572d2bf456bc2dba38cb3d7134668" and "49a5ccbf54592b240271b05e97513cc72223b039" have entirely different histories.

3 changed files with 25 additions and 126 deletions

View File

@ -178,14 +178,12 @@ 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) {
@ -289,27 +287,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,
}; };
}; };
@ -428,8 +417,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();
} }
}; };
@ -443,7 +431,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);
@ -459,10 +447,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');
}; };
@ -663,8 +647,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
@ -755,40 +739,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);
if (!live.isActive) continue; return {
nextCart.push({
...item, ...item,
priceInr: live.priceInr, priceInr: live.priceInr,
priceUsd: live.priceUsd, priceUsd: live.priceUsd,
priceEur: live.priceEur, 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]);
}, [publicPlans, plansLoaded, currency, cart]);
const calculatePricing = async () => { const calculatePricing = async () => {
setLoadingPricing(true); setLoadingPricing(true);

View File

@ -30,11 +30,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">
@ -62,7 +57,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">
@ -181,7 +176,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">
@ -300,7 +295,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">
@ -419,7 +414,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">
@ -539,7 +534,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>
@ -640,8 +635,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; 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 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;
return isCustom && isActive; return isCustom && isActive;
}); });

View File

@ -49,28 +49,6 @@ 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> = {}) {
@ -460,43 +438,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/');
});
}); });