10 Commits

14 changed files with 1204 additions and 263 deletions

187
README.md
View File

@@ -1,5 +1,186 @@
# MantisBase Admin Dashboard
This is the admin dashboard for [mantis](https://github.com/allankoechke/mantisbase), a BaaS written in C++.
> Still in development, some features may be broken!
![](screenshot.png)
A modern, web-based admin dashboard for managing your MantisBase backend. This dashboard provides an intuitive interface for managing entities, admins, settings, and more.
![MantisBase Admin Dashboard](mantisbase-admin.png)
## 📋 Table of Contents
- [About](#about)
- [Getting Started](#getting-started)
- [Development](#development)
- [Building for Production](#building-for-production)
- [Integration with MantisBase](#integration-with-mantisbase)
- [Features](#features)
- [Links](#links)
## 🎯 About
MantisBase Admin Dashboard is the official administrative interface for [MantisBase](https://github.com/allankoechke/mantisbase), a lightweight Backend-as-a-Service (BaaS) written in C++. This dashboard allows you to:
- Manage database entities and their schemas
- Configure access rules and permissions
- Manage admin users
- View application logs
- Configure application settings
- And much more!
## 🚀 Getting Started
### Prerequisites
Before you begin, ensure you have the following installed:
- **Node.js** (version 20 or higher)
- **npm** (comes with Node.js)
- A running **MantisBase** server instance
### Installation
1. **Clone the repository**
```bash
git clone https://github.com/allankoechke/mantisbase-admin.git
cd mantis-admin
```
2. **Install dependencies**
```bash
npm install
```
3. **Start the development server**
```bash
npm run dev
```
4. **Open your browser**
Navigate to `http://localhost:3000` (or the port shown in your terminal)
### First Login
1. If this is your first time setting up MantisBase, you'll need to create an admin account:
- Navigate to `/mb/setup?token=YOUR_SETUP_TOKEN`
- Enter your email and password
- You'll be redirected to the login page
2. Log in with your admin credentials at `/mb/login`
## 💻 Development
### Available Scripts
- `npm run dev` - Start the development server with hot-reload
- `npm run build` - Build the application for production
- `npm run lint` - Run ESLint to check code quality
- `npm start` - Start the production server (requires build first)
### Development Mode
In development mode, the dashboard will:
- Connect to `http://localhost:7070` by default (or the port specified in `MANTIS_PORT` environment variable)
- Enable hot module replacement for faster development
- Show detailed error messages
### Environment Variables
You can customize the development setup using environment variables:
- `MANTIS_PORT` - Port for the MantisBase API (default: 7070)
- `NEXT_PUBLIC_BASE_PATH` - Base path for the application (default: `/mb` in production)
## 🏗️ Building for Production
To build the dashboard for production:
```bash
npm run build
```
The built static files will be in the `out/` directory. These files can be served by any static file server.
### Static Export
The dashboard is configured for static export, making it easy to deploy to:
- GitHub Pages
- Netlify
- Vercel
- Any static hosting service
## 🔗 Integration with MantisBase
### The `mb-admins` Branch
This repository includes a special branch called `mb-admins` that is automatically integrated with the main [MantisBase project](https://github.com/allankoechke/mantisbase) via CMake.
**Important Notes:**
- The `mb-admins` branch contains the built static files of the admin dashboard
- This branch is **automatically updated** on every release
- The MantisBase CMake build system uses this branch to include the admin interface
- When you build MantisBase, it automatically fetches the latest admin dashboard from this branch
### How It Works
1. When a new version is released (tagged with `v*`), a GitHub Action automatically:
- Builds the admin dashboard
- Updates the `mb-admins` branch with the latest static files
- Creates a GitHub release with downloadable assets
2. The MantisBase CMake configuration:
- Clones or updates the `mb-admins` branch during build
- Includes the admin dashboard files in the MantisBase build
- Serves the admin interface at `/mb/*` when MantisBase is running
This integration ensures that MantisBase always includes the latest stable version of the admin dashboard without requiring manual updates.
## ✨ Features
### Entity Management
- Create, read, update, and delete database entities
- Configure entity schemas with custom fields
- Set up access rules (list, get, add, update, delete)
- View and manage entity records
### Admin Management
- Create and manage admin user accounts
- Change admin passwords
- View admin activity
### Settings
- Configure application settings
- Manage file upload limits
- Configure session timeouts
- Enable/disable features
### Logs
- View application logs
- Filter and search logs
- Monitor system activity
### Modern UI
- Dark/light theme support
- Responsive design
- Intuitive navigation
- Real-time updates
## 🔗 Links
- **Main MantisBase Project**: [https://github.com/allankoechke/mantisbase](https://github.com/allankoechke/mantisbase)
- **Documentation**: [https://docs.mantisbase.com](https://docs.mantisbase.com)
- **This Repository**: [https://github.com/allankoechke/mantisbase-admin](https://github.com/allankoechke/mantisbase-admin)
## 📝 Notes
> **Note**: This project is still in active development. Some features may be incomplete or subject to change.
## 🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## 📄 License
This project is part of the MantisBase ecosystem. Please refer to the main MantisBase repository for license information.
---
**Made with ❤️ for the MantisBase community**

View File

@@ -16,7 +16,8 @@ import {
DrawerTitle,
} from "@/components/ui/drawer"
import { ScrollArea } from "@/components/ui/scroll-area"
import type { ApiClient, TableMetadata } from "@/lib/api"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import type { ApiClient, TableMetadata, TableField } from "@/lib/api"
import { Badge } from "../ui/badge"
import { useToast } from "@/hooks/use-toast"
@@ -34,16 +35,55 @@ 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 [fkRecords, setFkRecords] = React.useState<Record<string, any[]>>({}) // Store FK records by field name
const { toast } = useToast()
// Fetch records for foreign key fields
const fetchForeignKeyRecords = React.useCallback(async (field: TableField) => {
if (!field.foreign_key?.entity) return
try {
const response = await apiClient.call<any>(`/api/v1/entities/${field.foreign_key.entity}`)
// Handle paginated response
let records: any[] = []
if (Array.isArray(response)) {
records = response
} else if (response?.items && Array.isArray(response.items)) {
records = response.items
} else if (response?.data?.items && Array.isArray(response.data.items)) {
records = response.data.items
}
setFkRecords(prev => ({
...prev,
[field.name]: records
}))
} catch (error) {
console.error(`Failed to fetch records for FK field ${field.name}:`, error)
setFkRecords(prev => ({
...prev,
[field.name]: []
}))
}
}, [apiClient])
React.useEffect(() => {
if (open) {
setFormData({})
setHasUnsavedChanges(false)
setTableFields(table.schema?.fields.filter(f => !isSystemGeneratedField(f)))
const fields = table.schema?.fields.filter(f => !isSystemGeneratedField(f)) || []
setTableFields(fields)
setIsViewIsViewType(table?.schema.type === "view")
// Fetch records for all foreign key fields
fields.forEach((field: any) => {
if (field.foreign_key?.entity) {
fetchForeignKeyRecords(field)
}
})
}
}, [open])
}, [open, table, fetchForeignKeyRecords])
const prepareRequestBody = (data: Record<string, any>, tableFields: TableField[]): FormData | string => {
const hasFileField = tableFields.some(f => ["file", "files"].includes(f.type));
@@ -107,6 +147,11 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
const field = tableFields?.find((f: any) => f.name === fieldName);
if (!field) return value;
// For foreign key fields, return the value as-is (id string or null)
if (field.foreign_key && field.foreign_key.entity && field.foreign_key.field) {
return value === "null" ? null : value;
}
const type = field.type;
try {
@@ -239,13 +284,43 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
</Badge>
</div>
{tableFields?.map((field: any) => (
{tableFields?.map((field: any) => {
const isFkField = field.foreign_key && field.foreign_key.entity && field.foreign_key.field
const fkRecordsForField = fkRecords[field.name] || []
return (
<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>
{field.type === "bool" ? (
{isFkField ? (
<Select
value={formData[field.name] === null || formData[field.name] === undefined ? "null" : formData[field.name]}
onValueChange={(value) => handleFieldChange(field.name, value === "null" ? null : value)}
disabled={field.type === "view" || isSystemGeneratedField(field)}
>
<SelectTrigger className={field.type === "view" || isSystemGeneratedField(field) ? "bg-muted" : ""}>
<SelectValue placeholder="Select a record or leave empty" />
</SelectTrigger>
<SelectContent>
{!field.required && (
<SelectItem value="null">(None)</SelectItem>
)}
{fkRecordsForField.map((record: any) => {
const refFieldValue = record[field.foreign_key.field]
const displayValue = refFieldValue !== undefined && refFieldValue !== null
? String(refFieldValue)
: record.id
return (
<SelectItem key={record.id} value={record.id}>
{displayValue} ({record.id})
</SelectItem>
)
})}
</SelectContent>
</Select>
) : field.type === "bool" ? (
<div className="flex items-center gap-2">
<Switch
id={field.name}
@@ -317,7 +392,7 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
/>
)}
</div>
))}
)})}
{(!tableFields || tableFields.length === 0) &&
<p className="text-xs text-muted-foreground">No additional fields for input, proceed to create the record.</p>

View File

@@ -22,7 +22,7 @@ import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/component
import { Checkbox } from "@/components/ui/checkbox"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Textarea } from "@/components/ui/textarea"
import type { ApiClient, TableMetadata, TableField } from "@/lib/api"
import type { ApiClient, TableMetadata, TableField, ForeignKeyConfig } from "@/lib/api"
import { dataTypes } from "@/lib/constants"
import { useToast } from "@/hooks/use-toast"
import { cn } from "@/lib/utils"
@@ -31,6 +31,7 @@ import { fi } from "date-fns/locale"
interface AddTableDialogProps {
apiClient: ApiClient
onTablesUpdate: (tables: TableMetadata[]) => void
tables?: TableMetadata[] // List of existing tables for foreign key entity selection
children?: React.ReactNode
}
@@ -49,9 +50,10 @@ interface Field {
min_value: number | null
validator: string | null
}
foreign_key?: ForeignKeyConfig // Optional foreign key configuration
}
export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTableDialogProps) {
export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], children }: AddTableDialogProps) {
const [tableType, setTableType] = React.useState<"base" | "auth" | "view">("base")
const [tableName, setTableName] = React.useState("")
const [fields, setFields] = React.useState<Field[]>([])
@@ -253,6 +255,12 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
)
}
// Get fields for a selected entity (for foreign key field selector)
const getEntityFields = (entityName: string): TableField[] => {
const entity = tables.find(t => t.schema.name === entityName)
return entity?.schema.fields || []
}
const toggleFieldExpanded = (fieldKey: string) => {
setExpandedFields((prev) => {
const next = new Set(prev)
@@ -358,6 +366,10 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
if (field.id && field.id.startsWith("mbf_")) {
fieldData.id = field.id
}
// Include foreign_key if configured
if (field.foreign_key && field.foreign_key.entity && field.foreign_key.field) {
fieldData.foreign_key = field.foreign_key
}
return fieldData
},
@@ -693,6 +705,131 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
className="h-8 text-xs"
/>
</div>
{/* Foreign Key Configuration */}
<div className="space-y-3 pt-2 border-t">
<Label className="text-xs font-semibold">Foreign Key</Label>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label htmlFor={`fk-entity-${fieldKey}`} className="text-xs">
Entity
</Label>
<Select
value={field.foreign_key?.entity || ""}
onValueChange={(value) => {
updateField(fieldKey, {
foreign_key: {
...field.foreign_key,
entity: value,
field: "", // Reset field when entity changes
} as ForeignKeyConfig
})
}}
>
<SelectTrigger className="h-8 text-xs">
<SelectValue placeholder="Select entity" />
</SelectTrigger>
<SelectContent>
{tables
.filter(t => t.schema.name !== tableName) // Don't allow self-reference
.map((table) => (
<SelectItem key={table.schema.name} value={table.schema.name}>
{table.schema.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label htmlFor={`fk-field-${fieldKey}`} className="text-xs">
Field
</Label>
<Select
value={field.foreign_key?.field || ""}
onValueChange={(value) => {
updateField(fieldKey, {
foreign_key: {
...field.foreign_key,
field: value,
} as ForeignKeyConfig
})
}}
disabled={!field.foreign_key?.entity}
>
<SelectTrigger className="h-8 text-xs" disabled={!field.foreign_key?.entity}>
<SelectValue placeholder="Select field" />
</SelectTrigger>
<SelectContent>
{field.foreign_key?.entity
? getEntityFields(field.foreign_key.entity).map((f) => (
<SelectItem key={f.id} value={f.name}>
{f.name}
</SelectItem>
))
: null}
</SelectContent>
</Select>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label htmlFor={`fk-on-update-${fieldKey}`} className="text-xs">
On Update
</Label>
<Select
value={field.foreign_key?.on_update || undefined}
onValueChange={(value) => {
updateField(fieldKey, {
foreign_key: {
...field.foreign_key,
on_update: value === "none" ? undefined : value,
} as ForeignKeyConfig
})
}}
disabled={!field.foreign_key?.entity || !field.foreign_key?.field}
>
<SelectTrigger className="h-8 text-xs" disabled={!field.foreign_key?.entity || !field.foreign_key?.field}>
<SelectValue placeholder="Optional" />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">None</SelectItem>
<SelectItem value="CASCADE">CASCADE</SelectItem>
<SelectItem value="SET NULL">SET NULL</SelectItem>
<SelectItem value="RESTRICT">RESTRICT</SelectItem>
<SelectItem value="NO ACTION">NO ACTION</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label htmlFor={`fk-on-delete-${fieldKey}`} className="text-xs">
On Delete
</Label>
<Select
value={field.foreign_key?.on_delete || undefined}
onValueChange={(value) => {
updateField(fieldKey, {
foreign_key: {
...field.foreign_key,
on_delete: value === "none" ? undefined : value,
} as ForeignKeyConfig
})
}}
disabled={!field.foreign_key?.entity || !field.foreign_key?.field}
>
<SelectTrigger className="h-8 text-xs" disabled={!field.foreign_key?.entity || !field.foreign_key?.field}>
<SelectValue placeholder="Optional" />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">None</SelectItem>
<SelectItem value="CASCADE">CASCADE</SelectItem>
<SelectItem value="SET NULL">SET NULL</SelectItem>
<SelectItem value="RESTRICT">RESTRICT</SelectItem>
<SelectItem value="NO ACTION">NO ACTION</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
</CollapsibleContent>
</Collapsible>
)}

View File

@@ -165,7 +165,7 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
/>
</div>
<div className="flex gap-2">
<AddTableDialog apiClient={apiClient} onTablesUpdate={onTablesUpdate}>
<AddTableDialog apiClient={apiClient} onTablesUpdate={onTablesUpdate} tables={tables}>
<Button size="sm" className="flex-1">
<Plus className="h-4 w-4 mr-2" />
New
@@ -235,6 +235,7 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
onTablesUpdate(updatedTables)
}}
onTablesUpdate={onTablesUpdate}
tables={tables}
/>
) : (
<div className="flex items-center justify-center h-full">
@@ -247,7 +248,7 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
Get started by creating your first entity. Entities are used to store and organize your data.
</p>
<div className="flex gap-3">
<AddTableDialog apiClient={apiClient} onTablesUpdate={onTablesUpdate}>
<AddTableDialog apiClient={apiClient} onTablesUpdate={onTablesUpdate} tables={tables}>
<Button>
<Plus className="h-4 w-4 mr-2" />
Create Entity

View File

@@ -16,7 +16,8 @@ import {
DrawerTitle,
} from "@/components/ui/drawer"
import { ScrollArea } from "@/components/ui/scroll-area"
import { ApiClient, TableMetadata, getApiBaseUrl } from "@/lib/api"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { ApiClient, TableMetadata, getApiBaseUrl, TableField } from "@/lib/api"
import { useToast } from "@/hooks/use-toast"
interface EditItemDrawerProps {
@@ -115,16 +116,55 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
const [isLoading, setIsLoading] = React.useState(false)
const [isViewType, setIsViewIsViewType] = React.useState(false)
const [hasUnsavedChanges, setHasUnsavedChanges] = React.useState(false)
const [fkRecords, setFkRecords] = React.useState<Record<string, any[]>>({}) // Store FK records by field name
const { toast } = useToast()
// Fetch records for foreign key fields
const fetchForeignKeyRecords = React.useCallback(async (field: TableField) => {
if (!field.foreign_key?.entity) return
try {
const response = await apiClient.call<any>(`/api/v1/entities/${field.foreign_key.entity}`)
// Handle paginated response
let records: any[] = []
if (Array.isArray(response)) {
records = response
} else if (response?.items && Array.isArray(response.items)) {
records = response.items
} else if (response?.data?.items && Array.isArray(response.data.items)) {
records = response.data.items
}
setFkRecords(prev => ({
...prev,
[field.name]: records
}))
} catch (error) {
console.error(`Failed to fetch records for FK field ${field.name}:`, error)
setFkRecords(prev => ({
...prev,
[field.name]: []
}))
}
}, [apiClient])
React.useEffect(() => {
if (open && item) {
setFormData({ ...item })
setHasUnsavedChanges(false)
setTableFields(table.schema?.fields.filter(f => !isSystemGeneratedField(f)))
const fields = table.schema?.fields.filter(f => !isSystemGeneratedField(f)) || []
setTableFields(fields)
setIsViewIsViewType(table?.schema?.type === "view")
// Fetch records for all foreign key fields
fields.forEach((field: any) => {
if (field.foreign_key?.entity) {
fetchForeignKeyRecords(field)
}
})
}
}, [open, item])
}, [open, item, table, fetchForeignKeyRecords])
const prepareRequestBody = (data: Record<string, any>, tableFields: TableField[]): FormData | string => {
const hasFileField = tableFields.some(f => ["file", "files"].includes(f.type));
@@ -219,6 +259,12 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
const castToType = (fieldName: string, value: any): any => {
const field = tableFields?.find((f: any) => f.name === fieldName);
if (!field) return value;
// For foreign key fields, return the value as-is (id string or null)
if (field.foreign_key && field.foreign_key.entity && field.foreign_key.field) {
return value === "null" ? null : value;
}
if (!value) return null; // handle null or undefined values
const type = field.type;
@@ -334,6 +380,8 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
const isDisabled = (field.type === "view" || isSystemGeneratedField(field));
const value = formData[field.name];
const isFileField = field.type === "file" || field.type === "files";
const isFkField = field.foreign_key && field.foreign_key.entity && field.foreign_key.field
const fkRecordsForField = fkRecords[field.name] || []
return (
<div key={field.name} className="space-y-2">
@@ -342,8 +390,34 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
{field.required && <span className="text-red-500 ml-1">*</span>}
</Label>
{/* FILE/FILES PREVIEW */}
{isFileField ? (
{/* FOREIGN KEY FIELD */}
{isFkField ? (
<Select
value={value === null || value === undefined ? "null" : value}
onValueChange={(selectedValue) => handleFieldChange(field.name, selectedValue === "null" ? null : selectedValue)}
disabled={isDisabled}
>
<SelectTrigger className={isDisabled ? "bg-muted" : ""}>
<SelectValue placeholder="Select a record or leave empty" />
</SelectTrigger>
<SelectContent>
{!field.required && (
<SelectItem value="null">(None)</SelectItem>
)}
{fkRecordsForField.map((record: any) => {
const refFieldValue = record[field.foreign_key.field]
const displayValue = refFieldValue !== undefined && refFieldValue !== null
? String(refFieldValue)
: record.id
return (
<SelectItem key={record.id} value={record.id}>
{displayValue} ({record.id})
</SelectItem>
)
})}
</SelectContent>
</Select>
) : isFileField ? (
<FilePreviewField
field={field}
value={value}

View File

@@ -31,10 +31,12 @@ import { ScrollArea } from "@/components/ui/scroll-area"
import { Textarea } from "@/components/ui/textarea"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
import { Checkbox } from "@/components/ui/checkbox"
import type { ApiClient, TableMetadata } from "@/lib/api"
import type { ApiClient, TableMetadata, ForeignKeyConfig } from "@/lib/api"
import { dataTypes } from "@/lib/constants"
import { useToast } from "@/hooks/use-toast"
import { useRouter } from "@/lib/router"
import { cn } from "@/lib/utils"
interface TableConfigDrawerProps {
@@ -44,6 +46,7 @@ interface TableConfigDrawerProps {
onClose: () => void
onTableUpdate: (table: TableMetadata) => void
onTablesUpdate?: (tables: TableMetadata[]) => void
tables?: TableMetadata[] // List of existing tables for foreign key entity selection
}
// The update structure for tables is a s follows
@@ -62,7 +65,7 @@ interface TableConfigDrawerProps {
*/
// NOTE: We don't support changing of field names yet!
export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpdate, onTablesUpdate }: TableConfigDrawerProps) {
export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpdate, onTablesUpdate, tables = [] }: TableConfigDrawerProps) {
const [columns, setColumns] = React.useState<any[]>([])
const [rules, setRules] = React.useState<{
list: { mode: string; expr: string }
@@ -81,7 +84,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
const [activeTab, setActiveTab] = React.useState("schema")
const [hasUnsavedChanges, setHasUnsavedChanges] = React.useState(false)
const [expandedFields, setExpandedFields] = React.useState<Set<string>>(new Set())
const [deletedColumns, setDeletedColumns] = React.useState<string[]>([]) // Track deleted field names
const [deletedColumns, setDeletedColumns] = React.useState<string[]>([]) // Track deleted field IDs
const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false)
const [isDeleting, setIsDeleting] = React.useState(false)
const { toast } = useToast()
@@ -102,6 +105,8 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
maxValue: col.constraints?.max_value || null,
defaultValue: col.constraints?.default_value || null,
validator: col.constraints?.validator || null,
// Include foreign_key if present
foreign_key: col.foreign_key,
})) || []
setColumns(transformedColumns)
// Initialize rules with mode and expr from API
@@ -169,12 +174,15 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
if (!(columns.length > 1 && !isSystemColumn))
return
const col_name = column.name
// Ensure the field we are deleting existed/exists in the table already
if (!deletedColumns.includes(col_name) && isAnExistingField(index)) {
// Add the column to the delete array
setDeletedColumns([...deletedColumns, col_name]);
if (isAnExistingField(index)) {
// Find the original field from the table schema to get its ID
const originalField = table.schema.fields.find((f: any) => f.name === column.old_name || f.name === column.name)
if (originalField?.id && !deletedColumns.includes(originalField.id)) {
// Add the field ID to the delete array
setDeletedColumns([...deletedColumns, originalField.id]);
}
}
setColumns(columns.filter((_, i) => i !== index))
}
@@ -193,7 +201,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
const updateColumn = (index: number, field: string, value: any) => {
const updatedColumns = columns.map((col, i) => {
if (i === index) {
var updated = col
var updated = { ...col }
updated[field] = value
return updated;
}
@@ -205,28 +213,50 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
setHasUnsavedChanges(true)
}
// Get fields for a selected entity (for foreign key field selector)
const getEntityFields = (entityName: string): any[] => {
const entity = tables.find(t => t.schema.name === entityName)
return entity?.schema.fields || []
}
const handleSaveSchema = async () => {
setIsLoading(true)
try {
// Transform UI format (camelCase flat) to API format (with constraints and snake_case)
const transformedFields = columns.map((col: any) => ({
id: col.id,
name: col.name,
type: col.type,
primary_key: col.primaryKey !== undefined ? col.primaryKey : col.primary_key,
required: col.required,
system: col.system || false,
unique: col.unique || false,
constraints: {
default_value: col.defaultValue !== undefined ? col.defaultValue : (col.constraints?.default_value || null),
max_value: col.maxValue !== undefined ? col.maxValue : (col.constraints?.max_value || null),
min_value: col.minValue !== undefined ? col.minValue : (col.constraints?.min_value || null),
validator: col.validator !== undefined ? col.validator : (col.constraints?.validator || null),
},
...(col.old_name && { old_name: col.old_name }),
const transformedFields = columns.map((col: any) => {
const fieldData: any = {
id: col.id,
name: col.name,
type: col.type,
primary_key: col.primaryKey !== undefined ? col.primaryKey : col.primary_key,
required: col.required,
system: col.system || false,
unique: col.unique || false,
constraints: {
default_value: col.defaultValue !== undefined ? col.defaultValue : (col.constraints?.default_value || null),
max_value: col.maxValue !== undefined ? col.maxValue : (col.constraints?.max_value || null),
min_value: col.minValue !== undefined ? col.minValue : (col.constraints?.min_value || null),
validator: col.validator !== undefined ? col.validator : (col.constraints?.validator || null),
},
...(col.old_name && { old_name: col.old_name }),
}
// Include foreign_key if configured
if (col.foreign_key && col.foreign_key.entity && col.foreign_key.field) {
fieldData.foreign_key = col.foreign_key
}
return fieldData
})
// Add deleted fields to the fields array with op: "delete"
const deletedFields = deletedColumns.map((fieldId: string) => ({
id: fieldId,
op: "delete"
}))
const body = { fields: transformedFields, deletedFields: deletedColumns };
// Combine regular fields and deleted fields in the fields array
const allFields = [...transformedFields, ...deletedFields]
const body = { fields: allFields };
console.log(body)
// return
const updatedTable = await apiClient.call<TableMetadata>(`/api/v1/schemas/${table.schema.name}`, {
@@ -598,6 +628,123 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
className="h-8 text-xs"
/>
</div>
{/* Foreign Key Configuration */}
<div className="space-y-3 pt-2 border-t">
<Label className="text-xs font-semibold">Foreign Key</Label>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label htmlFor={`fk-entity-${fieldKey}`} className="text-xs">
Entity
</Label>
<Select
value={column.foreign_key?.entity || ""}
onValueChange={(value) => {
updateColumn(index, "foreign_key", {
...column.foreign_key,
entity: value,
field: "", // Reset field when entity changes
} as ForeignKeyConfig)
}}
>
<SelectTrigger className="h-8 text-xs">
<SelectValue placeholder="Select entity" />
</SelectTrigger>
<SelectContent>
{tables
.filter(t => t.schema.name !== table.schema.name) // Don't allow self-reference
.map((t) => (
<SelectItem key={t.schema.name} value={t.schema.name}>
{t.schema.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label htmlFor={`fk-field-${fieldKey}`} className="text-xs">
Field
</Label>
<Select
value={column.foreign_key?.field || ""}
onValueChange={(value) => {
updateColumn(index, "foreign_key", {
...column.foreign_key,
field: value,
} as ForeignKeyConfig)
}}
disabled={!column.foreign_key?.entity}
>
<SelectTrigger className="h-8 text-xs" disabled={!column.foreign_key?.entity}>
<SelectValue placeholder="Select field" />
</SelectTrigger>
<SelectContent>
{column.foreign_key?.entity
? getEntityFields(column.foreign_key.entity).map((f: any) => (
<SelectItem key={f.id} value={f.name}>
{f.name}
</SelectItem>
))
: null}
</SelectContent>
</Select>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label htmlFor={`fk-on-update-${fieldKey}`} className="text-xs">
On Update
</Label>
<Select
value={column.foreign_key?.on_update || undefined}
onValueChange={(value) => {
updateColumn(index, "foreign_key", {
...column.foreign_key,
on_update: value === "none" ? undefined : value,
} as ForeignKeyConfig)
}}
disabled={!column.foreign_key?.entity || !column.foreign_key?.field}
>
<SelectTrigger className="h-8 text-xs" disabled={!column.foreign_key?.entity || !column.foreign_key?.field}>
<SelectValue placeholder="Optional" />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">None</SelectItem>
<SelectItem value="CASCADE">CASCADE</SelectItem>
<SelectItem value="SET NULL">SET NULL</SelectItem>
<SelectItem value="RESTRICT">RESTRICT</SelectItem>
<SelectItem value="NO ACTION">NO ACTION</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label htmlFor={`fk-on-delete-${fieldKey}`} className="text-xs">
On Delete
</Label>
<Select
value={column.foreign_key?.on_delete || undefined}
onValueChange={(value) => {
updateColumn(index, "foreign_key", {
...column.foreign_key,
on_delete: value === "none" ? undefined : value,
} as ForeignKeyConfig)
}}
disabled={!column.foreign_key?.entity || !column.foreign_key?.field}
>
<SelectTrigger className="h-8 text-xs" disabled={!column.foreign_key?.entity || !column.foreign_key?.field}>
<SelectValue placeholder="Optional" />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">None</SelectItem>
<SelectItem value="CASCADE">CASCADE</SelectItem>
<SelectItem value="SET NULL">SET NULL</SelectItem>
<SelectItem value="RESTRICT">RESTRICT</SelectItem>
<SelectItem value="NO ACTION">NO ACTION</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
</CollapsibleContent>
</Collapsible>
)}

View File

@@ -23,9 +23,10 @@ interface TableDetailViewProps {
apiClient: ApiClient
onTableUpdate: (table: TableMetadata) => void
onTablesUpdate?: (tables: TableMetadata[]) => void
tables?: TableMetadata[] // List of existing tables for foreign key entity selection
}
export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTablesUpdate }: TableDetailViewProps) {
export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTablesUpdate, tables = [] }: TableDetailViewProps) {
const [tableData, setTableData] = React.useState<any[]>([])
const [currentPage, setCurrentPage] = React.useState(1)
const [totalPages, setTotalPages] = React.useState(1)
@@ -469,6 +470,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
onClose={() => setConfigOpen(false)}
onTableUpdate={onTableUpdate}
onTablesUpdate={onTablesUpdate}
tables={tables}
/>
<TableRecordDocsDrawer table={table} open={docsOpen} onClose={() => setDocsOpen(false)} />

View File

@@ -1,7 +1,7 @@
"use client"
import * as React from "react"
import { FileText, ChevronDown, ChevronRight, X, Copy } from "lucide-react"
import { FileText, ChevronDown, ChevronRight, X, Copy, Radio } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
@@ -84,6 +84,8 @@ export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerP
/>
</>
)}
<RealtimeDocCard table={table} />
</div>
</ScrollArea>
</div>
@@ -92,6 +94,121 @@ export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerP
)
}
// Realtime (SSE) documentation: connect and update topics for this entity
function RealtimeDocCard({ table }: { table: TableMetadata }) {
const [isOpen, setIsOpen] = React.useState(false)
const entityName = table.schema.name
const baseUrl = "https://your-api.com"
const sampleRowId = "019c1b81-364b-7000-8120-b5416b2c42c2"
const connectExample = `# Connect to SSE: subscribe to this entity (all rows) and/or a specific row
# Topics: entity name only, or entity:row_id for a single row
curl -N -H "Authorization: Bearer YOUR_TOKEN" \\
"${baseUrl}/api/v1/realtime?topics=${entityName}"
# Subscribe to entity + a specific row (comma-separated)
curl -N -H "Authorization: Bearer YOUR_TOKEN" \\
"${baseUrl}/api/v1/realtime?topics=${entityName},${entityName}:${sampleRowId}"`
const updateTopicsExample = `# Update topics for an existing SSE session (from the "connected" event client_id)
curl -X POST "${baseUrl}/api/v1/realtime" \\
-H "Authorization: Bearer YOUR_TOKEN" \\
-H "Content-Type: application/json" \\
-d '{
"client_id": "sse_1769987962000_0abc1",
"topics": ["${entityName}", "${entityName}:${sampleRowId}"]
}'
# Clear topics to disconnect
curl -X POST "${baseUrl}/api/v1/realtime" \\
-H "Authorization: Bearer YOUR_TOKEN" \\
-H "Content-Type: application/json" \\
-d '{"client_id": "sse_1769987962000_0abc1", "topics": []}'`
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text)
}
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">
<Radio className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">Realtime (SSE)</span>
{isOpen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
</div>
</div>
<p className="text-sm text-muted-foreground mt-2">
Subscribe to database changes for this entity (all rows) or a specific row. Connect via GET, then update topics via POST.
</p>
</div>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="border-l-2 border-muted ml-4 pl-6 space-y-6 mt-4">
<div>
<h5 className="font-medium mb-1">Connect to SSE</h5>
<p className="text-sm text-muted-foreground mb-2">
Open a long-lived SSE stream. Use <code className="bg-muted px-1 rounded">topics</code> query param: entity name (e.g. <code className="bg-muted px-1 rounded">{entityName}</code>) for all rows, or <code className="bg-muted px-1 rounded">{entityName}:row_id</code> for a single row. Multiple topics are comma-separated.
</p>
<div className="flex justify-end mb-2">
<Button variant="outline" size="sm" onClick={() => copyToClipboard(connectExample)} className="h-8">
<Copy className="h-3 w-3 mr-1" />
Copy
</Button>
</div>
<ScrollArea className="h-40">
<pre className="bg-muted p-4 rounded text-sm border whitespace-pre">
<code>{connectExample}</code>
</pre>
</ScrollArea>
</div>
<div>
<h5 className="font-medium mb-1">Update topics to monitor</h5>
<p className="text-sm text-muted-foreground mb-2">
POST with <code className="bg-muted px-1 rounded">client_id</code> from the <code className="bg-muted px-1 rounded">connected</code> event and a new <code className="bg-muted px-1 rounded">topics</code> array. Send <code className="bg-muted px-1 rounded">topics: []</code> to disconnect.
</p>
<div className="flex justify-end mb-2">
<Button variant="outline" size="sm" onClick={() => copyToClipboard(updateTopicsExample)} 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 whitespace-pre">
<code>{updateTopicsExample}</code>
</pre>
</ScrollArea>
</div>
<div>
<h5 className="font-medium mb-2">SSE event types</h5>
<div className="grid grid-cols-1 gap-2 text-sm">
<div className="flex items-center gap-2">
<Badge variant="secondary" className="text-xs">connected</Badge>
<span>Sent once when the stream opens; includes <code className="bg-muted px-1 rounded">client_id</code> and <code className="bg-muted px-1 rounded">topics</code>.</span>
</div>
<div className="flex items-center gap-2">
<Badge variant="secondary" className="text-xs">ping</Badge>
<span>Keep-alive sent periodically.</span>
</div>
<div className="flex items-center gap-2">
<Badge variant="secondary" className="text-xs">change</Badge>
<span>Database change: <code className="bg-muted px-1 rounded">action</code> (insert/update/delete), <code className="bg-muted px-1 rounded">entity</code>, <code className="bg-muted px-1 rounded">row_id</code>, <code className="bg-muted px-1 rounded">data</code> (row payload or null for delete).</span>
</div>
</div>
</div>
<div className="text-sm text-muted-foreground">
<p>
Access uses the same rules as entity <strong>list</strong> (topic = entity name) and <strong>get</strong> (topic = entity:row_id). In browsers, <code className="bg-muted px-1 rounded">EventSource</code> cannot send <code className="bg-muted px-1 rounded">Authorization</code>; use <code className="bg-muted px-1 rounded">fetch()</code> with the same URL and headers, then read the body as a stream to process SSE events.
</p>
</div>
</div>
</CollapsibleContent>
</Collapsible>
)
}
function ApiEndpointCard({
method,
endpoint,

View File

@@ -1,14 +1,19 @@
"use client"
import * as React from "react"
import { Download, Search, ChevronLeft, ChevronRight } from "lucide-react"
import { Download, Search, RefreshCw, X } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from "@/components/ui/drawer"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Separator } from "@/components/ui/separator"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
Pagination,
PaginationContent,
@@ -18,156 +23,127 @@ import {
PaginationPrevious,
} from "@/components/ui/pagination"
import type { ApiClient } from "@/lib/api"
import { useToast } from "@/hooks/use-toast"
interface LogEntry {
id: string
timestamp: string
level: "info" | "warning" | "error"
created_at: number
level: "critical" | "warn" | "info" | "debug" | "trace"
message: string
source: string
origin: string
details?: string
data?: any // Optional JSON value (object/array/value/etc.)
}
interface PaginatedLogsResponse {
items: LogEntry[]
items_count: number
page: number
page_size: number
total_count: number
}
interface LogsSectionProps {
apiClient: ApiClient
}
const ITEMS_PER_PAGE = 10
const ITEMS_PER_PAGE = 100
export function LogsSection({ apiClient }: LogsSectionProps) {
// Mock data - sorted by latest first
const [allLogs] = React.useState<LogEntry[]>([
{
id: "1",
timestamp: "2024-01-15T10:30:00Z",
level: "info",
message: "User login successful",
source: "auth",
details: "User admin@example.com logged in from IP 192.168.1.1",
},
{
id: "2",
timestamp: "2024-01-15T10:25:00Z",
level: "warning",
message: "Rate limit approaching",
source: "api",
details: "API rate limit at 80% for endpoint /api/v1/tables",
},
{
id: "3",
timestamp: "2024-01-15T10:20:00Z",
level: "error",
message: "Database connection failed",
source: "database",
details: "Connection timeout after 30 seconds",
},
{
id: "4",
timestamp: "2024-01-15T10:15:00Z",
level: "info",
message: "Table created successfully",
source: "database",
details: "New table 'products' created with 5 columns",
},
{
id: "5",
timestamp: "2024-01-15T10:10:00Z",
level: "info",
message: "Backup completed",
source: "system",
details: "Daily backup completed successfully (2.3GB)",
},
{
id: "6",
timestamp: "2024-01-15T10:05:00Z",
level: "info",
message: "Cache cleared",
source: "system",
details: "Application cache cleared successfully",
},
{
id: "7",
timestamp: "2024-01-15T10:00:00Z",
level: "warning",
message: "High memory usage detected",
source: "system",
details: "Memory usage at 85% of available capacity",
},
{
id: "8",
timestamp: "2024-01-15T09:55:00Z",
level: "info",
message: "Scheduled task completed",
source: "system",
details: "Daily maintenance task completed in 2.3 seconds",
},
{
id: "9",
timestamp: "2024-01-15T09:50:00Z",
level: "error",
message: "Failed to send email notification",
source: "email",
details: "SMTP server connection timeout",
},
{
id: "10",
timestamp: "2024-01-15T09:45:00Z",
level: "info",
message: "API request processed",
source: "api",
details: "GET /api/v1/users processed in 45ms",
},
{
id: "11",
timestamp: "2024-01-15T09:40:00Z",
level: "info",
message: "User session expired",
source: "auth",
details: "Session expired for user user@example.com",
},
{
id: "12",
timestamp: "2024-01-15T09:35:00Z",
level: "warning",
message: "Slow query detected",
source: "database",
details: "Query took 2.5 seconds to execute",
},
].sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()))
const [searchTerm, setSearchTerm] = React.useState("")
const [levelFilter, setLevelFilter] = React.useState<string>("all")
const [logs, setLogs] = React.useState<LogEntry[]>([])
const [isLoading, setIsLoading] = React.useState(false)
const [currentPage, setCurrentPage] = React.useState(1)
const [totalCount, setTotalCount] = React.useState<number>(-1) // -1 means unknown
const [searchTerm, setSearchTerm] = React.useState("")
const [levelFilter, setLevelFilter] = React.useState<string>("all") // Exact level filter
const [minLevelFilter, setMinLevelFilter] = React.useState<string>("info") // Minimum level filter (default: info+)
const [useMinLevel, setUseMinLevel] = React.useState<boolean>(true) // Use minimum level by default
const [selectedLog, setSelectedLog] = React.useState<LogEntry | null>(null)
const [drawerOpen, setDrawerOpen] = React.useState(false)
const { toast } = useToast()
const filteredLogs = React.useMemo(() => {
return allLogs.filter((log) => {
const matchesSearch =
log.message.toLowerCase().includes(searchTerm.toLowerCase()) ||
log.source.toLowerCase().includes(searchTerm.toLowerCase()) ||
(log.details && log.details.toLowerCase().includes(searchTerm.toLowerCase()))
const matchesLevel = levelFilter === "all" || log.level === levelFilter
return matchesSearch && matchesLevel
})
}, [allLogs, searchTerm, levelFilter])
const loadLogs = React.useCallback(async (page: number = 1) => {
setIsLoading(true)
try {
// Build query parameters
const params = new URLSearchParams()
params.append("page", page.toString())
params.append("page_size", ITEMS_PER_PAGE.toString())
// Add level filter - use minimum level by default, or exact level if specified
if (useMinLevel && minLevelFilter) {
params.append("min_level", minLevelFilter)
} else if (!useMinLevel && levelFilter !== "all") {
params.append("level", levelFilter)
}
// Add search term if provided
if (searchTerm.trim()) {
params.append("search", searchTerm.trim())
}
const totalPages = Math.ceil(filteredLogs.length / ITEMS_PER_PAGE)
const startIndex = (currentPage - 1) * ITEMS_PER_PAGE
const endIndex = startIndex + ITEMS_PER_PAGE
const paginatedLogs = filteredLogs.slice(startIndex, endIndex)
const response = await apiClient.call<PaginatedLogsResponse>(`/api/v1/sys/logs?${params.toString()}`)
// Handle different response structures
let logsData: LogEntry[] = []
let count = -1
if (Array.isArray(response)) {
// Fallback: if response is directly an array
logsData = response
} else if (response?.items && Array.isArray(response.items)) {
// Paginated response
logsData = response.items
count = response.total_count ?? -1
} else if ((response as any)?.data?.items && Array.isArray((response as any).data.items)) {
// If data is nested (handle as any for nested structure)
logsData = (response as any).data.items
count = (response as any).data.total_count ?? -1
} else {
console.warn("Unexpected response format:", response)
logsData = []
}
setLogs(logsData)
setTotalCount(count)
} catch (error: any) {
console.error("Failed to load logs:", error)
toast({
variant: "destructive",
title: "Error",
description: error?.message || "Failed to load logs",
})
setLogs([])
setTotalCount(-1)
} finally {
setIsLoading(false)
}
}, [apiClient, levelFilter, minLevelFilter, useMinLevel, searchTerm, toast])
// Load logs when component mounts or filters change
React.useEffect(() => {
loadLogs(currentPage)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentPage, levelFilter, minLevelFilter, useMinLevel, searchTerm])
// Reset to first page when filters change
React.useEffect(() => {
// Reset to first page when filters change
setCurrentPage(1)
}, [searchTerm, levelFilter])
}, [searchTerm, levelFilter, minLevelFilter, useMinLevel])
const getLevelColor = (level: string) => {
switch (level) {
case "error":
case "critical":
return "destructive"
case "warning":
case "warn":
return "secondary"
case "info":
return "outline"
case "debug":
return "outline"
case "trace":
return "outline"
default:
return "outline"
}
@@ -185,6 +161,46 @@ export function LogsSection({ apiClient }: LogsSectionProps) {
})
}
const formatData = (data: any): string => {
if (data === null || data === undefined) {
return ""
}
try {
return JSON.stringify(data, null, 2)
} catch {
return String(data)
}
}
const handleLogClick = (log: LogEntry) => {
setSelectedLog(log)
setDrawerOpen(true)
}
const handleDrawerClose = () => {
setDrawerOpen(false)
setSelectedLog(null)
}
// Calculate total pages (show -- if total_count is -1)
const totalPages = totalCount === -1 ? null : Math.ceil(totalCount / ITEMS_PER_PAGE)
const hasMorePages = totalCount === -1 || (totalPages !== null && currentPage < totalPages)
const handleSearch = () => {
setCurrentPage(1)
loadLogs(1)
}
const handleSearchKeyPress = (e: React.KeyboardEvent) => {
if (e.key === "Enter") {
handleSearch()
}
}
const handleReload = () => {
loadLogs(currentPage)
}
return (
<div className="space-y-6 p-6">
{/* Header */}
@@ -193,10 +209,15 @@ export function LogsSection({ apiClient }: LogsSectionProps) {
<h1 className="text-3xl font-bold tracking-tight">Logs</h1>
<p className="text-muted-foreground">Monitor system activity and events</p>
</div>
<Button>
<Download className="h-4 w-4 mr-2" />
Export
</Button>
<div className="flex items-center gap-2">
<Button variant="outline" size="icon" onClick={handleReload} disabled={isLoading}>
<RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
</Button>
<Button variant="outline" disabled>
<Download className="h-4 w-4 mr-2" />
Export
</Button>
</div>
</div>
{/* Filters */}
@@ -209,20 +230,47 @@ export function LogsSection({ apiClient }: LogsSectionProps) {
placeholder="Search logs..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onKeyPress={handleSearchKeyPress}
className="pl-9"
/>
</div>
<Select value={levelFilter} onValueChange={setLevelFilter}>
<SelectTrigger className="w-[140px]">
<SelectValue placeholder="All Levels" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Levels</SelectItem>
<SelectItem value="info">Info</SelectItem>
<SelectItem value="warning">Warning</SelectItem>
<SelectItem value="error">Error</SelectItem>
</SelectContent>
</Select>
<Tabs value={useMinLevel ? "min" : "exact"} onValueChange={(value) => setUseMinLevel(value === "min")} className="w-auto">
<TabsList>
<TabsTrigger value="min">Minimum Level</TabsTrigger>
<TabsTrigger value="exact">Exact Level</TabsTrigger>
</TabsList>
</Tabs>
{useMinLevel ? (
<Select value={minLevelFilter} onValueChange={setMinLevelFilter}>
<SelectTrigger className="w-[140px]">
<SelectValue placeholder="Min Level" />
</SelectTrigger>
<SelectContent>
<SelectItem value="trace">Trace+</SelectItem>
<SelectItem value="debug">Debug+</SelectItem>
<SelectItem value="info">Info+</SelectItem>
<SelectItem value="warn">Warn+</SelectItem>
<SelectItem value="critical">Critical</SelectItem>
</SelectContent>
</Select>
) : (
<Select value={levelFilter} onValueChange={setLevelFilter}>
<SelectTrigger className="w-[140px]">
<SelectValue placeholder="All Levels" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Levels</SelectItem>
<SelectItem value="critical">Critical</SelectItem>
<SelectItem value="warn">Warn</SelectItem>
<SelectItem value="info">Info</SelectItem>
<SelectItem value="debug">Debug</SelectItem>
<SelectItem value="trace">Trace</SelectItem>
</SelectContent>
</Select>
)}
<Button onClick={handleSearch} variant="outline">
Search
</Button>
</div>
</CardContent>
</Card>
@@ -234,110 +282,261 @@ export function LogsSection({ apiClient }: LogsSectionProps) {
<div>
<CardTitle>System Logs</CardTitle>
<CardDescription>
Showing {startIndex + 1}-{Math.min(endIndex, filteredLogs.length)} of {filteredLogs.length} entries
{isLoading ? (
"Loading logs..."
) : totalCount === -1 ? (
`Showing page ${currentPage} (-- total entries)`
) : (
`Showing ${(currentPage - 1) * ITEMS_PER_PAGE + 1}-${Math.min(currentPage * ITEMS_PER_PAGE, totalCount)} of ${totalCount} entries`
)}
</CardDescription>
</div>
</div>
</CardHeader>
<CardContent>
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[180px]">Timestamp</TableHead>
<TableHead className="w-[100px]">Level</TableHead>
<TableHead className="w-[120px]">Source</TableHead>
<TableHead>Message</TableHead>
<TableHead className="max-w-md">Details</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{paginatedLogs.length === 0 ? (
{isLoading && logs.length === 0 ? (
<div className="flex items-center justify-center h-64">
<div className="text-center">
<div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"></div>
<p className="text-muted-foreground">Loading logs...</p>
</div>
</div>
) : (
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableCell colSpan={5} className="h-24 text-center text-muted-foreground">
No logs found
</TableCell>
<TableHead className="w-[180px]">Timestamp</TableHead>
<TableHead className="w-[100px]">Level</TableHead>
<TableHead className="w-[120px]">Origin</TableHead>
<TableHead>Message</TableHead>
<TableHead className="max-w-md">Details</TableHead>
<TableHead className="max-w-md">Data</TableHead>
</TableRow>
) : (
paginatedLogs.map((log) => (
<TableRow key={log.id} className="hover:bg-muted/50">
<TableCell className="font-mono text-xs">
{formatTimestamp(log.timestamp)}
</TableCell>
<TableCell>
<Badge variant={getLevelColor(log.level) as any} className="font-medium">
{log.level.toUpperCase()}
</Badge>
</TableCell>
<TableCell>
<span className="font-medium capitalize">{log.source}</span>
</TableCell>
<TableCell className="font-medium">{log.message}</TableCell>
<TableCell className="text-sm text-muted-foreground">
<div className="max-w-md truncate" title={log.details}>
{log.details || "-"}
</div>
</TableHeader>
<TableBody>
{logs.length === 0 ? (
<TableRow>
<TableCell colSpan={6} className="h-24 text-center text-muted-foreground">
No logs found
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
) : (
logs.map((log) => (
<TableRow
key={log.id}
className="hover:bg-muted/50 cursor-pointer"
onClick={() => handleLogClick(log)}
>
<TableCell className="font-mono text-xs">
{formatTimestamp(log.timestamp)}
</TableCell>
<TableCell>
<Badge variant={getLevelColor(log.level) as any} className="font-medium">
{log.level.toUpperCase()}
</Badge>
</TableCell>
<TableCell>
<span className="font-medium">{log.origin}</span>
</TableCell>
<TableCell className="font-medium">{log.message}</TableCell>
<TableCell className="text-sm text-muted-foreground">
<div className="max-w-md truncate" title={log.details}>
{log.details || "-"}
</div>
</TableCell>
<TableCell className="text-sm text-muted-foreground font-mono">
{log.data !== undefined && log.data !== null ? (
<div className="max-w-md truncate" title={formatData(log.data)}>
{formatData(log.data)}
</div>
) : (
"-"
)}
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
)}
{/* Pagination */}
{totalPages > 1 && (
{(totalPages !== null && totalPages > 1) || hasMorePages ? (
<div className="mt-4 flex items-center justify-between">
<div className="text-sm text-muted-foreground">
Page {currentPage} of {totalPages}
Page {currentPage} {totalPages !== null ? `of ${totalPages}` : "(--)"}
</div>
<Pagination>
<PaginationContent>
<PaginationItem>
<PaginationPrevious
onClick={() => setCurrentPage((prev) => Math.max(1, prev - 1))}
onClick={() => {
if (currentPage > 1) {
setCurrentPage((prev) => prev - 1)
}
}}
className={currentPage === 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
/>
</PaginationItem>
{Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => {
// Show first page, last page, current page, and pages around current
if (
page === 1 ||
page === totalPages ||
(page >= currentPage - 1 && page <= currentPage + 1)
) {
return (
<PaginationItem key={page}>
<PaginationLink
onClick={() => setCurrentPage(page)}
isActive={currentPage === page}
className="cursor-pointer"
>
{page}
</PaginationLink>
</PaginationItem>
)
} else if (page === currentPage - 2 || page === currentPage + 2) {
return (
<PaginationItem key={page}>
<span className="px-2">...</span>
</PaginationItem>
)
}
return null
})}
{totalPages !== null ? (
// Show page numbers when we know the total
Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => {
// Show first page, last page, current page, and pages around current
if (
page === 1 ||
page === totalPages ||
(page >= currentPage - 1 && page <= currentPage + 1)
) {
return (
<PaginationItem key={page}>
<PaginationLink
onClick={() => setCurrentPage(page)}
isActive={currentPage === page}
className="cursor-pointer"
>
{page}
</PaginationLink>
</PaginationItem>
)
} else if (page === currentPage - 2 || page === currentPage + 2) {
return (
<PaginationItem key={page}>
<span className="px-2">...</span>
</PaginationItem>
)
}
return null
})
) : (
// Show current page only when total is unknown
<PaginationItem>
<PaginationLink isActive className="cursor-default">
{currentPage}
</PaginationLink>
</PaginationItem>
)}
<PaginationItem>
<PaginationNext
onClick={() => setCurrentPage((prev) => Math.min(totalPages, prev + 1))}
className={currentPage === totalPages ? "pointer-events-none opacity-50" : "cursor-pointer"}
onClick={() => {
if (totalPages === null || currentPage < totalPages) {
setCurrentPage((prev) => prev + 1)
}
}}
className={
totalPages !== null && currentPage >= totalPages
? "pointer-events-none opacity-50"
: "cursor-pointer"
}
/>
</PaginationItem>
</PaginationContent>
</Pagination>
</div>
)}
) : null}
</CardContent>
</Card>
{/* Log Details Drawer */}
<Drawer open={drawerOpen} onOpenChange={handleDrawerClose}>
<DrawerContent side="right" className="w-[800px] max-w-[95vw]">
<DrawerHeader>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Badge variant={selectedLog ? (getLevelColor(selectedLog.level) as any) : "outline"} className="font-medium">
{selectedLog?.level.toUpperCase() || "LOG"}
</Badge>
<DrawerTitle>Log Details</DrawerTitle>
</div>
<Button variant="ghost" size="sm" onClick={handleDrawerClose}>
<X className="h-4 w-4" />
</Button>
</div>
<DrawerDescription>
Full details for log entry {selectedLog?.id}
</DrawerDescription>
</DrawerHeader>
<div className="flex-1 overflow-hidden">
<ScrollArea className="h-full">
<div className="p-6 space-y-6">
{selectedLog && (
<>
{/* Basic Information */}
<div className="space-y-4">
<div>
<Label className="text-xs font-semibold text-muted-foreground uppercase">ID</Label>
<p className="text-sm font-mono mt-1">{selectedLog.id}</p>
</div>
<Separator />
<div>
<Label className="text-xs font-semibold text-muted-foreground uppercase">Timestamp</Label>
<p className="text-sm mt-1">{formatTimestamp(selectedLog.timestamp)}</p>
<p className="text-xs text-muted-foreground font-mono mt-1">{selectedLog.timestamp}</p>
{selectedLog.created_at && (
<p className="text-xs text-muted-foreground mt-1">Created at: {selectedLog.created_at}</p>
)}
</div>
<Separator />
<div>
<Label className="text-xs font-semibold text-muted-foreground uppercase">Level</Label>
<div className="mt-1">
<Badge variant={getLevelColor(selectedLog.level) as any} className="font-medium">
{selectedLog.level.toUpperCase()}
</Badge>
</div>
</div>
<Separator />
<div>
<Label className="text-xs font-semibold text-muted-foreground uppercase">Origin</Label>
<p className="text-sm mt-1">{selectedLog.origin}</p>
</div>
<Separator />
<div>
<Label className="text-xs font-semibold text-muted-foreground uppercase">Message</Label>
<p className="text-sm mt-1">{selectedLog.message}</p>
</div>
{selectedLog.details && (
<>
<Separator />
<div>
<Label className="text-xs font-semibold text-muted-foreground uppercase">Details</Label>
<p className="text-sm mt-1 whitespace-pre-wrap">{selectedLog.details}</p>
</div>
</>
)}
{selectedLog.data !== undefined && selectedLog.data !== null && (
<>
<Separator />
<div>
<Label className="text-xs font-semibold text-muted-foreground uppercase">Data (JSON)</Label>
<div className="mt-2 p-4 bg-muted rounded-md border">
<pre className="text-xs font-mono overflow-x-auto">
{formatData(selectedLog.data)}
</pre>
</div>
</div>
</>
)}
</div>
</>
)}
</div>
</ScrollArea>
</div>
</DrawerContent>
</Drawer>
</div>
)
}

View File

@@ -11,6 +11,13 @@ export interface FieldConstraints {
validator: string | null
}
export interface ForeignKeyConfig {
entity: string // table name
field: string // column ref
on_update?: string // optional
on_delete?: string // optional
}
export interface TableField {
id: string
name: string
@@ -20,6 +27,7 @@ export interface TableField {
type: string
unique: boolean
constraints: FieldConstraints
foreign_key?: ForeignKeyConfig // optional foreign key configuration
}
export interface RuleConfig {

BIN
mantisbase-admin.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 179 KiB

8
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "mantis-admin",
"version": "0.3.3",
"name": "mantisbase-admin",
"version": "0.3.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "mantis-admin",
"version": "0.3.3",
"name": "mantisbase-admin",
"version": "0.3.6",
"dependencies": {
"@hookform/resolvers": "^3.9.1",
"@radix-ui/react-accordion": "1.2.2",

View File

@@ -1,6 +1,6 @@
{
"name": "mantis-admin",
"version": "0.3.4",
"name": "mantisbase-admin",
"version": "0.3.7",
"private": true,
"scripts": {
"export": "next build && next export",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 123 KiB