diff --git a/src/App.tsx b/src/App.tsx index 2429cf3..56e53f9 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -2,6 +2,7 @@ import { useState, useEffect, useMemo } from 'react'; import axios from 'axios'; import { CURRICULUM_MODULES } from './constants/modules'; +import { buildDynamicCatalog } from './utils/catalog'; import { getCountryRuleByName } from './constants/countries'; import type { ModuleItem, Currency, UserProfile, VerificationResult, PublicPlan } from './types'; import { API_BASE } from './services/api'; @@ -176,8 +177,10 @@ export default function App() { const [showBillingPhoneModal, setShowBillingPhoneModal] = useState(false); const [pendingCheckoutAfterPhone, setPendingCheckoutAfterPhone] = useState(false); - // Dynamic Public Storefront Plans + // Dynamic Public Storefront Plans & Modules const [publicPlans, setPublicPlans] = useState([]); + const [apiModules, setApiModules] = useState([]); + const [pendingUrlPlanCode, setPendingUrlPlanCode] = useState(null); const [plansLoaded, setPlansLoaded] = useState(false); const fetchPublicPlans = async () => { @@ -186,101 +189,48 @@ export default function App() { if (Array.isArray(res.data)) { setPublicPlans(res.data); setPlansLoaded(true); - fetchModuleCategories(res.data); } } catch (err) { console.error('Failed to load public plans:', err); } }; - // Dynamic Curriculum Modules with Live Categories + // Dynamic Curriculum Modules derived from /api/plans + /api/contents/modules const [curriculumModules, setCurriculumModules] = useState(CURRICULUM_MODULES); - const fetchModuleCategories = async (plansList?: PublicPlan[]) => { + const fetchModuleCategories = async () => { try { const res = await axios.get(`${API_BASE}/api/contents/modules`); - const apiModules: any[] = res.data?.modules || []; - const currentPlans = plansList && plansList.length > 0 ? plansList : publicPlans; - if (apiModules.length > 0) { - const normalizeCategory = (cat?: string): string | null => { - if (!cat) return null; - const c = cat.toLowerCase().trim(); - if (c === 'point' || c === 'points') return 'Points'; - if (c === 'pattern' || c === 'patterns' || c === 'five-elements') return 'Pattern'; - if (c === 'nutrition') return 'Nutrition'; - if (c === 'therapeutics' || c === 'therapeutic') return 'Therapeutics'; - if (c === 'lifetime') return 'Lifetime'; - return cat.charAt(0).toUpperCase() + cat.slice(1); - }; - - setCurriculumModules((prev) => - prev.map((item) => { - // 1. If item maps directly to a plan with single module slug, match by that slug - const matchedPlan = currentPlans.find((p) => p.code === item.code || p.base_code === item.code); - let matched: any = null; - if (matchedPlan) { - const slugs: string[] = matchedPlan.module_slugs || (matchedPlan.modules || []).map((m: any) => m.slug).filter(Boolean); - if (slugs.length === 1) { - const targetSlug = slugs[0].toLowerCase(); - matched = apiModules.find((m) => (m.slug || '').toLowerCase() === targetSlug); - } - } - - // 2. Direct code match - if (!matched) { - const iCode = (item.code || '').toLowerCase(); - matched = apiModules.find((m) => (m.code || '').toLowerCase() === iCode); - } - - // 3. Normalized semantic match without collisions - if (!matched) { - const iName = item.name.toLowerCase(); - const cleanI = iName.replace('points:', '').replace('therapeutics:', '').split('(')[0].trim(); - - matched = apiModules.find((m) => { - const mSlug = (m.slug || '').toLowerCase(); - const mName = (m.name || '').toLowerCase(); - const cleanM = mName.replace('points:', '').replace('therapeutics:', '').split('(')[0].trim(); - - if (cleanI.includes('scalp') && (cleanM.includes('scalp') || mSlug.includes('scalp'))) return true; - - // Disambiguate Ear Reflexology / Auriculotherapy vs Ear Acupuncture - if (cleanI.includes('reflexology') || item.code === 'THERAPEUTICS_EAR') { - return mSlug.includes('auriculo') || cleanM.includes('reflexology') || mSlug.includes('reflexology'); - } - if (cleanI.includes('ear') || item.code === 'POINTS_EAR') { - return mSlug.includes('ear-acupuncture') || (cleanM.includes('ear') && !mSlug.includes('auriculo') && !cleanM.includes('reflexology')); - } - - if (cleanI.includes('acu') && cleanM.includes('acupuncture') && !cleanI.includes('scalp') && !cleanI.includes('ear')) return true; - if (cleanI.includes('gyneco') && mSlug.includes('gyneco')) return true; - if (cleanI.includes('eight') && mSlug.includes('eight')) return true; - if (cleanI.includes('zang') && mSlug.includes('tcm-pattern')) return true; - if (cleanI.includes('qi') && mSlug.includes('qi')) return true; - if (cleanI.includes('pathogenic') && mSlug.includes('pathogenic')) return true; - if (cleanI.includes('six') && mSlug.includes('six')) return true; - if (cleanI.includes('four') && mSlug.includes('four')) return true; - if (cleanI.includes('three') && mSlug.includes('three')) return true; - if (cleanI.includes('five') && mSlug.includes('five')) return true; - if (cleanI.includes('food') && mSlug.includes('nutrition')) return true; - return false; - }); - } - - const rawCat = matched?.category || matched?.metadata?.category || matched?.metadata?.kind; - const updatedCat = normalizeCategory(rawCat); - if (updatedCat) { - return { ...item, category: updatedCat }; - } - return item; - }) - ); + const mods: any[] = Array.isArray(res.data) ? res.data : (res.data?.modules || []); + if (mods.length > 0) { + setApiModules(mods); } } catch (err) { console.error('Failed to load module categories:', err); } }; + useEffect(() => { + if (publicPlans.length > 0) { + setCurriculumModules(buildDynamicCatalog(publicPlans, apiModules)); + } + }, [publicPlans, apiModules]); + + useEffect(() => { + if (!pendingUrlPlanCode) return; + const targetModule = curriculumModules.find( + (m) => m.code.toUpperCase() === pendingUrlPlanCode, + ); + if (targetModule) { + setCart([targetModule]); + setShowLockedByCategory((prev) => ({ + ...prev, + [targetModule.category]: true, + })); + setPendingUrlPlanCode(null); + } + }, [pendingUrlPlanCode, curriculumModules]); + const getLivePlan = (code: string) => { return publicPlans.find(p => p.code === code || p.base_code === code); @@ -360,6 +310,8 @@ export default function App() { ...prev, [targetModule.category]: true })); + } else { + setPendingUrlPlanCode(normalizedPlanCode); } } @@ -417,6 +369,7 @@ export default function App() { const mergedUser = { ...profileRes.data, active_subscriptions: accessRes.data.active_subscriptions || [], + unlocked_module_codes: accessRes.data.unlocked_module_codes || [], unlocked_module_slugs: accessRes.data.unlocked_module_slugs || [], }; @@ -920,25 +873,60 @@ export default function App() { if (!loggedInUser?.active_subscriptions) return false; const hasLifetime = loggedInUser.active_subscriptions.some((sub: any) => - sub.plan_code === 'LIFETIME_ALL' || sub.plan_code === 'LIFETIME_ALL_USD' + sub.plan_code === 'LIFETIME_ALL' || + sub.plan_code === 'LIFETIME_ALL_USD' || + sub.plan_code === 'LIFETIME_ALL_EUR' ); if (hasLifetime) return true; + const hasDirectSub = loggedInUser.active_subscriptions.some( + (sub: any) => + sub.plan_code === code || + sub.plan_code === `${code}_USD` || + sub.plan_code === `${code}_EUR` + ); + if (hasDirectSub) return true; + + // Dynamic unlock check via /api/access/me unlocked_module_codes / unlocked_module_slugs + const unlockedCodes = new Set( + (loggedInUser.unlocked_module_codes || []).map((c: string) => c.toLowerCase()), + ); + const unlockedSlugs = new Set( + (loggedInUser.unlocked_module_slugs || []).map((s: string) => s.toLowerCase()), + ); + if (unlockedCodes.size > 0 || unlockedSlugs.size > 0) { + const matchedPlan = getLivePlan(code); + const planModules = matchedPlan?.modules || []; + if (planModules.length > 0) { + const allModulesUnlocked = planModules.every( + (m: any) => + (m.code && unlockedCodes.has(String(m.code).toLowerCase())) || + (m.slug && unlockedSlugs.has(String(m.slug).toLowerCase())), + ); + if (allModulesUnlocked) return true; + } + const planSlugs = matchedPlan?.module_slugs || []; + if (planSlugs.length > 0 && planSlugs.every((s: string) => unlockedSlugs.has(s.toLowerCase()))) { + return true; + } + } + + // Legacy fallback when publicPlans lacks module lists if (code === 'POINTS_ACU' || code === 'POINTS_SCALP' || code === 'POINTS_EAR' || code === 'POINTS_TUNG') { const hasPointsPack = loggedInUser.active_subscriptions.some((sub: any) => - sub.plan_code === 'POINTS_PACK' || sub.plan_code === 'POINTS_PACK_USD' + sub.plan_code === 'POINTS_PACK' || sub.plan_code === 'POINTS_PACK_USD' || sub.plan_code === 'POINTS_PACK_EUR' ); if (hasPointsPack) return true; } if (code === 'THERAPEUTICS_GYNAE' || code === 'THERAPEUTICS_EAR') { const hasTherapeuticsPack = loggedInUser.active_subscriptions.some((sub: any) => - sub.plan_code === 'THERAPEUTICS_CORE' || sub.plan_code === 'THERAPEUTICS_CORE_USD' + sub.plan_code === 'THERAPEUTICS_CORE' || sub.plan_code === 'THERAPEUTICS_CORE_USD' || sub.plan_code === 'THERAPEUTICS_CORE_EUR' ); if (hasTherapeuticsPack) return true; } - return loggedInUser.active_subscriptions.some((sub: any) => sub.plan_code === code || sub.plan_code === `${code}_USD`); + return false; }; // Automatically remove already unlocked modules from the cart diff --git a/src/components/catalog/CatalogSection.tsx b/src/components/catalog/CatalogSection.tsx index 410cab3..b2f7a9c 100644 --- a/src/components/catalog/CatalogSection.tsx +++ b/src/components/catalog/CatalogSection.tsx @@ -1,6 +1,7 @@ import React from 'react'; import { BookOpen, Check } from 'lucide-react'; import type { ModuleItem, PublicPlan, Currency } from '../../types'; +import { CORE_PACK_CODES, MAIN_CATEGORIES, resolvePlanCategory } from '../../utils/catalog'; interface CatalogSectionProps { curriculumModules: ModuleItem[]; @@ -77,7 +78,9 @@ export const CatalogSection: React.FC = ({
{(() => { - const items = curriculumModules.filter(m => m.category === 'Points'); + const items = curriculumModules + .filter(m => m.category === 'Points') + .sort((a, b) => (a.sortOrder ?? 500) - (b.sortOrder ?? 500)); const visible = items.filter(sub => { const isUnlocked = isModuleUnlocked(sub.code); const live = getModulePrice(sub); @@ -196,7 +199,9 @@ export const CatalogSection: React.FC = ({
{(() => { - const items = curriculumModules.filter(m => m.category === 'Pattern' || m.category === 'Patterns'); + const items = curriculumModules + .filter(m => m.category === 'Pattern' || m.category === 'Patterns') + .sort((a, b) => (a.sortOrder ?? 500) - (b.sortOrder ?? 500)); const visible = items.filter(sub => { const isUnlocked = isModuleUnlocked(sub.code); const live = getModulePrice(sub); @@ -315,7 +320,9 @@ export const CatalogSection: React.FC = ({
{(() => { - const items = curriculumModules.filter(m => m.category === 'Nutrition'); + const items = curriculumModules + .filter(m => m.category === 'Nutrition') + .sort((a, b) => (a.sortOrder ?? 500) - (b.sortOrder ?? 500)); const visible = items.filter(sub => { const isUnlocked = isModuleUnlocked(sub.code); const live = getModulePrice(sub); @@ -434,7 +441,9 @@ export const CatalogSection: React.FC = ({
{(() => { - const items = curriculumModules.filter(m => m.category === 'Therapeutics'); + const items = curriculumModules + .filter(m => m.category === 'Therapeutics') + .sort((a, b) => (a.sortOrder ?? 500) - (b.sortOrder ?? 500)); const visible = items.filter(sub => { const isUnlocked = isModuleUnlocked(sub.code); const live = getModulePrice(sub); @@ -638,11 +647,15 @@ export const CatalogSection: React.FC = ({ {/* CARD 6: Custom Packages & Bundles (Dynamic Admin Plans) */} {(() => { 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 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 && activePrice > 0; - return isCustom && isActive; + if (!isActive || code === 'LIFETIME_ALL' || CORE_PACK_CODES.has(code)) return false; + if (p.plan_type === 'bundle') return true; + const resolvedCat = + curriculumModules.find((m) => m.code.toUpperCase() === code)?.category || + resolvePlanCategory(p); + return !MAIN_CATEGORIES.has(resolvedCat) && resolvedCat !== 'Lifetime'; }); if (customPlans.length === 0) return null; diff --git a/src/types/index.ts b/src/types/index.ts index bf73f81..f24c49c 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -10,6 +10,8 @@ export interface ModuleItem { desc: string; color: string; isRenewal?: boolean; + sortOrder?: number; + planType?: string; } export interface UserSubscription { @@ -37,6 +39,7 @@ export interface UserProfile { roles?: string[]; external_ref?: string; active_subscriptions: UserSubscription[]; + unlocked_module_codes?: string[]; unlocked_module_slugs?: string[]; created_at?: string; } @@ -76,15 +79,27 @@ export interface PublicPlan { code: string; base_code?: string; name: string; + plan_type?: string; + billing_period?: string; price_inr?: number; price_usd?: number; price_eur?: number; is_active?: boolean; + pricing_status?: string; + color?: string; badge_text?: string; heading?: string; subtitle?: string; description?: string; - modules?: Array<{ id?: string; name: string; slug?: string }>; + modules?: Array<{ + id?: string; + code?: string; + name: string; + slug?: string; + description?: string; + category?: string; + sort_order?: number; + }>; module_slugs?: string[]; } diff --git a/src/utils/catalog.ts b/src/utils/catalog.ts new file mode 100644 index 0000000..ee4e4d5 --- /dev/null +++ b/src/utils/catalog.ts @@ -0,0 +1,223 @@ +import { CURRICULUM_MODULES } from '../constants/modules'; +import type { ModuleItem, PublicPlan } from '../types'; + +export const CORE_PACK_CODES = new Set([ + 'POINTS_PACK', + 'PATTERN_CORE', + 'NUTRITION_CORE', + 'THERAPEUTICS_CORE', +]); + +export const MAIN_CATEGORIES = new Set([ + 'Points', + 'Pattern', + 'Nutrition', + 'Therapeutics', +]); + +const MULTI_ITEM_CORE_PACKS: Record = { + PATTERN_CORE: { + category: 'Pattern', + packTitle: 'Pattern: Complete Pack', + defaultColor: 'from-rose-600 to-orange-600', + }, + NUTRITION_CORE: { + category: 'Nutrition', + packTitle: 'Nutrition: Complete Pack', + defaultColor: 'from-teal-500 to-green-600', + }, +}; + +export function normalizeCategory(cat?: string | null): string | null { + if (!cat) return null; + const c = cat.toLowerCase().trim(); + if (c === 'point' || c === 'points') return 'Points'; + if (c === 'pattern' || c === 'patterns' || c === 'five-elements') return 'Pattern'; + if (c === 'nutrition') return 'Nutrition'; + if (c === 'therapeutics' || c === 'therapeutic') return 'Therapeutics'; + if (c === 'lifetime') return 'Lifetime'; + return cat.charAt(0).toUpperCase() + cat.slice(1); +} + +function findMatchingApiModule( + plan: PublicPlan, + apiModules: any[], +): any | undefined { + if (!apiModules.length) return undefined; + const firstMod = plan.modules?.[0]; + const slugs = plan.module_slugs || (plan.modules || []).map((m) => m.slug).filter(Boolean) as string[]; + const targetSlug = (firstMod?.slug || (slugs.length === 1 ? slugs[0] : undefined))?.toLowerCase(); + const targetCode = firstMod?.code?.toLowerCase(); + + if (targetCode) { + const byCode = apiModules.find((m) => (m.code || '').toLowerCase() === targetCode); + if (byCode) return byCode; + } + if (targetSlug) { + const bySlug = apiModules.find((m) => (m.slug || '').toLowerCase() === targetSlug); + if (bySlug) return bySlug; + } + const pCode = (plan.base_code || plan.code || '').toLowerCase(); + return apiModules.find( + (m) => (m.plan_code || '').toLowerCase() === pCode || (m.code || '').toLowerCase() === pCode, + ); +} + +export function resolvePlanCategory(plan: PublicPlan, apiModules: any[] = []): string { + const code = (plan.base_code || plan.code || '').toUpperCase(); + if (code === 'LIFETIME_ALL' || plan.plan_type === 'lifetime') return 'Lifetime'; + if (code === 'POINTS_PACK') return 'Points'; + if (code === 'PATTERN_CORE') return 'Pattern'; + if (code === 'NUTRITION_CORE') return 'Nutrition'; + if (code === 'THERAPEUTICS_CORE') return 'Therapeutics'; + + const firstMod = plan.modules?.[0]; + const apiMatch = findMatchingApiModule(plan, apiModules); + const rawCat = + firstMod?.category || + apiMatch?.category || + apiMatch?.metadata?.category || + apiMatch?.metadata?.kind; + const normalized = normalizeCategory(rawCat); + if (normalized) return normalized; + + const fallback = CURRICULUM_MODULES.find((m) => m.code.toUpperCase() === code); + if (fallback) return fallback.category; + + return plan.plan_type === 'bundle' ? 'Bundle' : 'Custom'; +} + +export function buildDynamicCatalog( + publicPlans: PublicPlan[], + apiModules: any[] = [], +): ModuleItem[] { + if (!publicPlans || publicPlans.length === 0) { + return CURRICULUM_MODULES; + } + + const items: ModuleItem[] = []; + + for (const plan of publicPlans) { + const code = (plan.base_code || plan.code || '').toUpperCase(); + if (!code) continue; + + const fallbackEntries = CURRICULUM_MODULES.filter((m) => m.code.toUpperCase() === code); + const primaryFallback = fallbackEntries[fallbackEntries.length - 1]; + + const priceInr = plan.price_inr ?? primaryFallback?.priceInr ?? 0; + const priceUsd = plan.price_usd ?? primaryFallback?.priceUsd ?? 0; + const priceEur = plan.price_eur ?? plan.price_usd ?? primaryFallback?.priceEur ?? priceUsd; + const planColor = plan.color || primaryFallback?.color || 'from-teal-500 to-cyan-500'; + const planDesc = plan.description || primaryFallback?.desc || ''; + + // 1. Multi-item Core Packs (PATTERN_CORE, NUTRITION_CORE): emit sub-items + Complete Pack row + if (code in MULTI_ITEM_CORE_PACKS) { + const cfg = MULTI_ITEM_CORE_PACKS[code]; + const planModules = [...(plan.modules || [])].sort( + (a, b) => (a.sort_order ?? 500) - (b.sort_order ?? 500), + ); + + if (planModules.length > 0) { + for (const mod of planModules) { + const apiMatch = apiModules.find( + (m) => + (mod.code && (m.code || '').toLowerCase() === mod.code.toLowerCase()) || + (mod.slug && (m.slug || '').toLowerCase() === mod.slug.toLowerCase()), + ); + items.push({ + code, + name: mod.name, + category: cfg.category, + priceInr, + priceUsd, + priceEur, + desc: mod.description || apiMatch?.description || planDesc, + color: planColor, + sortOrder: mod.sort_order ?? apiMatch?.sort_order ?? 500, + planType: plan.plan_type, + }); + } + if (planModules.length > 1) { + items.push({ + code, + name: cfg.packTitle, + category: cfg.category, + priceInr, + priceUsd, + priceEur, + desc: planDesc || primaryFallback?.desc || `Unlock all ${cfg.category} modules.`, + color: cfg.defaultColor, + sortOrder: Number.MAX_SAFE_INTEGER, + planType: plan.plan_type, + }); + } + } else if (fallbackEntries.length > 0) { + for (const fb of fallbackEntries) { + items.push({ + ...fb, + priceInr, + priceUsd, + priceEur, + sortOrder: fb.name.includes('Complete Pack') ? Number.MAX_SAFE_INTEGER : 500, + planType: plan.plan_type, + }); + } + } + continue; + } + + // 2. Lifetime or Core Category Packs (POINTS_PACK, THERAPEUTICS_CORE) + if (code === 'LIFETIME_ALL' || CORE_PACK_CODES.has(code)) { + const category = resolvePlanCategory(plan, apiModules); + items.push({ + code, + name: primaryFallback?.name || plan.name, + category, + priceInr, + priceUsd, + priceEur, + desc: planDesc, + color: planColor, + sortOrder: Number.MAX_SAFE_INTEGER, + planType: plan.plan_type, + }); + continue; + } + + // 3. Custom Bundles (plan_type === 'bundle') — rendered in Card 6 (Custom Packages & Bundles) + if (plan.plan_type === 'bundle') { + items.push({ + code, + name: plan.name, + category: 'Bundle', + priceInr, + priceUsd, + priceEur, + desc: planDesc || 'Custom bundled access.', + color: plan.color || 'from-slate-700 to-slate-900', + sortOrder: 500, + planType: plan.plan_type, + }); + continue; + } + + // 4. Single-module plans (POINTS_*, THERAPEUTICS_*, MOD_*, or any one_time plan) + const firstMod = plan.modules?.[0]; + const apiMatch = findMatchingApiModule(plan, apiModules); + const category = resolvePlanCategory(plan, apiModules); + items.push({ + code, + name: primaryFallback?.name || plan.name || firstMod?.name || code, + category, + priceInr, + priceUsd, + priceEur, + desc: planDesc || firstMod?.description || apiMatch?.description || '', + color: planColor, + sortOrder: firstMod?.sort_order ?? apiMatch?.sort_order ?? 500, + planType: plan.plan_type, + }); + } + + return items; +} diff --git a/tests/e2e/catalog.spec.ts b/tests/e2e/catalog.spec.ts index bb80ffa..18106a4 100644 --- a/tests/e2e/catalog.spec.ts +++ b/tests/e2e/catalog.spec.ts @@ -88,4 +88,43 @@ test.describe('Catalog Section', () => { await expect(page.getByText('Acu (EOV+Cat+Ext+MR)')).toBeVisible(); await expect(page.getByText('Scalp', { exact: true })).not.toBeVisible(); }); + + test('renders newly activated Module Builder plan in its category and supports ?planCode deep link', async ({ page }) => { + await mockPublicStoreApis(page); + await page.route('**/api/plans', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify([ + ...MOCK_PLANS, + { + code: 'MOD_M0044', + base_code: 'MOD_M0044', + name: 'Pediatric Disorders', + description: 'TCM pediatric treatment protocols.', + plan_type: 'one_time', + billing_period: 'yearly', + price_inr: 600, + price_usd: 15, + price_eur: 15, + is_active: true, + modules: [ + { + code: 'm0044', + slug: 'pediatric-disorders', + name: 'Pediatric Disorders', + description: 'TCM pediatric treatment protocols.', + category: 'Therapeutics', + sort_order: 40, + }, + ], + }, + ]), + }); + }); + + await page.goto('./?planCode=MOD_M0044'); + await expect(page.getByText('Pediatric Disorders').first()).toBeVisible(); + await expect(page.getByText('1 Item')).toBeVisible(); + }); }); diff --git a/tests/unit/catalog.test.ts b/tests/unit/catalog.test.ts new file mode 100644 index 0000000..0951a81 --- /dev/null +++ b/tests/unit/catalog.test.ts @@ -0,0 +1,144 @@ +import { describe, it, expect } from 'vitest'; +import { buildDynamicCatalog, resolvePlanCategory } from '../../src/utils/catalog'; +import { CURRICULUM_MODULES } from '../../src/constants/modules'; +import type { PublicPlan } from '../../src/types'; + +describe('buildDynamicCatalog', () => { + it('falls back to CURRICULUM_MODULES when publicPlans is empty', () => { + const result = buildDynamicCatalog([]); + expect(result).toEqual(CURRICULUM_MODULES); + }); + + it('maps newly created Module Builder one_time plan to its normalized category with sortOrder', () => { + const plans: PublicPlan[] = [ + { + code: 'MOD_M0044', + base_code: 'MOD_M0044', + name: 'Pediatric Disorders', + description: 'TCM pediatric treatment protocols.', + plan_type: 'one_time', + price_inr: 600, + price_usd: 15, + price_eur: 15, + is_active: true, + modules: [ + { + id: 'mod-44', + code: 'm0044', + slug: 'pediatric-disorders', + name: 'Pediatric Disorders', + description: 'TCM pediatric treatment protocols.', + category: 'Therapeutics', + sort_order: 40, + }, + ], + }, + ]; + + const result = buildDynamicCatalog(plans); + expect(result).toHaveLength(1); + expect(result[0]).toMatchObject({ + code: 'MOD_M0044', + name: 'Pediatric Disorders', + category: 'Therapeutics', + priceInr: 600, + priceUsd: 15, + priceEur: 15, + sortOrder: 40, + }); + }); + + it('expands PATTERN_CORE sub-modules from plan.modules and appends Complete Pack', () => { + const plans: PublicPlan[] = [ + { + code: 'PATTERN_CORE', + name: 'Pattern: Complete Pack', + description: 'All pattern methodologies.', + plan_type: 'bundle', + price_inr: 500, + price_usd: 10, + price_eur: 10, + is_active: true, + modules: [ + { name: 'Zang-Fu Organs', slug: 'zang-fu', category: 'Pattern', sort_order: 2 }, + { name: 'Eight Principles', slug: 'eight-principles', category: 'Pattern', sort_order: 1 }, + ], + }, + ]; + + const result = buildDynamicCatalog(plans); + expect(result.map((m) => m.name)).toEqual([ + 'Eight Principles', + 'Zang-Fu Organs', + 'Pattern: Complete Pack', + ]); + expect(result[2].sortOrder).toBe(Number.MAX_SAFE_INTEGER); + }); + + it('omits Complete Pack row for NUTRITION_CORE when only 1 module exists and keeps POINTS_PACK last', () => { + const plans: PublicPlan[] = [ + { + code: 'NUTRITION_CORE', + name: 'Nutrition Module Access (1 Yr)', + plan_type: 'one_time', + price_inr: 600, + price_usd: 15, + price_eur: 15, + is_active: true, + modules: [{ code: 'm0031', name: 'Nutrition', slug: 'nutrition', category: 'Nutrition', sort_order: 99999 }], + }, + { + code: 'POINTS_PACK', + name: 'Points Complete Pack (1 Yr)', + plan_type: 'bundle', + price_inr: 900, + price_usd: 15, + price_eur: 15, + is_active: true, + }, + { + code: 'POINTS_ACU', + name: 'Acu Points Module (1 Yr)', + plan_type: 'one_time', + price_inr: 300, + price_usd: 5, + price_eur: 5, + is_active: true, + modules: [{ code: 'm0001', name: 'Acupuncture Points', slug: 'acupuncture-points', category: 'Points', sort_order: 99999 }], + }, + ]; + + const result = buildDynamicCatalog(plans); + const nutritionItems = result.filter((m) => m.category === 'Nutrition'); + expect(nutritionItems).toHaveLength(1); + expect(nutritionItems[0].name).toBe('Nutrition'); + + const pointsItems = result + .filter((m) => m.category === 'Points') + .sort((a, b) => (a.sortOrder ?? 500) - (b.sortOrder ?? 500)); + expect(pointsItems.map((m) => m.code)).toEqual(['POINTS_ACU', 'POINTS_PACK']); + }); + + it('resolves non-standard category or custom bundle cleanly', () => { + const unknownCatPlan: PublicPlan = { + code: 'MOD_HERB', + name: 'Herbal Formulas', + plan_type: 'one_time', + is_active: true, + modules: [{ name: 'Herbal Formulas', category: 'Herbalism', sort_order: 50 }], + }; + expect(resolvePlanCategory(unknownCatPlan)).toBe('Herbalism'); + + const bundlePlan: PublicPlan = { + code: 'STARTER_BUNDLE', + name: 'Starter Bundle', + plan_type: 'bundle', + price_inr: 1200, + price_usd: 25, + price_eur: 25, + is_active: true, + }; + const result = buildDynamicCatalog([bundlePlan]); + expect(result[0].category).toBe('Bundle'); + }); +});