mirror of
https://github.com/allankoechke/mantisbase-admin.git
synced 2026-11-30 10:19:37 +00:00
feat: refactor admin-dashboard into modular components with mock API
Split admin-dashboard into logical components and add mock API support #VERCEL_SKIP Co-authored-by: Allan K. Koech <44490960+allankoechke@users.noreply.github.com>
This commit is contained in:
File diff suppressed because it is too large
Load Diff
96
components/admins/admins-section.tsx
Normal file
96
components/admins/admins-section.tsx
Normal file
@@ -0,0 +1,96 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { MoreHorizontal, Key, Trash2 } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
import { Dialog } from "@/components/ui/dialog"
|
||||
import type { ApiClient, Admin } from "@/lib/api"
|
||||
import { ChangePasswordDialog } from "./change-password-dialog"
|
||||
|
||||
interface AdminsSectionProps {
|
||||
admins: Admin[]
|
||||
apiClient: ApiClient
|
||||
onAdminsUpdate: (admins: Admin[]) => void
|
||||
}
|
||||
|
||||
export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSectionProps) {
|
||||
const [selectedAdmin, setSelectedAdmin] = React.useState<Admin | null>(null)
|
||||
|
||||
const handleDeleteAdmin = async (adminId: string) => {
|
||||
try {
|
||||
await apiClient.call(`/api/v1/admins/${adminId}`, { method: "DELETE" })
|
||||
const updatedAdmins = await apiClient.call<Admin[]>("/api/v1/admins")
|
||||
onAdminsUpdate(updatedAdmins)
|
||||
} catch (error) {
|
||||
console.error("Failed to delete admin:", error)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">Admin Management</h2>
|
||||
<p className="text-muted-foreground">Manage administrator accounts</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Administrator Accounts</CardTitle>
|
||||
<CardDescription>{admins.length} administrator accounts</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Created</TableHead>
|
||||
<TableHead>Updated</TableHead>
|
||||
<TableHead>Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{admins.map((admin) => (
|
||||
<TableRow key={admin.id}>
|
||||
<TableCell className="font-medium">{admin.email}</TableCell>
|
||||
<TableCell>{new Date(admin.created).toLocaleDateString()}</TableCell>
|
||||
<TableCell>{new Date(admin.updated).toLocaleDateString()}</TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setSelectedAdmin(admin)}>
|
||||
<Key className="h-4 w-4 mr-2" />
|
||||
Change Password
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-destructive" onClick={() => handleDeleteAdmin(admin.id)}>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
Remove Admin
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={!!selectedAdmin} onOpenChange={() => setSelectedAdmin(null)}>
|
||||
{selectedAdmin && (
|
||||
<ChangePasswordDialog admin={selectedAdmin} apiClient={apiClient} onClose={() => setSelectedAdmin(null)} />
|
||||
)}
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
94
components/admins/change-password-dialog.tsx
Normal file
94
components/admins/change-password-dialog.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import type { ApiClient, Admin } from "@/lib/api"
|
||||
|
||||
interface ChangePasswordDialogProps {
|
||||
admin: Admin
|
||||
apiClient: ApiClient
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export function ChangePasswordDialog({ admin, apiClient, onClose }: ChangePasswordDialogProps) {
|
||||
const [newPassword, setNewPassword] = React.useState("")
|
||||
const [confirmPassword, setConfirmPassword] = React.useState("")
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [error, setError] = React.useState("")
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (newPassword !== confirmPassword) {
|
||||
setError("Passwords do not match")
|
||||
return
|
||||
}
|
||||
if (newPassword.length < 8) {
|
||||
setError("Password must be at least 8 characters")
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
setError("")
|
||||
|
||||
try {
|
||||
await apiClient.call(`/api/v1/admins/${admin.id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ password: newPassword }),
|
||||
})
|
||||
onClose()
|
||||
} catch (error) {
|
||||
setError("Failed to change password")
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Change Password</DialogTitle>
|
||||
<DialogDescription>Change password for {admin.email}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<div>
|
||||
<Label htmlFor="new-password">New Password</Label>
|
||||
<Input
|
||||
id="new-password"
|
||||
type="password"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="confirm-password">Confirm Password</Label>
|
||||
<Input
|
||||
id="confirm-password"
|
||||
type="password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
{isLoading ? "Changing..." : "Change Password"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
)
|
||||
}
|
||||
342
components/database/add-table-dialog.tsx
Normal file
342
components/database/add-table-dialog.tsx
Normal file
@@ -0,0 +1,342 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Plus, Trash2 } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} 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"
|
||||
|
||||
interface AddTableDialogProps {
|
||||
apiClient: ApiClient
|
||||
onTablesUpdate: (tables: TableMetadata[]) => void
|
||||
}
|
||||
|
||||
export function AddTableDialog({ apiClient, onTablesUpdate }: AddTableDialogProps) {
|
||||
const [tableType, setTableType] = React.useState<"base" | "auth" | "view">("base")
|
||||
const [tableName, setTableName] = React.useState("")
|
||||
const [columns, setColumns] = React.useState<
|
||||
Array<{
|
||||
name: string
|
||||
type: string
|
||||
primaryKey: boolean
|
||||
nullable: boolean
|
||||
unique?: boolean
|
||||
isFile?: boolean
|
||||
isSystem?: boolean
|
||||
}>
|
||||
>([])
|
||||
const [sqlQuery, setSqlQuery] = React.useState("")
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [open, setOpen] = React.useState(false)
|
||||
|
||||
const dataTypes = [
|
||||
"string",
|
||||
"int",
|
||||
"bigint",
|
||||
"double",
|
||||
"float",
|
||||
"boolean",
|
||||
"date",
|
||||
"datetime",
|
||||
"timestamp",
|
||||
"json",
|
||||
"xml",
|
||||
"text",
|
||||
"varchar",
|
||||
"char",
|
||||
"binary",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
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 },
|
||||
])
|
||||
} 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 },
|
||||
])
|
||||
} else {
|
||||
setColumns([])
|
||||
}
|
||||
}, [tableType])
|
||||
|
||||
const addColumn = () => {
|
||||
setColumns([...columns, { name: "", type: "string", primaryKey: false, nullable: true, isSystem: false }])
|
||||
}
|
||||
|
||||
const removeColumn = (index: number) => {
|
||||
const column = columns[index]
|
||||
if (columns.length > 1 && !column.isSystem) {
|
||||
setColumns(columns.filter((_, i) => i !== index))
|
||||
}
|
||||
}
|
||||
|
||||
const updateColumn = (index: number, field: string, value: any) => {
|
||||
const updatedColumns = columns.map((col, i) => (i === index ? { ...col, [field]: value } : col))
|
||||
setColumns(updatedColumns)
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!tableName.trim()) return
|
||||
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const tableData: Partial<TableMetadata> = {
|
||||
name: tableName,
|
||||
type: tableType,
|
||||
rules: {
|
||||
list: "",
|
||||
get: "",
|
||||
add: tableType === "view" ? "" : "",
|
||||
update: tableType === "view" ? "" : "",
|
||||
delete: tableType === "view" ? "" : "",
|
||||
},
|
||||
}
|
||||
|
||||
if (tableType === "view") {
|
||||
tableData.sql = sqlQuery
|
||||
} else {
|
||||
tableData.fields = columns
|
||||
}
|
||||
|
||||
await apiClient.call("/api/v1/tables", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(tableData),
|
||||
})
|
||||
|
||||
// Refresh tables list
|
||||
const updatedTables = await apiClient.call<TableMetadata[]>("/api/v1/tables")
|
||||
onTablesUpdate(updatedTables)
|
||||
|
||||
// Reset form
|
||||
setTableName("")
|
||||
setSqlQuery("")
|
||||
setOpen(false)
|
||||
} catch (error) {
|
||||
console.error("Failed to create table:", error)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<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>
|
||||
<DialogTitle>Create New Table</DialogTitle>
|
||||
<DialogDescription>Create a new database table with custom columns and settings.</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="table-name">Table Name</Label>
|
||||
<Input
|
||||
id="table-name"
|
||||
placeholder="Enter table name"
|
||||
value={tableName}
|
||||
onChange={(e) => setTableName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="table-type">Table Type</Label>
|
||||
<Select value={tableType} onValueChange={(value: "base" | "auth" | "view") => setTableType(value)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="base">Base Table</SelectItem>
|
||||
<SelectItem value="auth">Auth Table</SelectItem>
|
||||
<SelectItem value="view">View</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{tableType === "view" ? (
|
||||
<div>
|
||||
<Label htmlFor="sql-query">SQL Query</Label>
|
||||
<Textarea
|
||||
id="sql-query"
|
||||
placeholder="SELECT * FROM users WHERE active = true"
|
||||
value={sqlQuery}
|
||||
onChange={(e) => setSqlQuery(e.target.value)}
|
||||
className="min-h-[200px] font-mono"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground mt-2">
|
||||
Enter the SQL query that defines this view. The query should be valid SQL syntax.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div>
|
||||
<Label className="text-base font-medium">Columns</Label>
|
||||
<p className="text-sm text-muted-foreground">Define the columns for your {tableType} table</p>
|
||||
</div>
|
||||
<Button type="button" variant="outline" size="sm" onClick={addColumn}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Column
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 max-h-[300px] overflow-y-auto">
|
||||
{columns.map((column, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={`flex items-center gap-3 p-3 border rounded-lg ${column.isSystem ? "bg-muted/50" : ""}`}
|
||||
>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
placeholder="Column name"
|
||||
value={column.name}
|
||||
onChange={(e) => updateColumn(index, "name", e.target.value)}
|
||||
disabled={column.isSystem}
|
||||
className={column.isSystem ? "bg-muted" : ""}
|
||||
/>
|
||||
{column.isSystem && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
System
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-32">
|
||||
<Select
|
||||
value={column.type}
|
||||
onValueChange={(value) => updateColumn(index, "type", value)}
|
||||
disabled={column.isSystem}
|
||||
>
|
||||
<SelectTrigger className={column.isSystem ? "bg-muted" : ""}>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{dataTypes.map((type) => (
|
||||
<SelectItem key={type} value={type}>
|
||||
{type.toUpperCase()}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex items-center space-x-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id={`primary-${index}`}
|
||||
checked={column.primaryKey}
|
||||
onChange={(e) => updateColumn(index, "primaryKey", e.target.checked)}
|
||||
disabled={column.isSystem}
|
||||
className="rounded"
|
||||
/>
|
||||
<Label htmlFor={`primary-${index}`} className="text-xs">
|
||||
PK
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id={`unique-${index}`}
|
||||
checked={column.unique || false}
|
||||
onChange={(e) => updateColumn(index, "unique", e.target.checked)}
|
||||
disabled={column.isSystem}
|
||||
className="rounded"
|
||||
/>
|
||||
<Label htmlFor={`unique-${index}`} className="text-xs">
|
||||
Unique
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id={`required-${index}`}
|
||||
checked={!column.nullable}
|
||||
onChange={(e) => updateColumn(index, "nullable", !e.target.checked)}
|
||||
disabled={column.isSystem}
|
||||
className="rounded"
|
||||
/>
|
||||
<Label htmlFor={`required-${index}`} className="text-xs">
|
||||
Required
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id={`files-${index}`}
|
||||
checked={column.isFile || false}
|
||||
onChange={(e) => updateColumn(index, "isFile", e.target.checked)}
|
||||
disabled={column.isSystem}
|
||||
className="rounded"
|
||||
/>
|
||||
<Label htmlFor={`files-${index}`} className="text-xs">
|
||||
Files
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => removeColumn(index)}
|
||||
disabled={columns.length === 1 || column.isSystem}
|
||||
className={column.isSystem ? "opacity-30" : ""}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="text-sm text-muted-foreground mt-2">
|
||||
<p>
|
||||
<Badge variant="outline" className="text-xs mr-2">
|
||||
System
|
||||
</Badge>
|
||||
System columns are automatically managed and cannot be modified.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSubmit} disabled={isLoading || !tableName.trim()}>
|
||||
{isLoading ? "Creating..." : `Create ${tableType === "view" ? "View" : "Table"}`}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
133
components/database/database-section.tsx
Normal file
133
components/database/database-section.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Search, Table, Eye, Edit, Trash2, MoreHorizontal } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import type { ApiClient, TableMetadata } from "@/lib/api"
|
||||
import { AddTableDialog } from "./add-table-dialog"
|
||||
import { TableDetailView } from "./table-detail-view"
|
||||
|
||||
interface DatabaseSectionProps {
|
||||
apiClient: ApiClient
|
||||
tables: TableMetadata[]
|
||||
onTablesUpdate: (tables: TableMetadata[]) => void
|
||||
}
|
||||
|
||||
export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseSectionProps) {
|
||||
const [selectedTable, setSelectedTable] = React.useState<string | null>(null)
|
||||
const [searchTerm, setSearchTerm] = React.useState("")
|
||||
|
||||
const filteredTables = tables.filter((table) => table.name.toLowerCase().includes(searchTerm.toLowerCase()))
|
||||
|
||||
const handleDeleteTable = async (tableId: string) => {
|
||||
try {
|
||||
await apiClient.call(`/api/v1/tables/${tableId}`, { method: "DELETE" })
|
||||
const updatedTables = await apiClient.call<TableMetadata[]>("/api/v1/tables")
|
||||
onTablesUpdate(updatedTables)
|
||||
} catch (error) {
|
||||
console.error("Failed to delete table:", error)
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedTable) {
|
||||
const tableInfo = tables.find((t) => t.name === selectedTable)
|
||||
if (tableInfo) {
|
||||
return (
|
||||
<TableDetailView
|
||||
table={tableInfo}
|
||||
onBack={() => setSelectedTable(null)}
|
||||
apiClient={apiClient}
|
||||
onTableUpdate={(updatedTable) => {
|
||||
const updatedTables = tables.map((t) => (t.id === updatedTable.id ? updatedTable : t))
|
||||
onTablesUpdate(updatedTables)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">Database Tables</h2>
|
||||
<p className="text-muted-foreground">Manage your database tables and data</p>
|
||||
</div>
|
||||
<AddTableDialog apiClient={apiClient} onTablesUpdate={onTablesUpdate} />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Search className="h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search tables..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="max-w-sm"
|
||||
/>
|
||||
</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">
|
||||
<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>
|
||||
<Button variant="ghost" size="sm">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setSelectedTable(table.name)}>
|
||||
<Eye className="h-4 w-4 mr-2" />
|
||||
View Details
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<Edit className="h-4 w-4 mr-2" />
|
||||
Edit Structure
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-destructive" onClick={() => 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>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
280
components/database/table-detail-view.tsx
Normal file
280
components/database/table-detail-view.tsx
Normal file
@@ -0,0 +1,280 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Cog, FileText } 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 { Badge } from "@/components/ui/badge"
|
||||
import type { ApiClient, TableMetadata } from "@/lib/api"
|
||||
|
||||
interface TableDetailViewProps {
|
||||
table: TableMetadata
|
||||
onBack: () => void
|
||||
apiClient: ApiClient
|
||||
onTableUpdate: (table: TableMetadata) => void
|
||||
}
|
||||
|
||||
export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: TableDetailViewProps) {
|
||||
const [activeTab, setActiveTab] = React.useState("config")
|
||||
const [rules, setRules] = React.useState(table.rules)
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
|
||||
const handleSaveRules = async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const updatedTable = await apiClient.call<TableMetadata>(`/api/v1/tables/${table.id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ rules }),
|
||||
})
|
||||
onTableUpdate(updatedTable)
|
||||
} catch (error) {
|
||||
console.error("Failed to update rules:", error)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" onClick={onBack}>
|
||||
← Back
|
||||
</Button>
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold capitalize">{table.name} Table</h2>
|
||||
<p className="text-muted-foreground">Manage table configuration</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-4 border-b">
|
||||
{[
|
||||
{ id: "config", label: "Configuration", icon: Cog },
|
||||
{ id: "docs", label: "API Documentation", icon: FileText },
|
||||
].map((tab) => (
|
||||
<Button
|
||||
key={tab.id}
|
||||
variant={activeTab === tab.id ? "default" : "ghost"}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<tab.icon className="h-4 w-4" />
|
||||
{tab.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{activeTab === "config" && (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Access Control Rules</CardTitle>
|
||||
<CardDescription>Configure access permissions using rule expressions</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid gap-4">
|
||||
<div>
|
||||
<Label htmlFor="list-rule">List Rule</Label>
|
||||
<Input
|
||||
id="list-rule"
|
||||
placeholder='e.g., "True", "auth.id != None", ""'
|
||||
value={rules.list}
|
||||
onChange={(e) => setRules({ ...rules, list: e.target.value })}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">Controls who can list records</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="get-rule">Get Rule</Label>
|
||||
<Input
|
||||
id="get-rule"
|
||||
placeholder='e.g., "True", "auth.id == record.user_id"'
|
||||
value={rules.get}
|
||||
onChange={(e) => setRules({ ...rules, get: e.target.value })}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">Controls who can view individual records</p>
|
||||
</div>
|
||||
|
||||
{table.type !== "view" && (
|
||||
<>
|
||||
<div>
|
||||
<Label htmlFor="add-rule">Add Rule</Label>
|
||||
<Input
|
||||
id="add-rule"
|
||||
placeholder='e.g., "auth.id != None", "auth.role == "admin""'
|
||||
value={rules.add}
|
||||
onChange={(e) => setRules({ ...rules, add: e.target.value })}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">Controls who can create new records</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="update-rule">Update Rule</Label>
|
||||
<Input
|
||||
id="update-rule"
|
||||
placeholder='e.g., "auth.id == record.user_id", ""'
|
||||
value={rules.update}
|
||||
onChange={(e) => setRules({ ...rules, update: e.target.value })}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">Controls who can update records</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="delete-rule">Delete Rule</Label>
|
||||
<Input
|
||||
id="delete-rule"
|
||||
placeholder='e.g., "auth.role == "admin"", ""'
|
||||
value={rules.delete}
|
||||
onChange={(e) => setRules({ ...rules, delete: e.target.value })}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">Controls who can delete records</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={handleSaveRules} disabled={isLoading}>
|
||||
{isLoading ? "Saving..." : "Save Rules"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 p-3 bg-muted rounded-lg">
|
||||
<h5 className="font-medium mb-2">Rule Examples</h5>
|
||||
<div className="space-y-1 text-sm text-muted-foreground">
|
||||
<p>
|
||||
<code>""</code> - Admin access only
|
||||
</p>
|
||||
<p>
|
||||
<code>"True"</code> - Public access
|
||||
</p>
|
||||
<p>
|
||||
<code>"auth.id != None"</code> - Authenticated users only
|
||||
</p>
|
||||
<p>
|
||||
<code>"auth.id == record.user_id"</code> - Owner access only
|
||||
</p>
|
||||
<p>
|
||||
<code>"auth.role == \"admin\""</code> - Admin role required
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Table Structure</CardTitle>
|
||||
<CardDescription>
|
||||
{table.type === "view" ? "SQL Query" : "Table fields and their properties"}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{table.type === "view" ? (
|
||||
<pre className="bg-muted p-4 rounded-lg text-sm overflow-x-auto">
|
||||
<code>{table.sql}</code>
|
||||
</pre>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{table.fields?.map((field, index) => (
|
||||
<div key={index} className="flex items-center justify-between p-2 border rounded">
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="text-sm font-mono">{field.name}</code>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{field.type}
|
||||
</Badge>
|
||||
{field.primaryKey && (
|
||||
<Badge variant="default" className="text-xs">
|
||||
PK
|
||||
</Badge>
|
||||
)}
|
||||
{field.unique && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
Unique
|
||||
</Badge>
|
||||
)}
|
||||
{!field.nullable && (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
Required
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === "docs" && (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>API Documentation</CardTitle>
|
||||
<CardDescription>Auto-generated API endpoints for the {table.name} table</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
<div className="p-4 border rounded-lg">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Badge className="bg-green-100 text-green-800">GET</Badge>
|
||||
<code className="text-sm">/api/v1/tables/{table.name}</code>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">List all records in the {table.name} table</p>
|
||||
</div>
|
||||
|
||||
<div className="p-4 border rounded-lg">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Badge className="bg-green-100 text-green-800">GET</Badge>
|
||||
<code className="text-sm">
|
||||
/api/v1/tables/{table.name}/{"{"}id{"}"}
|
||||
</code>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">Get a specific record by ID</p>
|
||||
</div>
|
||||
|
||||
{table.type !== "view" && (
|
||||
<>
|
||||
<div className="p-4 border rounded-lg">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Badge className="bg-blue-100 text-blue-800">POST</Badge>
|
||||
<code className="text-sm">/api/v1/tables/{table.name}</code>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">Create a new record</p>
|
||||
</div>
|
||||
|
||||
<div className="p-4 border rounded-lg">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Badge className="bg-yellow-100 text-yellow-800">PATCH</Badge>
|
||||
<code className="text-sm">
|
||||
/api/v1/tables/{table.name}/{"{"}id{"}"}
|
||||
</code>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">Update a specific record</p>
|
||||
</div>
|
||||
|
||||
<div className="p-4 border rounded-lg">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Badge className="bg-red-100 text-red-800">DELETE</Badge>
|
||||
<code className="text-sm">
|
||||
/api/v1/tables/{table.name}/{"{"}id{"}"}
|
||||
</code>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">Delete a specific record</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -8,14 +8,15 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import { loginWithPassword } from "@/lib/api"
|
||||
|
||||
interface LoginFormProps {
|
||||
onLogin: (token: string) => void
|
||||
}
|
||||
|
||||
export function LoginForm({ onLogin }: LoginFormProps) {
|
||||
const [email, setEmail] = React.useState("")
|
||||
const [password, setPassword] = React.useState("")
|
||||
const [email, setEmail] = React.useState("admin@example.com")
|
||||
const [password, setPassword] = React.useState("password")
|
||||
const [showPassword, setShowPassword] = React.useState(false)
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [error, setError] = React.useState("")
|
||||
@@ -26,19 +27,7 @@ export function LoginForm({ onLogin }: LoginFormProps) {
|
||||
setError("")
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/v1/admins/auth-with-password", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ email, password }),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Invalid credentials")
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const data = await loginWithPassword(email, password)
|
||||
localStorage.setItem("admin_token", data.token)
|
||||
onLogin(data.token)
|
||||
} catch (err) {
|
||||
@@ -104,6 +93,12 @@ export function LoginForm({ onLogin }: LoginFormProps) {
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? "Signing in..." : "Sign In"}
|
||||
</Button>
|
||||
|
||||
<div className="text-sm text-muted-foreground text-center">
|
||||
<p>Demo credentials:</p>
|
||||
<p>Email: admin@example.com</p>
|
||||
<p>Password: password</p>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
47
components/settings/settings-section.tsx
Normal file
47
components/settings/settings-section.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
"use client"
|
||||
|
||||
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"
|
||||
|
||||
export function SettingsSection() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">Application Settings</h2>
|
||||
<p className="text-muted-foreground">Configure global application settings</p>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>General Settings</CardTitle>
|
||||
<CardDescription>Basic application configuration</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<Label htmlFor="app-name">Application Name</Label>
|
||||
<Input id="app-name" defaultValue="Admin Dashboard" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="base-url">Base URL</Label>
|
||||
<Input id="base-url" defaultValue="https://api.example.com" placeholder="https://your-api-domain.com" />
|
||||
<p className="text-sm text-muted-foreground mt-1">The base URL for your API endpoints</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<Label>Maintenance Mode</Label>
|
||||
<p className="text-sm text-muted-foreground">Enable maintenance mode for the application</p>
|
||||
</div>
|
||||
<Switch />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button>Save Settings</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
260
lib/api.ts
Normal file
260
lib/api.ts
Normal file
@@ -0,0 +1,260 @@
|
||||
"use client"
|
||||
|
||||
// Mock data for testing
|
||||
const mockTables = [
|
||||
{
|
||||
id: "1",
|
||||
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'",
|
||||
},
|
||||
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 },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
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'",
|
||||
},
|
||||
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 },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
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: "",
|
||||
},
|
||||
sql: "SELECT id, email, created FROM users WHERE updated > NOW() - INTERVAL 30 DAY",
|
||||
},
|
||||
]
|
||||
|
||||
const mockAdmins = [
|
||||
{
|
||||
id: "1",
|
||||
email: "admin@example.com",
|
||||
created: "2024-01-01T10:00:00Z",
|
||||
updated: "2024-01-01T10:00:00Z",
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
email: "john.admin@example.com",
|
||||
created: "2024-01-15T10:00:00Z",
|
||||
updated: "2024-01-15T10:00:00Z",
|
||||
},
|
||||
]
|
||||
|
||||
// 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 class ApiClient {
|
||||
private token: string
|
||||
private onUnauthorized: () => void
|
||||
|
||||
constructor(token: string, onUnauthorized: () => void) {
|
||||
this.token = token
|
||||
this.onUnauthorized = onUnauthorized
|
||||
}
|
||||
|
||||
private async mockApiCall<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
|
||||
// Simulate network delay
|
||||
await delay(300 + Math.random() * 200)
|
||||
|
||||
// Simulate 401 for invalid tokens (uncomment to test)
|
||||
// if (Math.random() < 0.1) {
|
||||
// this.onUnauthorized()
|
||||
// throw new Error('Unauthorized')
|
||||
// }
|
||||
|
||||
const method = options.method || "GET"
|
||||
const url = new URL(endpoint, "http://localhost")
|
||||
|
||||
// Mock API responses
|
||||
if (url.pathname === "/api/v1/tables") {
|
||||
if (method === "GET") {
|
||||
return mockTables as T
|
||||
}
|
||||
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(),
|
||||
}
|
||||
mockTables.push(newTable)
|
||||
return newTable as T
|
||||
}
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith("/api/v1/tables/")) {
|
||||
const tableId = url.pathname.split("/").pop()
|
||||
const tableIndex = mockTables.findIndex((t) => t.id === tableId)
|
||||
|
||||
if (method === "PATCH" && tableIndex !== -1) {
|
||||
const body = JSON.parse(options.body as string)
|
||||
mockTables[tableIndex] = {
|
||||
...mockTables[tableIndex],
|
||||
...body,
|
||||
updated: new Date().toISOString(),
|
||||
}
|
||||
return mockTables[tableIndex] as T
|
||||
}
|
||||
|
||||
if (method === "DELETE" && tableIndex !== -1) {
|
||||
mockTables.splice(tableIndex, 1)
|
||||
return { success: true } as T
|
||||
}
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/admins") {
|
||||
if (method === "GET") {
|
||||
return mockAdmins as T
|
||||
}
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith("/api/v1/admins/")) {
|
||||
const adminId = url.pathname.split("/").pop()
|
||||
const adminIndex = mockAdmins.findIndex((a) => a.id === adminId)
|
||||
|
||||
if (method === "PATCH" && adminIndex !== -1) {
|
||||
const body = JSON.parse(options.body as string)
|
||||
mockAdmins[adminIndex] = {
|
||||
...mockAdmins[adminIndex],
|
||||
updated: new Date().toISOString(),
|
||||
}
|
||||
return mockAdmins[adminIndex] as T
|
||||
}
|
||||
|
||||
if (method === "DELETE" && adminIndex !== -1) {
|
||||
mockAdmins.splice(adminIndex, 1)
|
||||
return { success: true } as T
|
||||
}
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/admins/auth-with-password") {
|
||||
if (method === "POST") {
|
||||
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
|
||||
}
|
||||
throw new Error("Invalid credentials")
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Mock API: Unhandled ${method} ${endpoint}`)
|
||||
}
|
||||
|
||||
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()
|
||||
|
||||
// For now, use mock API
|
||||
return this.mockApiCall<T>(endpoint, options)
|
||||
} catch (error) {
|
||||
console.error("API call failed:", 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],
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("Invalid credentials")
|
||||
}
|
||||
Reference in New Issue
Block a user