4 Commits

16 changed files with 440 additions and 111 deletions

4
.gitignore vendored
View File

@@ -24,4 +24,6 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts
next-env.d.ts
changes.md

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, 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"
@@ -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[] = []
@@ -148,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",
@@ -160,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[] = []
@@ -177,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 {

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,7 +26,7 @@ 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
@@ -383,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,
@@ -691,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: {
@@ -711,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: {
@@ -731,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

@@ -17,7 +17,7 @@ import {
} from "@/components/ui/drawer"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { ApiClient, TableMetadata, getApiBaseUrl, TableField } from "@/lib/api"
import { ApiClient, TableMetadata, entityFileUrl, TableField } from "@/lib/api"
import { useToast } from "@/hooks/use-toast"
interface EditItemDrawerProps {
@@ -57,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
};
@@ -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

@@ -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"
@@ -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,13 +234,15 @@ 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 (
<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);
@@ -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>
))}

View File

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

View File

@@ -9,7 +9,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
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"
@@ -57,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/auth/setup/admin", {
const response: any = await apiClient.call(SYS_ADMINS_SETUP_API, {
method: "POST",
body: JSON.stringify({
email,

View File

@@ -68,6 +68,20 @@ export interface Admin {
updated: string
}
/** System admin REST API (list, CRUD). Login: `${SYS_ADMINS_API}/login`. */
export const SYS_ADMINS_API = "/api/v1/sys/admins" as const
/** 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
@@ -234,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"
}),
})

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

16
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "mantisbase-admin",
"version": "0.3.8",
"version": "0.3.9",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "mantisbase-admin",
"version": "0.3.6",
"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",

View File

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