import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { Database, RefreshCw, RefreshCcw, Menu, Sparkles } from 'lucide-react'; import { API_BASE } from './services/api'; import type { AdminTabType } from './types'; import { normalizeCategory } from './utils/category'; // Modular Components import { AdminSidebar } from './components/layout/AdminSidebar'; import { SyncOverview } from './components/sync/SyncOverview'; import { ModulesTab } from './components/modules/ModulesTab'; import { EditModuleModal } from './components/modules/EditModuleModal'; import { ModuleBuilderTab } from './components/modules/ModuleBuilderTab'; import { PlansTab } from './components/plans/PlansTab'; import { CreatePlanModal } from './components/plans/CreatePlanModal'; import { EditPriceModal } from './components/plans/EditPriceModal'; import { CouponsTab } from './components/coupons/CouponsTab'; import { CouponModal, type CouponFormData } from './components/coupons/CouponModal'; import { CustomersTab } from './components/users/CustomersTab'; import { CustomerDrawer } from './components/users/CustomerDrawer'; import { AdminsTab } from './components/users/AdminsTab'; import { SubscriptionsTab } from './components/subscriptions/SubscriptionsTab'; import { PaymentsTab } from './components/payments/PaymentsTab'; import { DatabaseBackupTab } from './components/database/DatabaseBackupTab'; import { ReportsExportTab } from './components/database/ReportsExportTab'; import { AdminLoginForm } from './components/auth/AdminLoginForm'; export function extractErrorMessage(err: any, fallback: string = 'An error occurred.'): string { if (!err) return fallback; const detail = err.response?.data?.detail ?? err.response?.data?.message ?? err.message; if (typeof detail === 'string') { return detail; } if (detail && typeof detail === 'object') { if (typeof detail.message === 'string' && detail.message) { return detail.message; } if (Array.isArray(detail.issues) && detail.issues.length > 0) { return detail.issues.map((i: any) => i.msg || JSON.stringify(i)).join('; '); } if (Array.isArray(detail.context?.issues) && detail.context.issues.length > 0) { return detail.context.issues.map((i: any) => i.msg || JSON.stringify(i)).join('; '); } if (Array.isArray(detail) && detail.length > 0) { return detail.map((i: any) => i.msg || (typeof i === 'string' ? i : JSON.stringify(i))).join('; '); } try { return JSON.stringify(detail); } catch { return fallback; } } return fallback; } export default function App() { const [userToken, setUserToken] = useState(localStorage.getItem('access_token')); const [loggedInUser, setLoggedInUser] = useState(null); const isAdmin = Boolean( loggedInUser?.roles?.some((role: string) => role === 'super_admin' || role === 'finance_admin' || role === 'admin') ); // Admin Login State const [adminAuthLoading, setAdminAuthLoading] = useState(false); const [adminAuthError, setAdminAuthError] = useState(null); // Tab Navigation State const [adminSyncing, setAdminSyncing] = useState(false); const [adminLogs, setAdminLogs] = useState([]); const [adminSubTab, setAdminSubTab] = useState('overview'); const [rzpPayments, setRzpPayments] = useState([]); const [usersSubscriptions, setUsersSubscriptions] = useState([]); const [adminDataLoading, setAdminDataLoading] = useState(false); const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(() => { return localStorage.getItem('admin_sidebar_collapsed') === 'true'; }); const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false); // Database & Backups State const [dbInfo, setDbInfo] = useState(null); const [dbBackupDownloading, setDbBackupDownloading] = useState<'full' | 'content' | null>(null); const [dbBackupError, setDbBackupError] = useState(null); const [dbBackupSuccess, setDbBackupSuccess] = useState(null); // Reports & Exports State const [reportDateFilter, setReportDateFilter] = useState<'all' | 'this_month' | 'last_30_days' | 'custom'>('all'); const [reportStartDate, setReportStartDate] = useState(''); const [reportEndDate, setReportEndDate] = useState(''); const [reportDownloading, setReportDownloading] = useState(null); const [reportExportSuccess, setReportExportSuccess] = useState(null); const [reportExportError, setReportExportError] = useState(null); // Customer Profile Drawer State const [selectedCustomerDrawerId, setSelectedCustomerDrawerId] = useState(null); const [customerDrawerData, setCustomerDrawerData] = useState(null); const [customerDrawerLoading, setCustomerDrawerLoading] = useState(false); const [customerStatusToggling, setCustomerStatusToggling] = useState(false); const [customerDrawerTab, setCustomerDrawerTab] = useState<'overview' | 'subscriptions' | 'invoices'>('overview'); // Modules State const [adminModulesList, setAdminModulesList] = useState([]); const [moduleCategoryFilter, setModuleCategoryFilter] = useState('all'); const [moduleStatusFilter, setModuleStatusFilter] = useState('all'); const [moduleSearchQuery, setModuleSearchQuery] = useState(''); const [selectedEditModule, setSelectedEditModule] = useState(null); const [editModuleName, setEditModuleName] = useState(''); const [editModuleDesc, setEditModuleDesc] = useState(''); const [editModuleCategory, setEditModuleCategory] = useState('point'); const [editModuleSaving, setEditModuleSaving] = useState(false); // Plans State const [adminPlansList, setAdminPlansList] = useState([]); const [planSearchQuery, setPlanSearchQuery] = useState(''); const [planTypeFilter, setPlanTypeFilter] = useState('all'); const [selectedEditPricePlan, setSelectedEditPricePlan] = useState(null); const [editPriceInr, setEditPriceInr] = useState(''); const [editPriceUsd, setEditPriceUsd] = useState(''); const [editPriceEur, setEditPriceEur] = useState(''); const [editPlanName, setEditPlanName] = useState(''); const [editPlanDesc, setEditPlanDesc] = useState(''); const [editPlanBadge, setEditPlanBadge] = useState(''); const [editPlanHeading, setEditPlanHeading] = useState(''); const [editPlanSubtitle, setEditPlanSubtitle] = useState(''); const [editPriceSaving, setEditPriceSaving] = useState(false); // Create Custom Plan State const [showCreatePlanModal, setShowCreatePlanModal] = useState(false); const [createPlanCode, setCreatePlanCode] = useState(''); const [createPlanName, setCreatePlanName] = useState(''); const [createPlanDesc, setCreatePlanDesc] = useState(''); const [createPlanBadge, setCreatePlanBadge] = useState(''); const [createPlanHeading, setCreatePlanHeading] = useState(''); const [createPlanSubtitle, setCreatePlanSubtitle] = useState(''); const [createPlanType, setCreatePlanType] = useState('bundle'); const [createPlanDuration, setCreatePlanDuration] = useState('yearly'); const [createPlanPriceInr, setCreatePlanPriceInr] = useState(''); const [createPlanPriceUsd, setCreatePlanPriceUsd] = useState(''); const [createPlanPriceEur, setCreatePlanPriceEur] = useState(''); const [createPlanModuleIds, setCreatePlanModuleIds] = useState([]); const [createPlanSaving, setCreatePlanSaving] = useState(false); const [createPlanError, setCreatePlanError] = useState(null); // Coupons State const [adminCouponsList, setAdminCouponsList] = useState([]); const [couponFilterStatus, setCouponFilterStatus] = useState<'all' | 'active' | 'scheduled' | 'expired'>('all'); const [couponSearchQuery, setCouponSearchQuery] = useState(''); // Unified Coupon Modal State const [couponModalMode, setCouponModalMode] = useState<'create' | 'edit' | null>(null); const [selectedEditCoupon, setSelectedEditCoupon] = useState(null); const [couponFormData, setCouponFormData] = useState({ code: '', category: 'general', discountType: 'percentage', discountValue: '20', maxDiscountCap: '0', description: '', startDate: '', endDate: '', scope: 'storewide', applicablePlanIds: [], applicableModuleIds: [], minSpend: '0', usageLimit: '0', firstOnly: false, }); const [couponSaving, setCouponSaving] = useState(false); // Filters for Subscriptions Ledger const [filterCustomerName, setFilterCustomerName] = useState(''); const [filterModuleName, setFilterModuleName] = useState(''); // Invoice Downloading State const [downloadingInvoiceId, setDownloadingInvoiceId] = useState(null); const [sharingInvoiceId, setSharingInvoiceId] = useState(null); // Admins & Practitioners const [adminsList, setAdminsList] = useState([]); const [practitionersList, setPractitionersList] = useState([]); const [createAdminEmail, setCreateAdminEmail] = useState(''); const [createAdminPassword, setCreateAdminPassword] = useState(''); const [createAdminName, setCreateAdminName] = useState(''); const [adminActionLoading, setAdminActionLoading] = useState(false); // Pagination States const [modulesPage, setModulesPage] = useState(1); const [modulesPerPage, setModulesPerPage] = useState(10); const [plansPage, setPlansPage] = useState(1); const [plansPerPage, setPlansPerPage] = useState(10); const [couponsPage, setCouponsPage] = useState(1); const [couponsPerPage, setCouponsPerPage] = useState(10); const [customersPage, setCustomersPage] = useState(1); const [customersPerPage, setCustomersPerPage] = useState(10); const [subscriptionsPage, setSubscriptionsPage] = useState(1); const [subscriptionsPerPage, setSubscriptionsPerPage] = useState(10); const [paymentsPage, setPaymentsPage] = useState(1); const [paymentsPerPage, setPaymentsPerPage] = useState(10); // Fetch initial profile const fetchUserProfile = async (token: string) => { try { const res = await axios.get(`${API_BASE}/api/auth/profile`, { headers: { Authorization: `Bearer ${token}` }, }); setLoggedInUser(res.data); } catch (err) { console.error('Failed to load profile:', err); localStorage.removeItem('access_token'); setUserToken(null); setLoggedInUser(null); } }; useEffect(() => { if (userToken) { fetchUserProfile(userToken); } }, [userToken]); useEffect(() => { if (isAdmin) { fetchAdminData(); } }, [isAdmin]); const fetchAdminData = async () => { setAdminSyncing(true); try { const userRes = await axios.get(`${API_BASE}/`); setAdminLogs((prev) => [ `[System] Connected to backend. Environment: ${userRes.data?.environment || 'production'}`, ...prev, ]); await fetchRazorpayAdminData(); } catch (err) { setAdminLogs((prev) => [ `[Admin Error] Backend connect failed: ${err instanceof Error ? err.message : String(err)}`, ...prev, ]); } finally { setAdminSyncing(false); } }; const fetchRazorpayAdminData = async () => { if (!userToken) return; setAdminDataLoading(true); const headers = { Authorization: `Bearer ${userToken}` }; try { const [payRes, adminsRes, practRes, subLedgerRes, modulesRes, plansRes, couponsRes, dbRes] = await Promise.allSettled([ axios.get(`${API_BASE}/api/admin/razorpay/payments`, { headers }), axios.get(`${API_BASE}/api/admin/super-admins`, { headers }), axios.get(`${API_BASE}/api/admin/practitioners`, { headers }), axios.get(`${API_BASE}/api/admin/users-subscriptions`, { headers }), axios.get(`${API_BASE}/api/admin/modules`, { headers }), axios.get(`${API_BASE}/api/admin/plans`, { headers }), axios.get(`${API_BASE}/api/admin/coupons`, { headers }), axios.get(`${API_BASE}/api/admin/database/info`, { headers }), ]); if (payRes.status === 'fulfilled') setRzpPayments(payRes.value.data.payments || []); if (adminsRes.status === 'fulfilled') setAdminsList(adminsRes.value.data || []); if (practRes.status === 'fulfilled') setPractitionersList(practRes.value.data || []); if (subLedgerRes.status === 'fulfilled') setUsersSubscriptions(subLedgerRes.value.data || []); if (modulesRes.status === 'fulfilled') { const rawMods: any[] = modulesRes.value.data || []; const resolved = rawMods.map((m: any) => ({ ...m, category: normalizeCategory(m.category || m.metadata?.category || m.metadata?.kind || m.kind), })); setAdminModulesList(resolved); } if (plansRes.status === 'fulfilled') setAdminPlansList(plansRes.value.data || []); if (couponsRes.status === 'fulfilled') setAdminCouponsList(couponsRes.value.data || []); if (dbRes.status === 'fulfilled') setDbInfo(dbRes.value.data || null); } catch (err) { console.error('Error fetching admin data:', err); } finally { setAdminDataLoading(false); } }; // Auth Handlers const handleAdminLogin = async (credentials: { email: string; password: string }) => { setAdminAuthLoading(true); setAdminAuthError(null); try { const res = await axios.post(`${API_BASE}/api/auth/login`, { email: credentials.email, password: credentials.password, }); const token = res.data.access_token; localStorage.setItem('access_token', token); setUserToken(token); fetchUserProfile(token); } catch (err: any) { setAdminAuthError(extractErrorMessage(err, 'Invalid administrative credentials.')); } finally { setAdminAuthLoading(false); } }; const handleLogout = () => { localStorage.removeItem('access_token'); setUserToken(null); setLoggedInUser(null); setAdminAuthError(null); }; // Force Sync Gateway Handler const handleForceSync = async () => { if (!loggedInUser) return; setAdminSyncing(true); setAdminLogs((prev) => ['[Admin Sync] Starting force-sync with Razorpay Gateway...', ...prev]); try { const headers = { Authorization: `Bearer ${userToken}` }; const res = await axios.post(`${API_BASE}/api/admin/force-sync`, {}, { headers }); setAdminLogs((prev) => [ `[Admin Sync] SUCCESS: ${res.data.message} (${res.data.records_processed} processed)`, ...prev, ]); await fetchUserProfile(userToken!); await fetchRazorpayAdminData(); } catch (err: any) { const errorMsg = extractErrorMessage(err, 'Failed to sync with Razorpay Gateway.'); setAdminLogs((prev) => [`[Admin Sync] FAILED: ${errorMsg}`, ...prev]); } finally { setAdminSyncing(false); } }; // Database Backup Handlers const handleDownloadBackup = async (scope: 'full' | 'content') => { if (!userToken) return; setDbBackupDownloading(scope); setDbBackupError(null); setDbBackupSuccess(null); try { const response = await axios.get(`${API_BASE}/api/admin/database/backup?scope=${scope}`, { headers: { Authorization: `Bearer ${userToken}` }, responseType: 'blob', }); const disposition = response.headers['content-disposition']; let filename = `panaceadb_backup_${scope}_${new Date().toISOString().replace(/[:.-]/g, '').slice(0, 15)}.sql.gz`; if (disposition && disposition.includes('filename=')) { const match = disposition.match(/filename="?([^"]+)"?/); if (match && match[1]) filename = match[1]; } const blob = new Blob([response.data], { type: 'application/gzip' }); const url = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.setAttribute('download', filename); document.body.appendChild(link); link.click(); link.remove(); window.URL.revokeObjectURL(url); setDbBackupSuccess( `Successfully downloaded ${scope === 'full' ? 'Full Database' : 'Clinical Content'} backup (${filename})` ); setTimeout(() => setDbBackupSuccess(null), 8000); } catch (err: any) { setDbBackupError( extractErrorMessage(err, 'Failed to download database backup. Ensure database client is active.') ); } finally { setDbBackupDownloading(null); } }; // Reports Handlers const handleDownloadReport = async (reportType: string) => { if (!userToken) return; setReportDownloading(reportType); setReportExportError(null); setReportExportSuccess(null); try { let startParam = ''; let endParam = ''; if (reportDateFilter === 'this_month') { const now = new Date(); const start = new Date(now.getFullYear(), now.getMonth(), 1); startParam = start.toISOString().split('T')[0]; endParam = now.toISOString().split('T')[0]; } else if (reportDateFilter === 'last_30_days') { const now = new Date(); const start = new Date(); start.setDate(now.getDate() - 30); startParam = start.toISOString().split('T')[0]; endParam = now.toISOString().split('T')[0]; } else if (reportDateFilter === 'custom') { startParam = reportStartDate; endParam = reportEndDate; } const params = new URLSearchParams(); if (startParam) params.append('start_date', startParam); if (endParam) params.append('end_date', endParam); const url = `${API_BASE}/api/admin/reports/${reportType}/export${ params.toString() ? '?' + params.toString() : '' }`; const response = await axios.get(url, { headers: { Authorization: `Bearer ${userToken}` }, responseType: 'blob', }); const disposition = response.headers['content-disposition']; let filename = `${reportType}_ledger_${new Date().toISOString().replace(/[:.-]/g, '').slice(0, 15)}.csv`; if (disposition && disposition.includes('filename=')) { const match = disposition.match(/filename="?([^"]+)"?/); if (match && match[1]) filename = match[1]; } const blob = new Blob([response.data], { type: 'text/csv;charset=utf-8;' }); const downloadUrl = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = downloadUrl; link.setAttribute('download', filename); document.body.appendChild(link); link.click(); link.remove(); window.URL.revokeObjectURL(downloadUrl); setReportExportSuccess(`Successfully downloaded ${reportType} report (${filename})`); setTimeout(() => setReportExportSuccess(null), 8000); } catch (err: any) { setReportExportError(extractErrorMessage(err, 'Failed to export report CSV.')); } finally { setReportDownloading(null); } }; // Customer Drawer Handlers const handleOpenCustomerDrawer = async (userId: string) => { setSelectedCustomerDrawerId(userId); setCustomerDrawerLoading(true); setCustomerDrawerData(null); setCustomerDrawerTab('overview'); try { const res = await axios.get(`${API_BASE}/api/admin/customers/${userId}/detail`, { headers: { Authorization: `Bearer ${userToken}` }, }); setCustomerDrawerData(res.data); } catch (err: any) { alert(extractErrorMessage(err, 'Failed to load customer details.')); } finally { setCustomerDrawerLoading(false); } }; const handleToggleCustomerActiveStatus = async () => { if (!customerDrawerData || !userToken) return; const newActive = !customerDrawerData.is_active; setCustomerStatusToggling(true); try { const res = await axios.patch( `${API_BASE}/api/admin/customers/${customerDrawerData.id}/status`, { is_active: newActive }, { headers: { Authorization: `Bearer ${userToken}` } } ); setCustomerDrawerData((prev: any) => (prev ? { ...prev, is_active: newActive } : prev)); setPractitionersList((prev: any[]) => prev.map((p) => (p.id === customerDrawerData.id ? { ...p, is_active: newActive } : p)) ); setAdminsList((prev: any[]) => prev.map((a) => (a.id === customerDrawerData.id ? { ...a, is_active: newActive } : a)) ); setAdminLogs((prev) => [`[Customer Control] ${res.data.message}`, ...prev]); } catch (err: any) { alert(extractErrorMessage(err, 'Failed to update account status.')); } finally { setCustomerStatusToggling(false); } }; // Module Handlers const handleToggleModuleStatus = async (mod: any) => { if (!userToken) return; const newActive = !mod.is_active; const newStatus = newActive ? 'active' : 'inactive'; setAdminModulesList((prev) => prev.map((m) => (m.id === mod.id ? { ...m, is_active: newActive, status: newStatus } : m)) ); try { await axios.patch( `${API_BASE}/api/admin/modules/${mod.id}/status`, { is_active: newActive, status: newStatus }, { headers: { Authorization: `Bearer ${userToken}` } } ); const linkedPlans = adminPlansList.filter((p) => p.base_code?.toLowerCase() === mod.code?.toLowerCase() || p.module_ids?.includes(mod.id) || p.modules?.some((m: any) => m.id === mod.id || m.slug === mod.slug) ); for (const plan of linkedPlans) { if (plan.is_active !== newActive) { try { await axios.patch( `${API_BASE}/api/admin/plans/${plan.base_code}/status`, { is_active: newActive }, { headers: { Authorization: `Bearer ${userToken}` } } ); setAdminPlansList((prev) => prev.map((p) => (p.base_code === plan.base_code ? { ...p, is_active: newActive } : p)) ); } catch (planErr) { console.error('Failed to sync linked plan status:', planErr); } } } setAdminLogs((prev) => [`[Catalog] ${mod.name} is now ${newActive ? 'Active' : 'Inactive'}`, ...prev]); } catch (err: any) { setAdminModulesList((prev) => prev.map((m) => (m.id === mod.id ? { ...m, is_active: !newActive, status: !newActive ? 'active' : 'inactive' } : m)) ); alert(extractErrorMessage(err, 'Failed to update module status.')); } }; const handleOpenEditModule = (mod: any) => { setSelectedEditModule(mod); setEditModuleName(mod.name || ''); setEditModuleDesc(mod.description || ''); setEditModuleCategory(normalizeCategory(mod.category)); }; const handleSaveModuleDetails = async (e: React.FormEvent) => { e.preventDefault(); if (!selectedEditModule || !userToken) return; setEditModuleSaving(true); const normalizedCat = normalizeCategory(editModuleCategory); try { await axios.put( `${API_BASE}/api/admin/modules/${selectedEditModule.id}`, { name: editModuleName, description: editModuleDesc, category: normalizedCat, }, { headers: { Authorization: `Bearer ${userToken}` } } ); setAdminModulesList((prev) => prev.map((m) => m.id === selectedEditModule.id ? { ...m, name: editModuleName, description: editModuleDesc, category: normalizedCat } : m ) ); setSelectedEditModule(null); setAdminLogs((prev) => [`[Catalog] Updated metadata for '${editModuleName}'`, ...prev]); } catch (err: any) { alert(extractErrorMessage(err, 'Failed to update module details.')); } finally { setEditModuleSaving(false); } }; // Plan Handlers const handleTogglePlanStatus = async (plan: any) => { if (!userToken) return; const newActive = !plan.is_active; setAdminPlansList((prev) => prev.map((p) => (p.base_code === plan.base_code ? { ...p, is_active: newActive } : p)) ); try { await axios.patch( `${API_BASE}/api/admin/plans/${plan.base_code}/status`, { is_active: newActive }, { headers: { Authorization: `Bearer ${userToken}` } } ); setAdminLogs((prev) => [ `[Plans] ${plan.name} (${plan.base_code}) is now ${newActive ? 'Active' : 'Inactive'}`, ...prev, ]); } catch (err: any) { setAdminPlansList((prev) => prev.map((p) => (p.base_code === plan.base_code ? { ...p, is_active: !newActive } : p)) ); alert(extractErrorMessage(err, 'Failed to update plan status.')); } }; const handleOpenEditPrice = (plan: any) => { setSelectedEditPricePlan(plan); setEditPriceInr(String(plan.price_inr ?? '')); setEditPriceUsd(String(plan.price_usd ?? '')); setEditPriceEur(String(plan.price_eur ?? plan.price_usd ?? '')); setEditPlanName(plan.name || ''); setEditPlanDesc(plan.description || ''); setEditPlanBadge(plan.badge_text || ''); setEditPlanHeading(plan.heading || ''); setEditPlanSubtitle(plan.subtitle || ''); }; const handleSavePlanPrice = async (e: React.FormEvent) => { e.preventDefault(); if (!selectedEditPricePlan || !userToken) return; const inrVal = parseFloat(editPriceInr); const usdVal = parseFloat(editPriceUsd); const eurVal = editPriceEur.trim() ? parseFloat(editPriceEur) : usdVal; if (isNaN(inrVal) || inrVal < 0 || isNaN(usdVal) || usdVal < 0 || isNaN(eurVal) || eurVal < 0) { alert('Please enter valid positive pricing values.'); return; } setEditPriceSaving(true); try { await axios.put( `${API_BASE}/api/admin/plans/${selectedEditPricePlan.base_code}/pricing`, { price_inr: inrVal, price_usd: usdVal, price_eur: eurVal, name: editPlanName.trim() || undefined, description: editPlanDesc.trim() || undefined, badge_text: editPlanBadge.trim() || undefined, heading: editPlanHeading.trim() || undefined, subtitle: editPlanSubtitle.trim() || undefined, }, { headers: { Authorization: `Bearer ${userToken}` } } ); setAdminPlansList((prev) => prev.map((p) => p.base_code === selectedEditPricePlan.base_code ? { ...p, name: editPlanName.trim() || selectedEditPricePlan.name, description: editPlanDesc.trim() || selectedEditPricePlan.description, badge_text: editPlanBadge.trim() || selectedEditPricePlan.badge_text, heading: editPlanHeading.trim() || selectedEditPricePlan.heading, subtitle: editPlanSubtitle.trim() || selectedEditPricePlan.subtitle, price_inr: inrVal, price_usd: usdVal, price_eur: eurVal, } : p ) ); setSelectedEditPricePlan(null); setAdminLogs((prev) => [ `[Plans] Updated details & pricing for '${editPlanName || selectedEditPricePlan.name}'`, ...prev, ]); } catch (err: any) { alert(extractErrorMessage(err, 'Failed to update plan.')); } finally { setEditPriceSaving(false); } }; const handleOpenCreatePlan = () => { setCreatePlanCode(''); setCreatePlanName(''); setCreatePlanDesc(''); setCreatePlanBadge(''); setCreatePlanHeading(''); setCreatePlanSubtitle(''); setCreatePlanType('bundle'); setCreatePlanDuration('yearly'); setCreatePlanPriceInr(''); setCreatePlanPriceUsd(''); setCreatePlanPriceEur(''); setCreatePlanModuleIds([]); setCreatePlanError(null); setShowCreatePlanModal(true); }; const handleSaveCreatePlan = async (e: React.FormEvent) => { e.preventDefault(); setCreatePlanError(null); if (!createPlanCode.trim() || !createPlanName.trim()) { setCreatePlanError('Plan code and plan name are required.'); return; } const inrVal = parseFloat(createPlanPriceInr); const usdVal = parseFloat(createPlanPriceUsd); const eurVal = createPlanPriceEur.trim() ? parseFloat(createPlanPriceEur) : usdVal; if (isNaN(inrVal) || inrVal < 0 || isNaN(usdVal) || usdVal < 0 || isNaN(eurVal) || eurVal < 0) { setCreatePlanError('Please provide valid positive prices for INR, USD, and EUR.'); return; } if (createPlanModuleIds.length === 0) { setCreatePlanError('Please select at least one clinical module to include in this plan.'); return; } setCreatePlanSaving(true); try { const res = await axios.post( `${API_BASE}/api/admin/plans`, { code: createPlanCode.trim(), name: createPlanName.trim(), description: createPlanDesc.trim(), badge_text: createPlanBadge.trim() || undefined, heading: createPlanHeading.trim() || undefined, subtitle: createPlanSubtitle.trim() || undefined, plan_type: createPlanType, billing_period: createPlanDuration, price_inr: inrVal, price_usd: usdVal, price_eur: eurVal, module_ids: createPlanModuleIds, is_featured: false, }, { headers: { Authorization: `Bearer ${userToken}` } } ); if (res.data?.plan) { setAdminPlansList((prev) => [res.data.plan, ...prev]); setAdminLogs((prev) => [ `[Plans] Created custom plan '${res.data.plan.name}' (${res.data.plan.base_code})`, ...prev, ]); } setShowCreatePlanModal(false); } catch (err: any) { setCreatePlanError(extractErrorMessage(err, 'Failed to create custom plan.')); } finally { setCreatePlanSaving(false); } }; // Coupon Handlers const handleOpenCreateCoupon = () => { const todayStr = new Date().toISOString().split('T')[0]; const nextYear = new Date(); nextYear.setFullYear(nextYear.getFullYear() + 1); const nextYearStr = nextYear.toISOString().split('T')[0]; setCouponFormData({ code: '', category: 'general', discountType: 'percentage', discountValue: '20', maxDiscountCap: '0', description: '', startDate: todayStr, endDate: nextYearStr, scope: 'storewide', applicablePlanIds: [], applicableModuleIds: [], minSpend: '0', usageLimit: '0', firstOnly: false, }); setCouponModalMode('create'); }; const handleOpenEditCoupon = (c: any) => { setSelectedEditCoupon(c); const hasSpecific = (c.applicable_plan_ids && c.applicable_plan_ids.length > 0) || (c.applicable_module_ids && c.applicable_module_ids.length > 0); setCouponFormData({ code: c.code, category: c.coupon_category || 'general', discountType: c.discount_type || 'percentage', discountValue: String(c.value ?? 0), maxDiscountCap: String(c.max_discount_limit ?? 0), description: c.description || '', startDate: c.start_date ? c.start_date.split('T')[0] : '', endDate: c.end_date ? c.end_date.split('T')[0] : '', scope: hasSpecific ? 'specific' : 'storewide', applicablePlanIds: c.applicable_plan_ids || [], applicableModuleIds: c.applicable_module_ids || [], minSpend: String(c.min_purchase_amount ?? 0), usageLimit: String(c.usage_limit ?? 0), firstOnly: Boolean(c.is_first_purchase_only), }); setCouponModalMode('edit'); }; const handleSaveCoupon = async (e: React.FormEvent) => { e.preventDefault(); if (!couponFormData.code.trim() || !userToken) return; if (couponFormData.startDate && couponFormData.endDate && couponFormData.endDate <= couponFormData.startDate) { alert('Invalid date range: Expiration date must be later than start date.'); return; } setCouponSaving(true); try { const headers = { Authorization: `Bearer ${userToken}` }; const payload: any = { code: couponFormData.code.trim().toUpperCase(), discount_type: couponFormData.discountType, coupon_category: couponFormData.category, value: parseFloat(couponFormData.discountValue) || 0, max_discount_limit: parseFloat(couponFormData.maxDiscountCap) || 0, usage_limit: parseInt(couponFormData.usageLimit) || 0, min_purchase_amount: parseFloat(couponFormData.minSpend) || 0, is_first_purchase_only: couponFormData.firstOnly, is_active: true, description: couponFormData.description.trim() || undefined, }; if (couponFormData.startDate) { payload.start_date = new Date(couponFormData.startDate + 'T00:00:00Z').toISOString(); } if (couponFormData.endDate) { payload.end_date = new Date(couponFormData.endDate + 'T23:59:59Z').toISOString(); } if (couponFormData.scope === 'specific') { payload.applicable_plan_ids = couponFormData.applicablePlanIds; payload.applicable_module_ids = couponFormData.applicableModuleIds; } else { payload.applicable_plan_ids = []; payload.applicable_module_ids = []; } if (couponModalMode === 'create') { await axios.post(`${API_BASE}/api/admin/coupons`, payload, { headers }); setAdminLogs((prev) => [`[Coupons] Created promo code ${payload.code}.`, ...prev]); } else if (couponModalMode === 'edit' && selectedEditCoupon) { await axios.put(`${API_BASE}/api/admin/coupons/${selectedEditCoupon.id}`, payload, { headers }); setAdminLogs((prev) => [`[Coupons] Updated promo code ${selectedEditCoupon.code}.`, ...prev]); } setCouponModalMode(null); setSelectedEditCoupon(null); await fetchRazorpayAdminData(); } catch (err: any) { alert(extractErrorMessage(err, 'Failed to save coupon.')); } finally { setCouponSaving(false); } }; const handleToggleCouponStatus = async (c: any) => { if (!userToken) return; const newActive = !c.is_active; setAdminCouponsList((prev) => prev.map((item) => item.id === c.id ? { ...item, is_active: newActive, schedule_status: newActive ? 'active' : 'inactive' } : item ) ); try { const headers = { Authorization: `Bearer ${userToken}` }; await axios.patch(`${API_BASE}/api/admin/coupons/${c.id}/status`, { is_active: newActive }, { headers }); setAdminLogs((prev) => [ `[Coupons] Promo code ${c.code} is now ${newActive ? 'Active' : 'Inactive'}.`, ...prev, ]); } catch (err: any) { setAdminCouponsList((prev) => prev.map((item) => (item.id === c.id ? { ...item, is_active: !newActive } : item)) ); alert(extractErrorMessage(err, 'Failed to update coupon status.')); } }; const handleDeleteCoupon = async (c: any) => { if (!userToken) return; if (!window.confirm(`Are you sure you want to permanently delete promo code "${c.code}"?`)) return; try { const headers = { Authorization: `Bearer ${userToken}` }; await axios.delete(`${API_BASE}/api/admin/coupons/${c.id}`, { headers }); setAdminCouponsList((prev) => prev.filter((item) => item.id !== c.id)); setAdminLogs((prev) => [`[Coupons] Deleted promo code ${c.code}.`, ...prev]); } catch (err: any) { alert(extractErrorMessage(err, 'Failed to delete coupon.')); } }; // Invoice Handlers const handleDownloadInvoice = async (paymentId: string) => { if (!userToken) return; setDownloadingInvoiceId(paymentId); try { const headers = { Authorization: `Bearer ${userToken}` }; const res = await axios.get(`${API_BASE}/api/admin/payments/${paymentId}/invoice`, { headers }); if (res.data?.short_url) { let url = res.data.short_url; if (!url.startsWith('http')) { url = `${API_BASE}${url}`; } if (url.includes('/api/admin/payments/')) { const sep = url.includes('?') ? '&' : '?'; url = `${url}${sep}token=${encodeURIComponent(userToken)}`; } window.open(url, '_blank'); } else { throw new Error('Invoice URL is missing in server response.'); } } catch (err: any) { alert(extractErrorMessage(err, 'Could not download invoice.')); } finally { setDownloadingInvoiceId(null); } }; const handleShareInvoice = async (paymentId: string) => { if (!userToken) return; setSharingInvoiceId(paymentId); try { const headers = { Authorization: `Bearer ${userToken}` }; const res = await axios.post(`${API_BASE}/api/admin/payments/${paymentId}/share-invoice`, {}, { headers }); alert(res.data?.message || 'Invoice shared successfully via email!'); } catch (err: any) { alert(extractErrorMessage(err, 'Could not share invoice.')); } finally { setSharingInvoiceId(null); } }; // Admin Creation Handler const handleCreateAdmin = async (e: React.FormEvent) => { e.preventDefault(); if (!loggedInUser || !createAdminEmail.trim() || !createAdminPassword.trim()) return; setAdminActionLoading(true); try { const headers = { Authorization: `Bearer ${userToken}` }; const res = await axios.post( `${API_BASE}/api/admin/create-super-admin`, { email: createAdminEmail, password: createAdminPassword, display_name: createAdminName || undefined, }, { headers } ); alert(`Success: ${res.data.message}`); setCreateAdminEmail(''); setCreateAdminPassword(''); setCreateAdminName(''); await fetchRazorpayAdminData(); } catch (err: any) { alert(`Admin creation failed: ${extractErrorMessage(err, 'Admin creation failed.')}`); } finally { setAdminActionLoading(false); } }; // Not Logged In or Not Admin View if (!loggedInUser || !isAdmin) { return ( ); } return (
{/* Mobile Top Header Bar (Only visible on screens < md) */}

