mirror of
https://github.com/allankoechke/mantisbase-admin.git
synced 2026-12-01 01:15:36 +00:00
Compare commits
28 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0df61e3574 | |||
| fd7a565d6b | |||
| e5df3eea6b | |||
| 3b475865dc | |||
| 97f1139abb | |||
| 5f5b7260ec | |||
| d213b760e0 | |||
| 783b7818f8 | |||
| 0b1ee7c76f | |||
| 3ef1afecdf | |||
| ba2bbe38eb | |||
| 230b3b8889 | |||
| 6966cd190b | |||
| 5e8e00695c | |||
| 7d62841cdb | |||
| 6ff6fb6157 | |||
| 71f539a4af | |||
| 15264a65cd | |||
| 2e43450b5a | |||
| 7b20a7ca91 | |||
| dfe21d4163 | |||
| f9a6c77259 | |||
| b53c098364 | |||
| f3821ab557 | |||
| 592657e0dc | |||
| 2ab08e32b9 | |||
| a397f39233 | |||
| 5800ef9c67 |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -24,4 +24,6 @@ yarn-error.log*
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
next-env.d.ts
|
||||
|
||||
changes.md
|
||||
187
README.md
187
README.md
@@ -1,5 +1,184 @@
|
||||
# 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!
|
||||
# MantisBase Admin Dashboard
|
||||
|
||||

|
||||
A modern, web-based admin dashboard for managing your MantisBase backend. This dashboard provides an intuitive interface for managing entities, admins, settings, and more.
|
||||
|
||||

