88 Commits
v0.1.5 ... dev

Author SHA1 Message Date
6d3e109ca6 fixes rehydration of table drawer on schema changes 2026-11-11 01:48:10 +03:00
064e6db700 feat: added password reset action for auth users 2026-11-11 01:40:24 +03:00
c3b1da50d2 version bump to v0.4.2 2026-11-11 00:38:21 +03:00
b3c38067f4 fix: fixes for required fields on auth and verification email button trigger 2026-11-11 00:36:25 +03:00
846cdc1631 feat: added email verfication flag and settings 2026-11-11 00:24:02 +03:00
82d5716848 feat: ensure password method is enabled for backward compatibility 2026-11-10 01:33:18 +03:00
6111fb5321 feat: add auth methods toggles 2026-11-10 01:30:01 +03:00
b17b556fa2 feat: added SMTP test button and feedback prompt 2026-11-09 13:53:35 +03:00
97d6b111e0 feat: bump version to 0.4.0 2026-09-10 02:47:11 +03:00
698ba092ea feat: fix broken link for admin setup page 2026-09-10 02:44:01 +03:00
06ed6c8405 docs: update readme to match impl changes 2026-08-18 15:12:00 +03:00
17d87cefde fix: fixes enabling/disabling ouath for entities via API 2026-08-18 15:04:12 +03:00
6af6ba5d2a docs: update doc views in the admin page to match openapi spec 2026-08-18 14:20:20 +03:00
1ee5ce681a fix: wrong file resolution URL 2026-08-18 13:49:39 +03:00
68588bf9e4 refactor: move api keys views for shared view across admins + auth views 2026-08-18 02:07:46 +03:00
71487d40b6 feat: fix legacy data types conversion 2026-08-18 01:52:02 +03:00
32f4e95194 feat: cleanup xml and blob types 2026-08-18 01:29:11 +03:00
0cc78ad586 feat: fix API keys listing + UI mounting bugs 2026-08-18 00:18:33 +03:00
db26e88196 feat: fix auth loop issue 2026-08-17 23:11:52 +03:00
76f39b6fc5 feat: switch to react router + switch to cookie use 2026-08-17 22:51:23 +03:00
eba0878c59 Merge pull request #28 from allankoechke/v0.3.x
V0.3.x
2026-03-21 01:16:56 +03:00
fd7a565d6b Undo column name capitalization by default 2026-03-21 01:13:03 +03:00
e5df3eea6b Fix type casting bugs for data validation 2026-03-21 01:01:50 +03:00
3b475865dc Update API endpoints for admins login + data query 2026-03-20 23:52:35 +03:00
e196fc6008 Merge pull request #26 from allankoechke/v0.3.x
Entity table cloning + editing name + text eliding for UX
2026-02-26 02:26:04 +03:00
97f1139abb Fix entity name eliding on entity view + eliding of table records beyond 2 lines 2026-02-26 02:24:08 +03:00
5f5b7260ec Added clone, edit and delete entity options 2026-02-26 02:04:20 +03:00
d213b760e0 Updated mantis admin dashboard snapshot 2026-02-26 01:38:48 +03:00
2630c1fa22 Merge pull request #25 from allankoechke/v0.3.x
Fix base route for admin dashboard to be overriden by env vars
2026-02-22 23:39:42 +03:00
783b7818f8 Fix base route for admin dashboard to be overriden by env vars 2026-02-22 23:38:08 +03:00
8ed0085670 Merge pull request #24 from allankoechke/v0.3.x
V0.3.x
2026-02-21 20:34:29 +03:00
0b1ee7c76f Added demo flag for toggling between demo mode and production UI 2026-02-21 20:31:14 +03:00
3ef1afecdf Added demo flag for toggling between demo mode and production UI 2026-02-21 20:30:00 +03:00
e25916728f Merge pull request #18 from allankoechke/v0.3.x
Bumped version to 0.3.7
2026-02-03 23:29:03 +03:00
ba2bbe38eb Bumped version to 0.3.7 2026-02-03 23:28:01 +03:00
7d15508cf2 Merge pull request #17 from allankoechke/v0.3.x
V0.3.x
2026-02-03 23:23:46 +03:00
230b3b8889 Update minimum log level filter default to 'info' 2026-02-03 23:22:39 +03:00
6966cd190b Add Realtime (SSE) documentation and examples to TableRecordDocsDrawer component 2026-02-03 23:17:39 +03:00
fa34b386ff Merge pull request #16 from allankoechke/v0.3.x
V0.3.x
2026-01-08 15:43:56 +03:00
5e8e00695c Bump version to 0.3.6 2026-01-08 15:35:24 +03:00
7d62841cdb Added FK support in fields
Added logs query, formatting and sorting
2026-01-08 15:33:19 +03:00
6ff6fb6157 Added logs fetching from logs api endpoint 2026-01-07 21:07:12 +03:00
b8122a94ee Merge pull request #15 from allankoechke/v0.3.x
V0.3.x
2025-12-17 03:29:30 +03:00
71f539a4af Bumped versions to v0.3.5 2025-12-17 01:12:13 +03:00
15264a65cd Add newer screenshot for the dashboard 2025-12-17 01:09:35 +03:00
2e43450b5a Updated README 2025-12-17 00:41:27 +03:00
7b20a7ca91 Fix field deletion in UI to match API changes 2025-12-16 00:28:16 +03:00
4439ccadfb Merge pull request #14 from allankoechke/v0.3.x
Bump version to 0.3.4 and update base path from /mb-admin to /mb
2025-12-15 23:11:52 +03:00
dfe21d4163 Bump version to 0.3.4 and update base path from /mb-admin to /mb 2025-12-15 23:10:02 +03:00
b8064a73fb Merge pull request #13 from allankoechke/v0.3.x
Fix prod route to /mb to match backend
2025-12-15 22:40:47 +03:00
f9a6c77259 Fix prod route to /mb to match backend 2025-12-15 22:39:48 +03:00
78232e85f1 Merge pull request #12 from allankoechke/v0.3.x
V0.3.x
2025-12-14 20:10:04 +03:00
b53c098364 Fix setup form page for admin setup on first start 2025-12-14 20:09:21 +03:00
f3821ab557 Added mantisbase logo 2025-12-14 01:28:50 +03:00
592657e0dc Fix add schema disabling logic 2025-12-13 20:10:37 +03:00
2ab08e32b9 Fix fields not added in schema 2025-12-13 14:38:33 +03:00
a397f39233 Removed cancel button in config drawer 2025-12-13 07:33:38 +03:00
5800ef9c67 Updated access rules selection & updating to match new schema format 2025-12-13 06:37:53 +03:00
d743538892 Merge pull request #11 from allankoechke/v0.3.x
Update git workflow to match master branch
2025-12-13 05:39:02 +03:00
ca9e58c9d0 Merge branch 'master' into v0.3.x 2025-12-13 05:38:48 +03:00
81827d5a65 Update git workflow to match master branch 2025-12-13 05:36:57 +03:00
93c6066270 Merge pull request #10 from allankoechke/v0.3.x
V0.3.x
2025-12-13 03:16:21 +03:00
5c57809f2d Move admin loading to when we switch to admin page 2025-12-13 03:14:17 +03:00
2f4d670420 Remove loading config data on first load 2025-12-13 03:10:54 +03:00
ee5166257c Fix table refresh on switching selected entity 2025-12-13 03:07:19 +03:00
9734a648a1 Fix slug errors 2025-12-13 03:00:03 +03:00
f6292111c8 Fix slug error on reloading pages 2025-12-13 02:27:09 +03:00
96ecfa91a7 Update docs drawer with new schema 2025-12-13 02:08:23 +03:00
12c43bba26 Update auth error dialog for simplicity 2025-12-13 01:35:42 +03:00
9d92efd4a9 Merge pull request #9 from allankoechke/v0.3.x
V0.3.x
2025-12-13 01:31:59 +03:00
fb4b5eee2c Update schema on add table drawer 2025-12-13 01:28:47 +03:00
33bf97d7f9 Fix file display on record rows 2025-12-12 23:16:25 +03:00
77de7c447c Update admin schema to match new v0.3.x mantisbase changes 2025-12-12 15:32:57 +03:00
7b99195ccf Fix admin routing and logic 2025-12-12 15:24:19 +03:00
60fee77f05 Updated endpoints and match new schemas for entities + pagination for entities responses 2025-12-12 13:54:39 +03:00
e5b03b2fb5 Added API query for login page 2025-12-12 00:50:10 +03:00
420583f13d Added mb-admin branch to release 2025-12-11 02:09:30 +03:00
ded52c728d Added release workflow for static files 2025-12-11 02:03:27 +03:00
9767bbfd66 Merge pull request #7 from allankoechke/v0.3-dev
V0.3 dev
2025-12-11 01:25:59 +03:00
23b578aa0b Reverted to root routing for now; Added /setup page; Fixed bugs 2025-11-28 11:19:49 +03:00
ea46055dec Refactor sidebar/navigation/pages/etc 2025-11-27 18:05:46 +03:00
67cee19b86 Table: Fix for displaying table records, adding new records and updating records 2025-08-21 17:54:23 +03:00
595a6d08f6 Updated toast display 2025-08-14 01:01:44 +03:00
925da2ecff Set all toast to destruct except error popups 2025-08-05 00:51:28 +03:00
7dbb224642 Core: Fix date pickup and display format in the record input drawer 2025-08-04 02:00:30 +03:00
437282b753 Core: Fixed table record display per data type and handle empty records accordingly 2025-08-04 01:45:01 +03:00
247236828a Core: Added form data for creating table records & updated filed types to capture new changes 2025-08-03 23:44:47 +03:00
c05a27ae0e Fix for success and error popups showing up when requests fail 2025-07-02 19:01:46 +03:00
62 changed files with 12960 additions and 2719 deletions

View File

@@ -39,3 +39,43 @@ jobs:
files: mantis-admin-static.zip
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Checkout mb-admin branch
uses: actions/checkout@v4
with:
ref: mb-admin
path: mb-admin-branch
- name: Clear and update public directory in mb-admin
run: |
# Remove existing public directory contents
rm -rf mb-admin-branch/public
mkdir -p mb-admin-branch/public
# Copy built files to public directory
cp -r out/* mb-admin-branch/public/
- name: Commit and push to mb-admin branch
working-directory: mb-admin-branch
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add public/
git commit -m "chore: update static files from master tag ${{ github.ref_name }}" --allow-empty
git push origin mb-admin
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Zip mb-admin branch
run: |
zip -r mantis-admin-branch.zip mb-admin-branch -x "mb-admin-branch/.git/*"
- name: Upload both zips to release
uses: softprops/action-gh-release@v1
with:
files: |
mantis-admin-static.zip
mantis-admin-branch.zip
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

239
README.md
View File

@@ -1,5 +1,236 @@
# 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
![](screenshot.png)
A modern, web-based admin dashboard for managing your [MantisBase](https://github.com/allankoechke/mantisbase) backend. Manage entities, schemas, auth, OAuth, API keys, admins, settings, and logs from a single UI.
![MantisBase Admin Dashboard](mantisbase-admin.png)
## Table of Contents
- [About](#about)
- [Getting Started](#getting-started)
- [Development](#development)
- [Authentication](#authentication)
- [Building for Production](#building-for-production)
- [Integration with MantisBase](#integration-with-mantisbase)
- [Features](#features)
- [API Reference](#api-reference)
- [Project Structure](#project-structure)
- [Links](#links)
## About
MantisBase Admin is the official administrative interface for MantisBase, a lightweight Backend-as-a-Service (BaaS) written in C++. It talks to the MantisBase REST API at `/api/v1/` and is designed to be served alongside the backend (typically under `/mb/`).
## Getting Started
### Prerequisites
- **Node.js** 20 or higher
- **npm**
- A running **MantisBase** server (default port `7070`)
### Installation
1. **Clone the repository**
```bash
git clone https://github.com/allankoechke/mantisbase-admin.git
cd mantisbase-admin
```
2. **Install dependencies**
```bash
npm install
```
3. **Start the development server**
```bash
npm run dev
```
4. **Open the app**
Navigate to `http://localhost:3000` (or the port shown in the terminal).
In development, API requests to `/api/*` are proxied to the MantisBase backend (see [Development](#development)).
### First login
1. **Initial setup** (first run of MantisBase only):
- Go to `/mb/setup?token=YOUR_SETUP_TOKEN`
- Create the first admin account
- You will be redirected to login
2. **Sign in** at `/mb/login` with your admin credentials.
## Development
### Scripts
| Command | Description |
|---------|-------------|
| `npm run dev` | Development server with hot reload |
| `npm run build` | Production static export to `out/` |
| `npm run lint` | Run ESLint |
| `npm start` | Production server (requires build) |
### Dev API proxy
During `npm run dev`, Next.js rewrites `/api/:path*` to the MantisBase backend so the admin UI and API share the same origin. That allows **HttpOnly session cookies** to work without CORS issues.
Default target: `http://127.0.0.1:7070` (override with `MANTIS_PORT` or `MANTIS_PROXY_URL`).
When `NEXT_PUBLIC_MANTIS_BASE_URL` is set, the client calls that URL directly instead of using the dev proxy (useful for remote backends).
### Environment variables
| Variable | Description |
|----------|-------------|
| `MANTIS_PORT` | MantisBase API port when using the dev proxy (default: `7070`) |
| `MANTIS_PROXY_URL` | Full backend URL for the dev proxy (overrides `MANTIS_PORT`) |
| `NEXT_PUBLIC_BASE_PATH` | App base path. Default: `/mb` in production, empty in dev. Set to `""` for no prefix. |
| `NEXT_PUBLIC_MANTIS_BASE_URL` | Backend API base URL (e.g. `https://api.example.com`). No trailing slash. Bypasses same-origin/proxy. |
| `NEXT_PUBLIC_MB_IS_DEMO_MODE` | Set to `true` or `1` for demo mode (prefilled login + demo banner) |
## Authentication
Admin authentication uses **HttpOnly cookies** set by the backend on login/refresh. The dashboard does **not** store JWTs in `localStorage` or `sessionStorage`.
- Login: `POST /api/v1/sys/admins/login`
- Session check: `GET /api/v1/sys/admins`
- Logout: `POST /api/v1/sys/admins/logout`
All authenticated API calls use `credentials: "include"`.
## Building for Production
```bash
npm run build
```
Static files are written to `out/` and can be served by any static host or bundled with MantisBase (see below).
Production builds use `output: 'export'` and default `basePath` of `/mb`.
## Integration with MantisBase
### The `mb-admins` branch
This repo includes an `mb-admins` branch with **built static files**, integrated into the main [MantisBase](https://github.com/allankoechke/mantisbase) project via CMake.
- Updated automatically on release tags (`v*`)
- MantisBase fetches this branch during its build
- Admin UI is served at `/mb/*` when MantisBase is running
## Features
### Database & entities
- List, create, and open entities
- **Entity types:** `base`, `auth`, and `view` (read-only SQL views)
- **Configure drawer**:
- **Fields** — schema editor with constraints, validators, foreign keys
- **Auth** (auth entities) — toggles for password, email OTP, and OAuth login methods; OAuth provider registry appears only when OAuth is enabled
- **Access Rules** — per-operation modes: admin-only, public, authenticated, custom expression
- Record CRUD with search/filter, column visibility, file field uploads
- Legacy field types (`int32`, `xml`, `blob`, etc.) are normalized in the editor and auto-migrated on save
- **Field types:** `string`, `double`, `date`, `int` (with precision `u8`–`u64`, `i8`–`i64`), `json`, `bool`, `file`, `files`
- In-app **API documentation** drawers:
- Schema-level docs on the database list page
- Per-entity docs on the entity detail page (CRUD, files, realtime SSE/WebSocket, auth/OAuth when applicable)
### Auth entities
For entities with `type: "auth"`:
- **Records** tab — user records
- **API Keys** tab — list/create/revoke entity user API keys (`/api/v1/auth/{entity}/api-keys`)
- Per-user “Create API Key” from row actions
- **Login methods** — `auth.password` / `auth.otp` / `auth.oauth` on the schema (defaults: password on, OTP/OAuth off). Public apps read `GET /api/v1/auth/{entity}/methods`.
- **Email verification** — `auth.requireEmailVerification` (default off). Auth records include system field `email_verified` (admin-editable). Apps use `/verify-email` and `/verify-email/request`.
- **Password reset** — auth row actions can send a reset email via `/password-reset/request`. Users complete the flow with `/password-reset` (HTML form or JSON `{ token, password }`).
- **OAuth providers** — shown under Auth only when `auth.oauth` is on; per-provider enablement via `enabled_for_entity`
Auth / OAuth workflow:
1. Enable the desired methods under **Configure → Auth**
2. For OTP or required email verification, configure SMTP (and Site Domain for verification links) under Settings
3. For OAuth, register providers and toggle **Enabled for entity**
4. Client apps should call `/methods` and only show enabled options / verification UX when flagged
### Admins
- **Accounts** tab — create, list, delete admin users; change passwords
- **API Keys** tab — admin API keys (`/api/v1/sys/api-keys`) with create, edit, revoke; secret shown once at creation
### Settings
Connected to `GET/PATCH /api/v1/sys/settings/config`:
- **General** — organization name, site domain, CORS origins
- **File & Sessions** — max upload size (MB in UI, bytes in API), session timeouts
- **Features** — registration, email verification, schema mutations, JWT issuer/audience flags
- **SMTP** — outbound mail configuration, plus **Test SMTP** (`POST /api/v1/sys/settings/smtp/test`) using the saved server config
- Server version from settings (`mantisVersion`) shown in the Settings header
Site domain is used for OAuth callback URL hints in the configure drawer.
### Logs
- Browse and filter application logs from `/api/v1/sys/logs`
### UI
- Dark/light theme
- Responsive layout with sidebar navigation
- Toast notifications and confirmation dialogs
## API Reference
| Resource | Location |
|----------|----------|
| OpenAPI spec | [`openapi.yaml`](openapi.yaml) in this repository |
| In-app schema API docs | Database page → documentation icon |
| In-app entity API docs | Entity detail page → documentation icon |
| External docs | [docs.mantisbase.com](https://docs.mantisbase.com) |
The OpenAPI spec covers entity CRUD, auth (login, refresh, API keys, OAuth), files (`/api/v1/files/{entity}/{file}`), realtime (SSE + WebSocket), schema management, and system routes (admins, settings, logs, OAuth registry).
**Response envelope:** most JSON endpoints return `{ "status", "data", "error" }`.
**Entity user credentials:** JWT or API key (`mb_sk_...`) via `Authorization: Bearer <token>`.
## Project Structure
```
app/ Next.js app shell and routes
components/
admins/ Admin accounts and admin API keys
api-keys/ Shared API key UI (admins + auth entities)
database/ Entities, records, schema config, API doc drawers
oauth/ OAuth provider dialogs and entity OAuth panel
settings/ Application settings
logs/ Log viewer
lib/
api.ts API client, types, endpoint constants
field-types.ts Field type definitions and migration helpers
schema-migration.ts Legacy schema normalization
openapi.yaml MantisBase REST API OpenAPI 3.1 spec
```
## Links
- **MantisBase:** [github.com/allankoechke/mantisbase](https://github.com/allankoechke/mantisbase)
- **Documentation:** [docs.mantisbase.com](https://docs.mantisbase.com)
- **This repository:** [github.com/allankoechke/mantisbase-admin](https://github.com/allankoechke/mantisbase-admin)
## Contributing
Contributions are welcome. Please open an issue or pull request on GitHub.
## License
Part of the MantisBase ecosystem. See the main MantisBase repository for license details.

33
app/[[...slug]]/error.tsx Normal file
View File

@@ -0,0 +1,33 @@
"use client"
import * as React from "react"
import { Button } from "@/components/ui/button"
import { AlertTriangle } from "lucide-react"
interface ErrorProps {
error: Error & { digest?: string }
reset: () => void
}
export default function Error({ error, reset }: ErrorProps) {
React.useEffect(() => {
// Log the error to an error reporting service
console.error("Route error:", error)
}, [error])
return (
<div className="flex min-h-screen w-full items-center justify-center bg-background">
<div className="text-center space-y-4 max-w-md">
<AlertTriangle className="h-12 w-12 text-destructive mx-auto" />
<h1 className="text-2xl font-bold">Something went wrong</h1>
<p className="text-muted-foreground">
{error.message || "An unexpected error occurred"}
</p>
<Button onClick={reset} variant="default">
Try again
</Button>
</div>
</div>
)
}

44
app/[[...slug]]/page.tsx Normal file
View File

@@ -0,0 +1,44 @@
// Optional catch-all route for all paths including root
// This handles paths like /, /setup, /entities/students, etc.
// Note: This must be a server component to use generateStaticParams()
// The MainPage component it renders is already a client component
import MainPage from "@/components/main-page"
// For static export, Next.js requires all routes to be pre-generated
// Since entity names are dynamic, we can't generate them all at build time
// Workaround: We generate a catch-all page that handles all routing client-side
// The issue is that Next.js will complain about missing routes during build,
// but the client-side router will handle them correctly at runtime
export function generateStaticParams() {
// Return base routes that are always accessible
// Include empty array for root path (/)
// For dynamic entity routes like /entities/test, we can't pre-generate them
// The client-side router will parse the actual entity name from window.location.pathname
return [
{ slug: [] }, // Root path
{ slug: ['setup'] },
{ slug: ['login'] },
{ slug: ['entities'] },
{ slug: ['logs'] },
{ slug: ['admins'] },
{ slug: ['settings'] },
]
}
// Note: With static export, Next.js will complain about routes not in generateStaticParams
// However, since we're using client-side routing, this is expected and acceptable
// The Page component will handle all routing based on window.location.pathname
export default function CatchAllPage({
params,
}: {
params: { slug?: string[] }
// Explicitly don't use searchParams to avoid serialization issues with static export
}) {
// Always render the main page - client-side router handles the actual routing
// The MainPage component parses window.location.pathname and renders the appropriate view
// This works for both pre-generated routes and dynamic routes like /entities/test
// Params are optional for the optional catch-all route
// We don't use searchParams here - the client-side router handles query params
return <MainPage />
}

33
app/error.tsx Normal file
View File

@@ -0,0 +1,33 @@
"use client"
import * as React from "react"
import { Button } from "@/components/ui/button"
import { AlertTriangle } from "lucide-react"
interface ErrorProps {
error: Error & { digest?: string }
reset: () => void
}
export default function Error({ error, reset }: ErrorProps) {
React.useEffect(() => {
// Log the error to an error reporting service
console.error("Application error:", error)
}, [error])
return (
<div className="flex min-h-screen w-full items-center justify-center bg-background">
<div className="text-center space-y-4 max-w-md">
<AlertTriangle className="h-12 w-12 text-destructive mx-auto" />
<h1 className="text-2xl font-bold">Something went wrong</h1>
<p className="text-muted-foreground">
{error.message || "An unexpected error occurred"}
</p>
<Button onClick={reset} variant="default">
Try again
</Button>
</div>
</div>
)
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 182 KiB

View File

@@ -4,48 +4,50 @@
@layer base {
:root {
/* Light Theme - Clean and minimal */
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--foreground: 0 0% 3.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--card-foreground: 0 0% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 142.1 76.2% 36.3%;
--primary-foreground: 355.7 100% 97.3%;
--secondary: 210 40% 96%;
--secondary-foreground: 222.2 84% 4.9%;
--muted: 210 40% 96%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 210 40% 96%;
--accent-foreground: 222.2 84% 4.9%;
--popover-foreground: 0 0% 3.9%;
--primary: 0 0% 9%;
--primary-foreground: 0 0% 98%;
--secondary: 0 0% 96.1%;
--secondary-foreground: 0 0% 9%;
--muted: 0 0% 96.1%;
--muted-foreground: 0 0% 45.1%;
--accent: 0 0% 96.1%;
--accent-foreground: 0 0% 9%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 142.1 76.2% 36.3%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 89.8%;
--input: 0 0% 89.8%;
--ring: 0 0% 3.9%;
--radius: 0.5rem;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--primary: 142.1 70.6% 45.3%;
--primary-foreground: 144.9 80.4% 10%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 142.4 71.8% 29.2%;
/* Visual Studio Dark Theme - Improved Contrast */
--background: 0 0% 13%;
--foreground: 0 0% 95%;
--card: 0 0% 15%;
--card-foreground: 0 0% 95%;
--popover: 0 0% 15%;
--popover-foreground: 0 0% 95%;
--primary: 0 0% 98%;
--primary-foreground: 0 0% 9%;
--secondary: 0 0% 20%;
--secondary-foreground: 0 0% 98%;
--muted: 0 0% 20%;
--muted-foreground: 0 0% 75%;
--accent: 0 0% 20%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 50%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 25%;
--input: 0 0% 20%;
--ring: 0 0% 90%;
}
}

View File

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

11
app/not-found.tsx Normal file
View File

@@ -0,0 +1,11 @@
// Custom 404 page for static export
// This handles routes that weren't pre-generated (like dynamic entity routes)
// It renders the main MainPage component which handles routing client-side
import MainPage from "@/components/main-page"
export default function NotFound() {
// Render the main page - client-side router will handle the actual routing
// This allows dynamic routes like /entities/test to work even if not pre-generated
return <MainPage />
}

View File

@@ -1,88 +0,0 @@
"use client"
import * as React from "react"
import { LoginForm } from "@/components/login-form"
import { AdminDashboard } from "@/components/admin-dashboard"
import { Toaster } from "@/components/ui/toaster"
import { ThemeProvider } from "@/components/theme-provider"
import { AppStateProvider } from "@/lib/app-state"
import { useRouter } from "@/lib/router"
export default function Page() {
const [token, setToken] = React.useState<string | null>(null)
const [mounted, setMounted] = React.useState(false)
const { route, navigate } = useRouter()
React.useEffect(() => {
setMounted(true)
// Get saved token safely
try {
const savedToken = localStorage.getItem("admin_token")
if (savedToken) {
setToken(savedToken)
}
} catch (error) {
console.warn("Failed to get saved token:", error)
}
}, [])
React.useEffect(() => {
if (mounted) {
try {
const currentPath = route.path
if (!token && currentPath !== "/login") {
navigate("/login")
} else if (token && currentPath === "/login") {
navigate("/tables")
}
} catch (error) {
console.warn("Failed to handle route change:", error)
}
}
}, [token, route.path, mounted, navigate])
const handleLogin = (newToken: string) => {
try {
setToken(newToken)
navigate("/tables")
} catch (error) {
console.warn("Failed to handle login:", error)
}
}
const handleLogout = () => {
try {
setToken(null)
localStorage.removeItem("admin_token")
navigate("/login")
} catch (error) {
console.warn("Failed to handle logout:", error)
}
}
if (!mounted) {
return (
<div className="flex min-h-screen w-full items-center justify-center">
<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...</p>
</div>
</div>
)
}
return (
<ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
<AppStateProvider>
{route.path === "/login" || !token ? (
<LoginForm onLogin={handleLogin} />
) : (
<AdminDashboard token={token} onLogout={handleLogout} />
)}
<Toaster />
</AppStateProvider>
</ThemeProvider>
)
}

View File

