Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 67cee19b86 | |||
| 595a6d08f6 | |||
| 925da2ecff | |||
| 7dbb224642 | |||
| 437282b753 | |||
| 247236828a | |||
| c05a27ae0e | |||
| d924f2e8e5 | |||
| f8d006e845 | |||
| e361e7aea8 | |||
| 7b0c17fdb4 | |||
| 71a80d9f62 |
33
README.md
@@ -1,30 +1,5 @@
|
||||
# Admin dashboard requirements
|
||||
# Mantis Admin Dashboard
|
||||
This is the admin dashboard for [mantis](https://github.com/allankoechke/mantis), a BaaS written in C++.
|
||||
> Still in development, some features may be broken!
|
||||
|
||||
*Automatically synced with your [v0.dev](https://v0.dev) deployments*
|
||||
|
||||
[](https://vercel.com/allankoechke-1052s-projects/v0-admin-dashboard-requirements)
|
||||
[](https://v0.dev/chat/projects/ORViBtRL9uQ)
|
||||
|
||||
## Overview
|
||||
|
||||
This repository will stay in sync with your deployed chats on [v0.dev](https://v0.dev).
|
||||
Any changes you make to your deployed app will be automatically pushed to this repository from [v0.dev](https://v0.dev).
|
||||
|
||||
## Deployment
|
||||
|
||||
Your project is live at:
|
||||
|
||||
**[https://vercel.com/allankoechke-1052s-projects/v0-admin-dashboard-requirements](https://vercel.com/allankoechke-1052s-projects/v0-admin-dashboard-requirements)**
|
||||
|
||||
## Build your app
|
||||
|
||||
Continue building your app on:
|
||||
|
||||
**[https://v0.dev/chat/projects/ORViBtRL9uQ](https://v0.dev/chat/projects/ORViBtRL9uQ)**
|
||||
|
||||
## How It Works
|
||||
|
||||
1. Create and modify your project using [v0.dev](https://v0.dev)
|
||||
2. Deploy your chats from the v0 interface
|
||||
3. Changes are automatically pushed to this repository
|
||||
4. Vercel deploys the latest version from this repository
|
||||

|
||||
@@ -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>
|
||||
)
|
||||
|
||||
@@ -64,6 +64,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)
|
||||
@@ -76,13 +77,14 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
try {
|
||||
setAuthErrorReason(reason) // Set the auth error string
|
||||
setAuthErrorDialog(true) // Set the auth dialog to open
|
||||
handleLogout()
|
||||
} 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,38 +94,37 @@ 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 loadData = async () => {
|
||||
// Set default settings if loading fails
|
||||
setSettings({
|
||||
appName: "Mantis Admin",
|
||||
appName: "ACME Mantis Project",
|
||||
baseUrl: "http://127.0.0.1:7070",
|
||||
version: "1.2.3",
|
||||
mantisVersion: "0.0.0",
|
||||
maintenanceMode: false,
|
||||
maxFileSize: "10MB",
|
||||
maxFileSize: 10,
|
||||
allowRegistration: true,
|
||||
emailVerificationRequired: false,
|
||||
sessionTimeout: 3600,
|
||||
sessionTimeout: 84000,
|
||||
adminSessionTimeout: 3600,
|
||||
mode: mode,
|
||||
})
|
||||
|
||||
try {
|
||||
setLoading(true)
|
||||
|
||||
const [tablesData, adminsData/*, settingsData*/] = await Promise.all([
|
||||
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"),
|
||||
apiClient.call<AppSettings>("/api/v1/settings/config"),
|
||||
])
|
||||
|
||||
console.log("Data loaded:", { tablesData, adminsData/*, settingsData */ })
|
||||
|
||||
setTables(tablesData)
|
||||
setAdmins(adminsData)
|
||||
// setSettings(settingsData)
|
||||
setSettings(settingsData)
|
||||
} catch (error) {
|
||||
console.error("Failed to load data:", error)
|
||||
} finally {
|
||||
@@ -171,18 +172,18 @@ 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: "Logs",
|
||||
// icon: FileText,
|
||||
// id: "logs",
|
||||
// path: "/logs",
|
||||
// },
|
||||
// {
|
||||
// title: "Sync",
|
||||
// icon: RefreshCw,
|
||||
// id: "sync",
|
||||
// path: "/sync",
|
||||
// },
|
||||
{
|
||||
title: "Settings",
|
||||
icon: Settings,
|
||||
@@ -256,12 +257,15 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
<SidebarMenu>
|
||||
{settings && (
|
||||
<SidebarMenuItem>
|
||||
<div className="px-4 py-2 text-xs text-muted-foreground">Version {settings.version}</div>
|
||||
<div className="px-4 py-1 text-xs text-muted-foreground">Mantis Version {settings.mantisVersion}</div>
|
||||
</SidebarMenuItem>
|
||||
)}
|
||||
<SidebarMenuItem>
|
||||
<div className="px-4 py-1 text-xs text-muted-foreground">Mantis Admin Version {process.env.MANTIS_ADMIN_VERSION}</div>
|
||||
</SidebarMenuItem>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton asChild>
|
||||
<a href="https://docs.example.com" target="_blank" rel="noopener noreferrer">
|
||||
<a href="https://allankoechke.github.io/mantis" target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
<span>Documentation</span>
|
||||
</a>
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { MoreHorizontal, Key, Trash2 } from "lucide-react"
|
||||
import { MoreHorizontal, Key, Trash2, Plus, RefreshCw } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
import { Dialog } from "@/components/ui/dialog"
|
||||
import type { ApiClient, Admin } from "@/lib/api"
|
||||
import 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[]
|
||||
@@ -20,14 +22,129 @@ interface AdminsSectionProps {
|
||||
|
||||
export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSectionProps) {
|
||||
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",
|
||||
system: true,
|
||||
type: "auth",
|
||||
schema: {
|
||||
fields: [
|
||||
{
|
||||
autoGeneratePattern: null,
|
||||
defaultValue: null,
|
||||
maxValue: null,
|
||||
minValue: null,
|
||||
name: "id",
|
||||
primaryKey: true,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "string",
|
||||
unique: false,
|
||||
validator: null
|
||||
},
|
||||
{
|
||||
autoGeneratePattern: null,
|
||||
defaultValue: null,
|
||||
maxValue: null,
|
||||
minValue: 5.0,
|
||||
name: "email",
|
||||
primaryKey: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "string",
|
||||
unique: true,
|
||||
validator: "email"
|
||||
},
|
||||
{
|
||||
autoGeneratePattern: null,
|
||||
defaultValue: null,
|
||||
maxValue: null,
|
||||
minValue: 8.0,
|
||||
name: "password",
|
||||
primaryKey: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "string",
|
||||
unique: false,
|
||||
validator: "password"
|
||||
},
|
||||
{
|
||||
autoGeneratePattern: null,
|
||||
defaultValue: null,
|
||||
maxValue: null,
|
||||
minValue: 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
|
||||
}
|
||||
],
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteAdmin = async (adminId: string) => {
|
||||
try {
|
||||
await apiClient.call(`/api/v1/admins/${adminId}`, { method: "DELETE" })
|
||||
const res: any = await apiClient.call(`/api/v1/admins/${adminId}`, { method: "DELETE" })
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (res?.error?.length > 0) throw res.error
|
||||
|
||||
const updatedAdmins = await apiClient.call<Admin[]>("/api/v1/admins")
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (updatedAdmins?.error?.length > 0) throw updatedAdmins.error
|
||||
|
||||
onAdminsUpdate(updatedAdmins)
|
||||
|
||||
toast({
|
||||
title: "Admin Deleted",
|
||||
description: "Admin account deleted successfully!",
|
||||
duration: 3000,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to delete admin:", error)
|
||||
}
|
||||
}
|
||||
|
||||
const handleAdminAdded = (admin: Admin) => {
|
||||
onAdminsUpdate([...admins, admin])
|
||||
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Admin Added",
|
||||
description: "Admin account added successfully!",
|
||||
})
|
||||
}
|
||||
|
||||
const handleReload = async () => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
const updatedAdmins = await apiClient.call<Admin[]>("/api/v1/admins")
|
||||
onAdminsUpdate(updatedAdmins)
|
||||
} catch (error) {
|
||||
console.error("Failed to delete admin:", error)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +158,16 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
|
||||
<p className="text-muted-foreground">Manage administrator accounts</p>
|
||||
</div>
|
||||
</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 size="sm" onClick={() => setAddingAdmin(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Record
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
@@ -59,7 +186,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>
|
||||
@@ -95,6 +222,16 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
|
||||
<ChangePasswordDialog admin={selectedAdmin} apiClient={apiClient} onClose={() => setSelectedAdmin(null)} />
|
||||
)}
|
||||
</Dialog>
|
||||
|
||||
{addingAdmin && (
|
||||
<AddItemDrawer
|
||||
table={table}
|
||||
apiClient={apiClient}
|
||||
open={!!addingAdmin}
|
||||
onClose={() => setAddingAdmin(false)}
|
||||
onItemAdded={handleAdminAdded}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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/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,
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import type { ApiClient, TableMetadata } from "@/lib/api"
|
||||
import { Badge } from "../ui/badge"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
interface EditItemDrawerProps {
|
||||
table: TableMetadata
|
||||
@@ -32,6 +34,7 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [isViewType, setIsViewIsViewType] = React.useState(false)
|
||||
const [hasUnsavedChanges, setHasUnsavedChanges] = React.useState(false)
|
||||
const { toast } = useToast()
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
@@ -42,26 +45,123 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
|
||||
}
|
||||
}, [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 body = prepareRequestBody(formData, tableFields);
|
||||
console.log("Body: ", body)
|
||||
|
||||
const createdItem = await apiClient.call<any>(`/api/v1/${table.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 Record Created",
|
||||
description: `The record was created successfully.`,
|
||||
duration: 3000,
|
||||
})
|
||||
} 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)
|
||||
}
|
||||
@@ -81,6 +181,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]">
|
||||
@@ -97,9 +224,9 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
|
||||
<DrawerDescription>Create a new record in {table.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}
|
||||
@@ -113,25 +240,84 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
|
||||
updated
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{tableFields?.map((field: any) => (
|
||||
<div key={field.name} className="space-y-2">
|
||||
<Label htmlFor={field.name} className="text-sm font-medium capitalize">
|
||||
{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>
|
||||
))}
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import { Textarea } from "@/components/ui/textarea"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import type { ApiClient, TableMetadata, TableField } from "@/lib/api"
|
||||
import { dataTypes } from "@/lib/constants"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
interface AddTableDialogProps {
|
||||
apiClient: ApiClient
|
||||
@@ -44,11 +45,12 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
const [sqlQuery, setSqlQuery] = React.useState("")
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [open, setOpen] = React.useState(false)
|
||||
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
|
||||
React.useEffect(() => {
|
||||
if(open) {
|
||||
if (open) {
|
||||
// Reset all input fields to default values ...
|
||||
setTableName("");
|
||||
setSqlQuery("");
|
||||
@@ -146,19 +148,31 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
)
|
||||
}
|
||||
|
||||
await apiClient.call("/api/v1/tables", {
|
||||
const res: any = await apiClient.call("/api/v1/tables", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(tableData),
|
||||
})
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (res?.error?.length > 0) throw res.error
|
||||
|
||||
// Refresh tables list
|
||||
const updatedTables = await apiClient.call<TableMetadata[]>("/api/v1/tables")
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (updatedTables?.error?.length > 0) throw updatedTables.error
|
||||
|
||||
onTablesUpdate(updatedTables)
|
||||
|
||||
// Reset form
|
||||
setTableName("")
|
||||
setSqlQuery("")
|
||||
setOpen(false)
|
||||
|
||||
toast({
|
||||
title: "Table Updated",
|
||||
description: `The table '${tableData.name}' been updated successfully.`,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to create table:", error)
|
||||
} finally {
|
||||
@@ -170,7 +184,7 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{children || (
|
||||
<Button>
|
||||
<Button size="sm">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Table
|
||||
</Button>
|
||||
@@ -331,12 +345,12 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
</div>
|
||||
|
||||
<div className="text-sm text-muted-foreground mt-2">
|
||||
<p>
|
||||
<div>
|
||||
<Badge variant="outline" className="text-xs mr-2">
|
||||
System
|
||||
</Badge>
|
||||
System columns are automatically managed and cannot be modified.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Search, Table, Eye, Edit, Trash2, MoreHorizontal, RefreshCw, Plus, ExternalLink } from "lucide-react"
|
||||
import { Search, Table, Eye, Trash2, MoreHorizontal, RefreshCw, Plus, ExternalLink, FileText } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
@@ -12,7 +12,9 @@ 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"
|
||||
|
||||
interface DatabaseSectionProps {
|
||||
apiClient: ApiClient
|
||||
@@ -25,7 +27,9 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
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()
|
||||
const { toast } = useToast()
|
||||
|
||||
// Check if we're viewing a specific table - safer parsing
|
||||
const getSelectedTableName = () => {
|
||||
@@ -40,13 +44,29 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
|
||||
const selectedTableName = getSelectedTableName()
|
||||
|
||||
const filteredTables = tables?.filter((table) => table.name.toLowerCase().includes(searchTerm.toLowerCase()))
|
||||
const filteredTables = Array.isArray(tables) ? tables?.filter((table) => table.name.toLowerCase().includes(searchTerm.toLowerCase())) : []
|
||||
|
||||
const handleDeleteTable = async (tableId: string) => {
|
||||
try {
|
||||
await apiClient.call(`/api/v1/tables/${tableId}`, { method: "DELETE" })
|
||||
const res: any = await apiClient.call(`/api/v1/tables/${tableId}`, { method: "DELETE" })
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (res?.error?.length > 0) throw res.error
|
||||
|
||||
// Fetch new tables
|
||||
const updatedTables = await apiClient.call<TableMetadata[]>("/api/v1/tables")
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (updatedTables?.error?.length > 0) throw updatedTables.error
|
||||
|
||||
// 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)
|
||||
}
|
||||
@@ -64,6 +84,10 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
setIsRefreshing(true)
|
||||
try {
|
||||
const updatedTables = await apiClient.call<TableMetadata[]>("/api/v1/tables")
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (updatedTables?.error?.length > 0) throw updatedTables.error
|
||||
|
||||
onTablesUpdate(updatedTables)
|
||||
} catch (error) {
|
||||
console.error("Failed to refresh tables:", error)
|
||||
@@ -73,7 +97,7 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
}
|
||||
|
||||
if (selectedTableName) {
|
||||
const tableInfo = tables.find((t) => t.name === selectedTableName)
|
||||
const tableInfo = Array.isArray(tables) ? tables.find((t) => t.name === selectedTableName) : null
|
||||
if (tableInfo) {
|
||||
return (
|
||||
<TableDetailView
|
||||
@@ -122,6 +146,10 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
<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} />
|
||||
</div>
|
||||
</div>
|
||||
@@ -141,11 +169,9 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
Create Table
|
||||
</Button>
|
||||
</AddTableDialog>
|
||||
<Button variant="outline" asChild>
|
||||
<a href="https://docs.example.com/tables" target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
View Documentation
|
||||
</a>
|
||||
<Button variant="outline" onClick={() => setDocsOpen(true)}>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
View Documentation
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -220,6 +246,9 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Open docs on table CRUD */}
|
||||
<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,8 @@ 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 {
|
||||
table: TableMetadata
|
||||
@@ -26,29 +28,187 @@ 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.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)
|
||||
const [hasUnsavedChanges, setHasUnsavedChanges] = React.useState(false)
|
||||
const { toast } = useToast()
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open && item) {
|
||||
setFormData({ ...item })
|
||||
setHasUnsavedChanges(false)
|
||||
setTableFields(table.schema?.fields.filter(f => !isSystemGeneratedField(f)))
|
||||
setIsViewIsViewType(table?.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/${table.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 Record Updated",
|
||||
description: "Table record was updated successfully.",
|
||||
duration: 3000,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to update item:", error)
|
||||
} finally {
|
||||
@@ -56,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)
|
||||
}
|
||||
@@ -79,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,37 +330,81 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<ScrollArea className="h-full">
|
||||
<div className="p-6 space-y-6">
|
||||
{table.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.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>
|
||||
|
||||
@@ -22,6 +22,7 @@ import { Textarea } from "@/components/ui/textarea"
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
|
||||
import type { ApiClient, TableMetadata } from "@/lib/api"
|
||||
import { dataTypes } from "@/lib/constants"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
interface TableConfigDrawerProps {
|
||||
table: TableMetadata
|
||||
@@ -55,6 +56,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
const [hasUnsavedChanges, setHasUnsavedChanges] = React.useState(false)
|
||||
const [systemFieldsCollapsed, setSystemFieldsCollapsed] = React.useState(true)
|
||||
const [deletedColumns, setDeletedColumns] = React.useState([]) // Track deleted field names, we'll
|
||||
const { toast } = useToast()
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
@@ -76,7 +78,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
const column = columns[index]
|
||||
const isSystemColumn = column.system
|
||||
|
||||
if (!(columns.length > 1 && !isSystemColumn))
|
||||
if (!(columns.length > 1 && !isSystemColumn))
|
||||
return
|
||||
const col_name = column.name
|
||||
|
||||
@@ -90,7 +92,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
|
||||
const isAnExistingField = (index: number) => {
|
||||
const col_old_name = columns[index]?.old_name
|
||||
if(!col_old_name) return false;
|
||||
if (!col_old_name) return false;
|
||||
for (const f of table.schema.fields) {
|
||||
if (f.name === col_old_name) return true;
|
||||
}
|
||||
@@ -124,7 +126,16 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ fields: columns, deletedFields: deletedColumns }),
|
||||
})
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (updatedTable?.error?.length > 0) throw updatedTable.error
|
||||
|
||||
onTableUpdate(updatedTable)
|
||||
toast({
|
||||
title: "Table Updated",
|
||||
description: "Table fields updated successfully.",
|
||||
duration: 3000,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to update schema:", error)
|
||||
} finally {
|
||||
@@ -146,7 +157,16 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
deleteRule: rules.deleteRule,
|
||||
}),
|
||||
})
|
||||
|
||||
// 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 {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { RefreshCw, Cog, FileText, Trash2, Search, Plus, ExternalLink } from "lucide-react"
|
||||
import { RefreshCw, Cog, FileText, Trash2, Search, Plus } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
@@ -9,12 +9,13 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@
|
||||
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 { TableDocsDrawer } from "./table-docs-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"
|
||||
|
||||
interface TableDetailViewProps {
|
||||
table: TableMetadata
|
||||
@@ -40,6 +41,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
const [isDeleting, setIsDeleting] = React.useState(false)
|
||||
const [filterTerm, setFilterTerm] = React.useState("")
|
||||
const [appliedFilter, setAppliedFilter] = React.useState("")
|
||||
const { toast } = useToast()
|
||||
|
||||
React.useEffect(() => {
|
||||
loadTableData()
|
||||
@@ -58,6 +60,10 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
|
||||
try {
|
||||
const tableData = await apiClient.call<any>(`/api/v1/${table.name}`)
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (tableData?.error?.length > 0) throw tableData.error
|
||||
|
||||
setTableData(tableData)
|
||||
|
||||
// setTotalPages(3) // Mock pagination
|
||||
@@ -126,7 +132,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
try {
|
||||
// Delete each selected item individually
|
||||
const deletePromises = selectedItems.map((itemId) =>
|
||||
apiClient.call(`/api/v1/tables/${table.name}/${itemId}`, { method: "DELETE" }),
|
||||
apiClient.call(`/api/v1/${table.name}/${itemId}`, { method: "DELETE" }),
|
||||
)
|
||||
|
||||
await Promise.all(deletePromises)
|
||||
@@ -143,6 +149,66 @@ 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.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.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">
|
||||
@@ -161,7 +227,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
<RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
{!isViewType &&
|
||||
<Button onClick={handleAddItem} disabled={isLoading}>
|
||||
<Button size="sm" onClick={handleAddItem} disabled={isLoading}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Record
|
||||
</Button>
|
||||
@@ -290,7 +356,9 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
/>
|
||||
</TableCell>
|
||||
{filteredFields.map((field) => (
|
||||
<TableCell key={field.name}>{row[field.name] || "-"}</TableCell>
|
||||
<TableCell key={field.name}>
|
||||
{renderCellContent(field, row[field.name])}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
@@ -342,7 +410,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
onTableUpdate={onTableUpdate}
|
||||
/>
|
||||
|
||||
<TableDocsDrawer table={table} open={docsOpen} onClose={() => setDocsOpen(false)} />
|
||||
<TableRecordDocsDrawer table={table} open={docsOpen} onClose={() => setDocsOpen(false)} />
|
||||
|
||||
{addingItem && (
|
||||
<AddItemDrawer
|
||||
|
||||
@@ -11,13 +11,13 @@ import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import type { TableMetadata } from "@/lib/api"
|
||||
|
||||
interface TableDocsDrawerProps {
|
||||
table: TableMetadata
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
// Generate docs based on user defined tables
|
||||
export function TableDocsDrawer({ table, open, onClose }: TableDocsDrawerProps) {
|
||||
export function TableDocsDrawer({ open, onClose }: TableDocsDrawerProps) {
|
||||
const [table, setTable] = React.useState({})
|
||||
const handleClose = () => {
|
||||
onClose()
|
||||
}
|
||||
@@ -29,7 +29,7 @@ export function TableDocsDrawer({ table, open, onClose }: TableDocsDrawerProps)
|
||||
<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>Tables API Documentation</DrawerTitle>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={onClose}>
|
||||
<X className="h-4 w-4" />
|
||||
@@ -43,47 +43,43 @@ export function TableDocsDrawer({ table, open, onClose }: TableDocsDrawerProps)
|
||||
<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/tables`}
|
||||
description={`List all records in the tables table`}
|
||||
table={table}
|
||||
operation="list"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="GET"
|
||||
endpoint={`/api/v1/${table.name}/{id}`}
|
||||
endpoint={`/api/v1/tables/{id}`}
|
||||
description="Get a specific record by ID"
|
||||
table={table}
|
||||
operation="get"
|
||||
/>
|
||||
|
||||
{table.schema.type !== "view" && (
|
||||
<>
|
||||
<ApiEndpointCard
|
||||
method="POST"
|
||||
endpoint={`/api/v1/${table.name}`}
|
||||
description="Create a new record"
|
||||
table={table}
|
||||
operation="create"
|
||||
/>
|
||||
<ApiEndpointCard
|
||||
method="POST"
|
||||
endpoint={`/api/v1/tables`}
|
||||
description="Create a new record"
|
||||
table={table}
|
||||
operation="create"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="PATCH"
|
||||
endpoint={`/api/v1/${table.name}/{id}`}
|
||||
description="Update a specific record"
|
||||
table={table}
|
||||
operation="update"
|
||||
/>
|
||||
<ApiEndpointCard
|
||||
method="PATCH"
|
||||
endpoint={`/api/v1/tables/{id}`}
|
||||
description="Update a specific record"
|
||||
table={table}
|
||||
operation="update"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="DELETE"
|
||||
endpoint={`/api/v1/${table.name}/{id}`}
|
||||
description="Delete a specific record"
|
||||
table={table}
|
||||
operation="delete"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<ApiEndpointCard
|
||||
method="DELETE"
|
||||
endpoint={`/api/v1/tables/{id}`}
|
||||
description="Delete a specific record"
|
||||
table={table}
|
||||
operation="delete"
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
@@ -138,7 +134,7 @@ function ApiEndpointCard({
|
||||
|
||||
if (operation === "create" || operation === "update") {
|
||||
const sampleData: any = {}
|
||||
table.schema.fields?.forEach((field) => {
|
||||
table?.schema?.fields?.forEach((field) => {
|
||||
if (field.name === "id" || field.name === "created" || field.name === "updated") return
|
||||
if (field.name === "email") {
|
||||
sampleData[field.name] = "user@example.com"
|
||||
@@ -158,7 +154,7 @@ function ApiEndpointCard({
|
||||
const generateResponseExample = () => {
|
||||
if (operation === "list") {
|
||||
const sampleRecord: any = {}
|
||||
table.schema.fields?.forEach((field) => {
|
||||
table?.schema?.fields?.forEach((field) => {
|
||||
if (field.name === "id") {
|
||||
sampleRecord[field.name] = "123e4567-e89b-12d3-a456-426614174000"
|
||||
} else if (field.name === "created" || field.name === "updated") {
|
||||
@@ -188,12 +184,12 @@ function ApiEndpointCard({
|
||||
}
|
||||
|
||||
if (operation === "delete") {
|
||||
return JSON.stringify({ success: true }, null, 2)
|
||||
return JSON.stringify({}, null, 2)
|
||||
}
|
||||
|
||||
// Single record response
|
||||
const sampleRecord: any = {}
|
||||
table.schema.fields?.forEach((field) => {
|
||||
table?.schema?.fields?.forEach((field) => {
|
||||
if (field.name === "id") {
|
||||
sampleRecord[field.name] = "123e4567-e89b-12d3-a456-426614174000"
|
||||
} else if (field.name === "created" || field.name === "updated") {
|
||||
|
||||
305
components/database/table-records-docs-drawer.tsx
Normal file
@@ -0,0 +1,305 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { FileText, ChevronDown, ChevronRight, X, Copy } from "lucide-react"
|
||||
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from "@/components/ui/drawer"
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import type { TableMetadata } from "@/lib/api"
|
||||
|
||||
interface TableDocsDrawerProps {
|
||||
table: TableMetadata
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
// Generate docs based on user defined tables
|
||||
export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerProps) {
|
||||
const handleClose = () => {
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<Drawer open={open} onOpenChange={handleClose}>
|
||||
<DrawerContent side="right" className="w-[1000px] max-w-[95vw]">
|
||||
<DrawerHeader>
|
||||
<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>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={onClose}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<DrawerDescription>Auto-generated API endpoints and examples</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<ScrollArea className="h-full">
|
||||
<div className="p-6 space-y-6">
|
||||
<ApiEndpointCard
|
||||
method="GET"
|
||||
endpoint={`/api/v1/${table.name}`}
|
||||
description={`List all records in the ${table.name} table`}
|
||||
table={table}
|
||||
operation="list"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="GET"
|
||||
endpoint={`/api/v1/${table.name}/{id}`}
|
||||
description="Get a specific record by ID"
|
||||
table={table}
|
||||
operation="get"
|
||||
/>
|
||||
|
||||
{table.schema.type !== "view" && (
|
||||
<>
|
||||
<ApiEndpointCard
|
||||
method="POST"
|
||||
endpoint={`/api/v1/${table.name}`}
|
||||
description="Create a new record"
|
||||
table={table}
|
||||
operation="create"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="PATCH"
|
||||
endpoint={`/api/v1/${table.name}/{id}`}
|
||||
description="Update a specific record"
|
||||
table={table}
|
||||
operation="update"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="DELETE"
|
||||
endpoint={`/api/v1/${table.name}/{id}`}
|
||||
description="Delete a specific record"
|
||||
table={table}
|
||||
operation="delete"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
function ApiEndpointCard({
|
||||
method,
|
||||
endpoint,
|
||||
description,
|
||||
table,
|
||||
operation,
|
||||
}: {
|
||||
method: string
|
||||
endpoint: string
|
||||
description: string
|
||||
table: TableMetadata
|
||||
operation: string
|
||||
}) {
|
||||
const [isOpen, setIsOpen] = React.useState(false)
|
||||
|
||||
const getMethodColor = (method: string) => {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
return "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"
|
||||
case "POST":
|
||||
return "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"
|
||||
case "PATCH":
|
||||
return "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200"
|
||||
case "DELETE":
|
||||
return "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"
|
||||
default:
|
||||
return "bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200"
|
||||
}
|
||||
}
|
||||
|
||||
const copyToClipboard = (text: string) => {
|
||||
navigator.clipboard.writeText(text)
|
||||
}
|
||||
|
||||
const generateRequestExample = () => {
|
||||
const baseUrl = "https://your-api.com"
|
||||
let example = `curl -X ${method} "${baseUrl}${endpoint}"`
|
||||
|
||||
if (method !== "GET") {
|
||||
example += ` \\\n -H "Content-Type: application/json"`
|
||||
}
|
||||
|
||||
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}`
|
||||
}
|
||||
})
|
||||
|
||||
example += ` \\\n -d '${JSON.stringify(sampleData, null, 2)}'`
|
||||
}
|
||||
|
||||
return example
|
||||
}
|
||||
|
||||
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}`
|
||||
}
|
||||
})
|
||||
|
||||
return JSON.stringify(
|
||||
{
|
||||
data: [sampleRecord],
|
||||
pagination: {
|
||||
page: 1,
|
||||
limit: 20,
|
||||
total: 1,
|
||||
pages: 1,
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)
|
||||
}
|
||||
|
||||
if (operation === "delete") {
|
||||
return JSON.stringify({ success: true }, null, 2)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
const requestExample = generateRequestExample()
|
||||
const responseExample = generateResponseExample()
|
||||
|
||||
return (
|
||||
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<div className="p-4 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge className={getMethodColor(method)} variant="secondary">
|
||||
{method}
|
||||
</Badge>
|
||||
<code className="text-sm font-mono bg-muted px-2 py-1 rounded">{endpoint}</code>
|
||||
{isOpen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-2">{description}</p>
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="border-l-2 border-muted ml-4 pl-6 space-y-6 mt-4">
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h5 className="font-medium">Request Example</h5>
|
||||
<Button variant="outline" size="sm" onClick={() => copyToClipboard(requestExample)} className="h-8">
|
||||
<Copy className="h-3 w-3 mr-1" />
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-48">
|
||||
<pre className="bg-muted p-4 rounded text-sm border">
|
||||
<code>{requestExample}</code>
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h5 className="font-medium">Response Example</h5>
|
||||
<Button variant="outline" size="sm" onClick={() => copyToClipboard(responseExample)} className="h-8">
|
||||
<Copy className="h-3 w-3 mr-1" />
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-48">
|
||||
<pre className="bg-muted p-4 rounded text-sm border">
|
||||
<code>{responseExample}</code>
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h5 className="font-medium mb-3">Possible Errors</h5>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<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>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
403
|
||||
</Badge>
|
||||
<span>Forbidden - Access denied by rules</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>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
500
|
||||
</Badge>
|
||||
<span>Internal Server Error - Server error</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)
|
||||
}
|
||||
@@ -16,8 +16,8 @@ interface LoginFormProps {
|
||||
}
|
||||
|
||||
export function LoginForm({ onLogin }: LoginFormProps) {
|
||||
const [email, setEmail] = React.useState("admin@example.com")
|
||||
const [password, setPassword] = React.useState("password")
|
||||
const [email, setEmail] = React.useState("")
|
||||
const [password, setPassword] = React.useState("")
|
||||
const [showPassword, setShowPassword] = React.useState(false)
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [error, setError] = React.useState("")
|
||||
@@ -96,12 +96,6 @@ export function LoginForm({ onLogin }: LoginFormProps) {
|
||||
{isLoading ? "Signing in..." : "Sign In"}
|
||||
</Button>
|
||||
|
||||
<div className="text-sm text-muted-foreground text-center">
|
||||
<p>Demo credentials:</p>
|
||||
<p>Email: admin@example.com</p>
|
||||
<p>Password: password</p>
|
||||
<p className="mt-2 text-xs">Mode: {mode}</p>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -30,7 +30,6 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
|
||||
React.useEffect(() => {
|
||||
if (settings) {
|
||||
console.log("Settings received:", settings)
|
||||
setFormData({ ...settings, mode })
|
||||
setHasChanges(false)
|
||||
}
|
||||
@@ -63,16 +62,21 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const updatedSettings = await apiClient.call<AppSettings>("/api/v1/settings", {
|
||||
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
|
||||
|
||||
onSettingsUpdate(updatedSettings)
|
||||
setHasChanges(false)
|
||||
|
||||
toast({
|
||||
title: "Settings Saved",
|
||||
description: "Application settings have been updated successfully.",
|
||||
duration: 3000,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to update settings:", error)
|
||||
@@ -84,7 +88,11 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
const handleRefresh = async () => {
|
||||
setIsRefreshing(true)
|
||||
try {
|
||||
const updatedSettings = await apiClient.call<AppSettings>("/api/v1/settings")
|
||||
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)
|
||||
@@ -126,72 +134,6 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Environment Mode Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Environment Mode</CardTitle>
|
||||
<CardDescription>Switch between test mode (mock data) and production mode (real API calls)</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<Card
|
||||
className={`cursor-pointer transition-all ${mode === "TEST" ? "ring-2 ring-primary" : "hover:bg-muted/50"}`}
|
||||
onClick={() => handleModeToggle("TEST")}
|
||||
>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<TestTube className="h-5 w-5 text-blue-600" />
|
||||
<div>
|
||||
<h4 className="font-medium">Test Mode</h4>
|
||||
<p className="text-sm text-muted-foreground">Uses mock data for development</p>
|
||||
</div>
|
||||
{mode === "TEST" && (
|
||||
<Badge variant="default" className="ml-auto">
|
||||
Active
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
className={`cursor-pointer transition-all ${mode === "PROD" ? "ring-2 ring-primary" : "hover:bg-muted/50"}`}
|
||||
onClick={() => handleModeToggle("PROD")}
|
||||
>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<Globe className="h-5 w-5 text-green-600" />
|
||||
<div>
|
||||
<h4 className="font-medium">Production Mode</h4>
|
||||
<p className="text-sm text-muted-foreground">Makes real API calls</p>
|
||||
</div>
|
||||
{mode === "PROD" && (
|
||||
<Badge variant="default" className="ml-auto">
|
||||
Active
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{mode === "PROD" && (
|
||||
<div className="p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
|
||||
<div className="flex items-start gap-2">
|
||||
<Globe className="h-4 w-4 text-yellow-600 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-yellow-800 dark:text-yellow-200">Production Mode Active</p>
|
||||
<p className="text-sm text-yellow-700 dark:text-yellow-300">
|
||||
All API calls will be made to the configured base URL. Ensure your API server is running and
|
||||
accessible.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>General Settings</CardTitle>
|
||||
@@ -211,8 +153,8 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
<Label htmlFor="version">Version</Label>
|
||||
<Input
|
||||
id="version"
|
||||
value={formData?.version || ""}
|
||||
onChange={(e) => handleInputChange("version", e.target.value)}
|
||||
value={formData?.mantisVersion || ""}
|
||||
disabled={true}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -233,12 +175,13 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="max-file-size">Max File Size</Label>
|
||||
<Label htmlFor="max-file-size">Max File Size (MB)</Label>
|
||||
<Input
|
||||
id="max-file-size"
|
||||
value={formData?.maxFileSize || ""}
|
||||
onChange={(e) => handleInputChange("maxFileSize", e.target.value)}
|
||||
placeholder="10MB"
|
||||
type="number"
|
||||
value={formData?.maxFileSize?.toString() || 10}
|
||||
onChange={(e) => handleInputChange("maxFileSize", Number.parseInt(e.target.value) || 10)}
|
||||
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
@@ -246,8 +189,17 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
<Input
|
||||
id="session-timeout"
|
||||
type="number"
|
||||
value={formData?.sessionTimeout || 3600}
|
||||
onChange={(e) => handleInputChange("sessionTimeout", Number.parseInt(e.target.value) || 3600)}
|
||||
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>
|
||||
@@ -289,95 +241,73 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Notification Test Section */}
|
||||
{/* Environment Mode Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Notification Testing</CardTitle>
|
||||
<CardDescription>Test different types of notifications and error messages</CardDescription>
|
||||
<CardTitle>Environment Mode</CardTitle>
|
||||
<CardDescription>Switch between test mode (cors supported) and production mode (real API calls)</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={() => {
|
||||
toast({
|
||||
title: "Info",
|
||||
description: "This is a test info message. Everything is working correctly!",
|
||||
})
|
||||
}}
|
||||
className="w-full"
|
||||
<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")}
|
||||
>
|
||||
Test Info
|
||||
</Button>
|
||||
<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>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
toast({
|
||||
title: "Warning",
|
||||
description: "This is a test warning message. Please pay attention to this.",
|
||||
variant: "default",
|
||||
})
|
||||
}}
|
||||
className="w-full"
|
||||
<Card
|
||||
className={`cursor-pointer transition-all ${mode === "PROD" ? "ring-2 ring-primary" : "hover:bg-muted/50"}`}
|
||||
onClick={() => handleModeToggle("PROD")}
|
||||
>
|
||||
Test Warning
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "This is a test error message. Something went wrong!",
|
||||
})
|
||||
}}
|
||||
className="w-full"
|
||||
>
|
||||
Test Error
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Authentication Error",
|
||||
description: "Your session has expired. Please log in again.",
|
||||
action: (
|
||||
<Button variant="outline" size="sm">
|
||||
Login
|
||||
</Button>
|
||||
),
|
||||
})
|
||||
}}
|
||||
className="w-full"
|
||||
>
|
||||
Test Auth Toast
|
||||
</Button>
|
||||
<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>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 text-sm text-muted-foreground">
|
||||
<p>Use these buttons to test different notification types:</p>
|
||||
<ul className="list-disc list-inside mt-2 space-y-1">
|
||||
<li>
|
||||
<strong>Info:</strong> General information messages
|
||||
</li>
|
||||
<li>
|
||||
<strong>Warning:</strong> Warning notifications
|
||||
</li>
|
||||
<li>
|
||||
<strong>Error:</strong> Error toast notifications
|
||||
</li>
|
||||
<li>
|
||||
<strong>Auth Error:</strong> Authentication error dialog
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
{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.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
|
||||
88
lib/api.ts
@@ -2,6 +2,7 @@
|
||||
|
||||
import type { AppMode } from "./app-state"
|
||||
|
||||
|
||||
// Updated interfaces to match the API response format
|
||||
export interface TableField {
|
||||
autoGeneratePattern: string | null
|
||||
@@ -50,29 +51,36 @@ export interface Admin {
|
||||
updated: string
|
||||
}
|
||||
|
||||
export interface AppSettings {
|
||||
appName: string
|
||||
baseUrl: string
|
||||
version: string
|
||||
maintenanceMode: boolean
|
||||
maxFileSize: string
|
||||
allowRegistration: boolean
|
||||
emailVerificationRequired: boolean
|
||||
sessionTimeout: number
|
||||
mode: AppMode
|
||||
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}`;
|
||||
}
|
||||
|
||||
// const mockSettings = {
|
||||
// appName: "Mantis Admin",
|
||||
// baseUrl: "https://api.example.com",
|
||||
// version: "1.2.3",
|
||||
// maintenanceMode: false,
|
||||
// maxFileSize: "10MB",
|
||||
// allowRegistration: true,
|
||||
// emailVerificationRequired: false,
|
||||
// sessionTimeout: 3600,
|
||||
// mode: "TEST" as AppMode,
|
||||
// }
|
||||
export interface AppSettings {
|
||||
allowRegistration: boolean
|
||||
appName: string
|
||||
baseUrl: string
|
||||
emailVerificationRequired: boolean
|
||||
maintenanceMode: boolean
|
||||
maxFileSize: Number
|
||||
mode: AppMode
|
||||
sessionTimeout: Number
|
||||
adminSessionTimeout: Number
|
||||
mantisVersion: string
|
||||
}
|
||||
|
||||
// API Response interface
|
||||
interface ApiResponse<T> {
|
||||
@@ -85,32 +93,27 @@ 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
|
||||
|
||||
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 async realApiCall<T>(endpoint: string, options: RequestInit = {}): Promise<ApiResponse<T>> {
|
||||
try {
|
||||
const url = `${this.baseUrl}${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, {
|
||||
@@ -152,6 +155,7 @@ export class ApiClient {
|
||||
|
||||
// General error handling
|
||||
if (response.status >= 400 || response.status <= 0 || response.error) {
|
||||
if(response.error === "Failed to fetch") response.error = `Failed to fetch '${endpoint}'. Could not reach the server!`
|
||||
this.onError?.(response.error || "Request failed", "error")
|
||||
throw new Error(response.error || "Request failed")
|
||||
}
|
||||
@@ -162,28 +166,18 @@ export class ApiClient {
|
||||
data: null as T,
|
||||
error: error.message || "Could not connect to the server!",
|
||||
status: 500, // could use 500 if you prefer
|
||||
} as T
|
||||
}
|
||||
}
|
||||
|
||||
// Method to update mode
|
||||
updateMode(mode: AppMode, baseUrl?: string) {
|
||||
this.mode = mode
|
||||
if (baseUrl) {
|
||||
this.baseUrl = baseUrl
|
||||
} as any
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function loginWithPassword(
|
||||
email: string,
|
||||
password: string,
|
||||
mode: AppMode = "PROD",
|
||||
baseUrl = "http://127.0.0.1:7070",
|
||||
password: string
|
||||
) {
|
||||
// Real API call
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}/api/v1/admins/auth-with-password`, {
|
||||
const response = await fetch(`${getApiBaseUrl()}/api/v1/admins/auth-with-password`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", },
|
||||
body: JSON.stringify({ email, password }),
|
||||
@@ -196,7 +190,7 @@ export async function loginWithPassword(
|
||||
if (responseData.data) {
|
||||
return responseData.data
|
||||
}
|
||||
return responseData
|
||||
return responseData.data
|
||||
} else {
|
||||
throw new Error(responseData.error || responseData.message || "Login failed")
|
||||
}
|
||||
|
||||
@@ -17,7 +17,8 @@ export const dataTypes = [
|
||||
"uint32",
|
||||
"int64",
|
||||
"uint64",
|
||||
"blob",
|
||||
"json",
|
||||
"bool"
|
||||
"bool",
|
||||
"file",
|
||||
"files"
|
||||
]
|
||||
@@ -1,5 +1,12 @@
|
||||
import { createRequire } from 'module';
|
||||
const require = createRequire(import.meta.url);
|
||||
const { version } = require('./package.json');
|
||||
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
env: {
|
||||
MANTIS_ADMIN_VERSION: version,
|
||||
},
|
||||
eslint: {
|
||||
ignoreDuringBuilds: true,
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mantis-admin",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.7",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"export": "next build && next export",
|
||||
|
||||
BIN
public/favicon.ico
Normal file
|
After Width: | Height: | Size: 183 KiB |
|
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 |
|
Before Width: | Height: | Size: 1.6 KiB |
|
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 |
BIN
screenshot.png
Normal file
|
After Width: | Height: | Size: 123 KiB |