mirror of
https://github.com/allankoechke/mantisbase-admin.git
synced 2026-11-30 17:15:58 +00:00
387 lines
14 KiB
TypeScript
387 lines
14 KiB
TypeScript
"use client"
|
|
|
|
import * as React from "react"
|
|
import { Table, Settings, Shield, LogOut, FileText, RefreshCw, ExternalLink, AlertTriangle } from "lucide-react"
|
|
import { Logo } from "./logo"
|
|
import {
|
|
Sidebar,
|
|
SidebarContent,
|
|
SidebarFooter,
|
|
SidebarGroup,
|
|
SidebarGroupContent,
|
|
SidebarGroupLabel,
|
|
SidebarHeader,
|
|
SidebarMenu,
|
|
SidebarMenuButton,
|
|
SidebarMenuItem,
|
|
SidebarProvider,
|
|
} from "@/components/ui/sidebar"
|
|
import { Button } from "@/components/ui/button"
|
|
import {
|
|
Tooltip,
|
|
TooltipContent,
|
|
TooltipProvider,
|
|
TooltipTrigger,
|
|
} from "@/components/ui/tooltip"
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from "@/components/ui/dialog"
|
|
import { ApiClient, SYS_ADMINS_API, type TableMetadata, type Admin } from "@/lib/api"
|
|
import { applySchemaListMigration } from "@/lib/schema-migration"
|
|
import { DatabaseSection } from "./database/database-section"
|
|
import { AdminsSection } from "./admins/admins-section"
|
|
import { SettingsSection } from "./settings/settings-section"
|
|
import { LogsSection } from "./logs/logs-section"
|
|
import { SyncSection } from "./sync/sync-section"
|
|
import { useToast } from "@/hooks/use-toast"
|
|
import { ThemeToggle } from "./theme-toggle"
|
|
import { useNavigate, useLocation } from "react-router-dom"
|
|
import { useAuth } from "@/lib/auth"
|
|
import { getDashboardSection, ROUTES } from "@/lib/routes"
|
|
import { cn } from "@/lib/utils"
|
|
|
|
export function AdminDashboard() {
|
|
const [mounted, setMounted] = React.useState(false)
|
|
const [tables, setTables] = React.useState<TableMetadata[]>([])
|
|
const [admins, setAdmins] = React.useState<Admin[]>([])
|
|
const [loading, setLoading] = React.useState(true)
|
|
const [authErrorDialog, setAuthErrorDialog] = React.useState(false)
|
|
const [authErrorReason, setAuthErrorReason] = React.useState("") // Auth error reason
|
|
const { toast } = useToast()
|
|
const navigate = useNavigate()
|
|
const location = useLocation()
|
|
const { logout, refreshSession } = useAuth()
|
|
|
|
const showError = React.useCallback(
|
|
(error: string, type: "error" | "warning" = "error") => {
|
|
try {
|
|
// Prevent error toasts for auth errors (401/403) - these are handled by the auth dialog
|
|
const errorLower = error.toLowerCase()
|
|
if (
|
|
errorLower.includes("unauthorized") ||
|
|
errorLower.includes("forbidden") ||
|
|
errorLower.includes("auth") ||
|
|
errorLower.includes("403") ||
|
|
errorLower.includes("401")
|
|
) {
|
|
return // Don't show toast for auth errors, handle with dialog
|
|
}
|
|
|
|
toast({
|
|
variant: type === "error" ? "destructive" : "default",
|
|
title: type === "error" ? "Error" : "Warning",
|
|
description: error,
|
|
duration: 10000,
|
|
})
|
|
} catch (toastError) {
|
|
console.warn("Failed to show error toast:", toastError)
|
|
}
|
|
},
|
|
[toast],
|
|
)
|
|
|
|
const handleUnauthorized = React.useCallback(async (reason?: string | "") => {
|
|
try {
|
|
const stillAuthenticated = await refreshSession()
|
|
if (stillAuthenticated) {
|
|
return
|
|
}
|
|
|
|
setAuthErrorReason(reason || "")
|
|
setAuthErrorDialog(true)
|
|
} catch (error) {
|
|
console.warn("Failed to handle unauthorized:", error)
|
|
}
|
|
}, [refreshSession])
|
|
|
|
const [apiClient, setApiClient] = React.useState(
|
|
() => new ApiClient(handleUnauthorized, showError),
|
|
)
|
|
|
|
React.useEffect(() => {
|
|
setMounted(true)
|
|
loadData()
|
|
}, [])
|
|
|
|
// Update API client when mode or settings change
|
|
React.useEffect(() => {
|
|
const newApiClient = new ApiClient(handleUnauthorized, showError)
|
|
setApiClient(newApiClient)
|
|
}, [handleUnauthorized, showError])
|
|
|
|
const loadAdmins = React.useCallback(async () => {
|
|
if (!apiClient) return
|
|
|
|
try {
|
|
const adminsData = await apiClient.call<any>(`${SYS_ADMINS_API}`)
|
|
|
|
// Ensure adminsData is an array - handle paginated response
|
|
let adminsArray: Admin[] = []
|
|
if (Array.isArray(adminsData)) {
|
|
// Fallback: if response is directly an array (shouldn't happen with new API)
|
|
adminsArray = adminsData
|
|
} else if (adminsData?.items && Array.isArray(adminsData.items)) {
|
|
// Paginated response: extract items from data object
|
|
adminsArray = adminsData.items
|
|
} else if (adminsData?.data?.items && Array.isArray(adminsData.data.items)) {
|
|
// If data is nested
|
|
adminsArray = adminsData.data.items
|
|
}
|
|
setAdmins(adminsArray)
|
|
} catch (error) {
|
|
console.error("Failed to load admins:", error)
|
|
}
|
|
}, [apiClient])
|
|
|
|
// Load admins when navigating to the admins page
|
|
React.useEffect(() => {
|
|
if (getDashboardSection(location.pathname) === "admins") {
|
|
loadAdmins()
|
|
}
|
|
}, [location.pathname, loadAdmins])
|
|
|
|
const loadData = async () => {
|
|
try {
|
|
setLoading(true)
|
|
|
|
// Only load tables on initial load
|
|
const tablesData = await apiClient.call<any>("/api/v1/schemas")
|
|
|
|
// Ensure tablesData is an array - handle different response structures
|
|
let tablesArray: TableMetadata[] = []
|
|
if (Array.isArray(tablesData)) {
|
|
tablesArray = tablesData
|
|
} else if (tablesData?.data && Array.isArray(tablesData.data)) {
|
|
tablesArray = tablesData.data
|
|
}
|
|
|
|
const migratedTables = await applySchemaListMigration(apiClient, tablesArray)
|
|
setTables(migratedTables)
|
|
} catch (error) {
|
|
console.error("Failed to load data:", error)
|
|
} finally {
|
|
setLoading(false)
|
|
}
|
|
}
|
|
|
|
|
|
const handleLogout = async () => {
|
|
try {
|
|
await logout()
|
|
navigate(ROUTES.login, { replace: true })
|
|
} catch (error) {
|
|
console.warn("Failed to logout:", error)
|
|
}
|
|
}
|
|
|
|
const handleAuthErrorLogin = () => {
|
|
try {
|
|
setAuthErrorDialog(false)
|
|
// Always navigate to login and discard token, regardless of button clicked
|
|
handleLogout()
|
|
} catch (error) {
|
|
console.warn("Failed to handle auth error login:", error)
|
|
}
|
|
}
|
|
|
|
const handleAuthErrorDialogClose = (open: boolean) => {
|
|
// If dialog is being closed (either by Cancel or X button), navigate to login
|
|
if (!open) {
|
|
handleAuthErrorLogin()
|
|
}
|
|
}
|
|
|
|
|
|
const sidebarItems = [
|
|
{
|
|
title: "Entities",
|
|
icon: Table,
|
|
id: "entities",
|
|
path: ROUTES.entities,
|
|
},
|
|
{
|
|
title: "Logs",
|
|
icon: FileText,
|
|
id: "logs",
|
|
path: ROUTES.logs,
|
|
},
|
|
{
|
|
title: "Admins",
|
|
icon: Shield,
|
|
id: "admins",
|
|
path: ROUTES.admins,
|
|
},
|
|
{
|
|
title: "Settings",
|
|
icon: Settings,
|
|
id: "settings",
|
|
path: ROUTES.settings,
|
|
},
|
|
]
|
|
|
|
const currentSection = getDashboardSection(location.pathname)
|
|
|
|
if (!mounted) {
|
|
return (
|
|
<div className="flex min-h-screen w-full items-center justify-center">
|
|
<div className="text-center">
|
|
<div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"></div>
|
|
<p className="text-muted-foreground">Loading MantisBase Admin Dashboard...</p>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
return (
|
|
<SidebarProvider open={false}>
|
|
<div className="flex min-h-screen w-full">
|
|
<Sidebar collapsible="icon" className="border-r" style={{width: "4rem", minWidth: "4rem", maxWidth: "4rem", "--sidebar-width": "4rem", "--sidebar-width-icon": "4rem"} as React.CSSProperties}>
|
|
<SidebarHeader className="border-b p-0 w-full">
|
|
<div className="flex h-16 w-full items-center justify-center">
|
|
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary text-primary-foreground">
|
|
<Logo className="h-6 w-6" size={24} />
|
|
</div>
|
|
</div>
|
|
</SidebarHeader>
|
|
<SidebarContent className="px-0 py-2 w-full">
|
|
<SidebarMenu className="space-y-1 w-full">
|
|
{sidebarItems.map((item) => (
|
|
<SidebarMenuItem key={item.id} className="w-full">
|
|
<TooltipProvider>
|
|
<Tooltip>
|
|
<TooltipTrigger asChild>
|
|
<SidebarMenuButton
|
|
onClick={() => navigate(item.path)}
|
|
isActive={currentSection === item.id}
|
|
style={{ height: "4rem", minHeight: "4rem" }}
|
|
className={cn(
|
|
"w-full justify-center p-0 mx-0 rounded-none border-l-2 border-transparent min-w-full",
|
|
currentSection === item.id && "border-l-primary bg-accent"
|
|
)}
|
|
>
|
|
<item.icon className={cn(
|
|
"h-6 w-6",
|
|
currentSection === item.id && "text-primary"
|
|
)} />
|
|
<span className="sr-only">{item.title}</span>
|
|
</SidebarMenuButton>
|
|
</TooltipTrigger>
|
|
<TooltipContent side="right">
|
|
<p>{item.title}</p>
|
|
</TooltipContent>
|
|
</Tooltip>
|
|
</TooltipProvider>
|
|
</SidebarMenuItem>
|
|
))}
|
|
</SidebarMenu>
|
|
</SidebarContent>
|
|
<SidebarFooter className="border-t p-0 w-full">
|
|
<SidebarMenu className="space-y-1 w-full">
|
|
<SidebarMenuItem className="w-full">
|
|
<TooltipProvider>
|
|
<Tooltip>
|
|
<TooltipTrigger asChild>
|
|
<div className="w-full">
|
|
<ThemeToggle iconOnly />
|
|
</div>
|
|
</TooltipTrigger>
|
|
<TooltipContent side="right">
|
|
<p>Toggle Theme</p>
|
|
</TooltipContent>
|
|
</Tooltip>
|
|
</TooltipProvider>
|
|
</SidebarMenuItem>
|
|
<SidebarMenuItem className="w-full">
|
|
<TooltipProvider>
|
|
<Tooltip>
|
|
<TooltipTrigger asChild>
|
|
<SidebarMenuButton asChild style={{ height: "4rem", minHeight: "4rem" }} className="w-full justify-center p-0 mx-0 rounded-none min-w-full">
|
|
<a href="https://docs.mantisbase.com" target="_blank" rel="noopener noreferrer" className="w-full flex items-center justify-center">
|
|
<ExternalLink className="h-6 w-6" />
|
|
<span className="sr-only">Documentation</span>
|
|
</a>
|
|
</SidebarMenuButton>
|
|
</TooltipTrigger>
|
|
<TooltipContent side="right">
|
|
<p>Documentation</p>
|
|
</TooltipContent>
|
|
</Tooltip>
|
|
</TooltipProvider>
|
|
</SidebarMenuItem>
|
|
<SidebarMenuItem className="w-full">
|
|
<TooltipProvider>
|
|
<Tooltip>
|
|
<TooltipTrigger asChild>
|
|
<SidebarMenuButton onClick={handleLogout} className="h-12 w-full justify-center p-0 mx-0 rounded-none min-w-full">
|
|
<LogOut className="h-6 w-6" />
|
|
<span className="sr-only">Logout</span>
|
|
</SidebarMenuButton>
|
|
</TooltipTrigger>
|
|
<TooltipContent side="right">
|
|
<p>Logout</p>
|
|
</TooltipContent>
|
|
</Tooltip>
|
|
</TooltipProvider>
|
|
</SidebarMenuItem>
|
|
</SidebarMenu>
|
|
</SidebarFooter>
|
|
</Sidebar>
|
|
|
|
<div className="flex-1">
|
|
<main className="pl-4">
|
|
{loading ? (
|
|
<div className="flex items-center justify-center h-64">
|
|
<div className="text-center">
|
|
<div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"></div>
|
|
<p className="text-muted-foreground">Loading...</p>
|
|
</div>
|
|
</div>
|
|
) : (
|
|
<>
|
|
{currentSection === "entities" && (
|
|
<DatabaseSection apiClient={apiClient} tables={tables} onTablesUpdate={setTables} />
|
|
)}
|
|
{currentSection === "admins" && (
|
|
<AdminsSection admins={admins} apiClient={apiClient} onAdminsUpdate={setAdmins} />
|
|
)}
|
|
{currentSection === "logs" && <LogsSection apiClient={apiClient} />}
|
|
{currentSection === "sync" && <SyncSection />}
|
|
{currentSection === "settings" && <SettingsSection apiClient={apiClient} />}
|
|
</>
|
|
)}
|
|
</main>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Auth Error Dialog */}
|
|
<Dialog open={authErrorDialog} onOpenChange={handleAuthErrorDialogClose}>
|
|
<DialogContent>
|
|
<DialogHeader>
|
|
<DialogTitle className="flex items-center gap-2">
|
|
<AlertTriangle className="h-5 w-5 text-destructive" />
|
|
Authentication Required
|
|
</DialogTitle>
|
|
<DialogDescription>
|
|
Your session has expired or you don't have permission to access this resource. You will be redirected to the login page.
|
|
</DialogDescription>
|
|
{authErrorReason.length > 0 && (
|
|
<div className="mt-4 p-3 rounded-md bg-muted border border-muted-foreground/20">
|
|
<p className="text-xs font-medium text-muted-foreground mb-1">API Response:</p>
|
|
<p className="text-sm text-foreground font-mono">{authErrorReason}</p>
|
|
</div>
|
|
)}
|
|
</DialogHeader>
|
|
<DialogFooter>
|
|
<Button onClick={handleAuthErrorLogin}>Go to Login</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
</SidebarProvider>
|
|
)
|
|
}
|