Downgraded to React 18.2, dropped mock data for API calls

This commit is contained in:
2025-06-26 23:32:55 +03:00
parent 0934eda5de
commit 8d4910cdd9
8 changed files with 5601 additions and 4297 deletions

View File

@@ -99,23 +99,23 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
setLoading(true) setLoading(true)
console.log("Loading dashboard data...") console.log("Loading dashboard data...")
const [tablesData, adminsData, settingsData] = await Promise.all([ const [tablesData, adminsData/*, settingsData*/] = await Promise.all([
apiClient.call<TableMetadata[]>("/api/v1/tables"), apiClient.call<TableMetadata[]>("/api/v1/tables"),
apiClient.call<Admin[]>("/api/v1/admins"), apiClient.call<Admin[]>("/api/v1/admins"),
apiClient.call<AppSettings>("/api/v1/settings"), // apiClient.call<AppSettings>("/api/v1/settings"),
]) ])
console.log("Data loaded:", { tablesData, adminsData, settingsData }) console.log("Data loaded:", { tablesData, adminsData/*, settingsData */})
setTables(tablesData) setTables(tablesData)
setAdmins(adminsData) setAdmins(adminsData)
setSettings(settingsData) // setSettings(settingsData)
} catch (error) { } catch (error) {
console.error("Failed to load data:", error) console.error("Failed to load data:", error)
// Set default settings if loading fails // Set default settings if loading fails
setSettings({ setSettings({
appName: "Mantis Admin", appName: "Mantis Admin",
baseUrl: "https://api.example.com", baseUrl: "http://127.0.0.1:7070",
version: "1.2.3", version: "1.2.3",
maintenanceMode: false, maintenanceMode: false,
maxFileSize: "10MB", maxFileSize: "10MB",

View File

@@ -1,3 +1,4 @@
/** @jsxImportSource react */
"use client" "use client"
import * as React from "react" import * as React from "react"
@@ -65,19 +66,39 @@ ToastAction.displayName = ToastPrimitives.Action.displayName
const ToastClose = React.forwardRef< const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>, React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close> React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => ( >(function ToastClose({ className, ...props }, ref) {
<ToastPrimitives.Close return (
ref={ref} <ToastPrimitives.Close
className={cn( ref={ref}
"absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600", className={cn(
className, "absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
)} className,
toast-close="" )}
{...props} toast-close=""
> {...props}
<X className="h-4 w-4" /> >
</ToastClose> <X className="h-4 w-4" />
)) </ToastPrimitives.Close>
)
})
// const ToastClose = React.forwardRef<
// React.ElementRef<typeof ToastPrimitives.Close>,
// React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
// >(({ className, ...props }, ref) => (
// <ToastPrimitives.Close
// ref={ref}
// className={cn(
// "absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
// className,
// )}
// toast-close=""
// {...props}
// >
// <X className="h-4 w-4" />
// </ToastClose>
// ))
ToastClose.displayName = ToastPrimitives.Close.displayName ToastClose.displayName = ToastPrimitives.Close.displayName
const ToastTitle = React.forwardRef< const ToastTitle = React.forwardRef<

View File

@@ -61,258 +61,17 @@ export interface AppSettings {
mode: AppMode mode: AppMode
} }
// Mock data updated to match new format // const mockSettings = {
const mockTables: TableMetadata[] = [ // appName: "Mantis Admin",
{ // baseUrl: "https://api.example.com",
created: "2025-06-21 22:04:15", // version: "1.2.3",
has_api: true, // maintenanceMode: false,
id: "mt_11699830787864871553", // maxFileSize: "10MB",
name: "users", // allowRegistration: true,
schema: { // emailVerificationRequired: false,
addRule: "", // sessionTimeout: 3600,
deleteRule: "", // mode: "TEST" as AppMode,
fields: [ // }
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: null,
name: "id",
primaryKey: true,
required: true,
system: true,
type: "string",
unique: false,
validator: null,
},
{
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,
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: 5.0,
name: "email",
primaryKey: false,
required: true,
system: true,
type: "string",
unique: true,
validator: "email",
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: 8.0,
name: "password",
primaryKey: false,
required: true,
system: true,
type: "string",
unique: false,
validator: "password",
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: 2.0,
name: "name",
primaryKey: false,
required: true,
system: true,
type: "string",
unique: false,
validator: null,
},
],
getRule: "",
has_api: true,
id: "mt_11699830787864871553",
listRule: "",
name: "users",
system: false,
type: "auth",
updateRule: "",
},
type: "auth",
updated: "2025-06-21 22:04:15",
},
{
created: "2025-06-20 10:00:00",
has_api: true,
id: "mt_22699830787864871554",
name: "products",
schema: {
addRule: "auth.id != None",
deleteRule: "auth.role == 'admin'",
fields: [
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: null,
name: "id",
primaryKey: true,
required: true,
system: true,
type: "string",
unique: false,
validator: null,
},
{
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,
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: 1.0,
name: "name",
primaryKey: false,
required: true,
system: false,
type: "string",
unique: false,
validator: null,
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: 999999.0,
minValue: 0.0,
name: "price",
primaryKey: false,
required: true,
system: false,
type: "float64",
unique: false,
validator: null,
},
{
autoGeneratePattern: null,
defaultValue: null,
maxValue: null,
minValue: null,
name: "category",
primaryKey: false,
required: false,
system: false,
type: "string",
unique: false,
validator: null,
},
],
getRule: "True",
has_api: true,
id: "mt_22699830787864871554",
listRule: "True",
name: "products",
system: false,
type: "base",
updateRule: "auth.id != None",
},
type: "base",
updated: "2025-06-20 10:00:00",
},
{
created: "2025-06-19 15:30:00",
has_api: true,
id: "mt_33699830787864871555",
name: "active_users_view",
schema: {
addRule: "",
deleteRule: "",
fields: [],
getRule: "auth.role == 'admin'",
has_api: true,
id: "mt_33699830787864871555",
listRule: "auth.role == 'admin'",
name: "active_users_view",
system: false,
type: "view",
updateRule: "",
sql: "SELECT id, email, created FROM users WHERE updated > NOW() - INTERVAL 30 DAY",
},
type: "view",
updated: "2025-06-19 15:30:00",
},
]
const mockAdmins = [
{
id: "1",
email: "admin@example.com",
created: "2024-01-01T10:00:00Z",
updated: "2024-01-01T10:00:00Z",
},
{
id: "2",
email: "john.admin@example.com",
created: "2024-01-15T10:00:00Z",
updated: "2024-01-15T10:00:00Z",
},
]
const mockSettings = {
appName: "Mantis Admin",
baseUrl: "https://api.example.com",
version: "1.2.3",
maintenanceMode: false,
maxFileSize: "10MB",
allowRegistration: true,
emailVerificationRequired: false,
sessionTimeout: 3600,
mode: "TEST" as AppMode,
}
// API Response interface // API Response interface
interface ApiResponse<T> { interface ApiResponse<T> {
@@ -321,9 +80,6 @@ interface ApiResponse<T> {
status: number status: number
} }
// Simulate API delay
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
export class ApiClient { export class ApiClient {
private token: string private token: string
private onUnauthorized: () => void private onUnauthorized: () => void
@@ -336,8 +92,8 @@ export class ApiClient {
constructor( constructor(
token: string, token: string,
onUnauthorized: () => void, onUnauthorized: () => void,
mode: AppMode = "TEST", mode: AppMode = "PROD",
baseUrl = "https://api.example.com", baseUrl = "http://127.0.0.1:7070",
onError?: (error: string, type?: "error" | "warning") => void, onError?: (error: string, type?: "error" | "warning") => void,
) { ) {
this.token = token this.token = token
@@ -347,169 +103,6 @@ export class ApiClient {
this.baseUrl = baseUrl this.baseUrl = baseUrl
} }
private async mockApiCall<T>(endpoint: string, options: RequestInit = {}): Promise<ApiResponse<T>> {
// Prevent infinite loops
this.requestCount++
if (this.requestCount > this.maxRequests) {
return {
data: null as T,
error: "Too many API requests - possible infinite loop detected",
status: 500,
}
}
// Reset counter after a delay
setTimeout(() => {
this.requestCount = Math.max(0, this.requestCount - 1)
}, 1000)
// Simulate network delay
await delay(300 + Math.random() * 200)
// Simulate occasional errors for testing (reduced frequency)
if (Math.random() < 0.02) {
return {
data: null as T,
error: "Network error occurred",
status: 500,
}
}
// Simulate 401 for invalid tokens (uncomment to test)
if (Math.random() < 0.01) {
return {
data: null as T,
error: "Unauthorized - Session expired",
status: 403,
}
}
const method = options.method || "GET"
const url = new URL(endpoint, "http://localhost")
// Mock API responses
if (url.pathname === "/api/v1/tables") {
if (method === "GET") {
return { data: mockTables as T, status: 200 }
}
if (method === "POST") {
const body = JSON.parse(options.body as string)
const newTable: TableMetadata = {
id: `mt_${Date.now()}${Math.floor(Math.random() * 1000)}`,
name: body.name,
type: body.type,
has_api: true,
created: new Date().toISOString().replace("T", " ").slice(0, 19),
updated: new Date().toISOString().replace("T", " ").slice(0, 19),
schema: {
id: `mt_${Date.now()}${Math.floor(Math.random() * 1000)}`,
name: body.name,
type: body.type,
system: false,
has_api: true,
fields: body.fields || [],
addRule: body.addRule || "",
deleteRule: body.deleteRule || "",
getRule: body.getRule || "",
listRule: body.listRule || "",
updateRule: body.updateRule || "",
sql: body.sql,
},
}
mockTables.push(newTable)
return { data: newTable as T, status: 201 }
}
}
if (url.pathname.startsWith("/api/v1/tables/")) {
const tableId = url.pathname.split("/").pop()
const tableIndex = mockTables.findIndex((t) => t.id === tableId)
if (method === "PATCH" && tableIndex !== -1) {
const body = JSON.parse(options.body as string)
mockTables[tableIndex] = {
...mockTables[tableIndex],
updated: new Date().toISOString().replace("T", " ").slice(0, 19),
schema: {
...mockTables[tableIndex].schema,
...body,
fields: body.fields || mockTables[tableIndex].schema.fields,
},
}
return { data: mockTables[tableIndex] as T, status: 200 }
}
if (method === "DELETE" && tableIndex !== -1) {
mockTables.splice(tableIndex, 1)
return { data: null as T, status: 204 }
}
}
if (url.pathname === "/api/v1/admins") {
if (method === "GET") {
return { data: mockAdmins as T, status: 200 }
}
}
if (url.pathname.startsWith("/api/v1/admins/")) {
const adminId = url.pathname.split("/").pop()
const adminIndex = mockAdmins.findIndex((a) => a.id === adminId)
if (method === "PATCH" && adminIndex !== -1) {
const body = JSON.parse(options.body as string)
mockAdmins[adminIndex] = {
...mockAdmins[adminIndex],
updated: new Date().toISOString(),
}
return { data: mockAdmins[adminIndex] as T, status: 200 }
}
if (method === "DELETE" && adminIndex !== -1) {
mockAdmins.splice(adminIndex, 1)
return { data: null as T, status: 204 }
}
}
if (url.pathname === "/api/v1/settings") {
if (method === "GET") {
console.log("Returning mock settings:", mockSettings)
return { data: mockSettings as T, status: 200 }
}
if (method === "PATCH") {
const body = JSON.parse(options.body as string)
Object.assign(mockSettings, body)
console.log("Updated mock settings:", mockSettings)
return { data: mockSettings as T, status: 200 }
}
}
if (url.pathname === "/api/v1/admins/auth-with-password") {
if (method === "POST") {
const body = JSON.parse(options.body as string)
if (body.email === "admin@example.com" && body.password === "password") {
return {
data: {
token: "mock-jwt-token-" + Date.now(),
user: mockAdmins[0],
} as T,
status: 200,
}
}
return {
data: null as T,
error: "Invalid credentials",
status: 403,
}
}
}
return {
data: null as T,
error: `Mock API: Unhandled ${method} ${endpoint}`,
status: 404,
}
}
private async realApiCall<T>(endpoint: string, options: RequestInit = {}): Promise<ApiResponse<T>> { private async realApiCall<T>(endpoint: string, options: RequestInit = {}): Promise<ApiResponse<T>> {
try { try {
const url = `${this.baseUrl}${endpoint}` const url = `${this.baseUrl}${endpoint}`
@@ -519,6 +112,8 @@ export class ApiClient {
...options.headers, ...options.headers,
} }
console.log(headers, this.baseUrl)
const response = await fetch(url, { const response = await fetch(url, {
...options, ...options,
headers, headers,
@@ -560,18 +155,14 @@ export class ApiClient {
async call<T>(endpoint: string, options: RequestInit = {}): Promise<T> { async call<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
try { try {
let response: ApiResponse<T> console.log(endpoint)
let response: ApiResponse<T> = await this.realApiCall<T>(endpoint, options)
if (this.mode === "TEST") { console.log(response)
response = await this.mockApiCall<T>(endpoint, options)
} else {
response = await this.realApiCall<T>(endpoint, options)
}
// Handle error responses // Handle error responses
if (response.error || response.status >= 400) { if (response.error || response.status >= 400) {
const error = new Error(response.error || "Request failed") const error = new Error(response.error || "Request failed")
;(error as any).status = response.status ; (error as any).status = response.status
// Handle auth errors specifically // Handle auth errors specifically
if (response.status === 401 || response.status === 403) { if (response.status === 401 || response.status === 403) {
@@ -618,46 +209,31 @@ export class ApiClient {
export async function loginWithPassword( export async function loginWithPassword(
email: string, email: string,
password: string, password: string,
mode: AppMode = "TEST", mode: AppMode = "PROD",
baseUrl = "https://api.example.com", baseUrl = "http://127.0.0.1:7070",
) { ) {
if (mode === "TEST") { // Real API call
// Simulate network delay try {
await delay(500) const response = await fetch(`${baseUrl}/api/v1/admins/auth-with-password`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, password }),
})
// Mock login - in production this would be a real API call const responseData = await response.json()
if (email === "admin@example.com" && password === "password") {
return { if (response.ok) {
token: "mock-jwt-token-" + Date.now(), // Check if response follows our API structure
user: mockAdmins[0], if (responseData.data) {
return responseData.data
} }
return responseData
} else {
throw new Error(responseData.error || responseData.message || "Login failed")
} }
} catch (error: any) {
throw new Error("Invalid credentials") throw new Error(error.message || "Network error occurred")
} else {
// Real API call
try {
const response = await fetch(`${baseUrl}/api/v1/admins/auth-with-password`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, 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")
}
} catch (error: any) {
throw new Error(error.message || "Network error occurred")
}
} }
} }

5511
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "my-v0-project", "name": "mantis-admin",
"version": "0.1.0", "version": "0.1.2",
"private": true, "private": true,
"scripts": { "scripts": {
"build": "next build", "build": "next build",
@@ -41,15 +41,15 @@
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cmdk": "1.0.4", "cmdk": "1.0.4",
"date-fns": "4.1.0", "date-fns": "^2.30.0",
"embla-carousel-react": "8.5.1", "embla-carousel-react": "8.5.1",
"input-otp": "1.4.1", "input-otp": "1.4.1",
"lucide-react": "^0.454.0", "lucide-react": "^0.454.0",
"next": "15.2.4", "next": "^15.3.4",
"next-themes": "latest", "next-themes": "latest",
"react": "^19", "react": "^18.2",
"react-day-picker": "8.10.1", "react-day-picker": "8.10.1",
"react-dom": "^19", "react-dom": "^18.2",
"react-hook-form": "^7.54.1", "react-hook-form": "^7.54.1",
"react-resizable-panels": "^2.1.7", "react-resizable-panels": "^2.1.7",
"recharts": "2.15.0", "recharts": "2.15.0",
@@ -61,10 +61,10 @@
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^22", "@types/node": "^22",
"@types/react": "^19", "@types/react": "^18.2",
"@types/react-dom": "^19", "@types/react-dom": "^18.2",
"postcss": "^8.5", "postcss": "^8.5",
"tailwindcss": "^3.4.17", "tailwindcss": "^3.4.17",
"typescript": "^5" "typescript": "^5"
} }
} }

3805
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -12,6 +12,7 @@
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "preserve", "jsx": "preserve",
"jsxImportSource": "react",
"incremental": true, "incremental": true,
"plugins": [ "plugins": [
{ {