mirror of
https://github.com/allankoechke/mantisbase-admin.git
synced 2026-12-01 01:15:36 +00:00
Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ca9e58c9d0 | |||
| 81827d5a65 | |||
| 93c6066270 | |||
| 5c57809f2d | |||
| 2f4d670420 | |||
| ee5166257c | |||
| 9734a648a1 | |||
| f6292111c8 | |||
| 96ecfa91a7 | |||
| 12c43bba26 | |||
| 9d92efd4a9 | |||
| fb4b5eee2c | |||
| 33bf97d7f9 | |||
| 77de7c447c | |||
| 7b99195ccf | |||
| 60fee77f05 | |||
| e5b03b2fb5 | |||
| 420583f13d | |||
| ded52c728d | |||
| 9767bbfd66 | |||
| 23b578aa0b | |||
| ea46055dec | |||
| 67cee19b86 | |||
| 595a6d08f6 | |||
| 925da2ecff | |||
| 7dbb224642 | |||
| 437282b753 | |||
| 247236828a | |||
| c05a27ae0e | |||
| d924f2e8e5 | |||
| f8d006e845 | |||
| e361e7aea8 |
40
.github/workflows/release-static.yml
vendored
40
.github/workflows/release-static.yml
vendored
@@ -39,3 +39,43 @@ jobs:
|
||||
files: mantis-admin-static.zip
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Checkout mb-admin branch
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: mb-admin
|
||||
path: mb-admin-branch
|
||||
|
||||
- name: Clear and update public directory in mb-admin
|
||||
run: |
|
||||
# Remove existing public directory contents
|
||||
rm -rf mb-admin-branch/public
|
||||
mkdir -p mb-admin-branch/public
|
||||
|
||||
# Copy built files to public directory
|
||||
cp -r out/* mb-admin-branch/public/
|
||||
|
||||
- name: Commit and push to mb-admin branch
|
||||
working-directory: mb-admin-branch
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
git add public/
|
||||
git commit -m "chore: update static files from master tag ${{ github.ref_name }}" --allow-empty
|
||||
git push origin mb-admin
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Zip mb-admin branch
|
||||
run: |
|
||||
zip -r mantis-admin-branch.zip mb-admin-branch -x "mb-admin-branch/.git/*"
|
||||
|
||||
- name: Upload both zips to release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
files: |
|
||||
mantis-admin-static.zip
|
||||
mantis-admin-branch.zip
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
33
app/[[...slug]]/error.tsx
Normal file
33
app/[[...slug]]/error.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { AlertTriangle } from "lucide-react"
|
||||
|
||||
interface ErrorProps {
|
||||
error: Error & { digest?: string }
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
export default function Error({ error, reset }: ErrorProps) {
|
||||
React.useEffect(() => {
|
||||
// Log the error to an error reporting service
|
||||
console.error("Route error:", error)
|
||||
}, [error])
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen w-full items-center justify-center bg-background">
|
||||
<div className="text-center space-y-4 max-w-md">
|
||||
<AlertTriangle className="h-12 w-12 text-destructive mx-auto" />
|
||||
<h1 className="text-2xl font-bold">Something went wrong</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{error.message || "An unexpected error occurred"}
|
||||
</p>
|
||||
<Button onClick={reset} variant="default">
|
||||
Try again
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
44
app/[[...slug]]/page.tsx
Normal file
44
app/[[...slug]]/page.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
// Optional catch-all route for all paths including root
|
||||
// This handles paths like /, /setup, /entities/students, etc.
|
||||
// Note: This must be a server component to use generateStaticParams()
|
||||
// The MainPage component it renders is already a client component
|
||||
import MainPage from "@/components/main-page"
|
||||
|
||||
// For static export, Next.js requires all routes to be pre-generated
|
||||
// Since entity names are dynamic, we can't generate them all at build time
|
||||
// Workaround: We generate a catch-all page that handles all routing client-side
|
||||
// The issue is that Next.js will complain about missing routes during build,
|
||||
// but the client-side router will handle them correctly at runtime
|
||||
export function generateStaticParams() {
|
||||
// Return base routes that are always accessible
|
||||
// Include empty array for root path (/)
|
||||
// For dynamic entity routes like /entities/test, we can't pre-generate them
|
||||
// The client-side router will parse the actual entity name from window.location.pathname
|
||||
return [
|
||||
{ slug: [] }, // Root path
|
||||
{ slug: ['setup'] },
|
||||
{ slug: ['login'] },
|
||||
{ slug: ['entities'] },
|
||||
{ slug: ['logs'] },
|
||||
{ slug: ['admins'] },
|
||||
{ slug: ['settings'] },
|
||||
]
|
||||
}
|
||||
|
||||
// Note: With static export, Next.js will complain about routes not in generateStaticParams
|
||||
// However, since we're using client-side routing, this is expected and acceptable
|
||||
// The Page component will handle all routing based on window.location.pathname
|
||||
export default function CatchAllPage({
|
||||
params,
|
||||
}: {
|
||||
params: { slug?: string[] }
|
||||
// Explicitly don't use searchParams to avoid serialization issues with static export
|
||||
}) {
|
||||
// Always render the main page - client-side router handles the actual routing
|
||||
// The MainPage component parses window.location.pathname and renders the appropriate view
|
||||
// This works for both pre-generated routes and dynamic routes like /entities/test
|
||||
// Params are optional for the optional catch-all route
|
||||
// We don't use searchParams here - the client-side router handles query params
|
||||
return <MainPage />
|
||||
}
|
||||
|
||||
33
app/error.tsx
Normal file
33
app/error.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { AlertTriangle } from "lucide-react"
|
||||
|
||||
interface ErrorProps {
|
||||
error: Error & { digest?: string }
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
export default function Error({ error, reset }: ErrorProps) {
|
||||
React.useEffect(() => {
|
||||
// Log the error to an error reporting service
|
||||
console.error("Application error:", error)
|
||||
}, [error])
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen w-full items-center justify-center bg-background">
|
||||
<div className="text-center space-y-4 max-w-md">
|
||||
<AlertTriangle className="h-12 w-12 text-destructive mx-auto" />
|
||||
<h1 className="text-2xl font-bold">Something went wrong</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{error.message || "An unexpected error occurred"}
|
||||
</p>
|
||||
<Button onClick={reset} variant="default">
|
||||
Try again
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -4,48 +4,50 @@
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
/* Light Theme - Clean and minimal */
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 222.2 84% 4.9%;
|
||||
--foreground: 0 0% 3.9%;
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 222.2 84% 4.9%;
|
||||
--card-foreground: 0 0% 3.9%;
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 222.2 84% 4.9%;
|
||||
--primary: 142.1 76.2% 36.3%;
|
||||
--primary-foreground: 355.7 100% 97.3%;
|
||||
--secondary: 210 40% 96%;
|
||||
--secondary-foreground: 222.2 84% 4.9%;
|
||||
--muted: 210 40% 96%;
|
||||
--muted-foreground: 215.4 16.3% 46.9%;
|
||||
--accent: 210 40% 96%;
|
||||
--accent-foreground: 222.2 84% 4.9%;
|
||||
--popover-foreground: 0 0% 3.9%;
|
||||
--primary: 0 0% 9%;
|
||||
--primary-foreground: 0 0% 98%;
|
||||
--secondary: 0 0% 96.1%;
|
||||
--secondary-foreground: 0 0% 9%;
|
||||
--muted: 0 0% 96.1%;
|
||||
--muted-foreground: 0 0% 45.1%;
|
||||
--accent: 0 0% 96.1%;
|
||||
--accent-foreground: 0 0% 9%;
|
||||
--destructive: 0 84.2% 60.2%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
--border: 214.3 31.8% 91.4%;
|
||||
--input: 214.3 31.8% 91.4%;
|
||||
--ring: 142.1 76.2% 36.3%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 0 0% 89.8%;
|
||||
--input: 0 0% 89.8%;
|
||||
--ring: 0 0% 3.9%;
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: 222.2 84% 4.9%;
|
||||
--foreground: 210 40% 98%;
|
||||
--card: 222.2 84% 4.9%;
|
||||
--card-foreground: 210 40% 98%;
|
||||
--popover: 222.2 84% 4.9%;
|
||||
--popover-foreground: 210 40% 98%;
|
||||
--primary: 142.1 70.6% 45.3%;
|
||||
--primary-foreground: 144.9 80.4% 10%;
|
||||
--secondary: 217.2 32.6% 17.5%;
|
||||
--secondary-foreground: 210 40% 98%;
|
||||
--muted: 217.2 32.6% 17.5%;
|
||||
--muted-foreground: 215 20.2% 65.1%;
|
||||
--accent: 217.2 32.6% 17.5%;
|
||||
--accent-foreground: 210 40% 98%;
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
--border: 217.2 32.6% 17.5%;
|
||||
--input: 217.2 32.6% 17.5%;
|
||||
--ring: 142.4 71.8% 29.2%;
|
||||
/* Visual Studio Dark Theme - Improved Contrast */
|
||||
--background: 0 0% 13%;
|
||||
--foreground: 0 0% 95%;
|
||||
--card: 0 0% 15%;
|
||||
--card-foreground: 0 0% 95%;
|
||||
--popover: 0 0% 15%;
|
||||
--popover-foreground: 0 0% 95%;
|
||||
--primary: 0 0% 98%;
|
||||
--primary-foreground: 0 0% 9%;
|
||||
--secondary: 0 0% 20%;
|
||||
--secondary-foreground: 0 0% 98%;
|
||||
--muted: 0 0% 20%;
|
||||
--muted-foreground: 0 0% 75%;
|
||||
--accent: 0 0% 20%;
|
||||
--accent-foreground: 0 0% 98%;
|
||||
--destructive: 0 62.8% 50%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 0 0% 25%;
|
||||
--input: 0 0% 20%;
|
||||
--ring: 0 0% 90%;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,8 @@ import type { Metadata } from 'next'
|
||||
import './globals.css'
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Mantis Admin',
|
||||
description: 'Admin dashboard for Mantis BaaS',
|
||||
generator: 'mantis.app',
|
||||
title: 'Mantis Admin Dashboard',
|
||||
description: 'Admin dashboard for Mantis: A lightweight BaaS in C++'
|
||||
}
|
||||
|
||||
export default function RootLayout({
|
||||
@@ -14,6 +13,9 @@ export default function RootLayout({
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</head>
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
)
|
||||
|
||||
11
app/not-found.tsx
Normal file
11
app/not-found.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
// Custom 404 page for static export
|
||||
// This handles routes that weren't pre-generated (like dynamic entity routes)
|
||||
// It renders the main MainPage component which handles routing client-side
|
||||
import MainPage from "@/components/main-page"
|
||||
|
||||
export default function NotFound() {
|
||||
// Render the main page - client-side router will handle the actual routing
|
||||
// This allows dynamic routes like /entities/test to work even if not pre-generated
|
||||
return <MainPage />
|
||||
}
|
||||
|
||||
@@ -16,6 +16,12 @@ import {
|
||||
SidebarProvider,
|
||||
} from "@/components/ui/sidebar"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -34,6 +40,7 @@ import { useToast } from "@/hooks/use-toast"
|
||||
import { ThemeToggle } from "./theme-toggle"
|
||||
import { useRouter } from "@/lib/router"
|
||||
import { useAppState, type AppMode } from "@/lib/app-state"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
interface AdminDashboardProps {
|
||||
token: string
|
||||
@@ -55,8 +62,15 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
const showError = React.useCallback(
|
||||
(error: string, type: "error" | "warning" = "error") => {
|
||||
try {
|
||||
// Prevent error loops by checking if error is already being shown
|
||||
if (error.includes("Unauthorized") || error.includes("auth")) {
|
||||
// Prevent error toasts for auth errors (401/403) - these are handled by the auth dialog
|
||||
const errorLower = error.toLowerCase()
|
||||
if (
|
||||
errorLower.includes("unauthorized") ||
|
||||
errorLower.includes("forbidden") ||
|
||||
errorLower.includes("auth") ||
|
||||
errorLower.includes("403") ||
|
||||
errorLower.includes("401")
|
||||
) {
|
||||
return // Don't show toast for auth errors, handle with dialog
|
||||
}
|
||||
|
||||
@@ -64,6 +78,7 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
variant: type === "error" ? "destructive" : "default",
|
||||
title: type === "error" ? "Error" : "Warning",
|
||||
description: error,
|
||||
duration: 10000,
|
||||
})
|
||||
} catch (toastError) {
|
||||
console.warn("Failed to show error toast:", toastError)
|
||||
@@ -72,17 +87,18 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
[toast],
|
||||
)
|
||||
|
||||
const handleUnauthorized = React.useCallback((reason: string | null) => {
|
||||
const handleUnauthorized = React.useCallback((reason?: string | "") => {
|
||||
try {
|
||||
setAuthErrorReason(reason) // Set the auth error string
|
||||
setAuthErrorReason(reason || "") // Set the auth error string
|
||||
setAuthErrorDialog(true) // Set the auth dialog to open
|
||||
// Don't call handleLogout() here - let the dialog handle navigation
|
||||
} catch (error) {
|
||||
console.warn("Failed to handle unauthorized:", error)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const [apiClient, setApiClient] = React.useState(
|
||||
() => new ApiClient(token, handleUnauthorized, mode, settings?.baseUrl, showError),
|
||||
() => new ApiClient(token || "", handleUnauthorized, showError),
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
@@ -92,9 +108,43 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
|
||||
// Update API client when mode or settings change
|
||||
React.useEffect(() => {
|
||||
const newApiClient = new ApiClient(token, handleUnauthorized, mode, settings?.baseUrl, showError)
|
||||
const newApiClient = new ApiClient(token || "", handleUnauthorized, showError)
|
||||
setApiClient(newApiClient)
|
||||
}, [mode, settings?.baseUrl, token, handleUnauthorized, showError])
|
||||
}, [token, handleUnauthorized, showError])
|
||||
|
||||
const loadAdmins = React.useCallback(async () => {
|
||||
if (!apiClient) return
|
||||
|
||||
try {
|
||||
const adminsData = await apiClient.call<any>("/api/v1/entities/mb_admins")
|
||||
|
||||
// Ensure adminsData is an array - handle paginated response
|
||||
let adminsArray: Admin[] = []
|
||||
if (Array.isArray(adminsData)) {
|
||||
// Fallback: if response is directly an array (shouldn't happen with new API)
|
||||
adminsArray = adminsData
|
||||
} else if (adminsData?.items && Array.isArray(adminsData.items)) {
|
||||
// Paginated response: extract items from data object
|
||||
adminsArray = adminsData.items
|
||||
} else if (adminsData?.data?.items && Array.isArray(adminsData.data.items)) {
|
||||
// If data is nested
|
||||
adminsArray = adminsData.data.items
|
||||
}
|
||||
setAdmins(adminsArray)
|
||||
} catch (error) {
|
||||
console.error("Failed to load admins:", error)
|
||||
}
|
||||
}, [apiClient])
|
||||
|
||||
// Load admins when navigating to the admins page
|
||||
React.useEffect(() => {
|
||||
// Check if we're on the admins page
|
||||
const pathParts = route.path.split("/").filter(Boolean)
|
||||
const section = pathParts[0] || "entities"
|
||||
if (section === "admins") {
|
||||
loadAdmins()
|
||||
}
|
||||
}, [route.path, loadAdmins])
|
||||
|
||||
const loadData = async () => {
|
||||
// Set default settings if loading fails
|
||||
@@ -114,15 +164,18 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
try {
|
||||
setLoading(true)
|
||||
|
||||
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/config"),
|
||||
])
|
||||
// Only load tables on initial load
|
||||
const tablesData = await apiClient.call<any>("/api/v1/schemas")
|
||||
|
||||
setTables(tablesData)
|
||||
setAdmins(adminsData)
|
||||
setSettings(settingsData)
|
||||
// Ensure tablesData is an array - handle different response structures
|
||||
let tablesArray: TableMetadata[] = []
|
||||
if (Array.isArray(tablesData)) {
|
||||
tablesArray = tablesData
|
||||
} else if (tablesData?.data && Array.isArray(tablesData.data)) {
|
||||
tablesArray = tablesData.data
|
||||
}
|
||||
|
||||
setTables(tablesArray)
|
||||
} catch (error) {
|
||||
console.error("Failed to load data:", error)
|
||||
} finally {
|
||||
@@ -130,6 +183,7 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const handleLogout = () => {
|
||||
try {
|
||||
localStorage.removeItem("admin_token")
|
||||
@@ -142,15 +196,23 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
const handleAuthErrorLogin = () => {
|
||||
try {
|
||||
setAuthErrorDialog(false)
|
||||
// Always navigate to login and discard token, regardless of button clicked
|
||||
handleLogout()
|
||||
} catch (error) {
|
||||
console.warn("Failed to handle auth error login:", error)
|
||||
}
|
||||
}
|
||||
|
||||
const handleAuthErrorDialogClose = (open: boolean) => {
|
||||
// If dialog is being closed (either by Cancel or X button), navigate to login
|
||||
if (!open) {
|
||||
handleAuthErrorLogin()
|
||||
}
|
||||
}
|
||||
|
||||
const handleModeChange = (newMode: AppMode, baseUrl?: string) => {
|
||||
// Update API client with new mode and base URL
|
||||
const newApiClient = new ApiClient(token, handleUnauthorized, newMode, baseUrl, showError)
|
||||
// Update API client when mode changes (mode is handled via app state)
|
||||
const newApiClient = new ApiClient(token || "", handleUnauthorized, showError)
|
||||
setApiClient(newApiClient)
|
||||
|
||||
// Reload data with new mode
|
||||
@@ -159,10 +221,16 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
|
||||
const sidebarItems = [
|
||||
{
|
||||
title: "Tables",
|
||||
title: "Entities",
|
||||
icon: Table,
|
||||
id: "tables",
|
||||
path: "/tables",
|
||||
id: "entities",
|
||||
path: "/entities",
|
||||
},
|
||||
{
|
||||
title: "Logs",
|
||||
icon: FileText,
|
||||
id: "logs",
|
||||
path: "/logs",
|
||||
},
|
||||
{
|
||||
title: "Admins",
|
||||
@@ -170,18 +238,6 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
id: "admins",
|
||||
path: "/admins",
|
||||
},
|
||||
// {
|
||||
// title: "Logs",
|
||||
// icon: FileText,
|
||||
// id: "logs",
|
||||
// path: "/logs",
|
||||
// },
|
||||
// {
|
||||
// title: "Sync",
|
||||
// icon: RefreshCw,
|
||||
// id: "sync",
|
||||
// path: "/sync",
|
||||
// },
|
||||
{
|
||||
title: "Settings",
|
||||
icon: Settings,
|
||||
@@ -193,11 +249,12 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
// Extract the section from the route path safely
|
||||
const getCurrentSection = () => {
|
||||
try {
|
||||
// Handle route patterns like "/entities/:name" -> "entities"
|
||||
const pathParts = route.path.split("/").filter(Boolean)
|
||||
return pathParts[0] || "tables"
|
||||
return pathParts[0] || "entities"
|
||||
} catch (error) {
|
||||
console.warn("Error parsing route:", error)
|
||||
return "tables"
|
||||
return "entities"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,82 +265,115 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
<div className="flex min-h-screen w-full items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"></div>
|
||||
<p className="text-muted-foreground">Loading dashboard...</p>
|
||||
<p className="text-muted-foreground">Loading MantisBase Admin Dashboard...</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<SidebarProvider defaultOpen={true}>
|
||||
<SidebarProvider open={false}>
|
||||
<div className="flex min-h-screen w-full">
|
||||
<Sidebar>
|
||||
<SidebarHeader>
|
||||
<div className="flex items-center gap-2 px-4 py-2">
|
||||
<Shield className="h-6 w-6" />
|
||||
<span className="font-semibold">Mantis Admin</span>
|
||||
<Sidebar collapsible="icon" className="border-r" style={{width: "4rem", minWidth: "4rem", maxWidth: "4rem", "--sidebar-width": "4rem", "--sidebar-width-icon": "4rem"} as React.CSSProperties}>
|
||||
<SidebarHeader className="border-b p-0 w-full">
|
||||
<div className="flex h-16 w-full items-center justify-center">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary text-primary-foreground">
|
||||
<Shield className="h-6 w-6" />
|
||||
</div>
|
||||
</div>
|
||||
</SidebarHeader>
|
||||
<SidebarContent>
|
||||
<SidebarGroup>
|
||||
<SidebarGroupLabel>Navigation</SidebarGroupLabel>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{sidebarItems.map((item) => (
|
||||
<SidebarMenuItem key={item.id}>
|
||||
<SidebarMenuButton
|
||||
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>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
</SidebarContent>
|
||||
<SidebarFooter>
|
||||
<SidebarMenu>
|
||||
{settings && (
|
||||
<SidebarMenuItem>
|
||||
<div className="px-4 py-1 text-xs text-muted-foreground">Mantis Version {settings.mantisVersion}</div>
|
||||
<SidebarContent className="px-0 py-2 w-full">
|
||||
<SidebarMenu className="space-y-1 w-full">
|
||||
{sidebarItems.map((item) => (
|
||||
<SidebarMenuItem key={item.id} className="w-full">
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<SidebarMenuButton
|
||||
onClick={() => {
|
||||
try {
|
||||
navigate(item.path, undefined, undefined)
|
||||
} catch (error) {
|
||||
console.warn("Failed to navigate:", error)
|
||||
}
|
||||
}}
|
||||
isActive={currentSection === item.id}
|
||||
style={{ height: "4rem", minHeight: "4rem" }}
|
||||
className={cn(
|
||||
"w-full justify-center p-0 mx-0 rounded-none border-l-2 border-transparent min-w-full",
|
||||
currentSection === item.id && "border-l-primary bg-accent"
|
||||
)}
|
||||
>
|
||||
<item.icon className={cn(
|
||||
"h-6 w-6",
|
||||
currentSection === item.id && "text-primary"
|
||||
)} />
|
||||
<span className="sr-only">{item.title}</span>
|
||||
</SidebarMenuButton>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">
|
||||
<p>{item.title}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</SidebarMenuItem>
|
||||
)}
|
||||
<SidebarMenuItem>
|
||||
<div className="px-4 py-1 text-xs text-muted-foreground">Mantis Admin Version {process.env.MANTIS_ADMIN_VERSION}</div>
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarContent>
|
||||
<SidebarFooter className="border-t p-0 w-full">
|
||||
<SidebarMenu className="space-y-1 w-full">
|
||||
<SidebarMenuItem className="w-full">
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="w-full">
|
||||
<ThemeToggle iconOnly />
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">
|
||||
<p>Toggle Theme</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</SidebarMenuItem>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton asChild>
|
||||
<a href="https://github.com/allankoechke/mantis" target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
<span>Documentation</span>
|
||||
</a>
|
||||
</SidebarMenuButton>
|
||||
<SidebarMenuItem className="w-full">
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<SidebarMenuButton asChild style={{ height: "4rem", minHeight: "4rem" }} className="w-full justify-center p-0 mx-0 rounded-none min-w-full">
|
||||
<a href="https://docs.mantisbase.com" target="_blank" rel="noopener noreferrer" className="w-full flex items-center justify-center">
|
||||
<ExternalLink className="h-6 w-6" />
|
||||
<span className="sr-only">Documentation</span>
|
||||
</a>
|
||||
</SidebarMenuButton>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">
|
||||
<p>Documentation</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</SidebarMenuItem>
|
||||
<SidebarMenuItem>
|
||||
<ThemeToggle />
|
||||
</SidebarMenuItem>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton onClick={handleLogout}>
|
||||
<LogOut className="h-4 w-4" />
|
||||
<span>Logout</span>
|
||||
</SidebarMenuButton>
|
||||
<SidebarMenuItem className="w-full">
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<SidebarMenuButton onClick={handleLogout} className="h-12 w-full justify-center p-0 mx-0 rounded-none min-w-full">
|
||||
<LogOut className="h-6 w-6" />
|
||||
<span className="sr-only">Logout</span>
|
||||
</SidebarMenuButton>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">
|
||||
<p>Logout</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarFooter>
|
||||
</Sidebar>
|
||||
|
||||
<div className="flex-1">
|
||||
<main className="p-6">
|
||||
<main className="pl-4">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<div className="text-center">
|
||||
@@ -293,13 +383,13 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{currentSection === "tables" && (
|
||||
{currentSection === "entities" && (
|
||||
<DatabaseSection apiClient={apiClient} tables={tables} onTablesUpdate={setTables} />
|
||||
)}
|
||||
{currentSection === "admins" && (
|
||||
<AdminsSection admins={admins} apiClient={apiClient} onAdminsUpdate={setAdmins} />
|
||||
)}
|
||||
{currentSection === "logs" && <LogsSection />}
|
||||
{currentSection === "logs" && <LogsSection apiClient={apiClient} />}
|
||||
{currentSection === "sync" && <SyncSection />}
|
||||
{currentSection === "settings" && (
|
||||
<SettingsSection
|
||||
@@ -316,30 +406,25 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
</div>
|
||||
|
||||
{/* Auth Error Dialog */}
|
||||
<Dialog open={authErrorDialog} onOpenChange={setAuthErrorDialog}>
|
||||
<Dialog open={authErrorDialog} onOpenChange={handleAuthErrorDialogClose}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5 text-destructive" />
|
||||
Authentication Error
|
||||
Authentication Required
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Your session has expired or you don't have permission to access this resource. Please log in again to
|
||||
continue.
|
||||
Your session has expired or you don't have permission to access this resource. You will be redirected to the login page.
|
||||
</DialogDescription>
|
||||
{
|
||||
authErrorReason.length > 0 && (
|
||||
<DialogDescription>
|
||||
{authErrorReason}
|
||||
</DialogDescription>
|
||||
)
|
||||
}
|
||||
{authErrorReason.length > 0 && (
|
||||
<div className="mt-4 p-3 rounded-md bg-muted border border-muted-foreground/20">
|
||||
<p className="text-xs font-medium text-muted-foreground mb-1">API Response:</p>
|
||||
<p className="text-sm text-foreground font-mono">{authErrorReason}</p>
|
||||
</div>
|
||||
)}
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setAuthErrorDialog(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleAuthErrorLogin}>Login Again</Button>
|
||||
<Button onClick={handleAuthErrorLogin}>Go to Login</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { ApiClient, Admin, TableMetadata } from "@/lib/api"
|
||||
import { ChangePasswordDialog } from "./change-password-dialog"
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar"
|
||||
import { AddItemDrawer } from "../database/add-item-drawer"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
interface AdminsSectionProps {
|
||||
admins: Admin[]
|
||||
@@ -23,88 +24,153 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
|
||||
const [selectedAdmin, setSelectedAdmin] = React.useState<Admin | null>(null)
|
||||
const [addingAdmin, setAddingAdmin] = React.useState(false)
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const { toast } = useToast()
|
||||
|
||||
const table: any = {
|
||||
has_api: true,
|
||||
name: "admins",
|
||||
name: "mb_admins",
|
||||
system: true,
|
||||
type: "auth",
|
||||
schema: {
|
||||
id: "mbt_10394585042835534856",
|
||||
name: "mb_admins",
|
||||
has_api: true,
|
||||
system: true,
|
||||
type: "auth",
|
||||
fields: [
|
||||
{
|
||||
autoGeneratePattern: null,
|
||||
defaultValue: null,
|
||||
maxValue: null,
|
||||
minValue: null,
|
||||
id: "mbf_14258576900392064537",
|
||||
name: "id",
|
||||
primaryKey: true,
|
||||
primary_key: true,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "string",
|
||||
unique: false,
|
||||
validator: null
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: "@password"
|
||||
}
|
||||
},
|
||||
{
|
||||
autoGeneratePattern: null,
|
||||
defaultValue: null,
|
||||
maxValue: null,
|
||||
minValue: 5.0,
|
||||
id: "mbf_13735287961322938256",
|
||||
name: "created",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false,
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "mbf_9124719522053273721",
|
||||
name: "updated",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false,
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "mbf_16339674465020246541",
|
||||
name: "email",
|
||||
primaryKey: false,
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "string",
|
||||
unique: true,
|
||||
validator: "email"
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: "@email"
|
||||
}
|
||||
},
|
||||
{
|
||||
autoGeneratePattern: null,
|
||||
defaultValue: null,
|
||||
maxValue: null,
|
||||
minValue: 8.0,
|
||||
id: "mbf_6072375419398818283",
|
||||
name: "password",
|
||||
primaryKey: false,
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "string",
|
||||
unique: false,
|
||||
validator: "password"
|
||||
},
|
||||
{
|
||||
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
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: "@password"
|
||||
}
|
||||
}
|
||||
],
|
||||
rules: {
|
||||
add: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
delete: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
get: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
list: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
update: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteAdmin = async (adminId: string) => {
|
||||
try {
|
||||
await apiClient.call(`/api/v1/admins/${adminId}`, { method: "DELETE" })
|
||||
const updatedAdmins = await apiClient.call<Admin[]>("/api/v1/admins")
|
||||
const res: any = await apiClient.call(`/api/v1/entities/mb_admins/${adminId}`, { method: "DELETE" })
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (res?.error?.length > 0) throw res.error
|
||||
|
||||
const response: any = await apiClient.call("/api/v1/entities/mb_admins")
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (response?.error?.length > 0) throw response.error
|
||||
|
||||
// Handle paginated response structure: { items: [...], items_count, page, page_size, total_count }
|
||||
let updatedAdmins: Admin[] = []
|
||||
if (Array.isArray(response)) {
|
||||
// Fallback: if response is directly an array (shouldn't happen with new API)
|
||||
updatedAdmins = response
|
||||
} else if (response?.items && Array.isArray(response.items)) {
|
||||
// Paginated response: extract items from data object
|
||||
updatedAdmins = response.items
|
||||
} else if (response?.data?.items && Array.isArray(response.data.items)) {
|
||||
// If data is nested
|
||||
updatedAdmins = response.data.items
|
||||
}
|
||||
|
||||
onAdminsUpdate(updatedAdmins)
|
||||
|
||||
toast({
|
||||
title: "Admin Deleted",
|
||||
description: "Admin account deleted successfully!",
|
||||
duration: 3000,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to delete admin:", error)
|
||||
}
|
||||
@@ -112,40 +178,58 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
|
||||
|
||||
const handleAdminAdded = (admin: Admin) => {
|
||||
onAdminsUpdate([...admins, admin])
|
||||
|
||||
toast({
|
||||
title: "Admin User Added",
|
||||
description: "Admin account added successfully!",
|
||||
})
|
||||
|
||||
setAddingAdmin(false)
|
||||
}
|
||||
|
||||
const handleReload = async () => {
|
||||
const handleReload = async () => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
const updatedAdmins = await apiClient.call<Admin[]>("/api/v1/admins")
|
||||
const response: any = await apiClient.call("/api/v1/entities/mb_admins")
|
||||
|
||||
// Handle paginated response structure: { items: [...], items_count, page, page_size, total_count }
|
||||
let updatedAdmins: Admin[] = []
|
||||
if (Array.isArray(response)) {
|
||||
// Fallback: if response is directly an array (shouldn't happen with new API)
|
||||
updatedAdmins = response
|
||||
} else if (response?.items && Array.isArray(response.items)) {
|
||||
// Paginated response: extract items from data object
|
||||
updatedAdmins = response.items
|
||||
} else if (response?.data?.items && Array.isArray(response.data.items)) {
|
||||
// If data is nested
|
||||
updatedAdmins = response.data.items
|
||||
}
|
||||
|
||||
onAdminsUpdate(updatedAdmins)
|
||||
} catch (error) {
|
||||
console.error("Failed to delete admin:", error)
|
||||
console.error("Failed to reload admins:", error)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-6 p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<SidebarTrigger />
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">Admin Management</h2>
|
||||
<p className="text-muted-foreground">Manage administrator accounts</p>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-3xl font-bold tracking-tight">Admins</h1>
|
||||
<p className="text-muted-foreground">Manage administrator accounts</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" onClick={handleReload} disabled={isLoading}>
|
||||
<RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={handleReload} disabled={isLoading}>
|
||||
<RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
|
||||
<Button size="sm" onClick={() => setAddingAdmin(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Record
|
||||
</Button>
|
||||
</div>
|
||||
<Button size="sm" onClick={() => setAddingAdmin(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Record
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
@@ -164,7 +248,7 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{admins.map((admin) => (
|
||||
{Array.isArray(admins) && admins.map((admin) => (
|
||||
<TableRow key={admin.id}>
|
||||
<TableCell className="font-medium">{admin.email}</TableCell>
|
||||
<TableCell>{new Date(admin.created).toLocaleDateString()}</TableCell>
|
||||
|
||||
@@ -8,6 +8,7 @@ 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"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
interface ChangePasswordDialogProps {
|
||||
admin: Admin
|
||||
@@ -20,6 +21,7 @@ export function ChangePasswordDialog({ admin, apiClient, onClose }: ChangePasswo
|
||||
const [confirmPassword, setConfirmPassword] = React.useState("")
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [error, setError] = React.useState("")
|
||||
const { toast } = useToast()
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
@@ -36,11 +38,21 @@ export function ChangePasswordDialog({ admin, apiClient, onClose }: ChangePasswo
|
||||
setError("")
|
||||
|
||||
try {
|
||||
await apiClient.call(`/api/v1/admins/${admin.id}`, {
|
||||
const res: any = await apiClient.call(`/api/v1/entities/mb_admins/${admin.id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ password: newPassword }),
|
||||
})
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (res?.error?.length > 0) throw res.error
|
||||
|
||||
onClose()
|
||||
|
||||
toast({
|
||||
title: "Admin Updated",
|
||||
description: "Admin account password updated successfully!",
|
||||
duration: 3000,
|
||||
})
|
||||
} catch (error) {
|
||||
setError("Failed to change password")
|
||||
} finally {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Edit, X, Plus } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
@@ -40,40 +41,130 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
|
||||
setFormData({})
|
||||
setHasUnsavedChanges(false)
|
||||
setTableFields(table.schema?.fields.filter(f => !isSystemGeneratedField(f)))
|
||||
setIsViewIsViewType(table?.type === "view")
|
||||
setIsViewIsViewType(table?.schema.type === "view")
|
||||
}
|
||||
}, [open])
|
||||
|
||||
const prepareRequestBody = (data: Record<string, any>, tableFields: TableField[]): FormData | string => {
|
||||
const hasFileField = tableFields.some(f => ["file", "files"].includes(f.type));
|
||||
if (!hasFileField) {
|
||||
return JSON.stringify(data);
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
const field = tableFields.find(f => f.name === key);
|
||||
if (!field) continue;
|
||||
|
||||
if (field.type === "file") {
|
||||
if (value instanceof File) {
|
||||
formData.append(key, value);
|
||||
}
|
||||
} else if (field.type === "files") {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((file, idx) => {
|
||||
if (file instanceof File) {
|
||||
formData.append(key, file);
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
formData.append(key, typeof value === "object" ? JSON.stringify(value) : String(value));
|
||||
}
|
||||
}
|
||||
|
||||
return formData;
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const createdItem = await apiClient.call<any>(`/api/v1/${table.name}`, {
|
||||
const body = prepareRequestBody(formData, tableFields);
|
||||
const createdItem = await apiClient.call<any>(`/api/v1/entities/${table.schema.name}`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(formData),
|
||||
body: body,
|
||||
})
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (createdItem?.error?.length > 0) throw createdItem.error
|
||||
|
||||
onItemAdded(createdItem)
|
||||
onClose()
|
||||
|
||||
toast({
|
||||
title: "Table Created",
|
||||
description: `A table ${table.name} has been created successfully.`,
|
||||
title: "Table Record Created",
|
||||
description: `The record was created successfully.`,
|
||||
duration: 2000,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to update item:", error)
|
||||
console.error("Failed to create item:", error)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleFieldChange = (fieldName: string, value: string) => {
|
||||
const castToType = (fieldName: string, value: any): any => {
|
||||
const field = tableFields?.find((f: any) => f.name === fieldName);
|
||||
if (!field) return value;
|
||||
|
||||
const type = field.type;
|
||||
|
||||
try {
|
||||
switch (type) {
|
||||
case "string":
|
||||
case "xml":
|
||||
return String(value);
|
||||
|
||||
case "int8":
|
||||
case "int16":
|
||||
case "int32":
|
||||
case "int64":
|
||||
case "uint8":
|
||||
case "uint16":
|
||||
case "uint32":
|
||||
case "uint64":
|
||||
case "double": {
|
||||
return Number(value);
|
||||
}
|
||||
|
||||
case "bool":
|
||||
if (typeof value === "boolean") return value;
|
||||
if (typeof value === "string") return value.toLowerCase() === "true";
|
||||
return Boolean(value);
|
||||
|
||||
case "json":
|
||||
return typeof value === "object" ? value : JSON.parse(value);
|
||||
|
||||
case "date": {
|
||||
const date = new Date(value);
|
||||
return isNaN(date.getTime()) ? null : date.toISOString();
|
||||
}
|
||||
|
||||
case "file":
|
||||
return value instanceof File ? value : null;
|
||||
|
||||
case "files":
|
||||
if (Array.isArray(value)) return value;
|
||||
if (value instanceof FileList) return Array.from(value);
|
||||
return [];
|
||||
|
||||
default:
|
||||
return value;
|
||||
}
|
||||
} catch {
|
||||
return value; // fallback on parse errors
|
||||
}
|
||||
};
|
||||
|
||||
const handleFieldChange = (fieldName: string, value: any) => {
|
||||
setFormData((prev: any) => ({
|
||||
...prev,
|
||||
[fieldName]: value,
|
||||
[fieldName]: castToType(fieldName, value),
|
||||
}))
|
||||
setHasUnsavedChanges(true)
|
||||
}
|
||||
|
||||
const isSystemGeneratedField = (field: any) => {
|
||||
console.log(field.name)
|
||||
return field.system && ["id", "created", "updated"].includes(field.name)
|
||||
}
|
||||
|
||||
@@ -88,6 +179,33 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
|
||||
}
|
||||
}
|
||||
|
||||
const isIntegralType = (type: string) => {
|
||||
switch (type) {
|
||||
case "int8":
|
||||
case "int16":
|
||||
case "int32":
|
||||
case "int64":
|
||||
case "uint8":
|
||||
case "uint16":
|
||||
case "uint32":
|
||||
case "uint64":
|
||||
case "double":
|
||||
return true
|
||||
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function formatDateForInput(value: string | Date | undefined): string {
|
||||
if (!value) return "";
|
||||
|
||||
const date = typeof value === "string" ? new Date(value) : value;
|
||||
if (isNaN(date.getTime())) return "";
|
||||
|
||||
return date.toISOString().slice(0, 16); // "YYYY-MM-DDTHH:MM"
|
||||
}
|
||||
|
||||
return (
|
||||
<Drawer open={open} onOpenChange={handleClose}>
|
||||
<DrawerContent side="right" className="w-[700px] max-w-[95vw]">
|
||||
@@ -101,15 +219,15 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<DrawerDescription>Create a new record in {table.name} table</DrawerDescription>
|
||||
<DrawerDescription>Create a new record in {table.schema.name} table</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<div className="flex-1 overflow-auto">
|
||||
<ScrollArea className="h-full">
|
||||
<div className="p-6 space-y-6">
|
||||
<div className="p-6 space-y-6 pb-64">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Autogenerated fields for <Badge variant="default" className="text-sm mr-2">
|
||||
{table.name}
|
||||
{table.schema.name}
|
||||
</Badge>table: <Badge variant="outline" className="text-xs mr-2">
|
||||
id
|
||||
</Badge>
|
||||
@@ -127,19 +245,77 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
|
||||
{field.name}
|
||||
{(field.required || field.system) && <span className="text-red-500 ml-1">*</span>}
|
||||
</Label>
|
||||
<Input
|
||||
id={field.name}
|
||||
type={
|
||||
field.name === "password"
|
||||
? "password"
|
||||
: field.type === "date" ? "datetime-local" : "text"
|
||||
}
|
||||
value={formData[field.name] || ""}
|
||||
onChange={(e) => handleFieldChange(field.name, e.target.value)}
|
||||
disabled={(field.type === "view" || isSystemGeneratedField(field))}
|
||||
className={`w-full ${(field.type === "view" || isSystemGeneratedField(field)) ? "bg-muted" : ""}`}
|
||||
placeholder={`Enter ${field.name}`}
|
||||
/>
|
||||
{field.type === "bool" ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id={field.name}
|
||||
checked={!!formData[field.name]}
|
||||
onCheckedChange={(checked: any) => handleFieldChange(field.name, checked)}
|
||||
disabled={(field.type === "view" || isSystemGeneratedField(field))}
|
||||
/>
|
||||
<span>{formData[field.name] ? "True" : "False"}</span>
|
||||
</div>
|
||||
) : field.type === "file" ? (
|
||||
<Input
|
||||
id={field.name}
|
||||
type="file"
|
||||
onChange={(e) => handleFieldChange(field.name, e.target.files?.[0])}
|
||||
disabled={(field.type === "view" || isSystemGeneratedField(field))}
|
||||
className={`w-full ${(field.type === "view" || isSystemGeneratedField(field)) ? "bg-muted" : ""}`}
|
||||
/>
|
||||
) : field.type === "files" ? (
|
||||
<Input
|
||||
id={field.name}
|
||||
type="file"
|
||||
multiple
|
||||
onChange={(e) => handleFieldChange(field.name, e.target.files)}
|
||||
disabled={(field.type === "view" || isSystemGeneratedField(field))}
|
||||
className={`w-full ${(field.type === "view" || isSystemGeneratedField(field)) ? "bg-muted" : ""}`}
|
||||
/>
|
||||
) : isIntegralType(field.type) ? (
|
||||
<Input
|
||||
id={field.name}
|
||||
type="number"
|
||||
value={formData[field.name] || ""}
|
||||
onChange={(e) => handleFieldChange(field.name, e.target.value)}
|
||||
disabled={(field.type === "view" || isSystemGeneratedField(field))}
|
||||
className={`w-full ${(field.type === "view" || isSystemGeneratedField(field)) ? "bg-muted" : ""}`}
|
||||
placeholder={`Enter '${field.name}' value`}
|
||||
/>
|
||||
) : field.name === "password" ? (
|
||||
<Input
|
||||
id={field.name}
|
||||
type="password"
|
||||
value={formData[field.name] || ""}
|
||||
onChange={(e) => handleFieldChange(field.name, e.target.value)}
|
||||
disabled={(field.type === "view" || isSystemGeneratedField(field))}
|
||||
className={`w-full ${(field.type === "view" || isSystemGeneratedField(field)) ? "bg-muted" : ""}`}
|
||||
placeholder={`Enter '${field.name}' value`}
|
||||
/>
|
||||
) : field.type === "date" ? (
|
||||
<Input
|
||||
id={field.name}
|
||||
type="datetime-local"
|
||||
onFocus={(e) => {
|
||||
// scroll parent container into view
|
||||
e.target.scrollIntoView({ behavior: "auto", block: "center" });
|
||||
}}
|
||||
value={formatDateForInput(formData[field.name])}
|
||||
onChange={(e) => handleFieldChange(field.name, e.target.value)}
|
||||
disabled={(field.type === "view" || isSystemGeneratedField(field))}
|
||||
className={`w-full ${(field.type === "view" || isSystemGeneratedField(field)) ? "bg-muted" : ""}`}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
id={field.name}
|
||||
type="text"
|
||||
value={formData[field.name] || ""}
|
||||
onChange={(e) => handleFieldChange(field.name, e.target.value)}
|
||||
disabled={(field.type === "view" || isSystemGeneratedField(field))}
|
||||
className={`w-full ${(field.type === "view" || isSystemGeneratedField(field)) ? "bg-muted" : ""}`}
|
||||
placeholder={`Enter '${field.name}' value`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
|
||||
@@ -1,26 +1,33 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Plus, Trash2 } from "lucide-react"
|
||||
import { Plus, Trash2, GripVertical, ChevronDown, ChevronUp, Lock } 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"
|
||||
Drawer,
|
||||
DrawerClose,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerFooter,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
DrawerTrigger,
|
||||
} from "@/components/ui/drawer"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import type { ApiClient, TableMetadata, TableField } from "@/lib/api"
|
||||
import { dataTypes } from "@/lib/constants"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { hash } from "crypto"
|
||||
import { fi } from "date-fns/locale"
|
||||
|
||||
interface AddTableDialogProps {
|
||||
apiClient: ApiClient
|
||||
@@ -28,335 +35,690 @@ interface AddTableDialogProps {
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
interface Field {
|
||||
id?: string // Optional - missing/empty means new field
|
||||
name: string
|
||||
type: string
|
||||
primary_key: boolean
|
||||
nullable: boolean
|
||||
unique?: boolean
|
||||
system?: boolean
|
||||
required?: boolean
|
||||
constraints: {
|
||||
default_value: any
|
||||
max_value: number | null
|
||||
min_value: number | null
|
||||
validator: string | null
|
||||
}
|
||||
}
|
||||
|
||||
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<
|
||||
Array<{
|
||||
name: string
|
||||
type: string
|
||||
primaryKey: boolean
|
||||
nullable: boolean
|
||||
unique?: boolean
|
||||
isSystem?: boolean
|
||||
required?: boolean
|
||||
}>
|
||||
>([])
|
||||
const [fields, setFields] = React.useState<Field[]>([])
|
||||
const [sqlQuery, setSqlQuery] = React.useState("")
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const [draggedIndex, setDraggedIndex] = React.useState<number | null>(null)
|
||||
const [expandedFields, setExpandedFields] = React.useState<Set<string>>(new Set())
|
||||
const { toast } = useToast()
|
||||
|
||||
// When we open the dialog, reset all input values to default
|
||||
// that way, we ensure we dont start with previous dialog data
|
||||
// Get unique key for field (use id if exists, otherwise generate one)
|
||||
const getFieldKey = (field: Field, index: number) => field.id || `temp-${index}`
|
||||
const genFieldBaseId = (name: string) => `mbf-${hash(name, "sha256").toString()}`
|
||||
|
||||
// When drawer opens, reset and add base fields
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
// Reset all input fields to default values ...
|
||||
setTableName("");
|
||||
setSqlQuery("");
|
||||
setIsLoading(false);
|
||||
setTableType("base");
|
||||
addBaseFields();
|
||||
setTableName("")
|
||||
setSqlQuery("")
|
||||
setIsLoading(false)
|
||||
setTableType("base")
|
||||
setExpandedFields(new Set())
|
||||
addBaseFields()
|
||||
}
|
||||
}, [open])
|
||||
|
||||
function addBaseFields() {
|
||||
// NOTE!!
|
||||
// THESE SYSTEM FIELDS ARE SHOWN HERE JUST FOR CONVINIENCE BUT WONT BE PROCESSED IN THE REQUEST BODY
|
||||
// AS SUCH, CHANGING ANY PARAMETERS WON'T HAVE ANY EFFECT ON THE DB SIDE.
|
||||
if (tableType === "base") {
|
||||
// Base types include `id`, `created` and `updated` fields
|
||||
setColumns([
|
||||
{ name: "id", type: "string", primaryKey: true, nullable: false, isSystem: true, required: true },
|
||||
{ name: "created", type: "date", primaryKey: false, nullable: false, isSystem: true, required: true },
|
||||
{ name: "updated", type: "date", primaryKey: false, nullable: false, isSystem: true, required: true },
|
||||
])
|
||||
} else if (tableType === "auth") {
|
||||
// Base types include `id`, `created`, `updated`, `email` and `password` fields
|
||||
setColumns([
|
||||
{ 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: "date", primaryKey: false, nullable: false, isSystem: true, required: true },
|
||||
{ name: "updated", type: "date", primaryKey: false, nullable: false, isSystem: true, required: true },
|
||||
])
|
||||
if (tableType === "view") {
|
||||
setFields([])
|
||||
} else {
|
||||
setColumns([])
|
||||
// Add base fields
|
||||
setFields([
|
||||
{
|
||||
id: genFieldBaseId("id"),
|
||||
name: "id",
|
||||
type: "string",
|
||||
primary_key: true,
|
||||
nullable: false,
|
||||
system: true,
|
||||
required: true,
|
||||
unique: false,
|
||||
constraints: {
|
||||
min_value: 6,
|
||||
max_value: null,
|
||||
default_value: null,
|
||||
validator: "@password"
|
||||
}
|
||||
},
|
||||
{
|
||||
id: genFieldBaseId("created"),
|
||||
name: "created",
|
||||
type: "date",
|
||||
primary_key: false,
|
||||
nullable: false,
|
||||
system: true,
|
||||
required: true,
|
||||
unique: false,
|
||||
constraints: {
|
||||
min_value: null,
|
||||
max_value: null,
|
||||
default_value: null,
|
||||
validator: null
|
||||
}
|
||||
},
|
||||
{
|
||||
id: genFieldBaseId("updated"),
|
||||
name: "updated",
|
||||
type: "date",
|
||||
primary_key: false,
|
||||
nullable: false,
|
||||
system: true,
|
||||
required: true,
|
||||
unique: false,
|
||||
constraints: {
|
||||
min_value: null,
|
||||
max_value: null,
|
||||
default_value: null,
|
||||
validator: null
|
||||
}
|
||||
},
|
||||
])
|
||||
|
||||
// For auth types, extend with auth specific fields
|
||||
if (tableType === "auth") {
|
||||
setFields([
|
||||
...fields,
|
||||
{
|
||||
id: genFieldBaseId("name"),
|
||||
name: "name",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
nullable: false,
|
||||
system: true,
|
||||
required: true,
|
||||
unique: false,
|
||||
constraints: {
|
||||
min_value: 3,
|
||||
max_value: null,
|
||||
default_value: null,
|
||||
validator: null
|
||||
}
|
||||
},
|
||||
{
|
||||
id: genFieldBaseId("email"),
|
||||
name: "email",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
nullable: false,
|
||||
system: true,
|
||||
required: true,
|
||||
unique: true,
|
||||
constraints: {
|
||||
min_value: 5,
|
||||
max_value: null,
|
||||
default_value: null,
|
||||
validator: "@email"
|
||||
}
|
||||
},
|
||||
{
|
||||
id: genFieldBaseId("password"),
|
||||
name: "password",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
nullable: false,
|
||||
system: true,
|
||||
required: true,
|
||||
unique: false,
|
||||
constraints: {
|
||||
min_value: 6,
|
||||
max_value: null,
|
||||
default_value: null,
|
||||
validator: "@password"
|
||||
}
|
||||
},
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update the default system columns when we change the table type.
|
||||
React.useEffect(() => {
|
||||
addBaseFields();
|
||||
}, [tableType])
|
||||
if (open) {
|
||||
addBaseFields()
|
||||
}
|
||||
}, [tableType, open])
|
||||
|
||||
// Add a new column field to the fields array.
|
||||
// By default, the data type is set to `string`. Note also that the `isSystem` field will be ignored, so
|
||||
// don't rely on it.
|
||||
const addColumn = () => {
|
||||
setColumns([
|
||||
...columns,
|
||||
{ name: "", type: "string", primaryKey: false, nullable: false, isSystem: false, required: false },
|
||||
const addField = () => {
|
||||
setFields([
|
||||
...fields,
|
||||
{
|
||||
name: "",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
nullable: true,
|
||||
system: false,
|
||||
required: false,
|
||||
unique: false,
|
||||
constraints: {
|
||||
min_value: null,
|
||||
max_value: null,
|
||||
default_value: null,
|
||||
validator: null
|
||||
}
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
// Remove an added field from the fields array
|
||||
const removeColumn = (index: number) => {
|
||||
const column = columns[index]
|
||||
if (columns.length > 1 && !column.isSystem) {
|
||||
setColumns(columns.filter((_, i) => i !== index))
|
||||
}
|
||||
const removeField = (fieldKey: string) => {
|
||||
setFields((prevFields) => {
|
||||
const fieldIndex = prevFields.findIndex((f, idx) => (f.id || `temp-${idx}`) === fieldKey)
|
||||
if (fieldIndex >= 0 && !prevFields[fieldIndex].system) {
|
||||
const newFields = prevFields.filter((_, idx) => idx !== fieldIndex)
|
||||
setExpandedFields((prev) => {
|
||||
const next = new Set(prev)
|
||||
next.delete(fieldKey)
|
||||
return next
|
||||
})
|
||||
return newFields
|
||||
}
|
||||
return prevFields
|
||||
})
|
||||
}
|
||||
|
||||
// Update an existing field with new value/option
|
||||
const updateColumn = (index: number, field: string, value: any) => {
|
||||
const updatedColumns = columns.map((col, i) => (i === index ? { ...col, [field]: value } : col))
|
||||
setColumns(updatedColumns)
|
||||
const updateField = (fieldKey: string, updates: Partial<Field> & { constraints?: Partial<Field['constraints']> }) => {
|
||||
setFields((prevFields) =>
|
||||
prevFields.map((field, index) => {
|
||||
const currentKey = field.id || `temp-${index}`
|
||||
if (currentKey === fieldKey) {
|
||||
// Handle constraints updates
|
||||
if (updates.constraints) {
|
||||
return {
|
||||
...field,
|
||||
...updates,
|
||||
constraints: { ...field.constraints, ...updates.constraints }
|
||||
}
|
||||
}
|
||||
return { ...field, ...updates }
|
||||
}
|
||||
return field
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const toggleFieldExpanded = (fieldKey: string) => {
|
||||
setExpandedFields((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(fieldKey)) {
|
||||
next.delete(fieldKey)
|
||||
} else {
|
||||
next.add(fieldKey)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
// Drag and drop handlers
|
||||
const handleDragStart = (index: number) => {
|
||||
setDraggedIndex(index)
|
||||
}
|
||||
|
||||
const handleDragOver = (e: React.DragEvent, index: number) => {
|
||||
e.preventDefault()
|
||||
if (draggedIndex === null || draggedIndex === index) return
|
||||
|
||||
const draggedField = fields[draggedIndex]
|
||||
const targetField = fields[index]
|
||||
|
||||
// Allow moving system fields, but don't allow placing non-system fields before system fields
|
||||
// This maintains system field integrity while allowing reordering
|
||||
const newFields = [...fields]
|
||||
newFields.splice(draggedIndex, 1)
|
||||
newFields.splice(index, 0, draggedField)
|
||||
setFields(newFields)
|
||||
setDraggedIndex(index)
|
||||
}
|
||||
|
||||
const handleDragEnd = () => {
|
||||
setDraggedIndex(null)
|
||||
}
|
||||
|
||||
// Handle submitting new table to the API
|
||||
const handleSubmit = async () => {
|
||||
if (!tableName.trim()) return
|
||||
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const tableData: Partial<TableMetadata> = {
|
||||
// For view types, require SQL query
|
||||
if (tableType === "view" && !sqlQuery.trim()) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Please provide a SQL query for view entities.",
|
||||
})
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
// For base and auth types, require at least one user field with a name
|
||||
if (tableType !== "view") {
|
||||
const userFields = fields.filter((f) => !f.system && f.name.trim())
|
||||
if (userFields.length === 0) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Please add at least one field with a name to the entity.",
|
||||
})
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Include all fields in order (system + user) for base/auth types
|
||||
// For view types, fields are typically empty or derived from SQL
|
||||
const allFields = tableType === "view"
|
||||
? []
|
||||
: fields.map(
|
||||
(field): TableField => {
|
||||
const fieldData: any = {
|
||||
name: field.name,
|
||||
type: field.type,
|
||||
primary_key: field.primary_key,
|
||||
required: field.required || !field.nullable,
|
||||
unique: field.unique || false,
|
||||
system: field.system || false,
|
||||
constraints: field.constraints,
|
||||
}
|
||||
// Only include id if it exists (for existing fields being updated)
|
||||
if (field.id) {
|
||||
fieldData.id = field.id
|
||||
}
|
||||
return fieldData
|
||||
},
|
||||
)
|
||||
|
||||
const tableData: any = {
|
||||
name: tableName,
|
||||
type: tableType,
|
||||
schema: {
|
||||
listRule: "",
|
||||
getRule: "",
|
||||
addRule: tableType === "view" ? "" : "",
|
||||
updateRule: tableType === "view" ? "" : "",
|
||||
deleteRule: tableType === "view" ? "" : ""
|
||||
id: "", // Will be generated by the API
|
||||
name: tableName,
|
||||
has_api: true,
|
||||
system: false,
|
||||
type: tableType,
|
||||
fields: allFields,
|
||||
rules: {
|
||||
add: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
delete: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
get: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
list: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
update: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
}
|
||||
},
|
||||
...(tableType === "view" && { sql: sqlQuery.trim() }),
|
||||
},
|
||||
}
|
||||
|
||||
if (tableType === "view") {
|
||||
tableData.sql = sqlQuery
|
||||
} else {
|
||||
tableData.fields = columns.map(
|
||||
(col): TableField => ({
|
||||
name: col.name,
|
||||
type: col.type,
|
||||
primaryKey: col.primaryKey,
|
||||
nullable: col.nullable,
|
||||
unique: col.unique,
|
||||
system: col.isSystem,
|
||||
required: col.required,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
await apiClient.call("/api/v1/tables", {
|
||||
const res: any = await apiClient.call("/api/v1/schemas", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(tableData),
|
||||
})
|
||||
|
||||
// Refresh tables list
|
||||
const updatedTables = await apiClient.call<TableMetadata[]>("/api/v1/tables")
|
||||
onTablesUpdate(updatedTables)
|
||||
if (res?.error?.length > 0) throw res.error
|
||||
|
||||
// Reset form
|
||||
const response: any = await apiClient.call("/api/v1/schemas")
|
||||
if (response?.error?.length > 0) throw response.error
|
||||
|
||||
// Handle different response structures
|
||||
let updatedTables: TableMetadata[] = []
|
||||
if (Array.isArray(response)) {
|
||||
updatedTables = response
|
||||
} else if (response?.data && Array.isArray(response.data)) {
|
||||
updatedTables = response.data
|
||||
}
|
||||
|
||||
onTablesUpdate(updatedTables)
|
||||
setTableName("")
|
||||
setSqlQuery("")
|
||||
setOpen(false)
|
||||
|
||||
toast({
|
||||
title: "Table Created",
|
||||
description: `The table '${tableData.name}' been updated successfully.`,
|
||||
title: "Entity Created",
|
||||
description: `The entity '${tableName}' has been created successfully.`,
|
||||
})
|
||||
} catch (error: any) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: error?.message || "Failed to create entity",
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to create table:", error)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Drawer open={open} onOpenChange={setOpen}>
|
||||
<DrawerTrigger asChild>
|
||||
{children || (
|
||||
<Button size="sm">
|
||||
<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>
|
||||
</DrawerTrigger>
|
||||
<DrawerContent side="right" className="w-full sm:w-[600px]">
|
||||
<DrawerHeader>
|
||||
<DrawerTitle>Create New Entity</DrawerTitle>
|
||||
<DrawerDescription>Create a new entity with custom fields and settings.</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
|
||||
<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 Type</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 and should have an `id` field.
|
||||
</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>
|
||||
<ScrollArea className="flex-1 px-6">
|
||||
<div className="space-y-6 py-4">
|
||||
{/* Entity Name and Type */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="entity-name">Entity Name</Label>
|
||||
<Input
|
||||
id="entity-name"
|
||||
placeholder="Enter entity name"
|
||||
value={tableName}
|
||||
onChange={(e) => setTableName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="entity-type">Type</Label>
|
||||
<Select value={tableType} onValueChange={(value: "base" | "auth" | "view") => setTableType(value)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="base">Base</SelectItem>
|
||||
<SelectItem value="auth">Auth</SelectItem>
|
||||
<SelectItem value="view">View</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</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>
|
||||
{/* SQL Query Section for View Types */}
|
||||
{tableType === "view" && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="sql-query">SQL Query</Label>
|
||||
<Textarea
|
||||
id="sql-query"
|
||||
placeholder="CREATE VIEW view_name AS SELECT id, column1, column2 FROM table_name WHERE condition..."
|
||||
value={sqlQuery}
|
||||
onChange={(e) => setSqlQuery(e.target.value)}
|
||||
className="min-h-[200px] font-mono text-sm"
|
||||
/>
|
||||
<div className="rounded-md bg-muted/50 p-3 space-y-1">
|
||||
<p className="text-xs text-muted-foreground font-medium">
|
||||
Note: The SQL query should start with <code className="text-foreground">CREATE VIEW</code> or similar statement.
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
At least one <code className="text-foreground">id</code> field is required in the view result.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Fields Section */}
|
||||
{tableType !== "view" && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<Label className="text-base font-medium">Fields</Label>
|
||||
<p className="text-sm text-muted-foreground">Define the fields for your entity</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
{fields.map((field, index) => {
|
||||
const fieldKey = getFieldKey(field, index)
|
||||
return (
|
||||
<div
|
||||
key={fieldKey}
|
||||
draggable={true}
|
||||
onDragStart={() => handleDragStart(index)}
|
||||
onDragOver={(e) => handleDragOver(e, index)}
|
||||
onDragEnd={handleDragEnd}
|
||||
className={cn(
|
||||
"border rounded-lg p-4 space-y-3 transition-colors",
|
||||
field.system && "bg-muted/30 border-muted",
|
||||
draggedIndex === index && "opacity-50"
|
||||
)}
|
||||
>
|
||||
{/* Field Header - Name and Type */}
|
||||
<div className="flex items-center gap-3">
|
||||
<GripVertical className="h-4 w-4 text-muted-foreground cursor-move flex-shrink-0" />
|
||||
{field.system && (
|
||||
<Lock className="h-4 w-4 text-muted-foreground flex-shrink-0" />
|
||||
)}
|
||||
<div className="flex-1 grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Input
|
||||
placeholder="Field name"
|
||||
value={field.name}
|
||||
onChange={(e) => updateField(fieldKey, { name: e.target.value })}
|
||||
disabled={field.system}
|
||||
className={field.system ? "bg-muted" : ""}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Select
|
||||
value={field.type}
|
||||
onValueChange={(value) => updateField(fieldKey, { type: value })}
|
||||
disabled={field.system}
|
||||
>
|
||||
<SelectTrigger className={field.system ? "bg-muted" : ""}>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{dataTypes.map((type) => (
|
||||
<SelectItem key={type} value={type}>
|
||||
{type.toUpperCase()}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
{!field.system && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => removeField(fieldKey)}
|
||||
className="flex-shrink-0"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{field.system && (
|
||||
<Badge variant="outline" className="text-xs flex-shrink-0">
|
||||
System
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Collapsible Advanced Options */}
|
||||
{!field.system && (
|
||||
<Collapsible open={expandedFields.has(fieldKey)} onOpenChange={() => toggleFieldExpanded(fieldKey)}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="w-full justify-between">
|
||||
<span className="text-xs text-muted-foreground">Advanced Options</span>
|
||||
{expandedFields.has(fieldKey) ? (
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="space-y-3 pt-2">
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id={`pk-${fieldKey}`}
|
||||
checked={field.primary_key}
|
||||
onCheckedChange={(checked) => updateField(fieldKey, { primary_key: checked as boolean })}
|
||||
/>
|
||||
<Label htmlFor={`pk-${fieldKey}`} className="text-xs cursor-pointer">
|
||||
Primary Key
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id={`unique-${fieldKey}`}
|
||||
checked={field.unique || false}
|
||||
onCheckedChange={(checked) => updateField(fieldKey, { unique: checked as boolean })}
|
||||
/>
|
||||
<Label htmlFor={`unique-${fieldKey}`} className="text-xs cursor-pointer">
|
||||
Unique
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id={`required-${fieldKey}`}
|
||||
checked={field.required || !field.nullable}
|
||||
onCheckedChange={(checked) => {
|
||||
updateField(fieldKey, { required: checked as boolean, nullable: !checked })
|
||||
}}
|
||||
/>
|
||||
<Label htmlFor={`required-${fieldKey}`} className="text-xs cursor-pointer">
|
||||
Required
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={`min-${fieldKey}`} className="text-xs">
|
||||
Min Value
|
||||
</Label>
|
||||
<Input
|
||||
id={`min-${fieldKey}`}
|
||||
type="number"
|
||||
placeholder="Min"
|
||||
value={field.constraints.min_value || ""}
|
||||
onChange={(e) =>
|
||||
updateField(fieldKey, {
|
||||
constraints: {
|
||||
...field.constraints,
|
||||
min_value: e.target.value ? Number.parseFloat(e.target.value) : null,
|
||||
}
|
||||
})
|
||||
}
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={`max-${fieldKey}`} className="text-xs">
|
||||
Max Value
|
||||
</Label>
|
||||
<Input
|
||||
id={`max-${fieldKey}`}
|
||||
type="number"
|
||||
placeholder="Max"
|
||||
value={field.constraints.max_value || ""}
|
||||
onChange={(e) =>
|
||||
updateField(fieldKey, {
|
||||
constraints: {
|
||||
...field.constraints,
|
||||
max_value: e.target.value ? Number.parseFloat(e.target.value) : null,
|
||||
}
|
||||
})
|
||||
}
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={`default-${fieldKey}`} className="text-xs">
|
||||
Default Value
|
||||
</Label>
|
||||
<Input
|
||||
id={`default-${fieldKey}`}
|
||||
placeholder="Default value"
|
||||
value={field.constraints.default_value || ""}
|
||||
onChange={(e) => updateField(fieldKey, { constraints: { ...field.constraints, default_value: e.target.value || null } })}
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={`validator-${fieldKey}`} className="text-xs">
|
||||
Validator
|
||||
</Label>
|
||||
<Input
|
||||
id={`validator-${fieldKey}`}
|
||||
placeholder="Validator pattern"
|
||||
value={field.constraints.validator || ""}
|
||||
onChange={(e) => updateField(fieldKey, { constraints: { ...field.constraints, validator: e.target.value || null } })}
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)}
|
||||
</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>
|
||||
<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>
|
||||
{/* Add Field Button */}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="w-full border-dashed"
|
||||
onClick={addField}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Field
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setOpen(false)}>
|
||||
Cancel
|
||||
<DrawerFooter>
|
||||
<DrawerClose asChild>
|
||||
<Button variant="outline">Cancel</Button>
|
||||
</DrawerClose>
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={
|
||||
isLoading ||
|
||||
!tableName.trim() ||
|
||||
(tableType === "view"
|
||||
? !sqlQuery.trim()
|
||||
: fields.filter((f) => !f.system).length === 0)
|
||||
}
|
||||
>
|
||||
{isLoading ? "Creating..." : "Create Entity"}
|
||||
</Button>
|
||||
<Button onClick={handleSubmit} disabled={isLoading || !tableName.trim()}>
|
||||
{isLoading ? "Creating..." : `Create ${tableType === "view" ? "View" : "Table"}`}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</DrawerFooter>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Search, Table, Eye, Trash2, MoreHorizontal, RefreshCw, Plus, ExternalLink, FileText } from "lucide-react"
|
||||
import { Search, Table, RefreshCw, Plus, ExternalLink, FileText, Database } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Card, CardContent } 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 { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import type { ApiClient, TableMetadata } from "@/lib/api"
|
||||
import { AddTableDialog } from "./add-table-dialog"
|
||||
import { TableDetailView } from "./table-detail-view"
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar"
|
||||
import { TableDocsDrawer } from "./table-docs-drawer"
|
||||
import { useRouter } from "@/lib/router"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
interface DatabaseSectionProps {
|
||||
apiClient: ApiClient
|
||||
@@ -22,50 +24,109 @@ interface DatabaseSectionProps {
|
||||
}
|
||||
|
||||
export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseSectionProps) {
|
||||
const [searchTerm, setSearchTerm] = React.useState("")
|
||||
const { route, navigate } = useRouter()
|
||||
const { toast } = useToast()
|
||||
|
||||
// Initialize search term from query params
|
||||
const initialFilter = route.queryParams.filter || ""
|
||||
const [searchTerm, setSearchTerm] = React.useState(initialFilter)
|
||||
const [editingTable, setEditingTable] = React.useState<TableMetadata | null>(null)
|
||||
const [searchExpanded, setSearchExpanded] = React.useState(false)
|
||||
const [isRefreshing, setIsRefreshing] = React.useState(false)
|
||||
const [docsOpen, setDocsOpen] = 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
|
||||
// Sync search term with query params
|
||||
React.useEffect(() => {
|
||||
const filterFromQuery = route.queryParams.filter || ""
|
||||
if (filterFromQuery !== searchTerm) {
|
||||
setSearchTerm(filterFromQuery)
|
||||
}
|
||||
}
|
||||
}, [route.queryParams.filter])
|
||||
|
||||
const selectedTableName = getSelectedTableName()
|
||||
// Update URL when search term changes (debounced)
|
||||
React.useEffect(() => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
if (route.path === "/entities" || route.path === "/entities/:name") {
|
||||
const queryParams: Record<string, string> = searchTerm ? { filter: searchTerm } : {}
|
||||
if (route.pathParams.name) {
|
||||
navigate("/entities/:name", { name: route.pathParams.name }, queryParams)
|
||||
} else {
|
||||
navigate("/entities", undefined, queryParams)
|
||||
}
|
||||
}
|
||||
}, 300) // Debounce for 300ms
|
||||
|
||||
const filteredTables = tables?.filter((table) => table.name.toLowerCase().includes(searchTerm.toLowerCase()))
|
||||
return () => clearTimeout(timeoutId)
|
||||
}, [searchTerm, route.path, route.pathParams.name])
|
||||
|
||||
// Get selected entity name from path params
|
||||
const selectedEntityName = route.pathParams.name || null
|
||||
|
||||
const filteredTables = Array.isArray(tables) ? tables?.filter((table) => table?.schema?.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")
|
||||
const res: any = await apiClient.call(`/api/v1/schemas/${tableId}`, { method: "DELETE" })
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (res?.error?.length > 0) throw res.error
|
||||
|
||||
// Fetch new tables
|
||||
const response: any = await apiClient.call("/api/v1/schemas")
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (response?.error?.length > 0) throw response.error
|
||||
|
||||
// Handle different response structures
|
||||
let updatedTables: TableMetadata[] = []
|
||||
if (Array.isArray(response)) {
|
||||
updatedTables = response
|
||||
} else if (response?.data && Array.isArray(response.data)) {
|
||||
updatedTables = response.data
|
||||
}
|
||||
|
||||
// Set the new tables
|
||||
onTablesUpdate(updatedTables)
|
||||
|
||||
toast({
|
||||
title: "Table Deleted",
|
||||
description: "Table deleted successfully!",
|
||||
duration: 3000,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to delete table:", error)
|
||||
// toast({
|
||||
// title: "Error Deleted",
|
||||
// description: "Table deleted successfully!",
|
||||
// duration: 3000,
|
||||
// })
|
||||
}
|
||||
}
|
||||
|
||||
const handleTableClick = (tableName: string) => {
|
||||
const handleEntityClick = (entityName: string) => {
|
||||
try {
|
||||
navigate(`/tables/${tableName}`)
|
||||
navigate("/entities/:name", { name: entityName })
|
||||
} catch (error) {
|
||||
console.warn("Failed to navigate to table:", error)
|
||||
console.warn("Failed to navigate to entity:", error)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRefresh = async () => {
|
||||
setIsRefreshing(true)
|
||||
try {
|
||||
const updatedTables = await apiClient.call<TableMetadata[]>("/api/v1/tables")
|
||||
const response: any = await apiClient.call("/api/v1/schemas")
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (response?.error?.length > 0) throw response.error
|
||||
|
||||
// Handle different response structures
|
||||
let updatedTables: TableMetadata[] = []
|
||||
if (Array.isArray(response)) {
|
||||
updatedTables = response
|
||||
} else if (response?.data && Array.isArray(response.data)) {
|
||||
updatedTables = response.data
|
||||
}
|
||||
|
||||
onTablesUpdate(updatedTables)
|
||||
} catch (error) {
|
||||
console.error("Failed to refresh tables:", error)
|
||||
@@ -74,158 +135,146 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedTableName) {
|
||||
const tableInfo = tables.find((t) => t.name === selectedTableName)
|
||||
if (tableInfo) {
|
||||
return (
|
||||
<TableDetailView
|
||||
table={tableInfo}
|
||||
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))
|
||||
onTablesUpdate(updatedTables)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
const selectedEntity = selectedEntityName
|
||||
? Array.isArray(tables) ? tables.find((t) => t.schema.name === selectedEntityName) : null
|
||||
: null
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Top Bar */}
|
||||
<div className="flex items-center gap-4">
|
||||
<SidebarTrigger />
|
||||
|
||||
{/* Expandable Search */}
|
||||
<div className={`flex items-center transition-all duration-200 ${searchExpanded ? "flex-1" : ""}`}>
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search tables..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
onFocus={() => setSearchExpanded(true)}
|
||||
onBlur={() => {
|
||||
if (!searchTerm) setSearchExpanded(false)
|
||||
}}
|
||||
className={`pl-10 transition-all duration-200 ${searchExpanded ? "w-80" : "w-64"}`}
|
||||
/>
|
||||
<div className="flex h-[100vh] gap-4 pr-8">
|
||||
{/* Entity List Sidebar */}
|
||||
<div className="w-64 flex-shrink-0 border-r bg-muted/30">
|
||||
<div className="flex flex-col h-full">
|
||||
{/* Sidebar Header */}
|
||||
<div className="p-4 border-b space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold flex items-center gap-2">
|
||||
<Database className="h-5 w-5" />
|
||||
Entities
|
||||
</h2>
|
||||
<Button variant="ghost" size="icon" onClick={handleRefresh} disabled={isRefreshing}>
|
||||
<RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search entities..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="pl-8 h-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<AddTableDialog apiClient={apiClient} onTablesUpdate={onTablesUpdate}>
|
||||
<Button size="sm" className="flex-1">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New
|
||||
</Button>
|
||||
</AddTableDialog>
|
||||
<Button variant="outline" size="sm" onClick={() => setDocsOpen(true)}>
|
||||
<FileText className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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>
|
||||
<Button variant="outline" size="sm" onClick={() => setDocsOpen(true)}>
|
||||
<FileText className="h-4 w-4 mr-2" />
|
||||
Table API Docs
|
||||
</Button>
|
||||
<AddTableDialog apiClient={apiClient} onTablesUpdate={onTablesUpdate} />
|
||||
{/* Entity List */}
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-2 space-y-1">
|
||||
{filteredTables.length === 0 ? (
|
||||
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||
{searchTerm ? "No entities found matching the search term" : "No entities, add some to get started"}
|
||||
</div>
|
||||
) : (
|
||||
filteredTables.map((table) => (
|
||||
<button
|
||||
key={table.id}
|
||||
onClick={() => handleEntityClick(table.schema.name)}
|
||||
className={cn(
|
||||
"w-full text-left p-3 rounded-lg transition-colors hover:bg-accent",
|
||||
selectedEntityName === table.schema.name && "bg-accent text-accent-foreground"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
<Table className="h-4 w-4 flex-shrink-0" />
|
||||
<span className="font-medium truncate">{table.schema.name}</span>
|
||||
</div>
|
||||
<Badge
|
||||
variant={table.schema.type === "auth" ? "default" : table.schema.type === "view" ? "secondary" : "outline"}
|
||||
className="text-xs flex-shrink-0 ml-2"
|
||||
>
|
||||
{table.schema.type}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
{table.schema.fields?.length || 0} fields
|
||||
</div>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{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" onClick={() => setDocsOpen(true)}>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
View Documentation
|
||||
</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" />
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 overflow-auto pt-4 pl-4">
|
||||
{selectedEntity ? (
|
||||
<TableDetailView
|
||||
table={selectedEntity}
|
||||
onBack={() => {
|
||||
try {
|
||||
navigate("/entities", undefined, undefined)
|
||||
} catch (error) {
|
||||
console.warn("Failed to navigate back:", error)
|
||||
}
|
||||
}}
|
||||
apiClient={apiClient}
|
||||
onTableUpdate={(updatedTable) => {
|
||||
const updatedTables = tables.map((t) => (t.id === updatedTable.id ? updatedTable : t))
|
||||
onTablesUpdate(updatedTables)
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
{tables.length === 0 && !isRefreshing ? (
|
||||
<Card className="w-full max-w-md">
|
||||
<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 Entities Found</h3>
|
||||
<p className="text-muted-foreground text-center mb-6">
|
||||
Get started by creating your first entity. Entities 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 Entity
|
||||
</Button>
|
||||
</AddTableDialog>
|
||||
<Button variant="outline" onClick={() => setDocsOpen(true)}>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
View Documentation
|
||||
</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
|
||||
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>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="text-center space-y-4">
|
||||
<Database className="h-16 w-16 text-muted-foreground mx-auto" />
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold mb-2">Select an Entity</h2>
|
||||
<p className="text-muted-foreground">
|
||||
Choose an entity from the sidebar to view and manage its data
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Open docs on table CRUD */}
|
||||
{/* Entity Schema API Documentation */}
|
||||
<TableDocsDrawer open={docsOpen} onClose={() => setDocsOpen(false)} />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Edit, X } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
@@ -15,7 +16,7 @@ import {
|
||||
DrawerTitle,
|
||||
} from "@/components/ui/drawer"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import type { ApiClient, TableMetadata } from "@/lib/api"
|
||||
import { ApiClient, TableMetadata, getApiBaseUrl } from "@/lib/api"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
interface EditItemDrawerProps {
|
||||
@@ -27,7 +28,89 @@ interface EditItemDrawerProps {
|
||||
onItemUpdate: (item: any) => void
|
||||
}
|
||||
|
||||
const FilePreviewField = ({
|
||||
field,
|
||||
value,
|
||||
onChange,
|
||||
onDelete,
|
||||
multiple = false,
|
||||
table,
|
||||
}: {
|
||||
field: any;
|
||||
value: any;
|
||||
onChange: (val: File | File[] | null) => void;
|
||||
onDelete: (index: number) => void;
|
||||
multiple?: boolean;
|
||||
table: TableMetadata;
|
||||
}) => {
|
||||
const files = Array.isArray(value) ? value : value ? [value] : [];
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const selected = e.target.files ? Array.from(e.target.files) : [];
|
||||
if (multiple) {
|
||||
onChange([...files, ...selected]);
|
||||
} else {
|
||||
onChange(selected[0] || null);
|
||||
}
|
||||
};
|
||||
|
||||
const getFileUrl = (file: File | string): string => {
|
||||
if (typeof file === "string") {
|
||||
return `${getApiBaseUrl()}/api/files/${table.schema.name}/${encodeURIComponent(file)}`;
|
||||
}
|
||||
return URL.createObjectURL(file); // for newly selected files
|
||||
};
|
||||
|
||||
const getFileName = (file: File | string): string => {
|
||||
return typeof file === "string" ? file : file.name;
|
||||
};
|
||||
|
||||
const isImageFile = (file: File | string): boolean => {
|
||||
const name = getFileName(file);
|
||||
return name.match(/\.(jpg|jpeg|png|gif|webp)$/i) !== null;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{files.map((file, idx) => {
|
||||
const url = getFileUrl(file);
|
||||
const isImage = isImageFile(file);
|
||||
|
||||
return (
|
||||
<div key={idx} className="relative group w-24 h-24 border rounded-md overflow-hidden">
|
||||
{isImage ? (
|
||||
<img src={url} alt="Preview" className="object-cover w-full h-full" />
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full text-xs p-2 text-center">
|
||||
📄 {file.name || "file"}
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
onClick={() => onDelete(idx)}
|
||||
className="absolute top-1 right-1 bg-white/80 rounded-full p-1 cursor-pointer hidden group-hover:block"
|
||||
>
|
||||
❌
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<Input
|
||||
type="file"
|
||||
multiple={multiple}
|
||||
onChange={handleFileChange}
|
||||
className="w-fit"
|
||||
placeholder={`Enter '${field.type}' value`}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUpdate }: EditItemDrawerProps) {
|
||||
const [tableFields, setTableFields] = React.useState<any>([])
|
||||
const [formData, setFormData] = React.useState<any>({})
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [isViewType, setIsViewIsViewType] = React.useState(false)
|
||||
@@ -38,22 +121,93 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
if (open && item) {
|
||||
setFormData({ ...item })
|
||||
setHasUnsavedChanges(false)
|
||||
setIsViewIsViewType(table?.type === "view")
|
||||
setTableFields(table.schema?.fields.filter(f => !isSystemGeneratedField(f)))
|
||||
setIsViewIsViewType(table?.schema?.type === "view")
|
||||
}
|
||||
}, [open, item])
|
||||
|
||||
const prepareRequestBody = (data: Record<string, any>, tableFields: TableField[]): FormData | string => {
|
||||
const hasFileField = tableFields.some(f => ["file", "files"].includes(f.type));
|
||||
if (!hasFileField) {
|
||||
return JSON.stringify(data);
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
const field = tableFields.find(f => f.name === key);
|
||||
if (!field) continue;
|
||||
if (!value) {
|
||||
formData.append(key, "");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (field.type === "file") {
|
||||
if (value instanceof File) {
|
||||
formData.append(key, value);
|
||||
}
|
||||
} else if (field.type === "files") {
|
||||
if (!value) {
|
||||
formData.append(key, value);
|
||||
}
|
||||
else if (Array.isArray(value)) {
|
||||
var files = value.filter(v => v instanceof File);
|
||||
var arr = value.filter(v => !(v instanceof File));
|
||||
files.forEach((file, idx) => {
|
||||
if (file instanceof File) {
|
||||
formData.append(key, file);
|
||||
}
|
||||
});
|
||||
|
||||
// Append the array of non-file values as a JSON string
|
||||
if (arr.length > 0) {
|
||||
formData.append(key, JSON.stringify(arr));
|
||||
} else {
|
||||
// Append empty string only if no files were added
|
||||
if (files.length === 0) {
|
||||
formData.append(key, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
formData.append(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
return formData;
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const updatedItem = await apiClient.call<any>(`/api/v1/${table.name}/${item.id}`, {
|
||||
const body = prepareRequestBody(formData, tableFields);
|
||||
console.log("Body to send:", body);
|
||||
|
||||
if (!body) {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "No data to update.",
|
||||
variant: "destructive",
|
||||
duration: 3000,
|
||||
});
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const updatedItem = await apiClient.call<any>(`/api/v1/entities/${table?.schema?.name}/${formData["id"]}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(formData),
|
||||
body: body,
|
||||
})
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (updatedItem?.error?.length > 0) throw updatedItem.error
|
||||
|
||||
onItemUpdate(updatedItem)
|
||||
onClose()
|
||||
|
||||
toast({
|
||||
title: "Table Updated",
|
||||
description: "Table data has been updated successfully.",
|
||||
title: "Table Record Updated",
|
||||
description: "Table record was updated successfully.",
|
||||
duration: 3000,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to update item:", error)
|
||||
@@ -62,10 +216,62 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
}
|
||||
}
|
||||
|
||||
const handleFieldChange = (fieldName: string, value: string) => {
|
||||
const castToType = (fieldName: string, value: any): any => {
|
||||
const field = tableFields?.find((f: any) => f.name === fieldName);
|
||||
if (!field) return value;
|
||||
if (!value) return null; // handle null or undefined values
|
||||
|
||||
const type = field.type;
|
||||
|
||||
try {
|
||||
switch (type) {
|
||||
case "int8":
|
||||
case "int16":
|
||||
case "int32":
|
||||
case "int64":
|
||||
case "uint8":
|
||||
case "uint16":
|
||||
case "uint32":
|
||||
case "uint64":
|
||||
case "double": {
|
||||
return Number(value);
|
||||
}
|
||||
|
||||
case "bool":
|
||||
if (typeof value === "boolean") return value;
|
||||
if (typeof value === "string") return value.toLowerCase() === "true";
|
||||
return Boolean(value);
|
||||
|
||||
case "json":
|
||||
return typeof value === "object" ? value : JSON.parse(value);
|
||||
|
||||
case "date": {
|
||||
const date = new Date(value);
|
||||
return isNaN(date.getTime()) ? null : date.toISOString();
|
||||
}
|
||||
|
||||
case "file":
|
||||
return value instanceof File ? value : null;
|
||||
|
||||
case "files":
|
||||
if (Array.isArray(value)) return value;
|
||||
if (value instanceof FileList) return Array.from(value);
|
||||
return [];
|
||||
|
||||
default:
|
||||
return value;
|
||||
}
|
||||
} catch {
|
||||
return value; // fallback on parse errors
|
||||
}
|
||||
};
|
||||
|
||||
const handleFieldChange = (fieldName: string, value: any) => {
|
||||
const v = castToType(fieldName, value);
|
||||
console.log(`Field changed: ${fieldName}, Value: ${v}, Type: ${typeof v}`);
|
||||
setFormData((prev: any) => ({
|
||||
...prev,
|
||||
[fieldName]: value,
|
||||
[fieldName]: v,
|
||||
}))
|
||||
setHasUnsavedChanges(true)
|
||||
}
|
||||
@@ -85,6 +291,26 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
}
|
||||
}
|
||||
|
||||
const handleFileDelete = (fieldName: string, index: number) => {
|
||||
const value = formData[fieldName];
|
||||
const updated = Array.isArray(value)
|
||||
? value.filter((_, i) => i !== index)
|
||||
: null;
|
||||
|
||||
// Update the form data with the new value
|
||||
handleFieldChange(fieldName, updated);
|
||||
};
|
||||
|
||||
function formatDateForInput(value: string | Date | undefined): string {
|
||||
if (!value) return "";
|
||||
|
||||
const date = typeof value === "string" ? new Date(value) : value;
|
||||
if (isNaN(date.getTime())) return "";
|
||||
|
||||
return date.toISOString().slice(0, 16); // "YYYY-MM-DDTHH:MM"
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<Drawer open={open} onOpenChange={handleClose}>
|
||||
<DrawerContent side="right" className="w-[700px] max-w-[95vw]">
|
||||
@@ -98,43 +324,87 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<DrawerDescription>Edit record in {table.name} table</DrawerDescription>
|
||||
<DrawerDescription>Edit record in {table.schema.name} table</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<ScrollArea className="h-full">
|
||||
<div className="p-6 space-y-6">
|
||||
{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}
|
||||
{!field.required && <span className="text-red-500 ml-1">*</span>}
|
||||
</Label>
|
||||
<Input
|
||||
id={field.name}
|
||||
type={
|
||||
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={isSystemGeneratedField(field)}
|
||||
className={`w-full ${isSystemGeneratedField(field) ? "bg-muted" : ""}`}
|
||||
placeholder={`Enter ${field.name}`}
|
||||
/>
|
||||
{isSystemGeneratedField(field) && (
|
||||
<p className="text-xs text-muted-foreground">System generated field - cannot be modified</p>
|
||||
)}
|
||||
{(table.type === "auth" && field.name === "password") && (
|
||||
<p className="text-xs text-muted-foreground">Password fields are redacted in API responses.</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{table.schema.fields?.map((field) => {
|
||||
const isDisabled = (field.type === "view" || isSystemGeneratedField(field));
|
||||
const value = formData[field.name];
|
||||
const isFileField = field.type === "file" || field.type === "files";
|
||||
|
||||
return (
|
||||
<div key={field.name} className="space-y-2">
|
||||
<Label htmlFor={field.name} className="text-sm font-medium capitalize">
|
||||
{field.name}
|
||||
{field.required && <span className="text-red-500 ml-1">*</span>}
|
||||
</Label>
|
||||
|
||||
{/* FILE/FILES PREVIEW */}
|
||||
{isFileField ? (
|
||||
<FilePreviewField
|
||||
field={field}
|
||||
value={value}
|
||||
onChange={(newValue) => handleFieldChange(field.name, newValue)}
|
||||
onDelete={(index) => handleFileDelete(field.name, index)}
|
||||
multiple={field.type === "files"}
|
||||
table={table}
|
||||
/>
|
||||
) : field.type === "bool" ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id={field.name}
|
||||
checked={!!value}
|
||||
onCheckedChange={(checked) => handleFieldChange(field.name, checked)}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<span>{formData[field.name] ? "True" : "False"}</span>
|
||||
</div>
|
||||
) : field.type === "date" || field.type === "datetime" || field.type === "timestamp" ? (
|
||||
<Input
|
||||
id={field.name}
|
||||
type="datetime-local"
|
||||
value={value ? formatDateForInput(value) : ""}
|
||||
onChange={(e) => handleFieldChange(field.name, e.target.value)}
|
||||
disabled={isDisabled}
|
||||
className={`w-full ${isDisabled ? "bg-muted" : ""}`}
|
||||
/>
|
||||
) : field.type.match(/^int|^uint|double|number$/) ? (
|
||||
<Input
|
||||
id={field.name}
|
||||
type="number"
|
||||
value={value ?? ""}
|
||||
onChange={(e) => handleFieldChange(field.name, e.target.value)}
|
||||
disabled={isDisabled}
|
||||
className={`w-full ${isDisabled ? "bg-muted" : ""}`}
|
||||
placeholder={`Enter '${field.type}' value`}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
id={field.name}
|
||||
type={field.name === "password" ? "password" : "text"}
|
||||
value={value ?? ""}
|
||||
onChange={(e) => handleFieldChange(field.name, e.target.value)}
|
||||
disabled={isDisabled}
|
||||
className={`w-full ${isDisabled ? "bg-muted" : ""}`}
|
||||
placeholder={`Enter '${field.type}' value`}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isDisabled && (
|
||||
<p className="text-xs text-muted-foreground">System generated field - cannot be modified</p>
|
||||
)}
|
||||
{table.schema.type === "auth" && field.name === "password" && (
|
||||
<p className="text-xs text-muted-foreground">Password fields are redacted in API responses.</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
</div>
|
||||
|
||||
<DrawerFooter>
|
||||
|
||||
@@ -60,8 +60,19 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
setColumns(table.schema?.fields.map(col => ({ ...col, old_name: col.name })) || [])
|
||||
setRules({ addRule: table.schema.addRule, listRule: table.schema.listRule, getRule: table.schema.getRule, updateRule: table.schema.updateRule, deletRule: table.schema.deleteRule })
|
||||
// Transform API format (with constraints) to UI format (flat camelCase)
|
||||
const transformedColumns = table.schema?.fields.map(col => ({
|
||||
...col,
|
||||
old_name: col.name,
|
||||
// Flatten constraints for UI
|
||||
primaryKey: col.primary_key || false,
|
||||
minValue: col.constraints?.min_value || null,
|
||||
maxValue: col.constraints?.max_value || null,
|
||||
defaultValue: col.constraints?.default_value || null,
|
||||
validator: col.constraints?.validator || null,
|
||||
})) || []
|
||||
setColumns(transformedColumns)
|
||||
setRules({ addRule: table.schema.rules.add, listRule: table.schema.rules.list, getRule: table.schema.rules.get, updateRule: table.schema.rules.update, deletRule: table.schema.rules.delete })
|
||||
setHasUnsavedChanges(false)
|
||||
setSystemFieldsCollapsed(true)
|
||||
setDeletedColumns([])
|
||||
@@ -69,7 +80,27 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
}, [open, table])
|
||||
|
||||
const addColumn = () => {
|
||||
setColumns([...columns, { name: "", type: "string", primaryKey: false, required: true, old_name: null }])
|
||||
setColumns([...columns, {
|
||||
id: `field-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
|
||||
name: "",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
primaryKey: false, // UI format
|
||||
required: true,
|
||||
system: false,
|
||||
unique: false,
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null,
|
||||
},
|
||||
minValue: null, // UI format
|
||||
maxValue: null, // UI format
|
||||
defaultValue: null, // UI format
|
||||
validator: null, // UI format
|
||||
old_name: null
|
||||
}])
|
||||
setHasUnsavedChanges(true)
|
||||
}
|
||||
|
||||
@@ -119,17 +150,40 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
const handleSaveSchema = async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const body = { fields: columns, deletedFields: deletedColumns };
|
||||
// Transform UI format (camelCase flat) to API format (with constraints and snake_case)
|
||||
const transformedFields = columns.map((col: any) => ({
|
||||
id: col.id,
|
||||
name: col.name,
|
||||
type: col.type,
|
||||
primary_key: col.primaryKey !== undefined ? col.primaryKey : col.primary_key,
|
||||
required: col.required,
|
||||
system: col.system || false,
|
||||
unique: col.unique || false,
|
||||
constraints: {
|
||||
default_value: col.defaultValue !== undefined ? col.defaultValue : (col.constraints?.default_value || null),
|
||||
max_value: col.maxValue !== undefined ? col.maxValue : (col.constraints?.max_value || null),
|
||||
min_value: col.minValue !== undefined ? col.minValue : (col.constraints?.min_value || null),
|
||||
validator: col.validator !== undefined ? col.validator : (col.constraints?.validator || null),
|
||||
},
|
||||
...(col.old_name && { old_name: col.old_name }),
|
||||
}))
|
||||
|
||||
const body = { fields: transformedFields, deletedFields: deletedColumns };
|
||||
console.log(body)
|
||||
// return
|
||||
const updatedTable = await apiClient.call<TableMetadata>(`/api/v1/tables/${table.id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ fields: columns, deletedFields: deletedColumns }),
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (updatedTable?.error?.length > 0) throw updatedTable.error
|
||||
|
||||
onTableUpdate(updatedTable)
|
||||
toast({
|
||||
title: "Table Updated",
|
||||
description: "Table config has been updated successfully.",
|
||||
description: "Table fields updated successfully.",
|
||||
duration: 3000,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to update schema:", error)
|
||||
@@ -145,14 +199,40 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
const updatedTable = await apiClient.call<TableMetadata>(`/api/v1/tables/${table.id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({
|
||||
listRule: rules.listRule,
|
||||
getRule: rules.getRule,
|
||||
addRule: rules.addRule,
|
||||
updateRule: rules.updateRule,
|
||||
deleteRule: rules.deleteRule,
|
||||
rules: {
|
||||
list: {
|
||||
expr: rules.listRule || "",
|
||||
mode: "auth"
|
||||
},
|
||||
get: {
|
||||
expr: rules.getRule || "",
|
||||
mode: "auth"
|
||||
},
|
||||
add: {
|
||||
expr: rules.addRule || "",
|
||||
mode: "auth"
|
||||
},
|
||||
update: {
|
||||
expr: rules.updateRule || "",
|
||||
mode: "auth"
|
||||
},
|
||||
delete: {
|
||||
expr: rules.deleteRule || "",
|
||||
mode: "auth"
|
||||
},
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (updatedTable?.error?.length > 0) throw updatedTable.error
|
||||
|
||||
onTableUpdate(updatedTable)
|
||||
toast({
|
||||
title: "Table Updated",
|
||||
description: "Table access rules updated successfully!",
|
||||
duration: 3000,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to update rules:", error)
|
||||
} finally {
|
||||
@@ -183,7 +263,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Cog className="h-5 w-5" />
|
||||
<DrawerTitle>Configure {table.name} Table</DrawerTitle>
|
||||
<DrawerTitle>Configure {table.schema.name} Table</DrawerTitle>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={onClose}>
|
||||
<X className="h-4 w-4" />
|
||||
@@ -207,7 +287,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
<h4 className="text-lg font-medium">Table Structure</h4>
|
||||
<p className="text-sm text-muted-foreground">Modify columns and their properties</p>
|
||||
</div>
|
||||
{table.type !== "view" && (
|
||||
{table.schema.type !== "view" && (
|
||||
<Button type="button" variant="outline" size="sm" onClick={addColumn}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Column
|
||||
@@ -215,7 +295,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
)}
|
||||
</div>
|
||||
|
||||
{table.type === "view" ? (
|
||||
{table.schema.type === "view" ? (
|
||||
<div className="p-4 bg-muted rounded-lg">
|
||||
<h5 className="font-medium mb-3">SQL Query</h5>
|
||||
<ScrollArea className="h-32">
|
||||
@@ -653,7 +733,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
</>
|
||||
)}
|
||||
|
||||
{table.type !== "view" && (
|
||||
{table.schema.type !== "view" && (
|
||||
<div className="text-sm text-muted-foreground p-3 bg-muted/50 rounded-lg">
|
||||
<div>
|
||||
<Badge variant="outline" className="text-xs mr-2">
|
||||
@@ -706,7 +786,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
<p className="text-xs text-muted-foreground mt-1">Controls who can view individual records</p>
|
||||
</div>
|
||||
|
||||
{table.type !== "view" && (
|
||||
{table.schema.type !== "view" && (
|
||||
<>
|
||||
<div>
|
||||
<Label htmlFor="add-rule" className="text-sm font-medium">
|
||||
|
||||
@@ -8,18 +8,18 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar"
|
||||
import type { ApiClient, TableMetadata } from "@/lib/api"
|
||||
import { ApiClient, TableMetadata, getApiBaseUrl } from "@/lib/api"
|
||||
import { TableConfigDrawer } from "./table-config-drawer"
|
||||
import { TableRecordDocsDrawer } from "./table-records-docs-drawer"
|
||||
import { EditItemDrawer } from "./edit-item-drawer"
|
||||
import { AddItemDrawer } from "./add-item-drawer"
|
||||
import { ColumnVisibilityDropdown } from "./column-visibility-dropdown"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { useRouter } from "@/lib/router"
|
||||
|
||||
interface TableDetailViewProps {
|
||||
table: TableMetadata
|
||||
onBack: () => void
|
||||
onBack?: () => void
|
||||
apiClient: ApiClient
|
||||
onTableUpdate: (table: TableMetadata) => void
|
||||
}
|
||||
@@ -39,17 +39,56 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
table.schema.fields?.map((field) => field.name) || [],
|
||||
)
|
||||
const [isDeleting, setIsDeleting] = React.useState(false)
|
||||
const [filterTerm, setFilterTerm] = React.useState("")
|
||||
const [appliedFilter, setAppliedFilter] = React.useState("")
|
||||
const { route, navigate } = useRouter()
|
||||
const { toast } = useToast()
|
||||
|
||||
// Initialize filter from query params
|
||||
const initialFilter = route.queryParams.filter || ""
|
||||
const [filterTerm, setFilterTerm] = React.useState(initialFilter)
|
||||
const [appliedFilter, setAppliedFilter] = React.useState(initialFilter)
|
||||
|
||||
// Sync filter with query params
|
||||
React.useEffect(() => {
|
||||
const filterFromQuery = route.queryParams.filter || ""
|
||||
if (filterFromQuery !== appliedFilter) {
|
||||
setAppliedFilter(filterFromQuery)
|
||||
setFilterTerm(filterFromQuery)
|
||||
}
|
||||
}, [route.queryParams.filter])
|
||||
|
||||
// Clear data and reset state when switching entities
|
||||
React.useEffect(() => {
|
||||
// Clear table data immediately when entity changes
|
||||
setTableData([])
|
||||
setCurrentPage(1)
|
||||
setTotalPages(1)
|
||||
setSelectedItems([])
|
||||
setFilterTerm("")
|
||||
setAppliedFilter("")
|
||||
setIsLoading(true)
|
||||
|
||||
// Update visible columns based on new table schema
|
||||
setVisibleColumns(table.schema.fields?.map((field) => field.name) || [])
|
||||
setIsViewType(table.schema.type === "view")
|
||||
|
||||
// Clear filter from URL when switching entities (if filter exists in query params)
|
||||
if (route.queryParams.filter) {
|
||||
navigate("/entities/:name", { name: table.schema.name }, {})
|
||||
}
|
||||
|
||||
// Load new data after clearing - this will use the reset values (page 1, empty filter)
|
||||
// Note: We don't need to call loadTableData here because the next useEffect will handle it
|
||||
// when currentPage and appliedFilter are updated
|
||||
}, [table.schema.name]) // Watch for entity name changes
|
||||
|
||||
// Load data when page, filter, or entity changes
|
||||
React.useEffect(() => {
|
||||
loadTableData()
|
||||
}, [currentPage, appliedFilter])
|
||||
}, [currentPage, appliedFilter, table.schema.name])
|
||||
|
||||
React.useEffect(() => {
|
||||
setIsViewType(table.type === "view")
|
||||
}, [table.type])
|
||||
setIsViewType(table.schema.type === "view")
|
||||
}, [table.schema.type])
|
||||
|
||||
React.useEffect(() => {
|
||||
setVisibleColumns(table.schema.fields?.map((field) => field.name) || [])
|
||||
@@ -59,13 +98,34 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const tableData = await apiClient.call<any>(`/api/v1/${table.name}`)
|
||||
const response = await apiClient.call<any>(`/api/v1/entities/${table.schema.name}`)
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (response?.error?.length > 0) throw response.error
|
||||
|
||||
// Handle paginated response structure: { items: [...], items_count, page, page_size, total_count }
|
||||
let tableData: any[] = []
|
||||
if (Array.isArray(response)) {
|
||||
// Fallback: if response is directly an array (shouldn't happen with new API)
|
||||
tableData = response
|
||||
} else if (response?.items && Array.isArray(response.items)) {
|
||||
// Paginated response: extract items from data object
|
||||
tableData = response.items
|
||||
} else if (response?.data?.items && Array.isArray(response.data.items)) {
|
||||
// If data is nested
|
||||
tableData = response.data.items
|
||||
} else {
|
||||
console.warn("Unexpected response format:", response)
|
||||
tableData = []
|
||||
}
|
||||
|
||||
setTableData(tableData)
|
||||
|
||||
// setTotalPages(3) // Mock pagination
|
||||
setSelectedItems([]) // Clear selection on reload
|
||||
} catch (error) {
|
||||
console.error("Failed to load table data:", error)
|
||||
setTableData([]) // Set empty array on error
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
@@ -83,6 +143,10 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
const handleFilter = () => {
|
||||
setAppliedFilter(filterTerm)
|
||||
setCurrentPage(1) // Reset to first page when filtering
|
||||
|
||||
// Update URL with filter query param
|
||||
const queryParams: Record<string, string> = filterTerm ? { filter: filterTerm } : {}
|
||||
navigate("/entities/:name", { name: table.schema.name }, queryParams)
|
||||
}
|
||||
|
||||
const handleFilterKeyPress = (e: React.KeyboardEvent) => {
|
||||
@@ -128,7 +192,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
try {
|
||||
// Delete each selected item individually
|
||||
const deletePromises = selectedItems.map((itemId) =>
|
||||
apiClient.call(`/api/v1/${table.name}/${itemId}`, { method: "DELETE" }),
|
||||
apiClient.call(`/api/v1/entities/${table.schema.name}/${itemId}`, { method: "DELETE" }),
|
||||
)
|
||||
|
||||
await Promise.all(deletePromises)
|
||||
@@ -136,10 +200,6 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
// Remove deleted items from table data
|
||||
setTableData((prevData) => prevData.filter((item) => !selectedItems.includes(item.id)))
|
||||
setSelectedItems([])
|
||||
toast({
|
||||
title: "Record(s) Deleted",
|
||||
description: "Table records have been updated successfully.",
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to delete items:", error)
|
||||
} finally {
|
||||
@@ -149,79 +209,136 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
|
||||
const filteredFields = table.schema.fields?.filter((field) => visibleColumns.includes(field.name)) || []
|
||||
|
||||
function renderCellContent(field: { name: string; type: string }, value: any) {
|
||||
if (value === null) return "N/A";
|
||||
|
||||
switch (field.type) {
|
||||
case "bool":
|
||||
case "boolean":
|
||||
return value ? "true" : "false";
|
||||
|
||||
case "json":
|
||||
try {
|
||||
return (
|
||||
<pre className="max-w-[300px] whitespace-pre-wrap text-xs bg-muted p-1 rounded">
|
||||
{JSON.stringify(value, null, 2)}
|
||||
</pre>
|
||||
);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
|
||||
case "file":
|
||||
case "files": {
|
||||
if(!value || value==="" || value.length === 0) return "N/A";
|
||||
|
||||
const filenames = Array.isArray(value) ? value : [value];
|
||||
return (
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
{filenames.map((filename: string, i: number) => {
|
||||
const url = `${getApiBaseUrl()}/api/files/${table.schema.name}/${encodeURIComponent(filename)}`;
|
||||
const ext = filename.split(".").pop()?.toLowerCase() || "";
|
||||
|
||||
const isImage = ["jpg", "jpeg", "png", "gif", "webp", "bmp", "svg"].includes(ext);
|
||||
|
||||
return isImage ? (
|
||||
<img
|
||||
key={i}
|
||||
src={url}
|
||||
alt={filename}
|
||||
className="h-10 w-10 object-cover rounded border"
|
||||
/>
|
||||
) : (
|
||||
<a
|
||||
key={i}
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs underline text-blue-600"
|
||||
>
|
||||
{filename}
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
default:
|
||||
return value ? String(value) : "N/A";
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<SidebarTrigger />
|
||||
<Button variant="ghost" onClick={onBack}>
|
||||
← Back
|
||||
</Button>
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold capitalize">{table.name} Table</h2>
|
||||
<p className="text-muted-foreground">View and manage table data</p>
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">
|
||||
Entity <span className="text-primary font-mono italic">'{table.schema.name}'</span> data
|
||||
</h2>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" onClick={handleReload} disabled={isLoading}>
|
||||
<Button variant="outline" size="icon" onClick={handleReload} disabled={isLoading}>
|
||||
<RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
{!isViewType &&
|
||||
<Button variant="outline" size="icon" onClick={() => setConfigOpen(true)}>
|
||||
<Cog className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button variant="outline" size="icon" onClick={() => setDocsOpen(true)}>
|
||||
<FileText className="h-4 w-4" />
|
||||
</Button>
|
||||
{!isViewType && (
|
||||
<Button size="sm" onClick={handleAddItem} disabled={isLoading}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Record
|
||||
</Button>
|
||||
}
|
||||
<Button variant="outline" size="sm" onClick={() => setConfigOpen(true)}>
|
||||
<Cog className="h-4 w-4 mr-2" />
|
||||
Config
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => setDocsOpen(true)}>
|
||||
<FileText className="h-4 w-4 mr-2" />
|
||||
API Docs
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Search/Filter Bar */}
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search records..."
|
||||
value={filterTerm}
|
||||
onChange={(e) => setFilterTerm(e.target.value)}
|
||||
onKeyPress={handleFilterKeyPress}
|
||||
className="pl-10"
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={handleFilter} disabled={isLoading}>
|
||||
Filter
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground z-10" />
|
||||
<Input
|
||||
placeholder="Search records..."
|
||||
value={filterTerm}
|
||||
onChange={(e) => setFilterTerm(e.target.value)}
|
||||
onKeyPress={handleFilterKeyPress}
|
||||
className="pl-10 pr-20"
|
||||
/>
|
||||
<Button
|
||||
onClick={handleFilter}
|
||||
disabled={isLoading}
|
||||
className="absolute right-1 top-1/2 transform -translate-y-1/2 h-7"
|
||||
size="sm"
|
||||
>
|
||||
Filter
|
||||
</Button>
|
||||
{appliedFilter && (
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<p className="text-sm text-muted-foreground">Filtering by: "{appliedFilter}"</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setFilterTerm("")
|
||||
setAppliedFilter("")
|
||||
navigate("/entities/:name", { name: table.schema.name }, {})
|
||||
}}
|
||||
className="h-6 text-xs"
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
{appliedFilter && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setFilterTerm("")
|
||||
setAppliedFilter("")
|
||||
}}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{appliedFilter && <p className="text-sm text-muted-foreground mt-2">Filtering by: "{appliedFilter}"</p>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>Table Data</CardTitle>
|
||||
<CardDescription>Current records in the {table.name} table</CardDescription>
|
||||
<CardDescription>Current records in the {table.schema.name} table</CardDescription>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{selectedItems.length > 0 && (
|
||||
@@ -241,76 +358,80 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{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">
|
||||
{!isViewType &&
|
||||
<Button onClick={handleAddItem} disabled={isDeleting || isLoading}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Record
|
||||
</Button>
|
||||
}
|
||||
<Button variant="outline" onClick={() => setDocsOpen(true)} disabled={isDeleting}>
|
||||
<FileText className="h-4 w-4 mr-2" />
|
||||
View API Documentation
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<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"
|
||||
/>
|
||||
<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>
|
||||
{filteredFields.map((field) => (
|
||||
<TableHead key={field.name} className="capitalize">
|
||||
{field.name}
|
||||
</TableHead>
|
||||
))}
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{isLoading ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={filteredFields.length + 1} className="text-center text-muted-foreground h-64">
|
||||
Loading...
|
||||
</TableCell>
|
||||
</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>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={filteredFields.length + 1} className="text-center text-muted-foreground">
|
||||
{isLoading ? "Loading..." : "No data available"}
|
||||
) : 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}>
|
||||
{renderCellContent(field, row[field.name])}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={filteredFields.length + 1} className="text-center h-64 align-middle">
|
||||
<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">
|
||||
{!isViewType && (
|
||||
<Button onClick={handleAddItem} disabled={isDeleting || isLoading}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Record
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="outline" onClick={() => setDocsOpen(true)} disabled={isDeleting}>
|
||||
<FileText className="h-4 w-4 mr-2" />
|
||||
View API Documentation
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-between mt-4">
|
||||
|
||||
@@ -15,9 +15,8 @@ interface TableDocsDrawerProps {
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
// Generate docs based on user defined tables
|
||||
// Generate docs for entity schema management API
|
||||
export function TableDocsDrawer({ open, onClose }: TableDocsDrawerProps) {
|
||||
const [table, setTable] = React.useState({})
|
||||
const handleClose = () => {
|
||||
onClose()
|
||||
}
|
||||
@@ -29,55 +28,59 @@ export function TableDocsDrawer({ open, onClose }: TableDocsDrawerProps) {
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="h-5 w-5" />
|
||||
<DrawerTitle>Tables API Documentation</DrawerTitle>
|
||||
<DrawerTitle>Entity Schema API Documentation</DrawerTitle>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={onClose}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<DrawerDescription>Auto-generated API endpoints and examples</DrawerDescription>
|
||||
<DrawerDescription>
|
||||
API endpoints for managing entity schemas. All endpoints require admin authentication token.
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<ScrollArea className="h-full">
|
||||
<div className="p-6 space-y-6">
|
||||
<div className="rounded-lg border bg-muted/30 p-4 mb-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<strong className="text-foreground">Note:</strong> All endpoints require an admin authentication token in the Authorization header:
|
||||
<code className="ml-2 px-2 py-1 bg-background rounded text-xs">Authorization: Bearer YOUR_ADMIN_TOKEN</code>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="GET"
|
||||
endpoint={`/api/v1/tables`}
|
||||
description={`List all records in the tables table`}
|
||||
table={table}
|
||||
endpoint={`/api/v1/schemas`}
|
||||
description="List all entity schemas"
|
||||
operation="list"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="GET"
|
||||
endpoint={`/api/v1/tables/{id}`}
|
||||
description="Get a specific record by ID"
|
||||
table={table}
|
||||
endpoint={`/api/v1/schemas/{ENTITY_SCHEMA_NAME_OR_ID}`}
|
||||
description="Get a specific entity schema by name or ID"
|
||||
operation="get"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="POST"
|
||||
endpoint={`/api/v1/tables`}
|
||||
description="Create a new record"
|
||||
table={table}
|
||||
endpoint={`/api/v1/schemas`}
|
||||
description="Create a new entity schema"
|
||||
operation="create"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="PATCH"
|
||||
endpoint={`/api/v1/tables/{id}`}
|
||||
description="Update a specific record"
|
||||
table={table}
|
||||
endpoint={`/api/v1/schemas/{ENTITY_SCHEMA_NAME_OR_ID}`}
|
||||
description="Update an existing entity schema"
|
||||
operation="update"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="DELETE"
|
||||
endpoint={`/api/v1/tables/{id}`}
|
||||
description="Delete a specific record"
|
||||
table={table}
|
||||
endpoint={`/api/v1/schemas/{ENTITY_SCHEMA_NAME_OR_ID}`}
|
||||
description="Delete an entity schema"
|
||||
operation="delete"
|
||||
/>
|
||||
</div>
|
||||
@@ -92,13 +95,11 @@ function ApiEndpointCard({
|
||||
method,
|
||||
endpoint,
|
||||
description,
|
||||
table,
|
||||
operation,
|
||||
}: {
|
||||
method: string
|
||||
endpoint: string
|
||||
description: string
|
||||
table: TableMetadata
|
||||
operation: string
|
||||
}) {
|
||||
const [isOpen, setIsOpen] = React.useState(false)
|
||||
@@ -123,29 +124,86 @@ function ApiEndpointCard({
|
||||
}
|
||||
|
||||
const generateRequestExample = () => {
|
||||
const baseUrl = "https://your-api.com"
|
||||
const baseUrl = "{{MANTISBASE_BASE_URL}}"
|
||||
let example = `curl -X ${method} "${baseUrl}${endpoint}"`
|
||||
|
||||
if (method !== "GET") {
|
||||
example += ` \\\n -H "Content-Type: application/json"`
|
||||
}
|
||||
example += ` \\\n -H "Content-Type: application/json"`
|
||||
example += ` \\\n -H "Authorization: Bearer YOUR_ADMIN_TOKEN"`
|
||||
|
||||
example += ` \\\n -H "Authorization: Bearer YOUR_TOKEN"`
|
||||
|
||||
if (operation === "create" || operation === "update") {
|
||||
const sampleData: any = {}
|
||||
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"
|
||||
} else if (field.name === "password") {
|
||||
sampleData[field.name] = "securepassword"
|
||||
} else {
|
||||
sampleData[field.name] = `sample_${field.name}`
|
||||
if (operation === "create") {
|
||||
const sampleSchema = {
|
||||
name: "example_entity",
|
||||
type: "base",
|
||||
schema: {
|
||||
fields: [
|
||||
{
|
||||
name: "title",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: false,
|
||||
unique: false,
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
}
|
||||
}
|
||||
],
|
||||
rules: {
|
||||
add: { expr: "", mode: "auth" },
|
||||
delete: { expr: "", mode: "auth" },
|
||||
get: { expr: "", mode: "auth" },
|
||||
list: { expr: "", mode: "auth" },
|
||||
update: { expr: "", mode: "auth" }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
example += ` \\\n -d '${JSON.stringify(sampleData, null, 2)}'`
|
||||
// For view types, also include: view_query: "CREATE VIEW ... AS SELECT ..."
|
||||
}
|
||||
example += ` \\\n -d '${JSON.stringify(sampleSchema, null, 2)}'`
|
||||
} else if (operation === "update") {
|
||||
const sampleUpdate = {
|
||||
name: "updated_entity_name",
|
||||
schema: {
|
||||
fields: [
|
||||
{
|
||||
id: "mbf_existing_field_id",
|
||||
name: "updated_field_name",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: false,
|
||||
unique: false,
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "new_field",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
required: false,
|
||||
system: false,
|
||||
unique: false,
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "mbf_field_to_delete",
|
||||
op: "delete"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
example += ` \\\n -d '${JSON.stringify(sampleUpdate, null, 2)}'`
|
||||
}
|
||||
|
||||
return example
|
||||
@@ -153,30 +211,160 @@ function ApiEndpointCard({
|
||||
|
||||
const generateResponseExample = () => {
|
||||
if (operation === "list") {
|
||||
const sampleRecord: any = {}
|
||||
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") {
|
||||
sampleRecord[field.name] = "2024-01-15T10:00:00Z"
|
||||
} else if (field.name === "email") {
|
||||
sampleRecord[field.name] = "user@example.com"
|
||||
} else if (field.name === "password") {
|
||||
return // Don't include password in response
|
||||
} else {
|
||||
sampleRecord[field.name] = `sample_${field.name}`
|
||||
}
|
||||
})
|
||||
|
||||
// List schemas - NOT paginated, returns direct array
|
||||
return JSON.stringify(
|
||||
{
|
||||
data: [sampleRecord],
|
||||
pagination: {
|
||||
page: 1,
|
||||
limit: 20,
|
||||
total: 1,
|
||||
pages: 1,
|
||||
},
|
||||
data: [
|
||||
{
|
||||
created: "2025-12-05 02:08:06",
|
||||
id: "mbt_7691163245302450708",
|
||||
schema: {
|
||||
fields: [
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: "@password"
|
||||
},
|
||||
id: "mbf_14258576900392064537",
|
||||
name: "id",
|
||||
primary_key: true,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "string",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_13735287961322938256",
|
||||
name: "created",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_9124719522053273721",
|
||||
name: "updated",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: [],
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_16766180539469268884",
|
||||
name: "avatar",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: false,
|
||||
type: "files",
|
||||
unique: false
|
||||
}
|
||||
],
|
||||
has_api: true,
|
||||
id: "mbt_7691163245302450708",
|
||||
name: "test_new",
|
||||
rules: {
|
||||
add: { expr: "", mode: "" },
|
||||
delete: { expr: "", mode: "auth" },
|
||||
get: { expr: "", mode: "auth" },
|
||||
list: { expr: "", mode: "auth" },
|
||||
update: { expr: "", mode: "auth" }
|
||||
},
|
||||
system: false,
|
||||
type: "base"
|
||||
},
|
||||
updated: "2025-12-10 23:24:46"
|
||||
},
|
||||
{
|
||||
created: "2025-12-12 16:21:45",
|
||||
id: "mbt_15118982290295364091",
|
||||
schema: {
|
||||
fields: [
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: "@password"
|
||||
},
|
||||
id: "mbf_14258576900392064537",
|
||||
name: "id",
|
||||
primary_key: true,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "string",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_13735287961322938256",
|
||||
name: "created",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_9124719522053273721",
|
||||
name: "updated",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false
|
||||
}
|
||||
],
|
||||
has_api: true,
|
||||
id: "mbt_15118982290295364091",
|
||||
name: "test",
|
||||
rules: {
|
||||
add: { expr: "", mode: "auth" },
|
||||
delete: { expr: "", mode: "auth" },
|
||||
get: { expr: "", mode: "auth" },
|
||||
list: { expr: "", mode: "auth" },
|
||||
update: { expr: "", mode: "auth" }
|
||||
},
|
||||
system: false,
|
||||
type: "base"
|
||||
},
|
||||
updated: "2025-12-12 16:21:45"
|
||||
}
|
||||
],
|
||||
error: "",
|
||||
status: 200
|
||||
},
|
||||
null,
|
||||
2,
|
||||
@@ -184,26 +372,99 @@ function ApiEndpointCard({
|
||||
}
|
||||
|
||||
if (operation === "delete") {
|
||||
return JSON.stringify({}, null, 2)
|
||||
return "Status: 204 No Content"
|
||||
}
|
||||
|
||||
// Single record response
|
||||
const sampleRecord: any = {}
|
||||
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") {
|
||||
sampleRecord[field.name] = "2024-01-15T10:00:00Z"
|
||||
} else if (field.name === "email") {
|
||||
sampleRecord[field.name] = "user@example.com"
|
||||
} else if (field.name === "password") {
|
||||
return // Don't include password in response
|
||||
} else {
|
||||
sampleRecord[field.name] = `sample_${field.name}`
|
||||
}
|
||||
})
|
||||
|
||||
return JSON.stringify(sampleRecord, null, 2)
|
||||
// Single schema response (get, create, or update)
|
||||
return JSON.stringify(
|
||||
{
|
||||
data: {
|
||||
created: "2025-12-05 02:08:06",
|
||||
id: "mbt_7691163245302450708",
|
||||
schema: {
|
||||
fields: [
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: "@password"
|
||||
},
|
||||
id: "mbf_14258576900392064537",
|
||||
name: "id",
|
||||
primary_key: true,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "string",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_13735287961322938256",
|
||||
name: "created",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_9124719522053273721",
|
||||
name: "updated",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: [],
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_16766180539469268884",
|
||||
name: "avatar",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: false,
|
||||
type: "files",
|
||||
unique: false
|
||||
}
|
||||
],
|
||||
has_api: true,
|
||||
id: "mbt_7691163245302450708",
|
||||
name: "test_new",
|
||||
rules: {
|
||||
add: { expr: "", mode: "" },
|
||||
delete: { expr: "", mode: "auth" },
|
||||
get: { expr: "", mode: "auth" },
|
||||
list: { expr: "", mode: "auth" },
|
||||
update: { expr: "", mode: "auth" }
|
||||
},
|
||||
system: false,
|
||||
type: "base"
|
||||
},
|
||||
updated: "2025-12-10 23:24:46"
|
||||
},
|
||||
error: "",
|
||||
status: operation === "create" ? 201 : 200
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)
|
||||
}
|
||||
|
||||
const requestExample = generateRequestExample()
|
||||
@@ -264,33 +525,27 @@ function ApiEndpointCard({
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
400
|
||||
</Badge>
|
||||
<span>Bad Request - Invalid input data</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
401
|
||||
</Badge>
|
||||
<span>Unauthorized - Invalid or missing token</span>
|
||||
<span>Bad Request - Parsing error (message will be provided)</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
403
|
||||
</Badge>
|
||||
<span>Forbidden - Access denied by rules</span>
|
||||
<span>Forbidden - Auth error (admin token required)</span>
|
||||
</div>
|
||||
{(operation === "get" || operation === "update" || operation === "delete") && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
404
|
||||
</Badge>
|
||||
<span>Not Found - Record does not exist</span>
|
||||
<span>Not Found - Resource/item not found</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
500
|
||||
</Badge>
|
||||
<span>Internal Server Error - Server error</span>
|
||||
<span>Internal Server Error</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -29,7 +29,7 @@ export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerP
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="h-5 w-5" />
|
||||
<DrawerTitle>API Documentation - {table.name}</DrawerTitle>
|
||||
<DrawerTitle>API Documentation - {table.schema.name}</DrawerTitle>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={onClose}>
|
||||
<X className="h-4 w-4" />
|
||||
@@ -43,15 +43,15 @@ export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerP
|
||||
<div className="p-6 space-y-6">
|
||||
<ApiEndpointCard
|
||||
method="GET"
|
||||
endpoint={`/api/v1/${table.name}`}
|
||||
description={`List all records in the ${table.name} table`}
|
||||
endpoint={`/api/v1/entities/${table.schema.name}`}
|
||||
description={`List all records in the ${table.schema.name} table`}
|
||||
table={table}
|
||||
operation="list"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="GET"
|
||||
endpoint={`/api/v1/${table.name}/{id}`}
|
||||
endpoint={`/api/v1/entities/${table.schema.name}/{id}`}
|
||||
description="Get a specific record by ID"
|
||||
table={table}
|
||||
operation="get"
|
||||
@@ -61,7 +61,7 @@ export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerP
|
||||
<>
|
||||
<ApiEndpointCard
|
||||
method="POST"
|
||||
endpoint={`/api/v1/${table.name}`}
|
||||
endpoint={`/api/v1/entities/${table.schema.name}`}
|
||||
description="Create a new record"
|
||||
table={table}
|
||||
operation="create"
|
||||
@@ -69,7 +69,7 @@ export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerP
|
||||
|
||||
<ApiEndpointCard
|
||||
method="PATCH"
|
||||
endpoint={`/api/v1/${table.name}/{id}`}
|
||||
endpoint={`/api/v1/entities/${table.schema.name}/{id}`}
|
||||
description="Update a specific record"
|
||||
table={table}
|
||||
operation="update"
|
||||
@@ -77,7 +77,7 @@ export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerP
|
||||
|
||||
<ApiEndpointCard
|
||||
method="DELETE"
|
||||
endpoint={`/api/v1/${table.name}/{id}`}
|
||||
endpoint={`/api/v1/entities/${table.schema.name}/{id}`}
|
||||
description="Delete a specific record"
|
||||
table={table}
|
||||
operation="delete"
|
||||
|
||||
@@ -9,7 +9,6 @@ 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
|
||||
@@ -21,7 +20,6 @@ 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()
|
||||
@@ -29,7 +27,7 @@ export function LoginForm({ onLogin }: LoginFormProps) {
|
||||
setError("")
|
||||
|
||||
try {
|
||||
const data = await loginWithPassword(email, password, mode)
|
||||
const data = await loginWithPassword(email, password)
|
||||
localStorage.setItem("admin_token", data.token)
|
||||
onLogin(data.token)
|
||||
} catch (err: any) {
|
||||
@@ -40,7 +38,7 @@ export function LoginForm({ onLogin }: LoginFormProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="min-h-screen flex items-center justify-center bg-background">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Download, Filter, Search } from "lucide-react"
|
||||
import { Download, Search, ChevronLeft, ChevronRight } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
@@ -9,7 +9,15 @@ import { Input } from "@/components/ui/input"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar"
|
||||
import {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationItem,
|
||||
PaginationLink,
|
||||
PaginationNext,
|
||||
PaginationPrevious,
|
||||
} from "@/components/ui/pagination"
|
||||
import type { ApiClient } from "@/lib/api"
|
||||
|
||||
interface LogEntry {
|
||||
id: string
|
||||
@@ -20,8 +28,15 @@ interface LogEntry {
|
||||
details?: string
|
||||
}
|
||||
|
||||
export function LogsSection() {
|
||||
const [logs] = React.useState<LogEntry[]>([
|
||||
interface LogsSectionProps {
|
||||
apiClient: ApiClient
|
||||
}
|
||||
|
||||
const ITEMS_PER_PAGE = 10
|
||||
|
||||
export function LogsSection({ apiClient }: LogsSectionProps) {
|
||||
// Mock data - sorted by latest first
|
||||
const [allLogs] = React.useState<LogEntry[]>([
|
||||
{
|
||||
id: "1",
|
||||
timestamp: "2024-01-15T10:30:00Z",
|
||||
@@ -62,18 +77,88 @@ export function LogsSection() {
|
||||
source: "system",
|
||||
details: "Daily backup completed successfully (2.3GB)",
|
||||
},
|
||||
])
|
||||
{
|
||||
id: "6",
|
||||
timestamp: "2024-01-15T10:05:00Z",
|
||||
level: "info",
|
||||
message: "Cache cleared",
|
||||
source: "system",
|
||||
details: "Application cache cleared successfully",
|
||||
},
|
||||
{
|
||||
id: "7",
|
||||
timestamp: "2024-01-15T10:00:00Z",
|
||||
level: "warning",
|
||||
message: "High memory usage detected",
|
||||
source: "system",
|
||||
details: "Memory usage at 85% of available capacity",
|
||||
},
|
||||
{
|
||||
id: "8",
|
||||
timestamp: "2024-01-15T09:55:00Z",
|
||||
level: "info",
|
||||
message: "Scheduled task completed",
|
||||
source: "system",
|
||||
details: "Daily maintenance task completed in 2.3 seconds",
|
||||
},
|
||||
{
|
||||
id: "9",
|
||||
timestamp: "2024-01-15T09:50:00Z",
|
||||
level: "error",
|
||||
message: "Failed to send email notification",
|
||||
source: "email",
|
||||
details: "SMTP server connection timeout",
|
||||
},
|
||||
{
|
||||
id: "10",
|
||||
timestamp: "2024-01-15T09:45:00Z",
|
||||
level: "info",
|
||||
message: "API request processed",
|
||||
source: "api",
|
||||
details: "GET /api/v1/users processed in 45ms",
|
||||
},
|
||||
{
|
||||
id: "11",
|
||||
timestamp: "2024-01-15T09:40:00Z",
|
||||
level: "info",
|
||||
message: "User session expired",
|
||||
source: "auth",
|
||||
details: "Session expired for user user@example.com",
|
||||
},
|
||||
{
|
||||
id: "12",
|
||||
timestamp: "2024-01-15T09:35:00Z",
|
||||
level: "warning",
|
||||
message: "Slow query detected",
|
||||
source: "database",
|
||||
details: "Query took 2.5 seconds to execute",
|
||||
},
|
||||
].sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()))
|
||||
|
||||
const [searchTerm, setSearchTerm] = React.useState("")
|
||||
const [levelFilter, setLevelFilter] = React.useState<string>("all")
|
||||
const [currentPage, setCurrentPage] = React.useState(1)
|
||||
|
||||
const filteredLogs = logs.filter((log) => {
|
||||
const matchesSearch =
|
||||
log.message.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
log.source.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
const matchesLevel = levelFilter === "all" || log.level === levelFilter
|
||||
return matchesSearch && matchesLevel
|
||||
})
|
||||
const filteredLogs = React.useMemo(() => {
|
||||
return allLogs.filter((log) => {
|
||||
const matchesSearch =
|
||||
log.message.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
log.source.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
(log.details && log.details.toLowerCase().includes(searchTerm.toLowerCase()))
|
||||
const matchesLevel = levelFilter === "all" || log.level === levelFilter
|
||||
return matchesSearch && matchesLevel
|
||||
})
|
||||
}, [allLogs, searchTerm, levelFilter])
|
||||
|
||||
const totalPages = Math.ceil(filteredLogs.length / ITEMS_PER_PAGE)
|
||||
const startIndex = (currentPage - 1) * ITEMS_PER_PAGE
|
||||
const endIndex = startIndex + ITEMS_PER_PAGE
|
||||
const paginatedLogs = filteredLogs.slice(startIndex, endIndex)
|
||||
|
||||
React.useEffect(() => {
|
||||
// Reset to first page when filters change
|
||||
setCurrentPage(1)
|
||||
}, [searchTerm, levelFilter])
|
||||
|
||||
const getLevelColor = (level: string) => {
|
||||
switch (level) {
|
||||
@@ -88,79 +173,169 @@ export function LogsSection() {
|
||||
}
|
||||
}
|
||||
|
||||
const formatTimestamp = (timestamp: string) => {
|
||||
const date = new Date(timestamp)
|
||||
return date.toLocaleString("en-US", {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-6 p-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<SidebarTrigger />
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">System Logs</h2>
|
||||
<p className="text-muted-foreground">Monitor system activity and events</p>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-3xl font-bold tracking-tight">Logs</h1>
|
||||
<p className="text-muted-foreground">Monitor system activity and events</p>
|
||||
</div>
|
||||
<Button>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Export Logs
|
||||
Export
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center space-x-2 flex-1">
|
||||
<Search className="h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search logs..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="max-w-sm"
|
||||
/>
|
||||
</div>
|
||||
<Select value={levelFilter} onValueChange={setLevelFilter}>
|
||||
<SelectTrigger className="w-32">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All Levels</SelectItem>
|
||||
<SelectItem value="info">Info</SelectItem>
|
||||
<SelectItem value="warning">Warning</SelectItem>
|
||||
<SelectItem value="error">Error</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button variant="outline">
|
||||
<Filter className="h-4 w-4 mr-2" />
|
||||
Filters
|
||||
</Button>
|
||||
</div>
|
||||
{/* Filters */}
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="relative flex-1 max-w-sm">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search logs..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<Select value={levelFilter} onValueChange={setLevelFilter}>
|
||||
<SelectTrigger className="w-[140px]">
|
||||
<SelectValue placeholder="All Levels" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All Levels</SelectItem>
|
||||
<SelectItem value="info">Info</SelectItem>
|
||||
<SelectItem value="warning">Warning</SelectItem>
|
||||
<SelectItem value="error">Error</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Logs Table */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Recent Activity</CardTitle>
|
||||
<CardDescription>{filteredLogs.length} log entries</CardDescription>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>System Logs</CardTitle>
|
||||
<CardDescription>
|
||||
Showing {startIndex + 1}-{Math.min(endIndex, filteredLogs.length)} of {filteredLogs.length} entries
|
||||
</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Timestamp</TableHead>
|
||||
<TableHead>Level</TableHead>
|
||||
<TableHead>Source</TableHead>
|
||||
<TableHead>Message</TableHead>
|
||||
<TableHead>Details</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{filteredLogs.map((log) => (
|
||||
<TableRow key={log.id}>
|
||||
<TableCell className="font-mono text-sm">{new Date(log.timestamp).toLocaleString()}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={getLevelColor(log.level) as any}>{log.level.toUpperCase()}</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">{log.source}</TableCell>
|
||||
<TableCell>{log.message}</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground max-w-xs truncate">{log.details}</TableCell>
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[180px]">Timestamp</TableHead>
|
||||
<TableHead className="w-[100px]">Level</TableHead>
|
||||
<TableHead className="w-[120px]">Source</TableHead>
|
||||
<TableHead>Message</TableHead>
|
||||
<TableHead className="max-w-md">Details</TableHead>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{paginatedLogs.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="h-24 text-center text-muted-foreground">
|
||||
No logs found
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
paginatedLogs.map((log) => (
|
||||
<TableRow key={log.id} className="hover:bg-muted/50">
|
||||
<TableCell className="font-mono text-xs">
|
||||
{formatTimestamp(log.timestamp)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={getLevelColor(log.level) as any} className="font-medium">
|
||||
{log.level.toUpperCase()}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span className="font-medium capitalize">{log.source}</span>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">{log.message}</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground">
|
||||
<div className="max-w-md truncate" title={log.details}>
|
||||
{log.details || "-"}
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
{totalPages > 1 && (
|
||||
<div className="mt-4 flex items-center justify-between">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Page {currentPage} of {totalPages}
|
||||
</div>
|
||||
<Pagination>
|
||||
<PaginationContent>
|
||||
<PaginationItem>
|
||||
<PaginationPrevious
|
||||
onClick={() => setCurrentPage((prev) => Math.max(1, prev - 1))}
|
||||
className={currentPage === 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
|
||||
/>
|
||||
</PaginationItem>
|
||||
{Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => {
|
||||
// Show first page, last page, current page, and pages around current
|
||||
if (
|
||||
page === 1 ||
|
||||
page === totalPages ||
|
||||
(page >= currentPage - 1 && page <= currentPage + 1)
|
||||
) {
|
||||
return (
|
||||
<PaginationItem key={page}>
|
||||
<PaginationLink
|
||||
onClick={() => setCurrentPage(page)}
|
||||
isActive={currentPage === page}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
{page}
|
||||
</PaginationLink>
|
||||
</PaginationItem>
|
||||
)
|
||||
} else if (page === currentPage - 2 || page === currentPage + 2) {
|
||||
return (
|
||||
<PaginationItem key={page}>
|
||||
<span className="px-2">...</span>
|
||||
</PaginationItem>
|
||||
)
|
||||
}
|
||||
return null
|
||||
})}
|
||||
<PaginationItem>
|
||||
<PaginationNext
|
||||
onClick={() => setCurrentPage((prev) => Math.min(totalPages, prev + 1))}
|
||||
className={currentPage === totalPages ? "pointer-events-none opacity-50" : "cursor-pointer"}
|
||||
/>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
|
||||
import * as React from "react"
|
||||
import { LoginForm } from "@/components/login-form"
|
||||
import { SetupForm } from "@/components/setup-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() {
|
||||
export default function MainPage() {
|
||||
const [token, setToken] = React.useState<string | null>(null)
|
||||
const [mounted, setMounted] = React.useState(false)
|
||||
const { route, navigate } = useRouter()
|
||||
@@ -31,11 +32,17 @@ export default function Page() {
|
||||
if (mounted) {
|
||||
try {
|
||||
const currentPath = route.path
|
||||
const isSetupRoute = currentPath === "/setup"
|
||||
|
||||
// Setup route doesn't require authentication
|
||||
if (isSetupRoute) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!token && currentPath !== "/login") {
|
||||
navigate("/login")
|
||||
navigate("/login", undefined, undefined)
|
||||
} else if (token && currentPath === "/login") {
|
||||
navigate("/tables")
|
||||
navigate("/entities", undefined, undefined)
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Failed to handle route change:", error)
|
||||
@@ -46,7 +53,7 @@ export default function Page() {
|
||||
const handleLogin = (newToken: string) => {
|
||||
try {
|
||||
setToken(newToken)
|
||||
navigate("/tables")
|
||||
navigate("/entities", undefined, undefined)
|
||||
} catch (error) {
|
||||
console.warn("Failed to handle login:", error)
|
||||
}
|
||||
@@ -56,12 +63,20 @@ export default function Page() {
|
||||
try {
|
||||
setToken(null)
|
||||
localStorage.removeItem("admin_token")
|
||||
navigate("/login")
|
||||
navigate("/login", undefined, undefined)
|
||||
} catch (error) {
|
||||
console.warn("Failed to handle logout:", error)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSetupComplete = () => {
|
||||
try {
|
||||
navigate("/login", undefined, undefined)
|
||||
} catch (error) {
|
||||
console.warn("Failed to handle setup complete:", error)
|
||||
}
|
||||
}
|
||||
|
||||
if (!mounted) {
|
||||
return (
|
||||
<div className="flex min-h-screen w-full items-center justify-center">
|
||||
@@ -73,10 +88,15 @@ export default function Page() {
|
||||
)
|
||||
}
|
||||
|
||||
const isSetupRoute = route.path === "/setup"
|
||||
const setupToken = route.queryParams.token
|
||||
|
||||
return (
|
||||
<ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
|
||||
<ThemeProvider attribute="class" defaultTheme="dark" enableSystem storageKey="mantis-admin-theme" disableTransitionOnChange>
|
||||
<AppStateProvider>
|
||||
{route.path === "/login" || !token ? (
|
||||
{isSetupRoute && setupToken ? (
|
||||
<SetupForm token={setupToken} onSetupComplete={handleSetupComplete} />
|
||||
) : route.path === "/login" || !token ? (
|
||||
<LoginForm onLogin={handleLogin} />
|
||||
) : (
|
||||
<AdminDashboard token={token} onLogout={handleLogout} />
|
||||
@@ -86,3 +106,4 @@ export default function Page() {
|
||||
</ThemeProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { RefreshCw, TestTube, Globe } from "lucide-react"
|
||||
import { RefreshCw, Save } 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"
|
||||
@@ -24,17 +22,78 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
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 [originalData, setOriginalData] = React.useState<AppSettings | null>(null)
|
||||
const [isLoading, setIsLoading] = React.useState<Record<string, boolean>>({})
|
||||
const [isRefreshing, setIsRefreshing] = React.useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (settings) {
|
||||
setFormData({ ...settings, mode })
|
||||
setHasChanges(false)
|
||||
const data = { ...settings, mode }
|
||||
setFormData(data)
|
||||
setOriginalData(data)
|
||||
}
|
||||
}, [settings, mode])
|
||||
|
||||
// Track changes per card section
|
||||
const getCardChanges = (cardType: "general" | "file" | "features"): boolean => {
|
||||
if (!formData || !originalData) return false
|
||||
|
||||
if (cardType === "general") {
|
||||
return (
|
||||
formData.appName !== originalData.appName ||
|
||||
formData.baseUrl !== originalData.baseUrl
|
||||
)
|
||||
}
|
||||
|
||||
if (cardType === "file") {
|
||||
return (
|
||||
formData.maxFileSize !== originalData.maxFileSize ||
|
||||
formData.sessionTimeout !== originalData.sessionTimeout ||
|
||||
formData.adminSessionTimeout !== originalData.adminSessionTimeout
|
||||
)
|
||||
}
|
||||
|
||||
if (cardType === "features") {
|
||||
return (
|
||||
formData.maintenanceMode !== originalData.maintenanceMode ||
|
||||
formData.allowRegistration !== originalData.allowRegistration ||
|
||||
formData.emailVerificationRequired !== originalData.emailVerificationRequired
|
||||
)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
const resetCardChanges = (cardType: "general" | "file" | "features") => {
|
||||
if (!formData || !originalData) return
|
||||
|
||||
if (cardType === "general") {
|
||||
setFormData({
|
||||
...formData,
|
||||
appName: originalData.appName,
|
||||
baseUrl: originalData.baseUrl,
|
||||
})
|
||||
}
|
||||
|
||||
if (cardType === "file") {
|
||||
setFormData({
|
||||
...formData,
|
||||
maxFileSize: originalData.maxFileSize,
|
||||
sessionTimeout: originalData.sessionTimeout,
|
||||
adminSessionTimeout: originalData.adminSessionTimeout,
|
||||
})
|
||||
}
|
||||
|
||||
if (cardType === "features") {
|
||||
setFormData({
|
||||
...formData,
|
||||
maintenanceMode: originalData.maintenanceMode,
|
||||
allowRegistration: originalData.allowRegistration,
|
||||
emailVerificationRequired: originalData.emailVerificationRequired,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleInputChange = (field: keyof AppSettings, value: any) => {
|
||||
if (!formData) return
|
||||
|
||||
@@ -42,41 +101,40 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
...formData,
|
||||
[field]: value,
|
||||
})
|
||||
setHasChanges(true)
|
||||
}
|
||||
|
||||
const handleModeToggle = (newMode: AppMode) => {
|
||||
setMode(newMode)
|
||||
if (formData) {
|
||||
setFormData({
|
||||
...formData,
|
||||
mode: newMode,
|
||||
})
|
||||
setHasChanges(true)
|
||||
}
|
||||
onModeChange(newMode, formData?.baseUrl)
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
const handleSave = async (cardType: "general" | "file" | "features") => {
|
||||
if (!formData) return
|
||||
|
||||
setIsLoading(true)
|
||||
setIsLoading({ ...isLoading, [cardType]: true })
|
||||
try {
|
||||
const updatedSettings = await apiClient.call<AppSettings>("/api/v1/settings/config", {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(formData),
|
||||
})
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (updatedSettings?.error?.length > 0) throw updatedSettings.error
|
||||
|
||||
const data = { ...updatedSettings, mode }
|
||||
setFormData(data)
|
||||
setOriginalData(data)
|
||||
onSettingsUpdate(updatedSettings)
|
||||
setHasChanges(false)
|
||||
|
||||
toast({
|
||||
title: "Settings Saved",
|
||||
description: "Application settings have been updated successfully.",
|
||||
description: `${cardType.charAt(0).toUpperCase() + cardType.slice(1)} settings have been updated successfully.`,
|
||||
duration: 3000,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to update settings:", error)
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Failed to save settings. Please try again.",
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
setIsLoading({ ...isLoading, [cardType]: false })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,6 +142,10 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
setIsRefreshing(true)
|
||||
try {
|
||||
const updatedSettings = await apiClient.call<AppSettings>("/api/v1/settings/config")
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (updatedSettings?.error?.length > 0) throw updatedSettings.error
|
||||
|
||||
onSettingsUpdate(updatedSettings)
|
||||
} catch (error) {
|
||||
console.error("Failed to refresh settings:", error)
|
||||
@@ -105,216 +167,225 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-8 p-6">
|
||||
{/* Header */}
|
||||
<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 className="space-y-1">
|
||||
<h1 className="text-3xl font-bold tracking-tight">Settings</h1>
|
||||
<p className="text-muted-foreground">Manage your application configuration and preferences</p>
|
||||
</div>
|
||||
<Button variant="outline" size="icon" onClick={handleRefresh} disabled={isRefreshing}>
|
||||
<RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>General Settings</CardTitle>
|
||||
<CardDescription>Basic application configuration</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="app-name">Application Name</Label>
|
||||
<Input
|
||||
id="app-name"
|
||||
value={formData?.appName || ""}
|
||||
onChange={(e) => handleInputChange("appName", e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="version">Version</Label>
|
||||
<Input
|
||||
id="version"
|
||||
value={formData?.mantisVersion || ""}
|
||||
disabled={true}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="base-url">Base URL</Label>
|
||||
<Input
|
||||
id="base-url"
|
||||
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{" "}
|
||||
{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">
|
||||
<div>
|
||||
<Label htmlFor="max-file-size">Max File Size (MB)</Label>
|
||||
<Input
|
||||
id="max-file-size"
|
||||
type="number"
|
||||
value={formData?.maxFileSize?.toString() || 10}
|
||||
onChange={(e) => handleInputChange("maxFileSize", Number.parseInt(e.target.value) || 10)}
|
||||
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="session-timeout">Session Timeout (seconds)</Label>
|
||||
<Input
|
||||
id="session-timeout"
|
||||
type="number"
|
||||
value={formData?.sessionTimeout?.toString() || 86400}
|
||||
onChange={(e) => handleInputChange("sessionTimeout", Number.parseInt(e.target.value) || 86400)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="session-timeout">Admin Session Timeout (seconds)</Label>
|
||||
<Input
|
||||
id="admin-session-timeout"
|
||||
type="number"
|
||||
value={formData?.adminSessionTimeout?.toString() || 84000}
|
||||
onChange={(e) => handleInputChange("adminSessionTimeout", Number.parseInt(e.target.value) || 3600)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-6">
|
||||
{/* General Settings */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<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>
|
||||
<CardTitle>General</CardTitle>
|
||||
<CardDescription>Basic application information and configuration</CardDescription>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData?.maintenanceMode || false}
|
||||
onCheckedChange={(checked) => handleInputChange("maintenanceMode", checked)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<Label>Allow Registration</Label>
|
||||
<p className="text-sm text-muted-foreground">Allow new users to register</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData?.allowRegistration || false}
|
||||
onCheckedChange={(checked) => handleInputChange("allowRegistration", checked)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<Label>Email Verification Required</Label>
|
||||
<p className="text-sm text-muted-foreground">Require email verification for new accounts</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData?.emailVerificationRequired || false}
|
||||
onCheckedChange={(checked) => handleInputChange("emailVerificationRequired", checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Environment Mode Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Environment Mode</CardTitle>
|
||||
<CardDescription>Switch between test mode (cors supported) 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 UI dev server for development</p>
|
||||
</div>
|
||||
{mode === "TEST" && (
|
||||
<Badge variant="default" className="ml-auto">
|
||||
Active
|
||||
</Badge>
|
||||
{getCardChanges("general") && (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleSave("general")}
|
||||
disabled={isLoading.general}
|
||||
className="gap-2"
|
||||
>
|
||||
{isLoading.general ? (
|
||||
<>
|
||||
<RefreshCw className="h-4 w-4 animate-spin" />
|
||||
Saving...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="h-4 w-4" />
|
||||
Save
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="app-name">Application Name</Label>
|
||||
<Input
|
||||
id="app-name"
|
||||
value={formData?.appName || ""}
|
||||
onChange={(e) => handleInputChange("appName", e.target.value)}
|
||||
placeholder="My Application"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="version">Version</Label>
|
||||
<Input
|
||||
id="version"
|
||||
value={formData?.mantisVersion || ""}
|
||||
disabled
|
||||
className="bg-muted"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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">API and UI running on same server.</p>
|
||||
</div>
|
||||
{mode === "PROD" && (
|
||||
<Badge variant="default" className="ml-auto">
|
||||
Active
|
||||
</Badge>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="base-url">Base URL</Label>
|
||||
<Input
|
||||
id="base-url"
|
||||
value={formData?.baseUrl || ""}
|
||||
onChange={(e) => handleInputChange("baseUrl", e.target.value)}
|
||||
placeholder="https://your-api-domain.com"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{mode === "PROD"
|
||||
? "The base URL for your API endpoints in production mode"
|
||||
: "Not used in test mode - API calls go to external server"}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* File & Session Settings */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>File & Sessions</CardTitle>
|
||||
<CardDescription>Configure file upload limits and session timeouts</CardDescription>
|
||||
</div>
|
||||
{getCardChanges("file") && (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleSave("file")}
|
||||
disabled={isLoading.file}
|
||||
className="gap-2"
|
||||
>
|
||||
{isLoading.file ? (
|
||||
<>
|
||||
<RefreshCw className="h-4 w-4 animate-spin" />
|
||||
Saving...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="h-4 w-4" />
|
||||
Save
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="max-file-size">Max File Size (MB)</Label>
|
||||
<Input
|
||||
id="max-file-size"
|
||||
type="number"
|
||||
value={formData?.maxFileSize?.toString() || 10}
|
||||
onChange={(e) => handleInputChange("maxFileSize", Number.parseInt(e.target.value) || 10)}
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="session-timeout">Session Timeout (s)</Label>
|
||||
<Input
|
||||
id="session-timeout"
|
||||
type="number"
|
||||
value={formData?.sessionTimeout?.toString() || 86400}
|
||||
onChange={(e) => handleInputChange("sessionTimeout", Number.parseInt(e.target.value) || 86400)}
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="admin-session-timeout">Admin Session (s)</Label>
|
||||
<Input
|
||||
id="admin-session-timeout"
|
||||
type="number"
|
||||
value={formData?.adminSessionTimeout?.toString() || 3600}
|
||||
onChange={(e) => handleInputChange("adminSessionTimeout", Number.parseInt(e.target.value) || 3600)}
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{mode === "TEST" && (
|
||||
<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">Testing Mode Active</p>
|
||||
<p className="text-sm text-yellow-700 dark:text-yellow-300">
|
||||
All API calls will be made to an external API server. Ensure your API server is running and
|
||||
accessible, and set `MANTIS_PORT` in the env settings.
|
||||
{/* Feature Toggles */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>Features</CardTitle>
|
||||
<CardDescription>Enable or disable application features</CardDescription>
|
||||
</div>
|
||||
{getCardChanges("features") && (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleSave("features")}
|
||||
disabled={isLoading.features}
|
||||
className="gap-2"
|
||||
>
|
||||
{isLoading.features ? (
|
||||
<>
|
||||
<RefreshCw className="h-4 w-4 animate-spin" />
|
||||
Saving...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="h-4 w-4" />
|
||||
Save
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-base">Maintenance Mode</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Temporarily disable access to the application
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData?.maintenanceMode || false}
|
||||
onCheckedChange={(checked) => handleInputChange("maintenanceMode", checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-base">Allow Registration</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Allow new users to create accounts
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData?.allowRegistration || false}
|
||||
onCheckedChange={(checked) => handleInputChange("allowRegistration", checked)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
if (settings) {
|
||||
setFormData({ ...settings, mode })
|
||||
setHasChanges(false)
|
||||
}
|
||||
}}
|
||||
disabled={!hasChanges}
|
||||
>
|
||||
Reset
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={isLoading || !hasChanges}>
|
||||
{isLoading ? "Saving..." : "Save Settings"}
|
||||
</Button>
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-base">Email Verification</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Require email verification for new accounts
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData?.emailVerificationRequired || false}
|
||||
onCheckedChange={(checked) => handleInputChange("emailVerificationRequired", checked)}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
183
components/setup-form.tsx
Normal file
183
components/setup-form.tsx
Normal file
@@ -0,0 +1,183 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Eye, EyeOff, Shield, CheckCircle2 } 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 { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import { ApiClient } from "@/lib/api"
|
||||
import { useAppState } from "@/lib/app-state"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
interface SetupFormProps {
|
||||
token: string
|
||||
onSetupComplete: () => void
|
||||
}
|
||||
|
||||
export function SetupForm({ token, onSetupComplete }: SetupFormProps) {
|
||||
const [email, setEmail] = React.useState("")
|
||||
const [password, setPassword] = React.useState("")
|
||||
const [confirmPassword, setConfirmPassword] = React.useState("")
|
||||
const [showPassword, setShowPassword] = React.useState(false)
|
||||
const [showConfirmPassword, setShowConfirmPassword] = React.useState(false)
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [error, setError] = React.useState("")
|
||||
const [success, setSuccess] = React.useState(false)
|
||||
const { mode } = useAppState()
|
||||
const { toast } = useToast()
|
||||
|
||||
const apiClient = React.useMemo(() => {
|
||||
return new ApiClient(
|
||||
token,
|
||||
() => {},
|
||||
(error) => setError(error)
|
||||
)
|
||||
}, [token])
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setIsLoading(true)
|
||||
setError("")
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
setError("Passwords do not match")
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
if (password.length < 8) {
|
||||
setError("Password must be at least 8 characters long")
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// Create admin account using the setup token
|
||||
const response: any = await apiClient.call("/api/v1/entities/mb_admins", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
password,
|
||||
}),
|
||||
})
|
||||
|
||||
if (response?.error?.length > 0) {
|
||||
throw new Error(response.error)
|
||||
}
|
||||
|
||||
setSuccess(true)
|
||||
toast({
|
||||
title: "Account Created",
|
||||
description: "Your admin account has been created successfully. You can now sign in.",
|
||||
})
|
||||
|
||||
// Wait a moment then redirect to login
|
||||
setTimeout(() => {
|
||||
onSetupComplete()
|
||||
}, 2000)
|
||||
} catch (err: any) {
|
||||
setError(err.message || "Failed to create admin account")
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-background">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<Shield className="h-12 w-12 text-primary" />
|
||||
</div>
|
||||
<CardTitle className="text-2xl">Setup Admin Account</CardTitle>
|
||||
<CardDescription>Create your first admin account to get started</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{success ? (
|
||||
<div className="text-center space-y-4 py-4">
|
||||
<CheckCircle2 className="h-16 w-16 text-green-500 mx-auto" />
|
||||
<p className="text-lg font-medium">Account created successfully!</p>
|
||||
<p className="text-sm text-muted-foreground">Redirecting to login...</p>
|
||||
</div>
|
||||
) : (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="admin@example.com"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? "text" : "password"}
|
||||
placeholder="Enter your password (min. 8 characters)"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
minLength={8}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
>
|
||||
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirm-password">Confirm Password</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="confirm-password"
|
||||
type={showConfirmPassword ? "text" : "password"}
|
||||
placeholder="Confirm your password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
required
|
||||
minLength={8}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
||||
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
||||
>
|
||||
{showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? "Creating account..." : "Create Admin Account"}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -19,14 +19,11 @@ export function SyncSection() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-6 p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<SidebarTrigger />
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">Data Synchronization</h2>
|
||||
<p className="text-muted-foreground">Manage data sync operations and status</p>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-3xl font-bold tracking-tight">Sync</h1>
|
||||
<p className="text-muted-foreground">Manage data sync operations and status</p>
|
||||
</div>
|
||||
<Button onClick={handleSync} disabled={isLoading}>
|
||||
<RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? "animate-spin" : ""}`} />
|
||||
|
||||
@@ -3,5 +3,9 @@ import { ThemeProvider as NextThemesProvider } from "next-themes"
|
||||
import type { ThemeProviderProps } from "next-themes"
|
||||
|
||||
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
|
||||
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
|
||||
return (
|
||||
<NextThemesProvider {...props} suppressColorSchemeWarning>
|
||||
{children}
|
||||
</NextThemesProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,11 @@ import { Moon, Sun } from "lucide-react"
|
||||
import { useTheme } from "next-themes"
|
||||
import { SidebarMenuButton } from "@/components/ui/sidebar"
|
||||
|
||||
export function ThemeToggle() {
|
||||
interface ThemeToggleProps {
|
||||
iconOnly?: boolean
|
||||
}
|
||||
|
||||
export function ThemeToggle({ iconOnly = false }: ThemeToggleProps) {
|
||||
const { theme, setTheme, resolvedTheme } = useTheme()
|
||||
const [mounted, setMounted] = React.useState(false)
|
||||
|
||||
@@ -15,21 +19,27 @@ export function ThemeToggle() {
|
||||
|
||||
if (!mounted) {
|
||||
return (
|
||||
<SidebarMenuButton>
|
||||
<div className="h-4 w-4" />
|
||||
<span>Theme</span>
|
||||
<SidebarMenuButton style={iconOnly ? { height: "4rem", minHeight: "4rem" } : undefined} className={iconOnly ? "w-full justify-center p-0 mx-0 rounded-none min-w-full" : ""}>
|
||||
<div className="h-6 w-6" />
|
||||
{!iconOnly && <span>Theme</span>}
|
||||
</SidebarMenuButton>
|
||||
)
|
||||
}
|
||||
|
||||
const toggleTheme = () => {
|
||||
setTheme(resolvedTheme === "dark" ? "light" : "dark")
|
||||
// Always toggle between light and dark explicitly
|
||||
const currentResolved = resolvedTheme || "light"
|
||||
const newTheme = currentResolved === "dark" ? "light" : "dark"
|
||||
setTheme(newTheme)
|
||||
}
|
||||
|
||||
const displayTheme = resolvedTheme || "light"
|
||||
|
||||
return (
|
||||
<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 onClick={toggleTheme} style={iconOnly ? { height: "4rem", minHeight: "4rem" } : undefined} className={iconOnly ? "w-full justify-center p-0 mx-0 rounded-none min-w-full" : ""}>
|
||||
{displayTheme === "dark" ? <Sun className="h-6 w-6" /> : <Moon className="h-6 w-6" />}
|
||||
{!iconOnly && <span>{displayTheme === "dark" ? "Light Mode" : "Dark Mode"}</span>}
|
||||
{iconOnly && <span className="sr-only">{displayTheme === "dark" ? "Switch to Light" : "Switch to Dark"}</span>}
|
||||
</SidebarMenuButton>
|
||||
)
|
||||
}
|
||||
|
||||
210
lib/api.ts
210
lib/api.ts
@@ -2,44 +2,54 @@
|
||||
|
||||
import type { AppMode } from "./app-state"
|
||||
|
||||
|
||||
// Updated interfaces to match the API response format
|
||||
export interface FieldConstraints {
|
||||
default_value: any
|
||||
max_value: number | null
|
||||
min_value: number | null
|
||||
validator: string | null
|
||||
}
|
||||
|
||||
export interface TableField {
|
||||
autoGeneratePattern: string | null
|
||||
defaultValue: string | null
|
||||
maxValue: number | null
|
||||
minValue: number | null
|
||||
id: string
|
||||
name: string
|
||||
old_name: string | null
|
||||
primaryKey: boolean
|
||||
primary_key: boolean
|
||||
required: boolean
|
||||
system: boolean
|
||||
type: string
|
||||
unique: boolean
|
||||
validator: string | null
|
||||
constraints: FieldConstraints
|
||||
}
|
||||
|
||||
export interface RuleConfig {
|
||||
expr: string
|
||||
mode: string
|
||||
}
|
||||
|
||||
export interface SchemaRules {
|
||||
add: RuleConfig
|
||||
delete: RuleConfig
|
||||
get: RuleConfig
|
||||
list: RuleConfig
|
||||
update: RuleConfig
|
||||
}
|
||||
|
||||
export interface TableSchema {
|
||||
addRule: string
|
||||
deleteRule: string
|
||||
fields: TableField[]
|
||||
getRule: string
|
||||
has_api: boolean
|
||||
id: string
|
||||
listRule: string
|
||||
name: string
|
||||
rules: SchemaRules
|
||||
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
|
||||
}
|
||||
|
||||
@@ -50,6 +60,24 @@ export interface Admin {
|
||||
updated: string
|
||||
}
|
||||
|
||||
export function getApiBaseUrl(): string {
|
||||
|
||||
const mode = process?.env?.NODE_ENV || "production";
|
||||
const port = process?.env?.MANTIS_PORT || 7070;
|
||||
|
||||
if (mode === "development") {
|
||||
// For debug mode, or non window sessions, pick port from env
|
||||
return `http://localhost:${port}`;
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
const { origin } = window.location;
|
||||
return `${origin}`;
|
||||
}
|
||||
|
||||
return `http://localhost:${port}`;
|
||||
}
|
||||
|
||||
export interface AppSettings {
|
||||
allowRegistration: boolean
|
||||
appName: string
|
||||
@@ -70,61 +98,31 @@ interface ApiResponse<T> {
|
||||
status: number
|
||||
}
|
||||
|
||||
// utils/getApiBaseUrl.ts
|
||||
|
||||
type AppState = {
|
||||
isTest: boolean;
|
||||
userDefinedApiUrl?: string; // from settings window
|
||||
};
|
||||
|
||||
export class ApiClient {
|
||||
private token: string
|
||||
private onUnauthorized: (error: string) => void
|
||||
private onError?: (error: string, type?: "error" | "warning") => void
|
||||
private requestCount = 0
|
||||
private maxRequests = 100
|
||||
private mode: AppMode
|
||||
private baseUrl: string
|
||||
private apiUrl: string
|
||||
|
||||
constructor(
|
||||
token: string,
|
||||
onUnauthorized: (reason?: string | "") => void,
|
||||
mode: AppMode = "PROD",
|
||||
baseUrl = "http://127.0.0.1:7070",
|
||||
onError?: (error: string, type?: "error" | "warning") => void,
|
||||
) {
|
||||
this.token = token
|
||||
this.onUnauthorized = onUnauthorized
|
||||
this.onError = onError
|
||||
this.mode = mode
|
||||
this.baseUrl = baseUrl
|
||||
}
|
||||
|
||||
private getApiBaseUrl(appMode: AppMode): string {
|
||||
if (appMode === "TEST") {
|
||||
// For debug mode, or non window sessions, pick port from env
|
||||
const port = process.env.MANTIS_PORT || 7070; // match your server default
|
||||
return `http://localhost:${port}`;
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
const { origin } = window.location;
|
||||
console.log("ORIGIN: ", origin)
|
||||
return `${origin}`;
|
||||
} else {
|
||||
const port = process.env.MANTIS_PORT || 7070; // match your server default
|
||||
return `http://localhost:${port}`;
|
||||
}
|
||||
}
|
||||
|
||||
private async realApiCall<T>(endpoint: string, options: RequestInit = {}): Promise<ApiResponse<T>> {
|
||||
try {
|
||||
const url = `${this.getApiBaseUrl(this.mode)}${endpoint}`
|
||||
const headers = {
|
||||
"Content-Type": "application/json",
|
||||
const url = `${getApiBaseUrl()}${endpoint}`
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
...options.headers,
|
||||
};
|
||||
|
||||
// only set content-type if body is not FormData
|
||||
if (!(options.body instanceof FormData)) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
}
|
||||
|
||||
const response = await fetch(url, {
|
||||
@@ -140,10 +138,29 @@ export class ApiClient {
|
||||
const responseData = await response.json()
|
||||
|
||||
// Ensure the structure always matches ApiResponse<T>
|
||||
// The API should always return { data: ..., status: ..., error: ... }
|
||||
// Handle both HTTP status and JSON body status
|
||||
const jsonStatus = responseData.status ?? response.status
|
||||
const jsonError = responseData.error ?? ""
|
||||
|
||||
// Extract data from response - should be an array for list endpoints
|
||||
let data = responseData.data
|
||||
|
||||
// If data is missing, check if the entire response is an array (fallback)
|
||||
if (data === undefined || data === null) {
|
||||
// If responseData itself is an array, use it
|
||||
if (Array.isArray(responseData)) {
|
||||
data = responseData as T
|
||||
} else {
|
||||
// Otherwise default based on expected type
|
||||
data = ({} as T)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
data: responseData.data ?? {},
|
||||
error: responseData.error ?? "",
|
||||
status: response.status,
|
||||
data: data,
|
||||
error: jsonError,
|
||||
status: jsonStatus,
|
||||
}
|
||||
} catch (error: any) {
|
||||
return {
|
||||
@@ -158,63 +175,90 @@ export class ApiClient {
|
||||
try {
|
||||
let response: ApiResponse<T> = await this.realApiCall<T>(endpoint, options)
|
||||
|
||||
// Unauthorized handling
|
||||
// Unauthorized handling - check both HTTP status and JSON status
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
this.onUnauthorized(response.error || "Unauthorized")
|
||||
throw new Error(response.error || "Unauthorized")
|
||||
}
|
||||
|
||||
// General error handling
|
||||
if (response.status >= 400 || response.status <= 0 || response.error) {
|
||||
this.onError?.(response.error || "Request failed", "error")
|
||||
throw new Error(response.error || "Request failed")
|
||||
// General error handling - check JSON status from API response
|
||||
// The API returns status in the JSON body: { data: [], status: 200, error: "" }
|
||||
// Only treat as error if status >= 400 or error string is non-empty
|
||||
if (response.status >= 400 || response.status <= 0) {
|
||||
const errorMsg = response.error && response.error.length > 0
|
||||
? response.error
|
||||
: "Request failed"
|
||||
if(errorMsg === "Failed to fetch") {
|
||||
const finalError = `Failed to fetch '${endpoint}'. Could not reach the server!`
|
||||
this.onError?.(finalError, "error")
|
||||
throw new Error(finalError)
|
||||
}
|
||||
this.onError?.(errorMsg, "error")
|
||||
throw new Error(errorMsg)
|
||||
}
|
||||
|
||||
// If there's an error message but status is OK, log it but don't throw
|
||||
if (response.error && response.error.length > 0) {
|
||||
console.warn(`API warning for ${endpoint}:`, response.error)
|
||||
}
|
||||
|
||||
// Return the data - should be an array for list endpoints
|
||||
return response.data
|
||||
} catch (error: any) {
|
||||
return {
|
||||
data: null as T,
|
||||
error: error.message || "Could not connect to the server!",
|
||||
status: 500, // could use 500 if you prefer
|
||||
} as T
|
||||
} as any
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Method to update mode
|
||||
updateMode(mode: AppMode, baseUrl?: string) {
|
||||
this.mode = mode
|
||||
if (baseUrl) {
|
||||
this.baseUrl = baseUrl
|
||||
}
|
||||
}
|
||||
export interface LoginResponse {
|
||||
token: string
|
||||
user: Admin
|
||||
}
|
||||
|
||||
export async function loginWithPassword(
|
||||
email: string,
|
||||
password: string,
|
||||
mode: AppMode = "PROD",
|
||||
baseUrl = "http://127.0.0.1:7070",
|
||||
) {
|
||||
// Real API call
|
||||
password: string
|
||||
): Promise<LoginResponse> {
|
||||
// Real API call to /api/v1/auth/login
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}/api/v1/admins/auth-with-password`, {
|
||||
const response = await fetch(`${getApiBaseUrl()}/api/v1/auth/login`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", },
|
||||
body: JSON.stringify({ email, password }),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
identity: email,
|
||||
password: password,
|
||||
entity: "mb_admins"
|
||||
}),
|
||||
})
|
||||
|
||||
const responseData = await response.json()
|
||||
// Handle non-JSON responses
|
||||
let responseData: any
|
||||
try {
|
||||
responseData = await response.json()
|
||||
} catch (jsonError) {
|
||||
throw new Error("Invalid response from server")
|
||||
}
|
||||
|
||||
if (response.ok) {
|
||||
// Check if response follows our API structure
|
||||
if (responseData.data) {
|
||||
return responseData.data
|
||||
// Handle response structure: { status, data: { token, user }, error }
|
||||
if (responseData.status === 200 && responseData.data && responseData.data.token) {
|
||||
return {
|
||||
token: responseData.data.token,
|
||||
user: responseData.data.user
|
||||
}
|
||||
return responseData
|
||||
} else {
|
||||
throw new Error(responseData.error || responseData.message || "Login failed")
|
||||
// Handle error response
|
||||
const errorMessage = responseData.error || responseData.message || "Login failed"
|
||||
throw new Error(errorMessage)
|
||||
}
|
||||
} catch (error: any) {
|
||||
// Re-throw if it's already an Error with a message
|
||||
if (error instanceof Error) {
|
||||
throw error
|
||||
}
|
||||
throw new Error(error.message || "Network error occurred")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,8 @@ export const dataTypes = [
|
||||
"uint32",
|
||||
"int64",
|
||||
"uint64",
|
||||
"blob",
|
||||
"json",
|
||||
"bool"
|
||||
"bool",
|
||||
"file",
|
||||
"files"
|
||||
]
|
||||
169
lib/router.ts
169
lib/router.ts
@@ -8,57 +8,136 @@ export interface RouteParams {
|
||||
|
||||
export interface ParsedRoute {
|
||||
path: string
|
||||
params: RouteParams
|
||||
pathParams: RouteParams
|
||||
queryParams: RouteParams
|
||||
}
|
||||
|
||||
// Use a custom event system instead of relying on hash changes
|
||||
// Use a custom event system for route changes
|
||||
const ROUTE_CHANGE_EVENT = "custom-route-change"
|
||||
|
||||
let currentRoute: ParsedRoute = { path: "/tables", params: {} }
|
||||
let currentRoute: ParsedRoute = { path: "/entities", pathParams: {}, queryParams: {} }
|
||||
|
||||
export function parseRoute(hash: string): ParsedRoute {
|
||||
// Get the base path for the application
|
||||
// In production, this should be '/mb-admin', in development it might be empty
|
||||
export function getBasePath(): string {
|
||||
if (typeof window === "undefined") {
|
||||
// Server-side: use env var or default to /mb-admin for production
|
||||
return process.env.NEXT_PUBLIC_BASE_PATH || (process.env.NODE_ENV === 'production' ? '/mb-admin' : '')
|
||||
}
|
||||
|
||||
// Client-side: try to detect base path from current location
|
||||
// If we're at /mb-admin/*, the base path is /mb-admin
|
||||
const pathname = window.location.pathname
|
||||
if (pathname.startsWith("/mb-admin")) {
|
||||
return "/mb-admin"
|
||||
}
|
||||
|
||||
// Fallback: check if we're in production mode
|
||||
// In development, base path might be empty
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
return process.env.NEXT_PUBLIC_BASE_PATH || "/mb-admin"
|
||||
}
|
||||
|
||||
// Development: no base path
|
||||
return process.env.NEXT_PUBLIC_BASE_PATH || ""
|
||||
}
|
||||
|
||||
// Strip base path from a full pathname
|
||||
function stripBasePath(pathname: string): string {
|
||||
const basePath = getBasePath()
|
||||
if (pathname.startsWith(basePath)) {
|
||||
return pathname.slice(basePath.length) || "/"
|
||||
}
|
||||
return pathname
|
||||
}
|
||||
|
||||
// Parse path params from route pattern (e.g., "/entities/:name" -> { name: "test" })
|
||||
function parsePathParams(pattern: string, path: string): RouteParams {
|
||||
const params: RouteParams = {}
|
||||
const patternParts = pattern.split("/")
|
||||
const pathParts = path.split("/")
|
||||
|
||||
if (patternParts.length !== pathParts.length) {
|
||||
return params
|
||||
}
|
||||
|
||||
for (let i = 0; i < patternParts.length; i++) {
|
||||
if (patternParts[i].startsWith(":")) {
|
||||
const paramName = patternParts[i].slice(1)
|
||||
params[paramName] = pathParts[i]
|
||||
}
|
||||
}
|
||||
|
||||
return params
|
||||
}
|
||||
|
||||
export function parseRoute(pathname: string, search: 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: {} }
|
||||
// Strip base path from the pathname first
|
||||
const pathWithoutBase = stripBasePath(pathname)
|
||||
|
||||
// Remove leading slash if present for consistency
|
||||
let cleanPath = pathWithoutBase.startsWith("/") ? pathWithoutBase : `/${pathWithoutBase}`
|
||||
|
||||
// Remove trailing slash for consistency
|
||||
if (cleanPath.endsWith("/") && cleanPath !== "/") {
|
||||
cleanPath = cleanPath.slice(0, -1)
|
||||
}
|
||||
|
||||
// Split path and query string
|
||||
const [pathPart, queryPart] = cleanHash.split("?")
|
||||
// If empty, default to /entities
|
||||
if (!cleanPath || cleanPath === "/") {
|
||||
return { path: "/entities", pathParams: {}, queryParams: {} }
|
||||
}
|
||||
|
||||
// Parse query parameters
|
||||
const params: RouteParams = {}
|
||||
if (queryPart) {
|
||||
// Parse query parameters from search string
|
||||
const queryParams: RouteParams = {}
|
||||
if (search) {
|
||||
try {
|
||||
const searchParams = new URLSearchParams(queryPart)
|
||||
const searchParams = new URLSearchParams(search.startsWith("?") ? search.slice(1) : search)
|
||||
for (const [key, value] of searchParams.entries()) {
|
||||
params[key] = value
|
||||
queryParams[key] = value
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Failed to parse query parameters:", error)
|
||||
}
|
||||
}
|
||||
|
||||
// Extract path params based on known route patterns
|
||||
const pathParams: RouteParams = {}
|
||||
|
||||
// Match /entities/:name pattern
|
||||
const entitiesMatch = cleanPath.match(/^\/entities\/([^/]+)$/)
|
||||
if (entitiesMatch) {
|
||||
pathParams.name = entitiesMatch[1]
|
||||
return { path: "/entities/:name", pathParams, queryParams }
|
||||
}
|
||||
|
||||
return {
|
||||
path: pathPart || "/tables",
|
||||
params,
|
||||
path: cleanPath,
|
||||
pathParams,
|
||||
queryParams,
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Failed to parse route:", error)
|
||||
return { path: "/tables", params: {} }
|
||||
return { path: "/entities", pathParams: {}, queryParams: {} }
|
||||
}
|
||||
}
|
||||
|
||||
export function buildRoute(path: string, params?: RouteParams): string {
|
||||
export function buildRoute(path: string, pathParams?: RouteParams, queryParams?: RouteParams): string {
|
||||
try {
|
||||
let route = path.startsWith("/") ? path : `/${path}`
|
||||
|
||||
if (params && Object.keys(params).length > 0) {
|
||||
// Replace path params (e.g., /entities/:name -> /entities/test)
|
||||
if (pathParams) {
|
||||
for (const [key, value] of Object.entries(pathParams)) {
|
||||
route = route.replace(`:${key}`, value)
|
||||
}
|
||||
}
|
||||
|
||||
// Add query parameters
|
||||
if (queryParams && Object.keys(queryParams).length > 0) {
|
||||
const searchParams = new URLSearchParams()
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
for (const [key, value] of Object.entries(queryParams)) {
|
||||
if (value) {
|
||||
searchParams.set(key, value)
|
||||
}
|
||||
@@ -69,10 +148,13 @@ export function buildRoute(path: string, params?: RouteParams): string {
|
||||
}
|
||||
}
|
||||
|
||||
return route
|
||||
// Prepend base path
|
||||
const basePath = getBasePath()
|
||||
return basePath + route
|
||||
} catch (error) {
|
||||
console.warn("Failed to build route:", error)
|
||||
return "/tables"
|
||||
const basePath = getBasePath()
|
||||
return basePath + "/entities"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,15 +168,15 @@ export function useRouter() {
|
||||
const [route, setRoute] = React.useState<ParsedRoute>(() => {
|
||||
if (typeof window !== "undefined") {
|
||||
try {
|
||||
const initialRoute = parseRoute(window.location.hash)
|
||||
const initialRoute = parseRoute(window.location.pathname, window.location.search)
|
||||
currentRoute = initialRoute
|
||||
return initialRoute
|
||||
} catch (error) {
|
||||
console.warn("Failed to get initial route:", error)
|
||||
return { path: "/tables", params: {} }
|
||||
return { path: "/entities", pathParams: {}, queryParams: {} }
|
||||
}
|
||||
}
|
||||
return { path: "/tables", params: {} }
|
||||
return { path: "/entities", pathParams: {}, queryParams: {} }
|
||||
})
|
||||
|
||||
React.useEffect(() => {
|
||||
@@ -108,19 +190,9 @@ export function useRouter() {
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
const newRoute = parseRoute(window.location.pathname, window.location.search)
|
||||
setRoute(newRoute)
|
||||
currentRoute = newRoute
|
||||
} catch (error) {
|
||||
@@ -130,29 +202,22 @@ export function useRouter() {
|
||||
|
||||
// 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) => {
|
||||
const navigate = React.useCallback((path: string, pathParams?: RouteParams, queryParams?: RouteParams) => {
|
||||
try {
|
||||
const routePath = buildRoute(path, params)
|
||||
const newRoute: ParsedRoute = { path: routePath, params: params || {} }
|
||||
const routePath = buildRoute(path, pathParams, queryParams)
|
||||
const newRoute = parseRoute(routePath.split("?")[0], routePath.includes("?") ? routePath.split("?")[1] : "")
|
||||
|
||||
// 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)
|
||||
// Update URL using pushState for clean paths
|
||||
if (window.location.pathname + window.location.search !== routePath) {
|
||||
window.history.pushState(null, "", routePath)
|
||||
}
|
||||
|
||||
// Dispatch our custom event
|
||||
|
||||
@@ -4,6 +4,8 @@ const { version } = require('./package.json');
|
||||
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
// Use basePath in production, or if explicitly set via env var
|
||||
basePath: process.env.NEXT_PUBLIC_BASE_PATH || (process.env.NODE_ENV === 'production' ? '/mb-admin' : ''),
|
||||
env: {
|
||||
MANTIS_ADMIN_VERSION: version,
|
||||
},
|
||||
@@ -16,10 +18,10 @@ const nextConfig = {
|
||||
images: {
|
||||
unoptimized: true,
|
||||
},
|
||||
output: 'export',
|
||||
trailingSlash: true, // ensures `/admin/index.html` works
|
||||
basePath: '/admin',
|
||||
assetPrefix: '/admin',
|
||||
// Only use static export in production builds, not in development
|
||||
// This allows dynamic routes to work in development
|
||||
...(process.env.NODE_ENV === 'production' && { output: 'export' }),
|
||||
trailingSlash: true,
|
||||
}
|
||||
|
||||
|
||||
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "mantis-admin",
|
||||
"version": "0.1.2",
|
||||
"version": "0.3.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "mantis-admin",
|
||||
"version": "0.1.2",
|
||||
"version": "0.3.0",
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^3.9.1",
|
||||
"@radix-ui/react-accordion": "1.2.2",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mantis-admin",
|
||||
"version": "0.1.4",
|
||||
"version": "0.3.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"export": "next build && next export",
|
||||
|
||||
BIN
public/favicon.ico
Normal file
BIN
public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 183 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 568 B |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="215" height="48" fill="none"><path fill="#000" d="M57.588 9.6h6L73.828 38h-5.2l-2.36-6.88h-11.36L52.548 38h-5.2l10.24-28.4Zm7.16 17.16-4.16-12.16-4.16 12.16h8.32Zm23.694-2.24c-.186-1.307-.706-2.32-1.56-3.04-.853-.72-1.866-1.08-3.04-1.08-1.68 0-2.986.613-3.92 1.84-.906 1.227-1.36 2.947-1.36 5.16s.454 3.933 1.36 5.16c.934 1.227 2.24 1.84 3.92 1.84 1.254 0 2.307-.373 3.16-1.12.854-.773 1.387-1.867 1.6-3.28l5.12.24c-.186 1.68-.733 3.147-1.64 4.4-.906 1.227-2.08 2.173-3.52 2.84-1.413.667-2.986 1-4.72 1-2.08 0-3.906-.453-5.48-1.36-1.546-.907-2.76-2.2-3.64-3.88-.853-1.68-1.28-3.627-1.28-5.84 0-2.24.427-4.187 1.28-5.84.88-1.68 2.094-2.973 3.64-3.88 1.574-.907 3.4-1.36 5.48-1.36 1.68 0 3.227.32 4.64.96 1.414.64 2.56 1.56 3.44 2.76.907 1.2 1.454 2.6 1.64 4.2l-5.12.28Zm11.486-7.72.12 3.4c.534-1.227 1.307-2.173 2.32-2.84 1.04-.693 2.267-1.04 3.68-1.04 1.494 0 2.76.387 3.8 1.16 1.067.747 1.827 1.813 2.28 3.2.507-1.44 1.294-2.52 2.36-3.24 1.094-.747 2.414-1.12 3.96-1.12 1.414 0 2.64.307 3.68.92s1.84 1.52 2.4 2.72c.56 1.2.84 2.667.84 4.4V38h-4.96V25.92c0-1.813-.293-3.187-.88-4.12-.56-.96-1.413-1.44-2.56-1.44-.906 0-1.68.213-2.32.64-.64.427-1.133 1.053-1.48 1.88-.32.827-.48 1.84-.48 3.04V38h-4.56V25.92c0-1.2-.133-2.213-.4-3.04-.24-.827-.626-1.453-1.16-1.88-.506-.427-1.133-.64-1.88-.64-.906 0-1.68.227-2.32.68-.64.427-1.133 1.053-1.48 1.88-.32.827-.48 1.827-.48 3V38h-4.96V16.8h4.48Zm26.723 10.6c0-2.24.427-4.187 1.28-5.84.854-1.68 2.067-2.973 3.64-3.88 1.574-.907 3.4-1.36 5.48-1.36 1.84 0 3.494.413 4.96 1.24 1.467.827 2.64 2.08 3.52 3.76.88 1.653 1.347 3.693 1.4 6.12v1.32h-15.08c.107 1.813.614 3.227 1.52 4.24.907.987 2.134 1.48 3.68 1.48.987 0 1.88-.253 2.68-.76a4.803 4.803 0 0 0 1.84-2.2l5.08.36c-.64 2.027-1.84 3.64-3.6 4.84-1.733 1.173-3.733 1.76-6 1.76-2.08 0-3.906-.453-5.48-1.36-1.573-.907-2.786-2.2-3.64-3.88-.853-1.68-1.28-3.627-1.28-5.84Zm15.16-2.04c-.213-1.733-.76-3.013-1.64-3.84-.853-.827-1.893-1.24-3.12-1.24-1.44 0-2.6.453-3.48 1.36-.88.88-1.44 2.12-1.68 3.72h9.92ZM163.139 9.6V38h-5.04V9.6h5.04Zm8.322 7.2.24 5.88-.64-.36c.32-2.053 1.094-3.56 2.32-4.52 1.254-.987 2.787-1.48 4.6-1.48 2.32 0 4.107.733 5.36 2.2 1.254 1.44 1.88 3.387 1.88 5.84V38h-4.96V25.92c0-1.253-.12-2.28-.36-3.08-.24-.8-.64-1.413-1.2-1.84-.533-.427-1.253-.64-2.16-.64-1.44 0-2.573.48-3.4 1.44-.8.933-1.2 2.307-1.2 4.12V38h-4.96V16.8h4.48Zm30.003 7.72c-.186-1.307-.706-2.32-1.56-3.04-.853-.72-1.866-1.08-3.04-1.08-1.68 0-2.986.613-3.92 1.84-.906 1.227-1.36 2.947-1.36 5.16s.454 3.933 1.36 5.16c.934 1.227 2.24 1.84 3.92 1.84 1.254 0 2.307-.373 3.16-1.12.854-.773 1.387-1.867 1.6-3.28l5.12.24c-.186 1.68-.733 3.147-1.64 4.4-.906 1.227-2.08 2.173-3.52 2.84-1.413.667-2.986 1-4.72 1-2.08 0-3.906-.453-5.48-1.36-1.546-.907-2.76-2.2-3.64-3.88-.853-1.68-1.28-3.627-1.28-5.84 0-2.24.427-4.187 1.28-5.84.88-1.68 2.094-2.973 3.64-3.88 1.574-.907 3.4-1.36 5.48-1.36 1.68 0 3.227.32 4.64.96 1.414.64 2.56 1.56 3.44 2.76.907 1.2 1.454 2.6 1.64 4.2l-5.12.28Zm11.443 8.16V38h-5.6v-5.32h5.6Z"/><path fill="#171717" fill-rule="evenodd" d="m7.839 40.783 16.03-28.054L20 6 0 40.783h7.839Zm8.214 0H40L27.99 19.894l-4.02 7.032 3.976 6.914H20.02l-3.967 6.943Z" clip-rule="evenodd"/></svg>
|
||||
|
Before Width: | Height: | Size: 3.1 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.6 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.0 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="1200" fill="none"><rect width="1200" height="1200" fill="#EAEAEA" rx="3"/><g opacity=".5"><g opacity=".5"><path fill="#FAFAFA" d="M600.709 736.5c-75.454 0-136.621-61.167-136.621-136.62 0-75.454 61.167-136.621 136.621-136.621 75.453 0 136.62 61.167 136.62 136.621 0 75.453-61.167 136.62-136.62 136.62Z"/><path stroke="#C9C9C9" stroke-width="2.418" d="M600.709 736.5c-75.454 0-136.621-61.167-136.621-136.62 0-75.454 61.167-136.621 136.621-136.621 75.453 0 136.62 61.167 136.62 136.621 0 75.453-61.167 136.62-136.62 136.62Z"/></g><path stroke="url(#a)" stroke-width="2.418" d="M0-1.209h553.581" transform="scale(1 -1) rotate(45 1163.11 91.165)"/><path stroke="url(#b)" stroke-width="2.418" d="M404.846 598.671h391.726"/><path stroke="url(#c)" stroke-width="2.418" d="M599.5 795.742V404.017"/><path stroke="url(#d)" stroke-width="2.418" d="m795.717 796.597-391.441-391.44"/><path fill="#fff" d="M600.709 656.704c-31.384 0-56.825-25.441-56.825-56.824 0-31.384 25.441-56.825 56.825-56.825 31.383 0 56.824 25.441 56.824 56.825 0 31.383-25.441 56.824-56.824 56.824Z"/><g clip-path="url(#e)"><path fill="#666" fill-rule="evenodd" d="M616.426 586.58h-31.434v16.176l3.553-3.554.531-.531h9.068l.074-.074 8.463-8.463h2.565l7.18 7.181V586.58Zm-15.715 14.654 3.698 3.699 1.283 1.282-2.565 2.565-1.282-1.283-5.2-5.199h-6.066l-5.514 5.514-.073.073v2.876a2.418 2.418 0 0 0 2.418 2.418h26.598a2.418 2.418 0 0 0 2.418-2.418v-8.317l-8.463-8.463-7.181 7.181-.071.072Zm-19.347 5.442v4.085a6.045 6.045 0 0 0 6.046 6.045h26.598a6.044 6.044 0 0 0 6.045-6.045v-7.108l1.356-1.355-1.282-1.283-.074-.073v-17.989h-38.689v23.43l-.146.146.146.147Z" clip-rule="evenodd"/></g><path stroke="#C9C9C9" stroke-width="2.418" d="M600.709 656.704c-31.384 0-56.825-25.441-56.825-56.824 0-31.384 25.441-56.825 56.825-56.825 31.383 0 56.824 25.441 56.824 56.825 0 31.383-25.441 56.824-56.824 56.824Z"/></g><defs><linearGradient id="a" x1="554.061" x2="-.48" y1=".083" y2=".087" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><linearGradient id="b" x1="796.912" x2="404.507" y1="599.963" y2="599.965" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><linearGradient id="c" x1="600.792" x2="600.794" y1="403.677" y2="796.082" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><linearGradient id="d" x1="404.85" x2="796.972" y1="403.903" y2="796.02" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><clipPath id="e"><path fill="#fff" d="M581.364 580.535h38.689v38.689h-38.689z"/></clipPath></defs></svg>
|
||||
|
Before Width: | Height: | Size: 3.2 KiB |
Reference in New Issue
Block a user