@@ -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,
@@ -16,6 +17,12 @@ import {
SidebarProvider,
} from "@/components/ui/sidebar"
import { Button } from "@/components/ui/button"
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip"
import {
Dialog,
DialogContent,
@@ -24,7 +31,8 @@ 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 } from "@/lib/api"
import { applySchemaListMigration } from "@/lib/schema-migration"
import { DatabaseSection } from "./database/database-section"
import { AdminsSection } from "./admins/admins-section"
import { SettingsSection } from "./settings/settings-section"
@@ -32,31 +40,35 @@ import { LogsSection } from "./logs/logs-section"
import { SyncSection } from "./sync/sync-section"
import { useToast } from "@/hooks/use-toast"
import { ThemeToggle } from "./theme-toggle"
import { useRouter } from "@/lib/router"
import { useAppState, type AppMode } from "@/lib/app-state"
import { useNavigate, useLocation } from "react-router-dom"
import { useAuth } from "@/lib/auth"
import { getDashboardSection, ROUTES } from "@/lib/routes"
import { cn } from "@/lib/utils"
interface AdminDashboardProps {
token: string
onLogout: () => void
}
export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
export function AdminDashboard() {
const [mounted, setMounted] = React.useState(false)
const [tables, setTables] = React.useState<TableMetadata[]>([])
const [admins, setAdmins] = React.useState<Admin[]>([])
const [loading, setLoading] = React.useState(true)
const [settings, setSettings] = React.useState<AppSettings | null>(null)
const [authErrorDialog, setAuthErrorDialog] = React.useState(false)
const [authErrorReason, setAuthErrorReason] = React.useState("") // Auth error reason
const { toast } = useToast()
const { route, navigate } = useRouter()
const { mode } = useAppState()
const navigate = useNavigate()
const location = useLocation()
const { logout, refreshSession } = useAuth()
const showError = React.useCallback(
(error: string, type: "error" | "warning" = "error") => {
try {
// Prevent error loops by checking if error is already being shown
if (error.includes("Unauthorized") || error.includes("auth")) {
// Prevent error toasts for auth errors (401/403) - these are handled by the auth dialog
const errorLower = error.toLowerCase()
if (
errorLower.includes("unauthorized") ||
errorLower.includes("forbidden") ||
errorLower.includes("auth") ||
errorLower.includes("403") ||
errorLower.includes("401")
) {
return // Don't show toast for auth errors, handle with dialog
}
@@ -64,6 +76,7 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
variant: type === "error" ? "destructive" : "default",
title: type === "error" ? "Error" : "Warning",
description: error,
duration: 10000,
})
} catch (toastError) {
console.warn("Failed to show error toast:", toastError)
@@ -72,18 +85,22 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
[toast],
)
const handleUnauthorized = React.useCallback((reason: string | null) => {
const handleUnauthorized = React.useCallback(async (reason?: string | "") => {
try {
setAuthErrorReason(reason) // Set the auth error string
setAuthErrorDialog(true) // Set the auth dialog to open
handleLogout()
const stillAuthenticated = await refreshSession()
if (stillAuthenticated) {
return
}
setAuthErrorReason(reason || "")
setAuthErrorDialog(true)
} catch (error) {
console.warn("Failed to handle unauthorized:", error)
}
}, [])
}, [refreshSession])
const [apiClient, setApiClient] = React.useState(
() => new ApiClient(token, handleUnauthorized, mode, settings?.baseUrl, showError),
() => new ApiClient(handleUnauthorized, showError),
)
React.useEffect(() => {
@@ -93,37 +110,58 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
// Update API client when mode or settings change
React.useEffect(() => {
const newApiClient = new ApiClient(token, handleUnauthorized, mode, settings?.baseUrl, showError)
const newApiClient = new ApiClient(handleUnauthorized, showError)
setApiClient(newApiClient)
}, [mode, settings?.baseUrl, token, handleUnauthorized, showError])
}, [handleUnauthorized, showError])
const loadAdmins = React.useCallback(async () => {
if (!apiClient) return
try {
const adminsData = await apiClient.call<any>(`${SYS_ADMINS_API}`)
// Ensure adminsData is an array - handle paginated response
let adminsArray: Admin[] = []
if (Array.isArray(adminsData)) {
// Fallback: if response is directly an array (shouldn't happen with new API)
adminsArray = adminsData
} else if (adminsData?.items && Array.isArray(adminsData.items)) {
// Paginated response: extract items from data object
adminsArray = adminsData.items
} else if (adminsData?.data?.items && Array.isArray(adminsData.data.items)) {
// If data is nested
adminsArray = adminsData.data.items
}
setAdmins(adminsArray)
} catch (error) {
console.error("Failed to load admins:", error)
}
}, [apiClient])
// Load admins when navigating to the admins page
React.useEffect(() => {
if (getDashboardSection(location.pathname) === "admins") {
loadAdmins()
}
}, [location.pathname, loadAdmins])
const loadData = async () => {
// Set default settings if loading fails
setSettings({
appName: "ACME Mantis Project",
baseUrl: "http://127.0.0.1:7070",
mantisVersion: "0.0.0",
maintenanceMode: false,
maxFileSize: 10,
allowRegistration: true,
emailVerificationRequired: false,
sessionTimeout: 84000,
adminSessionTimeout: 3600,
mode: mode,
})
try {
setLoading(true)
const [tablesData, adminsData, settingsData] = await Promise.all([
apiClient.call<TableMetadata[]>("/api/v1/tables"),
apiClient.call<Admin[]>("/api/v1/admins"),
apiClient.call<AppSettings>("/api/v1/settings/config"),
])
// Only load tables on initial load
const tablesData = await apiClient.call<any>("/api/v1/schemas")
setTables(tablesData)
setAdmins(adminsData)
setSettings(settingsData)
// Ensure tablesData is an array - handle different response structures
let tablesArray: TableMetadata[] = []
if (Array.isArray(tablesData)) {
tablesArray = tablesData
} else if (tablesData?.data && Array.isArray(tablesData.data)) {
tablesArray = tablesData.data
}
const migratedTables = await applySchemaListMigration(apiClient, tablesArray)
setTables(migratedTables)
} catch (error) {
console.error("Failed to load data:", error)
} finally {
@@ -131,10 +169,11 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
}
}
const handleLogout = () => {
const handleLogout = async () => {
try {
localStorage.removeItem("admin_token")
onLogout()
await logout()
navigate(ROUTES.login, { replace: true })
} catch (error) {
console.warn("Failed to logout:", error)
}
@@ -143,148 +182,158 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
const handleAuthErrorLogin = () => {
try {
setAuthErrorDialog(false)
// Always navigate to login and discard token, regardless of button clicked
handleLogout()
} catch (error) {
console.warn("Failed to handle auth error login:", error)
}
}
const handleModeChange = (newMode: AppMode, baseUrl?: string) => {
// Update API client with new mode and base URL
const newApiClient = new ApiClient(token, handleUnauthorized, newMode, baseUrl, showError)
setApiClient(newApiClient)
// Reload data with new mode
loadData()
const handleAuthErrorDialogClose = (open: boolean) => {
// If dialog is being closed (either by Cancel or X button), navigate to login
if (!open) {
handleAuthErrorLogin()
}
}
const sidebarItems = [
{
title: "Tables",
title: "Entities",
icon: Table,
id: "tables",
path: "/tables",
id: "entities",
path: ROUTES.entities,
},
{
title: "Logs",
icon: FileText,
id: "logs",
path: ROUTES.logs,
},
{
title: "Admins",
icon: Shield,
id: "admins",
path: "/admins",
path: ROUTES.admins,
},
// {
// title: "Logs",
// icon: FileText,
// id: "logs",
// path: "/logs",
// },
// {
// title: "Sync",
// icon: RefreshCw,
// id: "sync",
// path: "/sync",
// },
{
title: "Settings",
icon: Settings,
id: "settings",
path: "/settings",
path: ROUTES.settings,
},
]
// Extract the section from the route path safely
const getCurrentSection = () => {
try {
const pathParts = route.path.split("/").filter(Boolean)
return pathParts[0] || "tables"
} catch (error) {
console.warn("Error parsing route:", error)
return "tables"
}
}
const currentSection = getCurrentSection()
const currentSection = getDashboardSection(location.pathname)
if (!mounted) {
return (
<div className="flex min-h-screen w-full items-center justify-center">
<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 dashboard...</p>
<p className="text-muted-foreground">Loading MantisBase Admin Dashboard...</p>
</div>
</div>
)
}
return (
<SidebarProvider defaultOpen={true}>
<SidebarProvider open={false}>
<div className="flex min-h-screen w-full">
<Sidebar>
<SidebarHeader>
<div className="flex items-center gap-2 px-4 py-2">
<Shield className="h-6 w-6" />
<span className="font-semibold">Mantis Admin</span>
<Sidebar collapsible="icon" className="border-r" style={{width: "4rem", minWidth: "4rem", maxWidth: "4rem", "--sidebar-width": "4rem", "--sidebar-width-icon": "4rem"} as React.CSSProperties}>
<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">
<Logo className="h-6 w-6" size={24} />
</div>
</div>
</SidebarHeader>
<SidebarContent>
<SidebarGroup>
<SidebarGroupLabel>Navigation</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
{sidebarItems.map((item) => (
<SidebarMenuItem key={item.id}>
<SidebarMenuButton
onClick={() => {
try {
navigate(item.path)
} catch (error) {
console.warn("Failed to navigate:", error)
}
}}
isActive={currentSection === item.id}
className={currentSection === item.id ? "bg-accent text-accent-foreground" : ""}
>
<item.icon className="h-4 w-4" />
<span>{item.title}</span>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
</SidebarContent>
<SidebarFooter>
<SidebarMenu>
{settings && (
<SidebarMenuItem>
<div className="px-4 py-1 text-xs text-muted-foreground">Mantis Version {settings.mantisVersion}</div>
<SidebarContent className="px-0 py-2 w-full">
<SidebarMenu className="space-y-1 w-full">
{sidebarItems.map((item) => (
<SidebarMenuItem key={item.id} className="w-full">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<SidebarMenuButton
onClick={() => navigate(item.path)}
isActive={currentSection === item.id}
style={{ height: "4rem", minHeight: "4rem" }}
className={cn(
"w-full justify-center p-0 mx-0 rounded-none border-l-2 border-transparent min-w-full",
currentSection === item.id && "border-l-primary bg-accent"
)}
>
<item.icon className={cn(
"h-6 w-6",
currentSection === item.id && "text-primary"
)} />
<span className="sr-only">{item.title}</span>
</SidebarMenuButton>
</TooltipTrigger>
<TooltipContent side="right">
<p>{item.title}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</SidebarMenuItem>
)}
<SidebarMenuItem>
<div className="px-4 py-1 text-xs text-muted-foreground">Mantis Admin Version {process.env.MANTIS_ADMIN_VERSION}</div>
))}
</SidebarMenu>
</SidebarContent>
<SidebarFooter className="border-t p-0 w-full">
<SidebarMenu className="space-y-1 w-full">
<SidebarMenuItem className="w-full">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="w-full">
<ThemeToggle iconOnly />
</div>
</TooltipTrigger>
<TooltipContent side="right">
<p>Toggle Theme</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton asChild>
<a href="https://github.com/allankoechke/mantis" target="_blank" rel="noopener noreferrer">
<ExternalLink className="h-4 w-4" />
<span>Documentation</span>
</a>
</SidebarMenuButton>
<SidebarMenuItem className="w-full">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<SidebarMenuButton asChild style={{ height: "4rem", minHeight: "4rem" }} className="w-full justify-center p-0 mx-0 rounded-none min-w-full">
<a href="https://docs.mantisbase.com" target="_blank" rel="noopener noreferrer" className="w-full flex items-center justify-center">
<ExternalLink className="h-6 w-6" />
<span className="sr-only">Documentation</span>
</a>
</SidebarMenuButton>
</TooltipTrigger>
<TooltipContent side="right">
<p>Documentation</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</SidebarMenuItem>
<SidebarMenuItem>
<ThemeToggle />
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton onClick={handleLogout}>
<LogOut className="h-4 w-4" />
<span>Logout</span>
</SidebarMenuButton>
<SidebarMenuItem className="w-full">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<SidebarMenuButton onClick={handleLogout} className="h-12 w-full justify-center p-0 mx-0 rounded-none min-w-full">
<LogOut className="h-6 w-6" />
<span className="sr-only">Logout</span>
</SidebarMenuButton>
</TooltipTrigger>
<TooltipContent side="right">
<p>Logout</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</SidebarMenuItem>
</SidebarMenu>
</SidebarFooter>
</Sidebar>
<div className="flex-1">
<main className="p-6">
<main className="pl-4">
{loading ? (
<div className="flex items-center justify-center h-64">
<div className="text-center">
@@ -294,22 +343,15 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
</div>
) : (
<>
{currentSection === "tables" && (
{currentSection === "entities" && (
<DatabaseSection apiClient={apiClient} tables={tables} onTablesUpdate={setTables} />
)}
{currentSection === "admins" && (
<AdminsSection admins={admins} apiClient={apiClient} onAdminsUpdate={setAdmins} />
)}
{currentSection === "logs" && <LogsSection />}
{currentSection === "logs" && <LogsSection apiClient={apiClient} />}
{currentSection === "sync" && <SyncSection />}
{currentSection === "settings" && (
<SettingsSection
apiClient={apiClient}
settings={settings}
onSettingsUpdate={setSettings}
onModeChange={handleModeChange}
/>
)}
{currentSection === "settings" && <SettingsSection apiClient={apiClient} />}
</>
)}
</main>
@@ -317,30 +359,25 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
</div>
{/* Auth Error Dialog */}
<Dialog open={authErrorDialog} onOpenChange={setAuthErrorDialog}>
<Dialog open={authErrorDialog} onOpenChange={handleAuthErrorDialogClose}>
<DialogContent>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-destructive" />
Authentication Error
Authentication Required
</DialogTitle>
<DialogDescription>
Your session has expired or you don't have permission to access this resource. Please log in again to
continue.
Your session has expired or you don't have permission to access this resource. You will be redirected to the login page.
</DialogDescription>
{
authErrorReason.length > 0 && (
<DialogDescription>
{authErrorReason}
</DialogDescription>
)
}
{authErrorReason.length > 0 && (
<div className="mt-4 p-3 rounded-md bg-muted border border-muted-foreground/20">
<p className="text-xs font-medium text-muted-foreground mb-1">API Response:</p>
<p className="text-sm text-foreground font-mono">{authErrorReason}</p>
</div>
)}
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setAuthErrorDialog(false)}>
Cancel
</Button>
<Button onClick={handleAuthErrorLogin}>Login Again</Button>
<Button onClick={handleAuthErrorLogin}>Go to Login</Button>
</DialogFooter>
</DialogContent>
</Dialog>

View File

@@ -1,17 +1,18 @@
"use client"
import * as React from "react"
import { MoreHorizontal, Key, Trash2, Plus, RefreshCw } from "lucide-react"
import { Key, MoreHorizontal, Plus, RefreshCw, Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Dialog } from "@/components/ui/dialog"
import type { ApiClient, Admin, TableMetadata } from "@/lib/api"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { SYS_ADMINS_API, SYS_API_KEYS_API, extractListItems, getApiClientError, type ApiClient, type Admin } from "@/lib/api"
import { ChangePasswordDialog } from "./change-password-dialog"
import { SidebarTrigger } from "@/components/ui/sidebar"
import { AddItemDrawer } from "../database/add-item-drawer"
import { ApiKeysPanel, openCreateApiKeyDialog } from "../api-keys/api-keys-panel"
import { useToast } from "@/hooks/use-toast"
interface AdminsSectionProps {
@@ -24,94 +25,126 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
const [selectedAdmin, setSelectedAdmin] = React.useState<Admin | null>(null)
const [addingAdmin, setAddingAdmin] = React.useState(false)
const [isLoading, setIsLoading] = React.useState(false)
const [activeTab, setActiveTab] = React.useState("accounts")
const [createApiKeyForAdminId, setCreateApiKeyForAdminId] = React.useState<string | undefined>()
const [createApiKeyRequested, setCreateApiKeyRequested] = React.useState(false)
const [apiKeysReloadRequested, setApiKeysReloadRequested] = React.useState(0)
const [apiKeysLoading, setApiKeysLoading] = React.useState(false)
const { toast } = useToast()
const adminUsers = React.useMemo(
() => admins.map((admin) => ({ id: admin.id, label: admin.email })),
[admins],
)
const table: any = {
has_api: true,
name: "admins",
name: "mb_admins",
system: true,
type: "auth",
schema: {
id: "mbt_10394585042835534856",
name: "mb_admins",
has_api: true,
system: true,
type: "auth",
fields: [
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: null,
id: "mbf_14258576900392064537",
name: "id",
primaryKey: true,
primary_key: true,
required: true,
system: true,
type: "string",
unique: false,
validator: null
constraints: {
default_value: null,
max_value: null,
min_value: null,
validator: "@password",
},
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: 5.0,
id: "mbf_13735287961322938256",
name: "created",
primary_key: false,
required: true,
system: true,
type: "date",
unique: false,
constraints: {
default_value: null,
max_value: null,
min_value: null,
validator: null,
},
},
{
id: "mbf_9124719522053273721",
name: "updated",
primary_key: false,
required: true,
system: true,
type: "date",
unique: false,
constraints: {
default_value: null,
max_value: null,
min_value: null,
validator: null,
},
},
{
id: "mbf_16339674465020246541",
name: "email",
primaryKey: false,
primary_key: false,
required: true,
system: true,
type: "string",
unique: true,
validator: "email"
constraints: {
default_value: null,
max_value: null,
min_value: null,
validator: "@email",
},
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: 8.0,
id: "mbf_6072375419398818283",
name: "password",
primaryKey: false,
primary_key: false,
required: true,
system: true,
type: "string",
unique: false,
validator: "password"
constraints: {
default_value: null,
max_value: null,
min_value: null,
validator: "@password",
},
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: null,
name: "created",
primaryKey: false,
required: true,
system: true,
type: "date",
unique: false,
validator: null
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: null,
name: "updated",
primaryKey: false,
required: true,
system: true,
type: "date",
unique: false,
validator: null
}
],
}
};
rules: {
add: { expr: "", mode: "auth" },
delete: { expr: "", mode: "auth" },
get: { expr: "", mode: "auth" },
list: { expr: "", mode: "auth" },
update: { expr: "", mode: "auth" },
},
},
}
const handleDeleteAdmin = async (adminId: string) => {
try {
await apiClient.call(`/api/v1/admins/${adminId}`, { method: "DELETE" })
const updatedAdmins = await apiClient.call<Admin[]>("/api/v1/admins")
onAdminsUpdate(updatedAdmins)
await apiClient.call(`${SYS_ADMINS_API}/${adminId}`, { method: "DELETE" })
const response = await apiClient.call<unknown>(SYS_ADMINS_API)
onAdminsUpdate(extractListItems<Admin>(response))
toast({
variant: "default",
title: "Admin Deleted",
description: "Admin account deleted successfully!",
duration: 3000,
})
} catch (error) {
console.error("Failed to delete admin:", error)
@@ -122,92 +155,161 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
onAdminsUpdate([...admins, admin])
toast({
variant: "default",
title: "Admin Added",
title: "Admin User Added",
description: "Admin account added successfully!",
})
setAddingAdmin(false)
}
const handleReload = async () => {
try {
setIsLoading(true)
const updatedAdmins = await apiClient.call<Admin[]>("/api/v1/admins")
onAdminsUpdate(updatedAdmins)
const response = await apiClient.call<unknown>(SYS_ADMINS_API)
const error = getApiClientError(response)
if (error) {
throw new Error(error)
}
onAdminsUpdate(extractListItems<Admin>(response))
} catch (error) {
console.error("Failed to delete admin:", error)
console.error("Failed to reload admins:", error)
toast({
variant: "destructive",
title: "Error",
description: "Failed to reload admin accounts.",
})
} finally {
setIsLoading(false)
}
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<SidebarTrigger />
<div>
<h2 className="text-2xl font-bold">Admin Management</h2>
<p className="text-muted-foreground">Manage administrator accounts</p>
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={handleReload} disabled={isLoading}>
<RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
</Button>
const handleCreateApiKeyForAdmin = (adminId: string) => {
openCreateApiKeyDialog(setCreateApiKeyForAdminId, setCreateApiKeyRequested, adminId)
setActiveTab("api-keys")
}
<Button size="sm" onClick={() => setAddingAdmin(true)}>
<Plus className="h-4 w-4 mr-2" />
New Record
</Button>
</div>
return (
<div className="space-y-6 p-6">
<div className="space-y-1">
<h1 className="text-3xl font-bold tracking-tight">Admins</h1>
<p className="text-muted-foreground">Manage administrator accounts and API keys</p>
</div>
<Card>
<CardHeader>
<CardTitle>Administrator Accounts</CardTitle>
<CardDescription>{admins.length} administrator accounts</CardDescription>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Email</TableHead>
<TableHead>Created</TableHead>
<TableHead>Updated</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{admins.map((admin) => (
<TableRow key={admin.id}>
<TableCell className="font-medium">{admin.email}</TableCell>
<TableCell>{new Date(admin.created).toLocaleDateString()}</TableCell>
<TableCell>{new Date(admin.updated).toLocaleDateString()}</TableCell>
<TableCell>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setSelectedAdmin(admin)}>
<Key className="h-4 w-4 mr-2" />
Change Password
</DropdownMenuItem>
<DropdownMenuItem className="text-destructive" onClick={() => handleDeleteAdmin(admin.id)}>
<Trash2 className="h-4 w-4 mr-2" />
Remove Admin
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
<Tabs value={activeTab} onValueChange={setActiveTab}>
<div className="flex items-center justify-between gap-4">
<TabsList>
<TabsTrigger value="accounts">Accounts</TabsTrigger>
<TabsTrigger value="api-keys">API Keys</TabsTrigger>
</TabsList>
<div className="flex items-center gap-2">
{activeTab === "accounts" ? (
<>
<Button variant="outline" size="sm" onClick={handleReload} disabled={isLoading}>
<RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
</Button>
<Button size="sm" onClick={() => setAddingAdmin(true)}>
<Plus className="mr-2 h-4 w-4" />
New Record
</Button>
</>
) : (
<>
<Button
variant="outline"
size="sm"
onClick={() => setApiKeysReloadRequested((count) => count + 1)}
disabled={apiKeysLoading}
>
<RefreshCw className={`h-4 w-4 ${apiKeysLoading ? "animate-spin" : ""}`} />
</Button>
<Button
size="sm"
onClick={() => openCreateApiKeyDialog(setCreateApiKeyForAdminId, setCreateApiKeyRequested)}
disabled={admins.length === 0}
>
<Plus className="mr-2 h-4 w-4" />
New API Key
</Button>
</>
)}
</div>
</div>
<TabsContent value="accounts" className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Administrator Accounts</CardTitle>
<CardDescription>{admins.length} administrator accounts</CardDescription>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Email</TableHead>
<TableHead>Created</TableHead>
<TableHead>Updated</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{Array.isArray(admins) &&
admins.map((admin) => (
<TableRow key={admin.id}>
<TableCell className="font-medium">{admin.email}</TableCell>
<TableCell>{new Date(admin.created).toLocaleDateString()}</TableCell>
<TableCell>{new Date(admin.updated).toLocaleDateString()}</TableCell>
<TableCell>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setSelectedAdmin(admin)}>
<Key className="mr-2 h-4 w-4" />
Change Password
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleCreateApiKeyForAdmin(admin.id)}>
<Plus className="mr-2 h-4 w-4" />
Create API Key
</DropdownMenuItem>
<DropdownMenuItem className="text-destructive" onClick={() => handleDeleteAdmin(admin.id)}>
<Trash2 className="mr-2 h-4 w-4" />
Remove Admin
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="api-keys" className="space-y-6">
<ApiKeysPanel
users={adminUsers}
apiClient={apiClient}
apiKeysApi={SYS_API_KEYS_API}
cacheKey="mantis-admin-api-keys"
isActive={activeTab === "api-keys"}
defaultUserId={createApiKeyForAdminId}
createRequested={createApiKeyRequested}
reloadRequested={apiKeysReloadRequested}
onCreateRequestHandled={() => setCreateApiKeyRequested(false)}
onLoadingChange={setApiKeysLoading}
panelTitle="Admin API Keys"
userColumnLabel="Admin"
createDialogTitle="Create API Key"
createDialogDescription="Create a new API key linked to an admin account."
userFieldLabel="Admin Account"
/>
</TabsContent>
</Tabs>
<Dialog open={!!selectedAdmin} onOpenChange={() => setSelectedAdmin(null)}>
{selectedAdmin && (
@@ -219,6 +321,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,16 +38,20 @@ export function ChangePasswordDialog({ admin, apiClient, onClose }: ChangePasswo
setError("")
try {
await apiClient.call(`/api/v1/admins/${admin.id}`, {
const res: any = await apiClient.call(`${SYS_ADMINS_API}/${admin.id}`, {
method: "PATCH",
body: JSON.stringify({ password: newPassword }),
})
// If the request failed, throw the error here
if (res?.error?.length > 0) throw res.error
onClose()
toast({
variant: "default",
title: "Admin Updated",
description: "Admin account password updated successfully!",
duration: 3000,
})
} catch (error) {
setError("Failed to change password")

View File

@@ -0,0 +1,72 @@
"use client"
import * as React from "react"
import { Check, Copy } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Alert, AlertDescription } from "@/components/ui/alert"
interface ApiKeySecretDialogProps {
open: boolean
label: string
secret: string
onClose: () => void
}
export function ApiKeySecretDialog({ open, label, secret, onClose }: ApiKeySecretDialogProps) {
const [copied, setCopied] = React.useState(false)
React.useEffect(() => {
if (!open) {
setCopied(false)
}
}, [open])
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(secret)
setCopied(true)
window.setTimeout(() => setCopied(false), 2000)
} catch (error) {
console.error("Failed to copy API key:", error)
}
}
return (
<Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>API Key Created</DialogTitle>
<DialogDescription>
Copy the key for <span className="font-medium text-foreground">{label}</span> now. It will not be shown again.
</DialogDescription>
</DialogHeader>
<Alert>
<AlertDescription>
Store this key securely. You will not be able to view it again after closing this dialog.
</AlertDescription>
</Alert>
<div className="flex gap-2">
<Input readOnly value={secret} className="font-mono text-sm" />
<Button type="button" variant="outline" size="icon" onClick={handleCopy} aria-label="Copy API key">
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
</Button>
</div>
<DialogFooter>
<Button onClick={onClose}>Done</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,401 @@
"use client"
import * as React from "react"
import { MoreHorizontal, Pencil, Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import {
extractListItems,
getApiClientError,
type AdminApiKey,
type AdminApiKeyCreated,
type ApiClient,
type ApiKeyUser,
} from "@/lib/api"
import { useToast } from "@/hooks/use-toast"
import { ApiKeySecretDialog } from "./api-key-secret-dialog"
import { CreateApiKeyDialog } from "./create-api-key-dialog"
import { EditApiKeyDialog } from "./edit-api-key-dialog"
interface ApiKeysPanelProps {
users: ApiKeyUser[]
apiClient: ApiClient
apiKeysApi: string
cacheKey: string
isActive: boolean
defaultUserId?: string
createRequested?: boolean
reloadRequested?: number
supportsEdit?: boolean
panelTitle?: string
userColumnLabel?: string
createDialogTitle?: string
createDialogDescription?: string
userFieldLabel?: string
onCreateRequestHandled?: () => void
onLoadingChange?: (loading: boolean) => void
}
function formatDate(value: string | null): string {
if (!value) {
return "Never"
}
const date = new Date(value)
if (Number.isNaN(date.getTime())) {
return value
}
return date.toLocaleString()
}
function getUserLabel(users: ApiKeyUser[], userId: string): string {
return users.find((user) => user.id === userId)?.label ?? userId
}
function toCachedApiKey(key: AdminApiKey | AdminApiKeyCreated): AdminApiKey {
const { key: _secret, ...metadata } = key as AdminApiKeyCreated
return metadata
}
function readCachedApiKeys(cacheKey: string): AdminApiKey[] {
if (typeof window === "undefined") {
return []
}
try {
const raw = sessionStorage.getItem(cacheKey)
if (!raw) {
return []
}
const parsed = JSON.parse(raw)
return extractListItems<AdminApiKey>(parsed)
} catch {
return []
}
}
function writeCachedApiKeys(cacheKey: string, keys: AdminApiKey[]): void {
if (typeof window === "undefined") {
return
}
sessionStorage.setItem(cacheKey, JSON.stringify(keys))
}
function mergeApiKeys(fetched: AdminApiKey[], cached: AdminApiKey[]): AdminApiKey[] {
if (fetched.length > 0) {
return fetched
}
return cached
}
export function ApiKeysPanel({
users,
apiClient,
apiKeysApi,
cacheKey,
isActive,
defaultUserId,
createRequested,
reloadRequested = 0,
supportsEdit = true,
panelTitle = "API Keys",
userColumnLabel = "User",
createDialogTitle,
createDialogDescription,
userFieldLabel,
onCreateRequestHandled,
onLoadingChange,
}: ApiKeysPanelProps) {
const { toast } = useToast()
const [apiKeys, setApiKeys] = React.useState<AdminApiKey[]>(() => readCachedApiKeys(cacheKey))
const [isLoading, setIsLoading] = React.useState(false)
const [creating, setCreating] = React.useState(false)
const [selectedUserId, setSelectedUserId] = React.useState<string | undefined>()
const [editingKey, setEditingKey] = React.useState<AdminApiKey | null>(null)
const [deletingKey, setDeletingKey] = React.useState<AdminApiKey | null>(null)
const [createdSecret, setCreatedSecret] = React.useState<{ label: string; secret: string } | null>(null)
const hasLoadedRef = React.useRef(false)
const persistApiKeys = React.useCallback(
(keys: AdminApiKey[]) => {
setApiKeys(keys)
writeCachedApiKeys(cacheKey, keys)
},
[cacheKey],
)
const loadApiKeys = React.useCallback(async () => {
const cached = readCachedApiKeys(cacheKey)
try {
setIsLoading(true)
onLoadingChange?.(true)
const response = await apiClient.call<unknown>(apiKeysApi)
const error = getApiClientError(response)
if (error) {
throw new Error(error)
}
const fetched = extractListItems<AdminApiKey>(response)
const merged = mergeApiKeys(fetched, cached)
persistApiKeys(merged)
hasLoadedRef.current = true
} catch (error) {
console.error("Failed to load API keys:", error)
if (cached.length > 0) {
setApiKeys(cached)
}
toast({
variant: "destructive",
title: "Error",
description: hasLoadedRef.current
? "Failed to refresh API keys."
: cached.length > 0
? "Could not refresh API keys from the server. Showing cached keys from this browser session."
: "Failed to load API keys.",
})
} finally {
setIsLoading(false)
onLoadingChange?.(false)
}
}, [apiClient, apiKeysApi, cacheKey, onLoadingChange, persistApiKeys, toast])
React.useEffect(() => {
if (isActive) {
loadApiKeys()
}
}, [isActive, loadApiKeys])
React.useEffect(() => {
if (isActive && reloadRequested > 0) {
loadApiKeys()
}
}, [isActive, reloadRequested, loadApiKeys])
React.useEffect(() => {
if (createRequested) {
setSelectedUserId(defaultUserId)
setCreating(true)
onCreateRequestHandled?.()
}
}, [createRequested, defaultUserId, onCreateRequestHandled])
const handleCreated = (created: AdminApiKeyCreated) => {
const metadata = toCachedApiKey(created)
setApiKeys((current) => {
const next = [metadata, ...current.filter((key) => key.id !== metadata.id)]
writeCachedApiKeys(cacheKey, next)
return next
})
setCreatedSecret({ label: created.label, secret: created.key })
toast({
title: "API Key Created",
description: "Copy the key now. It will not be shown again.",
})
}
const handleUpdated = (updated: AdminApiKey) => {
setApiKeys((current) => {
const next = current.map((key) => (key.id === updated.id ? updated : key))
writeCachedApiKeys(cacheKey, next)
return next
})
toast({
title: "API Key Updated",
description: "API key settings were saved.",
})
}
const handleDelete = async () => {
if (!deletingKey) {
return
}
try {
const response = await apiClient.call(`${apiKeysApi}/${deletingKey.id}`, { method: "DELETE" })
const error = getApiClientError(response)
if (error) {
throw new Error(error)
}
setApiKeys((current) => {
const next = current.filter((key) => key.id !== deletingKey.id)
writeCachedApiKeys(cacheKey, next)
return next
})
toast({
title: "API Key Revoked",
description: `"${deletingKey.label}" has been deleted.`,
})
} catch (error) {
console.error("Failed to delete API key:", error)
toast({
variant: "destructive",
title: "Error",
description: "Failed to delete API key.",
})
} finally {
setDeletingKey(null)
}
}
return (
<>
<Card>
<CardHeader>
<CardTitle>{panelTitle}</CardTitle>
<CardDescription>
{isLoading && apiKeys.length === 0
? "Loading API keys..."
: `${apiKeys.length} API key${apiKeys.length === 1 ? "" : "s"}`}
</CardDescription>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Label</TableHead>
<TableHead>{userColumnLabel}</TableHead>
<TableHead>Created</TableHead>
<TableHead>Last Used</TableHead>
<TableHead>Expires</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{isLoading && apiKeys.length === 0 ? (
<TableRow>
<TableCell colSpan={6} className="text-center text-muted-foreground">
Loading API keys...
</TableCell>
</TableRow>
) : apiKeys.length === 0 ? (
<TableRow>
<TableCell colSpan={6} className="text-center text-muted-foreground">
No API keys yet.
</TableCell>
</TableRow>
) : (
apiKeys.map((apiKey) => (
<TableRow key={apiKey.id}>
<TableCell className="font-medium">{apiKey.label}</TableCell>
<TableCell>{getUserLabel(users, apiKey.user_id)}</TableCell>
<TableCell>{formatDate(apiKey.created)}</TableCell>
<TableCell>{formatDate(apiKey.last_used)}</TableCell>
<TableCell>{apiKey.expires_at ? formatDate(apiKey.expires_at) : "Never"}</TableCell>
<TableCell>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{supportsEdit && (
<DropdownMenuItem onClick={() => setEditingKey(apiKey)}>
<Pencil className="mr-2 h-4 w-4" />
Edit
</DropdownMenuItem>
)}
<DropdownMenuItem className="text-destructive" onClick={() => setDeletingKey(apiKey)}>
<Trash2 className="mr-2 h-4 w-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</CardContent>
</Card>
<CreateApiKeyDialog
open={creating}
users={users}
apiClient={apiClient}
apiKeysApi={apiKeysApi}
defaultUserId={selectedUserId}
userFieldLabel={userFieldLabel ?? userColumnLabel}
title={createDialogTitle}
description={createDialogDescription}
onClose={() => setCreating(false)}
onCreated={handleCreated}
/>
{supportsEdit && (
<EditApiKeyDialog
open={!!editingKey}
apiKey={editingKey}
apiClient={apiClient}
apiKeysApi={apiKeysApi}
onClose={() => setEditingKey(null)}
onUpdated={handleUpdated}
/>
)}
<ApiKeySecretDialog
open={!!createdSecret}
label={createdSecret?.label ?? ""}
secret={createdSecret?.secret ?? ""}
onClose={() => setCreatedSecret(null)}
/>
<AlertDialog open={!!deletingKey} onOpenChange={(open) => !open && setDeletingKey(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete API Key</AlertDialogTitle>
<AlertDialogDescription>
Revoke <span className="font-medium text-foreground">{deletingKey?.label}</span>? This action cannot be
undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
)
}
export function openCreateApiKeyDialog(
setDefaultUserId: (userId: string | undefined) => void,
setCreateRequested: (requested: boolean) => void,
userId?: string,
) {
setDefaultUserId(userId)
setCreateRequested(true)
}

View File

@@ -0,0 +1,179 @@
"use client"
import * as React from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Alert, AlertDescription } from "@/components/ui/alert"
import {
getApiClientError,
type AdminApiKeyCreated,
type ApiClient,
type ApiKeyUser,
} from "@/lib/api"
interface CreateApiKeyDialogProps {
open: boolean
users: ApiKeyUser[]
apiClient: ApiClient
apiKeysApi: string
defaultUserId?: string
userFieldLabel?: string
title?: string
description?: string
onClose: () => void
onCreated: (created: AdminApiKeyCreated) => void
}
export function CreateApiKeyDialog({
open,
users,
apiClient,
apiKeysApi,
defaultUserId,
userFieldLabel = "User",
title = "Create API Key",
description = "Create a new API key linked to a user account.",
onClose,
onCreated,
}: CreateApiKeyDialogProps) {
const [userId, setUserId] = React.useState(defaultUserId ?? "")
const [label, setLabel] = React.useState(`api-key-${Date.now()}`)
const [expiresAt, setExpiresAt] = React.useState("")
const [isLoading, setIsLoading] = React.useState(false)
const [error, setError] = React.useState("")
React.useEffect(() => {
if (open) {
setUserId(defaultUserId ?? users[0]?.id ?? "")
setLabel(`api-key-${Date.now()}`)
setExpiresAt("")
setError("")
}
}, [open, defaultUserId, users])
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault()
if (!userId) {
setError(`Select a ${userFieldLabel.toLowerCase()} for this API key`)
return
}
setIsLoading(true)
setError("")
try {
const body: Record<string, unknown> = {
user_id: userId,
label: label.trim() || "API Key",
}
if (expiresAt) {
body.expires_at = new Date(expiresAt).toISOString()
}
const created = await apiClient.call<AdminApiKeyCreated>(apiKeysApi, {
method: "POST",
body: JSON.stringify(body),
})
const apiError = getApiClientError(created)
if (apiError) {
throw new Error(apiError)
}
if (!created?.key) {
throw new Error("API key was created but the secret was not returned")
}
onCreated({ ...created, user_id: created.user_id ?? userId })
onClose()
} catch (submitError) {
console.error("Failed to create API key:", submitError)
setError(submitError instanceof Error ? submitError.message : "Failed to create API key")
} finally {
setIsLoading(false)
}
}
return (
<Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="api-key-user">{userFieldLabel}</Label>
<Select value={userId} onValueChange={setUserId}>
<SelectTrigger id="api-key-user">
<SelectValue placeholder={`Select ${userFieldLabel.toLowerCase()}`} />
</SelectTrigger>
<SelectContent>
{users.map((user) => (
<SelectItem key={user.id} value={user.id}>
{user.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="api-key-label">Label</Label>
<Input
id="api-key-label"
value={label}
onChange={(event) => setLabel(event.target.value)}
placeholder="Production automation"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="api-key-expires">Expires At (optional)</Label>
<Input
id="api-key-expires"
type="datetime-local"
value={expiresAt}
onChange={(event) => setExpiresAt(event.target.value)}
/>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" disabled={isLoading || users.length === 0}>
{isLoading ? "Creating..." : "Create API Key"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,139 @@
"use client"
import * as React from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { type AdminApiKey, type ApiClient } from "@/lib/api"
interface EditApiKeyDialogProps {
open: boolean
apiKey: AdminApiKey | null
apiClient: ApiClient
apiKeysApi: string
onClose: () => void
onUpdated: (updated: AdminApiKey) => void
}
function toDateTimeLocalValue(value: string | null): string {
if (!value) {
return ""
}
const date = new Date(value)
if (Number.isNaN(date.getTime())) {
return ""
}
const offset = date.getTimezoneOffset()
const local = new Date(date.getTime() - offset * 60_000)
return local.toISOString().slice(0, 16)
}
export function EditApiKeyDialog({
open,
apiKey,
apiClient,
apiKeysApi,
onClose,
onUpdated,
}: EditApiKeyDialogProps) {
const [label, setLabel] = React.useState("")
const [expiresAt, setExpiresAt] = React.useState("")
const [isLoading, setIsLoading] = React.useState(false)
const [error, setError] = React.useState("")
React.useEffect(() => {
if (open && apiKey) {
setLabel(apiKey.label)
setExpiresAt(toDateTimeLocalValue(apiKey.expires_at))
setError("")
}
}, [open, apiKey])
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault()
if (!apiKey) {
return
}
setIsLoading(true)
setError("")
try {
const updated = await apiClient.call<AdminApiKey>(`${apiKeysApi}/${apiKey.id}`, {
method: "PATCH",
body: JSON.stringify({
label: label.trim() || "API Key",
expires_at: expiresAt ? new Date(expiresAt).toISOString() : "",
}),
})
onUpdated(updated)
onClose()
} catch (submitError) {
console.error("Failed to update API key:", submitError)
setError(submitError instanceof Error ? submitError.message : "Failed to update API key")
} finally {
setIsLoading(false)
}
}
return (
<Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit API Key</DialogTitle>
<DialogDescription>Update the label or expiration for this API key.</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="edit-api-key-label">Label</Label>
<Input
id="edit-api-key-label"
value={label}
onChange={(event) => setLabel(event.target.value)}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="edit-api-key-expires">Expires At</Label>
<Input
id="edit-api-key-expires"
type="datetime-local"
value={expiresAt}
onChange={(event) => setExpiresAt(event.target.value)}
/>
<p className="text-sm text-muted-foreground">Leave blank for no expiration.</p>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" disabled={isLoading}>
{isLoading ? "Saving..." : "Save Changes"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}

157
components/app-routes.tsx Normal file
View File

@@ -0,0 +1,157 @@
"use client"
import * as React from "react"
import { AlertTriangle } from "lucide-react"
import {
BrowserRouter,
Navigate,
Outlet,
Route,
Routes,
useNavigate,
useSearchParams,
} from "react-router-dom"
import { LoginForm } from "@/components/login-form"
import { SetupForm } from "@/components/setup-form"
import { AdminDashboard } from "@/components/admin-dashboard"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Logo } from "@/components/logo"
import { AuthProvider, useAuth } from "@/lib/auth"
import { getBasePath, ROUTES } from "@/lib/routes"
function LoadingScreen({ message = "Loading..." }: { message?: string }) {
return (
<div className="flex min-h-screen w-full items-center justify-center">
<div className="text-center">
<div className="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
<p className="text-muted-foreground">{message}</p>
</div>
</div>
)
}
function RequireAuth() {
const { isAuthenticated, isLoading } = useAuth()
if (isLoading) {
return <LoadingScreen />
}
if (!isAuthenticated) {
return <Navigate to={ROUTES.login} replace />
}
return <Outlet />
}
function GuestOnly() {
const { isAuthenticated, isLoading } = useAuth()
if (isLoading) {
return <LoadingScreen />
}
if (isAuthenticated) {
return <Navigate to={ROUTES.entities} replace />
}
return <Outlet />
}
function LoginRoute() {
const { login } = useAuth()
const navigate = useNavigate()
return (
<LoginForm
onLogin={async (email, password) => {
await login(email, password)
navigate(ROUTES.entities, { replace: true })
}}
/>
)
}
function SetupRoute() {
const [searchParams] = useSearchParams()
const navigate = useNavigate()
const setupToken = searchParams.get("token")
if (!setupToken) {
return (
<div className="flex min-h-screen items-center justify-center bg-background">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<div className="mb-4 flex justify-center">
<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 in the query string (e.g. /setup?token=your-token-here).
</AlertDescription>
</Alert>
</CardContent>
</Card>
</div>
)
}
return (
<SetupForm
token={setupToken}
onSetupComplete={() => navigate(ROUTES.login, { replace: true })}
/>
)
}
function AppRoutesInner() {
return (
<Routes>
<Route path={ROUTES.setup} element={<SetupRoute />} />
<Route element={<GuestOnly />}>
<Route path={ROUTES.login} element={<LoginRoute />} />
</Route>
<Route element={<RequireAuth />}>
<Route path={ROUTES.home} element={<Navigate to={ROUTES.entities} replace />} />
<Route path={ROUTES.entities} element={<AdminDashboard />} />
<Route path={ROUTES.entityDetail} element={<AdminDashboard />} />
<Route path={ROUTES.logs} element={<AdminDashboard />} />
<Route path={ROUTES.admins} element={<AdminDashboard />} />
<Route path={ROUTES.settings} element={<AdminDashboard />} />
</Route>
<Route path="*" element={<Navigate to={ROUTES.entities} replace />} />
</Routes>
)
}
export function AppRouterProvider({ children }: { children: React.ReactNode }) {
const [mounted, setMounted] = React.useState(false)
React.useEffect(() => {
setMounted(true)
}, [])
if (!mounted) {
return <LoadingScreen />
}
return (
<BrowserRouter basename={getBasePath()}>
<AuthProvider>{children}</AuthProvider>
</BrowserRouter>
)
}
export function AppRoutes() {
return <AppRoutesInner />
}

View File

@@ -6,6 +6,7 @@ import { Edit, X, Plus } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import {
Drawer,
DrawerContent,
@@ -15,66 +16,208 @@ 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 { isFieldRequiredInForm } from "@/lib/auth-fields"
import { isNumericFieldType } from "@/lib/field-types"
import { Badge } from "../ui/badge"
import { useToast } from "@/hooks/use-toast"
import { PasswordFieldInput } from "./password-field-input"
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)))
setIsViewIsViewType(table?.type === "view")
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));
if (!hasFileField) {
return JSON.stringify(data);
}
const formData = new FormData();
for (const [key, value] of Object.entries(data)) {
const field = tableFields.find(f => f.name === key);
if (!field) continue;
if (field.type === "file") {
if (value instanceof File) {
formData.append(key, value);
}
} else if (field.type === "files") {
if (Array.isArray(value)) {
value.forEach((file, idx) => {
if (file instanceof File) {
formData.append(key, file);
}
});
}
} else {
formData.append(key, typeof value === "object" ? JSON.stringify(value) : String(value));
}
}
return formData;
};
const handleSubmit = async () => {
setIsLoading(true)
try {
const createdItem = await apiClient.call<any>(`/api/v1/${table.name}`, {
const body = prepareRequestBody(formData, tableFields);
const collectionUrl = entityCollectionPath ?? `/api/v1/entities/${table.schema.name}`
const createdItem = await apiClient.call<any>(collectionUrl, {
method: "POST",
body: JSON.stringify(formData),
body: body,
})
// If the request failed, throw the error here
if (createdItem?.error?.length > 0) throw createdItem.error
onItemAdded(createdItem)
onClose()
toast({
title: "Table Created",
description: `A table ${table.name} has been created successfully.`,
title: "Table Record Created",
description: `The record was created successfully.`,
duration: 2000,
})
} catch (error) {
console.error("Failed to update item:", error)
console.error("Failed to create item:", error)
} finally {
setIsLoading(false)
}
}
const handleFieldChange = (fieldName: string, value: string) => {
const castToType = (fieldName: string, value: any): any => {
const field = tableFields?.find((f: any) => f.name === fieldName);
if (!field) return value;
// 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 {
switch (type) {
case "string":
case "xml":
case "blob":
return String(value);
case "int":
case "int8":
case "int16":
case "int32":
case "int64":
case "uint8":
case "uint16":
case "uint32":
case "uint64":
case "double": {
return Number(value);
}
case "bool":
if (typeof value === "boolean") return value;
if (typeof value === "string") return value.toLowerCase() === "true";
return Boolean(value);
case "json":
return typeof value === "object" ? value : JSON.parse(value);
case "date": {
const date = new Date(value);
return isNaN(date.getTime()) ? null : date.toISOString();
}
case "file":
return value instanceof File ? value : null;
case "files":
if (Array.isArray(value)) return value;
if (value instanceof FileList) return Array.from(value);
return [];
default:
return value;
}
} catch {
return value; // fallback on parse errors
}
};
const handleFieldChange = (fieldName: string, value: any) => {
setFormData((prev: any) => ({
...prev,
[fieldName]: value,
[fieldName]: castToType(fieldName, value),
}))
setHasUnsavedChanges(true)
}
const isSystemGeneratedField = (field: any) => {
console.log(field.name)
return field.system && ["id", "created", "updated"].includes(field.name)
}
@@ -89,6 +232,19 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
}
}
const isIntegralType = (type: string) => isNumericFieldType(type)
function formatDateForInput(value: string | Date | number | undefined): string {
if (value === null || value === undefined || value === "") {
return ""
}
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"
}
return (
<Drawer open={open} onOpenChange={handleClose}>
<DrawerContent side="right" className="w-[700px] max-w-[95vw]">
@@ -102,15 +258,15 @@ export function AddItemDrawer({ table, apiClient, open, onClose, onItemAdded }:
<X className="h-4 w-4" />
</Button>
</div>
<DrawerDescription>Create a new record in {table.name} table</DrawerDescription>
<DrawerDescription>Create a new record in {table.schema.name} table</DrawerDescription>
</DrawerHeader>
<div className="flex-1 overflow-hidden">
<div className="flex-1 overflow-auto">
<ScrollArea className="h-full">
<div className="p-6 space-y-6">
<div className="p-6 space-y-6 pb-64">
<div className="text-sm text-muted-foreground">
Autogenerated fields for <Badge variant="default" className="text-sm mr-2">
{table.name}
{table.schema.name}
</Badge>table: <Badge variant="outline" className="text-xs mr-2">
id
</Badge>
@@ -122,27 +278,140 @@ 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>}
{isFieldRequiredInForm(field, table.schema.type) && <span className="text-red-500 ml-1">*</span>}
</Label>
<Input
id={field.name}
type={
field.name === "password"
? "password"
: field.type === "date" ? "datetime-local" : "text"
}
value={formData[field.name] || ""}
onChange={(e) => handleFieldChange(field.name, e.target.value)}
disabled={(field.type === "view" || isSystemGeneratedField(field))}
className={`w-full ${(field.type === "view" || isSystemGeneratedField(field)) ? "bg-muted" : ""}`}
placeholder={`Enter ${field.name}`}
/>
{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="space-y-2">
<div className="flex items-center gap-2">
<Switch
id={field.name}
checked={!!formData[field.name]}
onCheckedChange={(checked: any) => handleFieldChange(field.name, checked)}
disabled={field.type === "view" || isSystemGeneratedField(field)}
/>
<span>
{field.name === "email_verified"
? formData[field.name]
? "Verified"
: "Unverified"
: formData[field.name] === true
? "True"
: "False"}
</span>
</div>
{table.schema.type === "auth" && field.name === "email_verified" && (
<p className="text-xs text-muted-foreground">
Defaults to unverified. After creating the user, open Edit to send a verification email.
</p>
)}
</div>
) : field.type === "file" ? (
<Input
id={field.name}
type="file"
onChange={(e) => handleFieldChange(field.name, e.target.files?.[0])}
disabled={(field.type === "view" || isSystemGeneratedField(field))}
className={`w-full ${(field.type === "view" || isSystemGeneratedField(field)) ? "bg-muted" : ""}`}
/>
) : field.type === "files" ? (
<Input
id={field.name}
type="file"
multiple
onChange={(e) => handleFieldChange(field.name, e.target.files)}
disabled={(field.type === "view" || isSystemGeneratedField(field))}
className={`w-full ${(field.type === "view" || isSystemGeneratedField(field)) ? "bg-muted" : ""}`}
/>
) : isIntegralType(field.type) ? (
<Input
id={field.name}
type="number"
value={formData[field.name] ?? ""}
onChange={(e) => handleFieldChange(field.name, e.target.value)}
disabled={(field.type === "view" || isSystemGeneratedField(field))}
className={`w-full ${(field.type === "view" || isSystemGeneratedField(field)) ? "bg-muted" : ""}`}
placeholder={`Enter '${field.name}' value`}
/>
) : field.name === "password" ? (
<div className="space-y-2">
<PasswordFieldInput
id={field.name}
value={formData[field.name] ?? ""}
onChange={(next) => handleFieldChange(field.name, next)}
disabled={field.type === "view" || isSystemGeneratedField(field)}
className={field.type === "view" || isSystemGeneratedField(field) ? "bg-muted" : ""}
placeholder={
table.schema.type === "auth"
? "Optional — leave blank for OAuth-only users"
: "Enter password"
}
/>
{table.schema.type === "auth" && (
<p className="text-xs text-muted-foreground">
Optional for auth entities. OAuth users may have no password.
</p>
)}
</div>
) : field.type === "date" ? (
<Input
id={field.name}
type="datetime-local"
onFocus={(e) => {
// scroll parent container into view
e.target.scrollIntoView({ behavior: "auto", block: "center" });
}}
value={formatDateForInput(formData[field.name])}
onChange={(e) => handleFieldChange(field.name, e.target.value)}
disabled={(field.type === "view" || isSystemGeneratedField(field))}
className={`w-full ${(field.type === "view" || isSystemGeneratedField(field)) ? "bg-muted" : ""}`}
/>
) : (
<Input
id={field.name}
type="text"
value={formData[field.name] ?? ""}
onChange={(e) => handleFieldChange(field.name, e.target.value)}
disabled={(field.type === "view" || isSystemGeneratedField(field))}
className={`w-full ${(field.type === "view" || isSystemGeneratedField(field)) ? "bg-muted" : ""}`}
placeholder={`Enter '${field.name}' value`}
/>
)}
</div>
))}
)})}
{(!tableFields || tableFields.length === 0) &&
<p className="text-xs text-muted-foreground">No additional fields for input, proceed to create the record.</p>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,145 @@
"use client"
import * as React from "react"
import { ChevronDown, ChevronRight, Copy } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
import { ScrollArea } from "@/components/ui/scroll-area"
export function getMethodColor(method: string): string {
switch (method) {
case "GET":
return "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"
case "POST":
return "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"
case "PATCH":
return "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200"
case "DELETE":
return "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"
default:
return "bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200"
}
}
export function copyToClipboard(text: string): void {
navigator.clipboard.writeText(text)
}
export function DocCodeBlock({
code,
height = "h-48",
}: {
code: string
height?: string
}) {
return (
<div>
<div className="flex justify-end mb-2">
<Button variant="outline" size="sm" onClick={() => copyToClipboard(code)} className="h-8">
<Copy className="h-3 w-3 mr-1" />
Copy
</Button>
</div>
<ScrollArea className={height}>
<pre className="bg-muted p-4 rounded text-sm border whitespace-pre">
<code>{code}</code>
</pre>
</ScrollArea>
</div>
)
}
export function DocCollapsibleSection({
title,
description,
icon,
defaultOpen = false,
children,
}: {
title: React.ReactNode
description?: string
icon?: React.ReactNode
defaultOpen?: boolean
children: React.ReactNode
}) {
const [isOpen, setIsOpen] = React.useState(defaultOpen)
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">
{icon}
<span className="font-medium">{title}</span>
{isOpen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
</div>
</div>
{description && <p className="text-sm text-muted-foreground mt-2">{description}</p>}
</div>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="border-l-2 border-muted ml-4 pl-6 space-y-6 mt-4">{children}</div>
</CollapsibleContent>
</Collapsible>
)
}
export function DocEndpointHeader({
method,
endpoint,
description,
isOpen,
}: {
method: string
endpoint: string
description: string
isOpen: boolean
}) {
return (
<>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<Badge className={getMethodColor(method)} variant="secondary">
{method}
</Badge>
<code className="text-sm font-mono bg-muted px-2 py-1 rounded">{endpoint}</code>
{isOpen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
</div>
</div>
<p className="text-sm text-muted-foreground mt-2">{description}</p>
</>
)
}
export function DocErrorList({ errors }: { errors: Array<{ code: string; message: string }> }) {
return (
<div>
<h5 className="font-medium mb-3">Possible Errors</h5>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
{errors.map((error) => (
<div key={error.code} className="flex items-center gap-2">
<Badge variant="destructive" className="text-xs">
{error.code}
</Badge>
<span>{error.message}</span>
</div>
))}
</div>
</div>
)
}
export function DocSectionHeading({ children }: { children: React.ReactNode }) {
return (
<div className="pt-2">
<h3 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">{children}</h3>
</div>
)
}
export function DocInfoBanner({ children }: { children: React.ReactNode }) {
return <div className="rounded-lg border bg-muted/30 p-4">{children}</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,20 +1,46 @@
"use client"
import * as React from "react"
import { Search, Table, Eye, Trash2, MoreHorizontal, RefreshCw, Plus, ExternalLink, FileText } 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, CardHeader, CardTitle } from "@/components/ui/card"
import { Card, CardContent } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
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 { applySchemaListMigration } from "@/lib/schema-migration"
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 { useNavigate, useParams, useSearchParams } from "react-router-dom"
import { entityDetailPath, ROUTES } from "@/lib/routes"
import { useToast } from "@/hooks/use-toast"
import { cn } from "@/lib/utils"
interface DatabaseSectionProps {
apiClient: ApiClient
@@ -23,57 +49,162 @@ interface DatabaseSectionProps {
}
export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseSectionProps) {
const [searchTerm, setSearchTerm] = React.useState("")
const { name: entityNameParam } = useParams<{ name?: string }>()
const [searchParams, setSearchParams] = useSearchParams()
const navigate = useNavigate()
const { toast } = useToast()
const initialFilter = searchParams.get("filter") || ""
const [searchTerm, setSearchTerm] = React.useState(initialFilter)
const [editingTable, setEditingTable] = React.useState<TableMetadata | null>(null)
const [searchExpanded, setSearchExpanded] = React.useState(false)
const [isRefreshing, setIsRefreshing] = React.useState(false)
const [docsOpen, setDocsOpen] = React.useState(false)
const { route, navigate } = useRouter()
const { toast } = useToast()
// Check if we're viewing a specific table - safer parsing
const getSelectedTableName = () => {
try {
const pathParts = route.path.split("/").filter(Boolean)
return pathParts.length > 1 && pathParts[0] === "tables" ? pathParts[1] : null
} catch (error) {
console.warn("Error parsing table route:", error)
return null
// 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 = searchParams.get("filter") || ""
if (filterFromQuery !== searchTerm) {
setSearchTerm(filterFromQuery)
}
}
}, [searchParams])
const selectedTableName = getSelectedTableName()
// Update URL when search term changes (debounced)
React.useEffect(() => {
const timeoutId = setTimeout(() => {
const nextParams = new URLSearchParams(searchParams)
if (searchTerm) {
nextParams.set("filter", searchTerm)
} else {
nextParams.delete("filter")
}
const filteredTables = tables?.filter((table) => table.name.toLowerCase().includes(searchTerm.toLowerCase()))
if (nextParams.toString() !== searchParams.toString()) {
setSearchParams(nextParams, { replace: true })
}
}, 300)
return () => clearTimeout(timeoutId)
}, [searchTerm, searchParams, setSearchParams])
// Get selected entity name from route params
const selectedEntityName = entityNameParam || null
const filteredTables = Array.isArray(tables) ? tables?.filter((table) => table?.schema?.name?.toLowerCase().includes(searchTerm.toLowerCase())) : []
const handleDeleteTable = async (tableId: string) => {
setIsDeleting(true)
try {
await apiClient.call(`/api/v1/tables/${tableId}`, { method: "DELETE" })
const updatedTables = await apiClient.call<TableMetadata[]>("/api/v1/tables")
onTablesUpdate(updatedTables)
const res: any = await apiClient.call(`/api/v1/schemas/${tableId}`, { method: "DELETE" })
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(await applySchemaListMigration(apiClient, 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({
variant: "destructive",
title: "Error",
description: error instanceof Error ? error.message : "Failed to delete entity",
})
} finally {
setIsDeleting(false)
}
}
const handleTableClick = (tableName: string) => {
try {
navigate(`/tables/${tableName}`)
} catch (error) {
console.warn("Failed to navigate to table:", error)
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(await applySchemaListMigration(apiClient, 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)
}
}
const handleEntityClick = (entityName: string) => {
navigate(entityDetailPath(entityName))
}
const handleRefresh = async () => {
setIsRefreshing(true)
try {
const updatedTables = await apiClient.call<TableMetadata[]>("/api/v1/tables")
onTablesUpdate(updatedTables)
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
}
const migratedTables = await applySchemaListMigration(apiClient, updatedTables)
onTablesUpdate(migratedTables)
} catch (error) {
console.error("Failed to refresh tables:", error)
} finally {
@@ -81,159 +212,255 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
}
}
if (selectedTableName) {
const tableInfo = tables.find((t) => t.name === selectedTableName)
if (tableInfo) {
return (
<TableDetailView
table={tableInfo}
onBack={() => {
try {
navigate("/tables")
} catch (error) {
console.warn("Failed to navigate back:", error)
}
}}
apiClient={apiClient}
onTableUpdate={(updatedTable) => {
const updatedTables = tables.map((t) => (t.id === updatedTable.id ? updatedTable : t))
onTablesUpdate(updatedTables)
}}
/>
)
}
}
const selectedEntity = selectedEntityName
? Array.isArray(tables) ? tables.find((t) => t.schema.name === selectedEntityName) : null
: null
return (
<div className="space-y-6">
{/* Top Bar */}
<div className="flex items-center gap-4">
<SidebarTrigger />
{/* Expandable Search */}
<div className={`flex items-center transition-all duration-200 ${searchExpanded ? "flex-1" : ""}`}>
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search tables..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onFocus={() => setSearchExpanded(true)}
onBlur={() => {
if (!searchTerm) setSearchExpanded(false)
}}
className={`pl-10 transition-all duration-200 ${searchExpanded ? "w-80" : "w-64"}`}
/>
<div className="flex h-[100vh] gap-4 pr-8">
{/* Entity List Sidebar */}
<div className="w-64 flex-shrink-0 border-r bg-muted/30">
<div className="flex flex-col h-full">
{/* Sidebar Header */}
<div className="p-4 border-b space-y-3">
<div className="flex items-center justify-between">
<h2 className="text-lg font-semibold flex items-center gap-2">
<Database className="h-5 w-5" />
Entities
</h2>
<Button variant="ghost" size="icon" onClick={handleRefresh} disabled={isRefreshing}>
<RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />
</Button>
</div>
<div className="relative">
<Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search entities..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-8 h-9"
/>
</div>
<div className="flex gap-2">
<AddTableDialog apiClient={apiClient} onTablesUpdate={onTablesUpdate} tables={tables}>
<Button size="sm" className="flex-1">
<Plus className="h-4 w-4 mr-2" />
New
</Button>
</AddTableDialog>
<Button variant="outline" size="sm" onClick={() => setDocsOpen(true)}>
<FileText className="h-4 w-4" />
</Button>
</div>
</div>
</div>
<div className="ml-auto flex gap-2">
<Button variant="outline" size="sm" onClick={handleRefresh} disabled={isRefreshing}>
<RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />
</Button>
<Button variant="outline" size="sm" onClick={() => setDocsOpen(true)}>
<FileText className="h-4 w-4 mr-2" />
Table API Docs
</Button>
<AddTableDialog apiClient={apiClient} onTablesUpdate={onTablesUpdate} />
{/* Entity List */}
<ScrollArea className="flex-1">
<div className="p-2 space-y-1">
{filteredTables.length === 0 ? (
<div className="p-4 text-center text-sm text-muted-foreground">
{searchTerm ? "No entities found matching the search term" : "No entities, add some to get started"}
</div>
) : (
filteredTables.map((table) => {
const TypeIcon = table.schema.type === "auth" ? User : table.schema.type === "view" ? LayoutDashboard : Database
return (
<div
key={table.id}
className={cn(
"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"
)}
>
<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>
<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>
</div>
</div>
{tables.length === 0 && !isRefreshing ? (
<Card>
<CardContent className="flex flex-col items-center justify-center py-16">
<Table className="h-12 w-12 text-muted-foreground mb-4" />
<h3 className="text-lg font-semibold mb-2">No Tables Found</h3>
<p className="text-muted-foreground text-center mb-6 max-w-md">
Get started by creating your first table. Tables are used to store and organize your data.
</p>
<div className="flex gap-3">
<AddTableDialog apiClient={apiClient} onTablesUpdate={onTablesUpdate}>
<Button>
<Plus className="h-4 w-4 mr-2" />
Create Table
</Button>
</AddTableDialog>
<Button variant="outline" onClick={() => setDocsOpen(true)}>
<ExternalLink className="h-4 w-4 mr-2" />
View Documentation
</Button>
</div>
</CardContent>
</Card>
) : (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{filteredTables.map((table) => (
<Card
key={table.id}
className="cursor-pointer hover:shadow-md transition-shadow"
onClick={() => handleTableClick(table.name)}
>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
<div className="flex items-center gap-2">
<Table className="h-4 w-4" />
{table.name}
<Badge
variant={table.type === "auth" ? "default" : table.type === "view" ? "secondary" : "outline"}
className="text-xs"
>
{table.type}
</Badge>
</div>
</CardTitle>
<DropdownMenu>
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
<Button variant="ghost" size="sm">
<MoreHorizontal className="h-4 w-4" />
{/* Main Content Area */}
<div className="flex-1 overflow-auto pt-4 pl-4">
{selectedEntity ? (
<TableDetailView
table={selectedEntity}
onBack={() => navigate(ROUTES.entities)}
apiClient={apiClient}
onTableUpdate={(updatedTable) => {
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">
{tables.length === 0 && !isRefreshing ? (
<Card className="w-full max-w-md">
<CardContent className="flex flex-col items-center justify-center py-16">
<Table className="h-12 w-12 text-muted-foreground mb-4" />
<h3 className="text-lg font-semibold mb-2">No Entities Found</h3>
<p className="text-muted-foreground text-center mb-6">
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} tables={tables}>
<Button>
<Plus className="h-4 w-4 mr-2" />
Create Entity
</Button>
</AddTableDialog>
<Button variant="outline" onClick={() => setDocsOpen(true)}>
<ExternalLink className="h-4 w-4 mr-2" />
View Documentation
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
handleTableClick(table.name)
}}
>
<Eye className="h-4 w-4 mr-2" />
View Details
</DropdownMenuItem>
<DropdownMenuItem
className="text-destructive"
onClick={(e) => {
e.stopPropagation()
handleDeleteTable(table.id)
}}
>
<Trash2 className="h-4 w-4 mr-2" />
Delete Table
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Type:</span>
<span className="font-medium capitalize">{table.type}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Fields:</span>
<span className="font-medium">{table.schema.fields?.length || 0}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Created:</span>
<span className="font-medium">{new Date(table.created).toLocaleDateString()}</span>
</div>
</CardContent>
</Card>
) : (
<div className="text-center space-y-4">
<Database className="h-16 w-16 text-muted-foreground mx-auto" />
<div>
<h2 className="text-2xl font-semibold mb-2">Select an Entity</h2>
<p className="text-muted-foreground">
Choose an entity from the sidebar to view and manage its data
</p>
</div>
</CardContent>
</Card>
))}
</div>
)}
</div>
)}
</div>
)}
</div>
{/* Open docs on table CRUD */}
{/* 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

@@ -6,6 +6,7 @@ import { Edit, X } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import {
Drawer,
DrawerContent,
@@ -15,8 +16,13 @@ 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 { ApiClient, TableMetadata, TableField, buildEntityFileUrl } from "@/lib/api"
import { isFieldRequiredInForm } from "@/lib/auth-fields"
import { formatFieldTypeDisplay, isNumericFieldType } from "@/lib/field-types"
import { useToast } from "@/hooks/use-toast"
import { PasswordFieldInput } from "./password-field-input"
import { SendVerificationButton } from "./send-verification-button"
interface EditItemDrawerProps {
table: TableMetadata
@@ -27,34 +33,222 @@ interface EditItemDrawerProps {
onItemUpdate: (item: any) => void
}
const FilePreviewField = ({
field,
value,
onChange,
onDelete,
multiple = false,
table,
}: {
field: any;
value: any;
onChange: (val: File | File[] | null) => void;
onDelete: (index: number) => void;
multiple?: boolean;
table: TableMetadata;
}) => {
const files = Array.isArray(value) ? value : value ? [value] : [];
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const selected = e.target.files ? Array.from(e.target.files) : [];
if (multiple) {
onChange([...files, ...selected]);
} else {
onChange(selected[0] || null);
}
};
const getFileUrl = (file: File | string): string => {
if (typeof file === "string") {
return buildEntityFileUrl(table.schema.name, file);
}
return URL.createObjectURL(file); // for newly selected files
};
const getFileName = (file: File | string): string => {
return typeof file === "string" ? file : file.name;
};
const isImageFile = (file: File | string): boolean => {
const name = getFileName(file);
return name.match(/\.(jpg|jpeg|png|gif|webp)$/i) !== null;
};
return (
<div className="space-y-2">
<div className="flex flex-wrap gap-3">
{files.map((file, idx) => {
const url = getFileUrl(file);
const isImage = isImageFile(file);
return (
<div key={idx} className="relative group w-24 h-24 border rounded-md overflow-hidden">
{isImage ? (
<img src={url} alt="Preview" className="object-cover w-full h-full" />
) : (
<div className="flex items-center justify-center h-full text-xs p-2 text-center">
📄 {file.name || "file"}
</div>
)}
<div
onClick={() => onDelete(idx)}
className="absolute top-1 right-1 bg-white/80 rounded-full p-1 cursor-pointer hidden group-hover:block"
>
❌
</div>
</div>
);
})}
</div>
<Input
type="file"
multiple={multiple}
onChange={handleFileChange}
className="w-fit"
placeholder={`Enter '${field.type}' value`}
/>
</div>
);
};
export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUpdate }: EditItemDrawerProps) {
const [tableFields, setTableFields] = React.useState<any>([])
const [formData, setFormData] = React.useState<any>({})
const [isLoading, setIsLoading] = React.useState(false)
const [isViewType, setIsViewIsViewType] = React.useState(false)
const [hasUnsavedChanges, setHasUnsavedChanges] = React.useState(false)
const [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)
setIsViewIsViewType(table?.type === "view")
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));
if (!hasFileField) {
return JSON.stringify(data);
}
const formData = new FormData();
for (const [key, value] of Object.entries(data)) {
const field = tableFields.find(f => f.name === key);
if (!field) continue;
if (value === null || value === undefined) {
formData.append(key, "");
continue;
}
if (field.type === "file") {
if (value instanceof File) {
formData.append(key, value);
}
} else if (field.type === "files") {
if (Array.isArray(value)) {
var files = value.filter(v => v instanceof File);
var arr = value.filter(v => !(v instanceof File));
files.forEach((file, idx) => {
if (file instanceof File) {
formData.append(key, file);
}
});
// Append the array of non-file values as a JSON string
if (arr.length > 0) {
formData.append(key, JSON.stringify(arr));
} else {
// Append empty string only if no files were added
if (files.length === 0) {
formData.append(key, "");
}
}
}
} else {
formData.append(key, value);
}
}
return formData;
};
const handleSubmit = async () => {
setIsLoading(true)
try {
const updatedItem = await apiClient.call<any>(`/api/v1/${table.name}/${item.id}`, {
const body = prepareRequestBody(formData, tableFields);
console.log("Body to send:", body);
if (!body) {
toast({
title: "Error",
description: "No data to update.",
variant: "destructive",
duration: 3000,
});
setIsLoading(false);
return;
}
const updatedItem = await apiClient.call<any>(`/api/v1/entities/${table?.schema?.name}/${formData["id"]}`, {
method: "PATCH",
body: JSON.stringify(formData),
body: body,
})
// If the request failed, throw the error here
if (updatedItem?.error?.length > 0) throw updatedItem.error
onItemUpdate(updatedItem)
onClose()
toast({
title: "Table Updated",
description: "Table data has been updated successfully.",
title: "Table Record Updated",
description: "Table record was updated successfully.",
duration: 3000,
})
} catch (error) {
console.error("Failed to update item:", error)
@@ -63,10 +257,74 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
}
}
const handleFieldChange = (fieldName: string, value: string) => {
const castToType = (fieldName: string, value: any): any => {
const field = tableFields?.find((f: any) => f.name === fieldName);
if (!field) return value;
// 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;
try {
switch (type) {
case "int":
case "int8":
case "int16":
case "int32":
case "int64":
case "uint8":
case "uint16":
case "uint32":
case "uint64":
case "double": {
return Number(value);
}
case "bool":
if (typeof value === "boolean") return value;
if (typeof value === "string") return value.toLowerCase() === "true";
return Boolean(value);
case "json":
return typeof value === "object" ? value : JSON.parse(value);
case "date": {
const date = new Date(value);
return isNaN(date.getTime()) ? null : date.toISOString();
}
case "file":
return value instanceof File ? value : null;
case "files":
if (Array.isArray(value)) return value;
if (value instanceof FileList) return Array.from(value);
return [];
default:
return value;
}
} catch {
return value; // fallback on parse errors
}
};
const handleFieldChange = (fieldName: string, value: any) => {
const v = castToType(fieldName, value);
console.log(`Field changed: ${fieldName}, Value: ${v}, Type: ${typeof v}`);
setFormData((prev: any) => ({
...prev,
[fieldName]: value,
[fieldName]: v,
}))
setHasUnsavedChanges(true)
}
@@ -86,6 +344,28 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
}
}
const handleFileDelete = (fieldName: string, index: number) => {
const value = formData[fieldName];
const updated = Array.isArray(value)
? value.filter((_, i) => i !== index)
: null;
// Update the form data with the new value
handleFieldChange(fieldName, updated);
};
function formatDateForInput(value: string | Date | number | undefined): string {
if (value === null || value === undefined || value === "") {
return ""
}
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"
}
return (
<Drawer open={open} onOpenChange={handleClose}>
<DrawerContent side="right" className="w-[700px] max-w-[95vw]">
@@ -99,43 +379,155 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
<X className="h-4 w-4" />
</Button>
</div>
<DrawerDescription>Edit record in {table.name} table</DrawerDescription>
<DrawerDescription>Edit record in {table.schema.name} table</DrawerDescription>
</DrawerHeader>
<div className="flex-1 overflow-hidden">
<ScrollArea className="h-full">
<div className="p-6 space-y-6">
{table.schema.fields?.map((field) => (
<div key={field.name} className="space-y-2">
<Label htmlFor={field.name} className="text-sm font-medium capitalize">
{field.name}
{!field.required && <span className="text-red-500 ml-1">*</span>}
</Label>
<Input
id={field.name}
type={
field.name === "password"
? "password"
: field.type === "datetime" || field.type === "timestamp"
? "datetime-local"
: "text"
}
value={formData[field.name] || ""}
onChange={(e) => handleFieldChange(field.name, e.target.value)}
disabled={isSystemGeneratedField(field)}
className={`w-full ${isSystemGeneratedField(field) ? "bg-muted" : ""}`}
placeholder={`Enter ${field.name}`}
/>
{isSystemGeneratedField(field) && (
<p className="text-xs text-muted-foreground">System generated field - cannot be modified</p>
)}
{(table.type === "auth" && field.name === "password") && (
<p className="text-xs text-muted-foreground">Password fields are redacted in API responses.</p>
)}
</div>
))}
{table.schema.fields?.map((field) => {
const isDisabled = (field.type === "view" || isSystemGeneratedField(field));
const value = formData[field.name];
const isFileField = field.type === "file" || field.type === "files";
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">
{field.name}
{isFieldRequiredInForm(field, table.schema.type) && <span className="text-red-500 ml-1">*</span>}
</Label>
{/* 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}
onChange={(newValue) => handleFieldChange(field.name, newValue)}
onDelete={(index) => handleFileDelete(field.name, index)}
multiple={field.type === "files"}
table={table}
/>
) : field.type === "bool" ? (
<div className="space-y-2">
<div className="flex items-center gap-2">
<Switch
id={field.name}
checked={!!value}
onCheckedChange={(checked) => handleFieldChange(field.name, checked)}
disabled={isDisabled}
/>
<span>
{field.name === "email_verified"
? formData[field.name]
? "Verified"
: "Unverified"
: formData[field.name] === true
? "True"
: "False"}
</span>
</div>
{table.schema.type === "auth" && field.name === "email_verified" && (
<div className="space-y-2">
<p className="text-xs text-muted-foreground">
Admins can set this flag. Changing the email clears verification unless you also set
email_verified in the same save.
</p>
<SendVerificationButton
entityName={table.schema.name}
email={formData.email}
apiClient={apiClient}
/>
</div>
)}
</div>
) : field.type === "date" || field.type === "datetime" || field.type === "timestamp" ? (
<Input
id={field.name}
type="datetime-local"
value={value !== null && value !== undefined ? formatDateForInput(value) : ""}
onChange={(e) => handleFieldChange(field.name, e.target.value)}
disabled={isDisabled}
className={`w-full ${isDisabled ? "bg-muted" : ""}`}
/>
) : isNumericFieldType(field.type) ? (
<Input
id={field.name}
type="number"
value={value ?? ""}
onChange={(e) => handleFieldChange(field.name, e.target.value)}
disabled={isDisabled}
className={`w-full ${isDisabled ? "bg-muted" : ""}`}
placeholder={`Enter '${formatFieldTypeDisplay(field)}' value`}
/>
) : field.name === "password" ? (
<div className="space-y-2">
<PasswordFieldInput
id={field.name}
value={value ?? ""}
onChange={(next) => handleFieldChange(field.name, next)}
disabled={isDisabled}
className={isDisabled ? "bg-muted" : ""}
placeholder={
table.schema.type === "auth"
? "Leave blank to keep current / OAuth-only"
: "Enter password"
}
/>
{table.schema.type === "auth" && (
<p className="text-xs text-muted-foreground">
Optional. Leave blank to keep the current password. Responses redact password values.
</p>
)}
</div>
) : (
<Input
id={field.name}
type="text"
value={value ?? ""}
onChange={(e) => handleFieldChange(field.name, e.target.value)}
disabled={isDisabled}
className={`w-full ${isDisabled ? "bg-muted" : ""}`}
placeholder={`Enter '${field.type}' value`}
/>
)}
{isDisabled && (
<p className="text-xs text-muted-foreground">System generated field - cannot be modified</p>
)}
</div>
);
})}
</div>
</ScrollArea>
</div>
<DrawerFooter>

View File

@@ -0,0 +1,110 @@
"use client"
import * as React from "react"
import { Check, Copy, Eye, EyeOff, RefreshCw } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { generateRandomPassword } from "@/lib/auth-fields"
import { useToast } from "@/hooks/use-toast"
import { cn } from "@/lib/utils"
interface PasswordFieldInputProps {
id?: string
value: string
onChange: (value: string) => void
disabled?: boolean
className?: string
placeholder?: string
}
export function PasswordFieldInput({
id,
value,
onChange,
disabled,
className,
placeholder = "Enter password or generate one",
}: PasswordFieldInputProps) {
const { toast } = useToast()
const [visible, setVisible] = React.useState(false)
const [copied, setCopied] = React.useState(false)
const handleGenerate = () => {
const next = generateRandomPassword()
onChange(next)
setVisible(true)
toast({
title: "Password Generated",
description: "A random password was filled in. Copy it before saving if you need to share it.",
duration: 3000,
})
}
const handleCopy = async () => {
if (!value) {
toast({
variant: "destructive",
title: "Nothing to copy",
description: "Generate or enter a password first.",
})
return
}
try {
await navigator.clipboard.writeText(value)
setCopied(true)
toast({
title: "Copied",
description: "Password copied to clipboard.",
duration: 2000,
})
window.setTimeout(() => setCopied(false), 1500)
} catch {
toast({
variant: "destructive",
title: "Copy failed",
description: "Could not copy to clipboard.",
})
}
}
return (
<div className="space-y-2">
<div className="flex gap-2">
<div className="relative flex-1">
<Input
id={id}
type={visible ? "text" : "password"}
value={value}
onChange={(event) => onChange(event.target.value)}
disabled={disabled}
className={cn("pr-10", className)}
placeholder={placeholder}
autoComplete="new-password"
/>
<Button
type="button"
variant="ghost"
size="icon"
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2"
onClick={() => setVisible((current) => !current)}
disabled={disabled}
aria-label={visible ? "Hide password" : "Show password"}
>
{visible ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
</div>
</div>
<div className="flex flex-wrap gap-2">
<Button type="button" variant="outline" size="sm" onClick={handleGenerate} disabled={disabled}>
<RefreshCw className="mr-2 h-3.5 w-3.5" />
Generate
</Button>
<Button type="button" variant="outline" size="sm" onClick={handleCopy} disabled={disabled || !value}>
{copied ? <Check className="mr-2 h-3.5 w-3.5" /> : <Copy className="mr-2 h-3.5 w-3.5" />}
Copy
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,85 @@
"use client"
import * as React from "react"
import { Mail } from "lucide-react"
import { Button } from "@/components/ui/button"
import { getApiClientError, type ApiClient } from "@/lib/api"
import { useToast } from "@/hooks/use-toast"
interface SendVerificationButtonProps {
entityName: string
email: string | null | undefined
apiClient: ApiClient
variant?: "default" | "outline" | "ghost" | "secondary"
size?: "default" | "sm" | "lg" | "icon"
className?: string
}
export function SendVerificationButton({
entityName,
email,
apiClient,
variant = "outline",
size = "sm",
className,
}: SendVerificationButtonProps) {
const { toast } = useToast()
const [isSending, setIsSending] = React.useState(false)
const trimmedEmail = typeof email === "string" ? email.trim() : ""
const handleSend = async () => {
if (!trimmedEmail) {
toast({
variant: "destructive",
title: "Email required",
description: "This user has no email address to send a verification link to.",
})
return
}
setIsSending(true)
try {
const response = await apiClient.call<{ sent?: boolean }>(
`/api/v1/auth/${encodeURIComponent(entityName)}/verify-email/request`,
{
method: "POST",
body: JSON.stringify({ email: trimmedEmail }),
},
)
const error = getApiClientError(response)
if (error) {
throw new Error(error)
}
toast({
title: "Verification Email Requested",
description: "If an account exists for that email, we sent a verification link.",
duration: 4000,
})
} catch (error) {
console.error("Failed to send verification email:", error)
toast({
variant: "destructive",
title: "Could not send verification",
description: error instanceof Error ? error.message : "Failed to send verification email.",
})
} finally {
setIsSending(false)
}
}
return (
<Button
type="button"
variant={variant}
size={size}
className={className}
onClick={handleSend}
disabled={isSending || !trimmedEmail}
>
<Mail className="mr-2 h-3.5 w-3.5" />
{isSending ? "Sending..." : "Send verification email"}
</Button>
)
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,30 +1,37 @@
"use client"
import * as React from "react"
import { RefreshCw, Cog, FileText, Trash2, Search, Plus } from "lucide-react"
import { RefreshCw, Cog, FileText, Trash2, Search, Plus, Key, KeyRound, Mail, MoreHorizontal } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Checkbox } from "@/components/ui/checkbox"
import { Input } from "@/components/ui/input"
import { SidebarTrigger } from "@/components/ui/sidebar"
import type { ApiClient, TableMetadata } from "@/lib/api"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { ApiClient, TableMetadata, buildEntityFileUrl, entityApiKeysApi, getApiClientError } from "@/lib/api"
import { toApiKeyUsers } from "@/lib/entity-users"
import { ApiKeysPanel, openCreateApiKeyDialog } from "@/components/api-keys/api-keys-panel"
import { useToast } from "@/hooks/use-toast"
import { TableConfigDrawer } from "./table-config-drawer"
import { TableRecordDocsDrawer } from "./table-records-docs-drawer"
import { EditItemDrawer } from "./edit-item-drawer"
import { AddItemDrawer } from "./add-item-drawer"
import { ColumnVisibilityDropdown } from "./column-visibility-dropdown"
import { useToast } from "@/hooks/use-toast"
import { useSearchParams } from "react-router-dom"
interface TableDetailViewProps {
table: TableMetadata
onBack: () => void
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)
@@ -39,17 +46,66 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
table.schema.fields?.map((field) => field.name) || [],
)
const [isDeleting, setIsDeleting] = React.useState(false)
const [filterTerm, setFilterTerm] = React.useState("")
const [appliedFilter, setAppliedFilter] = React.useState("")
const [activeTab, setActiveTab] = React.useState("records")
const [createApiKeyForUserId, setCreateApiKeyForUserId] = React.useState<string | undefined>()
const [createApiKeyRequested, setCreateApiKeyRequested] = React.useState(false)
const [apiKeysReloadRequested, setApiKeysReloadRequested] = React.useState(0)
const [apiKeysLoading, setApiKeysLoading] = React.useState(false)
const [searchParams, setSearchParams] = useSearchParams()
const { toast } = useToast()
const isAuthEntity = table.schema.type === "auth"
const entityUsers = React.useMemo(() => toApiKeyUsers(tableData), [tableData])
const entityApiKeysPath = entityApiKeysApi(table.schema.name)
const entityApiKeysCacheKey = `mantis-entity-api-keys-${table.schema.name}`
const initialFilter = searchParams.get("filter") || ""
const [filterTerm, setFilterTerm] = React.useState(initialFilter)
const [appliedFilter, setAppliedFilter] = React.useState(initialFilter)
// Sync filter with query params
React.useEffect(() => {
const filterFromQuery = searchParams.get("filter") || ""
if (filterFromQuery !== appliedFilter) {
setAppliedFilter(filterFromQuery)
setFilterTerm(filterFromQuery)
}
}, [searchParams, appliedFilter])
// Clear data and reset state when switching entities
React.useEffect(() => {
// Clear table data immediately when entity changes
setTableData([])
setCurrentPage(1)
setTotalPages(1)
setSelectedItems([])
setFilterTerm("")
setAppliedFilter("")
setActiveTab("records")
setIsLoading(true)
// Update visible columns based on new table schema
setVisibleColumns(table.schema.fields?.map((field) => field.name) || [])
setIsViewType(table.schema.type === "view")
// Clear filter from URL when switching entities (if filter exists in query params)
if (searchParams.get("filter")) {
setSearchParams({}, { replace: true })
}
// Load new data after clearing - this will use the reset values (page 1, empty filter)
// Note: We don't need to call loadTableData here because the next useEffect will handle it
// when currentPage and appliedFilter are updated
}, [table.schema.name]) // Watch for entity name changes
// Load data when page, filter, or entity changes
React.useEffect(() => {
loadTableData()
}, [currentPage, appliedFilter])
}, [currentPage, appliedFilter, table.schema.name])
React.useEffect(() => {
setIsViewType(table.type === "view")
}, [table.type])
setIsViewType(table.schema.type === "view")
}, [table.schema.type])
React.useEffect(() => {
setVisibleColumns(table.schema.fields?.map((field) => field.name) || [])
@@ -59,13 +115,34 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
setIsLoading(true)
try {
const tableData = await apiClient.call<any>(`/api/v1/${table.name}`)
const response = await apiClient.call<any>(`/api/v1/entities/${table.schema.name}`)
// If the request failed, throw the error here
if (response?.error?.length > 0) throw response.error
// Handle paginated response structure: { items: [...], items_count, page, page_size, total_count }
let tableData: any[] = []
if (Array.isArray(response)) {
// Fallback: if response is directly an array (shouldn't happen with new API)
tableData = response
} else if (response?.items && Array.isArray(response.items)) {
// Paginated response: extract items from data object
tableData = response.items
} else if (response?.data?.items && Array.isArray(response.data.items)) {
// If data is nested
tableData = response.data.items
} else {
console.warn("Unexpected response format:", response)
tableData = []
}
setTableData(tableData)
// setTotalPages(3) // Mock pagination
setSelectedItems([]) // Clear selection on reload
} catch (error) {
console.error("Failed to load table data:", error)
setTableData([]) // Set empty array on error
} finally {
setIsLoading(false)
}
@@ -82,7 +159,13 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
const handleFilter = () => {
setAppliedFilter(filterTerm)
setCurrentPage(1) // Reset to first page when filtering
setCurrentPage(1)
const nextParams = new URLSearchParams()
if (filterTerm) {
nextParams.set("filter", filterTerm)
}
setSearchParams(nextParams, { replace: true })
}
const handleFilterKeyPress = (e: React.KeyboardEvent) => {
@@ -128,7 +211,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
try {
// Delete each selected item individually
const deletePromises = selectedItems.map((itemId) =>
apiClient.call(`/api/v1/${table.name}/${itemId}`, { method: "DELETE" }),
apiClient.call(`/api/v1/entities/${table.schema.name}/${itemId}`, { method: "DELETE" }),
)
await Promise.all(deletePromises)
@@ -136,10 +219,6 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
// Remove deleted items from table data
setTableData((prevData) => prevData.filter((item) => !selectedItems.includes(item.id)))
setSelectedItems([])
toast({
title: "Record(s) Deleted",
description: "Table records have been updated successfully.",
})
} catch (error) {
console.error("Failed to delete items:", error)
} finally {
@@ -147,198 +226,507 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
}
}
const handleSendVerificationEmail = async (row: { email?: string }) => {
const email = typeof row.email === "string" ? row.email.trim() : ""
if (!email) {
toast({
variant: "destructive",
title: "Email required",
description: "This user has no email address.",
})
return
}
try {
const response = await apiClient.call(
`/api/v1/auth/${encodeURIComponent(table.schema.name)}/verify-email/request`,
{
method: "POST",
body: JSON.stringify({ email }),
},
)
const error = getApiClientError(response)
if (error) {
throw new Error(error)
}
toast({
title: "Verification Email Requested",
description: "If an account exists for that email, we sent a verification link.",
duration: 4000,
})
} catch (error) {
console.error("Failed to send verification email:", error)
toast({
variant: "destructive",
title: "Could not send verification",
description: error instanceof Error ? error.message : "Failed to send verification email.",
})
}
}
const handleSendPasswordResetEmail = async (row: { email?: string }) => {
const email = typeof row.email === "string" ? row.email.trim() : ""
if (!email) {
toast({
variant: "destructive",
title: "Email required",
description: "This user has no email address.",
})
return
}
try {
const response = await apiClient.call(
`/api/v1/auth/${encodeURIComponent(table.schema.name)}/password-reset/request`,
{
method: "POST",
body: JSON.stringify({ email }),
},
)
const error = getApiClientError(response)
if (error) {
throw new Error(error)
}
toast({
title: "Password Reset Email Requested",
description: "If an account exists for that email, we sent a password reset link.",
duration: 4000,
})
} catch (error) {
console.error("Failed to send password reset email:", error)
toast({
variant: "destructive",
title: "Could not send password reset",
description: error instanceof Error ? error.message : "Failed to send password reset email.",
})
}
}
const handleCreateApiKeyForUser = (userId: string) => {
openCreateApiKeyDialog(setCreateApiKeyForUserId, setCreateApiKeyRequested, userId)
setActiveTab("api-keys")
}
const filteredFields = table.schema.fields?.filter((field) => visibleColumns.includes(field.name)) || []
function renderCellContent(field: { name: string; type: string }, value: any) {
if (value === null || value === undefined) {
return "N/A"
}
switch (field.type) {
case "bool":
case "boolean": {
const isTrue = value === true || value === "true" || value === 1
if (field.name === "email_verified") {
return (
<Badge variant={isTrue ? "secondary" : "outline"} className="text-xs">
{isTrue ? "Verified" : "Unverified"}
</Badge>
)
}
return isTrue ? "true" : "false"
}
case "json":
try {
return (
<pre className="max-w-[300px] whitespace-pre-wrap text-xs bg-muted p-1 rounded">
{JSON.stringify(value, null, 2)}
</pre>
);
} catch {
return String(value);
}
case "file":
case "files": {
if (value === "" || (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 = buildEntityFileUrl(table.schema.name, filename);
const ext = filename.split(".").pop()?.toLowerCase() || "";
const isImage = ["jpg", "jpeg", "png", "gif", "webp", "bmp", "svg"].includes(ext);
return isImage ? (
<img
key={i}
src={url}
alt={filename}
className="h-10 w-10 object-cover rounded border"
/>
) : (
<a
key={i}
href={url}
target="_blank"
rel="noopener noreferrer"
className="text-xs underline text-blue-600"
>
{filename}
</a>
);
})}
</div>
);
}
default:
if (typeof value === "number" && Number.isNaN(value)) {
return "N/A"
}
return String(value)
}
}
const recordsCard = (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle>Table Data</CardTitle>
<CardDescription>Current records in the {table.schema.name} table</CardDescription>
</div>
<div className="flex items-center gap-2">
{selectedItems.length > 0 && (
<Button variant="destructive" size="sm" onClick={handleDeleteSelected} disabled={isDeleting}>
<Trash2 className="h-4 w-4 mr-2" />
{isDeleting
? "Deleting..."
: `Delete ${selectedItems.length} item${selectedItems.length > 1 ? "s" : ""}`}
</Button>
)}
<ColumnVisibilityDropdown
table={table}
visibleColumns={visibleColumns}
onVisibilityChange={setVisibleColumns}
/>
</div>
</div>
</CardHeader>
<CardContent>
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-12">
<Checkbox
checked={selectedItems.length === tableData.length && tableData.length > 0}
onCheckedChange={handleSelectAll}
aria-label="Select all"
/>
</TableHead>
{filteredFields.map((field) => (
<TableHead key={field.name}>
{field.name}
</TableHead>
))}
{isAuthEntity && <TableHead>Actions</TableHead>}
</TableRow>
</TableHeader>
<TableBody>
{isLoading ? (
<TableRow>
<TableCell colSpan={filteredFields.length + 1 + (isAuthEntity ? 1 : 0)} className="text-center text-muted-foreground h-64">
Loading...
</TableCell>
</TableRow>
) : tableData.length > 0 ? (
tableData.map((row, index) => (
<TableRow
key={index}
className="cursor-pointer hover:bg-muted/50"
onClick={(e) => handleRowClick(row, e)}
>
<TableCell onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={selectedItems.includes(row.id)}
onCheckedChange={(checked) => handleSelectItem(row.id, checked as boolean)}
aria-label={`Select row ${index + 1}`}
/>
</TableCell>
{filteredFields.map((field) => (
<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>
))}
{isAuthEntity && (
<TableCell onClick={(e) => e.stopPropagation()}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => handleCreateApiKeyForUser(row.id)}>
<Key className="mr-2 h-4 w-4" />
Create API Key
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleSendVerificationEmail(row)}>
<Mail className="mr-2 h-4 w-4" />
Send verification email
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleSendPasswordResetEmail(row)}>
<KeyRound className="mr-2 h-4 w-4" />
Reset password
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
)}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={filteredFields.length + 1 + (isAuthEntity ? 1 : 0)} className="text-center h-64 align-middle">
<div className="flex flex-col items-center justify-center py-16">
<FileText className="h-12 w-12 text-muted-foreground mb-4" />
<h3 className="text-lg font-semibold mb-2">No Records Found</h3>
<p className="text-muted-foreground text-center mb-6 max-w-md">
This table doesn't have any records yet. Add some data to get started.
</p>
<div className="flex gap-3">
{!isViewType && (
<Button onClick={handleAddItem} disabled={isDeleting || isLoading}>
<Plus className="h-4 w-4 mr-2" />
New Record
</Button>
)}
<Button variant="outline" onClick={() => setDocsOpen(true)} disabled={isDeleting}>
<FileText className="h-4 w-4 mr-2" />
View API Documentation
</Button>
</div>
</div>
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
{totalPages > 1 && (
<div className="flex items-center justify-between mt-4">
<p className="text-sm text-muted-foreground">
Page {currentPage} of {totalPages}
</p>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
disabled={currentPage === 1}
>
Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
disabled={currentPage === totalPages}
>
Next
</Button>
</div>
</div>
)}
</CardContent>
</Card>
)
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<SidebarTrigger />
<Button variant="ghost" onClick={onBack}>
← Back
</Button>
<div>
<h2 className="text-2xl font-bold capitalize">{table.name} Table</h2>
<p className="text-muted-foreground">View and manage table data</p>
{isAuthEntity ? (
<Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
<div className="flex items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-bold">
Entity <span className="text-primary font-mono italic">'{table.schema.name}'</span> data
</h2>
</div>
<div className="flex items-center gap-2">
<TabsList>
<TabsTrigger value="records">Records</TabsTrigger>
<TabsTrigger value="api-keys">API Keys</TabsTrigger>
</TabsList>
<Button
variant="outline"
size="icon"
onClick={() =>
activeTab === "api-keys"
? setApiKeysReloadRequested((count) => count + 1)
: handleReload()
}
disabled={activeTab === "api-keys" ? apiKeysLoading : isLoading}
>
<RefreshCw
className={`h-4 w-4 ${(activeTab === "api-keys" ? apiKeysLoading : isLoading) ? "animate-spin" : ""}`}
/>
</Button>
<Button variant="outline" size="icon" onClick={() => setConfigOpen(true)}>
<Cog className="h-4 w-4" />
</Button>
<Button variant="outline" size="icon" onClick={() => setDocsOpen(true)}>
<FileText className="h-4 w-4" />
</Button>
{!isViewType && activeTab === "records" && (
<Button size="sm" onClick={handleAddItem} disabled={isLoading}>
<Plus className="h-4 w-4 mr-2" />
New Record
</Button>
)}
{activeTab === "api-keys" && (
<Button
size="sm"
onClick={() => openCreateApiKeyDialog(setCreateApiKeyForUserId, setCreateApiKeyRequested)}
disabled={entityUsers.length === 0}
>
<Plus className="h-4 w-4 mr-2" />
New API Key
</Button>
)}
</div>
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={handleReload} disabled={isLoading}>
<RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
</Button>
{!isViewType &&
<Button size="sm" onClick={handleAddItem} disabled={isLoading}>
<Plus className="h-4 w-4 mr-2" />
New Record
</Button>
}
<Button variant="outline" size="sm" onClick={() => setConfigOpen(true)}>
<Cog className="h-4 w-4 mr-2" />
Config
</Button>
<Button variant="outline" size="sm" onClick={() => setDocsOpen(true)}>
<FileText className="h-4 w-4 mr-2" />
API Docs
</Button>
</div>
</div>
{/* Search/Filter Bar */}
<Card>
<CardContent className="pt-6">
<div className="flex gap-2">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
{activeTab === "records" && (
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground z-10" />
<Input
placeholder="Search records..."
value={filterTerm}
onChange={(e) => setFilterTerm(e.target.value)}
onKeyPress={handleFilterKeyPress}
className="pl-10"
className="pl-10 pr-20"
/>
<Button
onClick={handleFilter}
disabled={isLoading}
className="absolute right-1 top-1/2 transform -translate-y-1/2 h-7"
size="sm"
>
Filter
</Button>
{appliedFilter && (
<div className="flex items-center gap-2 mt-2">
<p className="text-sm text-muted-foreground">Filtering by: "{appliedFilter}"</p>
<Button
variant="ghost"
size="sm"
onClick={() => {
setFilterTerm("")
setAppliedFilter("")
setSearchParams({}, { replace: true })
}}
className="h-6 text-xs"
>
Clear
</Button>
</div>
)}
</div>
<Button onClick={handleFilter} disabled={isLoading}>
)}
<TabsContent value="records" className="mt-0 space-y-6">
{recordsCard}
</TabsContent>
<TabsContent value="api-keys" className="mt-0 space-y-6">
<ApiKeysPanel
users={entityUsers}
apiClient={apiClient}
apiKeysApi={entityApiKeysPath}
cacheKey={entityApiKeysCacheKey}
isActive={activeTab === "api-keys"}
defaultUserId={createApiKeyForUserId}
createRequested={createApiKeyRequested}
reloadRequested={apiKeysReloadRequested}
onCreateRequestHandled={() => setCreateApiKeyRequested(false)}
onLoadingChange={setApiKeysLoading}
supportsEdit={false}
panelTitle={`${table.schema.name} API Keys`}
userColumnLabel="User"
createDialogTitle="Create Entity API Key"
createDialogDescription={`Create a new API key linked to a user in ${table.schema.name}.`}
userFieldLabel="User"
/>
</TabsContent>
</Tabs>
) : (
<>
<div className="flex items-center justify-between">
<div>
<h2 className="text-2xl font-bold">
Entity <span className="text-primary font-mono italic">'{table.schema.name}'</span> data
</h2>
</div>
<div className="flex gap-2">
<Button variant="outline" size="icon" onClick={handleReload} disabled={isLoading}>
<RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
</Button>
<Button variant="outline" size="icon" onClick={() => setConfigOpen(true)}>
<Cog className="h-4 w-4" />
</Button>
<Button variant="outline" size="icon" onClick={() => setDocsOpen(true)}>
<FileText className="h-4 w-4" />
</Button>
{!isViewType && (
<Button size="sm" onClick={handleAddItem} disabled={isLoading}>
<Plus className="h-4 w-4 mr-2" />
New Record
</Button>
)}
</div>
</div>
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground z-10" />
<Input
placeholder="Search records..."
value={filterTerm}
onChange={(e) => setFilterTerm(e.target.value)}
onKeyPress={handleFilterKeyPress}
className="pl-10 pr-20"
/>
<Button
onClick={handleFilter}
disabled={isLoading}
className="absolute right-1 top-1/2 transform -translate-y-1/2 h-7"
size="sm"
>
Filter
</Button>
{appliedFilter && (
<Button
variant="outline"
onClick={() => {
setFilterTerm("")
setAppliedFilter("")
}}
>
Clear
</Button>
<div className="flex items-center gap-2 mt-2">
<p className="text-sm text-muted-foreground">Filtering by: "{appliedFilter}"</p>
<Button
variant="ghost"
size="sm"
onClick={() => {
setFilterTerm("")
setAppliedFilter("")
setSearchParams({}, { replace: true })
}}
className="h-6 text-xs"
>
Clear
</Button>
</div>
)}
</div>
{appliedFilter && <p className="text-sm text-muted-foreground mt-2">Filtering by: "{appliedFilter}"</p>}
</CardContent>
</Card>
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle>Table Data</CardTitle>
<CardDescription>Current records in the {table.name} table</CardDescription>
</div>
<div className="flex items-center gap-2">
{selectedItems.length > 0 && (
<Button variant="destructive" size="sm" onClick={handleDeleteSelected} disabled={isDeleting}>
<Trash2 className="h-4 w-4 mr-2" />
{isDeleting
? "Deleting..."
: `Delete ${selectedItems.length} item${selectedItems.length > 1 ? "s" : ""}`}
</Button>
)}
<ColumnVisibilityDropdown
table={table}
visibleColumns={visibleColumns}
onVisibilityChange={setVisibleColumns}
/>
</div>
</div>
</CardHeader>
<CardContent>
{tableData.length === 0 && !isLoading ? (
<div className="flex flex-col items-center justify-center py-16">
<FileText className="h-12 w-12 text-muted-foreground mb-4" />
<h3 className="text-lg font-semibold mb-2">No Records Found</h3>
<p className="text-muted-foreground text-center mb-6 max-w-md">
This table doesn't have any records yet. Add some data to get started.
</p>
<div className="flex gap-3">
{!isViewType &&
<Button onClick={handleAddItem} disabled={isDeleting || isLoading}>
<Plus className="h-4 w-4 mr-2" />
New Record
</Button>
}
<Button variant="outline" onClick={() => setDocsOpen(true)} disabled={isDeleting}>
<FileText className="h-4 w-4 mr-2" />
View API Documentation
</Button>
</div>
</div>
) : (
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-12">
<Checkbox
checked={selectedItems.length === tableData.length && tableData.length > 0}
onCheckedChange={handleSelectAll}
aria-label="Select all"
/>
</TableHead>
{filteredFields.map((field) => (
<TableHead key={field.name} className="capitalize">
{field.name}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{tableData.length > 0 ? (
tableData.map((row, index) => (
<TableRow
key={index}
className="cursor-pointer hover:bg-muted/50"
onClick={(e) => handleRowClick(row, e)}
>
<TableCell onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={selectedItems.includes(row.id)}
onCheckedChange={(checked) => handleSelectItem(row.id, checked as boolean)}
aria-label={`Select row ${index + 1}`}
/>
</TableCell>
{filteredFields.map((field) => (
<TableCell key={field.name}>{row[field.name] || "-"}</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={filteredFields.length + 1} className="text-center text-muted-foreground">
{isLoading ? "Loading..." : "No data available"}
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
)}
{totalPages > 1 && (
<div className="flex items-center justify-between mt-4">
<p className="text-sm text-muted-foreground">
Page {currentPage} of {totalPages}
</p>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
disabled={currentPage === 1}
>
Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
disabled={currentPage === totalPages}
>
Next
</Button>
</div>
</div>
)}
</CardContent>
</Card>
{recordsCard}
</>
)}
<TableConfigDrawer
table={table}
@@ -346,6 +734,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)} />

View File

@@ -1,85 +1,104 @@
"use client"
import * as React from "react"
import { FileText, ChevronDown, ChevronRight, X, Copy } from "lucide-react"
import { BookOpen, FileText, X } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from "@/components/ui/drawer"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
import { ScrollArea } from "@/components/ui/scroll-area"
import type { TableMetadata } from "@/lib/api"
import {
DocCodeBlock,
DocCollapsibleSection,
DocEndpointHeader,
DocErrorList,
DocInfoBanner,
DocSectionHeading,
} from "@/components/database/api-doc-shared"
import { dataTypes, intPrecisions } from "@/lib/field-types"
import { getApiBaseUrl } from "@/lib/api"
interface TableDocsDrawerProps {
open: boolean
onClose: () => void
}
// Generate docs based on user defined tables
export function TableDocsDrawer({ open, onClose }: TableDocsDrawerProps) {
const [table, setTable] = React.useState({})
const handleClose = () => {
onClose()
}
return (
<Drawer open={open} onOpenChange={handleClose}>
<Drawer open={open} onOpenChange={onClose}>
<DrawerContent side="right" className="w-[1000px] max-w-[95vw]">
<DrawerHeader>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<FileText className="h-5 w-5" />
<DrawerTitle>Tables API Documentation</DrawerTitle>
<DrawerTitle>Entity Schema API Documentation</DrawerTitle>
</div>
<Button variant="ghost" size="sm" onClick={onClose}>
<X className="h-4 w-4" />
</Button>
</div>
<DrawerDescription>Auto-generated API endpoints and examples</DrawerDescription>
<DrawerDescription>
Admin-only endpoints for managing entity schemas, field types, and access rules.
</DrawerDescription>
</DrawerHeader>
<div className="flex-1 overflow-hidden">
<ScrollArea className="h-full">
<div className="p-6 space-y-6">
<DocInfoBanner>
<p className="text-sm text-muted-foreground space-y-2">
<span className="block">
<strong className="text-foreground">Admin authentication required:</strong> all schema endpoints
require an admin JWT in{" "}
<code className="bg-background px-1 rounded text-xs">Authorization: Bearer YOUR_ADMIN_TOKEN</code>.
</span>
<span className="block">
<strong className="text-foreground">Response envelope:</strong>{" "}
<code className="bg-background px-1 rounded text-xs">{`{ "status", "data", "error" }`}</code>.
</span>
</p>
</DocInfoBanner>
<DocSectionHeading>Schema CRUD</DocSectionHeading>
<ApiEndpointCard
method="GET"
endpoint={`/api/v1/tables`}
description={`List all records in the tables table`}
table={table}
endpoint="/api/v1/schemas"
description="List all entity schemas"
operation="list"
/>
<ApiEndpointCard
method="GET"
endpoint={`/api/v1/tables/{id}`}
description="Get a specific record by ID"
table={table}
endpoint="/api/v1/schemas/{schema_name_or_id}"
description="Get a specific entity schema by name or ID"
operation="get"
/>
<ApiEndpointCard
method="POST"
endpoint={`/api/v1/tables`}
description="Create a new record"
table={table}
endpoint="/api/v1/schemas"
description="Create a new entity schema"
operation="create"
/>
<ApiEndpointCard
method="PATCH"
endpoint={`/api/v1/tables/{id}`}
description="Update a specific record"
table={table}
endpoint="/api/v1/schemas/{schema_name_or_id}"
description="Update an existing entity schema (add/update/delete fields by id or name)"
operation="update"
/>
<ApiEndpointCard
method="DELETE"
endpoint={`/api/v1/tables/{id}`}
description="Delete a specific record"
table={table}
endpoint="/api/v1/schemas/{schema_name_or_id}"
description="Delete an entity schema"
operation="delete"
/>
<DocSectionHeading>Reference</DocSectionHeading>
<SchemaReferenceSection />
</div>
</ScrollArea>
</div>
@@ -88,212 +107,353 @@ export function TableDocsDrawer({ open, onClose }: TableDocsDrawerProps) {
)
}
function SchemaReferenceSection() {
const fieldTypesList = dataTypes
.map((type) => {
if (type === "int") {
return `int — integer with precision (${intPrecisions.join(", ")})`
}
return type
})
.join("\n")
const entityTypesExample = JSON.stringify(
{
base: "Standard CRUD entity with configurable access rules",
auth: "User authentication entity — login methods, email verification, API keys, and OAuth providers",
view: "Read-only SQL view — requires view_query, mutations rejected",
},
null,
2,
)
const accessRulesExample = JSON.stringify(
{
rules: {
list: { mode: "public", expr: "" },
get: { mode: "auth", expr: "" },
add: { mode: "auth", expr: "" },
update: { mode: "custom", expr: "@request.auth.id == @record.owner_id" },
delete: { mode: "", expr: "" },
},
},
null,
2,
)
const intFieldExample = JSON.stringify(
{
name: "quantity",
type: "int",
precision: "i32",
primary_key: false,
required: true,
system: false,
unique: false,
constraints: {
default_value: null,
max_value: 1000,
min_value: 0,
validator: null,
},
},
null,
2,
)
return (
<>
<DocCollapsibleSection
icon={<BookOpen className="h-4 w-4 text-muted-foreground" />}
title="Field types"
description="Supported field types when creating or patching schema fields."
>
<DocCodeBlock code={fieldTypesList} height="h-36" />
<div>
<h5 className="font-medium mb-2">Integer precision example</h5>
<p className="text-sm text-muted-foreground mb-2">
Use type <code className="bg-muted px-1 rounded">int</code> with a{" "}
<code className="bg-muted px-1 rounded">precision</code> property. Legacy types (int32, uint64, etc.) are
normalized to <code className="bg-muted px-1 rounded">int</code> + precision on load.
</p>
<DocCodeBlock code={intFieldExample} height="h-48" />
</div>
<p className="text-sm text-muted-foreground">
<code className="bg-muted px-1 rounded">file</code> and <code className="bg-muted px-1 rounded">files</code>{" "}
fields store upload paths served at <code className="bg-muted px-1 rounded">GET /api/v1/files/{"{entity}"}/{"{file}"}</code>.
Create/update records with <code className="bg-muted px-1 rounded">multipart/form-data</code>.
</p>
</DocCollapsibleSection>
<DocCollapsibleSection
icon={<BookOpen className="h-4 w-4 text-muted-foreground" />}
title="Entity types"
description="The type property determines entity behavior and available API routes."
>
<DocCodeBlock code={entityTypesExample} height="h-36" />
</DocCollapsibleSection>
<DocCollapsibleSection
icon={<BookOpen className="h-4 w-4 text-muted-foreground" />}
title="Access rules"
description="Each CRUD operation has a mode and optional custom expression."
>
<DocCodeBlock code={accessRulesExample} height="h-44" />
<div className="text-sm text-muted-foreground space-y-2">
<p>
<strong className="text-foreground">Modes:</strong>{" "}
<code className="bg-muted px-1 rounded">public</code> — no auth required;{" "}
<code className="bg-muted px-1 rounded">auth</code> — authenticated user required;{" "}
<code className="bg-muted px-1 rounded">custom</code> — expression must evaluate true; empty mode — admin
only (not exposed on public entity API).
</p>
<p>
Realtime topic access mirrors list (entity name) and get (entity:row_id) rules.
</p>
</div>
</DocCollapsibleSection>
<DocCollapsibleSection
icon={<BookOpen className="h-4 w-4 text-muted-foreground" />}
title="Field patch operations"
description="When updating a schema via PATCH, fields support add, update, and delete."
>
<DocCodeBlock
code={`// Add new field (omit id)
{ "name": "new_field", "type": "string", ... }
// Update existing field (include id)
{ "id": "mbf_existing_field_id", "name": "renamed_field", "type": "string", ... }
// Delete field
{ "id": "mbf_field_to_delete", "op": "delete" }`}
height="h-40"
/>
</DocCollapsibleSection>
</>
)
}
function ApiEndpointCard({
method,
endpoint,
description,
table,
operation,
}: {
method: string
endpoint: string
description: string
table: TableMetadata
operation: string
}) {
const [isOpen, setIsOpen] = React.useState(false)
const getMethodColor = (method: string) => {
switch (method) {
case "GET":
return "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"
case "POST":
return "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"
case "PATCH":
return "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200"
case "DELETE":
return "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"
default:
return "bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200"
}
}
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text)
}
const baseUrl = getApiBaseUrl()
const generateRequestExample = () => {
const baseUrl = "https://your-api.com"
let example = `curl -X ${method} "${baseUrl}${endpoint}"`
if (method !== "GET") {
example += ` \\\n -H "Content-Type: application/json"`
}
example += ` \\\n -H "Authorization: Bearer YOUR_TOKEN"`
example += ` \\\n -H "Authorization: Bearer YOUR_ADMIN_TOKEN"`
if (operation === "create" || operation === "update") {
const sampleData: any = {}
table?.schema?.fields?.forEach((field) => {
if (field.name === "id" || field.name === "created" || field.name === "updated") return
if (field.name === "email") {
sampleData[field.name] = "user@example.com"
} else if (field.name === "password") {
sampleData[field.name] = "securepassword"
} else {
sampleData[field.name] = `sample_${field.name}`
}
})
example += ` \\\n -d '${JSON.stringify(sampleData, null, 2)}'`
if (operation === "create") {
const sampleSchema = {
name: "example_entity",
type: "base",
fields: [
{
name: "title",
type: "string",
primary_key: false,
required: true,
system: false,
unique: false,
constraints: {
default_value: null,
max_value: null,
min_value: null,
validator: null,
},
},
{
name: "count",
type: "int",
precision: "i32",
primary_key: false,
required: false,
system: false,
unique: false,
constraints: {
default_value: 0,
max_value: null,
min_value: null,
validator: null,
},
},
],
rules: {
add: { expr: "", mode: "auth" },
delete: { expr: "", mode: "auth" },
get: { expr: "", mode: "auth" },
list: { expr: "", mode: "auth" },
update: { expr: "", mode: "auth" },
},
}
example += ` \\\n -d '${JSON.stringify(sampleSchema, null, 2)}'`
} else if (operation === "update") {
const sampleUpdate = {
fields: [
{
id: "mbf_existing_field_id",
name: "updated_field_name",
type: "string",
primary_key: false,
required: true,
system: false,
unique: false,
constraints: {
default_value: null,
max_value: null,
min_value: null,
validator: null,
},
},
{
name: "new_field",
type: "int",
precision: "u32",
primary_key: false,
required: false,
system: false,
unique: false,
constraints: {
default_value: null,
max_value: null,
min_value: null,
validator: null,
},
},
{
id: "mbf_field_to_delete",
op: "delete",
},
],
}
example += ` \\\n -d '${JSON.stringify(sampleUpdate, null, 2)}'`
}
return example
}
const generateResponseExample = () => {
if (operation === "list") {
const sampleRecord: any = {}
table?.schema?.fields?.forEach((field) => {
if (field.name === "id") {
sampleRecord[field.name] = "123e4567-e89b-12d3-a456-426614174000"
} else if (field.name === "created" || field.name === "updated") {
sampleRecord[field.name] = "2024-01-15T10:00:00Z"
} else if (field.name === "email") {
sampleRecord[field.name] = "user@example.com"
} else if (field.name === "password") {
return // Don't include password in response
} else {
sampleRecord[field.name] = `sample_${field.name}`
}
})
return JSON.stringify(
{
data: [sampleRecord],
pagination: {
page: 1,
limit: 20,
total: 1,
pages: 1,
const sampleSchema = {
created: "2026-01-15T10:00:00Z",
id: "mbt_7691163245302450708",
schema: {
fields: [
{
constraints: { default_value: null, max_value: null, min_value: null, validator: "@password" },
id: "mbf_14258576900392064537",
name: "id",
primary_key: true,
required: true,
system: true,
type: "string",
unique: false,
},
{
constraints: { default_value: null, max_value: null, min_value: null, validator: null },
id: "mbf_13735287961322938256",
name: "created",
primary_key: false,
required: true,
system: true,
type: "date",
unique: false,
},
{
constraints: { default_value: null, max_value: null, min_value: null, validator: null },
id: "mbf_9124719522053273721",
name: "updated",
primary_key: false,
required: true,
system: true,
type: "date",
unique: false,
},
{
constraints: { default_value: 0, max_value: null, min_value: null, validator: null },
id: "mbf_16766180539469268884",
name: "count",
precision: "i32",
primary_key: false,
required: false,
system: false,
type: "int",
unique: false,
},
],
has_api: true,
id: "mbt_7691163245302450708",
name: "example_entity",
rules: {
add: { expr: "", mode: "auth" },
delete: { expr: "", mode: "auth" },
get: { expr: "", mode: "auth" },
list: { expr: "", mode: "auth" },
update: { expr: "", mode: "auth" },
},
null,
2,
)
system: false,
type: "base",
},
updated: "2026-01-15T10:00:00Z",
}
if (operation === "list") {
return JSON.stringify({ status: 200, data: [sampleSchema], error: "" }, null, 2)
}
if (operation === "delete") {
return JSON.stringify({}, null, 2)
return JSON.stringify({ status: 200, data: null, error: "" }, null, 2)
}
// Single record response
const sampleRecord: any = {}
table?.schema?.fields?.forEach((field) => {
if (field.name === "id") {
sampleRecord[field.name] = "123e4567-e89b-12d3-a456-426614174000"
} else if (field.name === "created" || field.name === "updated") {
sampleRecord[field.name] = "2024-01-15T10:00:00Z"
} else if (field.name === "email") {
sampleRecord[field.name] = "user@example.com"
} else if (field.name === "password") {
return // Don't include password in response
} else {
sampleRecord[field.name] = `sample_${field.name}`
}
})
return JSON.stringify(sampleRecord, null, 2)
const status = operation === "create" ? 201 : 200
return JSON.stringify({ status, data: sampleSchema, error: "" }, null, 2)
}
const requestExample = generateRequestExample()
const responseExample = generateResponseExample()
const errors: Array<{ code: string; message: string }> = [
{ code: "400", message: "Bad Request — parsing or validation error" },
{ code: "401", message: "Unauthorized — admin token required" },
{ code: "403", message: "Forbidden — admin access denied" },
{ code: "500", message: "Internal Server Error" },
]
if (operation === "get" || operation === "update" || operation === "delete") {
errors.splice(3, 0, { code: "404", message: "Not Found — schema not found" })
}
return (
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
<CollapsibleTrigger asChild>
<div className="p-4 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<Badge className={getMethodColor(method)} variant="secondary">
{method}
</Badge>
<code className="text-sm font-mono bg-muted px-2 py-1 rounded">{endpoint}</code>
{isOpen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
</div>
</div>
<p className="text-sm text-muted-foreground mt-2">{description}</p>
<DocEndpointHeader method={method} endpoint={endpoint} description={description} isOpen={isOpen} />
</div>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="border-l-2 border-muted ml-4 pl-6 space-y-6 mt-4">
<div>
<div className="flex items-center justify-between mb-3">
<h5 className="font-medium">Request Example</h5>
<Button variant="outline" size="sm" onClick={() => copyToClipboard(requestExample)} className="h-8">
<Copy className="h-3 w-3 mr-1" />
Copy
</Button>
</div>
<ScrollArea className="h-48">
<pre className="bg-muted p-4 rounded text-sm border">
<code>{requestExample}</code>
</pre>
</ScrollArea>
<h5 className="font-medium mb-2">Request Example</h5>
<DocCodeBlock code={requestExample} height={operation === "create" || operation === "update" ? "h-64" : "h-48"} />
</div>
<div>
<div className="flex items-center justify-between mb-3">
<h5 className="font-medium">Response Example</h5>
<Button variant="outline" size="sm" onClick={() => copyToClipboard(responseExample)} className="h-8">
<Copy className="h-3 w-3 mr-1" />
Copy
</Button>
</div>
<ScrollArea className="h-48">
<pre className="bg-muted p-4 rounded text-sm border">
<code>{responseExample}</code>
</pre>
</ScrollArea>
</div>
<div>
<h5 className="font-medium mb-3">Possible Errors</h5>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
<div className="flex items-center gap-2">
<Badge variant="destructive" className="text-xs">
400
</Badge>
<span>Bad Request - Invalid input data</span>
</div>
<div className="flex items-center gap-2">
<Badge variant="destructive" className="text-xs">
401
</Badge>
<span>Unauthorized - Invalid or missing token</span>
</div>
<div className="flex items-center gap-2">
<Badge variant="destructive" className="text-xs">
403
</Badge>
<span>Forbidden - Access denied by rules</span>
</div>
{(operation === "get" || operation === "update" || operation === "delete") && (
<div className="flex items-center gap-2">
<Badge variant="destructive" className="text-xs">
404
</Badge>
<span>Not Found - Record does not exist</span>
</div>
)}
<div className="flex items-center gap-2">
<Badge variant="destructive" className="text-xs">
500
</Badge>
<span>Internal Server Error - Server error</span>
</div>
</div>
<h5 className="font-medium mb-2">Response Example</h5>
<DocCodeBlock code={responseExample} height="h-64" />
</div>
<DocErrorList errors={errors} />
</div>
</CollapsibleContent>
</Collapsible>

File diff suppressed because it is too large Load Diff

View File

@@ -1,27 +1,36 @@
"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"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { loginWithPassword } from "@/lib/api"
import { useAppState } from "@/lib/app-state"
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
onLogin: (email: string, password: string) => Promise<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("")
const { mode } = useAppState()
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
@@ -29,9 +38,7 @@ export function LoginForm({ onLogin }: LoginFormProps) {
setError("")
try {
const data = await loginWithPassword(email, password, mode)
localStorage.setItem("admin_token", data.token)
onLogin(data.token)
await onLogin(email, password)
} catch (err: any) {
setError(err.message || "Invalid email or password")
} finally {
@@ -40,11 +47,20 @@ export function LoginForm({ onLogin }: LoginFormProps) {
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<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>
@@ -99,6 +115,7 @@ export function LoginForm({ onLogin }: LoginFormProps) {
</form>
</CardContent>
</Card>
</div>
</div>
)
}

49
components/logo.tsx Normal file
View 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>
)
}

View File

@@ -1,168 +1,542 @@
"use client"
import * as React from "react"
import { Download, Filter, Search } 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 { SidebarTrigger } from "@/components/ui/sidebar"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
Pagination,
PaginationContent,
PaginationItem,
PaginationLink,
PaginationNext,
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.)
}
export function LogsSection() {
const [logs] = 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)",
},
])
interface PaginatedLogsResponse {
items: LogEntry[]
items_count: number
page: number
page_size: number
total_count: number
}
interface LogsSectionProps {
apiClient: ApiClient
}
const ITEMS_PER_PAGE = 100
export function LogsSection({ apiClient }: LogsSectionProps) {
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")
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 = logs.filter((log) => {
const matchesSearch =
log.message.toLowerCase().includes(searchTerm.toLowerCase()) ||
log.source.toLowerCase().includes(searchTerm.toLowerCase())
const matchesLevel = levelFilter === "all" || log.level === levelFilter
return matchesSearch && matchesLevel
})
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 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(() => {
setCurrentPage(1)
}, [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"
}
}
const formatTimestamp = (timestamp: string) => {
const date = new Date(timestamp)
return date.toLocaleString("en-US", {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
})
}
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">
<div className="space-y-6 p-6">
{/* Header */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<SidebarTrigger />
<div>
<h2 className="text-2xl font-bold">System Logs</h2>
<p className="text-muted-foreground">Monitor system activity and events</p>
</div>
<div className="space-y-1">
<h1 className="text-3xl font-bold tracking-tight">Logs</h1>
<p className="text-muted-foreground">Monitor system activity and events</p>
</div>
<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>
<Button>
<Download className="h-4 w-4 mr-2" />
Export Logs
</Button>
</div>
<div className="flex items-center gap-4">
<div className="flex items-center space-x-2 flex-1">
<Search className="h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search logs..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="max-w-sm"
/>
</div>
<Select value={levelFilter} onValueChange={setLevelFilter}>
<SelectTrigger className="w-32">
<SelectValue />
</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>
<Button variant="outline">
<Filter className="h-4 w-4 mr-2" />
Filters
</Button>
</div>
{/* Filters */}
<Card>
<CardHeader>
<CardTitle>Recent Activity</CardTitle>
<CardDescription>{filteredLogs.length} log entries</CardDescription>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Timestamp</TableHead>
<TableHead>Level</TableHead>
<TableHead>Source</TableHead>
<TableHead>Message</TableHead>
<TableHead>Details</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredLogs.map((log) => (
<TableRow key={log.id}>
<TableCell className="font-mono text-sm">{new Date(log.timestamp).toLocaleString()}</TableCell>
<TableCell>
<Badge variant={getLevelColor(log.level) as any}>{log.level.toUpperCase()}</Badge>
</TableCell>
<TableCell className="font-medium">{log.source}</TableCell>
<TableCell>{log.message}</TableCell>
<TableCell className="text-sm text-muted-foreground max-w-xs truncate">{log.details}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<CardContent className="pt-6">
<div className="flex items-center gap-4">
<div className="relative flex-1 max-w-sm">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search logs..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onKeyPress={handleSearchKeyPress}
className="pl-9"
/>
</div>
<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>
{/* Logs Table */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle>System Logs</CardTitle>
<CardDescription>
{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>
{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>
<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>
</TableHeader>
<TableBody>
{logs.length === 0 ? (
<TableRow>
<TableCell colSpan={6} className="h-24 text-center text-muted-foreground">
No logs found
</TableCell>
</TableRow>
) : (
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 !== null && totalPages > 1) || hasMorePages ? (
<div className="mt-4 flex items-center justify-between">
<div className="text-sm text-muted-foreground">
Page {currentPage} {totalPages !== null ? `of ${totalPages}` : "(--)"}
</div>
<Pagination>
<PaginationContent>
<PaginationItem>
<PaginationPrevious
onClick={() => {
if (currentPage > 1) {
setCurrentPage((prev) => prev - 1)
}
}}
className={currentPage === 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
/>
</PaginationItem>
{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={() => {
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>
)
}

20
components/main-page.tsx Normal file
View File

@@ -0,0 +1,20 @@
"use client"
import * as React from "react"
import { Toaster } from "@/components/ui/toaster"
import { ThemeProvider } from "@/components/theme-provider"
import { AppStateProvider } from "@/lib/app-state"
import { AppRouterProvider, AppRoutes } from "@/components/app-routes"
export default function MainPage() {
return (
<ThemeProvider attribute="class" defaultTheme="dark" enableSystem storageKey="mantis-admin-theme" disableTransitionOnChange>
<AppStateProvider>
<AppRouterProvider>
<AppRoutes />
</AppRouterProvider>
<Toaster />
</AppStateProvider>
</ThemeProvider>
)
}

View File

@@ -0,0 +1,162 @@
"use client"
import * as React from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Alert, AlertDescription } from "@/components/ui/alert"
import {
SYS_OAUTH_PROVIDERS_API,
getApiClientError,
type ApiClient,
type OAuthProvider,
} from "@/lib/api"
interface CreateOAuthProviderDialogProps {
open: boolean
apiClient: ApiClient
onClose: () => void
onCreated: (provider: OAuthProvider) => void
}
export function CreateOAuthProviderDialog({
open,
apiClient,
onClose,
onCreated,
}: CreateOAuthProviderDialogProps) {
const [name, setName] = React.useState("")
const [clientId, setClientId] = React.useState("")
const [clientSecret, setClientSecret] = React.useState("")
const [isLoading, setIsLoading] = React.useState(false)
const [error, setError] = React.useState("")
React.useEffect(() => {
if (open) {
setName("")
setClientId("")
setClientSecret("")
setError("")
}
}, [open])
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault()
const trimmedName = name.trim()
const trimmedClientId = clientId.trim()
const trimmedSecret = clientSecret.trim()
if (!trimmedName || !trimmedClientId || !trimmedSecret) {
setError("Name, client ID, and client secret are required")
return
}
setIsLoading(true)
setError("")
try {
const created = await apiClient.call<OAuthProvider>(SYS_OAUTH_PROVIDERS_API, {
method: "POST",
body: JSON.stringify({
name: trimmedName,
client_id: trimmedClientId,
client_secret: trimmedSecret,
}),
})
const apiError = getApiClientError(created)
if (apiError) {
throw new Error(apiError)
}
if (!created?.id) {
throw new Error("Provider was created but no ID was returned")
}
onCreated(created)
onClose()
} catch (submitError) {
console.error("Failed to create OAuth provider:", submitError)
setError(submitError instanceof Error ? submitError.message : "Failed to create OAuth provider")
} finally {
setIsLoading(false)
}
}
return (
<Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>Add OAuth Provider</DialogTitle>
<DialogDescription>
Register a global OAuth provider. Enable it for this entity after creation.
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="oauth-provider-name">Provider name</Label>
<Input
id="oauth-provider-name"
value={name}
onChange={(event) => setName(event.target.value)}
placeholder="google"
required
/>
<p className="text-xs text-muted-foreground">
Used in OAuth routes as <code className="bg-muted px-1 rounded">{`{provider}`}</code> (e.g. google,
github).
</p>
</div>
<div className="space-y-2">
<Label htmlFor="oauth-client-id">Client ID</Label>
<Input
id="oauth-client-id"
value={clientId}
onChange={(event) => setClientId(event.target.value)}
placeholder="your-client-id"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="oauth-client-secret">Client secret</Label>
<Input
id="oauth-client-secret"
type="password"
value={clientSecret}
onChange={(event) => setClientSecret(event.target.value)}
placeholder="your-client-secret"
required
/>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" disabled={isLoading}>
{isLoading ? "Creating..." : "Add Provider"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,160 @@
"use client"
import * as React from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Alert, AlertDescription } from "@/components/ui/alert"
import {
SYS_OAUTH_PROVIDERS_API,
getApiClientError,
type ApiClient,
type OAuthProvider,
} from "@/lib/api"
interface EditOAuthProviderDialogProps {
open: boolean
provider: OAuthProvider | null
apiClient: ApiClient
onClose: () => void
onUpdated: (provider: OAuthProvider) => void
}
export function EditOAuthProviderDialog({
open,
provider,
apiClient,
onClose,
onUpdated,
}: EditOAuthProviderDialogProps) {
const [name, setName] = React.useState("")
const [clientId, setClientId] = React.useState("")
const [clientSecret, setClientSecret] = React.useState("")
const [isLoading, setIsLoading] = React.useState(false)
const [error, setError] = React.useState("")
React.useEffect(() => {
if (open && provider) {
setName(provider.name ?? "")
setClientId(typeof provider.client_id === "string" ? provider.client_id : "")
setClientSecret("")
setError("")
}
}, [open, provider])
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault()
if (!provider) {
return
}
const trimmedName = name.trim()
const trimmedClientId = clientId.trim()
const trimmedSecret = clientSecret.trim()
if (!trimmedName || !trimmedClientId) {
setError("Name and client ID are required")
return
}
setIsLoading(true)
setError("")
try {
const body: Record<string, string> = {
name: trimmedName,
client_id: trimmedClientId,
}
if (trimmedSecret) {
body.client_secret = trimmedSecret
}
const updated = await apiClient.call<OAuthProvider>(`${SYS_OAUTH_PROVIDERS_API}/${provider.id}`, {
method: "PATCH",
body: JSON.stringify(body),
})
const apiError = getApiClientError(updated)
if (apiError) {
throw new Error(apiError)
}
onUpdated({ ...provider, ...updated, name: trimmedName, client_id: trimmedClientId })
onClose()
} catch (submitError) {
console.error("Failed to update OAuth provider:", submitError)
setError(submitError instanceof Error ? submitError.message : "Failed to update OAuth provider")
} finally {
setIsLoading(false)
}
}
return (
<Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit OAuth Provider</DialogTitle>
<DialogDescription>Update provider credentials. Leave client secret blank to keep the current value.</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="edit-oauth-provider-name">Provider name</Label>
<Input
id="edit-oauth-provider-name"
value={name}
onChange={(event) => setName(event.target.value)}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="edit-oauth-client-id">Client ID</Label>
<Input
id="edit-oauth-client-id"
value={clientId}
onChange={(event) => setClientId(event.target.value)}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="edit-oauth-client-secret">Client secret</Label>
<Input
id="edit-oauth-client-secret"
type="password"
value={clientSecret}
onChange={(event) => setClientSecret(event.target.value)}
placeholder="Leave blank to keep current secret"
/>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" disabled={isLoading || !provider}>
{isLoading ? "Saving..." : "Save Changes"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,389 @@
"use client"
import * as React from "react"
import { MoreHorizontal, Pencil, Plus, Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import { Switch } from "@/components/ui/switch"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import {
SYS_OAUTH_ENTITY_CONFIG_API,
SYS_OAUTH_PROVIDERS_API,
SYS_SETTINGS_CONFIG_API,
entityOAuthProvidersApi,
extractListItems,
getApiBaseUrl,
getApiClientError,
getOAuthProviderId,
type ApiClient,
type AppSettings,
type EntityOAuthProvider,
type OAuthEntityConfigResult,
type OAuthProvider,
} from "@/lib/api"
import { useToast } from "@/hooks/use-toast"
import { CreateOAuthProviderDialog } from "./create-oauth-provider-dialog"
import { EditOAuthProviderDialog } from "./edit-oauth-provider-dialog"
interface OAuthEntityPanelProps {
entityName: string
apiClient: ApiClient
isActive: boolean
}
function isGloballyEnabled(provider: EntityOAuthProvider): boolean {
return provider.enabled !== false
}
function isEnabledForEntity(provider: EntityOAuthProvider): boolean {
return provider.enabled_for_entity === true
}
function toOAuthProvider(provider: EntityOAuthProvider): OAuthProvider {
return {
id: getOAuthProviderId(provider),
name: provider.name,
client_id: provider.client_id,
enabled: provider.enabled,
}
}
function updateProviderEntityEnabled(
providers: EntityOAuthProvider[],
providerId: string,
enabledForEntity: boolean,
): EntityOAuthProvider[] {
return providers.map((provider) =>
getOAuthProviderId(provider) === providerId ? { ...provider, enabled_for_entity: enabledForEntity } : provider,
)
}
export function OAuthEntityPanel({ entityName, apiClient, isActive }: OAuthEntityPanelProps) {
const { toast } = useToast()
const [providers, setProviders] = React.useState<EntityOAuthProvider[]>([])
const [siteDomain, setSiteDomain] = React.useState("")
const [isLoading, setIsLoading] = React.useState(false)
const [togglingProviderId, setTogglingProviderId] = React.useState<string | null>(null)
const [creating, setCreating] = React.useState(false)
const [editingProvider, setEditingProvider] = React.useState<OAuthProvider | null>(null)
const [deletingProvider, setDeletingProvider] = React.useState<EntityOAuthProvider | null>(null)
const loadOAuthConfig = React.useCallback(async () => {
try {
setIsLoading(true)
const [providersResponse, settings] = await Promise.all([
apiClient.call<unknown>(entityOAuthProvidersApi(entityName)),
apiClient.call<AppSettings>(SYS_SETTINGS_CONFIG_API).catch(() => null),
])
const providersError = getApiClientError(providersResponse)
if (providersError) {
throw new Error(providersError)
}
setProviders(extractListItems<EntityOAuthProvider>(providersResponse))
if (settings?.siteDomain) {
setSiteDomain(settings.siteDomain)
}
} catch (error) {
console.error("Failed to load OAuth configuration:", error)
toast({
variant: "destructive",
title: "Error",
description: "Failed to load OAuth providers.",
})
} finally {
setIsLoading(false)
}
}, [apiClient, entityName, toast])
React.useEffect(() => {
if (isActive) {
loadOAuthConfig()
}
}, [isActive, loadOAuthConfig])
const handleToggleProvider = async (provider: EntityOAuthProvider, enabled: boolean) => {
const providerId = getOAuthProviderId(provider)
if (!providerId) {
toast({
variant: "destructive",
title: "Error",
description: "Provider ID is missing.",
})
return
}
setTogglingProviderId(providerId)
try {
const body = JSON.stringify({
entity_name: entityName,
provider_id: providerId,
})
const response = await apiClient.call<OAuthEntityConfigResult | null>(SYS_OAUTH_ENTITY_CONFIG_API, {
method: enabled ? "POST" : "DELETE",
body,
})
const error = getApiClientError(response)
if (error) {
if (!enabled && error.toLowerCase().includes("not found")) {
setProviders((current) => updateProviderEntityEnabled(current, providerId, false))
return
}
throw new Error(error)
}
setProviders((current) => updateProviderEntityEnabled(current, providerId, enabled))
toast({
title: enabled ? "OAuth Enabled" : "OAuth Disabled",
description: `${provider.name} is ${enabled ? "enabled" : "disabled"} for ${entityName}.`,
})
} catch (error) {
console.error("Failed to update OAuth entity config:", error)
toast({
variant: "destructive",
title: "Error",
description: `Failed to ${enabled ? "enable" : "disable"} ${provider.name}.`,
})
await loadOAuthConfig()
} finally {
setTogglingProviderId(null)
}
}
const handleProviderCreated = async (_provider: OAuthProvider) => {
toast({
title: "Provider Added",
description: `"${_provider.name}" was registered. Enable it for this entity when ready.`,
})
await loadOAuthConfig()
}
const handleProviderUpdated = async (provider: OAuthProvider) => {
toast({
title: "Provider Updated",
description: `"${provider.name}" settings were saved.`,
})
await loadOAuthConfig()
}
const handleDeleteProvider = async () => {
if (!deletingProvider) {
return
}
const providerId = getOAuthProviderId(deletingProvider)
try {
const response = await apiClient.call(`${SYS_OAUTH_PROVIDERS_API}/${providerId}`, {
method: "DELETE",
})
const error = getApiClientError(response)
if (error) {
throw new Error(error)
}
toast({
title: "Provider Removed",
description: `"${deletingProvider.name}" was deleted from the global registry.`,
})
await loadOAuthConfig()
} catch (error) {
console.error("Failed to delete OAuth provider:", error)
toast({
variant: "destructive",
title: "Error",
description: "Failed to delete OAuth provider.",
})
} finally {
setDeletingProvider(null)
}
}
const baseUrl = siteDomain || getApiBaseUrl()
const callbackExample = `${baseUrl.replace(/\/+$/, "")}/api/v1/auth/${entityName}/oauth/callback/google`
const enabledCount = providers.filter(isEnabledForEntity).length
return (
<>
<div className="space-y-4">
<div className="flex items-start justify-between gap-4">
<div>
<Label className="text-base font-medium">OAuth Providers</Label>
<p className="text-sm text-muted-foreground">
{isLoading && providers.length === 0
? "Loading OAuth configuration..."
: `${enabledCount} of ${providers.length} provider${providers.length === 1 ? "" : "s"} enabled for this entity`}
</p>
</div>
<Button size="sm" onClick={() => setCreating(true)} disabled={isLoading}>
<Plus className="h-4 w-4 mr-2" />
Add Provider
</Button>
</div>
<div className="rounded-lg border bg-muted/30 p-4 text-sm text-muted-foreground space-y-2">
<p>
Register OAuth providers, then enable them for this auth entity. User login requires the provider to be
globally enabled and enabled for this entity.
</p>
<p>
Users sign in via{" "}
<code className="bg-background px-1 rounded text-xs">/auth/{entityName}/oauth/authorize/{"{provider}"}</code>.
</p>
<p>
<strong className="text-foreground">Callback URL pattern:</strong>{" "}
<code className="bg-background px-1 rounded text-xs break-all">{callbackExample}</code>
</p>
{!siteDomain && (
<p>
Set <strong className="text-foreground">Site Domain</strong> in Settings for accurate OAuth redirect URLs
in production.
</p>
)}
</div>
<Table>
<TableHeader>
<TableRow>
<TableHead>Provider</TableHead>
<TableHead>Client ID</TableHead>
<TableHead>Status</TableHead>
<TableHead>Enabled for entity</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{isLoading && providers.length === 0 ? (
<TableRow>
<TableCell colSpan={5} className="text-center text-muted-foreground">
Loading OAuth providers...
</TableCell>
</TableRow>
) : providers.length === 0 ? (
<TableRow>
<TableCell colSpan={5} className="text-center text-muted-foreground">
No OAuth providers registered yet.
</TableCell>
</TableRow>
) : (
providers.map((provider) => {
const providerId = getOAuthProviderId(provider)
const enabledForEntity = isEnabledForEntity(provider)
const globallyEnabled = isGloballyEnabled(provider)
const isToggling = togglingProviderId === providerId
return (
<TableRow key={providerId || provider.name}>
<TableCell className="font-medium">{provider.name}</TableCell>
<TableCell className="font-mono text-sm">
{typeof provider.client_id === "string" ? provider.client_id : "—"}
</TableCell>
<TableCell>
{globallyEnabled ? (
<Badge variant="secondary" className="text-xs">
Global
</Badge>
) : (
<Badge variant="outline" className="text-xs">
Global off
</Badge>
)}
</TableCell>
<TableCell>
<Switch
checked={enabledForEntity}
disabled={isToggling || isLoading || !providerId || !globallyEnabled}
onCheckedChange={(checked) => handleToggleProvider(provider, checked)}
aria-label={`Enable ${provider.name} for ${entityName}`}
/>
</TableCell>
<TableCell>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setEditingProvider(toOAuthProvider(provider))}>
<Pencil className="mr-2 h-4 w-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem className="text-destructive" onClick={() => setDeletingProvider(provider)}>
<Trash2 className="mr-2 h-4 w-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
)
})
)}
</TableBody>
</Table>
</div>
<CreateOAuthProviderDialog
open={creating}
apiClient={apiClient}
onClose={() => setCreating(false)}
onCreated={handleProviderCreated}
/>
<EditOAuthProviderDialog
open={!!editingProvider}
provider={editingProvider}
apiClient={apiClient}
onClose={() => setEditingProvider(null)}
onUpdated={handleProviderUpdated}
/>
<AlertDialog open={!!deletingProvider} onOpenChange={(open) => !open && setDeletingProvider(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete OAuth Provider</AlertDialogTitle>
<AlertDialogDescription>
Remove <span className="font-medium text-foreground">{deletingProvider?.name}</span> from the global
registry? This removes it from all entities and cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteProvider}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
)
}

View File

@@ -1,103 +1,286 @@
"use client"
import * as React from "react"
import { RefreshCw, TestTube, Globe } from "lucide-react"
import { Mail, RefreshCw, Save } 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 { Switch } from "@/components/ui/switch"
import { SidebarTrigger } from "@/components/ui/sidebar"
import { Badge } from "@/components/ui/badge"
import type { ApiClient, AppSettings } from "@/lib/api"
import { Textarea } from "@/components/ui/textarea"
import {
SYS_SETTINGS_CONFIG_API,
type ApiClient,
type AppSettings,
type SmtpConfig,
} from "@/lib/api"
import { useToast } from "@/hooks/use-toast"
import { useAppState, type AppMode } from "@/lib/app-state"
import { SmtpTestDialog } from "./smtp-test-dialog"
interface SettingsSectionProps {
apiClient: ApiClient
settings: AppSettings | null
onSettingsUpdate: (settings: AppSettings) => void
onModeChange: (mode: AppMode, baseUrl?: string) => void
}
export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeChange }: SettingsSectionProps) {
type SettingsCard = "general" | "file" | "features" | "smtp"
const BYTES_PER_MB = 1024 * 1024
function corsOriginsToText(origins: string[]): string {
return origins.join("\n")
}
function textToCorsOrigins(text: string): string[] {
return text.split("\n").map((line) => line.trim()).filter(Boolean)
}
function smtpEqual(a: SmtpConfig, b: SmtpConfig, ignorePassword = false): boolean {
return (
a.host === b.host &&
a.port === b.port &&
a.user === b.user &&
a.from === b.from &&
a.tls === b.tls &&
(ignorePassword || a.password === b.password)
)
}
export function SettingsSection({ apiClient }: SettingsSectionProps) {
const { toast } = useToast()
const { mode, setMode } = useAppState()
const [formData, setFormData] = React.useState<AppSettings | null>(null)
const [isLoading, setIsLoading] = React.useState(false)
const [hasChanges, setHasChanges] = React.useState(false)
const [originalData, setOriginalData] = React.useState<AppSettings | null>(null)
const [corsOriginsText, setCorsOriginsText] = React.useState("")
const [originalCorsOriginsText, setOriginalCorsOriginsText] = React.useState("")
const [isLoading, setIsLoading] = React.useState<Record<string, boolean>>({})
const [isRefreshing, setIsRefreshing] = React.useState(false)
const [isBootstrapping, setIsBootstrapping] = React.useState(true)
const [smtpTestOpen, setSmtpTestOpen] = React.useState(false)
const applySettings = React.useCallback((settings: AppSettings) => {
const normalized: AppSettings = {
...settings,
corsAllowedOrigins: settings.corsAllowedOrigins ?? [],
smtp: {
host: "",
port: 587,
user: "",
password: "",
from: "",
tls: true,
...settings.smtp,
},
}
const corsText = corsOriginsToText(normalized.corsAllowedOrigins)
setFormData(normalized)
setOriginalData(normalized)
setCorsOriginsText(corsText)
setOriginalCorsOriginsText(corsText)
}, [])
const loadSettings = React.useCallback(async () => {
const settings = await apiClient.call<AppSettings>(SYS_SETTINGS_CONFIG_API)
applySettings(settings)
return settings
}, [apiClient, applySettings])
React.useEffect(() => {
if (settings) {
setFormData({ ...settings, mode })
setHasChanges(false)
let cancelled = false
const bootstrap = async () => {
try {
await loadSettings()
} catch (error) {
if (!cancelled) {
console.error("Failed to load settings:", error)
toast({
variant: "destructive",
title: "Error",
description: "Failed to load settings. Please try again.",
})
}
} finally {
if (!cancelled) {
setIsBootstrapping(false)
}
}
}
}, [settings, mode])
const handleInputChange = (field: keyof AppSettings, value: any) => {
bootstrap()
return () => {
cancelled = true
}
}, [loadSettings, toast])
const getCardChanges = (cardType: SettingsCard): boolean => {
if (!formData || !originalData) return false
if (cardType === "general") {
return (
formData.orgName !== originalData.orgName ||
formData.siteDomain !== originalData.siteDomain ||
corsOriginsText !== originalCorsOriginsText
)
}
if (cardType === "file") {
return (
formData.maxFileSize !== originalData.maxFileSize ||
formData.logRetentionDays !== originalData.logRetentionDays ||
formData.sessionTimeout !== originalData.sessionTimeout ||
formData.adminSessionTimeout !== originalData.adminSessionTimeout
)
}
if (cardType === "features") {
return (
formData.disableAdminRegistration !== originalData.disableAdminRegistration ||
formData.disableSchemaMutations !== originalData.disableSchemaMutations ||
formData.emailVerificationRequired !== originalData.emailVerificationRequired ||
formData.jwtEnableSetIssuer !== originalData.jwtEnableSetIssuer ||
formData.jwtEnableSetAudience !== originalData.jwtEnableSetAudience
)
}
if (cardType === "smtp") {
return !smtpEqual(formData.smtp, originalData.smtp)
}
return false
}
const buildPatchPayload = (cardType: SettingsCard): Partial<AppSettings> => {
if (!formData) return {}
if (cardType === "general") {
return {
orgName: formData.orgName,
siteDomain: formData.siteDomain,
corsAllowedOrigins: textToCorsOrigins(corsOriginsText),
}
}
if (cardType === "file") {
return {
maxFileSize: formData.maxFileSize,
logRetentionDays: formData.logRetentionDays,
sessionTimeout: formData.sessionTimeout,
adminSessionTimeout: formData.adminSessionTimeout,
}
}
if (cardType === "features") {
return {
disableAdminRegistration: formData.disableAdminRegistration,
disableSchemaMutations: formData.disableSchemaMutations,
emailVerificationRequired: formData.emailVerificationRequired,
jwtEnableSetIssuer: formData.jwtEnableSetIssuer,
jwtEnableSetAudience: formData.jwtEnableSetAudience,
}
}
const smtpPatch: Partial<SmtpConfig> = {
host: formData.smtp.host,
port: formData.smtp.port,
user: formData.smtp.user,
from: formData.smtp.from,
tls: formData.smtp.tls,
}
if (formData.smtp.password.length > 0) {
smtpPatch.password = formData.smtp.password
}
return { smtp: smtpPatch as SmtpConfig }
}
const handleInputChange = <K extends keyof AppSettings>(field: K, value: AppSettings[K]) => {
if (!formData) return
setFormData({ ...formData, [field]: value })
}
const handleSmtpChange = <K extends keyof SmtpConfig>(field: K, value: SmtpConfig[K]) => {
if (!formData) return
setFormData({
...formData,
[field]: value,
smtp: { ...formData.smtp, [field]: value },
})
setHasChanges(true)
}
const handleModeToggle = (newMode: AppMode) => {
setMode(newMode)
if (formData) {
setFormData({
...formData,
mode: newMode,
})
setHasChanges(true)
}
onModeChange(newMode, formData?.baseUrl)
}
const handleSave = async () => {
const handleSave = async (cardType: SettingsCard) => {
if (!formData) return
setIsLoading(true)
setIsLoading((prev) => ({ ...prev, [cardType]: true }))
try {
const updatedSettings = await apiClient.call<AppSettings>("/api/v1/settings/config", {
const updatedSettings = await apiClient.call<AppSettings>(SYS_SETTINGS_CONFIG_API, {
method: "PATCH",
body: JSON.stringify(formData),
body: JSON.stringify(buildPatchPayload(cardType)),
})
onSettingsUpdate(updatedSettings)
setHasChanges(false)
applySettings(updatedSettings)
toast({
title: "Settings Saved",
description: "Application settings have been updated successfully.",
description: `${cardType.charAt(0).toUpperCase()}${cardType.slice(1)} settings have been updated successfully.`,
duration: 3000,
})
} catch (error) {
console.error("Failed to update settings:", error)
toast({
variant: "destructive",
title: "Error",
description: "Failed to save settings. Please try again.",
})
} finally {
setIsLoading(false)
setIsLoading((prev) => ({ ...prev, [cardType]: false }))
}
}
const handleRefresh = async () => {
setIsRefreshing(true)
try {
const updatedSettings = await apiClient.call<AppSettings>("/api/v1/settings/config")
onSettingsUpdate(updatedSettings)
await loadSettings()
} catch (error) {
console.error("Failed to refresh settings:", error)
toast({
variant: "destructive",
title: "Error",
description: "Failed to refresh settings. Please try again.",
})
} finally {
setIsRefreshing(false)
}
}
// Show loading if we don't have formData yet
if (!formData) {
const renderSaveButton = (cardType: SettingsCard) => {
if (!getCardChanges(cardType)) return null
return (
<div className="flex items-center justify-center h-64">
<Button
size="sm"
onClick={() => handleSave(cardType)}
disabled={isLoading[cardType]}
className="gap-2"
>
{isLoading[cardType] ? (
<>
<RefreshCw className="h-4 w-4 animate-spin" />
Saving...
</>
) : (
<>
<Save className="h-4 w-4" />
Save
</>
)}
</Button>
)
}
if (isBootstrapping || !formData) {
return (
<div className="flex h-64 items-center justify-center">
<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>
<div className="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
<p className="text-muted-foreground">Loading settings...</p>
</div>
</div>
@@ -105,217 +288,300 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
}
return (
<div className="space-y-6">
<div className="space-y-8 p-6">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<SidebarTrigger />
<div>
<h2 className="text-2xl font-bold">Application Settings</h2>
<p className="text-muted-foreground">Configure global application settings</p>
</div>
</div>
<div className="flex items-center gap-2">
<Badge variant={mode === "TEST" ? "secondary" : "default"} className="flex items-center gap-1">
{mode === "TEST" ? <TestTube className="h-3 w-3" /> : <Globe className="h-3 w-3" />}
{mode} MODE
</Badge>
<Button variant="outline" size="sm" onClick={handleRefresh} disabled={isRefreshing}>
<RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />
</Button>
<div className="space-y-1">
<h1 className="text-3xl font-bold tracking-tight">Settings</h1>
<p className="text-muted-foreground">
Manage your application configuration and preferences
{formData.mantisVersion ? (
<>
{" "}
· Server <span className="font-mono text-foreground">{formData.mantisVersion}</span>
</>
) : null}
</p>
</div>
<Button variant="outline" size="icon" onClick={handleRefresh} disabled={isRefreshing}>
<RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />
</Button>
</div>
<Card>
<CardHeader>
<CardTitle>General Settings</CardTitle>
<CardDescription>Basic application configuration</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<Label htmlFor="app-name">Application Name</Label>
<Input
id="app-name"
value={formData?.appName || ""}
onChange={(e) => handleInputChange("appName", e.target.value)}
/>
</div>
<div>
<Label htmlFor="version">Version</Label>
<Input
id="version"
value={formData?.mantisVersion || ""}
disabled={true}
/>
</div>
</div>
<div>
<Label htmlFor="base-url">Base URL</Label>
<Input
id="base-url"
value={formData?.baseUrl || ""}
onChange={(e) => handleInputChange("baseUrl", e.target.value)}
placeholder="https://your-api-domain.com"
/>
<p className="text-sm text-muted-foreground mt-1">
The base URL for your API endpoints{" "}
{mode === "PROD" ? "(used in production mode)" : "(not used in test mode)"}
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<Label htmlFor="max-file-size">Max File Size (MB)</Label>
<Input
id="max-file-size"
type="number"
value={formData?.maxFileSize?.toString() || 10}
onChange={(e) => handleInputChange("maxFileSize", Number.parseInt(e.target.value) || 10)}
/>
</div>
<div>
<Label htmlFor="session-timeout">Session Timeout (seconds)</Label>
<Input
id="session-timeout"
type="number"
value={formData?.sessionTimeout?.toString() || 86400}
onChange={(e) => handleInputChange("sessionTimeout", Number.parseInt(e.target.value) || 86400)}
/>
</div>
<div>
<Label htmlFor="session-timeout">Admin Session Timeout (seconds)</Label>
<Input
id="admin-session-timeout"
type="number"
value={formData?.adminSessionTimeout?.toString() || 84000}
onChange={(e) => handleInputChange("adminSessionTimeout", Number.parseInt(e.target.value) || 3600)}
/>
</div>
</div>
<div className="space-y-4">
<div className="space-y-6">
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<Label>Maintenance Mode</Label>
<p className="text-sm text-muted-foreground">Enable maintenance mode for the application</p>
<CardTitle>General</CardTitle>
<CardDescription>Organization details, public site URL, and CORS origins</CardDescription>
</div>
{renderSaveButton("general")}
</div>
</CardHeader>
<CardContent className="space-y-6">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="org-name">Organization Name</Label>
<Input
id="org-name"
value={formData.orgName}
onChange={(e) => handleInputChange("orgName", e.target.value)}
placeholder="ACME Corp"
/>
</div>
<div className="space-y-2">
<Label htmlFor="site-domain">Site Domain</Label>
<Input
id="site-domain"
value={formData.siteDomain}
onChange={(e) => handleInputChange("siteDomain", e.target.value)}
placeholder="https://acme.example.com"
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="cors-origins">CORS Allowed Origins</Label>
<Textarea
id="cors-origins"
value={corsOriginsText}
onChange={(e) => setCorsOriginsText(e.target.value)}
placeholder={"http://localhost:3000\nhttp://127.0.0.1:3000"}
rows={4}
/>
<p className="text-sm text-muted-foreground">Enter one origin per line.</p>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle>File & Sessions</CardTitle>
<CardDescription>Upload limits, log retention, and session timeouts</CardDescription>
</div>
{renderSaveButton("file")}
</div>
</CardHeader>
<CardContent className="space-y-6">
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<div className="space-y-2">
<Label htmlFor="max-file-size">Max File Size (MB)</Label>
<Input
id="max-file-size"
type="number"
value={Math.round(formData.maxFileSize / BYTES_PER_MB)}
onChange={(e) =>
handleInputChange(
"maxFileSize",
(Number.parseInt(e.target.value, 10) || 1) * BYTES_PER_MB,
)
}
min="1"
/>
</div>
<div className="space-y-2">
<Label htmlFor="log-retention-days">Log Retention (days)</Label>
<Input
id="log-retention-days"
type="number"
value={formData.logRetentionDays}
onChange={(e) =>
handleInputChange("logRetentionDays", Number.parseInt(e.target.value, 10) || 1)
}
min="1"
/>
</div>
<div className="space-y-2">
<Label htmlFor="session-timeout">Session Timeout (s)</Label>
<Input
id="session-timeout"
type="number"
value={formData.sessionTimeout}
onChange={(e) =>
handleInputChange("sessionTimeout", Number.parseInt(e.target.value, 10) || 1)
}
min="1"
/>
</div>
<div className="space-y-2">
<Label htmlFor="admin-session-timeout">Admin Session (s)</Label>
<Input
id="admin-session-timeout"
type="number"
value={formData.adminSessionTimeout}
onChange={(e) =>
handleInputChange("adminSessionTimeout", Number.parseInt(e.target.value, 10) || 1)
}
min="1"
/>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle>Features</CardTitle>
<CardDescription>Registration, schema changes, email verification, and JWT options</CardDescription>
</div>
{renderSaveButton("features")}
</div>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<Label className="text-base">Disable Admin Registration</Label>
<p className="text-sm text-muted-foreground">Prevent creation of new admin accounts</p>
</div>
<Switch
checked={formData?.maintenanceMode || false}
onCheckedChange={(checked) => handleInputChange("maintenanceMode", checked)}
checked={formData.disableAdminRegistration}
onCheckedChange={(checked) => handleInputChange("disableAdminRegistration", checked)}
/>
</div>
<div className="flex items-center justify-between">
<div>
<Label>Allow Registration</Label>
<p className="text-sm text-muted-foreground">Allow new users to register</p>
<div className="flex items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<Label className="text-base">Disable Schema Mutations</Label>
<p className="text-sm text-muted-foreground">Block create, update, and delete operations on schemas</p>
</div>
<Switch
checked={formData?.allowRegistration || false}
onCheckedChange={(checked) => handleInputChange("allowRegistration", checked)}
checked={formData.disableSchemaMutations}
onCheckedChange={(checked) => handleInputChange("disableSchemaMutations", checked)}
/>
</div>
<div className="flex items-center justify-between">
<div>
<Label>Email Verification Required</Label>
<div className="flex items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<Label className="text-base">Email Verification Required</Label>
<p className="text-sm text-muted-foreground">Require email verification for new accounts</p>
</div>
<Switch
checked={formData?.emailVerificationRequired || false}
checked={formData.emailVerificationRequired}
onCheckedChange={(checked) => handleInputChange("emailVerificationRequired", checked)}
/>
</div>
</div>
</CardContent>
</Card>
{/* Environment Mode Card */}
<Card>
<CardHeader>
<CardTitle>Environment Mode</CardTitle>
<CardDescription>Switch between test mode (cors supported) and production mode (real API calls)</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Card
className={`cursor-pointer transition-all ${mode === "TEST" ? "ring-2 ring-primary" : "hover:bg-muted/50"}`}
onClick={() => handleModeToggle("TEST")}
>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<TestTube className="h-5 w-5 text-blue-600" />
<div>
<h4 className="font-medium">Test Mode</h4>
<p className="text-sm text-muted-foreground">Uses UI dev server for development</p>
</div>
{mode === "TEST" && (
<Badge variant="default" className="ml-auto">
Active
</Badge>
)}
</div>
</CardContent>
</Card>
<div className="flex items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<Label className="text-base">JWT Set Issuer</Label>
<p className="text-sm text-muted-foreground">Include issuer claim when signing JWTs</p>
</div>
<Switch
checked={formData.jwtEnableSetIssuer}
onCheckedChange={(checked) => handleInputChange("jwtEnableSetIssuer", checked)}
/>
</div>
<Card
className={`cursor-pointer transition-all ${mode === "PROD" ? "ring-2 ring-primary" : "hover:bg-muted/50"}`}
onClick={() => handleModeToggle("PROD")}
>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<Globe className="h-5 w-5 text-green-600" />
<div>
<h4 className="font-medium">Production Mode</h4>
<p className="text-sm text-muted-foreground">API and UI running on same server.</p>
</div>
{mode === "PROD" && (
<Badge variant="default" className="ml-auto">
Active
</Badge>
)}
</div>
</CardContent>
</Card>
</div>
<div className="flex items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<Label className="text-base">JWT Set Audience</Label>
<p className="text-sm text-muted-foreground">Include audience claim when signing JWTs</p>
</div>
<Switch
checked={formData.jwtEnableSetAudience}
onCheckedChange={(checked) => handleInputChange("jwtEnableSetAudience", checked)}
/>
</div>
</CardContent>
</Card>
{mode === "TEST" && (
<div className="p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
<div className="flex items-start gap-2">
<Globe className="h-4 w-4 text-yellow-600 mt-0.5" />
<div>
<p className="text-sm font-medium text-yellow-800 dark:text-yellow-200">Testing Mode Active</p>
<p className="text-sm text-yellow-700 dark:text-yellow-300">
All API calls will be made to an external API server. Ensure your API server is running and
accessible, and set `MANTIS_PORT` in the env settings.
</p>
</div>
<Card>
<CardHeader>
<div className="flex items-center justify-between gap-3">
<div>
<CardTitle>SMTP</CardTitle>
<CardDescription>Outbound email delivery configuration</CardDescription>
</div>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setSmtpTestOpen(true)}
className="gap-2"
>
<Mail className="h-4 w-4" />
Test SMTP
</Button>
{renderSaveButton("smtp")}
</div>
</div>
</CardHeader>
<CardContent className="space-y-6">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="smtp-host">Host</Label>
<Input
id="smtp-host"
value={formData.smtp.host}
onChange={(e) => handleSmtpChange("host", e.target.value)}
placeholder="smtp.example.com"
/>
</div>
<div className="space-y-2">
<Label htmlFor="smtp-port">Port</Label>
<Input
id="smtp-port"
type="number"
value={formData.smtp.port}
onChange={(e) => handleSmtpChange("port", Number.parseInt(e.target.value, 10) || 587)}
min="1"
/>
</div>
<div className="space-y-2">
<Label htmlFor="smtp-user">Username</Label>
<Input
id="smtp-user"
value={formData.smtp.user}
onChange={(e) => handleSmtpChange("user", e.target.value)}
placeholder="smtp-user"
/>
</div>
<div className="space-y-2">
<Label htmlFor="smtp-password">Password</Label>
<Input
id="smtp-password"
type="password"
value={formData.smtp.password}
onChange={(e) => handleSmtpChange("password", e.target.value)}
placeholder="Leave blank to keep current password"
autoComplete="new-password"
/>
</div>
<div className="space-y-2 sm:col-span-2">
<Label htmlFor="smtp-from">From Address</Label>
<Input
id="smtp-from"
value={formData.smtp.from}
onChange={(e) => handleSmtpChange("from", e.target.value)}
placeholder="noreply@example.com"
/>
</div>
</div>
)}
</CardContent>
</Card>
<div className="flex items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<Label className="text-base">Use TLS</Label>
<p className="text-sm text-muted-foreground">Enable TLS for SMTP connections</p>
</div>
<Switch
checked={formData.smtp.tls}
onCheckedChange={(checked) => handleSmtpChange("tls", checked)}
/>
</div>
<div className="flex justify-end gap-2">
<Button
variant="outline"
onClick={() => {
if (settings) {
setFormData({ ...settings, mode })
setHasChanges(false)
}
}}
disabled={!hasChanges}
>
Reset
</Button>
<Button onClick={handleSave} disabled={isLoading || !hasChanges}>
{isLoading ? "Saving..." : "Save Settings"}
</Button>
<p className="text-sm text-muted-foreground">
Test SMTP uses the configuration already saved on the server. Save any changes before testing.
</p>
</CardContent>
</Card>
</div>
<SmtpTestDialog open={smtpTestOpen} apiClient={apiClient} onClose={() => setSmtpTestOpen(false)} />
</div>
)
}

View File

@@ -0,0 +1,133 @@
"use client"
import * as React from "react"
import { Mail } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Alert, AlertDescription } from "@/components/ui/alert"
import {
SYS_SETTINGS_SMTP_TEST_API,
getApiClientError,
type ApiClient,
type SmtpTestResult,
} from "@/lib/api"
import { useToast } from "@/hooks/use-toast"
interface SmtpTestDialogProps {
open: boolean
apiClient: ApiClient
onClose: () => void
}
function isValidEmail(value: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
}
export function SmtpTestDialog({ open, apiClient, onClose }: SmtpTestDialogProps) {
const { toast } = useToast()
const [email, setEmail] = React.useState("")
const [isLoading, setIsLoading] = React.useState(false)
const [error, setError] = React.useState("")
React.useEffect(() => {
if (open) {
setEmail("")
setError("")
}
}, [open])
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault()
const trimmed = email.trim()
if (!trimmed || !isValidEmail(trimmed)) {
setError("Enter a valid email address")
return
}
setIsLoading(true)
setError("")
try {
const result = await apiClient.call<SmtpTestResult>(SYS_SETTINGS_SMTP_TEST_API, {
method: "POST",
body: JSON.stringify({ email: trimmed }),
})
const apiError = getApiClientError(result)
if (apiError) {
throw new Error(apiError)
}
toast({
title: "Test Email Sent",
description: result?.message || `A test message was sent to ${trimmed}.`,
duration: 5000,
})
onClose()
} catch (submitError) {
console.error("Failed to send SMTP test email:", submitError)
setError(submitError instanceof Error ? submitError.message : "Failed to send test email")
} finally {
setIsLoading(false)
}
}
return (
<Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Mail className="h-5 w-5" />
Send Test Email
</DialogTitle>
<DialogDescription>
Sends a message using the SMTP settings already saved on the server. Unsaved form changes are not used.
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="smtp-test-email">Recipient email</Label>
<Input
id="smtp-test-email"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
placeholder="you@example.com"
required
autoFocus
/>
<p className="text-xs text-muted-foreground">
Limited to 3 test messages per recipient per hour.
</p>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose} disabled={isLoading}>
Cancel
</Button>
<Button type="submit" disabled={isLoading}>
{isLoading ? "Sending..." : "Send Test Email"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}

189
components/setup-form.tsx Normal file
View File

@@ -0,0 +1,189 @@
"use client"
import * as React from "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 { useAppState } from "@/lib/app-state"
import { useToast } from "@/hooks/use-toast"
interface SetupFormProps {
token: string
onSetupComplete: () => void
}
export function SetupForm({ token, onSetupComplete }: SetupFormProps) {
const [email, setEmail] = React.useState("")
const [password, setPassword] = React.useState("")
const [confirmPassword, setConfirmPassword] = React.useState("")
const [showPassword, setShowPassword] = React.useState(false)
const [showConfirmPassword, setShowConfirmPassword] = React.useState(false)
const [isLoading, setIsLoading] = React.useState(false)
const [error, setError] = React.useState("")
const [success, setSuccess] = React.useState(false)
const { mode } = useAppState()
const { toast } = useToast()
const apiClient = React.useMemo(() => {
return new ApiClient(
() => {},
(error) => setError(error),
token,
)
}, [token])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setIsLoading(true)
setError("")
if (password !== confirmPassword) {
setError("Passwords do not match")
setIsLoading(false)
return
}
if (password.length < 8) {
setError("Password must be at least 8 characters long")
setIsLoading(false)
return
}
try {
// Create admin account using the setup token
const response: any = await apiClient.call("/api/v1/sys/admins/setup", {
method: "POST",
body: JSON.stringify({
email,
password,
}),
})
// 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",
description: "Your admin account has been created successfully. You can now sign in.",
})
// Wait a moment then redirect to login
setTimeout(() => {
onSetupComplete()
}, 2000)
} catch (err: any) {
// 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)
}
}
return (
<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 Admin Account</CardTitle>
<CardDescription>Create your first admin account to get started</CardDescription>
</CardHeader>
<CardContent>
{success ? (
<div className="text-center space-y-4 py-4">
<CheckCircle2 className="h-16 w-16 text-green-500 mx-auto" />
<p className="text-lg font-medium">Account created successfully!</p>
<p className="text-sm text-muted-foreground">Redirecting to login...</p>
</div>
) : (
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
placeholder="admin@example.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">Password</Label>
<div className="relative">
<Input
id="password"
type={showPassword ? "text" : "password"}
placeholder="Enter your password (min. 8 characters)"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={8}
/>
<Button
type="button"
variant="ghost"
size="sm"
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
onClick={() => setShowPassword(!showPassword)}
>
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="confirm-password">Confirm Password</Label>
<div className="relative">
<Input
id="confirm-password"
type={showConfirmPassword ? "text" : "password"}
placeholder="Confirm your password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
minLength={8}
/>
<Button
type="button"
variant="ghost"
size="sm"
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
>
{showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
</div>
</div>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? "Creating account..." : "Create Admin Account"}
</Button>
</form>
)}
</CardContent>
</Card>
</div>
)
}

View File

@@ -19,14 +19,11 @@ export function SyncSection() {
}
return (
<div className="space-y-6">
<div className="space-y-6 p-6">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<SidebarTrigger />
<div>
<h2 className="text-2xl font-bold">Data Synchronization</h2>
<p className="text-muted-foreground">Manage data sync operations and status</p>
</div>
<div className="space-y-1">
<h1 className="text-3xl font-bold tracking-tight">Sync</h1>
<p className="text-muted-foreground">Manage data sync operations and status</p>
</div>
<Button onClick={handleSync} disabled={isLoading}>
<RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? "animate-spin" : ""}`} />

View File

@@ -3,5 +3,9 @@ import { ThemeProvider as NextThemesProvider } from "next-themes"
import type { ThemeProviderProps } from "next-themes"
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
return (
<NextThemesProvider {...props} suppressColorSchemeWarning>
{children}
</NextThemesProvider>
)
}

View File

@@ -5,7 +5,11 @@ import { Moon, Sun } from "lucide-react"
import { useTheme } from "next-themes"
import { SidebarMenuButton } from "@/components/ui/sidebar"
export function ThemeToggle() {
interface ThemeToggleProps {
iconOnly?: boolean
}
export function ThemeToggle({ iconOnly = false }: ThemeToggleProps) {
const { theme, setTheme, resolvedTheme } = useTheme()
const [mounted, setMounted] = React.useState(false)
@@ -15,21 +19,27 @@ export function ThemeToggle() {
if (!mounted) {
return (
<SidebarMenuButton>
<div className="h-4 w-4" />
<span>Theme</span>
<SidebarMenuButton style={iconOnly ? { height: "4rem", minHeight: "4rem" } : undefined} className={iconOnly ? "w-full justify-center p-0 mx-0 rounded-none min-w-full" : ""}>
<div className="h-6 w-6" />
{!iconOnly && <span>Theme</span>}
</SidebarMenuButton>
)
}
const toggleTheme = () => {
setTheme(resolvedTheme === "dark" ? "light" : "dark")
// Always toggle between light and dark explicitly
const currentResolved = resolvedTheme || "light"
const newTheme = currentResolved === "dark" ? "light" : "dark"
setTheme(newTheme)
}
const displayTheme = resolvedTheme || "light"
return (
<SidebarMenuButton onClick={toggleTheme}>
{resolvedTheme === "dark" ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
<span>{resolvedTheme === "dark" ? "Light Mode" : "Dark Mode"}</span>
<SidebarMenuButton onClick={toggleTheme} style={iconOnly ? { height: "4rem", minHeight: "4rem" } : undefined} className={iconOnly ? "w-full justify-center p-0 mx-0 rounded-none min-w-full" : ""}>
{displayTheme === "dark" ? <Sun className="h-6 w-6" /> : <Moon className="h-6 w-6" />}
{!iconOnly && <span>{displayTheme === "dark" ? "Light Mode" : "Dark Mode"}</span>}
{iconOnly && <span className="sr-only">{displayTheme === "dark" ? "Switch to Light" : "Switch to Dark"}</span>}
</SidebarMenuButton>
)
}

View File

@@ -44,7 +44,7 @@ const TabsContent = React.forwardRef<
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 data-[state=inactive]:hidden",
className
)}
{...props}

View File

@@ -1,46 +1,115 @@
"use client"
import type { AppMode } from "./app-state"
import { useRouter } from "@/lib/router"
// Updated interfaces to match the API response format
export interface TableField {
autoGeneratePattern: string | null
defaultValue: string | null
maxValue: number | null
minValue: number | null
name: string
old_name: string | null
primaryKey: boolean
required: boolean
system: boolean
type: string
unique: boolean
export interface FieldConstraints {
default_value: any
max_value: number | null
min_value: number | null
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
primary_key: boolean
required: boolean
system: boolean
type: string
precision?: string | null
unique: boolean
constraints: FieldConstraints
foreign_key?: ForeignKeyConfig // optional foreign key configuration
}
export interface RuleConfig {
expr: string
mode: string
}
export interface SchemaRules {
add: RuleConfig
delete: RuleConfig
get: RuleConfig
list: RuleConfig
update: RuleConfig
}
/** Login methods and verification policy for auth-type entities (PATCH via schema `auth`). */
export interface AuthMethods {
password: boolean
otp: boolean
oauth: boolean
requireEmailVerification: boolean
}
export const DEFAULT_AUTH_METHODS: AuthMethods = {
password: true,
otp: false,
oauth: false,
requireEmailVerification: false,
}
/**
* Normalize schema auth flags for UI/API use.
* Backward compatible: when `auth` is null/undefined (older schemas), password is ON
* and otp/oauth/requireEmailVerification are OFF — matching pre-method-flag password-only login.
*/
export function normalizeAuthMethods(auth?: Partial<AuthMethods> | null): AuthMethods {
if (auth == null) {
return { ...DEFAULT_AUTH_METHODS }
}
return {
// Missing password key on a partial auth object also defaults to ON.
password: auth.password ?? true,
otp: auth.otp ?? false,
oauth: auth.oauth ?? false,
requireEmailVerification: auth.requireEmailVerification ?? false,
}
}
export function authMethodLabel(method: keyof AuthMethods): string {
switch (method) {
case "otp":
return "Email sign-in codes"
case "oauth":
return "OAuth"
case "requireEmailVerification":
return "Require email verification"
case "password":
default:
return "Password login"
}
}
/** Public login-method flags for an auth entity. */
export function entityAuthMethodsApi(entityName: string): string {
return `/api/v1/auth/${encodeURIComponent(entityName)}/methods`
}
export interface TableSchema {
addRule: string
deleteRule: string
fields: TableField[]
getRule: string
has_api: boolean
id: string
listRule: string
name: string
rules: SchemaRules
system: boolean
type: "base" | "auth" | "view"
updateRule: string
/** Present on auth entities: which login methods are enabled. */
auth?: AuthMethods
sql?: string
}
export interface TableMetadata {
created: string
has_api: boolean
id: string
name: string
schema: TableSchema
type: "base" | "auth" | "view"
updated: string
}
@@ -51,17 +120,214 @@ 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
/** Application settings (GET/PATCH). */
export const SYS_SETTINGS_CONFIG_API = "/api/v1/sys/settings/config" as const
/** Send a test email using the saved SMTP configuration. */
export const SYS_SETTINGS_SMTP_TEST_API = "/api/v1/sys/settings/smtp/test" as const
/** Admin API keys (list, create, update, revoke). */
export const SYS_API_KEYS_API = "/api/v1/sys/api-keys" as const
/** OAuth provider registry (list, create, update, remove). */
export const SYS_OAUTH_PROVIDERS_API = "/api/v1/sys/oauth/providers" as const
/** Enable or disable OAuth providers per auth entity. */
export const SYS_OAUTH_ENTITY_CONFIG_API = "/api/v1/sys/oauth/entity-config" as const
export interface AdminApiKey {
id: string
entity_name: string
user_id: string
label: string
permissions: unknown[]
last_used: string | null
created: string
expires_at: string | null
}
export interface AdminApiKeyCreated extends AdminApiKey {
key: string
}
export interface AdminApiKeyCreateRequest {
user_id: string
label?: string
permissions?: unknown[]
expires_at?: string
}
export interface ApiKeyUser {
id: string
label: string
}
/** Entity auth user API keys (list, create, revoke). */
export function entityApiKeysApi(entityName: string): string {
return `/api/v1/auth/${encodeURIComponent(entityName)}/api-keys`
}
/** OAuth providers enabled for an auth entity (public list). */
export function entityOAuthProvidersApi(entityName: string): string {
return `/api/v1/auth/${encodeURIComponent(entityName)}/oauth/providers`
}
/** Provider row from GET /auth/{entity}/oauth/providers (includes entity enablement). */
export interface EntityOAuthProvider {
id: string
name: string
client_id?: string
enabled?: boolean
enabled_for_entity?: boolean
[key: string]: unknown
}
export interface OAuthProvider {
id: string
name: string
client_id?: string
enabled?: boolean
[key: string]: unknown
}
export interface OAuthProviderCreateRequest {
name: string
client_id: string
client_secret: string
}
export interface OAuthProviderUpdateRequest {
name?: string
client_id?: string
client_secret?: string
}
export interface OAuthEntityConfigRequest {
entity_name: string
provider_id: string
}
export interface OAuthEntityConfigResult {
entity_name: string
provider_id: string
enabled: boolean
}
/** Resolve provider UUID used in entity-config requests. */
export function getOAuthProviderId(provider: { id?: string; provider_id?: string }): string {
return provider.id ?? provider.provider_id ?? ""
}
/** Build URL to download or display an uploaded entity file. */
export function buildEntityFileUrl(entityName: string, fileName: string): string {
return `${getApiBaseUrl()}/api/v1/files/${encodeURIComponent(entityName)}/${encodeURIComponent(fileName)}`
}
export interface AdminApiKeyUpdateRequest {
label?: string
expires_at?: string | null
}
/** Extract list items from direct arrays or paginated API responses. */
export function extractListItems<T>(response: unknown): T[] {
if (Array.isArray(response)) {
return response
}
if (response && typeof response === "object") {
const record = response as Record<string, unknown>
if (Array.isArray(record.items)) {
return record.items as T[]
}
const data = record.data
if (Array.isArray(data)) {
return data as T[]
}
if (data && typeof data === "object") {
const nested = data as Record<string, unknown>
if (Array.isArray(nested.items)) {
return nested.items as T[]
}
}
}
return []
}
/** Detect error objects returned by ApiClient.call's catch handler. */
export function getApiClientError(response: unknown): string | null {
if (!response || typeof response !== "object") {
return null
}
const record = response as { error?: unknown; status?: unknown }
if (typeof record.error === "string" && record.error.length > 0) {
const status = typeof record.status === "number" ? record.status : 0
if (status >= 400 || status <= 0) {
return record.error
}
}
return null
}
/** HttpOnly cookie name set by the MantisBase backend on admin login/refresh; cleared on logout. */
export const ADMIN_SESSION_COOKIE = "admin_token" as const
/** 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(/\/+$/, "")
}
if (typeof window !== "undefined") {
return window.location.origin
}
const port = process?.env?.MANTIS_PORT || 7070
return `http://127.0.0.1:${port}`
}
export interface SmtpConfig {
host: string
port: number
user: string
password: string
from: string
tls: boolean
}
export interface AppSettings {
allowRegistration: boolean
appName: string
baseUrl: string
orgName: string
siteDomain: string
corsAllowedOrigins: string[]
maxFileSize: number
logRetentionDays: number
disableAdminRegistration: boolean
disableSchemaMutations: boolean
emailVerificationRequired: boolean
maintenanceMode: boolean
maxFileSize: Number
mode: AppMode
sessionTimeout: Number
adminSessionTimeout: Number
mantisVersion: string
sessionTimeout: number
adminSessionTimeout: number
jwtEnableSetIssuer: boolean
jwtEnableSetAudience: boolean
smtp: SmtpConfig
/** Running MantisBase server version (read-only from GET settings). */
mantisVersion?: string
}
export interface SmtpTestRequest {
email: string
}
export interface SmtpTestResult {
to: string
subject: string
message: string
}
// API Response interface
@@ -71,58 +337,47 @@ interface ApiResponse<T> {
status: number
}
export class ApiClient {
private token: string
private onUnauthorized: (error: string) => void
private onError?: (error: string, type?: "error" | "warning") => void
private requestCount = 0
private maxRequests = 100
private mode: AppMode
private baseUrl: string
function buildRequestHeaders(body: BodyInit | null | undefined, bearerToken?: string): Record<string, string> {
const headers: Record<string, string> = {}
constructor(
token: string,
onUnauthorized: (reason?: string | "") => void,
mode: AppMode = "PROD",
baseUrl = "http://127.0.0.1:7070",
onError?: (error: string, type?: "error" | "warning") => void,
) {
this.token = token
this.onUnauthorized = onUnauthorized
this.onError = onError
this.mode = mode
this.baseUrl = baseUrl
if (bearerToken) {
headers.Authorization = `Bearer ${bearerToken}`
}
private getApiBaseUrl(appMode: AppMode): string {
if (appMode === "TEST") {
// For debug mode, or non window sessions, pick port from env
const port = process.env.MANTIS_PORT || 7070; // match your server default
return `http://localhost:${port}`;
}
if (!(body instanceof FormData)) {
headers["Content-Type"] = "application/json"
}
if (typeof window !== "undefined") {
const { origin } = window.location;
console.log("ORIGIN: ", origin)
return `${origin}`;
} else {
const port = process.env.MANTIS_PORT || 7070; // match your server default
return `http://localhost:${port}`;
}
return headers
}
export class ApiClient {
private bearerToken?: string
private onUnauthorized: (error: string) => void
private onError?: (error: string, type?: "error" | "warning") => void
constructor(
onUnauthorized: (reason?: string | "") => void,
onError?: (error: string, type?: "error" | "warning") => void,
bearerToken?: string,
) {
this.bearerToken = bearerToken
this.onUnauthorized = onUnauthorized
this.onError = onError
}
private async realApiCall<T>(endpoint: string, options: RequestInit = {}): Promise<ApiResponse<T>> {
try {
const url = `${this.getApiBaseUrl(this.mode)}${endpoint}`
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${this.token}`,
...options.headers,
}
const url = `${getApiBaseUrl()}${endpoint}`
const headers = buildRequestHeaders(options.body, this.bearerToken)
const response = await fetch(url, {
...options,
headers,
credentials: "include",
headers: {
...headers,
...(options.headers as Record<string, string> | undefined),
},
})
// DELETE or No Content
@@ -133,10 +388,29 @@ export class ApiClient {
const responseData = await response.json()
// Ensure the structure always matches ApiResponse<T>
// The API should always return { data: ..., status: ..., error: ... }
// Handle both HTTP status and JSON body status
const jsonStatus = responseData.status ?? response.status
const jsonError = responseData.error ?? ""
// Extract data from response - should be an array for list endpoints
let data = responseData.data
// If data is missing, check if the entire response is an array (fallback)
if (data === undefined || data === null) {
// If responseData itself is an array, use it
if (Array.isArray(responseData)) {
data = responseData as T
} else {
// Otherwise default based on expected type
data = ({} as T)
}
}
return {
data: responseData.data ?? {},
error: responseData.error ?? "",
status: response.status,
data: data,
error: jsonError,
status: jsonStatus,
}
} catch (error: any) {
return {
@@ -151,63 +425,117 @@ export class ApiClient {
try {
let response: ApiResponse<T> = await this.realApiCall<T>(endpoint, options)
// Unauthorized handling
// Unauthorized handling - check both HTTP status and JSON status
if (response.status === 401 || response.status === 403) {
this.onUnauthorized(response.error || "Unauthorized")
throw new Error(response.error || "Unauthorized")
}
// General error handling
if (response.status >= 400 || response.status <= 0 || response.error) {
this.onError?.(response.error || "Request failed", "error")
throw new Error(response.error || "Request failed")
// General error handling - check JSON status from API response
// The API returns status in the JSON body: { data: [], status: 200, error: "" }
// Only treat as error if status >= 400 or error string is non-empty
if (response.status >= 400 || response.status <= 0) {
const errorMsg = response.error && response.error.length > 0
? response.error
: "Request failed"
if(errorMsg === "Failed to fetch") {
const finalError = `Failed to fetch '${endpoint}'. Could not reach the server!`
this.onError?.(finalError, "error")
throw new Error(finalError)
}
this.onError?.(errorMsg, "error")
throw new Error(errorMsg)
}
// If there's an error message but status is OK, log it but don't throw
if (response.error && response.error.length > 0) {
console.warn(`API warning for ${endpoint}:`, response.error)
}
// Return the data - should be an array for list endpoints
return response.data
} catch (error: any) {
return {
data: null as T,
error: error.message || "Could not connect to the server!",
status: 500, // could use 500 if you prefer
} as T
} as any
}
}
}
// Method to update mode
updateMode(mode: AppMode, baseUrl?: string) {
this.mode = mode
if (baseUrl) {
this.baseUrl = baseUrl
}
}
export interface LoginResponse {
user: Admin
}
export async function loginWithPassword(
email: string,
password: string,
mode: AppMode = "PROD",
baseUrl = "http://127.0.0.1:7070",
) {
// Real API call
password: string
): Promise<LoginResponse> {
try {
const response = await fetch(`${baseUrl}/api/v1/admins/auth-with-password`, {
const response = await fetch(`${getApiBaseUrl()}${SYS_ADMINS_API}/login`, {
method: "POST",
headers: { "Content-Type": "application/json", },
body: JSON.stringify({ email, password }),
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
identity: email,
password: password,
}),
})
const responseData = await response.json()
if (response.ok) {
// Check if response follows our API structure
if (responseData.data) {
return responseData.data
}
return responseData
} else {
throw new Error(responseData.error || responseData.message || "Login failed")
// Handle non-JSON responses
let responseData: any
try {
responseData = await response.json()
} catch (jsonError) {
throw new Error("Invalid response from server")
}
// Session cookie is set by the backend via Set-Cookie; JS must not read or store the token.
if (responseData.status === 200 && responseData.data?.user) {
return {
user: responseData.data.user,
}
}
const errorMessage = responseData.error || responseData.message || "Login failed"
throw new Error(errorMessage)
} catch (error: any) {
// Re-throw if it's already an Error with a message
if (error instanceof Error) {
throw error
}
throw new Error(error.message || "Network error occurred")
}
}
export async function checkAuthSession(): Promise<boolean> {
try {
const response = await fetch(`${getApiBaseUrl()}${SYS_ADMINS_API}`, {
method: "GET",
credentials: "include",
headers: { "Content-Type": "application/json" },
})
if (response.status === 401 || response.status === 403) {
return false
}
const responseData = await response.json()
return responseData.status === 200
} catch {
return false
}
}
export async function logoutSession(): Promise<void> {
try {
await fetch(`${getApiBaseUrl()}${SYS_ADMINS_API}/logout`, {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
})
} catch (error) {
console.warn("Failed to clear admin session cookie:", error)
}
}

52
lib/auth-fields.ts Normal file
View File

@@ -0,0 +1,52 @@
import type { TableField } from "@/lib/api"
/** Auth-entity fields that are optional when OAuth (or other methods) can create accounts. */
const OPTIONAL_AUTH_FIELD_NAMES = new Set(["password", "avatar"])
export function isOptionalAuthField(fieldName: string): boolean {
return OPTIONAL_AUTH_FIELD_NAMES.has(fieldName)
}
/**
* Whether a field must be filled in the admin record form.
* Password and avatar are never required on auth entities (OAuth-capable accounts).
*/
export function isFieldRequiredInForm(
field: Pick<TableField, "name" | "required">,
entityType: string,
): boolean {
if (entityType === "auth" && isOptionalAuthField(field.name)) {
return false
}
return Boolean(field.required)
}
/** Normalize auth schema field flags for UI (does not PATCH the server). */
export function normalizeAuthSchemaField<T extends Pick<TableField, "name" | "required" | "system">>(
field: T,
entityType: string,
): T {
if (entityType !== "auth" || !isOptionalAuthField(field.name)) {
return field
}
return {
...field,
required: false,
}
}
const PASSWORD_ALPHABET =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*-_=+"
/** Cryptographically random password suitable for admin-created auth users. */
export function generateRandomPassword(length = 20): string {
const size = Math.max(12, Math.min(length, 64))
const bytes = new Uint8Array(size)
crypto.getRandomValues(bytes)
let result = ""
for (let i = 0; i < size; i++) {
result += PASSWORD_ALPHABET[bytes[i]! % PASSWORD_ALPHABET.length]
}
return result
}

93
lib/auth.tsx Normal file
View File

@@ -0,0 +1,93 @@
"use client"
import * as React from "react"
import { checkAuthSession, loginWithPassword, logoutSession, type Admin } from "@/lib/api"
interface AuthContextValue {
isAuthenticated: boolean
isLoading: boolean
user: Admin | null
login: (email: string, password: string) => Promise<void>
logout: () => Promise<void>
refreshSession: () => Promise<boolean>
}
const AuthContext = React.createContext<AuthContextValue | null>(null)
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [isAuthenticated, setIsAuthenticated] = React.useState(false)
const [isLoading, setIsLoading] = React.useState(true)
const [user, setUser] = React.useState<Admin | null>(null)
const refreshSession = React.useCallback(async (): Promise<boolean> => {
const authenticated = await checkAuthSession()
setIsAuthenticated(authenticated)
if (!authenticated) {
setUser(null)
}
return authenticated
}, [])
React.useEffect(() => {
let cancelled = false
const bootstrap = async () => {
try {
const authenticated = await checkAuthSession()
if (!cancelled) {
setIsAuthenticated(authenticated)
}
} finally {
if (!cancelled) {
setIsLoading(false)
}
}
}
bootstrap()
return () => {
cancelled = true
}
}, [])
const login = React.useCallback(async (email: string, password: string) => {
const result = await loginWithPassword(email, password)
const authenticated = await checkAuthSession()
if (!authenticated) {
throw new Error(
"Login succeeded but the session cookie was not established. Ensure the admin UI and API share the same origin.",
)
}
setUser(result.user)
setIsAuthenticated(true)
}, [])
const logout = React.useCallback(async () => {
await logoutSession()
setUser(null)
setIsAuthenticated(false)
}, [])
const value = React.useMemo(
() => ({
isAuthenticated,
isLoading,
user,
login,
logout,
refreshSession,
}),
[isAuthenticated, isLoading, user, login, logout, refreshSession],
)
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}
export function useAuth() {
const context = React.useContext(AuthContext)
if (!context) {
throw new Error("useAuth must be used within an AuthProvider")
}
return context
}

View File

@@ -1,23 +1,3 @@
"use client"
import * as React from "react"
// Set expected data types, this should map what the database expects
// our column data types to be.
export const dataTypes = [
"xml",
"string",
"double",
"date",
"int8",
"uint8",
"int16",
"uint16",
"int32",
"uint32",
"int64",
"uint64",
"blob",
"json",
"bool"
]
export { dataTypes, intPrecisions, DEFAULT_INT_PRECISION } from "@/lib/field-types"

28
lib/entity-users.ts Normal file
View File

@@ -0,0 +1,28 @@
import type { ApiKeyUser } from "@/lib/api"
const DEFAULT_LABEL_FIELDS = ["email", "name", "username"] as const
export function getEntityUserLabel(
user: Record<string, unknown>,
preferredFields: readonly string[] = DEFAULT_LABEL_FIELDS,
): string {
for (const field of preferredFields) {
const value = user[field]
if (typeof value === "string" && value.trim()) {
return value
}
}
if (user.id !== undefined && user.id !== null) {
return String(user.id)
}
return "Unknown user"
}
export function toApiKeyUsers(records: Record<string, unknown>[]): ApiKeyUser[] {
return records.map((record) => ({
id: String(record.id),
label: getEntityUserLabel(record),
}))
}

150
lib/field-types.ts Normal file
View File

@@ -0,0 +1,150 @@
/** Supported entity field types in the schema editor. */
export const dataTypes = [
"string",
"double",
"date",
"int",
"json",
"bool",
"file",
"files",
] as const
/** Legacy types removed from the editor; normalized to `string` when loading schemas. */
const LEGACY_STRING_TYPES = new Set(["xml", "blob"])
export function isLegacyStringFieldType(type: string): boolean {
return LEGACY_STRING_TYPES.has(type)
}
/** Integer precision sizes for fields with type `int`. */
export const intPrecisions = [
"u8",
"u16",
"u32",
"u64",
"i8",
"i16",
"i32",
"i64",
] as const
export type IntPrecision = (typeof intPrecisions)[number]
export const DEFAULT_INT_PRECISION: IntPrecision = "i32"
const LEGACY_INT_TYPE_TO_PRECISION: Record<string, IntPrecision> = {
int8: "i8",
int16: "i16",
int32: "i32",
int64: "i64",
uint8: "u8",
uint16: "u16",
uint32: "u32",
uint64: "u64",
}
const LEGACY_INT_TYPES = new Set(Object.keys(LEGACY_INT_TYPE_TO_PRECISION))
export function isIntFieldType(type: string): boolean {
return type === "int" || LEGACY_INT_TYPES.has(type)
}
export function isNumericFieldType(type: string): boolean {
return isIntFieldType(type) || type === "double"
}
export function isUnsignedPrecision(precision: string | null | undefined): boolean {
return precision?.startsWith("u") ?? false
}
export function resolveFieldPrecision(field: {
type: string
precision?: string | null
}): string | null {
if (field.type === "int") {
return field.precision ?? DEFAULT_INT_PRECISION
}
return LEGACY_INT_TYPE_TO_PRECISION[field.type] ?? null
}
export function formatFieldTypeDisplay(field: {
type: string
precision?: string | null
}): string {
if (field.type === "int") {
const precision = field.precision ?? DEFAULT_INT_PRECISION
return `int(${precision})`
}
return field.type
}
export function normalizeFieldTypeForEditor(field: {
type: string
precision?: string | null
}): { type: string; precision: string | null } {
if (field.type === "int") {
return {
type: "int",
precision: field.precision ?? DEFAULT_INT_PRECISION,
}
}
const legacyPrecision = LEGACY_INT_TYPE_TO_PRECISION[field.type]
if (legacyPrecision) {
return {
type: "int",
precision: legacyPrecision,
}
}
if (LEGACY_STRING_TYPES.has(field.type)) {
return {
type: "string",
precision: null,
}
}
return {
type: field.type,
precision: field.precision ?? null,
}
}
export function applyFieldTypeChange(
currentType: string,
nextType: string,
currentPrecision?: string | null,
): { type: string; precision: string | null } {
if (nextType === "int") {
return {
type: "int",
precision: currentType === "int" ? (currentPrecision ?? DEFAULT_INT_PRECISION) : DEFAULT_INT_PRECISION,
}
}
return {
type: nextType,
precision: null,
}
}
export function appendPrecisionToFieldPayload(
fieldData: Record<string, unknown>,
field: { type: string; precision?: string | null },
): void {
if (field.type === "int") {
fieldData.precision = field.precision ?? DEFAULT_INT_PRECISION
}
}
/** True when a field still uses a removed legacy type from the API. */
export function fieldNeedsTypeMigration(field: { type: string }): boolean {
return LEGACY_INT_TYPES.has(field.type) || LEGACY_STRING_TYPES.has(field.type)
}
export function schemaFieldsNeedMigration(fields: { type: string }[]): boolean {
return fields.some(fieldNeedsTypeMigration)
}

View File

@@ -1,171 +0,0 @@
"use client"
import * as React from "react"
export interface RouteParams {
[key: string]: string
}
export interface ParsedRoute {
path: string
params: RouteParams
}
// Use a custom event system instead of relying on hash changes
const ROUTE_CHANGE_EVENT = "custom-route-change"
let currentRoute: ParsedRoute = { path: "/tables", params: {} }
export function parseRoute(hash: string): ParsedRoute {
try {
// Remove the # if present
const cleanHash = hash.startsWith("#") ? hash.slice(1) : hash
// If empty, default to /tables
if (!cleanHash) {
return { path: "/tables", params: {} }
}
// Split path and query string
const [pathPart, queryPart] = cleanHash.split("?")
// Parse query parameters
const params: RouteParams = {}
if (queryPart) {
try {
const searchParams = new URLSearchParams(queryPart)
for (const [key, value] of searchParams.entries()) {
params[key] = value
}
} catch (error) {
console.warn("Failed to parse query parameters:", error)
}
}
return {
path: pathPart || "/tables",
params,
}
} catch (error) {
console.warn("Failed to parse route:", error)
return { path: "/tables", params: {} }
}
}
export function buildRoute(path: string, params?: RouteParams): string {
try {
let route = path.startsWith("/") ? path : `/${path}`
if (params && Object.keys(params).length > 0) {
const searchParams = new URLSearchParams()
for (const [key, value] of Object.entries(params)) {
if (value) {
searchParams.set(key, value)
}
}
const queryString = searchParams.toString()
if (queryString) {
route += `?${queryString}`
}
}
return route
} catch (error) {
console.warn("Failed to build route:", error)
return "/tables"
}
}
// Custom event dispatcher
function dispatchRouteChange(route: ParsedRoute) {
const event = new CustomEvent(ROUTE_CHANGE_EVENT, { detail: route })
window.dispatchEvent(event)
}
export function useRouter() {
const [route, setRoute] = React.useState<ParsedRoute>(() => {
if (typeof window !== "undefined") {
try {
const initialRoute = parseRoute(window.location.hash)
currentRoute = initialRoute
return initialRoute
} catch (error) {
console.warn("Failed to get initial route:", error)
return { path: "/tables", params: {} }
}
}
return { path: "/tables", params: {} }
})
React.useEffect(() => {
const handleCustomRouteChange = (event: CustomEvent) => {
try {
const newRoute = event.detail as ParsedRoute
setRoute(newRoute)
currentRoute = newRoute
} catch (error) {
console.warn("Failed to handle route change:", error)
}
}
const handleHashChange = () => {
try {
const newRoute = parseRoute(window.location.hash)
setRoute(newRoute)
currentRoute = newRoute
} catch (error) {
console.warn("Failed to handle hash change:", error)
}
}
const handlePopState = () => {
try {
const newRoute = parseRoute(window.location.hash)
setRoute(newRoute)
currentRoute = newRoute
} catch (error) {
console.warn("Failed to handle pop state:", error)
}
}
// Listen for our custom events
window.addEventListener(ROUTE_CHANGE_EVENT, handleCustomRouteChange as EventListener)
// Still listen for hash changes for browser navigation
window.addEventListener("hashchange", handleHashChange)
window.addEventListener("popstate", handlePopState)
return () => {
window.removeEventListener(ROUTE_CHANGE_EVENT, handleCustomRouteChange as EventListener)
window.removeEventListener("hashchange", handleHashChange)
window.removeEventListener("popstate", handlePopState)
}
}, [])
const navigate = React.useCallback((path: string, params?: RouteParams) => {
try {
const routePath = buildRoute(path, params)
const newRoute: ParsedRoute = { path: routePath, params: params || {} }
// Update URL without triggering hash change event
const hashValue = `#${routePath}`
// Use replaceState to avoid adding to history if it's the same route
if (window.location.hash !== hashValue) {
window.history.pushState(null, "", hashValue)
}
// Dispatch our custom event
dispatchRouteChange(newRoute)
} catch (error) {
console.warn("Failed to navigate:", error)
}
}, [])
return { route, navigate }
}
// Helper function to get current route without hooks
export function getCurrentRoute(): ParsedRoute {
return currentRoute
}

49
lib/routes.ts Normal file
View File

@@ -0,0 +1,49 @@
"use client"
/** Admin dashboard route paths (without basePath). */
export const ROUTES = {
home: "/",
login: "/login",
setup: "/setup",
entities: "/entities",
entityDetail: "/entities/:name",
logs: "/logs",
admins: "/admins",
settings: "/settings",
} as const
export type DashboardSection = "entities" | "logs" | "admins" | "settings" | "sync"
const DASHBOARD_SECTIONS = new Set<string>(["entities", "logs", "admins", "settings", "sync"])
function getDefaultBasePath(): string {
return process.env.NODE_ENV === "production" ? "/mb" : ""
}
/** Application base path (e.g. `/mb` in production). */
export function getBasePath(): string {
if (typeof process.env.NEXT_PUBLIC_BASE_PATH !== "undefined") {
return process.env.NEXT_PUBLIC_BASE_PATH
}
if (typeof window !== "undefined") {
const pathname = window.location.pathname
if (pathname === "/mb" || pathname.startsWith("/mb/")) {
return "/mb"
}
}
return getDefaultBasePath()
}
export function entityDetailPath(name: string): string {
return `/entities/${encodeURIComponent(name)}`
}
export function getDashboardSection(pathname: string): DashboardSection {
const segment = pathname.split("/").filter(Boolean)[0] || "entities"
if (DASHBOARD_SECTIONS.has(segment)) {
return segment as DashboardSection
}
return "entities"
}

248
lib/schema-constraints.ts Normal file
View File

@@ -0,0 +1,248 @@
/**
* 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"
import { isIntFieldType, isUnsignedPrecision } from "@/lib/field-types"
const NUMERIC_TYPES = new Set(["double", "int"])
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 isUnsignedIntegerField(fieldType: string, precision?: string | null): boolean {
if (fieldType === "int") {
return isUnsignedPrecision(precision)
}
return fieldType.startsWith("uint")
}
function parseDefaultValue(
fieldType: string,
raw: unknown,
precision?: string | null,
): { 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":
case "blob": {
return { ok: true, value: typeof raw === "string" ? raw : String(raw) }
}
case "int":
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 (isUnsignedIntegerField(fieldType, precision) && 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,
precision?: string | null,
): 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) || isIntFieldType(fieldType)) {
const isInteger = isIntFieldType(fieldType)
const minInt = minR.value !== null && isInteger && !Number.isInteger(minR.value)
const maxInt = maxR.value !== null && isInteger && !Number.isInteger(maxR.value)
if (minInt || maxInt) {
return { ok: false, message: "Min/max for integer types must be whole numbers." }
}
if (isUnsignedIntegerField(fieldType, precision)) {
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, precision)
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,
},
}
}

124
lib/schema-migration.ts Normal file
View File

@@ -0,0 +1,124 @@
import type { ApiClient, TableField, TableMetadata } from "@/lib/api"
import { normalizeAuthMethods } from "@/lib/api"
import { normalizeAuthSchemaField } from "@/lib/auth-fields"
import {
appendPrecisionToFieldPayload,
normalizeFieldTypeForEditor,
schemaFieldsNeedMigration,
} from "@/lib/field-types"
export function normalizeSchemaField(field: TableField): TableField {
const { type, precision } = normalizeFieldTypeForEditor(field)
const normalized: TableField = { ...field, type }
if (type === "int") {
normalized.precision = precision
} else {
normalized.precision = undefined
}
return normalized
}
export function normalizeTableSchema(table: TableMetadata): TableMetadata {
if (!table.schema) {
return table
}
const schema = {
...table.schema,
fields: table.schema.fields?.map((field) => {
const typed = normalizeSchemaField(field)
return normalizeAuthSchemaField(typed, table.schema.type)
}) ?? table.schema.fields,
}
// Older auth entities may omit `auth`; treat as password-only login.
if (schema.type === "auth") {
schema.auth = normalizeAuthMethods(schema.auth)
}
return {
...table,
schema,
}
}
export function buildFieldPatchPayload(field: TableField): Record<string, unknown> {
const normalized = normalizeSchemaField(field)
const fieldData: Record<string, unknown> = {
id: field.id,
name: field.name,
type: normalized.type,
primary_key: field.primary_key,
required: field.required,
system: field.system ?? false,
unique: field.unique ?? false,
constraints: field.constraints ?? {
default_value: null,
max_value: null,
min_value: null,
validator: null,
},
}
appendPrecisionToFieldPayload(fieldData, normalized)
if (field.foreign_key?.entity && field.foreign_key?.field) {
fieldData.foreign_key = field.foreign_key
}
return fieldData
}
export async function migrateSchemaFieldsIfNeeded(
apiClient: ApiClient,
table: TableMetadata,
): Promise<TableMetadata | null> {
const fields = table.schema?.fields ?? []
if (!schemaFieldsNeedMigration(fields)) {
return null
}
const updatedTable = await apiClient.call<TableMetadata>(`/api/v1/schemas/${table.schema.name}`, {
method: "PATCH",
body: JSON.stringify({
fields: fields.map(buildFieldPatchPayload),
}),
})
if ((updatedTable as { error?: unknown[] })?.error?.length) {
throw (updatedTable as { error: unknown[] }).error
}
return normalizeTableSchema(updatedTable)
}
/**
* Normalize schemas in memory and persist legacy field-type migrations to the backend.
*/
export async function applySchemaListMigration(
apiClient: ApiClient,
tables: TableMetadata[],
onTableMigrated?: (table: TableMetadata) => void,
): Promise<TableMetadata[]> {
let result = tables.map(normalizeTableSchema)
for (const table of tables) {
if (!schemaFieldsNeedMigration(table.schema?.fields ?? [])) {
continue
}
try {
const migrated = await migrateSchemaFieldsIfNeeded(apiClient, table)
if (migrated) {
result = result.map((entry) => (entry.id === migrated.id ? migrated : entry))
onTableMigrated?.(migrated)
}
} catch (error) {
console.error(`Failed to migrate schema "${table.schema.name}":`, error)
}
}
return result
}

BIN
mantisbase-admin.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 511 KiB

View File

@@ -4,6 +4,12 @@ const { version } = require('./package.json');
/** @type {import('next').NextConfig} */
const nextConfig = {
// 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,
},
@@ -16,10 +22,25 @@ const nextConfig = {
images: {
unoptimized: true,
},
output: 'export',
trailingSlash: true, // ensures `/admin/index.html` works
basePath: '/admin',
assetPrefix: '/admin',
// Only use static export in production builds, not in development
// This allows dynamic routes to work in development
...(process.env.NODE_ENV === 'production' && { output: 'export' }),
trailingSlash: true,
async rewrites() {
if (process.env.NODE_ENV === 'production') {
return []
}
const port = process.env.MANTIS_PORT || '7070'
const target = (process.env.MANTIS_PROXY_URL || `http://127.0.0.1:${port}`).replace(/\/+$/, '')
return [
{
source: '/api/:path*',
destination: `${target}/api/:path*`,
},
]
},
}

2521
openapi.yaml Normal file

File diff suppressed because it is too large Load Diff

50
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "mantis-admin",
"version": "0.1.2",
"name": "mantisbase-admin",
"version": "0.4.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "mantis-admin",
"version": "0.1.2",
"name": "mantisbase-admin",
"version": "0.4.3",
"dependencies": {
"@hookform/resolvers": "^3.9.1",
"@radix-ui/react-accordion": "1.2.2",
@@ -51,6 +51,7 @@
"react-dom": "^18.2",
"react-hook-form": "^7.54.1",
"react-resizable-panels": "^2.1.7",
"react-router-dom": "^6.30.4",
"recharts": "2.15.0",
"sonner": "^1.7.1",
"tailwind-merge": "^2.5.5",
@@ -3031,6 +3032,15 @@
"integrity": "sha512-A9+lCBZoaMJlVKcRBz2YByCG+Cp2t6nAnMnNba+XiWxnj6r4JUFqfsgwocMBZU9LPtdxC6wB56ySYpc7LQIoJg==",
"license": "MIT"
},
"node_modules/@remix-run/router": {
"version": "1.23.3",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.3.tgz",
"integrity": "sha512-4An71tdz9X8+3sI4Qqqd2LWd9vS39J7sqd9EU4Scw7TJE/qB10Flv/UuqbPVgfQV9XoK8Np6jNquZitnZq5i+Q==",
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/@swc/counter": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz",
@@ -4648,6 +4658,38 @@
"react-dom": "^16.14.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"
}
},
"node_modules/react-router": {
"version": "6.30.4",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.4.tgz",
"integrity": "sha512-SVUsDe+DybHM/WmYKIVYhZh1o5Dcuf16yM6WjG02Q9XVFMZIJyHYhwrr6bFBXZkVP6z69kNkMyBCujt8FaFLJA==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.3"
},
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"react": ">=16.8"
}
},
"node_modules/react-router-dom": {
"version": "6.30.4",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.4.tgz",
"integrity": "sha512-q4HvNl+mmDdkS0g+MqiBZNteQJCuimWoOyHMy4T/RQLAn9Z29+E91QXRaxOujeMl2HTzRSS0KFPd7lxX3PjV0Q==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.3",
"react-router": "6.30.4"
},
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"react": ">=16.8",
"react-dom": ">=16.8"
}
},
"node_modules/react-smooth": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.4.tgz",

View File

@@ -1,6 +1,6 @@
{
"name": "mantis-admin",
"version": "0.1.5",
"name": "mantisbase-admin",
"version": "0.4.3",
"private": true,
"scripts": {
"export": "next build && next export",
@@ -53,6 +53,7 @@
"react-dom": "^18.2",
"react-hook-form": "^7.54.1",
"react-resizable-panels": "^2.1.7",
"react-router-dom": "^6.30.4",
"recharts": "2.15.0",
"sonner": "^1.7.1",
"tailwind-merge": "^2.5.5",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 182 KiB

After

Width:  |  Height:  |  Size: 183 KiB

51
public/mantisbase.svg Normal file
View 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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 123 KiB