1334 lines
54 KiB
TypeScript
1334 lines
54 KiB
TypeScript
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<string | null>(localStorage.getItem('access_token'));
|
|
const [loggedInUser, setLoggedInUser] = useState<any>(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<string | null>(null);
|
|
|
|
// Tab Navigation State
|
|
const [adminSyncing, setAdminSyncing] = useState<boolean>(false);
|
|
const [adminLogs, setAdminLogs] = useState<string[]>([]);
|
|
const [adminSubTab, setAdminSubTab] = useState<AdminTabType>('overview');
|
|
const [rzpPayments, setRzpPayments] = useState<any[]>([]);
|
|
const [usersSubscriptions, setUsersSubscriptions] = useState<any[]>([]);
|
|
const [adminDataLoading, setAdminDataLoading] = useState(false);
|
|
const [isSidebarCollapsed, setIsSidebarCollapsed] = useState<boolean>(() => {
|
|
return localStorage.getItem('admin_sidebar_collapsed') === 'true';
|
|
});
|
|
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState<boolean>(false);
|
|
|
|
// Database & Backups State
|
|
const [dbInfo, setDbInfo] = useState<any | null>(null);
|
|
const [dbBackupDownloading, setDbBackupDownloading] = useState<'full' | 'content' | null>(null);
|
|
const [dbBackupError, setDbBackupError] = useState<string | null>(null);
|
|
const [dbBackupSuccess, setDbBackupSuccess] = useState<string | null>(null);
|
|
|
|
// Reports & Exports State
|
|
const [reportDateFilter, setReportDateFilter] = useState<'all' | 'this_month' | 'last_30_days' | 'custom'>('all');
|
|
const [reportStartDate, setReportStartDate] = useState<string>('');
|
|
const [reportEndDate, setReportEndDate] = useState<string>('');
|
|
const [reportDownloading, setReportDownloading] = useState<string | null>(null);
|
|
const [reportExportSuccess, setReportExportSuccess] = useState<string | null>(null);
|
|
const [reportExportError, setReportExportError] = useState<string | null>(null);
|
|
|
|
// Customer Profile Drawer State
|
|
const [selectedCustomerDrawerId, setSelectedCustomerDrawerId] = useState<string | null>(null);
|
|
const [customerDrawerData, setCustomerDrawerData] = useState<any | null>(null);
|
|
const [customerDrawerLoading, setCustomerDrawerLoading] = useState<boolean>(false);
|
|
const [customerStatusToggling, setCustomerStatusToggling] = useState<boolean>(false);
|
|
const [customerDrawerTab, setCustomerDrawerTab] = useState<'overview' | 'subscriptions' | 'invoices'>('overview');
|
|
|
|
// Modules State
|
|
const [adminModulesList, setAdminModulesList] = useState<any[]>([]);
|
|
const [moduleCategoryFilter, setModuleCategoryFilter] = useState<string>('all');
|
|
const [moduleStatusFilter, setModuleStatusFilter] = useState<string>('all');
|
|
const [moduleSearchQuery, setModuleSearchQuery] = useState<string>('');
|
|
const [selectedEditModule, setSelectedEditModule] = useState<any | null>(null);
|
|
const [editModuleName, setEditModuleName] = useState<string>('');
|
|
const [editModuleDesc, setEditModuleDesc] = useState<string>('');
|
|
const [editModuleCategory, setEditModuleCategory] = useState<string>('point');
|
|
const [editModuleSaving, setEditModuleSaving] = useState<boolean>(false);
|
|
|
|
// Plans State
|
|
const [adminPlansList, setAdminPlansList] = useState<any[]>([]);
|
|
const [planSearchQuery, setPlanSearchQuery] = useState<string>('');
|
|
const [planTypeFilter, setPlanTypeFilter] = useState<string>('all');
|
|
const [selectedEditPricePlan, setSelectedEditPricePlan] = useState<any | null>(null);
|
|
const [editPriceInr, setEditPriceInr] = useState<string>('');
|
|
const [editPriceUsd, setEditPriceUsd] = useState<string>('');
|
|
const [editPlanName, setEditPlanName] = useState<string>('');
|
|
const [editPlanDesc, setEditPlanDesc] = useState<string>('');
|
|
const [editPlanBadge, setEditPlanBadge] = useState<string>('');
|
|
const [editPlanHeading, setEditPlanHeading] = useState<string>('');
|
|
const [editPlanSubtitle, setEditPlanSubtitle] = useState<string>('');
|
|
const [editPriceSaving, setEditPriceSaving] = useState<boolean>(false);
|
|
|
|
// Create Custom Plan State
|
|
const [showCreatePlanModal, setShowCreatePlanModal] = useState<boolean>(false);
|
|
const [createPlanCode, setCreatePlanCode] = useState<string>('');
|
|
const [createPlanName, setCreatePlanName] = useState<string>('');
|
|
const [createPlanDesc, setCreatePlanDesc] = useState<string>('');
|
|
const [createPlanBadge, setCreatePlanBadge] = useState<string>('');
|
|
const [createPlanHeading, setCreatePlanHeading] = useState<string>('');
|
|
const [createPlanSubtitle, setCreatePlanSubtitle] = useState<string>('');
|
|
const [createPlanType, setCreatePlanType] = useState<string>('bundle');
|
|
const [createPlanDuration, setCreatePlanDuration] = useState<string>('yearly');
|
|
const [createPlanPriceInr, setCreatePlanPriceInr] = useState<string>('');
|
|
const [createPlanPriceUsd, setCreatePlanPriceUsd] = useState<string>('');
|
|
const [createPlanModuleIds, setCreatePlanModuleIds] = useState<string[]>([]);
|
|
const [createPlanSaving, setCreatePlanSaving] = useState<boolean>(false);
|
|
const [createPlanError, setCreatePlanError] = useState<string | null>(null);
|
|
|
|
// Coupons State
|
|
const [adminCouponsList, setAdminCouponsList] = useState<any[]>([]);
|
|
const [couponFilterStatus, setCouponFilterStatus] = useState<'all' | 'active' | 'scheduled' | 'expired'>('all');
|
|
const [couponSearchQuery, setCouponSearchQuery] = useState<string>('');
|
|
|
|
// Unified Coupon Modal State
|
|
const [couponModalMode, setCouponModalMode] = useState<'create' | 'edit' | null>(null);
|
|
const [selectedEditCoupon, setSelectedEditCoupon] = useState<any | null>(null);
|
|
const [couponFormData, setCouponFormData] = useState<CouponFormData>({
|
|
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<boolean>(false);
|
|
|
|
// Filters for Subscriptions Ledger
|
|
const [filterCustomerName, setFilterCustomerName] = useState<string>('');
|
|
const [filterModuleName, setFilterModuleName] = useState<string>('');
|
|
|
|
// Invoice Downloading State
|
|
const [downloadingInvoiceId, setDownloadingInvoiceId] = useState<string | null>(null);
|
|
const [sharingInvoiceId, setSharingInvoiceId] = useState<string | null>(null);
|
|
|
|
// Admins & Practitioners
|
|
const [adminsList, setAdminsList] = useState<any[]>([]);
|
|
const [practitionersList, setPractitionersList] = useState<any[]>([]);
|
|
const [createAdminEmail, setCreateAdminEmail] = useState('');
|
|
const [createAdminPassword, setCreateAdminPassword] = useState('');
|
|
const [createAdminName, setCreateAdminName] = useState('');
|
|
const [adminActionLoading, setAdminActionLoading] = useState(false);
|
|
|
|
// Pagination States
|
|
const [modulesPage, setModulesPage] = useState<number>(1);
|
|
const [modulesPerPage, setModulesPerPage] = useState<number>(10);
|
|
const [plansPage, setPlansPage] = useState<number>(1);
|
|
const [plansPerPage, setPlansPerPage] = useState<number>(10);
|
|
const [couponsPage, setCouponsPage] = useState<number>(1);
|
|
const [couponsPerPage, setCouponsPerPage] = useState<number>(10);
|
|
const [customersPage, setCustomersPage] = useState<number>(1);
|
|
const [customersPerPage, setCustomersPerPage] = useState<number>(10);
|
|
const [subscriptionsPage, setSubscriptionsPage] = useState<number>(1);
|
|
const [subscriptionsPerPage, setSubscriptionsPerPage] = useState<number>(10);
|
|
const [paymentsPage, setPaymentsPage] = useState<number>(1);
|
|
const [paymentsPerPage, setPaymentsPerPage] = useState<number>(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 ?? ''));
|
|
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);
|
|
if (isNaN(inrVal) || inrVal < 0 || isNaN(usdVal) || usdVal < 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,
|
|
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,
|
|
}
|
|
: 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('');
|
|
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);
|
|
if (isNaN(inrVal) || inrVal < 0 || isNaN(usdVal) || usdVal < 0) {
|
|
setCreatePlanError('Please provide valid positive prices for INR and USD.');
|
|
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,
|
|
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 (
|
|
<AdminLoginForm
|
|
loading={adminAuthLoading}
|
|
error={adminAuthError}
|
|
loggedInUser={loggedInUser}
|
|
isAdmin={isAdmin}
|
|
onSubmit={handleAdminLogin}
|
|
onLogout={handleLogout}
|
|
/>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className="min-h-screen bg-slate-50 flex flex-col md:flex-row text-slate-800 selection:bg-indigo-500 selection:text-white">
|
|
{/* Mobile Top Header Bar (Only visible on screens < md) */}
|
|
<header className="md:hidden flex items-center justify-between px-4 py-3 bg-[#0A0A0E] text-white border-b border-slate-800 sticky top-0 z-30 shadow-md">
|
|
<button
|
|
type="button"
|
|
onClick={() => setIsMobileMenuOpen(true)}
|
|
className="p-2 -ml-2 rounded-xl text-slate-300 hover:text-white hover:bg-slate-800/80 transition-colors cursor-pointer border border-transparent hover:border-slate-700/60"
|
|
aria-label="Open navigation menu"
|
|
>
|
|
<Menu className="h-5 w-5" />
|
|
</button>
|
|
|
|
<div className="flex items-center gap-2">
|
|
<div className="h-7 w-7 rounded-lg bg-gradient-to-tr from-indigo-500 to-cyan-400 flex items-center justify-center shadow-xs">
|
|
<Sparkles className="h-3.5 w-3.5 text-white" />
|
|
</div>
|
|
<div>
|
|
<h1 className="text-xs font-black tracking-tight text-white leading-tight">ACUPEDIA</h1>
|
|
<p className="text-[7px] text-slate-400 font-bold tracking-widest uppercase leading-none">ADMIN CONSOLE</p>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Current Tab Indicator Badge on Mobile */}
|
|
<div className="text-[11px] font-bold text-indigo-400 bg-indigo-950/80 border border-indigo-500/30 px-2.5 py-0.5 rounded-full capitalize max-w-[120px] truncate">
|
|
{adminSubTab === 'users_subscriptions' ? 'Subscriptions' : adminSubTab.replace('_', ' ')}
|
|
</div>
|
|
</header>
|
|
|
|
{/* 1. Collapsible & Responsive Sidebar */}
|
|
<AdminSidebar
|
|
loggedInUser={loggedInUser}
|
|
activeTab={adminSubTab}
|
|
onSelectTab={setAdminSubTab}
|
|
counts={{
|
|
modules: adminModulesList.length,
|
|
plans: adminPlansList.length,
|
|
coupons: adminCouponsList.length,
|
|
customers: practitionersList.length,
|
|
subscriptions: usersSubscriptions.length,
|
|
payments: rzpPayments.length,
|
|
admins: adminsList.length,
|
|
}}
|
|
isCollapsed={isSidebarCollapsed}
|
|
onToggleCollapse={() => {
|
|
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 */}
|
|
<main className="flex-1 overflow-y-auto w-full min-w-0 p-4 sm:p-6 lg:p-8">
|
|
<div className="max-w-[1600px] mx-auto space-y-6 flex-1 w-full">
|
|
{/* Sleek Top Header Bar */}
|
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-2 border-b border-slate-200">
|
|
<div className="space-y-1">
|
|
<div className="inline-flex items-center gap-1.5 bg-indigo-50 border border-indigo-200 text-indigo-700 text-xs px-2.5 py-0.5 rounded-full font-bold">
|
|
<Database className="h-3 w-3 animate-pulse" /> Backoffice Controls
|
|
</div>
|
|
<h2 className="text-xl sm:text-2xl font-black text-slate-900 tracking-tight">
|
|
{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'}
|
|
</h2>
|
|
<p className="text-slate-500 text-xs font-semibold">
|
|
{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.'}
|
|
</p>
|
|
</div>
|
|
|
|
{/* Top Quick Actions (Force-Sync Gateway & Refresh) */}
|
|
<div className="flex items-center gap-2.5 shrink-0">
|
|
<button
|
|
type="button"
|
|
onClick={handleForceSync}
|
|
disabled={adminSyncing || !loggedInUser}
|
|
className="px-3.5 py-2 rounded-xl bg-cyan-600 hover:bg-cyan-500 disabled:bg-slate-200 disabled:text-slate-400 text-xs font-bold text-white transition-all flex items-center gap-2 cursor-pointer shadow-sm hover:shadow active:scale-[0.98]"
|
|
title="Pulls active payment states from Razorpay and resolves pending database rows"
|
|
>
|
|
<RefreshCcw className={`h-3.5 w-3.5 ${adminSyncing ? 'animate-spin' : ''}`} />
|
|
<span>{adminSyncing ? 'Syncing...' : 'Force-Sync Gateway'}</span>
|
|
</button>
|
|
|
|
<button
|
|
type="button"
|
|
onClick={fetchRazorpayAdminData}
|
|
disabled={adminDataLoading}
|
|
className="px-3.5 py-2 rounded-xl bg-white border border-slate-200 hover:bg-slate-50 text-slate-700 text-xs font-bold transition-all flex items-center gap-2 cursor-pointer shadow-sm hover:shadow active:scale-[0.98] disabled:opacity-50"
|
|
title="Refresh current administrative data"
|
|
>
|
|
<RefreshCw className={`h-3.5 w-3.5 ${adminDataLoading ? 'animate-spin' : ''}`} />
|
|
<span>Refresh</span>
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* SubTab Content View */}
|
|
<div className="bg-white border border-slate-200 rounded-2xl shadow-sm p-4 sm:p-6 overflow-hidden">
|
|
{adminSubTab === 'overview' && (
|
|
<SyncOverview
|
|
stats={{
|
|
totalUsers: practitionersList.length + adminsList.length,
|
|
subscriptions: usersSubscriptions.length,
|
|
superAdmins: adminsList.length,
|
|
payments: rzpPayments.length,
|
|
}}
|
|
adminLogs={adminLogs}
|
|
onClearLogs={() => setAdminLogs([])}
|
|
/>
|
|
)}
|
|
|
|
{adminSubTab === 'modules' && (
|
|
<ModulesTab
|
|
modules={adminModulesList}
|
|
searchQuery={moduleSearchQuery}
|
|
statusFilter={moduleStatusFilter}
|
|
categoryFilter={moduleCategoryFilter}
|
|
currentPage={modulesPage}
|
|
perPage={modulesPerPage}
|
|
onSearchChange={setModuleSearchQuery}
|
|
onStatusFilterChange={setModuleStatusFilter}
|
|
onCategoryFilterChange={setModuleCategoryFilter}
|
|
onPageChange={setModulesPage}
|
|
onPerPageChange={setModulesPerPage}
|
|
onToggleStatus={handleToggleModuleStatus}
|
|
onEditModule={handleOpenEditModule}
|
|
/>
|
|
)}
|
|
|
|
{adminSubTab === 'module_builder' && (
|
|
<ModuleBuilderTab />
|
|
)}
|
|
|
|
{adminSubTab === 'plans' && (
|
|
<PlansTab
|
|
plans={adminPlansList}
|
|
searchQuery={planSearchQuery}
|
|
typeFilter={planTypeFilter}
|
|
currentPage={plansPage}
|
|
perPage={plansPerPage}
|
|
onSearchChange={setPlanSearchQuery}
|
|
onTypeFilterChange={setPlanTypeFilter}
|
|
onPageChange={setPlansPage}
|
|
onPerPageChange={setPlansPerPage}
|
|
onOpenCreatePlan={handleOpenCreatePlan}
|
|
onTogglePlanStatus={handleTogglePlanStatus}
|
|
onOpenEditPrice={handleOpenEditPrice}
|
|
/>
|
|
)}
|
|
|
|
{adminSubTab === 'coupons' && (
|
|
<CouponsTab
|
|
coupons={adminCouponsList}
|
|
filterStatus={couponFilterStatus}
|
|
searchQuery={couponSearchQuery}
|
|
currentPage={couponsPage}
|
|
perPage={couponsPerPage}
|
|
onFilterStatusChange={setCouponFilterStatus}
|
|
onSearchChange={setCouponSearchQuery}
|
|
onPageChange={setCouponsPage}
|
|
onPerPageChange={setCouponsPerPage}
|
|
onOpenCreateCoupon={handleOpenCreateCoupon}
|
|
onOpenEditCoupon={handleOpenEditCoupon}
|
|
onToggleStatus={handleToggleCouponStatus}
|
|
onDeleteCoupon={handleDeleteCoupon}
|
|
/>
|
|
)}
|
|
|
|
{adminSubTab === 'customers' && (
|
|
<CustomersTab
|
|
customers={practitionersList}
|
|
currentPage={customersPage}
|
|
perPage={customersPerPage}
|
|
onPageChange={setCustomersPage}
|
|
onPerPageChange={setCustomersPerPage}
|
|
onOpenCustomerDrawer={handleOpenCustomerDrawer}
|
|
/>
|
|
)}
|
|
|
|
{adminSubTab === 'users_subscriptions' && (
|
|
<SubscriptionsTab
|
|
subscriptions={usersSubscriptions}
|
|
filterCustomerName={filterCustomerName}
|
|
filterModuleName={filterModuleName}
|
|
currentPage={subscriptionsPage}
|
|
perPage={subscriptionsPerPage}
|
|
onFilterCustomerChange={setFilterCustomerName}
|
|
onFilterModuleChange={setFilterModuleName}
|
|
onPageChange={setSubscriptionsPage}
|
|
onPerPageChange={setSubscriptionsPerPage}
|
|
/>
|
|
)}
|
|
|
|
{adminSubTab === 'payments' && (
|
|
<PaymentsTab
|
|
payments={rzpPayments}
|
|
currentPage={paymentsPage}
|
|
perPage={paymentsPerPage}
|
|
downloadingId={downloadingInvoiceId}
|
|
sharingId={sharingInvoiceId}
|
|
onPageChange={setPaymentsPage}
|
|
onPerPageChange={setPaymentsPerPage}
|
|
onDownloadInvoice={handleDownloadInvoice}
|
|
onShareInvoice={handleShareInvoice}
|
|
/>
|
|
)}
|
|
|
|
{adminSubTab === 'admins' && (
|
|
<AdminsTab
|
|
admins={adminsList}
|
|
name={createAdminName}
|
|
email={createAdminEmail}
|
|
password={createAdminPassword}
|
|
loading={adminActionLoading}
|
|
onNameChange={setCreateAdminName}
|
|
onEmailChange={setCreateAdminEmail}
|
|
onPasswordChange={setCreateAdminPassword}
|
|
onCreateAdmin={handleCreateAdmin}
|
|
/>
|
|
)}
|
|
|
|
{adminSubTab === 'database' && (
|
|
<DatabaseBackupTab
|
|
dbInfo={dbInfo}
|
|
downloadingType={dbBackupDownloading}
|
|
successMessage={dbBackupSuccess}
|
|
errorMessage={dbBackupError}
|
|
loading={adminDataLoading}
|
|
onRefresh={fetchRazorpayAdminData}
|
|
onDownloadBackup={handleDownloadBackup}
|
|
/>
|
|
)}
|
|
|
|
{adminSubTab === 'reports' && (
|
|
<ReportsExportTab
|
|
dateFilter={reportDateFilter}
|
|
startDate={reportStartDate}
|
|
endDate={reportEndDate}
|
|
downloadingReport={reportDownloading}
|
|
successMessage={reportExportSuccess}
|
|
errorMessage={reportExportError}
|
|
totalUsers={practitionersList.length + adminsList.length}
|
|
totalPayments={rzpPayments.length}
|
|
totalSubscriptions={usersSubscriptions.length}
|
|
totalCoupons={adminCouponsList.length}
|
|
onDateFilterChange={setReportDateFilter}
|
|
onStartDateChange={setReportStartDate}
|
|
onEndDateChange={setReportEndDate}
|
|
onDownloadReport={handleDownloadReport}
|
|
/>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</main>
|
|
|
|
{/* Global Modals & Drawers */}
|
|
<EditModuleModal
|
|
module={selectedEditModule}
|
|
name={editModuleName}
|
|
description={editModuleDesc}
|
|
category={editModuleCategory}
|
|
saving={editModuleSaving}
|
|
onNameChange={setEditModuleName}
|
|
onDescriptionChange={setEditModuleDesc}
|
|
onCategoryChange={setEditModuleCategory}
|
|
onSave={handleSaveModuleDetails}
|
|
onClose={() => setSelectedEditModule(null)}
|
|
/>
|
|
|
|
<CreatePlanModal
|
|
show={showCreatePlanModal}
|
|
code={createPlanCode}
|
|
name={createPlanName}
|
|
desc={createPlanDesc}
|
|
badge={createPlanBadge}
|
|
heading={createPlanHeading}
|
|
subtitle={createPlanSubtitle}
|
|
type={createPlanType}
|
|
duration={createPlanDuration}
|
|
priceInr={createPlanPriceInr}
|
|
priceUsd={createPlanPriceUsd}
|
|
selectedModuleIds={createPlanModuleIds}
|
|
allModules={adminModulesList}
|
|
saving={createPlanSaving}
|
|
error={createPlanError}
|
|
onCodeChange={setCreatePlanCode}
|
|
onNameChange={setCreatePlanName}
|
|
onDescChange={setCreatePlanDesc}
|
|
onBadgeChange={setCreatePlanBadge}
|
|
onHeadingChange={setCreatePlanHeading}
|
|
onSubtitleChange={setCreatePlanSubtitle}
|
|
onTypeChange={setCreatePlanType}
|
|
onDurationChange={setCreatePlanDuration}
|
|
onPriceInrChange={setCreatePlanPriceInr}
|
|
onPriceUsdChange={setCreatePlanPriceUsd}
|
|
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)}
|
|
/>
|
|
|
|
<EditPriceModal
|
|
plan={selectedEditPricePlan}
|
|
name={editPlanName}
|
|
desc={editPlanDesc}
|
|
badge={editPlanBadge}
|
|
heading={editPlanHeading}
|
|
subtitle={editPlanSubtitle}
|
|
priceInr={editPriceInr}
|
|
priceUsd={editPriceUsd}
|
|
saving={editPriceSaving}
|
|
onNameChange={setEditPlanName}
|
|
onDescChange={setEditPlanDesc}
|
|
onBadgeChange={setEditPlanBadge}
|
|
onHeadingChange={setEditPlanHeading}
|
|
onSubtitleChange={setEditPlanSubtitle}
|
|
onPriceInrChange={setEditPriceInr}
|
|
onPriceUsdChange={setEditPriceUsd}
|
|
onSave={handleSavePlanPrice}
|
|
onClose={() => setSelectedEditPricePlan(null)}
|
|
/>
|
|
|
|
<CouponModal
|
|
mode={couponModalMode}
|
|
data={couponFormData}
|
|
plans={adminPlansList}
|
|
modules={adminModulesList}
|
|
saving={couponSaving}
|
|
onChange={(field, val) => setCouponFormData((prev) => ({ ...prev, [field]: val }))}
|
|
onSave={handleSaveCoupon}
|
|
onClose={() => setCouponModalMode(null)}
|
|
/>
|
|
|
|
<CustomerDrawer
|
|
customerId={selectedCustomerDrawerId}
|
|
customerData={customerDrawerData}
|
|
loading={customerDrawerLoading}
|
|
statusToggling={customerStatusToggling}
|
|
activeTab={customerDrawerTab}
|
|
onTabChange={setCustomerDrawerTab}
|
|
onToggleStatus={handleToggleCustomerActiveStatus}
|
|
onClose={() => {
|
|
setSelectedCustomerDrawerId(null);
|
|
setCustomerDrawerData(null);
|
|
}}
|
|
onDownloadInvoice={handleDownloadInvoice}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|