|
||||
|
||||
## 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 app (default: `/mb` in production, empty in dev). Set to empty string for no prefix; overrides at both build and runtime.
|
||||
- `NEXT_PUBLIC_MANTIS_BASE_URL` - Backend API base URL. When set (e.g. `https://api.example.com`), all API and login requests use this URL instead of same-origin or localhost. Omit trailing slash.
|
||||
- `NEXT_PUBLIC_MB_IS_DEMO_MODE` - Set to `true` or `1` to enable demo mode: prefills login with test credentials and shows a banner that data is cleared every 30 minutes
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -14,7 +14,8 @@ export default function RootLayout({
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
<link rel="icon" href="/mantisbase.svg" type="image/svg+xml" />
|
||||
<link rel="alternate icon" href="/favicon.ico" />
|
||||
</head>
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import * as React from "react"
|
||||
import { Table, Settings, Shield, LogOut, FileText, RefreshCw, ExternalLink, AlertTriangle } from "lucide-react"
|
||||
import { Logo } from "./logo"
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
@@ -30,7 +31,7 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { ApiClient, type TableMetadata, type Admin, type AppSettings } from "@/lib/api"
|
||||
import { ApiClient, SYS_ADMINS_API, SYS_SETTINGS_API, type TableMetadata, type Admin, type AppSettings } from "@/lib/api"
|
||||
import { DatabaseSection } from "./database/database-section"
|
||||
import { AdminsSection } from "./admins/admins-section"
|
||||
import { SettingsSection } from "./settings/settings-section"
|
||||
@@ -116,7 +117,7 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
if (!apiClient) return
|
||||
|
||||
try {
|
||||
const adminsData = await apiClient.call<any>("/api/v1/entities/mb_admins")
|
||||
const adminsData = await apiClient.call<any>(`${SYS_ADMINS_API}`)
|
||||
|
||||
// Ensure adminsData is an array - handle paginated response
|
||||
let adminsArray: Admin[] = []
|
||||
@@ -147,8 +148,7 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
}, [route.path, loadAdmins])
|
||||
|
||||
const loadData = async () => {
|
||||
// Set default settings if loading fails
|
||||
setSettings({
|
||||
const defaultSettings: AppSettings = {
|
||||
appName: "ACME Mantis Project",
|
||||
baseUrl: "http://127.0.0.1:7070",
|
||||
mantisVersion: "0.0.0",
|
||||
@@ -159,13 +159,16 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
sessionTimeout: 84000,
|
||||
adminSessionTimeout: 3600,
|
||||
mode: mode,
|
||||
})
|
||||
}
|
||||
setSettings(defaultSettings)
|
||||
|
||||
try {
|
||||
setLoading(true)
|
||||
|
||||
// Only load tables on initial load
|
||||
const tablesData = await apiClient.call<any>("/api/v1/schemas")
|
||||
const [tablesData, settingsData] = await Promise.all([
|
||||
apiClient.call<any>("/api/v1/schemas"),
|
||||
apiClient.call<AppSettings>(SYS_SETTINGS_API).catch(() => null),
|
||||
])
|
||||
|
||||
// Ensure tablesData is an array - handle different response structures
|
||||
let tablesArray: TableMetadata[] = []
|
||||
@@ -176,6 +179,10 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
}
|
||||
|
||||
setTables(tablesArray)
|
||||
|
||||
if (settingsData && !settingsData?.error) {
|
||||
setSettings({ ...settingsData, mode })
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load data:", error)
|
||||
} finally {
|
||||
@@ -278,7 +285,7 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
<SidebarHeader className="border-b p-0 w-full">
|
||||
<div className="flex h-16 w-full items-center justify-center">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary text-primary-foreground">
|
||||
<Shield className="h-6 w-6" />
|
||||
<Logo className="h-6 w-6" size={24} />
|
||||
</div>
|
||||
</div>
|
||||
</SidebarHeader>
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
|
||||
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, TableMetadata } from "@/lib/api"
|
||||
import { SYS_ADMINS_API, type ApiClient, type Admin, type TableMetadata } from "@/lib/api"
|
||||
import { ChangePasswordDialog } from "./change-password-dialog"
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar"
|
||||
import { AddItemDrawer } from "../database/add-item-drawer"
|
||||
@@ -141,12 +141,12 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
|
||||
|
||||
const handleDeleteAdmin = async (adminId: string) => {
|
||||
try {
|
||||
const res: any = await apiClient.call(`/api/v1/entities/mb_admins/${adminId}`, { method: "DELETE" })
|
||||
const res: any = await apiClient.call(`${SYS_ADMINS_API}/${adminId}`, { method: "DELETE" })
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (res?.error?.length > 0) throw res.error
|
||||
|
||||
const response: any = await apiClient.call("/api/v1/entities/mb_admins")
|
||||
const response: any = await apiClient.call(SYS_ADMINS_API)
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (response?.error?.length > 0) throw response.error
|
||||
@@ -190,7 +190,7 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
|
||||
const handleReload = async () => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
const response: any = await apiClient.call("/api/v1/entities/mb_admins")
|
||||
const response: any = await apiClient.call(SYS_ADMINS_API)
|
||||
|
||||
// Handle paginated response structure: { items: [...], items_count, page, page_size, total_count }
|
||||
let updatedAdmins: Admin[] = []
|
||||
@@ -289,6 +289,7 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
|
||||
<AddItemDrawer
|
||||
table={table}
|
||||
apiClient={apiClient}
|
||||
entityCollectionPath={SYS_ADMINS_API}
|
||||
open={!!addingAdmin}
|
||||
onClose={() => setAddingAdmin(false)}
|
||||
onItemAdded={handleAdminAdded}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import type { ApiClient, Admin } from "@/lib/api"
|
||||
import { SYS_ADMINS_API, type ApiClient, type Admin } from "@/lib/api"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
interface ChangePasswordDialogProps {
|
||||
@@ -38,7 +38,7 @@ export function ChangePasswordDialog({ admin, apiClient, onClose }: ChangePasswo
|
||||
setError("")
|
||||
|
||||
try {
|
||||
const res: any = await apiClient.call(`/api/v1/entities/mb_admins/${admin.id}`, {
|
||||
const res: any = await apiClient.call(`${SYS_ADMINS_API}/${admin.id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ password: newPassword }),
|
||||
})
|
||||
|
||||
@@ -16,34 +16,76 @@ 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"
|
||||
|
||||
interface EditItemDrawerProps {
|
||||
table: TableMetadata
|
||||
apiClient: ApiClient
|
||||
/** When set, POST goes here instead of `/api/v1/entities/{schema.name}` (e.g. system admin API). */
|
||||
entityCollectionPath?: string
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onItemAdded: (item: any) => void
|
||||
}
|
||||
|
||||
export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }: EditItemDrawerProps) {
|
||||
export function AddItemDrawer({ table, apiClient, entityCollectionPath, open, onClose, onItemAdded }: 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 [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));
|
||||
@@ -80,7 +122,8 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const body = prepareRequestBody(formData, tableFields);
|
||||
const createdItem = await apiClient.call<any>(`/api/v1/entities/${table.schema.name}`, {
|
||||
const collectionUrl = entityCollectionPath ?? `/api/v1/entities/${table.schema.name}`
|
||||
const createdItem = await apiClient.call<any>(collectionUrl, {
|
||||
method: "POST",
|
||||
body: body,
|
||||
})
|
||||
@@ -107,6 +150,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 {
|
||||
@@ -197,10 +245,12 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
|
||||
}
|
||||
}
|
||||
|
||||
function formatDateForInput(value: string | Date | undefined): string {
|
||||
if (!value) return "";
|
||||
function formatDateForInput(value: string | Date | number | undefined): string {
|
||||
if (value === null || value === undefined || value === "") {
|
||||
return ""
|
||||
}
|
||||
|
||||
const date = typeof value === "string" ? new Date(value) : value;
|
||||
const date = typeof value === "string" || typeof value === "number" ? new Date(value) : value
|
||||
if (isNaN(date.getTime())) return "";
|
||||
|
||||
return date.toISOString().slice(0, 16); // "YYYY-MM-DDTHH:MM"
|
||||
@@ -239,13 +289,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">
|
||||
<Label htmlFor={field.name} className="text-sm font-medium">
|
||||
{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}
|
||||
@@ -253,7 +333,7 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
|
||||
onCheckedChange={(checked: any) => handleFieldChange(field.name, checked)}
|
||||
disabled={(field.type === "view" || isSystemGeneratedField(field))}
|
||||
/>
|
||||
<span>{formData[field.name] ? "True" : "False"}</span>
|
||||
<span>{formData[field.name] === true ? "True" : "False"}</span>
|
||||
</div>
|
||||
) : field.type === "file" ? (
|
||||
<Input
|
||||
@@ -276,7 +356,7 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
|
||||
<Input
|
||||
id={field.name}
|
||||
type="number"
|
||||
value={formData[field.name] || ""}
|
||||
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" : ""}`}
|
||||
@@ -286,7 +366,7 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
|
||||
<Input
|
||||
id={field.name}
|
||||
type="password"
|
||||
value={formData[field.name] || ""}
|
||||
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" : ""}`}
|
||||
@@ -309,7 +389,7 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
|
||||
<Input
|
||||
id={field.name}
|
||||
type="text"
|
||||
value={formData[field.name] || ""}
|
||||
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" : ""}`}
|
||||
@@ -317,7 +397,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>
|
||||
|
||||
@@ -22,17 +22,22 @@ 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"
|
||||
import { hash } from "crypto"
|
||||
import { fi } from "date-fns/locale"
|
||||
import { formatConstraintDefaultForInput, normalizeConstraintsForFieldType } from "@/lib/schema-constraints"
|
||||
|
||||
interface AddTableDialogProps {
|
||||
apiClient: ApiClient
|
||||
onTablesUpdate: (tables: TableMetadata[]) => void
|
||||
tables?: TableMetadata[] // List of existing tables for foreign key entity selection
|
||||
children?: React.ReactNode
|
||||
/** When set, drawer opens in "clone" mode with fields pre-filled from this entity */
|
||||
sourceTable?: TableMetadata | null
|
||||
/** Controlled open state (e.g. for opening from Clone action) */
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}
|
||||
|
||||
interface Field {
|
||||
@@ -50,34 +55,69 @@ interface Field {
|
||||
min_value: number | null
|
||||
validator: string | null
|
||||
}
|
||||
foreign_key?: ForeignKeyConfig // Optional foreign key configuration
|
||||
}
|
||||
|
||||
export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTableDialogProps) {
|
||||
function tableFieldToField(tf: TableField): Field {
|
||||
return {
|
||||
id: tf.id,
|
||||
name: tf.name,
|
||||
type: tf.type,
|
||||
primary_key: tf.primary_key,
|
||||
nullable: !tf.required,
|
||||
unique: tf.unique ?? false,
|
||||
system: tf.system ?? false,
|
||||
required: tf.required,
|
||||
constraints: tf.constraints ?? {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null,
|
||||
},
|
||||
foreign_key: tf.foreign_key,
|
||||
}
|
||||
}
|
||||
|
||||
export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], children, sourceTable, open: controlledOpen, onOpenChange: controlledOnOpenChange }: AddTableDialogProps) {
|
||||
const [internalOpen, setInternalOpen] = React.useState(false)
|
||||
const isControlled = controlledOpen !== undefined && controlledOnOpenChange !== undefined
|
||||
const open = isControlled ? controlledOpen : internalOpen
|
||||
const setOpen = isControlled ? controlledOnOpenChange! : setInternalOpen
|
||||
|
||||
const [tableType, setTableType] = React.useState<"base" | "auth" | "view">("base")
|
||||
const [tableName, setTableName] = React.useState("")
|
||||
const [fields, setFields] = React.useState<Field[]>([])
|
||||
const [sqlQuery, setSqlQuery] = React.useState("")
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const [draggedIndex, setDraggedIndex] = React.useState<number | null>(null)
|
||||
const [expandedFields, setExpandedFields] = React.useState<Set<string>>(new Set())
|
||||
const { toast } = useToast()
|
||||
|
||||
// Get unique key for field (use id if exists, otherwise generate one)
|
||||
const getFieldKey = (field: Field, index: number) => field.id || `temp-${index}`
|
||||
const genFieldBaseId = (name: string) => `mbf-${hash(name, "sha256").toString()}`
|
||||
|
||||
// When drawer opens, reset and add base fields
|
||||
// When drawer opens: either populate from sourceTable (clone) or reset
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
if (!open) return
|
||||
setExpandedFields(new Set())
|
||||
setIsLoading(false)
|
||||
if (sourceTable?.schema) {
|
||||
const schema = sourceTable.schema
|
||||
setTableName(`${schema.name}_copy`)
|
||||
setTableType(schema.type)
|
||||
setSqlQuery(schema.sql ?? "")
|
||||
setFields((schema.fields ?? []).map(tableFieldToField))
|
||||
} else {
|
||||
setTableName("")
|
||||
setSqlQuery("")
|
||||
setIsLoading(false)
|
||||
setTableType("base")
|
||||
setExpandedFields(new Set())
|
||||
addBaseFields()
|
||||
setFields([
|
||||
{ id: "mbf_14258576900392064537", name: "id", type: "string", primary_key: true, nullable: false, system: true, required: true, unique: false, constraints: { min_value: 6, max_value: null, default_value: null, validator: "@password" } },
|
||||
{ id: "mbf_13735287961322938256", name: "created", type: "date", primary_key: false, nullable: false, system: true, required: true, unique: false, constraints: { min_value: null, max_value: null, default_value: null, validator: null } },
|
||||
{ id: "mbf_9124719522053273721", name: "updated", type: "date", primary_key: false, nullable: false, system: true, required: true, unique: false, constraints: { min_value: null, max_value: null, default_value: null, validator: null } },
|
||||
])
|
||||
}
|
||||
}, [open])
|
||||
}, [open, sourceTable?.id])
|
||||
|
||||
function addBaseFields() {
|
||||
if (tableType === "view") {
|
||||
@@ -86,7 +126,7 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
// Add base fields
|
||||
setFields([
|
||||
{
|
||||
id: genFieldBaseId("id"),
|
||||
id: "mbf_14258576900392064537",
|
||||
name: "id",
|
||||
type: "string",
|
||||
primary_key: true,
|
||||
@@ -102,7 +142,7 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
}
|
||||
},
|
||||
{
|
||||
id: genFieldBaseId("created"),
|
||||
id: "mbf_13735287961322938256",
|
||||
name: "created",
|
||||
type: "date",
|
||||
primary_key: false,
|
||||
@@ -118,7 +158,7 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
}
|
||||
},
|
||||
{
|
||||
id: genFieldBaseId("updated"),
|
||||
id: "mbf_9124719522053273721",
|
||||
name: "updated",
|
||||
type: "date",
|
||||
primary_key: false,
|
||||
@@ -140,7 +180,7 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
setFields([
|
||||
...fields,
|
||||
{
|
||||
id: genFieldBaseId("name"),
|
||||
id: "mbf_10420554295983197538",
|
||||
name: "name",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
@@ -156,7 +196,7 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
}
|
||||
},
|
||||
{
|
||||
id: genFieldBaseId("email"),
|
||||
id: "mbf_16339674465020246541",
|
||||
name: "email",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
@@ -172,7 +212,7 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
}
|
||||
},
|
||||
{
|
||||
id: genFieldBaseId("password"),
|
||||
id: "mbf_6072375419398818283",
|
||||
name: "password",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
@@ -192,11 +232,12 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
}
|
||||
}
|
||||
|
||||
// When user changes entity type in the form, reset fields (but not when opening for clone)
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
if (open && !sourceTable) {
|
||||
addBaseFields()
|
||||
}
|
||||
}, [tableType, open])
|
||||
}, [tableType, open, sourceTable?.id])
|
||||
|
||||
const addField = () => {
|
||||
setFields([
|
||||
@@ -255,6 +296,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)
|
||||
@@ -308,79 +355,103 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
return
|
||||
}
|
||||
|
||||
// For base and auth types, require at least one user field with a name
|
||||
// For base and auth types, validate that any non-system fields have valid name and type
|
||||
if (tableType !== "view") {
|
||||
const userFields = fields.filter((f) => !f.system && f.name.trim())
|
||||
if (userFields.length === 0) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Please add at least one field with a name to the entity.",
|
||||
})
|
||||
setIsLoading(false)
|
||||
return
|
||||
const nonSystemFields = fields.filter((f) => !f.system)
|
||||
for (const field of nonSystemFields) {
|
||||
if (!field.name.trim()) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "All non-system fields must have a valid name.",
|
||||
})
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
if (!field.type || !field.type.trim()) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: `Field "${field.name || 'unnamed'}" must have a valid type selected.`,
|
||||
})
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Include all fields in order (system + user) for base/auth types
|
||||
// Include all fields in order (system + valid user fields) for base/auth types
|
||||
// For view types, fields are typically empty or derived from SQL
|
||||
const allFields = tableType === "view"
|
||||
? []
|
||||
: fields.map(
|
||||
(field): TableField => {
|
||||
const fieldData: any = {
|
||||
name: field.name,
|
||||
type: field.type,
|
||||
primary_key: field.primary_key,
|
||||
required: field.required || !field.nullable,
|
||||
unique: field.unique || false,
|
||||
system: field.system || false,
|
||||
constraints: field.constraints,
|
||||
}
|
||||
// Only include id if it exists (for existing fields being updated)
|
||||
if (field.id) {
|
||||
fieldData.id = field.id
|
||||
}
|
||||
return fieldData
|
||||
},
|
||||
)
|
||||
// Filter out non-system fields that don't have valid name and type
|
||||
const allFields: TableField[] = []
|
||||
if (tableType !== "view") {
|
||||
const candidateFields = fields.filter((field) => {
|
||||
if (field.system) return true
|
||||
return field.name.trim() && field.type && field.type.trim()
|
||||
})
|
||||
for (const field of candidateFields) {
|
||||
const normalized = normalizeConstraintsForFieldType(field.type, field.constraints)
|
||||
if (!normalized.ok) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Invalid constraints",
|
||||
description: `${field.name || "Field"}: ${normalized.message}`,
|
||||
})
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
const fieldData: any = {
|
||||
name: field.name,
|
||||
type: field.type,
|
||||
primary_key: field.primary_key,
|
||||
required: field.required,
|
||||
unique: field.unique || false,
|
||||
system: field.system || false,
|
||||
constraints: normalized.constraints,
|
||||
}
|
||||
if (field.id && field.id.startsWith("mbf_")) {
|
||||
fieldData.id = field.id
|
||||
}
|
||||
if (field.foreign_key && field.foreign_key.entity && field.foreign_key.field) {
|
||||
fieldData.foreign_key = field.foreign_key
|
||||
}
|
||||
allFields.push(fieldData)
|
||||
}
|
||||
}
|
||||
|
||||
const tableData: any = {
|
||||
name: tableName,
|
||||
has_api: true,
|
||||
system: false,
|
||||
type: tableType,
|
||||
schema: {
|
||||
id: "", // Will be generated by the API
|
||||
name: tableName,
|
||||
has_api: true,
|
||||
system: false,
|
||||
type: tableType,
|
||||
fields: allFields,
|
||||
rules: {
|
||||
add: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
delete: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
get: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
list: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
update: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
}
|
||||
fields: allFields,
|
||||
rules: {
|
||||
add: {
|
||||
expr: "",
|
||||
mode: ""
|
||||
},
|
||||
...(tableType === "view" && { sql: sqlQuery.trim() }),
|
||||
delete: {
|
||||
expr: "",
|
||||
mode: ""
|
||||
},
|
||||
get: {
|
||||
expr: "",
|
||||
mode: ""
|
||||
},
|
||||
list: {
|
||||
expr: "",
|
||||
mode: ""
|
||||
},
|
||||
update: {
|
||||
expr: "",
|
||||
mode: ""
|
||||
}
|
||||
},
|
||||
...(tableType === "view" && { sql: sqlQuery.trim() }),
|
||||
}
|
||||
|
||||
console.log(tableData)
|
||||
|
||||
const res: any = await apiClient.call("/api/v1/schemas", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(tableData),
|
||||
@@ -421,14 +492,16 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
|
||||
return (
|
||||
<Drawer open={open} onOpenChange={setOpen}>
|
||||
<DrawerTrigger asChild>
|
||||
{children || (
|
||||
<Button size="sm">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Table
|
||||
</Button>
|
||||
)}
|
||||
</DrawerTrigger>
|
||||
{!isControlled && (
|
||||
<DrawerTrigger asChild>
|
||||
{children || (
|
||||
<Button size="sm">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Table
|
||||
</Button>
|
||||
)}
|
||||
</DrawerTrigger>
|
||||
)}
|
||||
<DrawerContent side="right" className="w-full sm:w-[600px]">
|
||||
<DrawerHeader>
|
||||
<DrawerTitle>Create New Entity</DrawerTitle>
|
||||
@@ -621,7 +694,11 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
id={`min-${fieldKey}`}
|
||||
type="number"
|
||||
placeholder="Min"
|
||||
value={field.constraints.min_value || ""}
|
||||
value={
|
||||
field.constraints.min_value === null || field.constraints.min_value === undefined
|
||||
? ""
|
||||
: String(field.constraints.min_value)
|
||||
}
|
||||
onChange={(e) =>
|
||||
updateField(fieldKey, {
|
||||
constraints: {
|
||||
@@ -641,7 +718,11 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
id={`max-${fieldKey}`}
|
||||
type="number"
|
||||
placeholder="Max"
|
||||
value={field.constraints.max_value || ""}
|
||||
value={
|
||||
field.constraints.max_value === null || field.constraints.max_value === undefined
|
||||
? ""
|
||||
: String(field.constraints.max_value)
|
||||
}
|
||||
onChange={(e) =>
|
||||
updateField(fieldKey, {
|
||||
constraints: {
|
||||
@@ -661,8 +742,12 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
<Input
|
||||
id={`default-${fieldKey}`}
|
||||
placeholder="Default value"
|
||||
value={field.constraints.default_value || ""}
|
||||
onChange={(e) => updateField(fieldKey, { constraints: { ...field.constraints, default_value: e.target.value || null } })}
|
||||
value={formatConstraintDefaultForInput(field.type, field.constraints.default_value)}
|
||||
onChange={(e) =>
|
||||
updateField(fieldKey, {
|
||||
constraints: { ...field.constraints, default_value: e.target.value },
|
||||
})
|
||||
}
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
@@ -678,6 +763,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>
|
||||
)}
|
||||
@@ -710,9 +920,7 @@ export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTable
|
||||
disabled={
|
||||
isLoading ||
|
||||
!tableName.trim() ||
|
||||
(tableType === "view"
|
||||
? !sqlQuery.trim()
|
||||
: fields.filter((f) => !f.system).length === 0)
|
||||
(tableType === "view" ? !sqlQuery.trim() : false)
|
||||
}
|
||||
>
|
||||
{isLoading ? "Creating..." : "Create Entity"}
|
||||
|
||||
@@ -65,7 +65,7 @@ export function ColumnVisibilityDropdown({ table, visibleColumns, onVisibilityCh
|
||||
onCheckedChange={() => toggleColumn(field.name)}
|
||||
disabled={field.name === "id"} // Always keep ID visible
|
||||
>
|
||||
<span className="capitalize">{field.name}</span>
|
||||
<span>{field.name}</span>
|
||||
{field.name === "id" && <span className="text-xs text-muted-foreground ml-2">(required)</span>}
|
||||
</DropdownMenuCheckboxItem>
|
||||
))}
|
||||
|
||||
@@ -1,17 +1,40 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Search, Table, RefreshCw, Plus, ExternalLink, FileText, Database } from "lucide-react"
|
||||
import { Search, Table, RefreshCw, Plus, ExternalLink, FileText, Database, MoreHorizontal, Copy, Pencil, Trash2, User, LayoutDashboard } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
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"
|
||||
@@ -26,7 +49,7 @@ interface DatabaseSectionProps {
|
||||
export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseSectionProps) {
|
||||
const { route, navigate } = useRouter()
|
||||
const { toast } = useToast()
|
||||
|
||||
|
||||
// Initialize search term from query params
|
||||
const initialFilter = route.queryParams.filter || ""
|
||||
const [searchTerm, setSearchTerm] = React.useState(initialFilter)
|
||||
@@ -35,6 +58,19 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
const [isRefreshing, setIsRefreshing] = React.useState(false)
|
||||
const [docsOpen, setDocsOpen] = React.useState(false)
|
||||
|
||||
// Clone: open create-entity drawer with schema pre-filled
|
||||
const [addDrawerOpen, setAddDrawerOpen] = React.useState(false)
|
||||
const [cloneSourceTable, setCloneSourceTable] = React.useState<TableMetadata | null>(null)
|
||||
|
||||
// Rename entity dialog
|
||||
const [renameTable, setRenameTable] = React.useState<TableMetadata | null>(null)
|
||||
const [renameNewName, setRenameNewName] = React.useState("")
|
||||
const [isRenaming, setIsRenaming] = React.useState(false)
|
||||
|
||||
// Delete entity confirmation
|
||||
const [deleteTable, setDeleteTable] = React.useState<TableMetadata | null>(null)
|
||||
const [isDeleting, setIsDeleting] = React.useState(false)
|
||||
|
||||
// Sync search term with query params
|
||||
React.useEffect(() => {
|
||||
const filterFromQuery = route.queryParams.filter || ""
|
||||
@@ -65,41 +101,80 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
const filteredTables = Array.isArray(tables) ? tables?.filter((table) => table?.schema?.name?.toLowerCase().includes(searchTerm.toLowerCase())) : []
|
||||
|
||||
const handleDeleteTable = async (tableId: string) => {
|
||||
setIsDeleting(true)
|
||||
try {
|
||||
const res: any = await apiClient.call(`/api/v1/schemas/${tableId}`, { method: "DELETE" })
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (res?.error?.length > 0) throw res.error
|
||||
|
||||
// Fetch new tables
|
||||
const response: any = await apiClient.call("/api/v1/schemas")
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (response?.error?.length > 0) throw response.error
|
||||
|
||||
// Handle different response structures
|
||||
let updatedTables: TableMetadata[] = []
|
||||
if (Array.isArray(response)) {
|
||||
updatedTables = response
|
||||
} else if (response?.data && Array.isArray(response.data)) {
|
||||
updatedTables = response.data
|
||||
}
|
||||
|
||||
// Set the new tables
|
||||
onTablesUpdate(updatedTables)
|
||||
|
||||
setDeleteTable(null)
|
||||
toast({
|
||||
title: "Table Deleted",
|
||||
description: "Table deleted successfully!",
|
||||
title: "Entity deleted",
|
||||
description: "The entity has been deleted successfully.",
|
||||
duration: 3000,
|
||||
})
|
||||
} catch (error) {
|
||||
} catch (error: unknown) {
|
||||
console.error("Failed to delete table:", error)
|
||||
// toast({
|
||||
// title: "Error Deleted",
|
||||
// description: "Table deleted successfully!",
|
||||
// duration: 3000,
|
||||
// })
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: error instanceof Error ? error.message : "Failed to delete entity",
|
||||
})
|
||||
} finally {
|
||||
setIsDeleting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRenameSubmit = async () => {
|
||||
if (!renameTable || !renameNewName.trim()) return
|
||||
const trimmed = renameNewName.trim()
|
||||
if (trimmed === renameTable.schema.name) {
|
||||
setRenameTable(null)
|
||||
setRenameNewName("")
|
||||
return
|
||||
}
|
||||
setIsRenaming(true)
|
||||
try {
|
||||
const res: any = await apiClient.call(`/api/v1/schemas/${renameTable.id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ name: trimmed }),
|
||||
})
|
||||
if (res?.error?.length > 0) throw res.error
|
||||
|
||||
const response: any = await apiClient.call("/api/v1/schemas")
|
||||
if (response?.error?.length > 0) throw response.error
|
||||
|
||||
let updatedTables: TableMetadata[] = []
|
||||
if (Array.isArray(response)) {
|
||||
updatedTables = response
|
||||
} else if (response?.data && Array.isArray(response.data)) {
|
||||
updatedTables = response.data
|
||||
}
|
||||
onTablesUpdate(updatedTables)
|
||||
setRenameTable(null)
|
||||
setRenameNewName("")
|
||||
toast({
|
||||
title: "Entity renamed",
|
||||
description: `Renamed to "${trimmed}".`,
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
console.error("Failed to rename entity:", error)
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: error instanceof Error ? error.message : "Failed to rename entity",
|
||||
})
|
||||
} finally {
|
||||
setIsRenaming(false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,7 +240,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
|
||||
@@ -185,32 +260,77 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
{searchTerm ? "No entities found matching the search term" : "No entities, add some to get started"}
|
||||
</div>
|
||||
) : (
|
||||
filteredTables.map((table) => (
|
||||
<button
|
||||
filteredTables.map((table) => {
|
||||
const TypeIcon = table.schema.type === "auth" ? User : table.schema.type === "view" ? LayoutDashboard : Database
|
||||
return (
|
||||
<div
|
||||
key={table.id}
|
||||
onClick={() => handleEntityClick(table.schema.name)}
|
||||
className={cn(
|
||||
"w-full text-left p-3 rounded-lg transition-colors hover:bg-accent",
|
||||
"group grid grid-cols-[1fr_auto] items-stretch gap-0 rounded-lg transition-colors pr-2 min-w-0 overflow-hidden",
|
||||
selectedEntityName === table.schema.name && "bg-accent text-accent-foreground"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
<Table className="h-4 w-4 flex-shrink-0" />
|
||||
<span className="font-medium truncate">{table.schema.name}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleEntityClick(table.schema.name)}
|
||||
className={cn(
|
||||
"min-w-0 text-left p-3 rounded-lg transition-colors hover:bg-accent overflow-hidden",
|
||||
selectedEntityName === table.schema.name && "bg-accent text-accent-foreground"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0 overflow-hidden">
|
||||
<TypeIcon className="h-4 w-4 flex-shrink-0 text-muted-foreground" />
|
||||
<span className="font-medium truncate block min-w-0" title={table.schema.name}>
|
||||
{table.schema.name}
|
||||
</span>
|
||||
</div>
|
||||
<Badge
|
||||
variant={table.schema.type === "auth" ? "default" : table.schema.type === "view" ? "secondary" : "outline"}
|
||||
className="text-xs flex-shrink-0 ml-2"
|
||||
>
|
||||
{table.schema.type}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
{table.schema.fields?.length || 0} fields
|
||||
</div>
|
||||
</button>
|
||||
))
|
||||
<div className="text-xs text-muted-foreground mt-1 truncate">
|
||||
{table.schema.fields?.length || 0} fields
|
||||
</div>
|
||||
</button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-auto self-stretch flex-shrink-0 rounded-lg opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 px-2"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
<span className="sr-only">Entity actions</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setCloneSourceTable(table)
|
||||
setAddDrawerOpen(true)
|
||||
}}
|
||||
>
|
||||
<Copy className="h-4 w-4 mr-2" />
|
||||
Clone
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setRenameTable(table)
|
||||
setRenameNewName(table.schema.name)
|
||||
}}
|
||||
>
|
||||
<Pencil className="h-4 w-4 mr-2" />
|
||||
Rename
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onClick={() => setDeleteTable(table)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
@@ -234,6 +354,8 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
const updatedTables = tables.map((t) => (t.id === updatedTable.id ? updatedTable : t))
|
||||
onTablesUpdate(updatedTables)
|
||||
}}
|
||||
onTablesUpdate={onTablesUpdate}
|
||||
tables={tables}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
@@ -246,7 +368,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
|
||||
@@ -276,6 +398,73 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
|
||||
{/* Entity Schema API Documentation */}
|
||||
<TableDocsDrawer open={docsOpen} onClose={() => setDocsOpen(false)} />
|
||||
|
||||
{/* Clone entity: create drawer with schema pre-filled */}
|
||||
<AddTableDialog
|
||||
apiClient={apiClient}
|
||||
onTablesUpdate={onTablesUpdate}
|
||||
tables={tables}
|
||||
open={addDrawerOpen}
|
||||
onOpenChange={(open) => {
|
||||
setAddDrawerOpen(open)
|
||||
if (!open) setCloneSourceTable(null)
|
||||
}}
|
||||
sourceTable={cloneSourceTable}
|
||||
/>
|
||||
|
||||
{/* Rename entity dialog */}
|
||||
<Dialog open={!!renameTable} onOpenChange={(open) => { if (!open) { setRenameTable(null); setRenameNewName("") } }}>
|
||||
<DialogContent className="sm:max-w-md" onClick={(e) => e.stopPropagation()}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Rename entity</DialogTitle>
|
||||
<DialogDescription>
|
||||
Enter a new name for the entity. This does not affect existing data.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="rename-entity-name">New name</Label>
|
||||
<Input
|
||||
id="rename-entity-name"
|
||||
value={renameNewName}
|
||||
onChange={(e) => setRenameNewName(e.target.value)}
|
||||
placeholder="Entity name"
|
||||
onKeyDown={(e) => e.key === "Enter" && handleRenameSubmit()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => { setRenameTable(null); setRenameNewName("") }}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleRenameSubmit} disabled={!renameNewName.trim() || isRenaming}>
|
||||
{isRenaming ? "Renaming..." : "Rename"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete entity confirmation */}
|
||||
<AlertDialog open={!!deleteTable} onOpenChange={(open) => { if (!open) setDeleteTable(null) }}>
|
||||
<AlertDialogContent onClick={(e) => e.stopPropagation()}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete entity</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete the entity <strong>"{deleteTable?.schema.name}"</strong>? This action cannot be undone and will permanently delete all data associated with this entity.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
disabled={isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={() => deleteTable && handleDeleteTable(deleteTable.id)}
|
||||
>
|
||||
{isDeleting ? "Deleting..." : "Delete"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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, entityFileUrl, TableField } from "@/lib/api"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
interface EditItemDrawerProps {
|
||||
@@ -56,7 +57,7 @@ const FilePreviewField = ({
|
||||
|
||||
const getFileUrl = (file: File | string): string => {
|
||||
if (typeof file === "string") {
|
||||
return `${getApiBaseUrl()}/api/files/${table.schema.name}/${encodeURIComponent(file)}`;
|
||||
return entityFileUrl(table.schema.name, file);
|
||||
}
|
||||
return URL.createObjectURL(file); // for newly selected files
|
||||
};
|
||||
@@ -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));
|
||||
@@ -136,9 +176,9 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
const field = tableFields.find(f => f.name === key);
|
||||
if (!field) continue;
|
||||
if (!value) {
|
||||
if (value === null || value === undefined) {
|
||||
formData.append(key, "");
|
||||
continue;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (field.type === "file") {
|
||||
@@ -146,10 +186,7 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
formData.append(key, value);
|
||||
}
|
||||
} else if (field.type === "files") {
|
||||
if (!value) {
|
||||
formData.append(key, value);
|
||||
}
|
||||
else if (Array.isArray(value)) {
|
||||
if (Array.isArray(value)) {
|
||||
var files = value.filter(v => v instanceof File);
|
||||
var arr = value.filter(v => !(v instanceof File));
|
||||
files.forEach((file, idx) => {
|
||||
@@ -219,7 +256,18 @@ 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;
|
||||
if (!value) return null; // handle null or undefined values
|
||||
|
||||
// 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 === null || value === undefined) {
|
||||
return null
|
||||
}
|
||||
if (value === "") {
|
||||
return null
|
||||
}
|
||||
|
||||
const type = field.type;
|
||||
|
||||
@@ -301,10 +349,12 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
handleFieldChange(fieldName, updated);
|
||||
};
|
||||
|
||||
function formatDateForInput(value: string | Date | undefined): string {
|
||||
if (!value) return "";
|
||||
function formatDateForInput(value: string | Date | number | undefined): string {
|
||||
if (value === null || value === undefined || value === "") {
|
||||
return ""
|
||||
}
|
||||
|
||||
const date = typeof value === "string" ? new Date(value) : value;
|
||||
const date = typeof value === "string" || typeof value === "number" ? new Date(value) : value
|
||||
if (isNaN(date.getTime())) return "";
|
||||
|
||||
return date.toISOString().slice(0, 16); // "YYYY-MM-DDTHH:MM"
|
||||
@@ -334,16 +384,44 @@ 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">
|
||||
<Label htmlFor={field.name} className="text-sm font-medium capitalize">
|
||||
<Label htmlFor={field.name} className="text-sm font-medium">
|
||||
{field.name}
|
||||
{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}
|
||||
@@ -360,13 +438,13 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
onCheckedChange={(checked) => handleFieldChange(field.name, checked)}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<span>{formData[field.name] ? "True" : "False"}</span>
|
||||
<span>{formData[field.name] === true ? "True" : "False"}</span>
|
||||
</div>
|
||||
) : field.type === "date" || field.type === "datetime" || field.type === "timestamp" ? (
|
||||
<Input
|
||||
id={field.name}
|
||||
type="datetime-local"
|
||||
value={value ? formatDateForInput(value) : ""}
|
||||
value={value !== null && value !== undefined ? formatDateForInput(value) : ""}
|
||||
onChange={(e) => handleFieldChange(field.name, e.target.value)}
|
||||
disabled={isDisabled}
|
||||
className={`w-full ${isDisabled ? "bg-muted" : ""}`}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -8,7 +8,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { ApiClient, TableMetadata, getApiBaseUrl } from "@/lib/api"
|
||||
import { ApiClient, TableMetadata, entityFileUrl } from "@/lib/api"
|
||||
import { TableConfigDrawer } from "./table-config-drawer"
|
||||
import { TableRecordDocsDrawer } from "./table-records-docs-drawer"
|
||||
import { EditItemDrawer } from "./edit-item-drawer"
|
||||
@@ -22,9 +22,11 @@ interface TableDetailViewProps {
|
||||
onBack?: () => void
|
||||
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 }: 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)
|
||||
@@ -210,12 +212,14 @@ 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";
|
||||
if (value === null || value === undefined) {
|
||||
return "N/A"
|
||||
}
|
||||
|
||||
switch (field.type) {
|
||||
case "bool":
|
||||
case "boolean":
|
||||
return value ? "true" : "false";
|
||||
return value === true || value === "true" || value === 1 ? "true" : "false"
|
||||
|
||||
case "json":
|
||||
try {
|
||||
@@ -230,13 +234,15 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
|
||||
case "file":
|
||||
case "files": {
|
||||
if(!value || value==="" || value.length === 0) return "N/A";
|
||||
if (value === "" || (Array.isArray(value) && value.length === 0)) {
|
||||
return "N/A"
|
||||
}
|
||||
|
||||
const filenames = Array.isArray(value) ? value : [value];
|
||||
return (
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
{filenames.map((filename: string, i: number) => {
|
||||
const url = `${getApiBaseUrl()}/api/files/${table.schema.name}/${encodeURIComponent(filename)}`;
|
||||
const url = entityFileUrl(table.schema.name, filename);
|
||||
const ext = filename.split(".").pop()?.toLowerCase() || "";
|
||||
|
||||
const isImage = ["jpg", "jpeg", "png", "gif", "webp", "bmp", "svg"].includes(ext);
|
||||
@@ -265,7 +271,10 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
}
|
||||
|
||||
default:
|
||||
return value ? String(value) : "N/A";
|
||||
if (typeof value === "number" && Number.isNaN(value)) {
|
||||
return "N/A"
|
||||
}
|
||||
return String(value)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -370,7 +379,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
/>
|
||||
</TableHead>
|
||||
{filteredFields.map((field) => (
|
||||
<TableHead key={field.name} className="capitalize">
|
||||
<TableHead key={field.name}>
|
||||
{field.name}
|
||||
</TableHead>
|
||||
))}
|
||||
@@ -398,8 +407,10 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
/>
|
||||
</TableCell>
|
||||
{filteredFields.map((field) => (
|
||||
<TableCell key={field.name}>
|
||||
{renderCellContent(field, row[field.name])}
|
||||
<TableCell key={field.name} className="max-w-0">
|
||||
<div className="min-w-0 max-w-full line-clamp-2 break-words overflow-hidden text-ellipsis" title={typeof row[field.name] === "string" ? row[field.name] : undefined}>
|
||||
{renderCellContent(field, row[field.name])}
|
||||
</div>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
@@ -467,6 +478,8 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
open={configOpen}
|
||||
onClose={() => setConfigOpen(false)}
|
||||
onTableUpdate={onTableUpdate}
|
||||
onTablesUpdate={onTablesUpdate}
|
||||
tables={tables}
|
||||
/>
|
||||
|
||||
<TableRecordDocsDrawer table={table} open={docsOpen} onClose={() => setDocsOpen(false)} />
|
||||
|
||||
@@ -9,6 +9,7 @@ import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } f
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import type { TableMetadata } from "@/lib/api"
|
||||
import { getApiBaseUrl } from "@/lib/api"
|
||||
|
||||
interface TableDocsDrawerProps {
|
||||
open: boolean
|
||||
@@ -124,7 +125,7 @@ function ApiEndpointCard({
|
||||
}
|
||||
|
||||
const generateRequestExample = () => {
|
||||
const baseUrl = "{{MANTISBASE_BASE_URL}}"
|
||||
const baseUrl = getApiBaseUrl()
|
||||
let example = `curl -X ${method} "${baseUrl}${endpoint}"`
|
||||
|
||||
example += ` \\\n -H "Content-Type: application/json"`
|
||||
|
||||
@@ -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"
|
||||
@@ -9,6 +9,7 @@ import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } f
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import type { TableMetadata } from "@/lib/api"
|
||||
import { getApiBaseUrl } from "@/lib/api"
|
||||
|
||||
interface TableDocsDrawerProps {
|
||||
table: TableMetadata
|
||||
@@ -84,6 +85,8 @@ export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerP
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<RealtimeDocCard table={table} />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
@@ -92,6 +95,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 = getApiBaseUrl()
|
||||
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,
|
||||
@@ -127,7 +245,7 @@ function ApiEndpointCard({
|
||||
}
|
||||
|
||||
const generateRequestExample = () => {
|
||||
const baseUrl = "https://your-api.com"
|
||||
const baseUrl = getApiBaseUrl()
|
||||
let example = `curl -X ${method} "${baseUrl}${endpoint}"`
|
||||
|
||||
if (method !== "GET") {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Eye, EyeOff, Shield } from "lucide-react"
|
||||
import { Eye, EyeOff, Info } from "lucide-react"
|
||||
import { Logo } from "./logo"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
@@ -10,13 +11,24 @@ import { Label } from "@/components/ui/label"
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import { loginWithPassword } from "@/lib/api"
|
||||
|
||||
const DEMO_EMAIL = "test@test.com"
|
||||
const DEMO_PASSWORD = "123456789"
|
||||
|
||||
function isDemoMode(): boolean {
|
||||
if (typeof window === "undefined") {
|
||||
return process.env.NEXT_PUBLIC_MB_IS_DEMO_MODE === "true" || process.env.NEXT_PUBLIC_MB_IS_DEMO_MODE === "1"
|
||||
}
|
||||
return process.env.NEXT_PUBLIC_MB_IS_DEMO_MODE === "true" || process.env.NEXT_PUBLIC_MB_IS_DEMO_MODE === "1"
|
||||
}
|
||||
|
||||
interface LoginFormProps {
|
||||
onLogin: (token: string) => void
|
||||
}
|
||||
|
||||
export function LoginForm({ onLogin }: LoginFormProps) {
|
||||
const [email, setEmail] = React.useState("")
|
||||
const [password, setPassword] = React.useState("")
|
||||
const isDemo = isDemoMode()
|
||||
const [email, setEmail] = React.useState(isDemo ? DEMO_EMAIL : "")
|
||||
const [password, setPassword] = React.useState(isDemo ? DEMO_PASSWORD : "")
|
||||
const [showPassword, setShowPassword] = React.useState(false)
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [error, setError] = React.useState("")
|
||||
@@ -38,11 +50,20 @@ export function LoginForm({ onLogin }: LoginFormProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-background">
|
||||
<div className="min-h-screen flex flex-col bg-background">
|
||||
{isDemo && (
|
||||
<Alert className="rounded-none border-x-0 border-t-0 bg-amber-500/10 text-amber-900 dark:bg-amber-500/10 dark:text-amber-200 border-amber-500/30">
|
||||
<Info className="h-4 w-4" />
|
||||
<AlertDescription className="font-medium">
|
||||
This is a demo site. Data is cleared every 30 minutes. Default login: {DEMO_EMAIL} / {DEMO_PASSWORD}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<div className="flex-1 flex items-center justify-center p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<Shield className="h-12 w-12 text-primary" />
|
||||
<Logo className="h-12 w-12 text-primary" size={48} />
|
||||
</div>
|
||||
<CardTitle className="text-2xl">Mantis Admin</CardTitle>
|
||||
<CardDescription>Sign in to access the admin dashboard</CardDescription>
|
||||
@@ -97,6 +118,7 @@ export function LoginForm({ onLogin }: LoginFormProps) {
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
49
components/logo.tsx
Normal file
49
components/logo.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
interface LogoProps {
|
||||
className?: string
|
||||
size?: number
|
||||
}
|
||||
|
||||
export function Logo({ className, size = 40 }: LogoProps) {
|
||||
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 40.018326 43.557034"
|
||||
className={cn("transition-colors", className)}
|
||||
fill="currentColor"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<g transform="translate(-76.752395,-70.247194)">
|
||||
<g transform="matrix(0.35277778,0,0,0.35277778,27.80232,86.453883)">
|
||||
<g
|
||||
clipPath="url(#5346413700)"
|
||||
transform="translate(138.6038,-57.494913)"
|
||||
style={{ fill: "currentColor" }}
|
||||
>
|
||||
<path
|
||||
d="m 106.50391,11.554688 c -6.05469,0.04297 -14.179691,10.277343 -21.875004,27.5625 -1.28125,2.878906 -2.332031,5.316406 -2.332031,5.414062 0,0.542969 0.507813,-0.109375 2.09375,-2.699219 2.585937,-4.226562 9.738281,-11.082031 15.195313,-14.558593 10.179692,-6.492188 11.945312,-7.71875 12.808592,-8.90625 0.80469,-1.101563 0.83594,-1.398438 0.29297,-2.710938 -0.75,-1.804688 -4.23047,-4.117188 -6.18359,-4.101562 z m -99.199222,0.09375 c -0.417969,-0.01172 -0.824219,0.01953 -1.222657,0.09375 -2.214843,0.414062 -5.316406,3.375 -5.316406,5.074218 0,1.722656 1.6875,3.203125 8.199219,7.195313 2.964844,1.820312 6.773437,4.328125 8.460937,5.570312 4.101563,3.019531 10.363281,9.683594 12.359375,13.152344 0.886719,1.539063 1.6875,2.730469 1.773438,2.648437 0.08984,-0.08203 -0.914063,-2.601562 -2.230469,-5.59375 C 21.503906,21.996094 13.535156,11.859375 7.304688,11.648438 Z m 9.121093,34.699218 C 12.449219,46.324219 11.773438,46.453125 9,47.769531 2.671875,50.765625 0.144531,54.5625 0.152344,61.0625 c 0.019531,11.21875 8.820312,22.660156 20.476562,26.621094 0.476563,0.160156 0.867188,1.039062 1.074219,2.414062 1.042969,6.945313 4.808594,14.824224 9.351563,19.542974 l 3.339843,3.47265 -0.757812,3.1211 c -1.0625,4.3789 -0.671875,9.55078 0.96875,12.83984 1.136719,2.27344 4.152343,5.91797 4.898437,5.91797 0.175782,0 0.113282,-0.87891 -0.132812,-1.95703 -0.742188,-3.23047 -0.277344,-10.46094 0.796875,-12.29688 0.5,-0.85937 1.128906,-1.63672 1.394531,-1.72265 0.265625,-0.0898 0.933594,0.64062 1.484375,1.625 1.378906,2.44921 4.738281,5.44531 7.609375,6.78125 2.859375,1.33203 8.238281,1.53906 11.367188,0.43359 2.898437,-1.02344 6.117187,-3.58984 8.085937,-6.44531 0.960937,-1.39844 1.933594,-2.53907 2.15625,-2.53907 0.226563,0 0.859375,0.98438 1.40625,2.1875 1.070313,2.34766 1.386719,8.00782 0.671875,11.99219 l -0.351562,1.97266 1.082031,-0.70703 c 1.464843,-0.96094 3.859375,-4.36719 4.769531,-6.78516 0.972656,-2.58984 0.964844,-9.46094 -0.01172,-12.54687 -0.703125,-2.21875 -0.695312,-2.28907 0.296875,-2.95313 4.992188,-3.34375 10.484375,-13.671875 12.097656,-22.753906 0.179688,-1.019532 0.570313,-1.730469 0.945313,-1.730469 1.3125,0 6.492187,-2.796875 9.152346,-4.941406 11.87109,-9.570313 15.03906,-26.179688 6.23047,-32.671875 -3.58203,-2.636719 -6.55078,-3.554688 -11.515629,-3.554688 -4.9375,0 -7.9375,0.910156 -11.984374,3.632813 l -2.300782,1.546875 -2.875,-1.292969 c -6.164062,-2.773437 -8.011718,-3.011719 -23.144531,-3.019531 -12.996094,0 -14.035156,0.05859 -17.417969,1.039062 -1.976562,0.574219 -4.617187,1.558594 -5.859375,2.191406 L 31.191406,51.625 28.574219,49.949219 C 24.332031,47.234375 21.4375,46.375 16.425781,46.347656 Z m 81.507813,3.996094 c 4.492186,0.02734 9.109376,1.824219 10.648436,4.3125 3.35938,5.441406 0.0195,16.671875 -7.08984,23.820312 -4.656252,4.683594 -10.949221,7.691407 -16.089846,7.691407 -1.558594,0 -1.621094,-0.07031 -2.320313,-2.648438 -2.726562,-10.050781 -2.640625,-18.355469 0.25,-24.683593 2.289063,-5.003907 6.328125,-7.675782 12.691407,-8.394532 0.628906,-0.07031 1.269531,-0.101562 1.910156,-0.09766 z m -81.160156,0.0625 c 0.675781,0.03516 1.34375,0.109375 2.003906,0.226562 4.390625,0.769532 8.398437,2.910157 10.113281,5.398438 2.839844,4.128906 3.402344,6.542969 3.367187,14.472656 -0.02734,6.003906 -0.210937,7.800782 -1.136718,11.285156 L 30.015625,85.9375 28.175781,86.03125 C 27.160156,86.085938 25.21875,85.824219 23.855469,85.449219 15.117188,83.0625 7.386719,75.117188 4.675781,65.734375 3.597656,62 3.855469,56.324219 5.1875,54.53125 c 2.007812,-2.710938 6.871094,-4.371094 11.585938,-4.125 z m 40.390624,1.222656 c 13.476563,0.0078 18.050782,0.535156 19.800782,2.285156 1.011718,1.011719 0.953125,1.398438 -1.082032,7.011719 -0.898437,2.484375 -0.914062,2.800781 -0.269531,5.859375 0.65625,3.136719 0.558594,5.371094 -0.320312,7.085938 -0.234375,0.457031 -2.089844,2.632812 -4.121094,4.835937 C 64.328125,86.121094 60.019531,92.335938 57.070312,99.0625 56.71875,99.867188 56.554688,99.976562 56.535156,99.429688 56.476562,98.03125 52.625,91.058594 49.953125,87.527344 48.527344,85.640625 45.28125,81.761719 42.738281,78.914062 37.785156,73.355469 37.222656,72.171875 37.816406,68.519531 38.675781,63.203125 38.65625,62.386719 37.621094,60.09375 37.0625,58.855469 36.421875,57.242188 36.203125,56.511719 35.015625,52.5625 39.082031,51.617188 57.164062,51.628906 Z M 47.023438,107.79297 c 0.847656,-0.0312 2.066406,0.66797 3.304687,1.98047 3.746094,3.96875 3.710937,4.27734 -0.273437,2.21484 -2.8125,-1.45312 -4.394532,-2.93359 -3.933594,-3.68359 0.203125,-0.32813 0.515625,-0.4961 0.902344,-0.51172 z m 19.289062,0.0234 c 2.121094,0 1.578125,1.55859 -1.125,3.22265 -2.78125,1.71094 -4.539062,2.44141 -4.539062,1.88672 0,-0.21875 0.996093,-1.45703 2.210937,-2.7539 1.601563,-1.70704 2.554687,-2.35547 3.453125,-2.35547 z m 0,0"
|
||||
fill="currentColor"
|
||||
fillOpacity="1"
|
||||
fillRule="nonzero"
|
||||
/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="5346413700">
|
||||
<path
|
||||
d="M 0.0742188,11.554688 H 113.92578 V 135.14062 H 0.0742188 Z m 0,0"
|
||||
clipRule="nonzero"
|
||||
/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { AlertTriangle } from "lucide-react"
|
||||
import { LoginForm } from "@/components/login-form"
|
||||
import { SetupForm } from "@/components/setup-form"
|
||||
import { AdminDashboard } from "@/components/admin-dashboard"
|
||||
@@ -8,6 +9,9 @@ import { Toaster } from "@/components/ui/toaster"
|
||||
import { ThemeProvider } from "@/components/theme-provider"
|
||||
import { AppStateProvider } from "@/lib/app-state"
|
||||
import { useRouter } from "@/lib/router"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
|
||||
import { Logo } from "./logo"
|
||||
|
||||
export default function MainPage() {
|
||||
const [token, setToken] = React.useState<string | null>(null)
|
||||
@@ -91,6 +95,38 @@ export default function MainPage() {
|
||||
const isSetupRoute = route.path === "/setup"
|
||||
const setupToken = route.queryParams.token
|
||||
|
||||
// Show error if on setup route but no token provided
|
||||
if (isSetupRoute && !setupToken) {
|
||||
return (
|
||||
<ThemeProvider attribute="class" defaultTheme="dark" enableSystem storageKey="mantis-admin-theme" disableTransitionOnChange>
|
||||
<AppStateProvider>
|
||||
<div className="min-h-screen flex items-center justify-center bg-background">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<Logo className="h-12 w-12 text-primary" size={48} />
|
||||
</div>
|
||||
<CardTitle className="text-2xl">Setup Access Required</CardTitle>
|
||||
<CardDescription>An access token is required to access the setup page</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertTitle>Missing Access Token</AlertTitle>
|
||||
<AlertDescription>
|
||||
This page requires an access token to be provided via the query parameter.
|
||||
Please ensure you have a valid setup token in the URL (e.g., /setup?token=your-token-here).
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<Toaster />
|
||||
</AppStateProvider>
|
||||
</ThemeProvider>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemeProvider attribute="class" defaultTheme="dark" enableSystem storageKey="mantis-admin-theme" disableTransitionOnChange>
|
||||
<AppStateProvider>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import type { ApiClient, AppSettings } from "@/lib/api"
|
||||
import { SYS_SETTINGS_API, type ApiClient, type AppSettings } from "@/lib/api"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { useAppState, type AppMode } from "@/lib/app-state"
|
||||
|
||||
@@ -108,7 +108,7 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
|
||||
setIsLoading({ ...isLoading, [cardType]: true })
|
||||
try {
|
||||
const updatedSettings = await apiClient.call<AppSettings>("/api/v1/settings/config", {
|
||||
const updatedSettings = await apiClient.call<AppSettings>(SYS_SETTINGS_API, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(formData),
|
||||
})
|
||||
@@ -141,7 +141,7 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
const handleRefresh = async () => {
|
||||
setIsRefreshing(true)
|
||||
try {
|
||||
const updatedSettings = await apiClient.call<AppSettings>("/api/v1/settings/config")
|
||||
const updatedSettings = await apiClient.call<AppSettings>(SYS_SETTINGS_API)
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (updatedSettings?.error?.length > 0) throw updatedSettings.error
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Eye, EyeOff, Shield, CheckCircle2 } from "lucide-react"
|
||||
import { Eye, EyeOff, CheckCircle2 } from "lucide-react"
|
||||
import { Logo } from "./logo"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import { ApiClient } from "@/lib/api"
|
||||
import { ApiClient, SYS_ADMINS_SETUP_API } from "@/lib/api"
|
||||
import { useAppState } from "@/lib/app-state"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
@@ -56,7 +57,7 @@ export function SetupForm({ token, onSetupComplete }: SetupFormProps) {
|
||||
|
||||
try {
|
||||
// Create admin account using the setup token
|
||||
const response: any = await apiClient.call("/api/v1/entities/mb_admins", {
|
||||
const response: any = await apiClient.call(SYS_ADMINS_SETUP_API, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
@@ -64,10 +65,12 @@ export function SetupForm({ token, onSetupComplete }: SetupFormProps) {
|
||||
}),
|
||||
})
|
||||
|
||||
if (response?.error?.length > 0) {
|
||||
// Check if response has an error field (ApiClient may return error in catch block)
|
||||
if (response?.error && response.error.length > 0) {
|
||||
throw new Error(response.error)
|
||||
}
|
||||
|
||||
// If we get here, the account was created successfully
|
||||
setSuccess(true)
|
||||
toast({
|
||||
title: "Account Created",
|
||||
@@ -79,7 +82,10 @@ export function SetupForm({ token, onSetupComplete }: SetupFormProps) {
|
||||
onSetupComplete()
|
||||
}, 2000)
|
||||
} catch (err: any) {
|
||||
setError(err.message || "Failed to create admin account")
|
||||
// Handle API errors - ApiClient throws errors for failed requests
|
||||
const errorMessage = err.message || "Failed to create admin account"
|
||||
setError(errorMessage)
|
||||
console.error("Setup error:", err)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
@@ -90,7 +96,7 @@ export function SetupForm({ token, onSetupComplete }: SetupFormProps) {
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<Shield className="h-12 w-12 text-primary" />
|
||||
<Logo className="h-12 w-12 text-primary" size={48} />
|
||||
</div>
|
||||
<CardTitle className="text-2xl">Setup Admin Account</CardTitle>
|
||||
<CardDescription>Create your first admin account to get started</CardDescription>
|
||||
|
||||
45
lib/api.ts
45
lib/api.ts
@@ -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 {
|
||||
@@ -60,22 +68,39 @@ export interface Admin {
|
||||
updated: string
|
||||
}
|
||||
|
||||
export function getApiBaseUrl(): string {
|
||||
/** System admin REST API (list, CRUD). Login: `${SYS_ADMINS_API}/login`. */
|
||||
export const SYS_ADMINS_API = "/api/v1/sys/admins" as const
|
||||
|
||||
const mode = process?.env?.NODE_ENV || "production";
|
||||
const port = process?.env?.MANTIS_PORT || 7070;
|
||||
/** Initial admin setup (one-time, requires setup token). */
|
||||
export const SYS_ADMINS_SETUP_API = "/api/v1/sys/admins/setup" as const
|
||||
|
||||
/** System settings config endpoint. */
|
||||
export const SYS_SETTINGS_API = "/api/v1/sys/settings/config" as const
|
||||
|
||||
/** Build a file download URL for an entity record attachment. */
|
||||
export function entityFileUrl(entity: string, filename: string): string {
|
||||
return `${getApiBaseUrl()}/api/v1/files/${entity}/${encodeURIComponent(filename)}`
|
||||
}
|
||||
|
||||
/** Backend API base URL. Override with NEXT_PUBLIC_MANTIS_BASE_URL (e.g. https://api.example.com) to use an external backend. */
|
||||
export function getApiBaseUrl(): string {
|
||||
const override = process.env.NEXT_PUBLIC_MANTIS_BASE_URL
|
||||
if (override !== undefined && override !== "") {
|
||||
return override.replace(/\/+$/, "")
|
||||
}
|
||||
|
||||
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}`;
|
||||
return `http://localhost:${port}`
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
const { origin } = window.location;
|
||||
return `${origin}`;
|
||||
return window.location.origin
|
||||
}
|
||||
|
||||
return `http://localhost:${port}`;
|
||||
return `http://localhost:${port}`
|
||||
}
|
||||
|
||||
export interface AppSettings {
|
||||
@@ -223,15 +248,13 @@ export async function loginWithPassword(
|
||||
email: string,
|
||||
password: string
|
||||
): Promise<LoginResponse> {
|
||||
// Real API call to /api/v1/auth/login
|
||||
try {
|
||||
const response = await fetch(`${getApiBaseUrl()}/api/v1/auth/login`, {
|
||||
const response = await fetch(`${getApiBaseUrl()}${SYS_ADMINS_API}/login`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
identity: email,
|
||||
password: password,
|
||||
entity: "mb_admins"
|
||||
}),
|
||||
})
|
||||
|
||||
|
||||
@@ -17,29 +17,31 @@ const ROUTE_CHANGE_EVENT = "custom-route-change"
|
||||
|
||||
let currentRoute: ParsedRoute = { path: "/entities", pathParams: {}, queryParams: {} }
|
||||
|
||||
// Get the base path for the application
|
||||
// In production, this should be '/mb-admin', in development it might be empty
|
||||
// Resolve default base path when env is not set (shared for server and client fallback)
|
||||
function getDefaultBasePath(): string {
|
||||
return process.env.NODE_ENV === "production" ? "/mb" : ""
|
||||
}
|
||||
|
||||
// Get the base path for the application. Env var overrides for both build and runtime; empty string = no base path.
|
||||
export function getBasePath(): string {
|
||||
if (typeof window === "undefined") {
|
||||
// Server-side: use env var or default to /mb-admin for production
|
||||
return process.env.NEXT_PUBLIC_BASE_PATH || (process.env.NODE_ENV === 'production' ? '/mb-admin' : '')
|
||||
return typeof process.env.NEXT_PUBLIC_BASE_PATH !== "undefined"
|
||||
? process.env.NEXT_PUBLIC_BASE_PATH
|
||||
: getDefaultBasePath()
|
||||
}
|
||||
|
||||
// Client-side: try to detect base path from current location
|
||||
// If we're at /mb-admin/*, the base path is /mb-admin
|
||||
|
||||
// Client-side: env var wins when set (including empty string)
|
||||
if (typeof process.env.NEXT_PUBLIC_BASE_PATH !== "undefined") {
|
||||
return process.env.NEXT_PUBLIC_BASE_PATH
|
||||
}
|
||||
|
||||
// Infer from current location when env not set: if we're under /mb, use /mb
|
||||
const pathname = window.location.pathname
|
||||
if (pathname.startsWith("/mb-admin")) {
|
||||
return "/mb-admin"
|
||||
if (pathname === "/mb" || pathname.startsWith("/mb/")) {
|
||||
return "/mb"
|
||||
}
|
||||
|
||||
// Fallback: check if we're in production mode
|
||||
// In development, base path might be empty
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
return process.env.NEXT_PUBLIC_BASE_PATH || "/mb-admin"
|
||||
}
|
||||
|
||||
// Development: no base path
|
||||
return process.env.NEXT_PUBLIC_BASE_PATH || ""
|
||||
|
||||
return getDefaultBasePath()
|
||||
}
|
||||
|
||||
// Strip base path from a full pathname
|
||||
|
||||
245
lib/schema-constraints.ts
Normal file
245
lib/schema-constraints.ts
Normal file
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* Normalize and validate field `constraints` when creating/updating entity schemas.
|
||||
* Aligns with runtime entity value casting in add-item-drawer / edit-item-drawer.
|
||||
*/
|
||||
|
||||
import type { FieldConstraints } from "@/lib/api"
|
||||
|
||||
const INTEGER_TYPES = new Set([
|
||||
"int8",
|
||||
"int16",
|
||||
"int32",
|
||||
"int64",
|
||||
"uint8",
|
||||
"uint16",
|
||||
"uint32",
|
||||
"uint64",
|
||||
])
|
||||
|
||||
const NUMERIC_TYPES = new Set([
|
||||
...INTEGER_TYPES,
|
||||
"double",
|
||||
])
|
||||
|
||||
export interface RawConstraintsInput {
|
||||
default_value: unknown
|
||||
min_value: unknown
|
||||
max_value: unknown
|
||||
validator: string | null
|
||||
}
|
||||
|
||||
export type ConstraintsNormalizeResult =
|
||||
| { ok: true; constraints: FieldConstraints }
|
||||
| { ok: false; message: string }
|
||||
|
||||
/**
|
||||
* Coerce min/max bounds from UI or API into a finite number or null.
|
||||
*/
|
||||
export function normalizeConstraintBound(value: unknown): { ok: true; value: number | null } | { ok: false; message: string } {
|
||||
if (value === null || value === undefined || value === "") {
|
||||
return { ok: true, value: null }
|
||||
}
|
||||
if (typeof value === "number") {
|
||||
if (!Number.isFinite(value)) {
|
||||
return { ok: false, message: "Min/max must be valid numbers." }
|
||||
}
|
||||
return { ok: true, value }
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
const t = value.trim()
|
||||
if (t === "") {
|
||||
return { ok: true, value: null }
|
||||
}
|
||||
const n = Number.parseFloat(t)
|
||||
if (!Number.isFinite(n)) {
|
||||
return { ok: false, message: "Min/max must be valid numbers." }
|
||||
}
|
||||
return { ok: true, value: n }
|
||||
}
|
||||
return { ok: false, message: "Min/max must be numbers or empty." }
|
||||
}
|
||||
|
||||
function validateMinMaxOrder(min: number | null, max: number | null): string | null {
|
||||
if (min !== null && max !== null && min > max) {
|
||||
return "Min value cannot be greater than max value."
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function parseDefaultValue(fieldType: string, raw: unknown): { ok: true; value: unknown } | { ok: false; message: string } {
|
||||
if (raw === null || raw === undefined) {
|
||||
return { ok: true, value: null }
|
||||
}
|
||||
|
||||
if (typeof raw === "string") {
|
||||
const t = raw.trim()
|
||||
if (t === "") {
|
||||
return { ok: true, value: null }
|
||||
}
|
||||
}
|
||||
|
||||
switch (fieldType) {
|
||||
case "string":
|
||||
case "xml": {
|
||||
return { ok: true, value: typeof raw === "string" ? raw : String(raw) }
|
||||
}
|
||||
|
||||
case "int8":
|
||||
case "int16":
|
||||
case "int32":
|
||||
case "int64":
|
||||
case "uint8":
|
||||
case "uint16":
|
||||
case "uint32":
|
||||
case "uint64": {
|
||||
const n = typeof raw === "number" ? raw : Number.parseFloat(String(raw).trim())
|
||||
if (!Number.isFinite(n)) {
|
||||
return { ok: false, message: "Default value must be a valid number for integer fields." }
|
||||
}
|
||||
if (!Number.isInteger(n)) {
|
||||
return { ok: false, message: "Default value must be an integer for this field type." }
|
||||
}
|
||||
if (fieldType.startsWith("uint") && n < 0) {
|
||||
return { ok: false, message: "Default value must be non-negative for unsigned integer fields." }
|
||||
}
|
||||
return { ok: true, value: n }
|
||||
}
|
||||
|
||||
case "double": {
|
||||
const n = typeof raw === "number" ? raw : Number.parseFloat(String(raw).trim())
|
||||
if (!Number.isFinite(n)) {
|
||||
return { ok: false, message: "Default value must be a valid number." }
|
||||
}
|
||||
return { ok: true, value: n }
|
||||
}
|
||||
|
||||
case "bool": {
|
||||
if (typeof raw === "boolean") {
|
||||
return { ok: true, value: raw }
|
||||
}
|
||||
const s = String(raw).trim().toLowerCase()
|
||||
if (s === "true" || s === "1") {
|
||||
return { ok: true, value: true }
|
||||
}
|
||||
if (s === "false" || s === "0") {
|
||||
return { ok: true, value: false }
|
||||
}
|
||||
return { ok: false, message: 'Default value must be "true" or "false" for boolean fields.' }
|
||||
}
|
||||
|
||||
case "json": {
|
||||
if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) {
|
||||
return { ok: true, value: raw }
|
||||
}
|
||||
if (Array.isArray(raw)) {
|
||||
return { ok: true, value: raw }
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(String(raw).trim())
|
||||
return { ok: true, value: parsed }
|
||||
} catch {
|
||||
return { ok: false, message: "Default value must be valid JSON." }
|
||||
}
|
||||
}
|
||||
|
||||
case "date": {
|
||||
if (raw instanceof Date) {
|
||||
return isNaN(raw.getTime())
|
||||
? { ok: false, message: "Default value must be a valid date." }
|
||||
: { ok: true, value: raw.toISOString() }
|
||||
}
|
||||
const d = new Date(String(raw).trim())
|
||||
if (isNaN(d.getTime())) {
|
||||
return { ok: false, message: "Default value must be a valid date." }
|
||||
}
|
||||
return { ok: true, value: d.toISOString() }
|
||||
}
|
||||
|
||||
case "file":
|
||||
case "files": {
|
||||
const v = raw === null || raw === undefined ? null : String(raw).trim()
|
||||
return { ok: true, value: v === "" ? null : v }
|
||||
}
|
||||
|
||||
default:
|
||||
return { ok: true, value: raw }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a constraint default for a text input (handles 0, false, JSON objects).
|
||||
*/
|
||||
export function formatConstraintDefaultForInput(fieldType: string, value: unknown): string {
|
||||
if (value === null || value === undefined) {
|
||||
return ""
|
||||
}
|
||||
if (fieldType === "json" && (typeof value === "object" || Array.isArray(value))) {
|
||||
try {
|
||||
return JSON.stringify(value)
|
||||
} catch {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
if (typeof value === "boolean") {
|
||||
return value ? "true" : "false"
|
||||
}
|
||||
return String(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and cast constraints for the schema API from raw UI/API state.
|
||||
*/
|
||||
export function normalizeConstraintsForFieldType(
|
||||
fieldType: string,
|
||||
input: RawConstraintsInput,
|
||||
): ConstraintsNormalizeResult {
|
||||
const minR = normalizeConstraintBound(input.min_value)
|
||||
if (!minR.ok) {
|
||||
return { ok: false, message: minR.message }
|
||||
}
|
||||
const maxR = normalizeConstraintBound(input.max_value)
|
||||
if (!maxR.ok) {
|
||||
return { ok: false, message: maxR.message }
|
||||
}
|
||||
|
||||
const orderErr = validateMinMaxOrder(minR.value, maxR.value)
|
||||
if (orderErr) {
|
||||
return { ok: false, message: orderErr }
|
||||
}
|
||||
|
||||
if (NUMERIC_TYPES.has(fieldType)) {
|
||||
const minInt = minR.value !== null && INTEGER_TYPES.has(fieldType) && !Number.isInteger(minR.value)
|
||||
const maxInt = maxR.value !== null && INTEGER_TYPES.has(fieldType) && !Number.isInteger(maxR.value)
|
||||
if (minInt || maxInt) {
|
||||
return { ok: false, message: "Min/max for integer types must be whole numbers." }
|
||||
}
|
||||
if (fieldType.startsWith("uint")) {
|
||||
if (minR.value !== null && minR.value < 0) {
|
||||
return { ok: false, message: "Min cannot be negative for unsigned integer fields." }
|
||||
}
|
||||
if (maxR.value !== null && maxR.value < 0) {
|
||||
return { ok: false, message: "Max cannot be negative for unsigned integer fields." }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const defR = parseDefaultValue(fieldType, input.default_value)
|
||||
if (!defR.ok) {
|
||||
return { ok: false, message: defR.message }
|
||||
}
|
||||
|
||||
const validator =
|
||||
input.validator === null || input.validator === undefined || input.validator === ""
|
||||
? null
|
||||
: String(input.validator)
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
constraints: {
|
||||
default_value: defR.value,
|
||||
min_value: minR.value,
|
||||
max_value: maxR.value,
|
||||
validator,
|
||||
},
|
||||
}
|
||||
}
|
||||
BIN
mantisbase-admin.png
Normal file
BIN
mantisbase-admin.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 511 KiB |
@@ -4,8 +4,12 @@ const { version } = require('./package.json');
|
||||
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
// Use basePath in production, or if explicitly set via env var
|
||||
basePath: process.env.NEXT_PUBLIC_BASE_PATH || (process.env.NODE_ENV === 'production' ? '/mb-admin' : ''),
|
||||
// Env var overrides for both build and runtime: empty string = no base path
|
||||
basePath: typeof process.env.NEXT_PUBLIC_BASE_PATH !== "undefined"
|
||||
? process.env.NEXT_PUBLIC_BASE_PATH
|
||||
: process.env.NODE_ENV === "production"
|
||||
? "/mb"
|
||||
: "",
|
||||
env: {
|
||||
MANTIS_ADMIN_VERSION: version,
|
||||
},
|
||||
|
||||
20
package-lock.json
generated
20
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "mantis-admin",
|
||||
"version": "0.3.0",
|
||||
"name": "mantisbase-admin",
|
||||
"version": "0.3.9",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "mantis-admin",
|
||||
"version": "0.3.0",
|
||||
"name": "mantisbase-admin",
|
||||
"version": "0.3.9",
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^3.9.1",
|
||||
"@radix-ui/react-accordion": "1.2.2",
|
||||
@@ -3132,6 +3132,7 @@
|
||||
"integrity": "sha512-/LDXMQh55EzZQ0uVAZmKKhfENivEvWz6E+EYzh+/MCjMhNsotd+ZHhBGIjFDTi6+fz0OhQQQLbTgdQIxxCsC0w==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/prop-types": "*",
|
||||
"csstype": "^3.0.2"
|
||||
@@ -3143,6 +3144,7 @@
|
||||
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"peerDependencies": {
|
||||
"@types/react": "^18.0.0"
|
||||
}
|
||||
@@ -3303,6 +3305,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"caniuse-lite": "^1.0.30001726",
|
||||
"electron-to-chromium": "^1.5.173",
|
||||
@@ -3645,6 +3648,7 @@
|
||||
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.30.0.tgz",
|
||||
"integrity": "sha512-fnULvOpxnC5/Vg3NCiWelDsLiUc9bRwAPs/+LfTLNvetFCtCTN+yQz15C/fs4AwX1R9K5GLtLfn8QW+dWisaAw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.21.0"
|
||||
},
|
||||
@@ -3716,7 +3720,8 @@
|
||||
"version": "8.5.1",
|
||||
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.5.1.tgz",
|
||||
"integrity": "sha512-JUb5+FOHobSiWQ2EJNaueCNT/cQU9L6XWBbWmorWPQT9bkbk+fhsuLr8wWrzXKagO3oWszBO7MSx+GfaRk4E6A==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/embla-carousel-react": {
|
||||
"version": "8.5.1",
|
||||
@@ -4404,6 +4409,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.11",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -4535,6 +4541,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
|
||||
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0"
|
||||
},
|
||||
@@ -4561,6 +4568,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
|
||||
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"scheduler": "^0.23.2"
|
||||
@@ -4574,6 +4582,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.58.1.tgz",
|
||||
"integrity": "sha512-Lml/KZYEEFfPhUVgE0RdCVpnC4yhW+PndRhbiTtdvSlQTL8IfVR+iQkBjLIvmmc6+GGoVeM11z37ktKFPAb0FA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
@@ -5109,6 +5118,7 @@
|
||||
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz",
|
||||
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@alloc/quick-lru": "^5.2.0",
|
||||
"arg": "^5.0.2",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mantis-admin",
|
||||
"version": "0.3.0",
|
||||
"name": "mantisbase-admin",
|
||||
"version": "0.3.9",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"export": "next build && next export",
|
||||
|
||||
51
public/mantisbase.svg
Normal file
51
public/mantisbase.svg
Normal file
@@ -0,0 +1,51 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
width="40.018326mm"
|
||||
height="43.557034mm"
|
||||
viewBox="0 0 40.018326 43.557034"
|
||||
version="1.1"
|
||||
id="svg1"
|
||||
xml:space="preserve"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"><sodipodi:namedview
|
||||
id="namedview1"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#000000"
|
||||
borderopacity="0.25"
|
||||
inkscape:showpageshadow="2"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
inkscape:deskcolor="#d1d1d1"
|
||||
inkscape:document-units="mm"><inkscape:page
|
||||
x="0"
|
||||
y="0"
|
||||
width="40.018326"
|
||||
height="43.557034"
|
||||
id="page2"
|
||||
margin="0"
|
||||
bleed="0" /></sodipodi:namedview><defs
|
||||
id="defs1"><clipPath
|
||||
id="5346413700"><path
|
||||
d="M 0.0742188,11.554688 H 113.92578 V 135.14062 H 0.0742188 Z m 0,0"
|
||||
clip-rule="nonzero"
|
||||
id="path2" /></clipPath></defs><g
|
||||
inkscape:label="Layer 1"
|
||||
inkscape:groupmode="layer"
|
||||
id="layer1"
|
||||
transform="translate(-76.752395,-70.247194)"><g
|
||||
id="g2"
|
||||
transform="matrix(0.35277778,0,0,0.35277778,27.80232,86.453883)"><g
|
||||
clip-path="url(#5346413700)"
|
||||
id="g4"
|
||||
style="fill:#000000"
|
||||
transform="translate(138.6038,-57.494913)"><path
|
||||
fill="#ffffff"
|
||||
d="m 106.50391,11.554688 c -6.05469,0.04297 -14.179691,10.277343 -21.875004,27.5625 -1.28125,2.878906 -2.332031,5.316406 -2.332031,5.414062 0,0.542969 0.507813,-0.109375 2.09375,-2.699219 2.585937,-4.226562 9.738281,-11.082031 15.195313,-14.558593 10.179692,-6.492188 11.945312,-7.71875 12.808592,-8.90625 0.80469,-1.101563 0.83594,-1.398438 0.29297,-2.710938 -0.75,-1.804688 -4.23047,-4.117188 -6.18359,-4.101562 z m -99.199222,0.09375 c -0.417969,-0.01172 -0.824219,0.01953 -1.222657,0.09375 -2.214843,0.414062 -5.316406,3.375 -5.316406,5.074218 0,1.722656 1.6875,3.203125 8.199219,7.195313 2.964844,1.820312 6.773437,4.328125 8.460937,5.570312 4.101563,3.019531 10.363281,9.683594 12.359375,13.152344 0.886719,1.539063 1.6875,2.730469 1.773438,2.648437 0.08984,-0.08203 -0.914063,-2.601562 -2.230469,-5.59375 C 21.503906,21.996094 13.535156,11.859375 7.304688,11.648438 Z m 9.121093,34.699218 C 12.449219,46.324219 11.773438,46.453125 9,47.769531 2.671875,50.765625 0.144531,54.5625 0.152344,61.0625 c 0.019531,11.21875 8.820312,22.660156 20.476562,26.621094 0.476563,0.160156 0.867188,1.039062 1.074219,2.414062 1.042969,6.945313 4.808594,14.824224 9.351563,19.542974 l 3.339843,3.47265 -0.757812,3.1211 c -1.0625,4.3789 -0.671875,9.55078 0.96875,12.83984 1.136719,2.27344 4.152343,5.91797 4.898437,5.91797 0.175782,0 0.113282,-0.87891 -0.132812,-1.95703 -0.742188,-3.23047 -0.277344,-10.46094 0.796875,-12.29688 0.5,-0.85937 1.128906,-1.63672 1.394531,-1.72265 0.265625,-0.0898 0.933594,0.64062 1.484375,1.625 1.378906,2.44921 4.738281,5.44531 7.609375,6.78125 2.859375,1.33203 8.238281,1.53906 11.367188,0.43359 2.898437,-1.02344 6.117187,-3.58984 8.085937,-6.44531 0.960937,-1.39844 1.933594,-2.53907 2.15625,-2.53907 0.226563,0 0.859375,0.98438 1.40625,2.1875 1.070313,2.34766 1.386719,8.00782 0.671875,11.99219 l -0.351562,1.97266 1.082031,-0.70703 c 1.464843,-0.96094 3.859375,-4.36719 4.769531,-6.78516 0.972656,-2.58984 0.964844,-9.46094 -0.01172,-12.54687 -0.703125,-2.21875 -0.695312,-2.28907 0.296875,-2.95313 4.992188,-3.34375 10.484375,-13.671875 12.097656,-22.753906 0.179688,-1.019532 0.570313,-1.730469 0.945313,-1.730469 1.3125,0 6.492187,-2.796875 9.152346,-4.941406 11.87109,-9.570313 15.03906,-26.179688 6.23047,-32.671875 -3.58203,-2.636719 -6.55078,-3.554688 -11.515629,-3.554688 -4.9375,0 -7.9375,0.910156 -11.984374,3.632813 l -2.300782,1.546875 -2.875,-1.292969 c -6.164062,-2.773437 -8.011718,-3.011719 -23.144531,-3.019531 -12.996094,0 -14.035156,0.05859 -17.417969,1.039062 -1.976562,0.574219 -4.617187,1.558594 -5.859375,2.191406 L 31.191406,51.625 28.574219,49.949219 C 24.332031,47.234375 21.4375,46.375 16.425781,46.347656 Z m 81.507813,3.996094 c 4.492186,0.02734 9.109376,1.824219 10.648436,4.3125 3.35938,5.441406 0.0195,16.671875 -7.08984,23.820312 -4.656252,4.683594 -10.949221,7.691407 -16.089846,7.691407 -1.558594,0 -1.621094,-0.07031 -2.320313,-2.648438 -2.726562,-10.050781 -2.640625,-18.355469 0.25,-24.683593 2.289063,-5.003907 6.328125,-7.675782 12.691407,-8.394532 0.628906,-0.07031 1.269531,-0.101562 1.910156,-0.09766 z m -81.160156,0.0625 c 0.675781,0.03516 1.34375,0.109375 2.003906,0.226562 4.390625,0.769532 8.398437,2.910157 10.113281,5.398438 2.839844,4.128906 3.402344,6.542969 3.367187,14.472656 -0.02734,6.003906 -0.210937,7.800782 -1.136718,11.285156 L 30.015625,85.9375 28.175781,86.03125 C 27.160156,86.085938 25.21875,85.824219 23.855469,85.449219 15.117188,83.0625 7.386719,75.117188 4.675781,65.734375 3.597656,62 3.855469,56.324219 5.1875,54.53125 c 2.007812,-2.710938 6.871094,-4.371094 11.585938,-4.125 z m 40.390624,1.222656 c 13.476563,0.0078 18.050782,0.535156 19.800782,2.285156 1.011718,1.011719 0.953125,1.398438 -1.082032,7.011719 -0.898437,2.484375 -0.914062,2.800781 -0.269531,5.859375 0.65625,3.136719 0.558594,5.371094 -0.320312,7.085938 -0.234375,0.457031 -2.089844,2.632812 -4.121094,4.835937 C 64.328125,86.121094 60.019531,92.335938 57.070312,99.0625 56.71875,99.867188 56.554688,99.976562 56.535156,99.429688 56.476562,98.03125 52.625,91.058594 49.953125,87.527344 48.527344,85.640625 45.28125,81.761719 42.738281,78.914062 37.785156,73.355469 37.222656,72.171875 37.816406,68.519531 38.675781,63.203125 38.65625,62.386719 37.621094,60.09375 37.0625,58.855469 36.421875,57.242188 36.203125,56.511719 35.015625,52.5625 39.082031,51.617188 57.164062,51.628906 Z M 47.023438,107.79297 c 0.847656,-0.0312 2.066406,0.66797 3.304687,1.98047 3.746094,3.96875 3.710937,4.27734 -0.273437,2.21484 -2.8125,-1.45312 -4.394532,-2.93359 -3.933594,-3.68359 0.203125,-0.32813 0.515625,-0.4961 0.902344,-0.51172 z m 19.289062,0.0234 c 2.121094,0 1.578125,1.55859 -1.125,3.22265 -2.78125,1.71094 -4.539062,2.44141 -4.539062,1.88672 0,-0.21875 0.996093,-1.45703 2.210937,-2.7539 1.601563,-1.70704 2.554687,-2.35547 3.453125,-2.35547 z m 0,0"
|
||||
fill-opacity="1"
|
||||
fill-rule="nonzero"
|
||||
id="path4"
|
||||
style="fill:#000000" /></g></g></g></svg>
|
||||
|
After Width: | Height: | Size: 6.3 KiB |
BIN
screenshot.png
BIN
screenshot.png
Binary file not shown.
|
Before Width: | Height: | Size: 123 KiB |
Reference in New Issue
Block a user