Merge pull request #2 from allankoechke/dev-v0

Dev v0
This commit is contained in:
2025-06-26 22:09:57 +03:00
committed by GitHub
17 changed files with 1627 additions and 419 deletions

View File

@@ -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<string | null>(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 (
<ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
{!token ? <LoginForm onLogin={handleLogin} /> : <AdminDashboard token={token} onLogout={handleLogout} />}
<Toaster />
<AppStateProvider>
{route.path === "/login" || !token ? (
<LoginForm onLogin={handleLogin} />
) : (
<AdminDashboard token={token} onLogout={handleLogout} />
)}
<Toaster />
</AppStateProvider>
</ThemeProvider>
)
}

View File

@@ -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<TableMetadata[]>([])
const [admins, setAdmins] = React.useState<Admin[]>([])
const [loading, setLoading] = React.useState(true)
const { toast } = useToast()
const [settings, setSettings] = React.useState<AppSettings | null>(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<TableMetadata[]>("/api/v1/tables"),
apiClient.call<Admin[]>("/api/v1/admins"),
apiClient.call<AppSettings>("/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 (
<div className="flex min-h-screen w-full items-center justify-center">
@@ -126,7 +220,7 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
<SidebarHeader>
<div className="flex items-center gap-2 px-4 py-2">
<Shield className="h-6 w-6" />
<span className="font-semibold">Admin Dashboard</span>
<span className="font-semibold">Mantis Admin</span>
</div>
</SidebarHeader>
<SidebarContent>
@@ -137,9 +231,15 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
{sidebarItems.map((item) => (
<SidebarMenuItem key={item.id}>
<SidebarMenuButton
onClick={() => 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.icon className="h-4 w-4" />
<span>{item.title}</span>
@@ -189,22 +289,49 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
</div>
) : (
<>
{activeSection === "tables" && (
{currentSection === "tables" && (
<DatabaseSection apiClient={apiClient} tables={tables} onTablesUpdate={setTables} />
)}
{activeSection === "admins" && (
{currentSection === "admins" && (
<AdminsSection admins={admins} apiClient={apiClient} onAdminsUpdate={setAdmins} />
)}
{activeSection === "logs" && <LogsSection />}
{activeSection === "sync" && <SyncSection />}
{activeSection === "settings" && (
<SettingsSection apiClient={apiClient} settings={settings} onSettingsUpdate={setSettings} />
{currentSection === "logs" && <LogsSection />}
{currentSection === "sync" && <SyncSection />}
{currentSection === "settings" && (
<SettingsSection
apiClient={apiClient}
settings={settings}
onSettingsUpdate={setSettings}
onModeChange={handleModeChange}
/>
)}
</>
)}
</main>
</div>
</div>
{/* Auth Error Dialog */}
<Dialog open={authErrorDialog} onOpenChange={setAuthErrorDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-destructive" />
Authentication Error
</DialogTitle>
<DialogDescription>
Your session has expired or you don't have permission to access this resource. Please log in again to
continue.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setAuthErrorDialog(false)}>
Cancel
</Button>
<Button onClick={handleAuthErrorLogin}>Login Again</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</SidebarProvider>
)
}

View File

@@ -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 (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4 mr-2" />
Add Table
</Button>
{children || (
<Button>
<Plus className="h-4 w-4 mr-2" />
Add Table
</Button>
)}
</DialogTrigger>
<DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
<DialogHeader>

View File

@@ -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
</Button>
</div>
<DropdownMenuSeparator />
{table.fields?.map((field) => (
{table.schema.fields?.map((field) => (
<DropdownMenuCheckboxItem
key={field.name}
checked={visibleColumns.includes(field.name)}

View File

@@ -1,7 +1,7 @@
"use client"
import * as React from "react"
import { Search, Table, Eye, Edit, Trash2, MoreHorizontal } from "lucide-react"
import { Search, Table, Eye, Edit, Trash2, MoreHorizontal, RefreshCw, Plus, ExternalLink } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
@@ -13,6 +13,7 @@ import { AddTableDialog } from "./add-table-dialog"
import { TableDetailView } from "./table-detail-view"
import { EditSchemaDialog } from "./edit-schema-dialog"
import { SidebarTrigger } from "@/components/ui/sidebar"
import { useRouter } from "@/lib/router"
interface DatabaseSectionProps {
apiClient: ApiClient
@@ -21,10 +22,24 @@ interface DatabaseSectionProps {
}
export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseSectionProps) {
const [selectedTable, setSelectedTable] = React.useState<string | null>(null)
const [searchTerm, setSearchTerm] = React.useState("")
const [editingTable, setEditingTable] = React.useState<TableMetadata | null>(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<TableMetadata[]>("/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 (
<TableDetailView
table={tableInfo}
onBack={() => 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
</div>
</div>
<div className="ml-auto">
<div className="ml-auto flex gap-2">
<Button variant="outline" size="sm" onClick={handleRefresh} disabled={isRefreshing}>
<RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />
</Button>
<AddTableDialog apiClient={apiClient} onTablesUpdate={onTablesUpdate} />
</div>
</div>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{filteredTables.map((table) => (
<Card
key={table.id}
className="cursor-pointer hover:shadow-md transition-shadow"
onClick={() => handleTableClick(table.name)}
>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
<div className="flex items-center gap-2">
<Table className="h-4 w-4" />
{table.name}
<Badge
variant={table.type === "auth" ? "default" : table.type === "view" ? "secondary" : "outline"}
className="text-xs"
>
{table.type}
</Badge>
{tables.length === 0 && !isRefreshing ? (
<Card>
<CardContent className="flex flex-col items-center justify-center py-16">
<Table className="h-12 w-12 text-muted-foreground mb-4" />
<h3 className="text-lg font-semibold mb-2">No Tables Found</h3>
<p className="text-muted-foreground text-center mb-6 max-w-md">
Get started by creating your first table. Tables are used to store and organize your data.
</p>
<div className="flex gap-3">
<AddTableDialog apiClient={apiClient} onTablesUpdate={onTablesUpdate}>
<Button>
<Plus className="h-4 w-4 mr-2" />
Create Table
</Button>
</AddTableDialog>
<Button variant="outline" asChild>
<a href="https://docs.example.com/tables" target="_blank" rel="noopener noreferrer">
<ExternalLink className="h-4 w-4 mr-2" />
View Documentation
</a>
</Button>
</div>
</CardContent>
</Card>
) : (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{filteredTables.map((table) => (
<Card
key={table.id}
className="cursor-pointer hover:shadow-md transition-shadow"
onClick={() => handleTableClick(table.name)}
>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
<div className="flex items-center gap-2">
<Table className="h-4 w-4" />
{table.name}
<Badge
variant={table.type === "auth" ? "default" : table.type === "view" ? "secondary" : "outline"}
className="text-xs"
>
{table.type}
</Badge>
</div>
</CardTitle>
<DropdownMenu>
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
<Button variant="ghost" size="sm">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
handleTableClick(table.name)
}}
>
<Eye className="h-4 w-4 mr-2" />
View Details
</DropdownMenuItem>
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
setEditingTable(table)
}}
>
<Edit className="h-4 w-4 mr-2" />
Edit Schema
</DropdownMenuItem>
<DropdownMenuItem
className="text-destructive"
onClick={(e) => {
e.stopPropagation()
handleDeleteTable(table.id)
}}
>
<Trash2 className="h-4 w-4 mr-2" />
Delete Table
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Type:</span>
<span className="font-medium capitalize">{table.type}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Fields:</span>
<span className="font-medium">{table.schema.fields?.length || 0}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Created:</span>
<span className="font-medium">{new Date(table.created).toLocaleDateString()}</span>
</div>
</div>
</CardTitle>
<DropdownMenu>
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
<Button variant="ghost" size="sm">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
setSelectedTable(table.name)
}}
>
<Eye className="h-4 w-4 mr-2" />
View Details
</DropdownMenuItem>
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
setEditingTable(table)
}}
>
<Edit className="h-4 w-4 mr-2" />
Edit Schema
</DropdownMenuItem>
<DropdownMenuItem
className="text-destructive"
onClick={(e) => {
e.stopPropagation()
handleDeleteTable(table.id)
}}
>
<Trash2 className="h-4 w-4 mr-2" />
Delete Table
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Type:</span>
<span className="font-medium capitalize">{table.type}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Fields:</span>
<span className="font-medium">{table.fields?.length || 0}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Created:</span>
<span className="font-medium">{new Date(table.created).toLocaleDateString()}</span>
</div>
</div>
</CardContent>
</Card>
))}
</div>
</CardContent>
</Card>
))}
</div>
)}
{editingTable && (
<EditSchemaDialog

View File

@@ -62,8 +62,8 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
setHasUnsavedChanges(true)
}
const isSystemField = (fieldName: string) => {
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
<div className="flex-1 overflow-hidden">
<ScrollArea className="h-full">
<div className="p-6 space-y-6">
{table.fields?.map((field) => (
{table.schema.fields?.map((field) => (
<div key={field.name} className="space-y-2">
<Label htmlFor={field.name} className="text-sm font-medium capitalize">
{field.name}
@@ -105,15 +105,19 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
<Input
id={field.name}
type={
field.name === "password" ? "password" : field.type === "datetime" ? "datetime-local" : "text"
field.name === "password"
? "password"
: field.type === "datetime" || field.type === "timestamp"
? "datetime-local"
: "text"
}
value={formData[field.name] || ""}
onChange={(e) => handleFieldChange(field.name, e.target.value)}
disabled={isSystemField(field.name)}
className={`w-full ${isSystemField(field.name) ? "bg-muted" : ""}`}
disabled={isSystemField(field)}
className={`w-full ${isSystemField(field) ? "bg-muted" : ""}`}
placeholder={`Enter ${field.name}`}
/>
{isSystemField(field.name) && (
{isSystemField(field) && (
<p className="text-xs text-muted-foreground">System field - cannot be modified</p>
)}
</div>

View File

@@ -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<TableMetadata>(`/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
<div className="space-y-3 max-h-[400px] overflow-y-auto">
{columns.map((column, index) => {
const isSystem = isSystemColumn(column.name)
const isSystem = isSystemColumn(column)
return (
<div
key={index}
@@ -130,6 +129,51 @@ export function EditSchemaDialog({ table, apiClient, onClose, onTableUpdate }: E
</Badge>
)}
</div>
<div className="flex items-center gap-2 mt-2">
<Input
placeholder="Auto Generate Pattern"
value={column.autoGeneratePattern || ""}
onChange={(e) => updateColumn(index, "autoGeneratePattern", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
/>
</div>
<div className="flex items-center gap-2 mt-2">
<Input
placeholder="Default Value"
value={column.defaultValue || ""}
onChange={(e) => updateColumn(index, "defaultValue", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
/>
</div>
<div className="flex items-center gap-2 mt-2">
<Input
placeholder="Max Value"
value={column.maxValue || ""}
onChange={(e) => updateColumn(index, "maxValue", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
/>
</div>
<div className="flex items-center gap-2 mt-2">
<Input
placeholder="Min Value"
value={column.minValue || ""}
onChange={(e) => updateColumn(index, "minValue", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
/>
</div>
<div className="flex items-center gap-2 mt-2">
<Input
placeholder="Validator"
value={column.validator || ""}
onChange={(e) => updateColumn(index, "validator", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
/>
</div>
</div>
<div className="w-32">
<Select
@@ -180,8 +224,8 @@ export function EditSchemaDialog({ table, apiClient, onClose, onTableUpdate }: E
<input
type="checkbox"
id={`required-${index}`}
checked={!column.nullable}
onChange={(e) => updateColumn(index, "nullable", !e.target.checked)}
checked={column.required || false}
onChange={(e) => updateColumn(index, "required", e.target.checked)}
disabled={isSystem}
className="rounded"
/>

View File

@@ -31,7 +31,7 @@ interface TableConfigDrawerProps {
}
export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpdate }: TableConfigDrawerProps) {
const [columns, setColumns] = React.useState(table.fields || [])
const [columns, setColumns] = React.useState(table.schema?.fields || [])
const [rules, setRules] = React.useState(table.rules)
const [isLoading, setIsLoading] = React.useState(false)
const [activeTab, setActiveTab] = React.useState("schema")
@@ -40,7 +40,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
React.useEffect(() => {
if (open) {
setColumns(table.fields || [])
setColumns(table.schema?.fields || [])
setRules(table.rules)
setHasUnsavedChanges(false)
setSystemFieldsCollapsed(true)
@@ -73,7 +73,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
const removeColumn = (index: number) => {
const column = columns[index]
const isSystemColumn = ["id", "created", "updated", "email", "password"].includes(column.name)
const isSystemColumn = column.system
if (columns.length > 1 && !isSystemColumn) {
setColumns(columns.filter((_, i) => i !== index))
}
@@ -90,7 +90,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
try {
const updatedTable = await apiClient.call<TableMetadata>(`/api/v1/tables/${table.id}`, {
method: "PATCH",
body: JSON.stringify({ fields: columns }),
body: JSON.stringify({ schema: { fields: columns } }),
})
onTableUpdate(updatedTable)
} catch (error) {
@@ -105,7 +105,15 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
try {
const updatedTable = await apiClient.call<TableMetadata>(`/api/v1/tables/${table.id}`, {
method: "PATCH",
body: JSON.stringify({ rules }),
body: JSON.stringify({
rules: {
listRule: rules.listRule,
getRule: rules.getRule,
addRule: rules.addRule,
updateRule: rules.updateRule,
deleteRule: rules.deleteRule,
},
}),
})
onTableUpdate(updatedTable)
} catch (error) {
@@ -115,8 +123,8 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
}
}
const isSystemColumn = (columnName: string) => {
return ["id", "created", "updated", "email", "password"].includes(columnName)
const isSystemColumn = (column: any) => {
return column.system
}
const handleClose = () => {
@@ -174,14 +182,14 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
<h5 className="font-medium mb-3">SQL Query</h5>
<ScrollArea className="h-32">
<pre className="text-sm whitespace-pre-wrap">
<code>{table.sql}</code>
<code>{table.schema?.sql}</code>
</pre>
</ScrollArea>
</div>
) : (
<>
{/* System Fields - Collapsible */}
{columns.filter((col) => isSystemColumn(col.name)).length > 0 && (
{columns.filter((col) => isSystemColumn(col)).length > 0 && (
<Collapsible
open={!systemFieldsCollapsed}
onOpenChange={(open) => setSystemFieldsCollapsed(!open)}
@@ -189,7 +197,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
<CollapsibleTrigger asChild>
<Button variant="ghost" className="w-full justify-between p-2 mb-4">
<span className="text-sm font-medium">
System Fields ({columns.filter((col) => isSystemColumn(col.name)).length})
System Fields ({columns.filter((col) => isSystemColumn(col)).length})
</span>
<ChevronDown
className={`h-4 w-4 transition-transform ${systemFieldsCollapsed ? "" : "rotate-180"}`}
@@ -198,7 +206,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
</CollapsibleTrigger>
<CollapsibleContent className="space-y-4 mb-6">
{columns.map((column, index) => {
const isSystem = isSystemColumn(column.name)
const isSystem = isSystemColumn(column)
if (!isSystem) return null
return (
<div key={index} className="border rounded-lg bg-muted/50">
@@ -262,8 +270,8 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
<input
type="checkbox"
id={`required-${index}`}
checked={!column.nullable}
onChange={(e) => 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
<Label className="text-sm font-medium mb-2 block">Default Value</Label>
<Input
placeholder="Default value"
value={column.defaultValue || ""}
onChange={(e) => updateColumn(index, "defaultValue", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
/>
@@ -322,15 +332,55 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
<Input
type="number"
placeholder="Max length"
value={column.maxValue || ""}
onChange={(e) => updateColumn(index, "maxValue", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
/>
</div>
<div>
<Label className="text-sm font-medium mb-2 block">Min Length</Label>
<Input
type="number"
placeholder="Min length"
value={column.minValue || ""}
onChange={(e) => updateColumn(index, "minValue", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
/>
</div>
<div>
<Label className="text-sm font-medium mb-2 block">
Auto Generate Pattern
</Label>
<Input
placeholder="Auto Generate Pattern"
value={column.autoGeneratePattern || ""}
onChange={(e) =>
updateColumn(index, "autoGeneratePattern", e.target.value)
}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
/>
</div>
</div>
<div>
<Label className="text-sm font-medium mb-2 block">Validator</Label>
<Textarea
placeholder="Column validator"
value={column.validator || ""}
onChange={(e) => updateColumn(index, "validator", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
rows={2}
/>
</div>
<div>
<Label className="text-sm font-medium mb-2 block">Description</Label>
<Textarea
placeholder="Column description"
value={column.description || ""}
onChange={(e) => updateColumn(index, "description", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
rows={2}
@@ -364,7 +414,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
{/* Regular Fields */}
<div className="space-y-4">
{columns.map((column, index) => {
const isSystem = isSystemColumn(column.name)
const isSystem = isSystemColumn(column)
if (isSystem) return null // Skip system fields as they're in collapsible section
return (
<div key={index} className="border rounded-lg">
@@ -428,8 +478,8 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
<input
type="checkbox"
id={`required-${index}`}
checked={!column.nullable}
onChange={(e) => updateColumn(index, "nullable", !e.target.checked)}
checked={column.required}
onChange={(e) => updateColumn(index, "required", e.target.checked)}
disabled={isSystem}
className="rounded"
/>
@@ -479,6 +529,8 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
<Label className="text-sm font-medium mb-2 block">Default Value</Label>
<Input
placeholder="Default value"
value={column.defaultValue || ""}
onChange={(e) => updateColumn(index, "defaultValue", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
/>
@@ -488,15 +540,51 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
<Input
type="number"
placeholder="Max length"
value={column.maxValue || ""}
onChange={(e) => updateColumn(index, "maxValue", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
/>
</div>
<div>
<Label className="text-sm font-medium mb-2 block">Min Length</Label>
<Input
type="number"
placeholder="Min length"
value={column.minValue || ""}
onChange={(e) => updateColumn(index, "minValue", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
/>
</div>
<div>
<Label className="text-sm font-medium mb-2 block">Auto Generate Pattern</Label>
<Input
placeholder="Auto Generate Pattern"
value={column.autoGeneratePattern || ""}
onChange={(e) => updateColumn(index, "autoGeneratePattern", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
/>
</div>
</div>
<div>
<Label className="text-sm font-medium mb-2 block">Validator</Label>
<Textarea
placeholder="Column validator"
value={column.validator || ""}
onChange={(e) => updateColumn(index, "validator", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
rows={2}
/>
</div>
<div>
<Label className="text-sm font-medium mb-2 block">Description</Label>
<Textarea
placeholder="Column description"
value={column.description || ""}
onChange={(e) => updateColumn(index, "description", e.target.value)}
disabled={isSystem}
className={isSystem ? "bg-muted" : ""}
rows={2}
@@ -550,8 +638,8 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
<Textarea
id="list-rule"
placeholder='e.g., "True", "auth.id != None", ""'
value={rules.list}
onChange={(e) => setRules({ ...rules, list: e.target.value })}
value={rules.listRule}
onChange={(e) => setRules({ ...rules, listRule: e.target.value })}
className="mt-2"
rows={3}
/>
@@ -565,8 +653,8 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
<Textarea
id="get-rule"
placeholder='e.g., "True", "auth.id == record.user_id"'
value={rules.get}
onChange={(e) => setRules({ ...rules, get: e.target.value })}
value={rules.getRule}
onChange={(e) => setRules({ ...rules, getRule: e.target.value })}
className="mt-2"
rows={3}
/>
@@ -582,8 +670,8 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
<Textarea
id="add-rule"
placeholder='e.g., "auth.id != None", "auth.role == "admin""'
value={rules.add}
onChange={(e) => setRules({ ...rules, add: e.target.value })}
value={rules.addRule}
onChange={(e) => setRules({ ...rules, addRule: e.target.value })}
className="mt-2"
rows={3}
/>
@@ -597,8 +685,8 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
<Textarea
id="update-rule"
placeholder='e.g., "auth.id == record.user_id", ""'
value={rules.update}
onChange={(e) => setRules({ ...rules, update: e.target.value })}
value={rules.updateRule}
onChange={(e) => setRules({ ...rules, updateRule: e.target.value })}
className="mt-2"
rows={3}
/>
@@ -612,8 +700,8 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
<Textarea
id="delete-rule"
placeholder='e.g., "auth.role == "admin"", ""'
value={rules.delete}
onChange={(e) => setRules({ ...rules, delete: e.target.value })}
value={rules.deleteRule}
onChange={(e) => setRules({ ...rules, deleteRule: e.target.value })}
className="mt-2"
rows={3}
/>

View File

@@ -1,7 +1,7 @@
"use client"
import * as React from "react"
import { RefreshCw, Cog, FileText, Trash2, Search } from "lucide-react"
import { RefreshCw, Cog, FileText, Trash2, Search, Plus, ExternalLink } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
@@ -31,7 +31,9 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
const [docsOpen, setDocsOpen] = React.useState(false)
const [editingItem, setEditingItem] = React.useState<any>(null)
const [selectedItems, setSelectedItems] = React.useState<string[]>([])
const [visibleColumns, setVisibleColumns] = React.useState<string[]>(table.fields?.map((field) => field.name) || [])
const [visibleColumns, setVisibleColumns] = React.useState<string[]>(
table.schema.fields?.map((field) => field.name) || [],
)
const [isDeleting, setIsDeleting] = React.useState(false)
const [filterTerm, setFilterTerm] = React.useState("")
const [appliedFilter, setAppliedFilter] = React.useState("")
@@ -41,8 +43,8 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
}, [currentPage, appliedFilter])
React.useEffect(() => {
setVisibleColumns(table.fields?.map((field) => field.name) || [])
}, [table.fields])
setVisibleColumns(table.schema.fields?.map((field) => field.name) || [])
}, [table.schema.fields])
const loadTableData = async () => {
setIsLoading(true)
@@ -52,7 +54,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
const id = `${currentPage}-${i + 1}`
const baseData: any = { id }
table.fields?.forEach((field) => {
table.schema.fields?.forEach((field) => {
if (field.name === "id") return
if (field.name === "created" || field.name === "updated") {
baseData[field.name] = new Date().toISOString()
@@ -149,7 +151,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
}
}
const filteredFields = table.fields?.filter((field) => visibleColumns.includes(field.name)) || []
const filteredFields = table.schema.fields?.filter((field) => visibleColumns.includes(field.name)) || []
return (
<div className="space-y-6">
@@ -166,8 +168,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={handleReload} disabled={isLoading}>
<RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? "animate-spin" : ""}`} />
Reload
<RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
</Button>
<Button variant="outline" size="sm" onClick={() => setConfigOpen(true)}>
<Cog className="h-4 w-4 mr-2" />
@@ -238,54 +239,76 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
</div>
</CardHeader>
<CardContent>
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-12">
<Checkbox
checked={selectedItems.length === tableData.length && tableData.length > 0}
onCheckedChange={handleSelectAll}
aria-label="Select all"
/>
</TableHead>
{filteredFields.map((field) => (
<TableHead key={field.name} className="capitalize">
{field.name}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{tableData.length > 0 ? (
tableData.map((row, index) => (
<TableRow
key={index}
className="cursor-pointer hover:bg-muted/50"
onClick={(e) => handleRowClick(row, e)}
>
<TableCell onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={selectedItems.includes(row.id)}
onCheckedChange={(checked) => handleSelectItem(row.id, checked as boolean)}
aria-label={`Select row ${index + 1}`}
/>
</TableCell>
{filteredFields.map((field) => (
<TableCell key={field.name}>{row[field.name] || "-"}</TableCell>
))}
</TableRow>
))
) : (
{tableData.length === 0 && !isLoading ? (
<div className="flex flex-col items-center justify-center py-16">
<FileText className="h-12 w-12 text-muted-foreground mb-4" />
<h3 className="text-lg font-semibold mb-2">No Records Found</h3>
<p className="text-muted-foreground text-center mb-6 max-w-md">
This table doesn't have any records yet. Add some data to get started.
</p>
<div className="flex gap-3">
<Button>
<Plus className="h-4 w-4 mr-2" />
Add Record
</Button>
<Button variant="outline" asChild>
<a href="https://docs.example.com/records" target="_blank" rel="noopener noreferrer">
<ExternalLink className="h-4 w-4 mr-2" />
View Documentation
</a>
</Button>
</div>
</div>
) : (
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableCell colSpan={filteredFields.length + 1} className="text-center text-muted-foreground">
{isLoading ? "Loading..." : "No data available"}
</TableCell>
<TableHead className="w-12">
<Checkbox
checked={selectedItems.length === tableData.length && tableData.length > 0}
onCheckedChange={handleSelectAll}
aria-label="Select all"
/>
</TableHead>
{filteredFields.map((field) => (
<TableHead key={field.name} className="capitalize">
{field.name}
</TableHead>
))}
</TableRow>
)}
</TableBody>
</Table>
</div>
</TableHeader>
<TableBody>
{tableData.length > 0 ? (
tableData.map((row, index) => (
<TableRow
key={index}
className="cursor-pointer hover:bg-muted/50"
onClick={(e) => handleRowClick(row, e)}
>
<TableCell onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={selectedItems.includes(row.id)}
onCheckedChange={(checked) => handleSelectItem(row.id, checked as boolean)}
aria-label={`Select row ${index + 1}`}
/>
</TableCell>
{filteredFields.map((field) => (
<TableCell key={field.name}>{row[field.name] || "-"}</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={filteredFields.length + 1} className="text-center text-muted-foreground">
{isLoading ? "Loading..." : "No data available"}
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
)}
{totalPages > 1 && (
<div className="flex items-center justify-between mt-4">

View File

@@ -56,7 +56,7 @@ export function TableDocsDrawer({ table, open, onClose }: TableDocsDrawerProps)
operation="get"
/>
{table.type !== "view" && (
{table.schema.type !== "view" && (
<>
<ApiEndpointCard
method="POST"
@@ -137,7 +137,7 @@ function ApiEndpointCard({
if (operation === "create" || operation === "update") {
const sampleData: any = {}
table.fields?.forEach((field) => {
table.schema.fields?.forEach((field) => {
if (field.name === "id" || field.name === "created" || field.name === "updated") return
if (field.name === "email") {
sampleData[field.name] = "user@example.com"
@@ -157,7 +157,7 @@ function ApiEndpointCard({
const generateResponseExample = () => {
if (operation === "list") {
const sampleRecord: any = {}
table.fields?.forEach((field) => {
table.schema.fields?.forEach((field) => {
if (field.name === "id") {
sampleRecord[field.name] = "123e4567-e89b-12d3-a456-426614174000"
} else if (field.name === "created" || field.name === "updated") {
@@ -192,7 +192,7 @@ function ApiEndpointCard({
// Single record response
const sampleRecord: any = {}
table.fields?.forEach((field) => {
table.schema.fields?.forEach((field) => {
if (field.name === "id") {
sampleRecord[field.name] = "123e4567-e89b-12d3-a456-426614174000"
} else if (field.name === "created" || field.name === "updated") {

View File

@@ -9,6 +9,7 @@ import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { loginWithPassword } from "@/lib/api"
import { useAppState } from "@/lib/app-state"
interface LoginFormProps {
onLogin: (token: string) => void
@@ -20,6 +21,7 @@ export function LoginForm({ onLogin }: LoginFormProps) {
const [showPassword, setShowPassword] = React.useState(false)
const [isLoading, setIsLoading] = React.useState(false)
const [error, setError] = React.useState("")
const { mode } = useAppState()
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
@@ -27,11 +29,11 @@ export function LoginForm({ onLogin }: LoginFormProps) {
setError("")
try {
const data = await loginWithPassword(email, password)
const data = await loginWithPassword(email, password, mode)
localStorage.setItem("admin_token", data.token)
onLogin(data.token)
} catch (err) {
setError("Invalid email or password")
} catch (err: any) {
setError(err.message || "Invalid email or password")
} finally {
setIsLoading(false)
}
@@ -44,7 +46,7 @@ export function LoginForm({ onLogin }: LoginFormProps) {
<div className="flex justify-center mb-4">
<Shield className="h-12 w-12 text-primary" />
</div>
<CardTitle className="text-2xl">Admin Login</CardTitle>
<CardTitle className="text-2xl">Mantis Admin</CardTitle>
<CardDescription>Sign in to access the admin dashboard</CardDescription>
</CardHeader>
<CardContent>
@@ -98,6 +100,7 @@ export function LoginForm({ onLogin }: LoginFormProps) {
<p>Demo credentials:</p>
<p>Email: admin@example.com</p>
<p>Password: password</p>
<p className="mt-2 text-xs">Mode: {mode}</p>
</div>
</form>
</CardContent>

View File

@@ -1,31 +1,40 @@
"use client"
import * as React from "react"
import { RefreshCw, TestTube, Globe } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { SidebarTrigger } from "@/components/ui/sidebar"
import { Badge } from "@/components/ui/badge"
import type { ApiClient, AppSettings } from "@/lib/api"
import { useToast } from "@/hooks/use-toast"
import { useAppState, type AppMode } from "@/lib/app-state"
interface SettingsSectionProps {
apiClient: ApiClient
settings: AppSettings | null
onSettingsUpdate: (settings: AppSettings) => void
onModeChange: (mode: AppMode, baseUrl?: string) => void
}
export function SettingsSection({ apiClient, settings, onSettingsUpdate }: SettingsSectionProps) {
export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeChange }: SettingsSectionProps) {
const { toast } = useToast()
const { mode, setMode } = useAppState()
const [formData, setFormData] = React.useState<AppSettings | null>(null)
const [isLoading, setIsLoading] = React.useState(false)
const [hasChanges, setHasChanges] = React.useState(false)
const [isRefreshing, setIsRefreshing] = React.useState(false)
React.useEffect(() => {
if (settings) {
setFormData({ ...settings })
console.log("Settings received:", settings)
setFormData({ ...settings, mode })
setHasChanges(false)
}
}, [settings])
}, [settings, mode])
const handleInputChange = (field: keyof AppSettings, value: any) => {
if (!formData) return
@@ -37,6 +46,18 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
setHasChanges(true)
}
const handleModeToggle = (newMode: AppMode) => {
setMode(newMode)
if (formData) {
setFormData({
...formData,
mode: newMode,
})
setHasChanges(true)
}
onModeChange(newMode, formData?.baseUrl)
}
const handleSave = async () => {
if (!formData) return
@@ -48,6 +69,11 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
})
onSettingsUpdate(updatedSettings)
setHasChanges(false)
toast({
title: "Settings Saved",
description: "Application settings have been updated successfully.",
})
} catch (error) {
console.error("Failed to update settings:", error)
} finally {
@@ -55,6 +81,19 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
}
}
const handleRefresh = async () => {
setIsRefreshing(true)
try {
const updatedSettings = await apiClient.call<AppSettings>("/api/v1/settings")
onSettingsUpdate(updatedSettings)
} catch (error) {
console.error("Failed to refresh settings:", error)
} finally {
setIsRefreshing(false)
}
}
// Show loading if we don't have formData yet
if (!formData) {
return (
<div className="flex items-center justify-center h-64">
@@ -68,14 +107,91 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
return (
<div className="space-y-6">
<div className="flex items-center gap-4">
<SidebarTrigger />
<div>
<h2 className="text-2xl font-bold">Application Settings</h2>
<p className="text-muted-foreground">Configure global application settings</p>
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<SidebarTrigger />
<div>
<h2 className="text-2xl font-bold">Application Settings</h2>
<p className="text-muted-foreground">Configure global application settings</p>
</div>
</div>
<div className="flex items-center gap-2">
<Badge variant={mode === "TEST" ? "secondary" : "default"} className="flex items-center gap-1">
{mode === "TEST" ? <TestTube className="h-3 w-3" /> : <Globe className="h-3 w-3" />}
{mode} MODE
</Badge>
<Button variant="outline" size="sm" onClick={handleRefresh} disabled={isRefreshing}>
<RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />
</Button>
</div>
</div>
{/* Environment Mode Card */}
<Card>
<CardHeader>
<CardTitle>Environment Mode</CardTitle>
<CardDescription>Switch between test mode (mock data) and production mode (real API calls)</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Card
className={`cursor-pointer transition-all ${mode === "TEST" ? "ring-2 ring-primary" : "hover:bg-muted/50"}`}
onClick={() => handleModeToggle("TEST")}
>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<TestTube className="h-5 w-5 text-blue-600" />
<div>
<h4 className="font-medium">Test Mode</h4>
<p className="text-sm text-muted-foreground">Uses mock data for development</p>
</div>
{mode === "TEST" && (
<Badge variant="default" className="ml-auto">
Active
</Badge>
)}
</div>
</CardContent>
</Card>
<Card
className={`cursor-pointer transition-all ${mode === "PROD" ? "ring-2 ring-primary" : "hover:bg-muted/50"}`}
onClick={() => handleModeToggle("PROD")}
>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<Globe className="h-5 w-5 text-green-600" />
<div>
<h4 className="font-medium">Production Mode</h4>
<p className="text-sm text-muted-foreground">Makes real API calls</p>
</div>
{mode === "PROD" && (
<Badge variant="default" className="ml-auto">
Active
</Badge>
)}
</div>
</CardContent>
</Card>
</div>
{mode === "PROD" && (
<div className="p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
<div className="flex items-start gap-2">
<Globe className="h-4 w-4 text-yellow-600 mt-0.5" />
<div>
<p className="text-sm font-medium text-yellow-800 dark:text-yellow-200">Production Mode Active</p>
<p className="text-sm text-yellow-700 dark:text-yellow-300">
All API calls will be made to the configured base URL. Ensure your API server is running and
accessible.
</p>
</div>
</div>
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>General Settings</CardTitle>
@@ -87,7 +203,7 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
<Label htmlFor="app-name">Application Name</Label>
<Input
id="app-name"
value={formData.appName}
value={formData?.appName || ""}
onChange={(e) => handleInputChange("appName", e.target.value)}
/>
</div>
@@ -95,7 +211,7 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
<Label htmlFor="version">Version</Label>
<Input
id="version"
value={formData.version}
value={formData?.version || ""}
onChange={(e) => handleInputChange("version", e.target.value)}
/>
</div>
@@ -105,11 +221,14 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
<Label htmlFor="base-url">Base URL</Label>
<Input
id="base-url"
value={formData.baseUrl}
value={formData?.baseUrl || ""}
onChange={(e) => handleInputChange("baseUrl", e.target.value)}
placeholder="https://your-api-domain.com"
/>
<p className="text-sm text-muted-foreground mt-1">The base URL for your API endpoints</p>
<p className="text-sm text-muted-foreground mt-1">
The base URL for your API endpoints{" "}
{mode === "PROD" ? "(used in production mode)" : "(not used in test mode)"}
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
@@ -117,7 +236,7 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
<Label htmlFor="max-file-size">Max File Size</Label>
<Input
id="max-file-size"
value={formData.maxFileSize}
value={formData?.maxFileSize || ""}
onChange={(e) => handleInputChange("maxFileSize", e.target.value)}
placeholder="10MB"
/>
@@ -127,7 +246,7 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
<Input
id="session-timeout"
type="number"
value={formData.sessionTimeout}
value={formData?.sessionTimeout || 3600}
onChange={(e) => handleInputChange("sessionTimeout", Number.parseInt(e.target.value) || 3600)}
/>
</div>
@@ -140,7 +259,7 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
<p className="text-sm text-muted-foreground">Enable maintenance mode for the application</p>
</div>
<Switch
checked={formData.maintenanceMode}
checked={formData?.maintenanceMode || false}
onCheckedChange={(checked) => handleInputChange("maintenanceMode", checked)}
/>
</div>
@@ -151,7 +270,7 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
<p className="text-sm text-muted-foreground">Allow new users to register</p>
</div>
<Switch
checked={formData.allowRegistration}
checked={formData?.allowRegistration || false}
onCheckedChange={(checked) => handleInputChange("allowRegistration", checked)}
/>
</div>
@@ -162,7 +281,7 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
<p className="text-sm text-muted-foreground">Require email verification for new accounts</p>
</div>
<Switch
checked={formData.emailVerificationRequired}
checked={formData?.emailVerificationRequired || false}
onCheckedChange={(checked) => handleInputChange("emailVerificationRequired", checked)}
/>
</div>
@@ -170,12 +289,101 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
</CardContent>
</Card>
{/* Notification Test Section */}
<Card>
<CardHeader>
<CardTitle>Notification Testing</CardTitle>
<CardDescription>Test different types of notifications and error messages</CardDescription>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<Button
variant="default"
onClick={() => {
toast({
title: "Info",
description: "This is a test info message. Everything is working correctly!",
})
}}
className="w-full"
>
Test Info
</Button>
<Button
variant="secondary"
onClick={() => {
toast({
title: "Warning",
description: "This is a test warning message. Please pay attention to this.",
variant: "default",
})
}}
className="w-full"
>
Test Warning
</Button>
<Button
variant="destructive"
onClick={() => {
toast({
variant: "destructive",
title: "Error",
description: "This is a test error message. Something went wrong!",
})
}}
className="w-full"
>
Test Error
</Button>
<Button
variant="outline"
onClick={() => {
toast({
variant: "destructive",
title: "Authentication Error",
description: "Your session has expired. Please log in again.",
action: (
<Button variant="outline" size="sm">
Login
</Button>
),
})
}}
className="w-full"
>
Test Auth Toast
</Button>
</div>
<div className="mt-4 text-sm text-muted-foreground">
<p>Use these buttons to test different notification types:</p>
<ul className="list-disc list-inside mt-2 space-y-1">
<li>
<strong>Info:</strong> General information messages
</li>
<li>
<strong>Warning:</strong> Warning notifications
</li>
<li>
<strong>Error:</strong> Error toast notifications
</li>
<li>
<strong>Auth Error:</strong> Authentication error dialog
</li>
</ul>
</div>
</CardContent>
</Card>
<div className="flex justify-end gap-2">
<Button
variant="outline"
onClick={() => {
if (settings) {
setFormData({ ...settings })
setFormData({ ...settings, mode })
setHasChanges(false)
}
}}

View File

@@ -6,7 +6,7 @@ import { useTheme } from "next-themes"
import { SidebarMenuButton } from "@/components/ui/sidebar"
export function ThemeToggle() {
const { theme, setTheme } = useTheme()
const { theme, setTheme, resolvedTheme } = useTheme()
const [mounted, setMounted] = React.useState(false)
React.useEffect(() => {
@@ -22,10 +22,14 @@ export function ThemeToggle() {
)
}
const toggleTheme = () => {
setTheme(resolvedTheme === "dark" ? "light" : "dark")
}
return (
<SidebarMenuButton onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
{theme === "dark" ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
<span>{theme === "dark" ? "Light Mode" : "Dark Mode"}</span>
<SidebarMenuButton onClick={toggleTheme}>
{resolvedTheme === "dark" ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
<span>{resolvedTheme === "dark" ? "Light Mode" : "Dark Mode"}</span>
</SidebarMenuButton>
)
}

View File

@@ -4,9 +4,8 @@ import * as React from "react"
import type { ToastActionElement, ToastProps } from "@/components/ui/toast"
const TOAST_LIMIT = 1
// Update the TOAST_REMOVE_DELAY to show toasts longer
const TOAST_REMOVE_DELAY = 5000
const TOAST_LIMIT = 5 // Allow multiple toasts
const TOAST_REMOVE_DELAY = 300000 // 5 minutes
type ToasterToast = ToastProps & {
id: string

View File

@@ -1,64 +1,289 @@
"use client"
// Mock data for testing
const mockTables = [
import type { AppMode } from "./app-state"
// Updated interfaces to match the API response format
export interface TableField {
autoGeneratePattern: string | null
defaultValue: string | null
maxValue: number | null
minValue: number | null
name: string
primaryKey: boolean
required: boolean
system: boolean
type: string
unique: boolean
validator: string | null
}
export interface TableSchema {
addRule: string
deleteRule: string
fields: TableField[]
getRule: string
has_api: boolean
id: string
listRule: string
name: string
system: boolean
type: "base" | "auth" | "view"
updateRule: string
sql?: string
}
export interface TableMetadata {
created: string
has_api: boolean
id: string
name: string
schema: TableSchema
type: "base" | "auth" | "view"
updated: string
}
export interface Admin {
id: string
email: string
created: string
updated: string
}
export interface AppSettings {
appName: string
baseUrl: string
version: string
maintenanceMode: boolean
maxFileSize: string
allowRegistration: boolean
emailVerificationRequired: boolean
sessionTimeout: number
mode: AppMode
}
// Mock data updated to match new format
const mockTables: TableMetadata[] = [
{
id: "1",
created: "2025-06-21 22:04:15",
has_api: true,
id: "mt_11699830787864871553",
name: "users",
type: "auth" as const,
created: "2024-01-15T10:00:00Z",
updated: "2024-01-15T10:00:00Z",
rules: {
list: "auth.id != None",
get: "auth.id == record.id",
add: "True",
update: "auth.id == record.id",
delete: "auth.role == 'admin'",
schema: {
addRule: "",
deleteRule: "",
fields: [
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: null,
name: "id",
primaryKey: true,
required: true,
system: true,
type: "string",
unique: false,
validator: null,
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: null,
name: "created",
primaryKey: false,
required: true,
system: true,
type: "date",
unique: false,
validator: null,
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: null,
name: "updated",
primaryKey: false,
required: true,
system: true,
type: "date",
unique: false,
validator: null,
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: 5.0,
name: "email",
primaryKey: false,
required: true,
system: true,
type: "string",
unique: true,
validator: "email",
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: 8.0,
name: "password",
primaryKey: false,
required: true,
system: true,
type: "string",
unique: false,
validator: "password",
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: 2.0,
name: "name",
primaryKey: false,
required: true,
system: true,
type: "string",
unique: false,
validator: null,
},
],
getRule: "",
has_api: true,
id: "mt_11699830787864871553",
listRule: "",
name: "users",
system: false,
type: "auth",
updateRule: "",
},
fields: [
{ name: "id", type: "string", primaryKey: true, nullable: false },
{ name: "email", type: "string", primaryKey: false, nullable: false },
{ name: "password", type: "string", primaryKey: false, nullable: false },
{ name: "created", type: "datetime", primaryKey: false, nullable: false },
{ name: "updated", type: "datetime", primaryKey: false, nullable: false },
],
type: "auth",
updated: "2025-06-21 22:04:15",
},
{
id: "2",
created: "2025-06-20 10:00:00",
has_api: true,
id: "mt_22699830787864871554",
name: "products",
type: "base" as const,
created: "2024-01-20T10:00:00Z",
updated: "2024-01-20T10:00:00Z",
rules: {
list: "True",
get: "True",
add: "auth.id != None",
update: "auth.id != None",
delete: "auth.role == 'admin'",
schema: {
addRule: "auth.id != None",
deleteRule: "auth.role == 'admin'",
fields: [
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: null,
name: "id",
primaryKey: true,
required: true,
system: true,
type: "string",
unique: false,
validator: null,
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: null,
name: "created",
primaryKey: false,
required: true,
system: true,
type: "date",
unique: false,
validator: null,
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: null,
name: "updated",
primaryKey: false,
required: true,
system: true,
type: "date",
unique: false,
validator: null,
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: 1.0,
name: "name",
primaryKey: false,
required: true,
system: false,
type: "string",
unique: false,
validator: null,
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: 999999.0,
minValue: 0.0,
name: "price",
primaryKey: false,
required: true,
system: false,
type: "float64",
unique: false,
validator: null,
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: null,
name: "category",
primaryKey: false,
required: false,
system: false,
type: "string",
unique: false,
validator: null,
},
],
getRule: "True",
has_api: true,
id: "mt_22699830787864871554",
listRule: "True",
name: "products",
system: false,
type: "base",
updateRule: "auth.id != None",
},
fields: [
{ name: "id", type: "string", primaryKey: true, nullable: false },
{ name: "name", type: "string", primaryKey: false, nullable: false },
{ name: "price", type: "double", primaryKey: false, nullable: false },
{ name: "category", type: "string", primaryKey: false, nullable: true },
{ name: "created", type: "datetime", primaryKey: false, nullable: false },
{ name: "updated", type: "datetime", primaryKey: false, nullable: false },
],
type: "base",
updated: "2025-06-20 10:00:00",
},
{
id: "3",
created: "2025-06-19 15:30:00",
has_api: true,
id: "mt_33699830787864871555",
name: "active_users_view",
type: "view" as const,
created: "2024-02-01T10:00:00Z",
updated: "2024-02-01T10:00:00Z",
rules: {
list: "auth.role == 'admin'",
get: "auth.role == 'admin'",
add: "",
update: "",
delete: "",
schema: {
addRule: "",
deleteRule: "",
fields: [],
getRule: "auth.role == 'admin'",
has_api: true,
id: "mt_33699830787864871555",
listRule: "auth.role == 'admin'",
name: "active_users_view",
system: false,
type: "view",
updateRule: "",
sql: "SELECT id, email, created FROM users WHERE updated > NOW() - INTERVAL 30 DAY",
},
sql: "SELECT id, email, created FROM users WHERE updated > NOW() - INTERVAL 30 DAY",
type: "view",
updated: "2025-06-19 15:30:00",
},
]
@@ -78,7 +303,7 @@ const mockAdmins = [
]
const mockSettings = {
appName: "Admin Dashboard",
appName: "Mantis Admin",
baseUrl: "https://api.example.com",
version: "1.2.3",
maintenanceMode: false,
@@ -86,84 +311,78 @@ const mockSettings = {
allowRegistration: true,
emailVerificationRequired: false,
sessionTimeout: 3600,
mode: "TEST" as AppMode,
}
// API Response interface
interface ApiResponse<T> {
data: T
error?: string
status: number
}
// Simulate API delay
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
export interface TableMetadata {
id: string
name: string
type: "base" | "auth" | "view"
created: string
updated: string
rules: {
list: string
get: string
add: string
update: string
delete: string
}
fields?: Array<{
name: string
type: string
primaryKey: boolean
nullable: boolean
unique?: boolean
isFile?: boolean
}>
sql?: string
}
export interface Admin {
id: string
email: string
created: string
updated: string
}
export interface AppSettings {
appName: string
baseUrl: string
version: string
maintenanceMode: boolean
maxFileSize: string
allowRegistration: boolean
emailVerificationRequired: boolean
sessionTimeout: number
}
export class ApiClient {
private token: string
private onUnauthorized: () => void
private onError?: (error: string, type?: "error" | "warning") => void
private requestCount = 0
private maxRequests = 100
private mode: AppMode
private baseUrl: string
constructor(
token: string,
onUnauthorized: () => void,
mode: AppMode = "TEST",
baseUrl = "https://api.example.com",
onError?: (error: string, type?: "error" | "warning") => void,
) {
this.token = token
this.onUnauthorized = onUnauthorized
this.onError = onError
this.mode = mode
this.baseUrl = baseUrl
}
private async mockApiCall<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
private async mockApiCall<T>(endpoint: string, options: RequestInit = {}): Promise<ApiResponse<T>> {
// Prevent infinite loops
this.requestCount++
if (this.requestCount > this.maxRequests) {
return {
data: null as T,
error: "Too many API requests - possible infinite loop detected",
status: 500,
}
}
// Reset counter after a delay
setTimeout(() => {
this.requestCount = Math.max(0, this.requestCount - 1)
}, 1000)
// Simulate network delay
await delay(300 + Math.random() * 200)
// Simulate occasional errors for testing
if (Math.random() < 0.05) {
const error = "Network error occurred"
this.onError?.(error, "error")
throw new Error(error)
// Simulate occasional errors for testing (reduced frequency)
if (Math.random() < 0.02) {
return {
data: null as T,
error: "Network error occurred",
status: 500,
}
}
// Simulate 401 for invalid tokens (uncomment to test)
// if (Math.random() < 0.1) {
// this.onUnauthorized()
// throw new Error('Unauthorized')
// }
if (Math.random() < 0.01) {
return {
data: null as T,
error: "Unauthorized - Session expired",
status: 403,
}
}
const method = options.method || "GET"
const url = new URL(endpoint, "http://localhost")
@@ -171,18 +390,34 @@ export class ApiClient {
// Mock API responses
if (url.pathname === "/api/v1/tables") {
if (method === "GET") {
return mockTables as T
return { data: mockTables as T, status: 200 }
}
if (method === "POST") {
const body = JSON.parse(options.body as string)
const newTable: TableMetadata = {
id: String(mockTables.length + 1),
...body,
created: new Date().toISOString(),
updated: new Date().toISOString(),
id: `mt_${Date.now()}${Math.floor(Math.random() * 1000)}`,
name: body.name,
type: body.type,
has_api: true,
created: new Date().toISOString().replace("T", " ").slice(0, 19),
updated: new Date().toISOString().replace("T", " ").slice(0, 19),
schema: {
id: `mt_${Date.now()}${Math.floor(Math.random() * 1000)}`,
name: body.name,
type: body.type,
system: false,
has_api: true,
fields: body.fields || [],
addRule: body.addRule || "",
deleteRule: body.deleteRule || "",
getRule: body.getRule || "",
listRule: body.listRule || "",
updateRule: body.updateRule || "",
sql: body.sql,
},
}
mockTables.push(newTable)
return newTable as T
return { data: newTable as T, status: 201 }
}
}
@@ -194,21 +429,25 @@ export class ApiClient {
const body = JSON.parse(options.body as string)
mockTables[tableIndex] = {
...mockTables[tableIndex],
...body,
updated: new Date().toISOString(),
updated: new Date().toISOString().replace("T", " ").slice(0, 19),
schema: {
...mockTables[tableIndex].schema,
...body,
fields: body.fields || mockTables[tableIndex].schema.fields,
},
}
return mockTables[tableIndex] as T
return { data: mockTables[tableIndex] as T, status: 200 }
}
if (method === "DELETE" && tableIndex !== -1) {
mockTables.splice(tableIndex, 1)
return { success: true } as T
return { data: null as T, status: 204 }
}
}
if (url.pathname === "/api/v1/admins") {
if (method === "GET") {
return mockAdmins as T
return { data: mockAdmins as T, status: 200 }
}
}
@@ -222,23 +461,25 @@ export class ApiClient {
...mockAdmins[adminIndex],
updated: new Date().toISOString(),
}
return mockAdmins[adminIndex] as T
return { data: mockAdmins[adminIndex] as T, status: 200 }
}
if (method === "DELETE" && adminIndex !== -1) {
mockAdmins.splice(adminIndex, 1)
return { success: true } as T
return { data: null as T, status: 204 }
}
}
if (url.pathname === "/api/v1/settings") {
if (method === "GET") {
return mockSettings as T
console.log("Returning mock settings:", mockSettings)
return { data: mockSettings as T, status: 200 }
}
if (method === "PATCH") {
const body = JSON.parse(options.body as string)
Object.assign(mockSettings, body)
return mockSettings as T
console.log("Updated mock settings:", mockSettings)
return { data: mockSettings as T, status: 200 }
}
}
@@ -247,61 +488,176 @@ export class ApiClient {
const body = JSON.parse(options.body as string)
if (body.email === "admin@example.com" && body.password === "password") {
return {
token: "mock-jwt-token-" + Date.now(),
user: mockAdmins[0],
} as T
data: {
token: "mock-jwt-token-" + Date.now(),
user: mockAdmins[0],
} as T,
status: 200,
}
}
return {
data: null as T,
error: "Invalid credentials",
status: 403,
}
throw new Error("Invalid credentials")
}
}
throw new Error(`Mock API: Unhandled ${method} ${endpoint}`)
return {
data: null as T,
error: `Mock API: Unhandled ${method} ${endpoint}`,
status: 404,
}
}
private async realApiCall<T>(endpoint: string, options: RequestInit = {}): Promise<ApiResponse<T>> {
try {
const url = `${this.baseUrl}${endpoint}`
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${this.token}`,
...options.headers,
}
const response = await fetch(url, {
...options,
headers,
})
// Handle different status codes
if (response.status === 204) {
return { data: null as T, status: 204 }
}
const responseData = await response.json()
// Check if response follows our API structure
if (responseData.hasOwnProperty("data") && responseData.hasOwnProperty("status")) {
return responseData as ApiResponse<T>
}
// If response doesn't follow our structure, wrap it
if (response.ok) {
return {
data: responseData as T,
status: response.status,
}
} else {
return {
data: null as T,
error: responseData.message || responseData.error || "Request failed",
status: response.status,
}
}
} catch (error: any) {
return {
data: null as T,
error: error.message || "Network error occurred",
status: 500,
}
}
}
async call<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
try {
// In production, this would be a real fetch call:
// const response = await fetch(endpoint, {
// ...options,
// headers: {
// ...options.headers,
// Authorization: `Bearer ${this.token}`,
// 'Content-Type': 'application/json',
// },
// })
//
// if (response.status === 401) {
// this.onUnauthorized()
// throw new Error('Unauthorized')
// }
//
// if (!response.ok) {
// throw new Error(`API call failed: ${response.statusText}`)
// }
//
// return response.json()
let response: ApiResponse<T>
// For now, use mock API
return this.mockApiCall<T>(endpoint, options)
if (this.mode === "TEST") {
response = await this.mockApiCall<T>(endpoint, options)
} else {
response = await this.realApiCall<T>(endpoint, options)
}
// Handle error responses
if (response.error || response.status >= 400) {
const error = new Error(response.error || "Request failed")
;(error as any).status = response.status
// Handle auth errors specifically
if (response.status === 401 || response.status === 403) {
this.onUnauthorized()
throw error
}
// Only call onError for non-auth errors to prevent loops
if (this.onError && response.status !== 401 && response.status !== 403) {
this.onError(response.error || "Request failed", "error")
}
throw error
}
return response.data
} catch (error: any) {
console.error("API call failed:", error)
this.onError?.(error.message, "error")
// Handle auth errors specifically
if (error.status === 401 || error.status === 403 || error.message.includes("Unauthorized")) {
this.onUnauthorized()
throw error
}
// Only call onError for non-auth errors to prevent loops
if (this.onError && !error.message.includes("Unauthorized")) {
this.onError(error.message, "error")
}
throw error
}
}
}
export async function loginWithPassword(email: string, password: string) {
// Simulate network delay
await delay(500)
// Mock login - in production this would be a real API call
if (email === "admin@example.com" && password === "password") {
return {
token: "mock-jwt-token-" + Date.now(),
user: mockAdmins[0],
// Method to update mode
updateMode(mode: AppMode, baseUrl?: string) {
this.mode = mode
if (baseUrl) {
this.baseUrl = baseUrl
}
}
}
export async function loginWithPassword(
email: string,
password: string,
mode: AppMode = "TEST",
baseUrl = "https://api.example.com",
) {
if (mode === "TEST") {
// Simulate network delay
await delay(500)
// Mock login - in production this would be a real API call
if (email === "admin@example.com" && password === "password") {
return {
token: "mock-jwt-token-" + Date.now(),
user: mockAdmins[0],
}
}
throw new Error("Invalid credentials")
} else {
// Real API call
try {
const response = await fetch(`${baseUrl}/api/v1/admins/auth-with-password`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, password }),
})
const responseData = await response.json()
if (response.ok) {
// Check if response follows our API structure
if (responseData.data) {
return responseData.data
}
return responseData
} else {
throw new Error(responseData.error || responseData.message || "Login failed")
}
} catch (error: any) {
throw new Error(error.message || "Network error occurred")
}
}
throw new Error("Invalid credentials")
}

53
lib/app-state.ts Normal file
View File

@@ -0,0 +1,53 @@
"use client"
import * as React from "react"
export type AppMode = "TEST" | "PROD"
interface AppState {
mode: AppMode
setMode: (mode: AppMode) => void
}
const AppStateContext = React.createContext<AppState | null>(null)
export function AppStateProvider({ children }: { children: React.ReactNode }) {
const [mode, setMode] = React.useState<AppMode>(() => {
if (typeof window !== "undefined") {
try {
const savedMode = localStorage.getItem("app_mode")
return (savedMode as AppMode) || "TEST"
} catch {
return "TEST"
}
}
return "TEST"
})
const updateMode = React.useCallback((newMode: AppMode) => {
setMode(newMode)
try {
localStorage.setItem("app_mode", newMode)
} catch (error) {
console.warn("Failed to save app mode:", error)
}
}, [])
const value = React.useMemo(
() => ({
mode,
setMode: updateMode,
}),
[mode, updateMode],
)
return <AppStateContext.Provider value={value}>{children}</AppStateContext.Provider>
}
export function useAppState() {
const context = React.useContext(AppStateContext)
if (!context) {
throw new Error("useAppState must be used within an AppStateProvider")
}
return context
}

171
lib/router.ts Normal file
View File

@@ -0,0 +1,171 @@
"use client"
import * as React from "react"
export interface RouteParams {
[key: string]: string
}
export interface ParsedRoute {
path: string
params: RouteParams
}
// Use a custom event system instead of relying on hash changes
const ROUTE_CHANGE_EVENT = "custom-route-change"
let currentRoute: ParsedRoute = { path: "/tables", params: {} }
export function parseRoute(hash: string): ParsedRoute {
try {
// Remove the # if present
const cleanHash = hash.startsWith("#") ? hash.slice(1) : hash
// If empty, default to /tables
if (!cleanHash) {
return { path: "/tables", params: {} }
}
// Split path and query string
const [pathPart, queryPart] = cleanHash.split("?")
// Parse query parameters
const params: RouteParams = {}
if (queryPart) {
try {
const searchParams = new URLSearchParams(queryPart)
for (const [key, value] of searchParams.entries()) {
params[key] = value
}
} catch (error) {
console.warn("Failed to parse query parameters:", error)
}
}
return {
path: pathPart || "/tables",
params,
}
} catch (error) {
console.warn("Failed to parse route:", error)
return { path: "/tables", params: {} }
}
}
export function buildRoute(path: string, params?: RouteParams): string {
try {
let route = path.startsWith("/") ? path : `/${path}`
if (params && Object.keys(params).length > 0) {
const searchParams = new URLSearchParams()
for (const [key, value] of Object.entries(params)) {
if (value) {
searchParams.set(key, value)
}
}
const queryString = searchParams.toString()
if (queryString) {
route += `?${queryString}`
}
}
return route
} catch (error) {
console.warn("Failed to build route:", error)
return "/tables"
}
}
// Custom event dispatcher
function dispatchRouteChange(route: ParsedRoute) {
const event = new CustomEvent(ROUTE_CHANGE_EVENT, { detail: route })
window.dispatchEvent(event)
}
export function useRouter() {
const [route, setRoute] = React.useState<ParsedRoute>(() => {
if (typeof window !== "undefined") {
try {
const initialRoute = parseRoute(window.location.hash)
currentRoute = initialRoute
return initialRoute
} catch (error) {
console.warn("Failed to get initial route:", error)
return { path: "/tables", params: {} }
}
}
return { path: "/tables", params: {} }
})
React.useEffect(() => {
const handleCustomRouteChange = (event: CustomEvent) => {
try {
const newRoute = event.detail as ParsedRoute
setRoute(newRoute)
currentRoute = newRoute
} catch (error) {
console.warn("Failed to handle route change:", error)
}
}
const handleHashChange = () => {
try {
const newRoute = parseRoute(window.location.hash)
setRoute(newRoute)
currentRoute = newRoute
} catch (error) {
console.warn("Failed to handle hash change:", error)
}
}
const handlePopState = () => {
try {
const newRoute = parseRoute(window.location.hash)
setRoute(newRoute)
currentRoute = newRoute
} catch (error) {
console.warn("Failed to handle pop state:", error)
}
}
// Listen for our custom events
window.addEventListener(ROUTE_CHANGE_EVENT, handleCustomRouteChange as EventListener)
// Still listen for hash changes for browser navigation
window.addEventListener("hashchange", handleHashChange)
window.addEventListener("popstate", handlePopState)
return () => {
window.removeEventListener(ROUTE_CHANGE_EVENT, handleCustomRouteChange as EventListener)
window.removeEventListener("hashchange", handleHashChange)
window.removeEventListener("popstate", handlePopState)
}
}, [])
const navigate = React.useCallback((path: string, params?: RouteParams) => {
try {
const routePath = buildRoute(path, params)
const newRoute: ParsedRoute = { path: routePath, params: params || {} }
// Update URL without triggering hash change event
const hashValue = `#${routePath}`
// Use replaceState to avoid adding to history if it's the same route
if (window.location.hash !== hashValue) {
window.history.pushState(null, "", hashValue)
}
// Dispatch our custom event
dispatchRouteChange(newRoute)
} catch (error) {
console.warn("Failed to navigate:", error)
}
}, [])
return { route, navigate }
}
// Helper function to get current route without hooks
export function getCurrentRoute(): ParsedRoute {
return currentRoute
}