diff --git a/app/page.tsx b/app/page.tsx index 2fe72c6..57a6ef2 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -5,25 +5,61 @@ import { LoginForm } from "@/components/login-form" import { AdminDashboard } from "@/components/admin-dashboard" import { Toaster } from "@/components/ui/toaster" import { ThemeProvider } from "@/components/theme-provider" +import { AppStateProvider } from "@/lib/app-state" +import { useRouter } from "@/lib/router" export default function Page() { const [token, setToken] = React.useState(null) const [mounted, setMounted] = React.useState(false) + const { route, navigate } = useRouter() React.useEffect(() => { setMounted(true) - const savedToken = localStorage.getItem("admin_token") - if (savedToken) { - setToken(savedToken) + + // Get saved token safely + try { + const savedToken = localStorage.getItem("admin_token") + if (savedToken) { + setToken(savedToken) + } + } catch (error) { + console.warn("Failed to get saved token:", error) } }, []) + React.useEffect(() => { + if (mounted) { + try { + const currentPath = route.path + + if (!token && currentPath !== "/login") { + navigate("/login") + } else if (token && currentPath === "/login") { + navigate("/tables") + } + } catch (error) { + console.warn("Failed to handle route change:", error) + } + } + }, [token, route.path, mounted, navigate]) + const handleLogin = (newToken: string) => { - setToken(newToken) + try { + setToken(newToken) + navigate("/tables") + } catch (error) { + console.warn("Failed to handle login:", error) + } } const handleLogout = () => { - setToken(null) + try { + setToken(null) + localStorage.removeItem("admin_token") + navigate("/login") + } catch (error) { + console.warn("Failed to handle logout:", error) + } } if (!mounted) { @@ -39,8 +75,14 @@ export default function Page() { return ( - {!token ? : } - + + {route.path === "/login" || !token ? ( + + ) : ( + + )} + + ) } diff --git a/components/admin-dashboard.tsx b/components/admin-dashboard.tsx index 1e997a5..8181991 100644 --- a/components/admin-dashboard.tsx +++ b/components/admin-dashboard.tsx @@ -1,7 +1,7 @@ "use client" import * as React from "react" -import { Table, Settings, Shield, LogOut, FileText, RefreshCw, ExternalLink } from "lucide-react" +import { Table, Settings, Shield, LogOut, FileText, RefreshCw, ExternalLink, AlertTriangle } from "lucide-react" import { Sidebar, SidebarContent, @@ -15,6 +15,15 @@ import { SidebarMenuItem, SidebarProvider, } from "@/components/ui/sidebar" +import { Button } from "@/components/ui/button" +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog" import { ApiClient, type TableMetadata, type Admin, type AppSettings } from "@/lib/api" import { DatabaseSection } from "./database/database-section" import { AdminsSection } from "./admins/admins-section" @@ -23,6 +32,8 @@ import { LogsSection } from "./logs/logs-section" import { SyncSection } from "./sync/sync-section" import { useToast } from "@/hooks/use-toast" import { ThemeToggle } from "./theme-toggle" +import { useRouter } from "@/lib/router" +import { useAppState, type AppMode } from "@/lib/app-state" interface AdminDashboardProps { token: string @@ -31,53 +42,118 @@ interface AdminDashboardProps { export function AdminDashboard({ token, onLogout }: AdminDashboardProps) { const [mounted, setMounted] = React.useState(false) - const [activeSection, setActiveSection] = React.useState("tables") const [tables, setTables] = React.useState([]) const [admins, setAdmins] = React.useState([]) const [loading, setLoading] = React.useState(true) - const { toast } = useToast() const [settings, setSettings] = React.useState(null) + const [authErrorDialog, setAuthErrorDialog] = React.useState(false) + const { toast } = useToast() + const { route, navigate } = useRouter() + const { mode } = useAppState() const showError = React.useCallback( (error: string, type: "error" | "warning" = "error") => { - toast({ - variant: type === "error" ? "destructive" : "default", - title: type === "error" ? "Error" : "Warning", - description: error, - }) + try { + // Prevent error loops by checking if error is already being shown + if (error.includes("Unauthorized") || error.includes("auth")) { + return // Don't show toast for auth errors, handle with dialog + } + + toast({ + variant: type === "error" ? "destructive" : "default", + title: type === "error" ? "Error" : "Warning", + description: error, + }) + } catch (toastError) { + console.warn("Failed to show error toast:", toastError) + } }, [toast], ) - const apiClient = React.useMemo(() => new ApiClient(token, onLogout, showError), [token, onLogout, showError]) + const handleUnauthorized = React.useCallback(() => { + try { + setAuthErrorDialog(true) + } catch (error) { + console.warn("Failed to handle unauthorized:", error) + } + }, []) + + const [apiClient, setApiClient] = React.useState( + () => new ApiClient(token, handleUnauthorized, mode, settings?.baseUrl, showError), + ) React.useEffect(() => { setMounted(true) loadData() }, []) + // Update API client when mode or settings change + React.useEffect(() => { + const newApiClient = new ApiClient(token, handleUnauthorized, mode, settings?.baseUrl, showError) + setApiClient(newApiClient) + }, [mode, settings?.baseUrl, token, handleUnauthorized, showError]) + const loadData = async () => { try { setLoading(true) + console.log("Loading dashboard data...") + const [tablesData, adminsData, settingsData] = await Promise.all([ apiClient.call("/api/v1/tables"), apiClient.call("/api/v1/admins"), apiClient.call("/api/v1/settings"), ]) + console.log("Data loaded:", { tablesData, adminsData, settingsData }) + setTables(tablesData) setAdmins(adminsData) setSettings(settingsData) } catch (error) { console.error("Failed to load data:", error) + // Set default settings if loading fails + setSettings({ + appName: "Mantis Admin", + baseUrl: "https://api.example.com", + version: "1.2.3", + maintenanceMode: false, + maxFileSize: "10MB", + allowRegistration: true, + emailVerificationRequired: false, + sessionTimeout: 3600, + mode: mode, + }) } finally { setLoading(false) } } const handleLogout = () => { - localStorage.removeItem("admin_token") - onLogout() + try { + localStorage.removeItem("admin_token") + onLogout() + } catch (error) { + console.warn("Failed to logout:", error) + } + } + + const handleAuthErrorLogin = () => { + try { + setAuthErrorDialog(false) + handleLogout() + } catch (error) { + console.warn("Failed to handle auth error login:", error) + } + } + + const handleModeChange = (newMode: AppMode, baseUrl?: string) => { + // Update API client with new mode and base URL + const newApiClient = new ApiClient(token, handleUnauthorized, newMode, baseUrl, showError) + setApiClient(newApiClient) + + // Reload data with new mode + loadData() } const sidebarItems = [ @@ -85,29 +161,47 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) { title: "Tables", icon: Table, id: "tables", + path: "/tables", }, { title: "Admins", icon: Shield, id: "admins", + path: "/admins", }, { title: "Logs", icon: FileText, id: "logs", + path: "/logs", }, { title: "Sync", icon: RefreshCw, id: "sync", + path: "/sync", }, { title: "Settings", icon: Settings, id: "settings", + path: "/settings", }, ] + // Extract the section from the route path safely + const getCurrentSection = () => { + try { + const pathParts = route.path.split("/").filter(Boolean) + return pathParts[0] || "tables" + } catch (error) { + console.warn("Error parsing route:", error) + return "tables" + } + } + + const currentSection = getCurrentSection() + if (!mounted) { return (
@@ -126,7 +220,7 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
- Admin Dashboard + Mantis Admin
@@ -137,9 +231,15 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) { {sidebarItems.map((item) => ( setActiveSection(item.id)} - isActive={activeSection === item.id} - className={activeSection === item.id ? "bg-accent text-accent-foreground" : ""} + onClick={() => { + try { + navigate(item.path) + } catch (error) { + console.warn("Failed to navigate:", error) + } + }} + isActive={currentSection === item.id} + className={currentSection === item.id ? "bg-accent text-accent-foreground" : ""} > {item.title} @@ -189,22 +289,49 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
) : ( <> - {activeSection === "tables" && ( + {currentSection === "tables" && ( )} - {activeSection === "admins" && ( + {currentSection === "admins" && ( )} - {activeSection === "logs" && } - {activeSection === "sync" && } - {activeSection === "settings" && ( - + {currentSection === "logs" && } + {currentSection === "sync" && } + {currentSection === "settings" && ( + )} )} + + {/* Auth Error Dialog */} + + + + + + Authentication Error + + + Your session has expired or you don't have permission to access this resource. Please log in again to + continue. + + + + + + + + ) } diff --git a/components/database/add-table-dialog.tsx b/components/database/add-table-dialog.tsx index aa99d4c..4998e25 100644 --- a/components/database/add-table-dialog.tsx +++ b/components/database/add-table-dialog.tsx @@ -18,14 +18,15 @@ import { } from "@/components/ui/dialog" import { Textarea } from "@/components/ui/textarea" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" -import type { ApiClient, TableMetadata } from "@/lib/api" +import type { ApiClient, TableMetadata, TableField } from "@/lib/api" interface AddTableDialogProps { apiClient: ApiClient onTablesUpdate: (tables: TableMetadata[]) => void + children?: React.ReactNode } -export function AddTableDialog({ apiClient, onTablesUpdate }: AddTableDialogProps) { +export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTableDialogProps) { const [tableType, setTableType] = React.useState<"base" | "auth" | "view">("base") const [tableName, setTableName] = React.useState("") const [columns, setColumns] = React.useState< @@ -37,6 +38,7 @@ export function AddTableDialog({ apiClient, onTablesUpdate }: AddTableDialogProp unique?: boolean isFile?: boolean isSystem?: boolean + required?: boolean }> >([]) const [sqlQuery, setSqlQuery] = React.useState("") @@ -45,10 +47,12 @@ export function AddTableDialog({ apiClient, onTablesUpdate }: AddTableDialogProp const dataTypes = [ "string", - "int", - "bigint", - "double", - "float", + "int8", + "int16", + "int32", + "int64", + "float32", + "float64", "boolean", "date", "datetime", @@ -65,17 +69,17 @@ export function AddTableDialog({ apiClient, onTablesUpdate }: AddTableDialogProp React.useEffect(() => { if (tableType === "base") { setColumns([ - { name: "id", type: "string", primaryKey: true, nullable: false, isSystem: true }, - { name: "created", type: "datetime", primaryKey: false, nullable: false, isSystem: true }, - { name: "updated", type: "datetime", primaryKey: false, nullable: false, isSystem: true }, + { name: "id", type: "string", primaryKey: true, nullable: false, isSystem: true, required: true }, + { name: "created", type: "datetime", primaryKey: false, nullable: false, isSystem: true, required: true }, + { name: "updated", type: "datetime", primaryKey: false, nullable: false, isSystem: true, required: true }, ]) } else if (tableType === "auth") { setColumns([ - { name: "id", type: "string", primaryKey: true, nullable: false, isSystem: true }, - { name: "email", type: "string", primaryKey: false, nullable: false, isSystem: true }, - { name: "password", type: "string", primaryKey: false, nullable: false, isSystem: true }, - { name: "created", type: "datetime", primaryKey: false, nullable: false, isSystem: true }, - { name: "updated", type: "datetime", primaryKey: false, nullable: false, isSystem: true }, + { name: "id", type: "string", primaryKey: true, nullable: false, isSystem: true, required: true }, + { name: "email", type: "string", primaryKey: false, nullable: false, isSystem: true, required: true }, + { name: "password", type: "string", primaryKey: false, nullable: false, isSystem: true, required: true }, + { name: "created", type: "datetime", primaryKey: false, nullable: false, isSystem: true, required: true }, + { name: "updated", type: "datetime", primaryKey: false, nullable: false, isSystem: true, required: true }, ]) } else { setColumns([]) @@ -83,7 +87,10 @@ export function AddTableDialog({ apiClient, onTablesUpdate }: AddTableDialogProp }, [tableType]) const addColumn = () => { - setColumns([...columns, { name: "", type: "string", primaryKey: false, nullable: true, isSystem: false }]) + setColumns([ + ...columns, + { name: "", type: "string", primaryKey: false, nullable: true, isSystem: false, required: false }, + ]) } const removeColumn = (index: number) => { @@ -118,7 +125,18 @@ export function AddTableDialog({ apiClient, onTablesUpdate }: AddTableDialogProp if (tableType === "view") { tableData.sql = sqlQuery } else { - tableData.fields = columns + tableData.fields = columns.map( + (col): TableField => ({ + name: col.name, + type: col.type, + primaryKey: col.primaryKey, + nullable: col.nullable, + unique: col.unique, + isFile: col.isFile, + system: col.isSystem, + required: col.required, + }), + ) } await apiClient.call("/api/v1/tables", { @@ -144,10 +162,12 @@ export function AddTableDialog({ apiClient, onTablesUpdate }: AddTableDialogProp return ( - + {children || ( + + )} diff --git a/components/database/column-visibility-dropdown.tsx b/components/database/column-visibility-dropdown.tsx index d66f626..b7971c1 100644 --- a/components/database/column-visibility-dropdown.tsx +++ b/components/database/column-visibility-dropdown.tsx @@ -28,7 +28,7 @@ export function ColumnVisibilityDropdown({ table, visibleColumns, onVisibilityCh } const showAll = () => { - onVisibilityChange(table.fields?.map((field) => field.name) || []) + onVisibilityChange(table.schema.fields?.map((field) => field.name) || []) } const hideAll = () => { @@ -58,7 +58,7 @@ export function ColumnVisibilityDropdown({ table, visibleColumns, onVisibilityCh - {table.fields?.map((field) => ( + {table.schema.fields?.map((field) => ( (null) const [searchTerm, setSearchTerm] = React.useState("") const [editingTable, setEditingTable] = React.useState(null) const [searchExpanded, setSearchExpanded] = React.useState(false) + const [isRefreshing, setIsRefreshing] = React.useState(false) + const { route, navigate } = useRouter() + + // Check if we're viewing a specific table - safer parsing + const getSelectedTableName = () => { + try { + const pathParts = route.path.split("/").filter(Boolean) + return pathParts.length > 1 && pathParts[0] === "tables" ? pathParts[1] : null + } catch (error) { + console.warn("Error parsing table route:", error) + return null + } + } + + const selectedTableName = getSelectedTableName() const filteredTables = tables.filter((table) => table.name.toLowerCase().includes(searchTerm.toLowerCase())) @@ -39,16 +54,38 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS } const handleTableClick = (tableName: string) => { - setSelectedTable(tableName) + try { + navigate(`/tables/${tableName}`) + } catch (error) { + console.warn("Failed to navigate to table:", error) + } } - if (selectedTable) { - const tableInfo = tables.find((t) => t.name === selectedTable) + const handleRefresh = async () => { + setIsRefreshing(true) + try { + const updatedTables = await apiClient.call("/api/v1/tables") + onTablesUpdate(updatedTables) + } catch (error) { + console.error("Failed to refresh tables:", error) + } finally { + setIsRefreshing(false) + } + } + + if (selectedTableName) { + const tableInfo = tables.find((t) => t.name === selectedTableName) if (tableInfo) { return ( setSelectedTable(null)} + onBack={() => { + try { + navigate("/tables") + } catch (error) { + console.warn("Failed to navigate back:", error) + } + }} apiClient={apiClient} onTableUpdate={(updatedTable) => { const updatedTables = tables.map((t) => (t.id === updatedTable.id ? updatedTable : t)) @@ -82,88 +119,117 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS -
+
+
-
- {filteredTables.map((table) => ( - handleTableClick(table.name)} - > - - -
- - {table.name} - - {table.type} - + {tables.length === 0 && !isRefreshing ? ( + + +
+

No Tables Found

+

+ Get started by creating your first table. Tables are used to store and organize your data. +

+
+ + + + +
+ + + ) : ( +
+ {filteredTables.map((table) => ( + handleTableClick(table.name)} + > + + +
+
+ {table.name} + + {table.type} + + + + + e.stopPropagation()}> + + + + { + e.stopPropagation() + handleTableClick(table.name) + }} + > + + View Details + + { + e.stopPropagation() + setEditingTable(table) + }} + > + + Edit Schema + + { + e.stopPropagation() + handleDeleteTable(table.id) + }} + > + + Delete Table + + + + + +
+
+ Type: + {table.type} +
+
+ Fields: + {table.schema.fields?.length || 0} +
+
+ Created: + {new Date(table.created).toLocaleDateString()} +
- - - e.stopPropagation()}> - - - - { - e.stopPropagation() - setSelectedTable(table.name) - }} - > - - View Details - - { - e.stopPropagation() - setEditingTable(table) - }} - > - - Edit Schema - - { - e.stopPropagation() - handleDeleteTable(table.id) - }} - > - - Delete Table - - - - - -
-
- Type: - {table.type} -
-
- Fields: - {table.fields?.length || 0} -
-
- Created: - {new Date(table.created).toLocaleDateString()} -
-
-
- - ))} - +
+ + ))} + + )} {editingTable && ( { - return ["id", "created", "updated"].includes(fieldName) + const isSystemField = (field: any) => { + return field.system === true } const handleClose = () => { @@ -96,7 +96,7 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
- {table.fields?.map((field) => ( + {table.schema.fields?.map((field) => (
diff --git a/components/database/edit-schema-dialog.tsx b/components/database/edit-schema-dialog.tsx index 7784df1..31db79d 100644 --- a/components/database/edit-schema-dialog.tsx +++ b/components/database/edit-schema-dialog.tsx @@ -26,7 +26,7 @@ interface EditSchemaDialogProps { } export function EditSchemaDialog({ table, apiClient, onClose, onTableUpdate }: EditSchemaDialogProps) { - const [columns, setColumns] = React.useState(table.fields || []) + const [columns, setColumns] = React.useState(table.schema.fields || []) const [isLoading, setIsLoading] = React.useState(false) const dataTypes = [ @@ -49,13 +49,12 @@ export function EditSchemaDialog({ table, apiClient, onClose, onTableUpdate }: E ] const addColumn = () => { - setColumns([...columns, { name: "", type: "string", primaryKey: false, nullable: true }]) + setColumns([...columns, { name: "", type: "string", primaryKey: false, required: false, system: false }]) } const removeColumn = (index: number) => { const column = columns[index] - const isSystemColumn = ["id", "created", "updated", "email", "password"].includes(column.name) - if (columns.length > 1 && !isSystemColumn) { + if (columns.length > 1 && !column.system) { setColumns(columns.filter((_, i) => i !== index)) } } @@ -70,7 +69,7 @@ export function EditSchemaDialog({ table, apiClient, onClose, onTableUpdate }: E try { const updatedTable = await apiClient.call(`/api/v1/tables/${table.id}`, { method: "PATCH", - body: JSON.stringify({ fields: columns }), + body: JSON.stringify({ schema: { fields: columns } }), }) onTableUpdate(updatedTable) } catch (error) { @@ -80,8 +79,8 @@ export function EditSchemaDialog({ table, apiClient, onClose, onTableUpdate }: E } } - const isSystemColumn = (columnName: string) => { - return ["id", "created", "updated", "email", "password"].includes(columnName) + const isSystemColumn = (column: any) => { + return column.system } return ( @@ -109,7 +108,7 @@ export function EditSchemaDialog({ table, apiClient, onClose, onTableUpdate }: E
{columns.map((column, index) => { - const isSystem = isSystemColumn(column.name) + const isSystem = isSystemColumn(column) return (
)}
+
+ updateColumn(index, "autoGeneratePattern", e.target.value)} + disabled={isSystem} + className={isSystem ? "bg-muted" : ""} + /> +
+
+ updateColumn(index, "defaultValue", e.target.value)} + disabled={isSystem} + className={isSystem ? "bg-muted" : ""} + /> +
+
+ updateColumn(index, "maxValue", e.target.value)} + disabled={isSystem} + className={isSystem ? "bg-muted" : ""} + /> +
+
+ updateColumn(index, "minValue", e.target.value)} + disabled={isSystem} + className={isSystem ? "bg-muted" : ""} + /> +
+
+ updateColumn(index, "validator", e.target.value)} + disabled={isSystem} + className={isSystem ? "bg-muted" : ""} + /> +
updateColumn(index, "nullable", !e.target.checked)} + checked={column.required} + onChange={(e) => updateColumn(index, "required", e.target.checked)} disabled={isSystem} className="rounded" /> @@ -313,6 +321,8 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda updateColumn(index, "defaultValue", e.target.value)} disabled={isSystem} className={isSystem ? "bg-muted" : ""} /> @@ -322,15 +332,55 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda updateColumn(index, "maxValue", e.target.value)} + disabled={isSystem} + className={isSystem ? "bg-muted" : ""} + /> +
+
+ + updateColumn(index, "minValue", e.target.value)} + disabled={isSystem} + className={isSystem ? "bg-muted" : ""} + /> +
+
+ + + updateColumn(index, "autoGeneratePattern", e.target.value) + } disabled={isSystem} className={isSystem ? "bg-muted" : ""} />
+
+ +