9 Commits

21 changed files with 764 additions and 202 deletions

View File

@@ -4,7 +4,7 @@ A modern, web-based admin dashboard for managing your MantisBase backend. This d
![MantisBase Admin Dashboard](mantisbase-admin.png)
## 📋 Table of Contents
## Table of Contents
- [About](#about)
- [Getting Started](#getting-started)
@@ -14,7 +14,7 @@ A modern, web-based admin dashboard for managing your MantisBase backend. This d
- [Features](#features)
- [Links](#links)
## 🎯 About
## 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:
@@ -25,7 +25,7 @@ MantisBase Admin Dashboard is the official administrative interface for [MantisB
- Configure application settings
- And much more!
## 🚀 Getting Started
## Getting Started
### Prerequisites
@@ -65,7 +65,7 @@ Before you begin, ensure you have the following installed:
2. Log in with your admin credentials at `/mb/login`
## 💻 Development
## Development
### Available Scripts
@@ -86,9 +86,11 @@ In development mode, the dashboard will:
You can customize the development setup using environment variables:
- `MANTIS_PORT` - Port for the MantisBase API (default: 7070)
- `NEXT_PUBLIC_BASE_PATH` - Base path for the application (default: `/mb` in production)
- `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
## Building for Production
To build the dashboard for production:
@@ -133,7 +135,7 @@ This repository includes a special branch called `mb-admins` that is automatical
This integration ensures that MantisBase always includes the latest stable version of the admin dashboard without requiring manual updates.
## ✨ Features
## Features
### Entity Management
- Create, read, update, and delete database entities
@@ -169,18 +171,14 @@ This integration ensures that MantisBase always includes the latest stable versi
- **Documentation**: [https://docs.mantisbase.com](https://docs.mantisbase.com)
- **This Repository**: [https://github.com/allankoechke/mantisbase-admin](https://github.com/allankoechke/mantisbase-admin)
## 📝 Notes
## Notes
> **Note**: This project is still in active development. Some features may be incomplete or subject to change.
## 🤝 Contributing
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## 📄 License
## License
This project is part of the MantisBase ecosystem. Please refer to the main MantisBase repository for license information.
---
**Made with ❤️ for the MantisBase community**

View File

@@ -31,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, 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"
@@ -117,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[] = []

View File

@@ -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}

View File

@@ -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 }),
})

View File

@@ -24,12 +24,14 @@ 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)
@@ -120,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,
})
@@ -242,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"
@@ -290,7 +295,7 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
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>
@@ -328,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
@@ -351,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" : ""}`}
@@ -361,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" : ""}`}
@@ -384,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" : ""}`}

View File

@@ -26,13 +26,18 @@ import type { ApiClient, TableMetadata, TableField, ForeignKeyConfig } from "@/l
import { dataTypes } from "@/lib/constants"
import { useToast } from "@/hooks/use-toast"
import { cn } from "@/lib/utils"
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 {
@@ -53,13 +58,37 @@ interface Field {
foreign_key?: ForeignKeyConfig // Optional foreign key configuration
}
export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], 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()
@@ -67,17 +96,28 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
// Get unique key for field (use id if exists, otherwise generate one)
const getFieldKey = (field: Field, index: number) => field.id || `temp-${index}`
// 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") {
@@ -192,11 +232,12 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
}
}
// 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([
@@ -342,38 +383,41 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
// Include all fields in order (system + valid user fields) for base/auth types
// For view types, fields are typically empty or derived from SQL
// Filter out non-system fields that don't have valid name and type
const allFields = tableType === "view"
? []
: fields
.filter((field) => {
// Keep all system fields
if (field.system) return true
// For non-system fields, only keep those with valid name and type
return field.name.trim() && field.type && field.type.trim()
})
.map(
(field): TableField => {
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: field.constraints,
}
// Only include id if it exists (for existing fields being updated)
if (field.id && field.id.startsWith("mbf_")) {
fieldData.id = field.id
}
// Include foreign_key if configured
if (field.foreign_key && field.foreign_key.entity && field.foreign_key.field) {
fieldData.foreign_key = field.foreign_key
}
return fieldData
},
)
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,
@@ -448,14 +492,16 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
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>
@@ -648,7 +694,11 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
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: {
@@ -668,7 +718,11 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
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: {
@@ -688,8 +742,12 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
<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>

View File

@@ -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>
))}

View File

@@ -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)
}
}
@@ -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>
@@ -278,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>
)
}

View File