ACUPEDIA

ADMIN CONSOLE

{/* Current Tab Indicator Badge on Mobile */}
{adminSubTab === 'users_subscriptions' ? 'Subscriptions' : adminSubTab.replace('_', ' ')}
{/* 1. Collapsible & Responsive Sidebar */} { setIsSidebarCollapsed((prev) => { const next = !prev; localStorage.setItem('admin_sidebar_collapsed', String(next)); return next; }); }} onLogout={handleLogout} isMobileOpen={isMobileMenuOpen} onCloseMobile={() => setIsMobileMenuOpen(false)} /> {/* 2. Main Administrative Workspace */}
{/* Sleek Top Header Bar */}
Backoffice Controls

{adminSubTab === 'overview' && 'System Overview & Audit Logs'} {adminSubTab === 'modules' && 'Curriculum Modules'} {adminSubTab === 'module_builder' && 'Clinical Module Builder'} {adminSubTab === 'plans' && 'Subscription Plans & Pricing'} {adminSubTab === 'coupons' && 'Promotions & Coupons'} {adminSubTab === 'customers' && 'Customer Directory'} {adminSubTab === 'users_subscriptions' && 'Active Subscriptions'} {adminSubTab === 'payments' && 'Transaction Ledgers'} {adminSubTab === 'admins' && 'Admin Accounts & Roles'} {adminSubTab === 'database' && 'Database Backups & Maintenance'} {adminSubTab === 'reports' && 'Reports & Financial Exports'}

{adminSubTab === 'overview' && 'Real-time telemetry, synchronized payment logs, and platform health metrics.'} {adminSubTab === 'modules' && 'Configure learning modules, categories, pricing, and availability states.'} {adminSubTab === 'module_builder' && 'Author and customize disease categories, clinical patterns, and treatment formulas.'} {adminSubTab === 'plans' && 'Manage localized pricing tiers, curriculum module bundles, and active pricing.'} {adminSubTab === 'coupons' && 'Manage discount codes, percentage cuts, module restrictions, and expiry dates.'} {adminSubTab === 'customers' && 'Inspect practitioner accounts, credentials, countries, and purchased plans.'} {adminSubTab === 'users_subscriptions' && 'Inspect live subscriber contracts, expiration dates, and access entitlements.'} {adminSubTab === 'payments' && 'View Razorpay transactions, currencies, invoice details, and captured amounts.'} {adminSubTab === 'admins' && 'Assign administrator credentials and RBAC privilege levels.'} {adminSubTab === 'database' && 'Export PostgreSQL dumps and verify database connectivity.'} {adminSubTab === 'reports' && 'Download revenue ledgers, customer records, and financial reports.'}

{/* Top Quick Actions (Force-Sync Gateway & Refresh) */}
{/* SubTab Content View */}
{adminSubTab === 'overview' && ( setAdminLogs([])} /> )} {adminSubTab === 'modules' && ( )} {adminSubTab === 'module_builder' && ( )} {adminSubTab === 'plans' && ( )} {adminSubTab === 'coupons' && ( )} {adminSubTab === 'customers' && ( )} {adminSubTab === 'users_subscriptions' && ( )} {adminSubTab === 'payments' && ( )} {adminSubTab === 'admins' && ( )} {adminSubTab === 'database' && ( )} {adminSubTab === 'reports' && ( )}
{/* Global Modals & Drawers */} setSelectedEditModule(null)} /> { setCreatePlanPriceUsd(v); if (!createPlanPriceEur || createPlanPriceEur === createPlanPriceUsd) { setCreatePlanPriceEur(v); } }} onPriceEurChange={setCreatePlanPriceEur} onToggleModule={(id) => setCreatePlanModuleIds((prev) => prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id] ) } onSelectAllModules={() => setCreatePlanModuleIds(adminModulesList.map((m) => m.id))} onClearAllModules={() => setCreatePlanModuleIds([])} onSave={handleSaveCreatePlan} onClose={() => setShowCreatePlanModal(false)} /> setSelectedEditPricePlan(null)} /> setCouponFormData((prev) => ({ ...prev, [field]: val }))} onSave={handleSaveCoupon} onClose={() => setCouponModalMode(null)} /> { setSelectedCustomerDrawerId(null); setCustomerDrawerData(null); }} onDownloadInvoice={handleDownloadInvoice} />
); }