@@ -176,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") {
@@ -186,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) => {
@@ -264,8 +261,13 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
if (field.foreign_key && field.foreign_key.entity && field.foreign_key.field) {
return value === "null" ? null : value;
}
if (!value) return null; // handle null or undefined values
if (value === null || value === undefined) {
return null
}
if (value === "") {
return null
}
const type = field.type;
@@ -347,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"
@@ -385,7 +389,7 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
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>
@@ -434,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" : ""}`}

View File

@@ -38,6 +38,7 @@ import { useRouter } from "@/lib/router"
import { cn } from "@/lib/utils"
import { formatConstraintDefaultForInput, normalizeConstraintsForFieldType } from "@/lib/schema-constraints"
interface TableConfigDrawerProps {
table: TableMetadata
@@ -223,7 +224,26 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
setIsLoading(true)
try {
// Transform UI format (camelCase flat) to API format (with constraints and snake_case)
const transformedFields = columns.map((col: any) => {
const transformedFields: any[] = []
for (const col of columns) {
const rawConstraints = {
default_value: col.defaultValue !== undefined ? col.defaultValue : col.constraints?.default_value,
min_value: col.minValue !== undefined ? col.minValue : col.constraints?.min_value,
max_value: col.maxValue !== undefined ? col.maxValue : col.constraints?.max_value,
validator:
col.validator !== undefined ? col.validator : (col.constraints?.validator ?? null),
}
const normalized = normalizeConstraintsForFieldType(col.type, rawConstraints)
if (!normalized.ok) {
toast({
variant: "destructive",
title: "Invalid constraints",
description: `${col.name || "Field"}: ${normalized.message}`,
duration: 5000,
})
setIsLoading(false)
return
}
const fieldData: any = {
id: col.id,
name: col.name,
@@ -232,20 +252,14 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
required: col.required,
system: col.system || false,
unique: col.unique || false,
constraints: {
default_value: col.defaultValue !== undefined ? col.defaultValue : (col.constraints?.default_value || null),
max_value: col.maxValue !== undefined ? col.maxValue : (col.constraints?.max_value || null),
min_value: col.minValue !== undefined ? col.minValue : (col.constraints?.min_value || null),
validator: col.validator !== undefined ? col.validator : (col.constraints?.validator || null),
},
constraints: normalized.constraints,
...(col.old_name && { old_name: col.old_name }),
}
// Include foreign_key if configured
if (col.foreign_key && col.foreign_key.entity && col.foreign_key.field) {
fieldData.foreign_key = col.foreign_key
}
return fieldData
})
transformedFields.push(fieldData)
}
// Add deleted fields to the fields array with op: "delete"
const deletedFields = deletedColumns.map((fieldId: string) => ({
@@ -581,7 +595,11 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
id={`min-${fieldKey}`}
type="number"
placeholder="Min"
value={column.minValue || ""}
value={
column.minValue === null || column.minValue === undefined
? ""
: String(column.minValue)
}
onChange={(e) =>
updateColumn(index, "minValue", e.target.value ? Number.parseFloat(e.target.value) : null)
}
@@ -596,7 +614,11 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
id={`max-${fieldKey}`}
type="number"
placeholder="Max"
value={column.maxValue || ""}
value={
column.maxValue === null || column.maxValue === undefined
? ""
: String(column.maxValue)
}
onChange={(e) =>
updateColumn(index, "maxValue", e.target.value ? Number.parseFloat(e.target.value) : null)
}
@@ -611,8 +633,8 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
<Input
id={`default-${fieldKey}`}
placeholder="Default value"
value={column.defaultValue || ""}
onChange={(e) => updateColumn(index, "defaultValue", e.target.value || null)}
value={formatConstraintDefaultForInput(column.type, column.defaultValue ?? column.constraints?.default_value)}
onChange={(e) => updateColumn(index, "defaultValue", e.target.value)}
className="h-8 text-xs"
/>
</div>

View File

@@ -212,12 +212,14 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
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 {
@@ -232,7 +234,9 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
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 (
@@ -267,7 +271,10 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
}
default:
return value ? String(value) : "N/A";
if (typeof value === "number" && Number.isNaN(value)) {
return "N/A"
}
return String(value)
}
}
@@ -372,7 +379,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
/>
</TableHead>
{filteredFields.map((field) => (
<TableHead key={field.name} className="capitalize">
<TableHead key={field.name}>
{field.name}
</TableHead>
))}
@@ -400,8 +407,10 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
/>
</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>

View File

@@ -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"`

View File

@@ -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
@@ -98,7 +99,7 @@ export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerP
function RealtimeDocCard({ table }: { table: TableMetadata }) {
const [isOpen, setIsOpen] = React.useState(false)
const entityName = table.schema.name
const baseUrl = "https://your-api.com"
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
@@ -244,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") {

View File

@@ -1,7 +1,7 @@
"use client"
import * as React from "react"
import { Eye, EyeOff } from "lucide-react"
import { Eye, EyeOff, Info } from "lucide-react"
import { Logo } from "./logo"
import { Button } from "@/components/ui/button"
@@ -11,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("")
@@ -39,7 +50,16 @@ 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">
@@ -98,6 +118,7 @@ export function LoginForm({ onLogin }: LoginFormProps) {
</form>
</CardContent>
</Card>
</div>
</div>
)
}

View File

@@ -68,22 +68,28 @@ 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;
/** 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 {
@@ -231,15 +237,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"
}),
})

View File

@@ -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', 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 for production
return process.env.NEXT_PUBLIC_BASE_PATH || (process.env.NODE_ENV === 'production' ? '/mb' : '')
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/* or exactly /mb, the base path is /mb
// 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 === "/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"
}
// 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
View 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,
},
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 179 KiB

After

Width:  |  Height:  |  Size: 511 KiB

View File

@@ -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' : ''),
// 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,
},

2
package-lock.json generated
View File

@@ -1,6 +1,6 @@
{
"name": "mantisbase-admin",
"version": "0.3.6",
"version": "0.3.8",
"lockfileVersion": 3,
"requires": true,
"packages": {

View File

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