1 Commits

Author SHA1 Message Date
Phearun UM bda862e4d3 menu collaged full view and font size adjustment (#162)
* menu sticky and add font adjustment

* menu sticky and add font adjustment

* ui menu sticky and fontsize adjustment

---------

Co-authored-by: phearun <phearun@whitesand.online>
2025-09-15 13:43:22 +07:00
699 changed files with 3015 additions and 180820 deletions
-10
View File
@@ -1,10 +0,0 @@
.git
server/
**/node_modules
**/dist
**/.next
**/.turbo
**/.cache
**/coverage
**/*.log
@@ -1,59 +0,0 @@
name: Build and Publish Frontend Image
on:
push:
branches: [ "develop", "feature/**" ]
paths:
- 'application/**'
- '.github/workflows/build-frontend-image.yml'
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
env:
IMAGE_NAME: ghcr.io/${{ github.repository_owner }}/checkcle-frontend
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=sha
- name: Build and push
uses: docker/build-push-action@v6
with:
context: application
file: application/Dockerfile
push: true
platforms: linux/amd64,linux/arm64
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
provenance: false
-4
View File
@@ -1,4 +0,0 @@
fileignoreconfig:
- filename: application/package-lock.json
checksum: 3253a06ef27a634ec2b8a8fe9c156288b9fcf57024623c7ddc3d321f2568e498
version: "1.0"
+2 -2
View File
@@ -79,7 +79,7 @@ Click "Fork" on [GitHub](https://github.com/operacle/checkcle) to create your ow
### 2. Clone Your Fork
```bash
git clone https://github.com/yourusername/checkcle.git
git clone --branch develop https://github.com/operacle/checkcle.git
cd checkcle
```
@@ -116,7 +116,7 @@ go run main.go (you do not need to change the .env while it's the localhost conn
Click "Fork" on [GitHub](https://github.com/operacle/Distributed-Regional-Monitoring) to create your own copy.
#### 2. Clone Your Fork
git clone https://github.com/yourusername/Distributed-Regional-Monitoring.git
git clone --branch main https://github.com/operacle/Distributed-Regional-Monitoring.git
cd Distributed-Regional-Monitoring
#### 3. Install Go Service (make sure you have installed the Go Service)
+2 -8
View File
@@ -60,7 +60,7 @@ CheckCle is an Open Source solution for seamless, real-time monitoring of full-s
- Infrastructure Server Monitoring, Supports Linux (🐧 Debian, Ubuntu, CentOS, Red Hat, etc.) and Windows (Beta). And Servers metrics like CPU, RAM, disk usage, and network activity) with an one-line installation angent script.
- Schedule Maintenance & Incident Management
- Operational Status / Public Status Pages
- Notifications via email, Telegram, Discord, Slack, Matrix, and more
- Notifications via email, Telegram, Discord, and Slack
- Reports & Analytics
- Settings Panel (User Management, Data Retention, Multi-language, Themes (Dark & Light Mode), Notification and channels and alert templates).
@@ -151,12 +151,6 @@ If youre a tech company interested in supporting CheckCle, please contact the
height="50"
alt="DigitalOcean Logo" />
</a>
</a>
<a href="https://www.jetbrains.com/">
<img src="https://cdn.checkcle.io/images/sponsor/jetbrains.png"
height="50"
alt="Jetbrains Logo" />
</a>
</div>
---
@@ -185,7 +179,7 @@ Here are some ways you can help improve CheckCle:
- Website: [checkcle.io](https://checkcle.io)
- Documentation: [docs.checkcle.io](https://docs.checkcle.io) | Big thanks to [GitBook](https://github.com/gitbookio) for sponsoring the OSS site plan for CheckCle!
- Chat on Discord: Join our community [@discord](https://discord.gg/xs9gbubGwX)
- Follow us on X: [@asqrm_io](https://x.com/asqrm_io)
- Follow us on X: [@checkcle_oss](https://x.com/checkcle_oss)
## 📜 License
-1
View File
@@ -39,7 +39,6 @@ We support the latest stable release of `checkcle`. Security patches may also be
| Version | Supported |
|---------|-----------|
| `develop` (latest) | ✅ Yes |
| `main` (latest) | ✅ Yes |
| Older versions | ⚠️ Best-effort |
| Pre-release or forks | ❌ No |
-6
View File
@@ -1,6 +0,0 @@
.git
node_modules
dist
.cache
*.log
-18
View File
@@ -1,18 +0,0 @@
# syntax=docker/dockerfile:1.7
FROM node:20-bullseye-slim AS build
WORKDIR /app
ENV npm_config_fund=false \
npm_config_audit=false \
npm_config_progress=false
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --no-audit --fund=false
COPY . .
RUN --mount=type=cache,target=/root/.npm npm run build
FROM nginx:1.27-alpine
RUN rm -rf /usr/share/nginx/html/*
COPY --from=build /app/dist /usr/share/nginx/html
# SPA fallback + asset caching
RUN printf 'server {\n listen 80;\n server_name _;\n root /usr/share/nginx/html;\n index index.html;\n location / { try_files $uri $uri/ /index.html; }\n location ~* \\.(?:js|css|png|jpg|jpeg|gif|svg|ico|woff2?)$ { expires 7d; add_header Cache-Control "public, max-age=604800, immutable"; try_files $uri =404; }\n}\n' > /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx","-g","daemon off;"]
+24 -20
View File
@@ -1,25 +1,29 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CheckCle</title>
<meta name="description" content="An open-source monitoring platform offering real-time insights into server and service health, incident management, and operational transparency." />
<meta name="author" content="Tola Leng" />
<meta property="og:title" content="checkcle-an-open-source" />
<meta property="og:description" content="An open-source monitoring platform offering real-time insights into server and service health, incident management, and operational transparency." />
<meta property="og:type" content="website" />
<meta property="og:image" content="https://pub-4a4062303020445f8f289a2fee84f9e8.r2.dev/images/checkcle-black.png" />
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CheckCle - Dev</title>
<meta name="description"
content="An open-source monitoring platform offering real-time insights into server and service health, incident management, and operational transparency." />
<meta name="author" content="Tola Leng" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@checkcle_oss" />
<meta name="twitter:image" content="https://pub-4a4062303020445f8f289a2fee84f9e8.r2.dev/images/checkcle-black.png" />
</head>
<meta property="og:title" content="checkcle-an-open-source" />
<meta property="og:description"
content="An open-source monitoring platform offering real-time insights into server and service health, incident management, and operational transparency." />
<meta property="og:type" content="website" />
<meta property="og:image" content="https://pub-4a4062303020445f8f289a2fee84f9e8.r2.dev/images/checkcle-black.png" />
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@checkcle_oss" />
<meta name="twitter:image" content="https://pub-4a4062303020445f8f289a2fee84f9e8.r2.dev/images/checkcle-black.png" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+191 -119
View File
File diff suppressed because it is too large Load Diff
+4 -2
View File
@@ -11,6 +11,7 @@
"preview": "vite preview"
},
"dependencies": {
"@headlessui/react": "2.2.7",
"@hookform/resolvers": "^3.9.0",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
@@ -45,12 +46,13 @@
"cmdk": "^1.0.0",
"date-fns": "^3.6.0",
"embla-carousel-react": "^8.3.0",
"framer-motion": "12.23.12",
"input-otp": "^1.2.4",
"jspdf": "^3.0.1",
"jspdf-autotable": "^5.0.2",
"lucide-react": "^0.462.0",
"next-themes": "^0.3.0",
"pocketbase": "^0.26.8",
"pocketbase": "^0.19.0",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
@@ -82,4 +84,4 @@
"typescript-eslint": "^8.0.1",
"vite": "^5.4.1"
}
}
}
@@ -1,11 +1,11 @@
[
{
"id": "pbc_1938176441",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "alert_configurations",
"type": "base",
"fields": [
@@ -380,11 +380,11 @@
},
{
"id": "pbc_2889059272",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "data_settings",
"type": "base",
"fields": [
@@ -478,11 +478,11 @@
},
{
"id": "pbc_285611395",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "dns_data",
"type": "base",
"fields": [
@@ -717,11 +717,11 @@
},
{
"id": "pbc_3168803865",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "docker_metrics",
"type": "base",
"fields": [
@@ -978,11 +978,11 @@
},
{
"id": "pbc_583547467",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "dockers",
"type": "base",
"fields": [
@@ -1249,11 +1249,11 @@
},
{
"id": "pbc_2189087560",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "incidents",
"type": "base",
"fields": [
@@ -1511,11 +1511,11 @@
},
{
"id": "pbc_1738231158",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "maintenance",
"type": "base",
"fields": [
@@ -1741,11 +1741,11 @@
},
{
"id": "pbc_3662317132",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "operational_page",
"type": "base",
"fields": [
@@ -1932,11 +1932,11 @@
},
{
"id": "pbc_1168766540",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "ping_data",
"type": "base",
"fields": [
@@ -2199,11 +2199,11 @@
},
{
"id": "pbc_171698555",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "regional_service",
"type": "base",
"fields": [
@@ -2331,11 +2331,11 @@
},
{
"id": "pbc_1998570700",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "server_metrics",
"type": "base",
"fields": [
@@ -2648,11 +2648,11 @@
},
{
"id": "pbc_1965843930",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "server_notification_templates",
"type": "base",
"fields": [
@@ -2948,11 +2948,11 @@
},
{
"id": "pbc_1464856393",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "server_threshold_templates",
"type": "base",
"fields": [
@@ -3094,11 +3094,11 @@
},
{
"id": "pbc_3738798621",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "servers",
"type": "base",
"fields": [
@@ -3556,11 +3556,11 @@
},
{
"id": "pbc_763794515",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": null,
"viewRule": null,
"createRule": null,
"updateRule": null,
"deleteRule": null,
"name": "service_group",
"type": "base",
"fields": [
@@ -3646,11 +3646,11 @@
},
{
"id": "pbc_1572233440",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "service_notification_templates",
"type": "base",
"fields": [
@@ -3806,11 +3806,11 @@
},
{
"id": "pbc_863811952",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "services",
"type": "base",
"fields": [
@@ -4162,11 +4162,11 @@
},
{
"id": "pbc_3575570325",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "services_metrics",
"type": "base",
"fields": [
@@ -4509,11 +4509,11 @@
},
{
"id": "pbc_1836745630",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "ssl_certificates",
"type": "base",
"fields": [
@@ -4841,11 +4841,11 @@
},
{
"id": "pbc_1753185970",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "ssl_history",
"type": "base",
"fields": [
@@ -5004,11 +5004,11 @@
},
{
"id": "pbc_351174173",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "ssl_notification_templates",
"type": "base",
"fields": [
@@ -5122,11 +5122,11 @@
},
{
"id": "pbc_1636150439",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "status_page_components",
"type": "base",
"fields": [
@@ -5252,11 +5252,11 @@
},
{
"id": "pbc_2331916230",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "tcp_data",
"type": "base",
"fields": [
@@ -5449,11 +5449,11 @@
},
{
"id": "pbc_67962705",
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": "@request.auth.id != \"\"",
"updateRule": "@request.auth.id != \"\"",
"deleteRule": "@request.auth.id != \"\"",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"name": "uptime_data",
"type": "base",
"fields": [
@@ -5658,4 +5658,4 @@
"indexes": [],
"system": false
}
]
]
Binary file not shown.

Before

Width:  |  Height:  |  Size: 250 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

+139 -45
View File
@@ -1,37 +1,40 @@
import React, { useState } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Toaster } from '@/components/ui/sonner';
import React, { useState } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Toaster } from "@/components/ui/sonner";
import { ThemeProvider } from './contexts/ThemeContext';
import { LanguageProvider } from './contexts/LanguageContext';
import { SidebarProvider } from './contexts/SidebarContext';
import { ThemeProvider } from "./contexts/ThemeContext";
import { LanguageProvider } from "./contexts/LanguageContext";
import { SidebarProvider } from "./contexts/SidebarContext";
import Index from './pages/Index';
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import InstanceMonitoring from './pages/InstanceMonitoring';
import ContainerMonitoring from './pages/ContainerMonitoring';
import ServiceDetail from './pages/ServiceDetail';
import SslDomain from './pages/SslDomain';
import ScheduleIncident from './pages/ScheduleIncident';
import OperationalPage from './pages/OperationalPage';
import RegionalMonitoring from './pages/RegionalMonitoring';
import Settings from './pages/Settings';
import Profile from './pages/Profile';
import NotFound from './pages/NotFound';
import PublicStatusPage from './pages/PublicStatusPage';
import { ProtectedRoute } from './components/auth/ProtectedRoute';
import ServerDetail from './pages/ServerDetail';
import Index from "./pages/Index";
import Login from "./pages/Login";
import Dashboard from "./pages/Dashboard";
import InstanceMonitoring from "./pages/InstanceMonitoring";
import ContainerMonitoring from "./pages/ContainerMonitoring";
import ServiceDetail from "./pages/ServiceDetail";
import SslDomain from "./pages/SslDomain";
import ScheduleIncident from "./pages/ScheduleIncident";
import OperationalPage from "./pages/OperationalPage";
import RegionalMonitoring from "./pages/RegionalMonitoring";
import Settings from "./pages/Settings";
import Profile from "./pages/Profile";
import NotFound from "./pages/NotFound";
import PublicStatusPage from "./pages/PublicStatusPage";
import { ProtectedRoute } from "./components/auth/ProtectedRoute";
import ServerDetail from "./pages/ServerDetail";
function App() {
const [queryClient] = useState(() => new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000
}
}
}));
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000,
},
},
})
);
return (
<BrowserRouter>
@@ -43,22 +46,113 @@ function App() {
<Routes>
{/* Public routes */}
<Route path="/public/:slug" element={<PublicStatusPage />} />
{/* Protected routes */}
<Route path="/login" element={<Login />} />
<Route path="/" element={<ProtectedRoute><Index /></ProtectedRoute>} />
<Route path="/dashboard" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
<Route path="/instance-monitoring" element={<ProtectedRoute><InstanceMonitoring /></ProtectedRoute>} />
<Route path="/server-detail/:serverId" element={<ProtectedRoute><ServerDetail /></ProtectedRoute>} />
<Route path="/container-monitoring" element={<ProtectedRoute><ContainerMonitoring /></ProtectedRoute>} />
<Route path="/container-monitoring/:serverId" element={<ProtectedRoute><ContainerMonitoring /></ProtectedRoute>} />
<Route path="/service/:id" element={<ProtectedRoute><ServiceDetail /></ProtectedRoute>} />
<Route path="/ssl-domain" element={<ProtectedRoute><SslDomain /></ProtectedRoute>} />
<Route path="/schedule-incident" element={<ProtectedRoute><ScheduleIncident /></ProtectedRoute>} />
<Route path="/operational-page" element={<ProtectedRoute><OperationalPage /></ProtectedRoute>} />
<Route path="/regional-monitoring" element={<ProtectedRoute><RegionalMonitoring /></ProtectedRoute>} />
<Route path="/settings" element={<ProtectedRoute><Settings /></ProtectedRoute>} />
<Route path="/profile" element={<ProtectedRoute><Profile /></ProtectedRoute>} />
<Route
path="/"
element={
<ProtectedRoute>
<Index />
</ProtectedRoute>
}
/>
<Route
path="/dashboard"
element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
}
/>
<Route
path="/instance-monitoring"
element={
<ProtectedRoute>
<InstanceMonitoring />
</ProtectedRoute>
}
/>
<Route
path="/server-detail/:serverId"
element={
<ProtectedRoute>
<ServerDetail />
</ProtectedRoute>
}
/>
<Route
path="/container-monitoring"
element={
<ProtectedRoute>
<ContainerMonitoring />
</ProtectedRoute>
}
/>
<Route
path="/container-monitoring/:serverId"
element={
<ProtectedRoute>
<ContainerMonitoring />
</ProtectedRoute>
}
/>
<Route
path="/service/:id"
element={
<ProtectedRoute>
<ServiceDetail />
</ProtectedRoute>
}
/>
<Route
path="/ssl-domain"
element={
<ProtectedRoute>
<SslDomain />
</ProtectedRoute>
}
/>
<Route
path="/schedule-incident"
element={
<ProtectedRoute>
<ScheduleIncident />
</ProtectedRoute>
}
/>
<Route
path="/operational-page"
element={
<ProtectedRoute>
<OperationalPage />
</ProtectedRoute>
}
/>
<Route
path="/regional-monitoring"
element={
<ProtectedRoute>
<RegionalMonitoring />
</ProtectedRoute>
}
/>
<Route
path="/settings"
element={
<ProtectedRoute>
<Settings />
</ProtectedRoute>
}
/>
<Route
path="/profile"
element={
<ProtectedRoute>
<Profile />
</ProtectedRoute>
}
/>
<Route path="*" element={<NotFound />} />
</Routes>
</QueryClientProvider>
@@ -69,4 +163,4 @@ function App() {
);
}
export default App;
export default App;
@@ -1,4 +1,3 @@
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Plus } from "lucide-react";
@@ -15,17 +14,24 @@ interface DashboardContentProps {
error: Error | null;
}
export const DashboardContent = ({ services, isLoading, error }: DashboardContentProps) => {
export const DashboardContent = ({
services,
isLoading,
error,
}: DashboardContentProps) => {
const { t } = useLanguage();
const [filter, setFilter] = useState<string>("all");
const [searchTerm, setSearchTerm] = useState<string>("");
const [isAddDialogOpen, setIsAddDialogOpen] = useState<boolean>(false);
// Filter services based on search term and type filter
const filteredServices = services.filter(service => {
const matchesSearch = service.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
(service.url && service.url.toLowerCase().includes(searchTerm.toLowerCase()));
const matchesFilter = filter === 'all' || service.type.toLowerCase() === filter.toLowerCase();
const filteredServices = services.filter((service) => {
const matchesSearch =
service.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
(service.url &&
service.url.toLowerCase().includes(searchTerm.toLowerCase()));
const matchesFilter =
filter === "all" || service.type.toLowerCase() === filter.toLowerCase();
return matchesSearch && matchesFilter;
});
@@ -33,40 +39,42 @@ export const DashboardContent = ({ services, isLoading, error }: DashboardConten
return (
<div className="flex flex-col items-center justify-center h-full gap-4 text-foreground">
<p>Error loading service data.</p>
<Button onClick={() => window.location.reload()}>{t('retry')}</Button>
<Button onClick={() => window.location.reload()}>{t("retry")}</Button>
</div>
);
}
return (
<main className="flex-1 flex flex-col overflow-auto bg-background p-6 pb-0">
<div className="flex flex-col flex-1">
<main className="flex-1 flex flex-col overflow-auto dark:bg-black p-2 shadow pb-0 ">
<div className="flex flex-col flex-1 bg-white dark:bg-black p-4 rounded-xl ">
<div className="flex justify-between items-center mb-6">
<h2 className="text-2xl font-bold text-foreground">{t('overview')}</h2>
<Button
<h2 className="text-2xl font-bold text-foreground">
{t("overview")}
</h2>
<Button
className="text-primary-foreground"
onClick={() => setIsAddDialogOpen(true)}
>
<Plus className="w-4 h-4 mr-2" /> {t('newService')}
<Plus className="w-4 h-4 mr-2" /> {t("newService")}
</Button>
</div>
<StatusCards services={services} />
<ServiceFilters
<ServiceFilters
filter={filter}
setFilter={setFilter}
searchTerm={searchTerm}
setSearchTerm={setSearchTerm}
servicesCount={filteredServices.length}
/>
<div className="flex-1 flex flex-col pb-6">
<ServicesTable services={filteredServices} />
</div>
</div>
<AddServiceDialog
<AddServiceDialog
open={isAddDialogOpen}
onOpenChange={setIsAddDialogOpen}
/>
+276 -111
View File
@@ -1,188 +1,350 @@
import { Button } from "@/components/ui/button";
import { AuthUser } from "@/services/authService";
import { useTheme } from "@/contexts/ThemeContext";
import {
Moon, PanelLeft, PanelLeftClose, Sun, Globe, FileText,
Github, Twitter, MessageSquare, Bell, User, Settings,
LogOut, Menu, X
import {
Moon,
PanelLeft,
PanelLeftClose,
Sun,
Globe,
FileText,
Github,
Twitter,
MessageSquare,
Bell,
User,
Settings,
LogOut,
CaseUpper,
BookA,
CaseSensitive,
CaseLower,
ALargeSmall,
} from "lucide-react";
import { useLanguage } from "@/contexts/LanguageContext";
import {
DropdownMenu, DropdownMenuContent, DropdownMenuItem,
DropdownMenuTrigger, DropdownMenuSeparator
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { useEffect, useState } from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useNavigate } from "react-router-dom";
import { useSystemSettings } from "@/hooks/useSystemSettings";
import { useSidebar } from "@/contexts/SidebarContext";
import { cn } from "@/lib/utils";
import useDynamicFontSize from "@/contexts/FontSizeContext";
interface HeaderProps {
currentUser: AuthUser | null;
onLogout: () => void;
sidebarCollapsed: boolean;
toggleSidebar: () => void;
}
export const Header = ({
currentUser,
onLogout,
sidebarCollapsed,
toggleSidebar,
}: HeaderProps) => {
const { theme, toggleTheme } = useTheme();
const { language, setLanguage, t } = useLanguage();
const { sidebarCollapsed, toggleSidebar, isMobileOpen, toggleMobileMenu } = useSidebar();
const [greeting, setGreeting] = useState<string>("");
const { systemName } = useSystemSettings();
const navigate = useNavigate();
// Set greeting based on time of day
useEffect(() => {
const updateGreeting = () => {
const hour = new Date().getHours();
if (hour >= 5 && hour < 12) setGreeting(t("goodMorning"));
else if (hour >= 12 && hour < 18) setGreeting(t("goodAfternoon"));
else setGreeting(t("goodEvening"));
if (hour >= 5 && hour < 12) {
setGreeting(t("goodMorning"));
} else if (hour >= 12 && hour < 18) {
setGreeting(t("goodAfternoon"));
} else {
setGreeting(t("goodEvening"));
}
};
updateGreeting();
// Update greeting if language changes
// You could add a timer to update the greeting throughout the day
// but that's typically unnecessary since most sessions aren't active across time periods
}, [language, t]);
const avatarUrl = currentUser?.avatar || '';
const openExternalLink = (url: string) => {
window.open(url, '_blank');
};
// Log avatar data for debugging
useEffect(() => {
if (currentUser) {
//console.log("Avatar URL in Header:", currentUser.avatar);
}
}, [currentUser]);
// Prepare avatar URL - ensure it displays correctly if it's a local profile image
let avatarUrl = "";
if (currentUser?.avatar) {
// If it's a relative path from the public folder, make sure it's resolved properly
if (currentUser.avatar.startsWith("/upload/profile/")) {
avatarUrl = currentUser.avatar;
} else {
avatarUrl = currentUser.avatar;
}
console.log("Final avatar URL:", avatarUrl);
}
const [fontSize, setFontSize] = useState(() => {
const savedFontSize = localStorage.getItem("fontSize");
return savedFontSize ? parseInt(savedFontSize, 10) : 14;
});
useDynamicFontSize(fontSize);
return (
<header className="relative bg-background border-b border-border px-4 lg:px-6 flex justify-between items-center h-16 shrink-0 z-30 overflow-hidden">
{/* Grid Pattern Overlay */}
<div className="absolute inset-0 z-0 pointer-events-none opacity-20">
<div
className="w-full h-full"
style={{
backgroundImage: `linear-gradient(${theme === 'dark' ? '#ffffff10' : '#00000010'} 1px, transparent 1px),
linear-gradient(90deg, ${theme === 'dark' ? '#ffffff10' : '#00000010'} 1px, transparent 1px)`,
backgroundSize: '20px 20px'
<header className="relative bg-background border-b border-border px-6 flex justify-between items-center py-[12px] overflow-hidden">
{/* Grid Pattern Overlay - Similar to StatusCards */}
<div className="absolute inset-0 z-0">
<div
className="w-full h-full dark:bg-black"
style={{
backgroundImage: `linear-gradient(${
theme === "dark" ? "#ffffff10" : "#00000010"
} 1px, transparent 1px),
linear-gradient(90deg, ${
theme === "dark" ? "#ffffff10" : "#00000010"
} 1px, transparent 1px)`,
backgroundSize: "20px 20px",
}}
>
<div className="w-full h-full backdrop-blur-[1px]"></div>
</div>
</div>
<div className="flex items-center gap-2 lg:gap-4 z-10">
{/* Mobile Toggle */}
<Button variant="ghost" size="icon" onClick={toggleMobileMenu} className="lg:hidden h-9 w-9">
{isMobileOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
{/* Header Content */}
<div className="flex items-center gap-4 z-10">
<div
className={` p-1 h-8 w-8 -ml-2 rounded bg-gray-600 ${
!sidebarCollapsed ? "hidden" : ""
}`}
>
<img
src="/favicon_sidebar.ico"
alt="CheckCle"
className={`h-6 w-6 `}
/>
</div>
<Button
variant="ghost"
size="icon"
onClick={toggleSidebar}
className="mr-2"
>
{sidebarCollapsed ? (
<PanelLeft className="h-5 w-5" />
) : (
<PanelLeftClose className="h-5 w-5" />
)}
</Button>
{/* Desktop Toggle */}
<Button variant="ghost" size="icon" onClick={toggleSidebar} className="hidden lg:flex h-9 w-9">
{sidebarCollapsed ? <PanelLeft className="h-5 w-5" /> : <PanelLeftClose className="h-5 w-5" />}
</Button>
<div className="flex items-center">
<h1 className="text-sm lg:text-lg font-medium truncate max-w-[150px] lg:max-w-none">
{greeting}, {currentUser?.name || currentUser?.email?.split('@')[0] || 'User'} 👋
<div className="flex items-center space-x-2">
<h1 className="font-medium text-xl">
{greeting},{" "}
{currentUser?.name || currentUser?.email?.split("@")[0] || "User"}{" "}
👋
</h1>
</div>
</div>
<div className="flex items-center space-x-1 lg:space-x-3 z-10">
{/* External Links - Hidden on small screens */}
<div className="hidden md:flex items-center space-x-1 mr-2">
<Button
variant="outline"
size="icon"
className="rounded-full w-8 h-8 border-border"
onClick={() => openExternalLink('https://docs.checkcle.io')}
title={t("documentation")}
>
<FileText className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="icon"
className="rounded-full w-8 h-8 border-border"
onClick={() => openExternalLink('https://github.com/operacle/checkcle')}
title="GitHub"
>
<Github className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="icon"
className="rounded-full w-8 h-8 border-border"
onClick={() => openExternalLink('https://x.com/checkcle_oss')}
title="X (Twitter)"
>
<Twitter className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="icon"
className="rounded-full w-8 h-8 border-border"
onClick={() => openExternalLink('https://discord.gg/xs9gbubGwX')}
title="Discord"
>
<MessageSquare className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="icon"
className="rounded-full w-8 h-8 border-border"
title={t("notifications")}
>
<Bell className="w-4 h-4" />
</Button>
</div>
<Button variant="outline" size="icon" className="rounded-full w-8 h-8 border-border hidden sm:flex" onClick={toggleTheme}>
<div className="flex items-center space-x-4 z-10">
<Button
variant="outline"
size="icon"
className="rounded-full w-8 h-8 border-border"
onClick={toggleTheme}
>
<span className="sr-only">Toggle theme</span>
{theme === 'dark' ? <Sun className="w-4 h-4" /> : <Moon className="w-4 h-4" />}
{theme === "dark" ? (
<Sun className="w-4 h-4" />
) : (
<Moon className="w-4 h-4" />
)}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="icon" className="rounded-full w-8 h-8 border-border">
<Button
variant="outline"
size="icon"
className="rounded-full w-8 h-8 border-border"
>
<span className="sr-only">{t("language")}</span>
<Globe className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40">
<DropdownMenuItem onClick={() => setLanguage("en")} className={language === "en" ? "bg-accent" : ""}>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => setLanguage("en")}
className={language === "en" ? "bg-accent" : ""}
>
{t("english")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setLanguage("km")} className={language === "km" ? "bg-accent" : ""}>
<DropdownMenuItem
onClick={() => setLanguage("km")}
className={language === "km" ? "bg-accent" : ""}
>
{t("khmer")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setLanguage("de")} className={language === "de" ? "bg-accent" : ""}>
{t("german")}
<DropdownMenuItem
onClick={() => setLanguage("de")}
className={language === "de" ? "bg-accent" : ""}
>
{t("Deutsch")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setLanguage("ko")} className={language === "ko" ? "bg-accent" : ""}>
<DropdownMenuItem
onClick={() => setLanguage("ko")}
className={language === "ko" ? "bg-accent" : ""}
>
{t("korean")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setLanguage("ja")} className={language === "ja" ? "bg-accent" : ""}>
<DropdownMenuItem
onClick={() => setLanguage("ja")}
className={language === "ja" ? "bg-accent" : ""}
>
{t("japanese")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setLanguage("zhcn")} className={language === "zhcn" ? "bg-accent" : ""}>
<DropdownMenuItem
onClick={() => setLanguage("zhcn")}
className={language === "zhcn" ? "bg-accent" : ""}
>
{t("simplifiedChinese")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<div className="h-8 w-px bg-border mx-1 hidden sm:block" />
{/* Documentation */}
<Button
variant="outline"
size="icon"
className="rounded-full w-8 h-8 border-border"
onClick={() => window.open("https://docs.checkcle.io", "_blank")}
>
<span className="sr-only">{t("documentation")}</span>
<FileText className="w-4 h-4" />
</Button>
{/* GitHub */}
<Button
variant="outline"
size="icon"
className="rounded-full w-8 h-8 border-border"
onClick={() =>
window.open("https://github.com/operacle/checkcle", "_blank")
}
>
<span className="sr-only">GitHub</span>
<Github className="w-4 h-4" />
</Button>
{/* X (Twitter) */}
<Button
variant="outline"
size="icon"
className="rounded-full w-8 h-8 border-border"
onClick={() => window.open("https://x.com/checkcle_oss)", "_blank")}
>
<span className="sr-only">X (Twitter)</span>
<Twitter className="w-4 h-4" />
</Button>
{/* Discord */}
<Button
variant="outline"
size="icon"
className="rounded-full w-8 h-8 border-border"
onClick={() => window.open("https://discord.gg/xs9gbubGwX", "_blank")}
>
<span className="sr-only">Discord</span>
<MessageSquare className="w-4 h-4" />
</Button>
{/* Notifications */}
<Button
variant="outline"
size="icon"
className="rounded-full w-8 h-8 border-border"
>
<span className="sr-only">{t("notifications")}</span>
<Bell className="w-4 h-4" />
</Button>
{/* Fond Size */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Avatar className="h-8 w-8 cursor-pointer border hover:ring-2 hover:ring-primary/20 transition-all">
{avatarUrl ? <AvatarImage src={avatarUrl} alt="User" /> : <AvatarFallback className="bg-primary/20 text-primary">{currentUser?.name?.[0] || 'U'}</AvatarFallback>}
<Button
variant="outline"
size="icon"
className="rounded-full w-8 h-8 border-border"
>
<span className="sr-only">{t("language")}</span>
<BookA className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => setFontSize((prev) => prev + 1)}
className={`cursor-pointer`}
>
<span className={`text-[15px] font-semibold`}> Aa +</span>
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setFontSize((prev) => prev - 1)}
className={`cursor-pointer`}
>
<span className={`text-[12px] font-semibold`}> Aa -</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{/* User Profile Dropdown */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Avatar className="h-8 w-8 cursor-pointer ring-offset-background transition-colors hover:bg-accent hover:text-accent-foreground">
{avatarUrl ? (
<AvatarImage
src={avatarUrl}
alt={
currentUser?.name ||
currentUser?.email?.split("@")[0] ||
"User"
}
/>
) : (
<AvatarFallback className="bg-primary/20 text-primary">
{currentUser?.name?.[0] || currentUser?.email?.[0] || "U"}
</AvatarFallback>
)}
</Avatar>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<div className="flex items-center gap-3 p-2">
<Avatar className="h-10 w-10">
{avatarUrl ? <AvatarImage src={avatarUrl} alt="User" /> : <AvatarFallback className="bg-primary/20 text-primary">{currentUser?.name?.[0] || 'U'}</AvatarFallback>}
{avatarUrl ? (
<AvatarImage
src={avatarUrl}
alt={
currentUser?.name ||
currentUser?.email?.split("@")[0] ||
"User"
}
/>
) : (
<AvatarFallback className="bg-primary/20 text-primary">
{currentUser?.name?.[0] || currentUser?.email?.[0] || "U"}
</AvatarFallback>
)}
</Avatar>
<div className="flex flex-col space-y-0.5">
<span className="text-sm font-medium truncate">{currentUser?.name || 'User'}</span>
<span className="text-xs text-muted-foreground truncate">{currentUser?.email}</span>
<div className="flex flex-col space-y-1">
<span className="font-medium">
{currentUser?.name || "User"}
</span>
<span className="text-xs text-muted-foreground truncate">
{currentUser?.email}
</span>
</div>
</div>
<DropdownMenuSeparator />
@@ -195,7 +357,10 @@ export const Header = ({
<span>{t("settings")}</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={onLogout} className="text-red-500 focus:text-red-500">
<DropdownMenuItem
onClick={onLogout}
className="text-red-500 focus:text-red-500"
>
<LogOut className="mr-2 h-4 w-4" />
<span>{t("logout")}</span>
</DropdownMenuItem>
@@ -204,4 +369,4 @@ export const Header = ({
</div>
</header>
);
};
};
@@ -1,7 +1,12 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "@/components/ui/select";
import {
Select,
SelectTrigger,
SelectValue,
SelectContent,
SelectItem,
} from "@/components/ui/select";
import { Plus } from "lucide-react";
import { useLanguage } from "@/contexts/LanguageContext";
@@ -13,29 +18,31 @@ interface ServiceFiltersProps {
servicesCount: number;
}
export const ServiceFilters = ({
filter,
setFilter,
searchTerm,
export const ServiceFilters = ({
filter,
setFilter,
searchTerm,
setSearchTerm,
servicesCount
servicesCount,
}: ServiceFiltersProps) => {
const { t } = useLanguage();
return (
<div className="mb-6 flex justify-between items-center">
<div className="mb-6 flex justify-between items-center ">
<div className="flex items-center">
<h3 className="text-xl font-semibold mr-2 text-foreground">{t('currentlyMonitoring')}</h3>
<h3 className="text-xl font-semibold mr-2 text-foreground">
{t("currentlyMonitoring")}
</h3>
<span className="bg-secondary text-secondary-foreground px-2 py-0.5 rounded text-sm">
{servicesCount}
</span>
</div>
<div className="flex space-x-4">
<Select value={filter} onValueChange={setFilter}>
<SelectTrigger className="w-40 bg-card border-border">
<SelectValue placeholder={t('allTypes')} />
<SelectTrigger className="w-40 bg-card border-border dark:bg-gray-800">
<SelectValue placeholder={t("allTypes")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">{t('allTypes')}</SelectItem>
<SelectItem value="all">{t("allTypes")}</SelectItem>
<SelectItem value="HTTP">HTTP</SelectItem>
<SelectItem value="PING">PING</SelectItem>
<SelectItem value="TCP">TCP</SelectItem>
@@ -43,9 +50,9 @@ export const ServiceFilters = ({
</SelectContent>
</Select>
<div className="relative">
<Input
className="w-72 bg-card border-border"
placeholder={t('search')}
<Input
className="w-72 bg-card border-border"
placeholder={t("search")}
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
@@ -3,42 +3,32 @@ import { useTheme } from "@/contexts/ThemeContext";
import { SidebarHeader } from "./sidebar/SidebarHeader";
import { MainNavigation } from "./sidebar/MainNavigation";
import { SettingsPanel } from "./sidebar/SettingsPanel";
import { useSidebar } from "@/contexts/SidebarContext";
import { cn } from "@/lib/utils";
export const Sidebar = () => {
interface SidebarProps {
collapsed: boolean;
}
export const Sidebar = ({ collapsed }: SidebarProps) => {
const { theme } = useTheme();
const { sidebarCollapsed, isMobileOpen, toggleMobileMenu } = useSidebar();
return (
<>
{/* Mobile Overlay */}
{isMobileOpen && (
<div
className="fixed inset-0 bg-black/60 z-40 lg:hidden backdrop-blur-sm transition-opacity animate-in fade-in"
onClick={toggleMobileMenu}
/>
)}
{/* Sidebar Container */}
<aside
className={cn(
"fixed inset-y-0 left-0 z-50 lg:static lg:block transition-all duration-300 ease-in-out border-r flex flex-col h-full",
theme === 'dark' ? 'bg-[#121212] border-[#1e1e1e]' : 'bg-sidebar border-sidebar-border',
// Mobile state
isMobileOpen ? "translate-x-0 w-64" : "-translate-x-full lg:translate-x-0",
// Desktop state (collapsed/expanded)
!isMobileOpen && sidebarCollapsed ? "lg:w-16" : "lg:w-64"
)}
>
<SidebarHeader collapsed={!isMobileOpen && sidebarCollapsed} />
<div className="flex-1 overflow-y-auto overflow-x-hidden custom-scrollbar">
<MainNavigation collapsed={!isMobileOpen && sidebarCollapsed} />
</div>
<SettingsPanel collapsed={!isMobileOpen && sidebarCollapsed} />
</aside>
</>
<div
className={`
${
theme === "dark"
? "bg-black border-[#1e1e1e]"
: "bg-sidebars border-sidebar-border"
}
border-r flex flex-col h-full
${collapsed ? "w-16" : "w-64"}
${collapsed ? "hidden" : ""}`}
>
<SidebarHeader collapsed={collapsed} />
<MainNavigation collapsed={collapsed} />
<SettingsPanel collapsed={collapsed} />
<div className="items-center ml-2 p-2 h-30 border-t ">
Version: latest
</div>
</div>
);
};
};
@@ -1,4 +1,3 @@
import React from "react";
import { MenuItem } from "./MenuItem";
import { mainMenuItems } from "./navigationData";
@@ -7,9 +6,15 @@ interface MainNavigationProps {
collapsed: boolean;
}
export const MainNavigation: React.FC<MainNavigationProps> = ({ collapsed }) => {
export const MainNavigation: React.FC<MainNavigationProps> = ({
collapsed,
}) => {
return (
<nav className="my-2 mx-1 py-1 px-1">
<nav
className={`my-2 mx-1 py-1 px-1 dark:bg-black ${
collapsed ? "hidden" : ""
}`}
>
{mainMenuItems.map((item) => (
<MenuItem
key={item.id}
@@ -24,4 +29,4 @@ export const MainNavigation: React.FC<MainNavigationProps> = ({ collapsed }) =>
))}
</nav>
);
};
};
@@ -3,7 +3,6 @@ import { useLocation, useNavigate } from "react-router-dom";
import { useTheme } from "@/contexts/ThemeContext";
import { useLanguage } from "@/contexts/LanguageContext";
import { LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";
interface MenuItemProps {
id: string;
@@ -16,51 +15,55 @@ interface MenuItemProps {
}
export const MenuItem: React.FC<MenuItemProps> = ({
id,
path,
icon: Icon,
translationKey,
color,
hasNavigation,
collapsed
collapsed,
}) => {
const { theme } = useTheme();
const { t } = useLanguage();
const location = useLocation();
const navigate = useNavigate();
const isActive = path && location.pathname === path;
const handleClick = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
if (hasNavigation && path) {
navigate(path);
navigate(path, { replace: false });
}
};
const isActive = path && location.pathname === path;
const mainIconSize = "h-6 w-6";
return (
<div
className={cn(
"group relative flex items-center mb-1 rounded-lg cursor-pointer transition-all duration-200",
collapsed ? "p-3 justify-center" : "p-2.5 px-4",
isActive
? (theme === 'dark' ? 'bg-zinc-800 text-white' : 'bg-primary/10 text-primary')
: (theme === 'dark' ? 'text-zinc-400 hover:bg-zinc-800/50 hover:text-white' : 'text-zinc-600 hover:bg-zinc-100')
)}
<div
className={`
${collapsed ? "p-3" : "p-2 pl-3"}
mb-1 rounded-lg
${
isActive
? theme === "dark"
? "bg-drak"
: "bg-sidebar-accent "
: `hover:${theme === "dark" ? "bg-gray-800" : "bg-sidebar-accent "}`
}
flex items-center
${collapsed ? "justify-center" : ""}
cursor-pointer
`}
onClick={handleClick}
title={collapsed ? t(translationKey) : ""}
>
<Icon className={cn("h-5 w-5 shrink-0 transition-colors", color, isActive ? "opacity-100" : "opacity-80 group-hover:opacity-100")} />
<Icon className={`${mainIconSize} ${color}`} />
{!collapsed && (
<span className="ml-3 font-medium tracking-wide text-sm truncate">
<span className="ml-2.5 font-medium text-foreground tracking-wide ">
{t(translationKey)}
</span>
)}
{/* Small Indicator for active state */}
{isActive && !collapsed && (
<div className="absolute left-0 w-1 h-6 bg-primary rounded-r-full" />
)}
</div>
);
};
};
@@ -1,10 +1,13 @@
import React, { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useTheme } from "@/contexts/ThemeContext";
import { useLanguage } from "@/contexts/LanguageContext";
import { Settings, ChevronDown } from "lucide-react";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { ScrollArea } from "@/components/ui/scroll-area";
import { settingsMenuItems } from "./navigationData";
@@ -17,19 +20,27 @@ export const SettingsPanel: React.FC<SettingsPanelProps> = ({ collapsed }) => {
const { t } = useLanguage();
const location = useLocation();
const navigate = useNavigate();
const [activeSettingsItem, setActiveSettingsItem] = useState<string | null>("general");
const [settingsPanelOpen, setSettingsPanelOpen] = useState(false);
const [activeSettingsItem, setActiveSettingsItem] = useState<string | null>(
"general"
);
//const [settingsPanelOpen, setSettingsPanelOpen] = useState(false);
const [settingsPanelOpen, setSettingsPanelOpen] = useState(() => {
const savedValue = localStorage.getItem("settingsPanelOpen");
// Check if the saved value exists and is "true"
return savedValue === "true";
});
// Update active settings item based on URL
useEffect(() => {
if (location.pathname === '/settings') {
if (location.pathname === "/settings") {
const params = new URLSearchParams(location.search);
const panel = params.get('panel');
const panel = params.get("panel");
if (panel) {
setActiveSettingsItem(panel);
}
}
}, [location]);
localStorage.setItem("settingsPanelOpen", settingsPanelOpen.toString());
}, [location, settingsPanelOpen]);
const handleSettingsItemClick = (item: string) => {
setActiveSettingsItem(item);
@@ -43,15 +54,27 @@ export const SettingsPanel: React.FC<SettingsPanelProps> = ({ collapsed }) => {
};
const getMenuItemClasses = (isActive: boolean) => {
return `p-2 ${isActive ? theme === 'dark' ? 'bg-[#1a1a1a]' : 'bg-sidebar-accent' : `hover:${theme === 'dark' ? 'bg-[#1a1a1a]' : 'bg-sidebar-accent'}`} rounded-lg flex items-center`;
return `p-2 ${
isActive
? theme === "dark"
? "bg-[#1a1a1a]"
: "bg-sidebar-accent"
: `hover:${theme === "dark" ? "bg-[#1a1a1a]" : "bg-sidebar-accent"}`
} rounded-lg flex items-center `;
};
if (collapsed) {
const mainIconSize = "h-6 w-6";
return (
<div className={`border-t ${theme === 'dark' ? 'border-[#1e1e1e] bg-[#121212]' : 'border-sidebar-border bg-sidebar'} p-4 flex justify-center`}>
<div
onClick={(e) => handleMenuItemClick('/settings', e)}
<div
className={`border-t ${
theme === "dark"
? "border-[#1e1e1e] bg-[#121212]"
: "border-sidebar-border bg-sidebar"
} p-4 flex justify-center ${collapsed ? "hidden" : ""}`}
>
<div
onClick={(e) => handleMenuItemClick("/settings", e)}
className="cursor-pointer"
>
<Settings className={`${mainIconSize} text-purple-400`} />
@@ -61,33 +84,59 @@ export const SettingsPanel: React.FC<SettingsPanelProps> = ({ collapsed }) => {
}
return (
<div className={`flex-1 flex flex-col border-t ${theme === 'dark' ? 'border-[#1e1e1e] bg-[#121212]' : 'border-sidebar-border bg-sidebar'} p-4`}>
<Collapsible open={settingsPanelOpen} onOpenChange={setSettingsPanelOpen} className="w-full flex flex-col flex-1">
<CollapsibleTrigger className={`flex items-center justify-between w-full mb-4 px-2 py-2 rounded-lg ${theme === 'dark' ? 'hover:bg-[#1a1a1a]' : 'hover:bg-sidebar-accent'}`}>
<div
className={`flex-1 flex flex-col border-t ${
theme === "dark"
? "border-[#1e1e1e] bg-black"
: "border-sidebar-border bg-sidebars"
} p-4 ${collapsed ? "hidden" : ""}`}
>
<Collapsible
open={settingsPanelOpen}
onOpenChange={setSettingsPanelOpen}
className="w-full flex flex-col flex-1"
>
<CollapsibleTrigger
className={`flex items-center justify-between w-full mb-4 px-2 py-2 rounded-lg ${
theme === "dark" ? "hover:bg-[#1a1a1a]" : "hover:bg-sidebar-accent"
}`}
>
<div className="flex items-center">
<span className="font-medium tracking-wide">{t("settingPanel")}</span>
<span className="font-medium tracking-wide">
{t("settingPanel")}
</span>
</div>
<div className="flex items-center">
<Settings className="h-4 w-4 mr-1" />
<ChevronDown className={`h-4 w-4 transition-transform duration-200 ${settingsPanelOpen ? 'rotate-180' : ''}`} />
<ChevronDown
className={`h-4 w-4 transition-transform duration-200 ${
settingsPanelOpen ? "rotate-180" : ""
}`}
/>
</div>
</CollapsibleTrigger>
<CollapsibleContent className={`${theme === 'dark' ? 'bg-[#121212]' : 'bg-sidebar'} flex-1 flex flex-col`}>
<CollapsibleContent
className={`${
theme === "dark" ? "bg-black" : "bg-sidebars"
} flex-1 flex flex-col`}
>
<div className="max-h-[300px] overflow-y-auto custom-scrollbar relative pr-1">
<ScrollArea className="h-full">
<div className="space-y-2 pr-4">
<div className="space-y-2 pr-4 cursor-pointer">
{settingsMenuItems.map((item) => (
<div
<div
key={item.id}
className={getMenuItemClasses(activeSettingsItem === item.id)}
className={getMenuItemClasses(
activeSettingsItem === item.id
)}
onClick={(e) => {
handleMenuItemClick(`/settings?panel=${item.id}`, e);
handleSettingsItemClick(item.id);
}}
>
<item.icon className="h-4 w-4 mr-2" />
<span className="text-sm">{t(item.translationKey)}</span>
<span className="text-base">{t(item.translationKey)}</span>
</div>
))}
</div>
@@ -97,4 +146,4 @@ export const SettingsPanel: React.FC<SettingsPanelProps> = ({ collapsed }) => {
</Collapsible>
</div>
);
};
};
@@ -1,4 +1,3 @@
import React from "react";
import { useTheme } from "@/contexts/ThemeContext";
@@ -10,15 +9,17 @@ export const SidebarHeader: React.FC<SidebarHeaderProps> = ({ collapsed }) => {
const { theme } = useTheme();
return (
<div className={`p-4 ${theme === 'dark' ? 'border-[#1e1e1e]' : 'border-sidebar-border'} border-b flex items-center ${collapsed ? 'justify-center' : ''}`}>
<div className="h-8 w-8 bg-gray-600 rounded flex items-center justify-center mr-2">
<img
src="/favicon_sidebar.ico"
alt="CheckCle"
className="h-6 w-6"
/>
<div
className={`p-[15.7px] ${
theme === "dark"
? "border-[#1e1e1e] bg-black"
: "border-sidebar-border bg-white"
} border-b flex items-center ${collapsed ? "justify-center" : ""}`}
>
<div className="h-8 w-8 rounded flex items-center justify-center mr-2 dark:bg-drak">
<img src="/favicon_sidebar.ico" alt="CheckCle" className="h-7 w-6" />
</div>
{!collapsed && <h1 className="text-xl font-semibold">CheckCle App</h1>}
</div>
);
};
};
@@ -4,7 +4,6 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody } from "@/components/ui/table";
import { DockerContainer } from "@/types/docker.types";
import { DockerMetricsDialog } from "./DockerMetricsDialog";
import { useLanguage } from "@/contexts/LanguageContext";
import {
DockerTableSearch,
DockerTableHeader,
@@ -19,7 +18,6 @@ interface DockerContainersTableProps {
}
export const DockerContainersTable = ({ containers, isLoading, onRefresh }: DockerContainersTableProps) => {
const { t } = useLanguage();
const [searchTerm, setSearchTerm] = useState("");
const [selectedContainer, setSelectedContainer] = useState<DockerContainer | null>(null);
const [metricsDialogOpen, setMetricsDialogOpen] = useState(false);
@@ -51,7 +49,7 @@ export const DockerContainersTable = ({ containers, isLoading, onRefresh }: Dock
<CardHeader className="pb-4 px-0">
<div className="flex flex-col gap-4">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<CardTitle className="text-lg sm:text-xl font-semibold">{t('dockerContainers', 'docker')}</CardTitle>
<CardTitle className="text-lg sm:text-xl font-semibold">Docker Containers</CardTitle>
<DockerTableSearch
searchTerm={searchTerm}
onSearchChange={setSearchTerm}
@@ -10,7 +10,6 @@ import { DockerContainer, DockerMetrics } from "@/types/docker.types";
import { dockerService } from "@/services/dockerService";
import { Loader2, Cpu, HardDrive, Network, MemoryStick } from "lucide-react";
import { useTheme } from "@/contexts/ThemeContext";
import { useLanguage } from "@/contexts/LanguageContext";
interface DockerMetricsDialogProps {
container: DockerContainer | null;
@@ -21,17 +20,16 @@ interface DockerMetricsDialogProps {
type TimeRange = '60m' | '1d' | '7d' | '1m' | '3m';
const timeRangeOptions = [
{ value: '60m' as TimeRange, label: 'minutes60', hours: 1 },
{ value: '1d' as TimeRange, label: 'day1', hours: 24 },
{ value: '7d' as TimeRange, label: 'days7', hours: 24 * 7 },
{ value: '1m' as TimeRange, label: 'month1', hours: 24 * 30 },
{ value: '3m' as TimeRange, label: 'months3', hours: 24 * 90 },
{ value: '60m' as TimeRange, label: '60 minutes', hours: 1 },
{ value: '1d' as TimeRange, label: '1 day', hours: 24 },
{ value: '7d' as TimeRange, label: '7 days', hours: 24 * 7 },
{ value: '1m' as TimeRange, label: '1 month', hours: 24 * 30 },
{ value: '3m' as TimeRange, label: '3 months', hours: 24 * 90 },
];
export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMetricsDialogProps) => {
const [timeRange, setTimeRange] = useState<TimeRange>("1d");
const { theme } = useTheme();
const { t } = useLanguage();
const {
data: metrics = [],
@@ -234,11 +232,11 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<DialogContent className="max-w-7xl max-h-[95vh] overflow-y-auto bg-background text-foreground">
<DialogHeader>
<DialogTitle className="flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="flex items-center gap-2">
<div className="h-8 w-8 rounded bg-primary/10 flex items-center justify-center">
<Cpu className="h-4 w-4 text-primary" />
</div>
{t('containerMetricsTitle', 'docker', { name: container.name })}
Container Metrics: {container.name}
</div>
<div className="flex items-center gap-2">
<Select value={timeRange} onValueChange={(value: TimeRange) => setTimeRange(value)}>
@@ -248,7 +246,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<SelectContent>
{timeRangeOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{t(option.label, 'docker')}
{option.label}
</SelectItem>
))}
</SelectContent>
@@ -256,22 +254,22 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
</div>
</DialogTitle>
<p className="text-sm text-muted-foreground">
{t('dockerId', 'docker')}: {container.docker_id} {container.hostname}
Docker ID: {container.docker_id} {container.hostname}
</p>
</DialogHeader>
{isLoading ? (
<div className="flex items-center justify-center h-96">
<Loader2 className="h-8 w-8 animate-spin" />
<span className="ml-2">{t('loadingMetrics', 'docker')}</span>
<span className="ml-2">Loading metrics...</span>
</div>
) : error ? (
<div className="flex items-center justify-center h-96 text-muted-foreground">
<p>{t('errorLoadingMetrics', 'docker')}: {String((error as any)?.message ?? '')}</p>
<p>Error loading metrics: {error.message}</p>
</div>
) : chartData.length === 0 ? (
<div className="flex items-center justify-center h-96 text-muted-foreground">
<p>{t('noMetricsAvailable', 'docker')}</p>
<p>No metrics data available for this container</p>
</div>
) : (
<>
@@ -279,7 +277,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
{latestMetric && (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
<MetricCard
title={t('cpu', 'docker')}
title="CPU"
used={`${latestMetric.cpuUsage}%`}
total={`${latestMetric.cpuCores} cores`}
free={`${(100 - latestMetric.cpuUsage).toFixed(1)}%`}
@@ -288,7 +286,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
color={chartConfig.cpuUsage.color}
/>
<MetricCard
title={t('memoryTitle', 'docker')}
title="Memory"
used={latestMetric.ramUsed}
total={latestMetric.ramTotal}
free={latestMetric.ramFree}
@@ -297,7 +295,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
color={chartConfig.ramUsagePercent.color}
/>
<MetricCard
title={t('diskTitle', 'docker')}
title="Disk"
used={latestMetric.diskUsed}
total={latestMetric.diskTotal}
free={latestMetric.diskFree}
@@ -306,10 +304,10 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
color={chartConfig.diskUsagePercent.color}
/>
<MetricCard
title={t('network', 'docker')}
title="Network"
used={`RX: ${latestMetric.networkRx}`}
total={`TX: ${latestMetric.networkTx}`}
free={`${t('networkSpeedKbs', 'docker').replace('(KB/s)', '')}: ${latestMetric.networkRxSpeed} KB/s`}
free={`Speed: ${latestMetric.networkRxSpeed} KB/s`}
percentage={0}
icon={Network}
color={chartConfig.networkRx.color}
@@ -321,19 +319,19 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<TabsList className="grid w-full grid-cols-4 bg-muted">
<TabsTrigger value="cpu" className="flex items-center gap-2 data-[state=active]:bg-background">
<Cpu className="h-4 w-4" />
{t('cpu', 'docker')}
CPU
</TabsTrigger>
<TabsTrigger value="memory" className="flex items-center gap-2 data-[state=active]:bg-background">
<MemoryStick className="h-4 w-4" />
{t('memoryTitle', 'docker')}
Memory
</TabsTrigger>
<TabsTrigger value="disk" className="flex items-center gap-2 data-[state=active]:bg-background">
<HardDrive className="h-4 w-4" />
{t('diskTitle', 'docker')}
Disk
</TabsTrigger>
<TabsTrigger value="network" className="flex items-center gap-2 data-[state=active]:bg-background">
<Network className="h-4 w-4" />
{t('network', 'docker')}
Network
</TabsTrigger>
</TabsList>
@@ -341,7 +339,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground">{t('cpuUsagePct', 'docker')}</CardTitle>
<CardTitle className="text-foreground">CPU Usage (%)</CardTitle>
</CardHeader>
<CardContent>
<ChartContainer config={chartConfig} className="h-80">
@@ -367,7 +365,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={chartConfig.cpuUsage.color}
strokeWidth={2}
dot={{ r: 3, fill: chartConfig.cpuUsage.color }}
name={t('cpuUsagePct', 'docker')}
name="CPU Usage (%)"
/>
</LineChart>
</ChartContainer>
@@ -376,7 +374,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground">{t('cpuUsageVsAvailable', 'docker')}</CardTitle>
<CardTitle className="text-foreground">CPU Usage vs Available</CardTitle>
</CardHeader>
<CardContent>
<ChartContainer config={chartConfig} className="h-80">
@@ -403,7 +401,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={theme === 'dark' ? "#6b7280" : "#9ca3af"}
fill={theme === 'dark' ? "#6b7280" : "#9ca3af"}
fillOpacity={0.3}
name={t('cpuAvailablePct', 'docker')}
name="CPU Available (%)"
/>
<Area
type="monotone"
@@ -412,7 +410,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={chartConfig.cpuUsage.color}
fill={chartConfig.cpuUsage.color}
fillOpacity={0.6}
name={t('cpuUsagePct', 'docker')}
name="CPU Usage (%)"
/>
</AreaChart>
</ChartContainer>
@@ -425,7 +423,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground">{t('ramUsagePct', 'docker')}</CardTitle>
<CardTitle className="text-foreground">Memory Usage (%)</CardTitle>
</CardHeader>
<CardContent>
<ChartContainer config={chartConfig} className="h-80">
@@ -461,7 +459,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground">{t('memoryUsageBytes', 'docker')}</CardTitle>
<CardTitle className="text-foreground">Memory Usage (Bytes)</CardTitle>
</CardHeader>
<CardContent>
<ChartContainer config={chartConfig} className="h-80">
@@ -481,8 +479,8 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
content={<ChartTooltipContent className="bg-popover border-border" />}
cursor={{ stroke: getGridColor() }}
formatter={(value, name) => [
name === t('usedMemory', 'docker') ? formatBytes(Number(value)) :
name === t('totalMemory', 'docker') ? formatBytes(Number(value)) : value,
name === 'Used Memory' ? formatBytes(Number(value)) :
name === 'Total Memory' ? formatBytes(Number(value)) : value,
name
]}
/>
@@ -493,7 +491,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={theme === 'dark' ? "#6b7280" : "#9ca3af"}
fill={theme === 'dark' ? "#6b7280" : "#9ca3af"}
fillOpacity={0.3}
name={t('totalMemory', 'docker')}
name="Total Memory"
/>
<Area
type="monotone"
@@ -502,7 +500,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={chartConfig.ramUsagePercent.color}
fill={chartConfig.ramUsagePercent.color}
fillOpacity={0.6}
name={t('usedMemory', 'docker')}
name="Used Memory"
/>
</AreaChart>
</ChartContainer>
@@ -515,7 +513,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground">{t('diskUsagePct', 'docker')}</CardTitle>
<CardTitle className="text-foreground">Disk Usage (%)</CardTitle>
</CardHeader>
<CardContent>
<ChartContainer config={chartConfig} className="h-80">
@@ -542,7 +540,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={chartConfig.diskUsagePercent.color}
fill={chartConfig.diskUsagePercent.color}
fillOpacity={0.6}
name={t('diskUsagePct', 'docker')}
name="Disk Usage (%)"
/>
</AreaChart>
</ChartContainer>
@@ -551,7 +549,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground">{t('diskUsageBytes', 'docker')}</CardTitle>
<CardTitle className="text-foreground">Disk Usage (Bytes)</CardTitle>
</CardHeader>
<CardContent>
<ChartContainer config={chartConfig} className="h-80">
@@ -571,8 +569,8 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
content={<ChartTooltipContent className="bg-popover border-border" />}
cursor={{ stroke: getGridColor() }}
formatter={(value, name) => [
name === t('usedDisk', 'docker') ? formatBytes(Number(value)) :
name === t('totalDisk', 'docker') ? formatBytes(Number(value)) : value,
name === 'Used Disk' ? formatBytes(Number(value)) :
name === 'Total Disk' ? formatBytes(Number(value)) : value,
name
]}
/>
@@ -583,7 +581,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={theme === 'dark' ? "#6b7280" : "#9ca3af"}
fill={theme === 'dark' ? "#6b7280" : "#9ca3af"}
fillOpacity={0.3}
name={t('totalDisk', 'docker')}
name="Total Disk"
/>
<Area
type="monotone"
@@ -592,7 +590,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={chartConfig.diskUsagePercent.color}
fill={chartConfig.diskUsagePercent.color}
fillOpacity={0.6}
name={t('usedDisk', 'docker')}
name="Used Disk"
/>
</AreaChart>
</ChartContainer>
@@ -605,7 +603,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground">{t('networkTraffic', 'docker')}</CardTitle>
<CardTitle className="text-foreground">Network Traffic</CardTitle>
</CardHeader>
<CardContent>
<ChartContainer config={chartConfig} className="h-64">
@@ -629,7 +627,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
dataKey="networkRxBytes"
stroke={chartConfig.networkRx.color}
strokeWidth={2}
name={t('rxBytes', 'docker')}
name="RX Bytes"
dot={{ r: 2 }}
/>
<Line
@@ -637,7 +635,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
dataKey="networkTxBytes"
stroke={chartConfig.networkTx.color}
strokeWidth={2}
name={t('txBytes', 'docker')}
name="TX Bytes"
dot={{ r: 2 }}
/>
</LineChart>
@@ -647,7 +645,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground">{t('networkSpeedKbs', 'docker')}</CardTitle>
<CardTitle className="text-foreground">Network Speed (KB/s)</CardTitle>
</CardHeader>
<CardContent>
<ChartContainer config={chartConfig} className="h-64">
@@ -671,7 +669,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
dataKey="networkRxSpeed"
stroke={chartConfig.networkRx.color}
strokeWidth={2}
name={t('rxSpeedKbs', 'docker')}
name="RX Speed (KB/s)"
dot={{ r: 2 }}
/>
<Line
@@ -679,7 +677,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
dataKey="networkTxSpeed"
stroke={chartConfig.networkTx.color}
strokeWidth={2}
name={t('txSpeedKbs', 'docker')}
name="TX Speed (KB/s)"
dot={{ r: 2 }}
/>
</LineChart>
@@ -4,7 +4,6 @@ import { Badge } from "@/components/ui/badge";
import { Container, Play, Square, AlertTriangle } from "lucide-react";
import { DockerStats } from "@/types/docker.types";
import { useTheme } from "@/contexts/ThemeContext";
import { useLanguage } from "@/contexts/LanguageContext";
interface DockerStatsCardsProps {
stats: DockerStats;
@@ -12,11 +11,10 @@ interface DockerStatsCardsProps {
export const DockerStatsCards = ({ stats }: DockerStatsCardsProps) => {
const { theme } = useTheme();
const { t } = useLanguage();
const cards = [
{
title: t('totalContainers', 'docker'),
title: "Total Containers",
value: stats.total,
icon: Container,
color: "text-blue-600",
@@ -25,7 +23,7 @@ export const DockerStatsCards = ({ stats }: DockerStatsCardsProps) => {
: "linear-gradient(135deg, rgba(65, 59, 55, 0.8) 0%, #3b82f6 100%)"
},
{
title: t('running', 'docker'),
title: "Running",
value: stats.running,
icon: Play,
color: "text-green-600",
@@ -34,7 +32,7 @@ export const DockerStatsCards = ({ stats }: DockerStatsCardsProps) => {
: "linear-gradient(135deg, rgba(65, 59, 55, 0.8) 0%, #10b981 100%)"
},
{
title: t('stopped', 'docker'),
title: "Stopped",
value: stats.stopped,
icon: Square,
color: "text-gray-600",
@@ -43,7 +41,7 @@ export const DockerStatsCards = ({ stats }: DockerStatsCardsProps) => {
: "linear-gradient(135deg, rgba(65, 59, 55, 0.8) 0%, #6b7280 100%)"
},
{
title: t('warning', 'docker'),
title: "Warning",
value: stats.warning,
icon: AlertTriangle,
color: "text-amber-600",
@@ -92,7 +90,7 @@ export const DockerStatsCards = ({ stats }: DockerStatsCardsProps) => {
variant="outline"
className="text-xs font-mono font-bold px-2 py-1 rounded-md bg-white/20 backdrop-blur-sm text-white border border-white/30"
>
{t('containersLabel', 'docker')}
Containers
</Badge>
</div>
</CardContent>
@@ -1,38 +1,36 @@
import { Badge } from "@/components/ui/badge";
import { useLanguage } from "@/contexts/LanguageContext";
interface DockerStatusBadgeProps {
status: 'running' | 'stopped' | 'warning';
}
export const DockerStatusBadge = ({ status }: DockerStatusBadgeProps) => {
const { t } = useLanguage();
const getStatusConfig = (status: string) => {
switch (status) {
case 'running':
return {
variant: 'default' as const,
className: 'bg-emerald-100 text-emerald-800 border-emerald-200 hover:bg-emerald-200',
label: t('running', 'docker')
label: 'Running'
};
case 'stopped':
return {
variant: 'secondary' as const,
className: 'bg-gray-100 text-gray-800 border-gray-200 hover:bg-gray-200',
label: t('stopped', 'docker')
label: 'Stopped'
};
case 'warning':
return {
variant: 'destructive' as const,
className: 'bg-amber-100 text-amber-800 border-amber-200 hover:bg-amber-200',
label: t('warning', 'docker')
label: 'Warning'
};
default:
return {
variant: 'outline' as const,
className: 'bg-gray-100 text-gray-600 border-gray-200',
label: t('unknown', 'docker')
label: 'Unknown'
};
}
};
@@ -1,22 +1,20 @@
import { TableCell, TableRow } from "@/components/ui/table";
import { useLanguage } from "@/contexts/LanguageContext";
interface DockerEmptyStateProps {
searchTerm: string;
}
export const DockerEmptyState = ({ searchTerm }: DockerEmptyStateProps) => {
const { t } = useLanguage();
return (
<TableRow>
<TableCell colSpan={8} className="text-center py-12 text-muted-foreground">
<div className="flex flex-col items-center gap-2">
<div className="text-lg font-medium">
{searchTerm ? t('noContainersFound', 'docker') : t('noContainersRunning', 'docker')}
{searchTerm ? "No containers found" : "No containers running"}
</div>
<div className="text-sm">
{searchTerm ? t('tryAdjustSearch', 'docker') : t('startSomeContainers', 'docker')}
{searchTerm ? "Try adjusting your search terms." : "Start some containers to see them here."}
</div>
</div>
</TableCell>
@@ -3,7 +3,6 @@ import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
import { MoreHorizontal, Eye, Play, Pause, Square, Trash2, BarChart3, RefreshCw } from "lucide-react";
import { DockerContainer } from "@/types/docker.types";
import { useLanguage } from "@/contexts/LanguageContext";
interface DockerRowActionsProps {
container: DockerContainer;
@@ -13,12 +12,11 @@ interface DockerRowActionsProps {
}
export const DockerRowActions = ({ container, containerStatus, onContainerAction, onViewMetrics }: DockerRowActionsProps) => {
const { t } = useLanguage();
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0 hover:bg-muted">
<span className="sr-only">{t('openMenu', 'docker')}</span>
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
@@ -28,14 +26,14 @@ export const DockerRowActions = ({ container, containerStatus, onContainerAction
className="cursor-pointer hover:bg-muted"
>
<BarChart3 className="mr-2 h-4 w-4" />
{t('viewMetrics', 'docker')}
View Metrics
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => onContainerAction('view-detail', container.id, container.name)}
className="cursor-pointer hover:bg-muted"
>
<Eye className="mr-2 h-4 w-4" />
{t('viewDetails', 'docker')}
View Details
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -1,20 +1,18 @@
import { TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useLanguage } from "@/contexts/LanguageContext";
export const DockerTableHeader = () => {
const { t } = useLanguage();
return (
<TableHeader>
<TableRow className="border-border bg-muted/30">
<TableHead className="min-w-[200px] font-semibold">{t('container', 'docker')}</TableHead>
<TableHead className="min-w-[100px] font-semibold">{t('status', 'docker')}</TableHead>
<TableHead className="min-w-[140px] font-semibold">{t('cpuUsage', 'docker')}</TableHead>
<TableHead className="min-w-[160px] font-semibold">{t('memory', 'docker')}</TableHead>
<TableHead className="min-w-[160px] font-semibold">{t('disk', 'docker')}</TableHead>
<TableHead className="min-w-[100px] font-semibold">{t('uptime', 'docker')}</TableHead>
<TableHead className="min-w-[160px] font-semibold">{t('lastChecked', 'docker')}</TableHead>
<TableHead className="min-w-[80px] text-center font-semibold">{t('actions', 'docker')}</TableHead>
<TableHead className="min-w-[200px] font-semibold">Container</TableHead>
<TableHead className="min-w-[100px] font-semibold">Status</TableHead>
<TableHead className="min-w-[140px] font-semibold">CPU Usage</TableHead>
<TableHead className="min-w-[160px] font-semibold">Memory</TableHead>
<TableHead className="min-w-[160px] font-semibold">Disk</TableHead>
<TableHead className="min-w-[100px] font-semibold">Uptime</TableHead>
<TableHead className="min-w-[160px] font-semibold">Last Checked</TableHead>
<TableHead className="min-w-[80px] text-center font-semibold">Actions</TableHead>
</TableRow>
</TableHeader>
);
@@ -2,7 +2,6 @@
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Search, RefreshCw } from "lucide-react";
import { useLanguage } from "@/contexts/LanguageContext";
interface DockerTableSearchProps {
searchTerm: string;
@@ -12,13 +11,12 @@ interface DockerTableSearchProps {
}
export const DockerTableSearch = ({ searchTerm, onSearchChange, onRefresh, isLoading }: DockerTableSearchProps) => {
const { t } = useLanguage();
return (
<div className="flex flex-col sm:flex-row gap-3 w-full sm:w-auto">
<div className="relative flex-1 sm:flex-initial">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
<Input
placeholder={t('searchContainersPlaceholder', 'docker')}
placeholder="Search containers..."
value={searchTerm}
onChange={(e) => onSearchChange(e.target.value)}
className="pl-10 sm:w-64 bg-background border-border"
@@ -32,7 +30,7 @@ export const DockerTableSearch = ({ searchTerm, onSearchChange, onRefresh, isLoa
className="w-full sm:w-auto bg-background border-border hover:bg-muted"
>
<RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? 'animate-spin' : ''}`} />
<span className="sm:inline">{t('refresh', 'docker')}</span>
<span className="sm:inline">Refresh</span>
</Button>
</div>
);
@@ -11,7 +11,6 @@ import { Plus, X, Server } from 'lucide-react';
import { StatusPageComponentRecord } from '@/types/statusPageComponents.types';
import { useQuery } from '@tanstack/react-query';
import { serviceService } from '@/services/serviceService';
import { useLanguage } from "@/contexts/LanguageContext";
interface ComponentsSelectorProps {
selectedComponents: Partial<StatusPageComponentRecord>[];
@@ -20,7 +19,6 @@ interface ComponentsSelectorProps {
}
export const ComponentsSelector = ({ selectedComponents, onComponentsChange, onComponentDelete }: ComponentsSelectorProps) => {
const { t } = useLanguage();
const [showAddForm, setShowAddForm] = useState(false);
const [newComponent, setNewComponent] = useState({
name: '',
@@ -73,16 +71,16 @@ export const ComponentsSelector = ({ selectedComponents, onComponentsChange, onC
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Server className="h-5 w-5" />
{t('statusPageComponents')}
Status Page Components
</CardTitle>
<CardDescription>
{t('addMonitoringComponentsDesc')}
Add monitoring components like uptime services, SSL certificates, and incident tracking
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{selectedComponents.length > 0 && (
<div className="space-y-2">
<Label>{t('selectedComponents')}</Label>
<Label>Selected Components</Label>
<div className="space-y-2">
{selectedComponents.map((component, index) => (
<div key={component.id || index} className="flex items-center justify-between p-3 border rounded-lg">
@@ -94,12 +92,12 @@ export const ComponentsSelector = ({ selectedComponents, onComponentsChange, onC
<div className="flex gap-2 mt-1">
{component.service_id && (
<Badge variant="secondary" className="text-xs">
{t('service')}: {services.find(s => s.id === component.service_id)?.name || component.service_id}
Service: {services.find(s => s.id === component.service_id)?.name || component.service_id}
</Badge>
)}
{component.server_id && (
<Badge variant="secondary" className="text-xs">
{t('server')}: {component.server_id}
Server: {component.server_id}
</Badge>
)}
</div>
@@ -124,22 +122,22 @@ export const ComponentsSelector = ({ selectedComponents, onComponentsChange, onC
className="w-full"
>
<Plus className="h-4 w-4 mr-2" />
{t('addComponent')}
Add Component
</Button>
) : (
<div className="border rounded-lg p-4 space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="component-name">{t('componentName')}</Label>
<Label htmlFor="component-name">Component Name</Label>
<Input
id="component-name"
placeholder={t('componentNamePlaceholder')}
placeholder="e.g., Main Website"
value={newComponent.name}
onChange={(e) => setNewComponent({ ...newComponent, name: e.target.value })}
/>
</div>
<div>
<Label htmlFor="display-order">{t('displayOrder')}</Label>
<Label htmlFor="display-order">Display Order</Label>
<Input
id="display-order"
type="number"
@@ -150,10 +148,10 @@ export const ComponentsSelector = ({ selectedComponents, onComponentsChange, onC
</div>
<div>
<Label htmlFor="component-description">{t('descriptionOptional')}</Label>
<Label htmlFor="component-description">Description (Optional)</Label>
<Textarea
id="component-description"
placeholder={t('descriptionPlaceholder')}
placeholder="Brief description of this component"
value={newComponent.description}
onChange={(e) => setNewComponent({ ...newComponent, description: e.target.value })}
/>
@@ -161,10 +159,10 @@ export const ComponentsSelector = ({ selectedComponents, onComponentsChange, onC
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="service-id">{t('uptimeServiceOptional')}</Label>
<Label htmlFor="service-id">Uptime Service (Optional)</Label>
<Select onValueChange={(value) => setNewComponent({ ...newComponent, service_id: value })}>
<SelectTrigger>
<SelectValue placeholder={t('selectUptimeService')} />
<SelectValue placeholder="Select an uptime service" />
</SelectTrigger>
<SelectContent>
{services.map((service) => (
@@ -183,10 +181,10 @@ export const ComponentsSelector = ({ selectedComponents, onComponentsChange, onC
</Select>
</div>
<div>
<Label htmlFor="server-id">{t('serverIdOptional')}</Label>
<Label htmlFor="server-id">Server ID (Optional)</Label>
<Input
id="server-id"
placeholder={t('serverIdPlaceholder')}
placeholder="server_456"
value={newComponent.server_id}
onChange={(e) => setNewComponent({ ...newComponent, server_id: e.target.value })}
/>
@@ -195,10 +193,10 @@ export const ComponentsSelector = ({ selectedComponents, onComponentsChange, onC
<div className="flex gap-2">
<Button onClick={addComponent} disabled={!newComponent.name.trim()}>
{t('addComponent')}
Add Component
</Button>
<Button variant="outline" onClick={() => setShowAddForm(false)}>
{t('cancel')}
Cancel
</Button>
</div>
</div>
@@ -14,7 +14,6 @@ import { useCreateStatusPageComponent } from '@/hooks/useStatusPageComponents';
import { ComponentsSelector } from './ComponentsSelector';
import { Plus } from 'lucide-react';
import { StatusPageComponentRecord } from '@/types/statusPageComponents.types';
import { useLanguage } from "@/contexts/LanguageContext";
const formSchema = z.object({
title: z.string().min(1, 'Title is required'),
@@ -32,7 +31,6 @@ const formSchema = z.object({
type FormData = z.infer<typeof formSchema>;
export const CreateOperationalPageDialog = () => {
const { t } = useLanguage();
const [open, setOpen] = useState(false);
const [selectedComponents, setSelectedComponents] = useState<Partial<StatusPageComponentRecord>[]>([]);
const createMutation = useCreateOperationalPage();
@@ -104,14 +102,14 @@ export const CreateOperationalPageDialog = () => {
<DialogTrigger asChild>
<Button className="gap-2">
<Plus className="h-4 w-4" />
{t('createPage')}
Create Page
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[800px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{t('createOperationalPage')}</DialogTitle>
<DialogTitle>Create Operational Page</DialogTitle>
<DialogDescription>
{t('createOperationalPageDesc')}
Create a new operational status page to monitor your services and components.
</DialogDescription>
</DialogHeader>
@@ -123,9 +121,9 @@ export const CreateOperationalPageDialog = () => {
name="title"
render={({ field }) => (
<FormItem>
<FormLabel>{t('title')}</FormLabel>
<FormLabel>Title</FormLabel>
<FormControl>
<Input placeholder={t('myServiceStatusPlaceholder')} {...field} />
<Input placeholder="My Service Status" {...field} />
</FormControl>
<FormMessage />
</FormItem>
@@ -137,9 +135,9 @@ export const CreateOperationalPageDialog = () => {
name="slug"
render={({ field }) => (
<FormItem>
<FormLabel>{t('slug')}</FormLabel>
<FormLabel>Slug</FormLabel>
<FormControl>
<Input placeholder={t('myServiceStatusSlugPlaceholder')} {...field} />
<Input placeholder="my-service-status" {...field} />
</FormControl>
<FormMessage />
</FormItem>
@@ -152,10 +150,10 @@ export const CreateOperationalPageDialog = () => {
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>{t('description')}</FormLabel>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea
placeholder={t('operationalPageDescriptionPlaceholder')}
placeholder="A brief description of your operational page"
className="min-h-[80px]"
{...field}
/>
@@ -171,17 +169,17 @@ export const CreateOperationalPageDialog = () => {
name="theme"
render={({ field }) => (
<FormItem>
<FormLabel>{t('theme')}</FormLabel>
<FormLabel>Theme</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder={t('selectTheme')} />
<SelectValue placeholder="Select theme" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="default">{t('themeDefault')}</SelectItem>
<SelectItem value="dark">{t('themeDark')}</SelectItem>
<SelectItem value="light">{t('themeLight')}</SelectItem>
<SelectItem value="default">Default</SelectItem>
<SelectItem value="dark">Dark</SelectItem>
<SelectItem value="light">Light</SelectItem>
</SelectContent>
</Select>
<FormMessage />
@@ -194,18 +192,18 @@ export const CreateOperationalPageDialog = () => {
name="status"
render={({ field }) => (
<FormItem>
<FormLabel>{t('initialStatus')}</FormLabel>
<FormLabel>Initial Status</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder={t('selectStatus')} />
<SelectValue placeholder="Select status" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="operational">{t('statusOperational')}</SelectItem>
<SelectItem value="degraded">{t('statusDegraded')}</SelectItem>
<SelectItem value="maintenance">{t('statusMaintenance')}</SelectItem>
<SelectItem value="major_outage">{t('statusMajorOutage')}</SelectItem>
<SelectItem value="operational">Operational</SelectItem>
<SelectItem value="degraded">Degraded Performance</SelectItem>
<SelectItem value="maintenance">Under Maintenance</SelectItem>
<SelectItem value="major_outage">Major Outage</SelectItem>
</SelectContent>
</Select>
<FormMessage />
@@ -220,9 +218,9 @@ export const CreateOperationalPageDialog = () => {
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm">
<div className="space-y-0.5">
<FormLabel>{t('publicPage')}</FormLabel>
<FormLabel>Public Page</FormLabel>
<FormDescription>
{t('makePagePublic')}
Make this page publicly accessible
</FormDescription>
</div>
<FormControl>
@@ -240,12 +238,12 @@ export const CreateOperationalPageDialog = () => {
name="custom_domain"
render={({ field }) => (
<FormItem>
<FormLabel>{t('customDomainOptional')}</FormLabel>
<FormLabel>Custom Domain (Optional)</FormLabel>
<FormControl>
<Input placeholder={t('customDomainPlaceholder')} {...field} />
<Input placeholder="status.yourdomain.com" {...field} />
</FormControl>
<FormDescription>
{t('customDomainDescription')}
Custom domain for your status page
</FormDescription>
<FormMessage />
</FormItem>
@@ -263,13 +261,13 @@ export const CreateOperationalPageDialog = () => {
variant="outline"
onClick={() => setOpen(false)}
>
{t('cancel')}
Cancel
</Button>
<Button
type="submit"
disabled={createMutation.isPending || createComponentMutation.isPending}
>
{createMutation.isPending || createComponentMutation.isPending ? t('creating') : t('createPage')}
{createMutation.isPending || createComponentMutation.isPending ? 'Creating...' : 'Create Page'}
</Button>
</div>
</form>
@@ -14,7 +14,6 @@ import { useCreateStatusPageComponent, useStatusPageComponentsByOperationalId, u
import { ComponentsSelector } from './ComponentsSelector';
import { OperationalPageRecord } from '@/types/operational.types';
import { StatusPageComponentRecord } from '@/types/statusPageComponents.types';
import { useLanguage } from "@/contexts/LanguageContext";
const formSchema = z.object({
title: z.string().min(1, 'Title is required'),
@@ -38,7 +37,6 @@ interface EditOperationalPageDialogProps {
}
export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOperationalPageDialogProps) => {
const { t } = useLanguage();
const [selectedComponents, setSelectedComponents] = useState<Partial<StatusPageComponentRecord>[]>([]);
const [isFormSubmitting, setIsFormSubmitting] = useState(false);
const [componentsLoaded, setComponentsLoaded] = useState(false);
@@ -197,9 +195,9 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[800px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{t('editOperationalPage')}</DialogTitle>
<DialogTitle>Edit Operational Page</DialogTitle>
<DialogDescription>
{t('updateYourOperationalPage')}
Update your operational status page settings and manage components.
</DialogDescription>
</DialogHeader>
@@ -211,9 +209,9 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
name="title"
render={({ field }) => (
<FormItem>
<FormLabel>{t('title')}</FormLabel>
<FormLabel>Title</FormLabel>
<FormControl>
<Input placeholder={t('myServiceStatusPlaceholder')} {...field} />
<Input placeholder="My Service Status" {...field} />
</FormControl>
<FormMessage />
</FormItem>
@@ -225,9 +223,9 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
name="slug"
render={({ field }) => (
<FormItem>
<FormLabel>{t('slug')}</FormLabel>
<FormLabel>Slug</FormLabel>
<FormControl>
<Input placeholder={t('myServiceStatusSlugPlaceholder')} {...field} />
<Input placeholder="my-service-status" {...field} />
</FormControl>
<FormMessage />
</FormItem>
@@ -240,10 +238,10 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>{t('description')}</FormLabel>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea
placeholder={t('operationalPageDescriptionPlaceholder')}
placeholder="A brief description of your operational page"
className="min-h-[80px]"
{...field}
/>
@@ -259,17 +257,17 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
name="theme"
render={({ field }) => (
<FormItem>
<FormLabel>{t('theme')}</FormLabel>
<FormLabel>Theme</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder={t('selectTheme')} />
<SelectValue placeholder="Select theme" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="default">{t('themeDefault')}</SelectItem>
<SelectItem value="dark">{t('themeDark')}</SelectItem>
<SelectItem value="light">{t('themeLight')}</SelectItem>
<SelectItem value="default">Default</SelectItem>
<SelectItem value="dark">Dark</SelectItem>
<SelectItem value="light">Light</SelectItem>
</SelectContent>
</Select>
<FormMessage />
@@ -282,18 +280,18 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
name="status"
render={({ field }) => (
<FormItem>
<FormLabel>{t('status')}</FormLabel>
<FormLabel>Status</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder={t('selectStatus')} />
<SelectValue placeholder="Select status" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="operational">{t('statusOperational')}</SelectItem>
<SelectItem value="degraded">{t('statusDegraded')}</SelectItem>
<SelectItem value="maintenance">{t('statusMaintenance')}</SelectItem>
<SelectItem value="major_outage">{t('statusMajorOutage')}</SelectItem>
<SelectItem value="operational">Operational</SelectItem>
<SelectItem value="degraded">Degraded Performance</SelectItem>
<SelectItem value="maintenance">Under Maintenance</SelectItem>
<SelectItem value="major_outage">Major Outage</SelectItem>
</SelectContent>
</Select>
<FormMessage />
@@ -308,9 +306,9 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm">
<div className="space-y-0.5">
<FormLabel>{t('publicPage')}</FormLabel>
<FormLabel>Public Page</FormLabel>
<FormDescription>
{t('makePagePublic')}
Make this page publicly accessible
</FormDescription>
</div>
<FormControl>
@@ -328,12 +326,12 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
name="custom_domain"
render={({ field }) => (
<FormItem>
<FormLabel>{t('customDomainOptional')}</FormLabel>
<FormLabel>Custom Domain (Optional)</FormLabel>
<FormControl>
<Input placeholder={t('customDomainPlaceholder')} {...field} />
<Input placeholder="status.yourdomain.com" {...field} />
</FormControl>
<FormDescription>
{t('customDomainDescription')}
Custom domain for your status page
</FormDescription>
<FormMessage />
</FormItem>
@@ -352,13 +350,13 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
variant="outline"
onClick={() => onOpenChange(false)}
>
{t('cancel')}
Cancel
</Button>
<Button
type="submit"
disabled={isFormSubmitting || updateMutation.isPending || createComponentMutation.isPending}
>
{isFormSubmitting || updateMutation.isPending || createComponentMutation.isPending ? t('updating') : t('updatePage')}
{isFormSubmitting || updateMutation.isPending || createComponentMutation.isPending ? 'Updating...' : 'Update Page'}
</Button>
</div>
</form>
@@ -6,7 +6,6 @@ import { OperationalPageRecord } from '@/types/operational.types';
import { StatusBadge } from './StatusBadge';
import { Globe, ExternalLink, Eye, Settings, Trash2 } from 'lucide-react';
import { format } from 'date-fns';
import { useLanguage } from "@/contexts/LanguageContext";
interface OperationalPageCardProps {
page: OperationalPageRecord;
@@ -16,8 +15,6 @@ interface OperationalPageCardProps {
}
export const OperationalPageCard = ({ page, onEdit, onView, onDelete }: OperationalPageCardProps) => {
const { t } = useLanguage();
return (
<Card className="hover:shadow-lg transition-shadow duration-200">
<CardHeader className="pb-3">
@@ -35,23 +32,23 @@ export const OperationalPageCard = ({ page, onEdit, onView, onDelete }: Operatio
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<span className="font-medium text-muted-foreground">{t('slug')}:</span>
<span className="font-medium text-muted-foreground">Slug:</span>
<p className="mt-1">{page.slug}</p>
</div>
<div>
<span className="font-medium text-muted-foreground">{t('theme')}:</span>
<span className="font-medium text-muted-foreground">Theme:</span>
<p className="mt-1 capitalize">{page.theme}</p>
</div>
<div>
<span className="font-medium text-muted-foreground">{t('public')}:</span>
<span className="font-medium text-muted-foreground">Public:</span>
<div className="mt-1">
<Badge variant={page.is_public === 'true' ? 'default' : 'secondary'}>
{page.is_public === 'true' ? t('yes') : t('no')}
{page.is_public === 'true' ? 'Yes' : 'No'}
</Badge>
</div>
</div>
<div>
<span className="font-medium text-muted-foreground">{t('updated')}:</span>
<span className="font-medium text-muted-foreground">Updated:</span>
<p className="mt-1">{format(new Date(page.updated), 'MMM dd, yyyy')}</p>
</div>
</div>
@@ -73,7 +70,7 @@ export const OperationalPageCard = ({ page, onEdit, onView, onDelete }: Operatio
className="flex-1"
>
<Eye className="h-4 w-4 mr-2" />
{t('view')}
View
</Button>
)}
{onEdit && (
@@ -84,7 +81,7 @@ export const OperationalPageCard = ({ page, onEdit, onView, onDelete }: Operatio
className="flex-1"
>
<Settings className="h-4 w-4 mr-2" />
{t('edit')}
Edit
</Button>
)}
{onDelete && (
@@ -1,16 +1,17 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useOperationalPages, useDeleteOperationalPage } from '@/hooks/useOperationalPage';
import { CreateOperationalPageDialog } from './CreateOperationalPageDialog';
import { EditOperationalPageDialog } from './EditOperationalPageDialog';
import { OperationalPageCard } from './OperationalPageCard';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { OperationalPageRecord } from '@/types/operational.types';
import { Activity, Plus, RefreshCw } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
import { useLanguage } from "@/contexts/LanguageContext";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import {
useOperationalPages,
useDeleteOperationalPage,
} from "@/hooks/useOperationalPage";
import { CreateOperationalPageDialog } from "./CreateOperationalPageDialog";
import { EditOperationalPageDialog } from "./EditOperationalPageDialog";
import { OperationalPageCard } from "./OperationalPageCard";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { OperationalPageRecord } from "@/types/operational.types";
import { Activity, Plus, RefreshCw } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import {
AlertDialog,
AlertDialogAction,
@@ -20,18 +21,26 @@ import {
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
} from "@/components/ui/alert-dialog";
export const OperationalPageContent = () => {
const { t } = useLanguage();
const navigate = useNavigate();
const { data: pages, isLoading, error, refetch, isRefetching } = useOperationalPages();
const {
data: pages,
isLoading,
error,
refetch,
isRefetching,
} = useOperationalPages();
const deleteMutation = useDeleteOperationalPage();
const [editingPage, setEditingPage] = useState<OperationalPageRecord | null>(null);
const [editingPage, setEditingPage] = useState<OperationalPageRecord | null>(
null
);
const [editDialogOpen, setEditDialogOpen] = useState(false);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [pageToDelete, setPageToDelete] = useState<OperationalPageRecord | null>(null);
const [pageToDelete, setPageToDelete] =
useState<OperationalPageRecord | null>(null);
const handleEdit = (page: OperationalPageRecord) => {
setEditingPage(page);
@@ -40,10 +49,10 @@ export const OperationalPageContent = () => {
const handleView = (page: OperationalPageRecord) => {
if (page.custom_domain) {
window.open(`https://${page.custom_domain}`, '_blank');
window.open(`https://${page.custom_domain}`, "_blank");
} else {
// Navigate to the public status page route using the correct format
window.open(`/public/${page.slug}`, '_blank');
window.open(`/public/${page.slug}`, "_blank");
}
};
@@ -59,7 +68,7 @@ export const OperationalPageContent = () => {
setDeleteDialogOpen(false);
setPageToDelete(null);
} catch (error) {
console.error('Error deleting page:', error);
console.error("Error deleting page:", error);
}
}
};
@@ -71,13 +80,15 @@ export const OperationalPageContent = () => {
<div className="mb-4">
<Activity className="h-12 w-12 text-muted-foreground mx-auto" />
</div>
<h3 className="text-lg font-semibold mb-2">{t('failedToLoadOperationalPages')}</h3>
<h3 className="text-lg font-semibold mb-2">
Failed to load operational pages
</h3>
<p className="text-muted-foreground mb-4">
{t('loadingoperationalPages')}
There was an error loading your operational pages. Please try again.
</p>
<Button onClick={() => refetch()} variant="outline">
<RefreshCw className="h-4 w-4 mr-2" />
{t('tryagain')}
Try Again
</Button>
</div>
</div>
@@ -85,16 +96,18 @@ export const OperationalPageContent = () => {
}
return (
<div className="container mx-auto px-4 py-8">
<div className="w-full container mx-auto px-4 py-8 ">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-8">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-8 ">
<div>
<h1 className="text-3xl font-bold tracking-tight mb-2"> {t('operationalPages')}</h1>
<h1 className="text-3xl font-bold tracking-tight mb-2">
Operational Pages
</h1>
<p className="text-muted-foreground">
{t('describeOperation')}
Manage your public status pages and monitor service health
</p>
</div>
<div className="flex items-center gap-2 mt-4 sm:mt-0">
<Button
variant="outline"
@@ -102,8 +115,10 @@ export const OperationalPageContent = () => {
onClick={() => refetch()}
disabled={isRefetching}
>
<RefreshCw className={`h-4 w-4 mr-2 ${isRefetching ? 'animate-spin' : ''}`} />
{t('refresh')}
<RefreshCw
className={`h-4 w-4 mr-2 ${isRefetching ? "animate-spin" : ""}`}
/>
Refresh
</Button>
<CreateOperationalPageDialog />
</div>
@@ -138,9 +153,12 @@ export const OperationalPageContent = () => {
<div className="mb-4">
<Activity className="h-12 w-12 text-muted-foreground mx-auto" />
</div>
<h3 className="text-lg font-semibold mb-2">{t('noOperationalPagesFound')}</h3>
<h3 className="text-lg font-semibold mb-2">
No operational pages found
</h3>
<p className="text-muted-foreground mb-6">
{t('createYourFirstOperationalPage')}
Create your first operational page to start monitoring your
services and communicate status to your users.
</p>
<CreateOperationalPageDialog />
</CardContent>
@@ -167,15 +185,15 @@ export const OperationalPageContent = () => {
<div className="mt-8 pt-6 border-t">
<div className="flex flex-wrap gap-6 text-sm text-muted-foreground">
<div>
<span className="font-medium">{t('totalPages')}:</span> {pages.length}
<span className="font-medium">Total Pages:</span> {pages.length}
</div>
<div>
<span className="font-medium">{t('totalPages')}:</span>{' '}
{pages.filter(p => p.is_public === 'true').length}
<span className="font-medium">Public Pages:</span>{" "}
{pages.filter((p) => p.is_public === "true").length}
</div>
<div>
<span className="font-medium">{t('operational')}:</span>{' '}
{pages.filter(p => p.status === 'operational').length}
<span className="font-medium">Operational:</span>{" "}
{pages.filter((p) => p.status === "operational").length}
</div>
</div>
</div>
@@ -192,23 +210,25 @@ export const OperationalPageContent = () => {
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('deleteOperationalPage')}</AlertDialogTitle>
<AlertDialogTitle>Delete Operational Page</AlertDialogTitle>
<AlertDialogDescription>
{t('deleteOperationalPageConfirm').replace('{title}', pageToDelete?.title ?? '')}
Are you sure you want to delete "{pageToDelete?.title}"? This
action cannot be undone and will permanently remove the
operational page and all its components.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('cancel')}</AlertDialogCancel>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={confirmDelete}
className="bg-red-600 hover:bg-red-700"
disabled={deleteMutation.isPending}
>
{deleteMutation.isPending ? t('deleting') : t('delete')}
{deleteMutation.isPending ? "Deleting..." : "Delete"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
};
};
@@ -5,7 +5,6 @@ import { format } from 'date-fns';
import { OperationalPageRecord } from '@/types/operational.types';
import { StatusPageComponentRecord } from '@/types/statusPageComponents.types';
import { Service } from '@/types/service.types';
import { useLanguage } from '@/contexts/LanguageContext';
interface CurrentStatusSectionProps {
page: OperationalPageRecord;
@@ -46,18 +45,18 @@ const getActualStatus = (components: StatusPageComponentRecord[], services: Serv
return 'operational';
};
const getStatusMessage = (status: OperationalPageRecord['status'], t: (k: string, m?: string) => string) => {
const getStatusMessage = (status: OperationalPageRecord['status']) => {
switch (status) {
case 'operational':
return t('allOperational', 'public');
return 'All systems are operational';
case 'degraded':
return t('degradedPerformance', 'public');
return 'Some systems are experiencing degraded performance';
case 'maintenance':
return t('underMaintenance', 'public');
return 'Systems are currently under maintenance';
case 'major_outage':
return t('majorOutage', 'public');
return 'We are experiencing a major service outage';
default:
return t('statusUnknown', 'public');
return 'Status unknown';
}
};
@@ -107,7 +106,6 @@ const getStatusBackground = (status: OperationalPageRecord['status']) => {
};
export const CurrentStatusSection = ({ page, components, services }: CurrentStatusSectionProps) => {
const { t } = useLanguage();
const actualStatus = getActualStatus(components, services);
const displayStatus = actualStatus; // Use actual status for real-time accuracy
@@ -116,7 +114,7 @@ export const CurrentStatusSection = ({ page, components, services }: CurrentStat
<CardHeader>
<CardTitle className="flex items-center gap-3 text-card-foreground text-xl">
<Shield className="h-6 w-6" />
{t('systemStatus', 'public')}
System Status
</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
@@ -125,10 +123,10 @@ export const CurrentStatusSection = ({ page, components, services }: CurrentStat
{getStatusIcon(displayStatus)}
<div>
<h3 className={`text-2xl font-bold ${getStatusColor(displayStatus)}`}>
{getStatusMessage(displayStatus, t)}
{getStatusMessage(displayStatus)}
</h3>
<p className="text-sm text-muted-foreground mt-1">
{t('autoUpdatedByHealth', 'public')}
Status automatically updated based on component health
</p>
</div>
</div>
@@ -138,20 +136,20 @@ export const CurrentStatusSection = ({ page, components, services }: CurrentStat
displayStatus === 'maintenance' ? 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200' :
'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
}`}>
{displayStatus === 'operational' ? t('allOperational', 'public') :
displayStatus === 'degraded' ? t('degradedPerformance', 'public') :
displayStatus === 'maintenance' ? t('underMaintenance', 'public') : t('majorOutage', 'public')}
{displayStatus === 'operational' ? 'All Systems Operational' :
displayStatus === 'degraded' ? 'Degraded Performance' :
displayStatus === 'maintenance' ? 'Under Maintenance' : 'Major Outage'}
</div>
</div>
<div className="flex items-center justify-between text-sm text-muted-foreground border-t pt-4">
<div className="flex items-center gap-2">
<Clock className="h-4 w-4" />
<span>{t('lastUpdatedAt', 'public', { time: format(new Date(), 'MMM dd, yyyy HH:mm') })}</span>
<span>Last updated: {format(new Date(), 'MMM dd, yyyy HH:mm')} UTC</span>
</div>
<div className="flex items-center gap-2">
<div className="h-2 w-2 bg-green-500 rounded-full animate-pulse"></div>
<span>{t('liveStatusMonitoring', 'public')}</span>
<span>Live status monitoring</span>
</div>
</div>
</CardContent>
@@ -9,10 +9,8 @@ import { CurrentStatusSection } from './CurrentStatusSection';
import { ComponentsStatusSection } from './ComponentsStatusSection';
import { OverallUptimeSection } from './OverallUptimeSection';
import { PublicStatusPageFooter } from './PublicStatusPageFooter';
import { useLanguage } from '@/contexts/LanguageContext';
export const PublicStatusPage = () => {
const { t } = useLanguage();
const { slug } = useParams<{ slug: string }>();
// console.log('PublicStatusPage - slug from params:', slug);
@@ -61,9 +59,9 @@ export const PublicStatusPage = () => {
<div className="text-center space-y-4">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"></div>
<div className="space-y-2">
<p className="text-lg font-medium text-foreground">{t('loadingStatusPage', 'public')}</p>
<p className="text-sm text-muted-foreground">{t('fetchingRealtimeStatus', 'public')}</p>
<p className="text-xs text-muted-foreground">{t('slugLabel', 'public')}: {slug || 'No slug provided'}</p>
<p className="text-lg font-medium text-foreground">Loading Status Page</p>
<p className="text-sm text-muted-foreground">Fetching real-time system status...</p>
<p className="text-xs text-muted-foreground">Slug: {slug || 'No slug provided'}</p>
</div>
</div>
</div>
@@ -78,19 +76,19 @@ export const PublicStatusPage = () => {
<AlertCircle className="h-8 w-8 text-red-600 dark:text-red-400" />
</div>
<div className="space-y-2">
<h1 className="text-2xl font-bold text-foreground">{t('statusPageNotFound', 'public')}</h1>
<h1 className="text-2xl font-bold text-foreground">Status Page Not Found</h1>
<p className="text-muted-foreground">
{error || t('notFoundDescription', 'public')}
{error || 'The requested status page could not be found or is not publicly accessible.'}
</p>
<p className="text-xs text-muted-foreground">{t('slugLabel', 'public')}: {slug || 'No slug provided'}</p>
<p className="text-xs text-muted-foreground">Slug: {slug || 'No slug provided'}</p>
</div>
<div className="flex gap-3 justify-center">
<Button onClick={() => window.history.back()} variant="outline">
{t('goBack', 'public')}
Go Back
</Button>
<Button onClick={() => window.location.reload()} className="gap-2">
<RefreshCw className="h-4 w-4" />
{t('retry', 'public')}
Retry
</Button>
</div>
</div>
@@ -1,12 +1,15 @@
import React, { useState, useEffect } from "react";
import React, { useState } from "react";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Copy, Download, Terminal, CheckCircle, Zap, Play } from "lucide-react";
import { regionalService } from "@/services/regionalService";
import { InstallCommand } from "@/types/regional.types";
import { useToast } from "@/hooks/use-toast";
import { useLanguage } from "@/contexts/LanguageContext";
import { getCurrentEndpoint } from "@/lib/pocketbase";
import { RegionalAgentConfigForm } from "./RegionalAgentConfigForm";
import { RegionalOneClickTab } from "./RegionalOneClickTab";
import { RegionalManualTab } from "./RegionalManualTab";
interface AddRegionalAgentDialogProps {
open: boolean;
@@ -19,54 +22,30 @@ export const AddRegionalAgentDialog: React.FC<AddRegionalAgentDialogProps> = ({
onOpenChange,
onAgentAdded
}) => {
const { t } = useLanguage();
const { toast } = useToast();
const [activeTab, setActiveTab] = useState("configure");
const [formData, setFormData] = useState({
regionName: "",
agentIp: "",
});
const [agentToken, setAgentToken] = useState("");
const [agentId, setAgentId] = useState("");
const [currentPocketBaseUrl, setCurrentPocketBaseUrl] = useState("");
const [step, setStep] = useState(1);
const [regionName, setRegionName] = useState("");
const [agentIp, setAgentIp] = useState("");
const [installCommand, setInstallCommand] = useState<InstallCommand | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const { toast } = useToast();
// Generate new credentials when dialog opens or after successful creation
const generateNewCredentials = () => {
const newToken = `rgn_${Math.random().toString(36).substring(2, 15)}${Math.random().toString(36).substring(2, 15)}`;
const newAgentId = `regional_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
setAgentToken(newToken);
setAgentId(newAgentId);
};
useEffect(() => {
if (open) {
const endpoint = getCurrentEndpoint();
setCurrentPocketBaseUrl(endpoint);
generateNewCredentials();
}
}, [open]);
const handleSubmit = async (e: React.FormEvent) => {
const handleCreateAgent = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.regionName.trim() || !formData.agentIp.trim()) return;
if (!regionName.trim() || !agentIp.trim()) return;
setIsSubmitting(true);
try {
await new Promise(resolve => setTimeout(resolve, 1000));
toast({
title: t('success'),
description: t('agentCreatedSuccessfully'),
const result = await regionalService.createRegionalService({
region_name: regionName,
agent_ip_address: agentIp,
});
setActiveTab("one-click");
generateNewCredentials();
onAgentAdded();
setInstallCommand(result.installCommand);
setStep(2);
} catch (error) {
toast({
title: t('error'),
description: t('failedToCreateAgent'),
title: "Error",
description: "Failed to create regional agent configuration.",
variant: "destructive",
});
} finally {
@@ -74,65 +53,407 @@ export const AddRegionalAgentDialog: React.FC<AddRegionalAgentDialogProps> = ({
}
};
const handleDialogClose = () => {
setFormData({
regionName: "",
agentIp: "",
const copyToClipboard = async (text: string, description: string = "Content") => {
try {
// Try the modern clipboard API first
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
toast({
title: "Copied!",
description: `${description} copied to clipboard.`,
});
return;
}
// Fallback for older browsers or non-secure contexts (like localhost)
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.left = '-999999px';
textArea.style.top = '-999999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
const successful = document.execCommand('copy');
document.body.removeChild(textArea);
if (successful) {
toast({
title: "Copied!",
description: `${description} copied to clipboard.`,
});
} else {
throw new Error('execCommand failed');
}
} catch (error) {
console.error('Failed to copy to clipboard:', error);
// Show the text in a modal or alert as final fallback
const userAgent = navigator.userAgent.toLowerCase();
const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
let errorMessage = "Failed to copy to clipboard.";
if (isLocalhost) {
errorMessage += " This is common in local development. Please manually copy the text.";
} else if (userAgent.includes('chrome')) {
errorMessage += " Try using HTTPS or enable clipboard permissions.";
}
toast({
title: "Copy failed",
description: errorMessage,
variant: "destructive",
});
// As a last resort, select the text for manual copying
try {
const textarea = document.querySelector('textarea[readonly]') as HTMLTextAreaElement;
if (textarea) {
textarea.select();
textarea.setSelectionRange(0, 99999); // For mobile devices
}
} catch (selectError) {
// console.error('Failed to select text:', selectError);
}
}
};
const downloadScript = () => {
if (!installCommand) return;
const blob = new Blob([installCommand.bash_script], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `install-regional-agent-${installCommand.agent_id}.sh`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
toast({
title: "Downloaded!",
description: "Installation script downloaded successfully.",
});
setActiveTab("configure");
generateNewCredentials();
};
const handleComplete = () => {
onAgentAdded();
setStep(1);
setRegionName("");
setAgentIp("");
setInstallCommand(null);
onOpenChange(false);
};
const resetDialog = () => {
setStep(1);
setRegionName("");
setAgentIp("");
setInstallCommand(null);
};
return (
<Dialog open={open} onOpenChange={handleDialogClose}>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[900px] max-h-[90vh] overflow-auto">
<DialogHeader>
<DialogTitle>{t('addRegionalMonitoringAgent')}</DialogTitle>
<DialogTitle>Add Regional Monitoring Agent</DialogTitle>
<DialogDescription>
{t('deployRegionalMonitoringAgent')}
Deploy a regional monitoring agent with automatic one-click installation.
</DialogDescription>
</DialogHeader>
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger value="configure">{t('configureAgent')}</TabsTrigger>
<TabsTrigger value="one-click">{t('oneClickInstallTab')}</TabsTrigger>
<TabsTrigger value="manual">{t('manualInstallTab')}</TabsTrigger>
</TabsList>
{step === 1 && (
<form onSubmit={handleCreateAgent} className="space-y-6">
<div className="space-y-4">
<div>
<Label htmlFor="regionName">Region Name</Label>
<Input
id="regionName"
placeholder="e.g., us-east-1, europe-west-1, asia-pacific-1"
value={regionName}
onChange={(e) => setRegionName(e.target.value)}
required
/>
</div>
<div>
<Label htmlFor="agentIp">Agent Server IP Address</Label>
<Input
id="agentIp"
placeholder="e.g., 192.168.1.100 or your-server.example.com"
value={agentIp}
onChange={(e) => setAgentIp(e.target.value)}
required
/>
</div>
</div>
<TabsContent value="configure" className="space-y-6">
<RegionalAgentConfigForm
formData={formData}
setFormData={setFormData}
agentId={agentId}
agentToken={agentToken}
currentPocketBaseUrl={currentPocketBaseUrl}
isSubmitting={isSubmitting}
onSubmit={handleSubmit}
/>
</TabsContent>
<div className="flex justify-end space-x-2">
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? "Generating..." : "Generate Installation"}
</Button>
</div>
</form>
)}
<TabsContent value="one-click" className="space-y-6">
<RegionalOneClickTab
agentToken={agentToken}
currentPocketBaseUrl={currentPocketBaseUrl}
formData={formData}
agentId={agentId}
onDialogClose={handleDialogClose}
/>
</TabsContent>
{step === 2 && installCommand && (
<div className="space-y-6">
<div className="text-center space-y-2">
<CheckCircle className="h-12 w-12 text-green-600 mx-auto" />
<h3 className="text-lg font-semibold">Agent Configuration Ready!</h3>
<p className="text-muted-foreground">
One-click installation script generated with automatic configuration.
</p>
</div>
<TabsContent value="manual" className="space-y-6">
<RegionalManualTab
agentToken={agentToken}
currentPocketBaseUrl={currentPocketBaseUrl}
formData={formData}
agentId={agentId}
onDialogClose={handleDialogClose}
/>
</TabsContent>
</Tabs>
<Tabs defaultValue="oneclicK" className="w-full">
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger value="oneclicK">One-Click Install</TabsTrigger>
<TabsTrigger value="details">Agent Details</TabsTrigger>
<TabsTrigger value="manual">Manual Install</TabsTrigger>
</TabsList>
<TabsContent value="oneclicK" className="space-y-4">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Zap className="h-5 w-5 text-yellow-500" />
One-Click Automatic Installation
</CardTitle>
<CardDescription>
Complete installation, configuration, and service startup in one command
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="bg-green-50 border border-green-200 rounded-lg p-4">
<div className="flex items-center gap-2 text-green-800 font-medium mb-2">
<Play className="h-4 w-4" />
What this script does automatically:
</div>
<ul className="text-sm text-green-700 space-y-1 ml-6">
<li> Downloads the latest .deb package</li>
<li> Installs the regional monitoring agent</li>
<li> Creates configuration file with your settings</li>
<li> Starts and enables the service</li>
<li> Runs health checks</li>
</ul>
</div>
<div className="space-y-2">
<Label>Run this command on your target server:</Label>
<div className="relative">
<Textarea
readOnly
value={`# One-click installation command:
curl -fsSL https://raw.githubusercontent.com/operacle/checkcle/refs/heads/main/scripts/install-regional-agent.sh | sudo bash -s -- \\
--region-name="${regionName}" \\
--agent-id="${installCommand.agent_id}" \\
--agent-ip="${agentIp}" \\
--token="${installCommand.token}" \\
--pocketbase-url="${installCommand.api_endpoint}"`}
className="font-mono text-sm min-h-[120px] pr-12"
/>
<Button
size="sm"
variant="outline"
className="absolute top-2 right-2"
onClick={() => copyToClipboard(`curl -fsSL https://raw.githubusercontent.com/operacle/checkcle/refs/heads/main/scripts/install-regional-agent.sh | sudo bash -s -- --region-name="${regionName}" --agent-id="${installCommand.agent_id}" --agent-ip="${agentIp}" --token="${installCommand.token}" --pocketbase-url="${installCommand.api_endpoint}"`, "Installation command")}
>
<Copy className="h-3 w-3" />
</Button>
</div>
</div>
<div className="flex gap-2">
<Button onClick={downloadScript} variant="outline" className="flex-1">
<Download className="mr-2 h-4 w-4" />
Download Complete Script
</Button>
<Button
onClick={() => copyToClipboard(installCommand.bash_script, "Installation script")}
variant="outline"
className="flex-1"
>
<Copy className="mr-2 h-4 w-4" />
Copy Full Script
</Button>
</div>
{/* Local development notice */}
{(window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') && (
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-3">
<p className="text-sm text-yellow-800">
<strong>Local Development Notice:</strong> If clipboard copying fails, this is normal in local development.
You can use the "Download Complete Script" button instead or manually copy the text.
</p>
</div>
)}
</CardContent>
</Card>
</TabsContent>
<TabsContent value="details" className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Generated Agent Configuration</CardTitle>
<CardDescription>
These values will be automatically configured during installation
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
<div className="grid grid-cols-2 gap-4">
<div>
<Label className="text-sm font-medium text-foreground">Agent ID</Label>
<div className="relative">
<Input
value={installCommand.agent_id}
readOnly
className="font-mono text-sm bg-muted/50 border-muted-foreground/20 text-foreground pr-10"
/>
<Button
size="sm"
variant="ghost"
className="absolute right-1 top-1/2 -translate-y-1/2 h-8 w-8 p-0 hover:bg-muted"
onClick={() => copyToClipboard(installCommand.agent_id, "Agent ID")}
>
<Copy className="h-3 w-3" />
</Button>
</div>
</div>
<div>
<Label className="text-sm font-medium text-foreground">Region Name</Label>
<Input
value={regionName}
readOnly
className="font-mono text-sm bg-muted/50 border-muted-foreground/20 text-foreground"
/>
</div>
<div>
<Label className="text-sm font-medium text-foreground">Server IP</Label>
<Input
value={agentIp}
readOnly
className="font-mono text-sm bg-muted/50 border-muted-foreground/20 text-foreground"
/>
</div>
<div>
<Label className="text-sm font-medium text-foreground">API Endpoint</Label>
<Input
value={installCommand.api_endpoint}
readOnly
className="font-mono text-sm bg-muted/50 border-muted-foreground/20 text-foreground"
/>
</div>
</div>
<div>
<Label className="text-sm font-medium text-foreground">Authentication Token</Label>
<div className="relative">
<Input
value={installCommand.token}
readOnly
className="font-mono text-sm bg-muted/50 border-muted-foreground/20 text-foreground pr-10"
/>
<Button
size="sm"
variant="ghost"
className="absolute right-1 top-1/2 -translate-y-1/2 h-8 w-8 p-0 hover:bg-muted"
onClick={() => copyToClipboard(installCommand.token, "Authentication token")}
>
<Copy className="h-3 w-3" />
</Button>
</div>
</div>
<div className="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
<p className="text-sm text-blue-800">
<strong>Configuration file location:</strong> /etc/regional-check-agent/regional-check-agent.env
</p>
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="manual" className="space-y-4">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Terminal className="h-5 w-5" />
Manual Installation Steps
</CardTitle>
<CardDescription>
Step-by-step manual installation process
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-sm space-y-4">
<div className="border-l-4 border-blue-500 pl-4">
<p className="font-medium">Step 1: Download Package</p>
<code className="text-xs bg-muted p-2 rounded block mt-1">
<p className="text-xs text-muted-foreground mt-1"> If youre using the amd64 architecture, please download this package. </p> <br/>
wget https://github.com/operacle/Distributed-Regional-Monitoring/releases/download/V1.0.0/distributed-regional-check-agent_1.0.0_amd64.deb
</code>
<code className="text-xs bg-muted p-2 rounded block mt-1">
<p className="text-xs text-muted-foreground mt-1"> If youre using the arm64 architecture, please download this package. </p> <br/>
wget https://github.com/operacle/Distributed-Regional-Monitoring/releases/download/V1.0.0/distributed-regional-check-agent_1.0.0_arm64.deb
</code>
</div>
<div className="border-l-4 border-blue-500 pl-4">
<p className="font-medium">Step 2: Install Package</p>
<code className="text-xs bg-muted p-2 rounded block mt-1">
sudo dpkg -i distributed-regional-check-agent_1.0.0_amd64.deb<br/>
sudo apt-get install -f
</code>
</div>
<div className="border-l-4 border-blue-500 pl-4">
<p className="font-medium">Step 3: Configure Agent</p>
<code className="text-xs bg-muted p-2 rounded block mt-1">
sudo nano /etc/regional-check-agent/regional-check-agent.env
</code>
<code className="text-xs bg-muted p-2 rounded block mt-1">
Copy sample configuration from https://github.com/operacle/Distributed-Regional-Monitoring/blob/main/packaging/regional-check-agent.conf
</code>
<p className="text-xs text-muted-foreground mt-1">Add the configuration values shown in the Agent Details tab</p>
</div>
<div className="border-l-4 border-blue-500 pl-4">
<p className="font-medium">Step 4: Start Service</p>
<code className="text-xs bg-muted p-2 rounded block mt-1">
sudo systemctl enable regional-check-agent<br/>
sudo systemctl start regional-check-agent
</code>
</div>
<div className="border-l-4 border-green-500 pl-4">
<p className="font-medium">Step 5: Verify Installation</p>
<code className="text-xs bg-muted p-2 rounded block mt-1">
sudo systemctl status regional-check-agent<br/>
curl http://localhost:8091/health
</code>
</div>
</div>
</CardContent>
</Card>
</TabsContent>
</Tabs>
<div className="flex justify-end space-x-2">
<Button variant="outline" onClick={resetDialog}>
Add Another Agent
</Button>
<Button onClick={handleComplete}>
Complete Setup
</Button>
</div>
</div>
)}
</DialogContent>
</Dialog>
);
@@ -8,7 +8,6 @@ import { MapPin, Wifi, WifiOff, MoreVertical, Trash2, Terminal, Copy } from "luc
import { RegionalService } from "@/types/regional.types";
import { formatDistanceToNow } from "date-fns";
import { useToast } from "@/hooks/use-toast";
import { useLanguage } from "@/contexts/LanguageContext";
interface RegionalAgentCardProps {
agent: RegionalService;
@@ -17,7 +16,6 @@ interface RegionalAgentCardProps {
export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onDelete }) => {
const { toast } = useToast();
const { t } = useLanguage();
// Check if this is the default agent that cannot be removed
const isDefaultAgent = agent.agent_id === "1" || agent.region_name === "Default";
@@ -26,13 +24,13 @@ export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onD
try {
await navigator.clipboard.writeText(agent.agent_id);
toast({
title: t('copied'),
description: t('copiedDescription'),
title: "Copied!",
description: "Agent ID copied to clipboard.",
});
} catch (error) {
toast({
title: t('copyFailed'),
description: t('copyFailedDescription'),
title: "Copy failed",
description: "Failed to copy agent ID.",
variant: "destructive",
});
}
@@ -42,14 +40,14 @@ export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onD
if (agent.connection === 'online') {
return {
icon: <Wifi className="h-4 w-4" />,
label: t('online'),
label: 'Online',
variant: 'default' as const,
className: 'bg-green-100 text-green-800 hover:bg-green-100'
};
} else {
return {
icon: <WifiOff className="h-4 w-4" />,
label: t('offline'),
label: 'Offline',
variant: 'secondary' as const,
className: 'bg-red-100 text-red-800 hover:bg-red-100'
};
@@ -69,7 +67,7 @@ export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onD
{agent.region_name}
{isDefaultAgent && (
<Badge variant="outline" className="text-xs bg-blue-50 text-blue-700 border-blue-200">
{t('defaultBadge')}
Default
</Badge>
)}
</CardTitle>
@@ -88,12 +86,12 @@ export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onD
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={copyAgentId}>
<Copy className="mr-2 h-4 w-4" />
{t('copyAgentId')}
Copy Agent ID
</DropdownMenuItem>
{!isDefaultAgent && (
<DropdownMenuItem onClick={onDelete} className="text-red-600">
<Trash2 className="mr-2 h-4 w-4" />
{t('removeAgent')}
Remove Agent
</DropdownMenuItem>
)}
</DropdownMenuContent>
@@ -118,12 +116,12 @@ export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onD
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">{t('agentId')}</span>
<span className="text-muted-foreground">Agent ID:</span>
<span className="font-mono text-xs">{agent.agent_id.substring(0, 12)}...</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">{t('lastUpdated')}</span>
<span className="text-muted-foreground">Last Updated:</span>
<span className="text-xs">
{formatDistanceToNow(new Date(agent.updated), { addSuffix: true })}
</span>
@@ -134,7 +132,7 @@ export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onD
<div className="pt-2 border-t">
<div className="flex items-center text-xs text-green-600">
<div className="w-2 h-2 bg-green-600 rounded-full mr-2 animate-pulse"></div>
{t('activeMonitoring')}
Active monitoring
</div>
</div>
)}
@@ -143,7 +141,7 @@ export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onD
<div className="pt-2 border-t">
<div className="flex items-center text-xs text-red-600">
<div className="w-2 h-2 bg-red-600 rounded-full mr-2"></div>
{t('connectionLost')}
Connection lost
</div>
</div>
)}
@@ -1,128 +0,0 @@
import React from "react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Copy } from "lucide-react";
import { copyToClipboard } from "@/utils/copyUtils";
import { useLanguage } from "@/contexts/LanguageContext";
interface RegionalAgentConfigFormProps {
formData: {
regionName: string;
agentIp: string;
};
setFormData: (data: { regionName: string; agentIp: string }) => void;
agentId: string;
agentToken: string;
currentPocketBaseUrl: string;
isSubmitting: boolean;
onSubmit: (e: React.FormEvent) => void;
}
export const RegionalAgentConfigForm: React.FC<RegionalAgentConfigFormProps> = ({
formData,
setFormData,
agentId,
agentToken,
currentPocketBaseUrl,
isSubmitting,
onSubmit,
}) => {
const { t } = useLanguage();
return (
<form onSubmit={onSubmit} className="space-y-6">
<div className="space-y-4">
<div>
<Label htmlFor="regionName">{t('regionName')}</Label>
<Input
id="regionName"
placeholder={t('regionNamePlaceholder')}
value={formData.regionName}
onChange={(e) => setFormData({ ...formData, regionName: e.target.value })}
required
/>
</div>
<div>
<Label htmlFor="agentIp">{t('agentServerIpAddress')}</Label>
<Input
id="agentIp"
placeholder={t('agentIpPlaceholder')}
value={formData.agentIp}
onChange={(e) => setFormData({ ...formData, agentIp: e.target.value })}
required
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label className="text-sm font-medium">{t('agentId')}</Label>
<div className="relative">
<Input
value={agentId}
readOnly
className="font-mono text-sm bg-muted/50 border-muted-foreground/20 pr-10"
/>
<Button
type="button"
size="sm"
variant="ghost"
className="absolute right-1 top-1/2 -translate-y-1/2 h-8 w-8 p-0 hover:bg-muted"
onClick={() => copyToClipboard(agentId)}
>
<Copy className="h-3 w-3" />
</Button>
</div>
</div>
<div>
<Label className="text-sm font-medium">{t('apiEndpoint')}</Label>
<div className="relative">
<Input
value={currentPocketBaseUrl}
readOnly
className="font-mono text-sm bg-muted/50 border-muted-foreground/20 pr-10"
/>
<Button
type="button"
size="sm"
variant="ghost"
className="absolute right-1 top-1/2 -translate-y-1/2 h-8 w-8 p-0 hover:bg-muted"
onClick={() => copyToClipboard(currentPocketBaseUrl)}
>
<Copy className="h-3 w-3" />
</Button>
</div>
</div>
</div>
<div>
<Label className="text-sm font-medium">{t('authenticationToken')}</Label>
<div className="relative">
<Input
value={agentToken}
readOnly
className="font-mono text-sm bg-muted/50 border-muted-foreground/20 pr-10"
/>
<Button
type="button"
size="sm"
variant="ghost"
className="absolute right-1 top-1/2 -translate-y-1/2 h-8 w-8 p-0 hover:bg-muted"
onClick={() => copyToClipboard(agentToken)}
>
<Copy className="h-3 w-3" />
</Button>
</div>
</div>
</div>
<div className="flex justify-end space-x-2">
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? t('creating') : t('createAgent')}
</Button>
</div>
</form>
);
};
@@ -1,159 +0,0 @@
import React from "react";
import { Button } from "@/components/ui/button";
import { Copy, Terminal } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { copyToClipboard } from "@/utils/copyUtils";
import { useLanguage } from "@/contexts/LanguageContext";
interface RegionalManualTabProps {
agentToken: string;
currentPocketBaseUrl: string;
formData: {
regionName: string;
agentIp: string;
};
agentId: string;
onDialogClose: () => void;
}
export const RegionalManualTab: React.FC<RegionalManualTabProps> = ({
agentToken,
currentPocketBaseUrl,
formData,
agentId,
onDialogClose,
}) => {
const { t } = useLanguage();
const getManualInstallSteps = () => {
return [
{
title: t('step1DownloadPackage'),
commands: [
{
label: t('downloadAmd64Notice'),
command: 'wget https://github.com/operacle/Distributed-Regional-Monitoring/releases/download/V1.0.0/distributed-regional-check-agent_1.0.0_amd64.deb'
},
{
label: t('downloadArm64Notice'),
command: 'wget https://github.com/operacle/Distributed-Regional-Monitoring/releases/download/V1.0.0/distributed-regional-check-agent_1.0.0_arm64.deb'
}
]
},
{
title: t('step2InstallPackage'),
commands: [
{
label: '',
command: 'sudo dpkg -i distributed-regional-check-agent_1.0.0_amd64.deb\nsudo apt-get install -f'
}
]
},
{
title: t('step3ConfigureAgent'),
commands: [
{
label: '',
command: 'sudo nano /etc/regional-check-agent/regional-check-agent.env'
},
{
label: t('addConfigurationValues'),
command: `POCKETBASE_URL=${currentPocketBaseUrl}
AGENT_TOKEN=${agentToken}
AGENT_ID=${agentId}
REGION_NAME=${formData.regionName}
AGENT_IP=${formData.agentIp}`
}
]
},
{
title: t('step4StartService'),
commands: [
{
label: '',
command: 'sudo systemctl enable regional-check-agent\nsudo systemctl start regional-check-agent'
}
]
},
{
title: t('step5VerifyInstallation'),
commands: [
{
label: '',
command: 'sudo systemctl status regional-check-agent\ncurl http://localhost:8091/health'
}
]
}
];
};
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Terminal className="h-5 w-5" />
{t('manualInstallationSteps')}
</CardTitle>
<CardDescription>
{t('stepByStepManualInstallation')}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-4">
{getManualInstallSteps().map((step, stepIndex) => (
<div key={stepIndex} className="border-l-4 border-blue-500 pl-4 space-y-2">
<div className="flex items-center gap-2">
<span className="flex items-center justify-center w-6 h-6 rounded-full bg-primary text-primary-foreground text-sm font-medium">
{stepIndex + 1}
</span>
<p className="font-medium">{step.title}</p>
</div>
{step.commands.map((cmd, cmdIndex) => (
<div key={cmdIndex} className="space-y-1">
{cmd.label && (
<p className="text-xs text-muted-foreground ml-8">{cmd.label}</p>
)}
<div className="ml-8 relative">
<pre className="bg-muted p-3 rounded-md text-sm overflow-x-auto whitespace-pre-wrap break-all">
<code>{cmd.command}</code>
</pre>
<Button
type="button"
variant="outline"
size="sm"
className="absolute top-2 right-2"
onClick={() => copyToClipboard(cmd.command)}
>
<Copy className="h-4 w-4 mr-1" />
Copy
</Button>
</div>
</div>
))}
</div>
))}
</div>
<div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-md p-4">
<h4 className="font-medium text-blue-900 dark:text-blue-100 mb-2">Prerequisites:</h4>
<ul className="text-sm text-blue-800 dark:text-blue-200 space-y-1 list-disc list-inside mb-3">
<li>Ensure you have root/sudo access on the target server</li>
<li>Make sure wget or curl is installed for downloading files</li>
<li>Internet connection required for downloading packages</li>
</ul>
<h4 className="font-medium text-blue-900 dark:text-blue-100 mb-2">After Installation:</h4>
<p className="text-sm text-blue-800 dark:text-blue-200">
The agent will start automatically and appear in your dashboard within a few minutes.
</p>
</div>
<div className="flex justify-end pt-4">
<Button onClick={onDialogClose}>
{t('done')}
</Button>
</div>
</CardContent>
</Card>
);
};
@@ -1,68 +1,80 @@
import React, { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Plus, MapPin, Activity, Wifi, WifiOff } from "lucide-react";
import { regionalService } from "@/services/regionalService";
import { RegionalService } from "@/types/regional.types";
import { AddRegionalAgentDialog } from "./AddRegionalAgentDialog";
import { RegionalAgentCard } from "./RegionalAgentCard";
import { useToast } from "@/hooks/use-toast";
import { useLanguage } from "@/contexts/LanguageContext";
export const RegionalMonitoringContent = () => {
const { t } = useLanguage();
const [addDialogOpen, setAddDialogOpen] = useState(false);
const { toast } = useToast();
const queryClient = useQueryClient();
const { data: regionalServices = [], isLoading, error } = useQuery({
queryKey: ['regional-services'],
const {
data: regionalServices = [],
isLoading,
error,
} = useQuery({
queryKey: ["regional-services"],
queryFn: regionalService.getRegionalServices,
refetchInterval: 30000, // Refetch every 30 seconds
});
const handleAgentAdded = () => {
queryClient.invalidateQueries({ queryKey: ['regional-services'] });
queryClient.invalidateQueries({ queryKey: ["regional-services"] });
toast({
title: t('regionalAgentAdded'),
description: t('regionalAgentAddedDesc'),
title: "Regional Agent Added",
description:
"The regional monitoring agent has been successfully configured.",
});
};
const handleDeleteAgent = async (id: string) => {
try {
await regionalService.deleteRegionalService(id);
queryClient.invalidateQueries({ queryKey: ['regional-services'] });
queryClient.invalidateQueries({ queryKey: ["regional-services"] });
toast({
title: t('agentRemoved'),
description: t('agentRemovedDesc'),
title: "Agent Removed",
description: "The regional monitoring agent has been removed.",
});
} catch (error) {
toast({
title: t('error'),
description: t('failedToRemoveAgent'),
title: "Error",
description: "Failed to remove the regional monitoring agent.",
variant: "destructive",
});
}
};
const onlineAgents = regionalServices.filter(agent => agent.connection === 'online').length;
const onlineAgents = regionalServices.filter(
(agent) => agent.connection === "online"
).length;
const totalAgents = regionalServices.length;
return (
<div className="p-6 space-y-6">
<div className="p-6 space-y-6 ">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold tracking-tight">{t('regionalmonitoring')}</h1>
<h1 className="text-3xl font-bold tracking-tight">
Regional Monitoring
</h1>
<p className="text-muted-foreground">
{t('descriptRegionPage')}
Manage distributed monitoring agents across different regions
</p>
</div>
<Button onClick={() => setAddDialogOpen(true)}>
<Plus className="mr-2 h-4 w-4" />
{t('addRegionalAgent')}
Add Regional Agent
</Button>
</div>
@@ -70,48 +82,50 @@ export const RegionalMonitoringContent = () => {
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">{t('totalAgents')}</CardTitle>
<CardTitle className="text-sm font-medium">Total Agents</CardTitle>
<MapPin className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{totalAgents}</div>
<p className="text-xs text-muted-foreground">
{t('regionalMonitoringAgents')}
Regional monitoring agents
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">{t('onlineAgents')}</CardTitle>
<CardTitle className="text-sm font-medium">Online Agents</CardTitle>
<Wifi className="h-4 w-4 text-green-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-green-600">{onlineAgents}</div>
<p className="text-xs text-muted-foreground">
{t('currentlyConnected')}
</p>
<div className="text-2xl font-bold text-green-600">
{onlineAgents}
</div>
<p className="text-xs text-muted-foreground">Currently connected</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">{t('offlineAgents')}</CardTitle>
<CardTitle className="text-sm font-medium">
Offline Agents
</CardTitle>
<WifiOff className="h-4 w-4 text-red-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-red-600">{totalAgents - onlineAgents}</div>
<p className="text-xs text-muted-foreground">
{t('disconnectedAgents')}
</p>
<div className="text-2xl font-bold text-red-600">
{totalAgents - onlineAgents}
</div>
<p className="text-xs text-muted-foreground">Disconnected agents</p>
</CardContent>
</Card>
</div>
{/* Agents List */}
<div className="space-y-4">
<h2 className="text-xl font-semibold">{t('regionalAgents')}</h2>
<h2 className="text-xl font-semibold">Regional Agents</h2>
{isLoading ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{[...Array(3)].map((_, i) => (
@@ -133,22 +147,23 @@ export const RegionalMonitoringContent = () => {
<Card>
<CardContent className="flex flex-col items-center justify-center py-12">
<MapPin className="h-12 w-12 text-muted-foreground mb-4" />
<h3 className="text-lg font-semibold mb-2">{t('noRegionalAgents')}</h3>
<h3 className="text-lg font-semibold mb-2">No Regional Agents</h3>
<p className="text-muted-foreground text-center mb-4">
{t('getStartedAddAgent')}
Get started by adding your first regional monitoring agent to
extend your monitoring coverage.
</p>
<Button onClick={() => setAddDialogOpen(true)}>
<Plus className="mr-2 h-4 w-4" />
{t('addFirstAgent')}
Add First Agent
</Button>
</CardContent>
</Card>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{regionalServices.map((agent) => (
<RegionalAgentCard
key={agent.id}
agent={agent}
<RegionalAgentCard
key={agent.id}
agent={agent}
onDelete={() => handleDeleteAgent(agent.id)}
/>
))}
@@ -163,4 +178,4 @@ export const RegionalMonitoringContent = () => {
/>
</div>
);
};
};
@@ -1,126 +0,0 @@
import React from "react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Copy, Download, Zap, Play } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { copyToClipboard } from "@/utils/copyUtils";
import { useLanguage } from "@/contexts/LanguageContext";
import { useToast } from "@/hooks/use-toast";
interface RegionalOneClickTabProps {
agentToken: string;
currentPocketBaseUrl: string;
formData: {
regionName: string;
agentIp: string;
};
agentId: string;
onDialogClose: () => void;
}
export const RegionalOneClickTab: React.FC<RegionalOneClickTabProps> = ({
agentToken,
currentPocketBaseUrl,
formData,
agentId,
onDialogClose,
}) => {
const { t } = useLanguage();
const { toast } = useToast();
const getOneClickCommand = () => {
return `curl -fsSL https://raw.githubusercontent.com/operacle/checkcle/refs/heads/main/scripts/install-regional-agent.sh | sudo bash -s -- \\
--region-name="${formData.regionName}" \\
--agent-id="${agentId}" \\
--agent-ip="${formData.agentIp}" \\
--token="${agentToken}" \\
--pocketbase-url="${currentPocketBaseUrl}"`;
};
const downloadScript = () => {
const scriptContent = getOneClickCommand();
const blob = new Blob([scriptContent], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `install-regional-agent-${agentId}.sh`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
toast({
title: t('downloaded'),
description: t('downloadedDescription'),
});
};
return (
<Card className="border-green-500/20 bg-green-50/50 dark:bg-green-950/20">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-green-700 dark:text-green-400">
<Zap className="h-5 w-5" />
{t('oneClickAutomaticInstallation')}
</CardTitle>
<CardDescription className="text-green-600 dark:text-green-300">
{t('completeInstallationDescription')}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="bg-green-50 border border-green-200 rounded-lg p-4 dark:bg-green-950/50 dark:border-green-800">
<div className="flex items-center gap-2 text-green-800 dark:text-green-200 font-medium mb-2">
<Play className="h-4 w-4" />
{t('whatThisScriptDoes')}
</div>
<ul className="text-sm text-green-700 dark:text-green-300 space-y-1 ml-6">
<li> {t('scriptActionDownload')}</li>
<li> {t('scriptActionInstall')}</li>
<li> {t('scriptActionConfigure')}</li>
<li> {t('scriptActionStart')}</li>
<li> {t('scriptActionHealthChecks')}</li>
</ul>
</div>
<div className="space-y-2">
<Label className="text-green-700 dark:text-green-400">{t('runCommandOnServer')}</Label>
<div className="relative">
<Textarea
readOnly
value={getOneClickCommand()}
className="font-mono text-sm min-h-[120px] pr-12 bg-muted/50 border-green-200 dark:border-green-800"
/>
<Button
type="button"
size="sm"
variant="outline"
className="absolute top-2 right-2 bg-green-50 dark:bg-green-950/50 border-green-200 dark:border-green-800 hover:bg-green-100 dark:hover:bg-green-900"
onClick={() => copyToClipboard(getOneClickCommand())}
>
<Copy className="h-3 w-3" />
</Button>
</div>
</div>
<div className="flex gap-2">
<Button onClick={downloadScript} variant="outline" className="flex-1">
<Download className="mr-2 h-4 w-4" />
{t('downloadCompleteScript')}
</Button>
</div>
{(window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') && (
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-3 dark:bg-yellow-950/20 dark:border-yellow-800">
<p className="text-sm text-yellow-800 dark:text-yellow-200" dangerouslySetInnerHTML={{ __html: t('localDevelopmentNotice') }} />
</div>
)}
<div className="flex justify-end pt-4">
<Button onClick={onDialogClose}>
{t('done')}
</Button>
</div>
</CardContent>
</Card>
);
};
@@ -1,33 +1,37 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect } from "react";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Plus, CalendarClock, AlertCircle } from "lucide-react";
import { useLanguage } from "@/contexts/LanguageContext";
import { ScheduledMaintenanceTab } from "./ScheduledMaintenanceTab";
import { IncidentManagementTab } from "./IncidentManagementTab";
import { CreateMaintenanceDialog } from './maintenance/CreateMaintenanceDialog';
import { CreateIncidentDialog } from './incident/CreateIncidentDialog';
import { useToast } from '@/hooks/use-toast';
import { initMaintenanceNotifications, stopMaintenanceNotifications } from '@/services/maintenance/maintenanceNotificationService';
import { CreateMaintenanceDialog } from "./maintenance/CreateMaintenanceDialog";
import { CreateIncidentDialog } from "./incident/CreateIncidentDialog";
import { useToast } from "@/hooks/use-toast";
import {
initMaintenanceNotifications,
stopMaintenanceNotifications,
} from "@/services/maintenance/maintenanceNotificationService";
export const ScheduleIncidentContent = () => {
const { t } = useLanguage();
const { toast } = useToast();
const [activeTab, setActiveTab] = useState("maintenance");
const [createMaintenanceDialogOpen, setCreateMaintenanceDialogOpen] = useState(false);
const [createIncidentDialogOpen, setCreateIncidentDialogOpen] = useState(false);
const [createMaintenanceDialogOpen, setCreateMaintenanceDialogOpen] =
useState(false);
const [createIncidentDialogOpen, setCreateIncidentDialogOpen] =
useState(false);
const [refreshTrigger, setRefreshTrigger] = useState(0);
const [incidentRefreshTrigger, setIncidentRefreshTrigger] = useState(0);
// Initialize maintenance notifications when the component mounts
useEffect(() => {
// console.log("Initializing maintenance notifications");
// console.log("Initializing maintenance notifications");
initMaintenanceNotifications();
// Clean up when the component unmounts
return () => {
// console.log("Cleaning up maintenance notifications");
// console.log("Cleaning up maintenance notifications");
stopMaintenanceNotifications();
};
}, []);
@@ -43,65 +47,67 @@ export const ScheduleIncidentContent = () => {
const handleMaintenanceCreated = () => {
// Refresh data by incrementing the refresh trigger
const newTriggerValue = refreshTrigger + 1;
// console.log("Maintenance created, refreshing data with new trigger value:", newTriggerValue);
// console.log("Maintenance created, refreshing data with new trigger value:", newTriggerValue);
setRefreshTrigger(newTriggerValue);
// Show success toast
toast({
title: t('success'),
description: t('maintenanceCreatedSuccess'),
title: t("success"),
description: t("maintenanceCreatedSuccess"),
});
};
const handleIncidentCreated = () => {
// Refresh data by incrementing the refresh trigger
const newTriggerValue = incidentRefreshTrigger + 1;
// console.log("Incident created, refreshing data with new trigger value:", newTriggerValue);
// console.log("Incident created, refreshing data with new trigger value:", newTriggerValue);
setIncidentRefreshTrigger(newTriggerValue);
// Show success toast
toast({
title: t('success'),
description: t('incidentCreatedSuccess'),
title: t("success"),
description: t("incidentCreatedSuccess"),
});
};
return (
<main className="flex-1 flex flex-col overflow-auto bg-background p-6">
<div className="flex flex-col gap-6">
<main className="flex-1 flex flex-col overflow-auto bg-background dark:bg-black p-2 ">
<div className="flex flex-col gap-6 bg-white dark:bg-black p-3 h-full rounded-xl">
<div className="flex justify-between items-center">
<h2 className="text-2xl font-bold text-foreground">
{t('scheduleIncidentManagement')}
{t("scheduleIncidentManagement")}
</h2>
<Button
<Button
className="text-primary-foreground"
onClick={handleCreateButtonClick}
>
<Plus className="w-4 h-4 mr-2" />
{activeTab === "maintenance" ? t('createMaintenanceWindow') : t('createIncident')}
<Plus className="w-4 h-4 mr-2" />
{activeTab === "maintenance"
? t("createMaintenanceWindow")
: t("createIncident")}
</Button>
</div>
<Tabs
defaultValue="maintenance"
<Tabs
defaultValue="maintenance"
className="w-full"
onValueChange={(value) => setActiveTab(value)}
>
<TabsList className="grid w-full grid-cols-2 mb-4">
<TabsTrigger value="maintenance">
<CalendarClock className="w-4 h-4 mr-2" />
{t('scheduledMaintenance')}
{t("scheduledMaintenance")}
</TabsTrigger>
<TabsTrigger value="incidents">
<AlertCircle className="w-4 h-4 mr-2" />
{t('incidentManagement')}
{t("incidentManagement")}
</TabsTrigger>
</TabsList>
<TabsContent value="maintenance" className="space-y-4">
<ScheduledMaintenanceTab refreshTrigger={refreshTrigger} />
</TabsContent>
<TabsContent value="incidents" className="space-y-4">
<IncidentManagementTab refreshTrigger={incidentRefreshTrigger} />
</TabsContent>
@@ -109,14 +115,14 @@ export const ScheduleIncidentContent = () => {
</div>
{/* Maintenance creation dialog */}
<CreateMaintenanceDialog
<CreateMaintenanceDialog
open={createMaintenanceDialogOpen}
onOpenChange={setCreateMaintenanceDialogOpen}
onMaintenanceCreated={handleMaintenanceCreated}
/>
{/* Incident creation dialog */}
<CreateIncidentDialog
<CreateIncidentDialog
open={createIncidentDialogOpen}
onOpenChange={setCreateIncidentDialogOpen}
onIncidentCreated={handleIncidentCreated}
@@ -16,7 +16,6 @@ import { ServerAgentConfigForm } from "./ServerAgentConfigForm";
import { OneClickInstallTab } from "./OneClickInstallTab";
import { DockerOneClickTab } from "./DockerOneClickTab";
import { ManualInstallTab } from "./ManualInstallTab";
import { useLanguage } from "@/contexts/LanguageContext";
interface AddServerAgentDialogProps {
open: boolean;
@@ -29,13 +28,15 @@ export const AddServerAgentDialog: React.FC<AddServerAgentDialogProps> = ({
onOpenChange,
onAgentAdded,
}) => {
const { t } = useLanguage();
const { toast } = useToast();
const queryClient = useQueryClient();
const [isSubmitting, setIsSubmitting] = useState(false);
const [activeTab, setActiveTab] = useState("configure");
// Get current PocketBase URL
const currentPocketBaseUrl = getCurrentEndpoint();
// Form state
const [formData, setFormData] = useState({
serverName: "",
description: "",
@@ -46,46 +47,23 @@ export const AddServerAgentDialog: React.FC<AddServerAgentDialogProps> = ({
notificationEnabled: true,
});
const generateNewCredentials = () => ({
serverToken: `srv_${Math.random().toString(36).substring(2, 15)}${Math.random().toString(36).substring(2, 15)}`,
serverId: `agent_${Math.random().toString(36).substring(2, 15)}${Math.random().toString(36).substring(2, 15)}`
});
const [serverToken, setServerToken] = useState(() =>
// Generated server token and agent ID
const [serverToken] = useState(() =>
`srv_${Math.random().toString(36).substring(2, 15)}${Math.random().toString(36).substring(2, 15)}`
);
const [serverId, setServerId] = useState(() =>
const [serverId] = useState(() =>
`agent_${Math.random().toString(36).substring(2, 15)}${Math.random().toString(36).substring(2, 15)}`
);
// Refresh credentials and reset form whenever the dialog opens
React.useEffect(() => {
if (open) {
const newCredentials = generateNewCredentials();
setServerToken(newCredentials.serverToken);
setServerId(newCredentials.serverId);
setActiveTab("configure");
setFormData({
serverName: "",
description: "",
osType: "",
checkInterval: "60",
retryAttempt: "3",
dockerEnabled: false,
notificationEnabled: true,
});
}
}, [open]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (isSubmitting) return;
if (!formData.serverName || !formData.osType) {
toast({
title: t('validationError'),
description: t('fillRequiredFields'),
title: "Validation Error",
description: "Please fill in all required fields.",
variant: "destructive",
});
return;
@@ -94,18 +72,22 @@ export const AddServerAgentDialog: React.FC<AddServerAgentDialogProps> = ({
setIsSubmitting(true);
try {
// Here you would typically create the server monitoring configuration
// For now, we'll simulate the process
await new Promise(resolve => setTimeout(resolve, 1500));
toast({
title: t('serverAgentCreated'),
description: t('serverAgentCreatedDesc').replace('{name}', formData.serverName),
title: "Server Agent Created",
description: `${formData.serverName} monitoring agent has been configured successfully.`,
});
// Switch to one-click install tab after successful creation
setActiveTab("one-click");
onAgentAdded();
} catch (error) {
toast({
title: t('error'),
description: t('failedToCreateAgent'),
title: "Error",
description: "Failed to create server monitoring agent.",
variant: "destructive",
});
} finally {
@@ -114,6 +96,17 @@ export const AddServerAgentDialog: React.FC<AddServerAgentDialogProps> = ({
};
const handleDialogClose = () => {
// Reset form and tab when dialog closes
setActiveTab("configure");
setFormData({
serverName: "",
description: "",
osType: "",
checkInterval: "60",
retryAttempt: "3",
dockerEnabled: false,
notificationEnabled: true,
});
onOpenChange(false);
};
@@ -123,19 +116,19 @@ export const AddServerAgentDialog: React.FC<AddServerAgentDialogProps> = ({
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Server className="h-5 w-5" />
{t('addServerMonitoringAgent')}
Add Server Monitoring Agent
</DialogTitle>
<DialogDescription>
{t('configureAgentDesc')}
Configure a new server monitoring agent to track system metrics and performance.
</DialogDescription>
</DialogHeader>
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
<TabsList className="grid w-full grid-cols-4">
<TabsTrigger value="configure">{t('configureAgent')}</TabsTrigger>
<TabsTrigger value="one-click">{t('oneClickInstall')}</TabsTrigger>
<TabsTrigger value="docker-one-click">{t('dockerOneClick')}</TabsTrigger>
<TabsTrigger value="manual">{t('manualInstallation')}</TabsTrigger>
<TabsTrigger value="configure">Configure Agent</TabsTrigger>
<TabsTrigger value="one-click">One-Click Install</TabsTrigger>
<TabsTrigger value="docker-one-click">Docker One-Click</TabsTrigger>
<TabsTrigger value="manual">Manual Installation</TabsTrigger>
</TabsList>
<TabsContent value="configure" className="space-y-6">
@@ -159,7 +152,7 @@ export const AddServerAgentDialog: React.FC<AddServerAgentDialogProps> = ({
onDialogClose={handleDialogClose}
/>
</TabsContent>
<TabsContent value="docker-one-click" className="space-y-6">
<DockerOneClickTab
serverToken={serverToken}
@@ -5,7 +5,6 @@ import { Label } from "@/components/ui/label";
import { Copy, Download, Container } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { copyToClipboard } from "@/utils/copyUtils";
import { useLanguage } from "@/contexts/LanguageContext";
interface DockerOneClickTabProps {
serverToken: string;
@@ -27,7 +26,6 @@ export const DockerOneClickTab: React.FC<DockerOneClickTabProps> = ({
serverId,
onDialogClose,
}) => {
const { t } = useLanguage();
const getDockerOneClickCommand = () => {
const scriptUrl = "https://cdn.checkcle.io/scripts/server-docker-agent.sh";
@@ -88,15 +86,15 @@ sudo -E bash ./server-docker-agent.sh`;
<CardHeader>
<CardTitle className="flex items-center gap-2 text-blue-700 dark:text-blue-400">
<Container className="h-5 w-5" />
{t('dockerOneClickTitle')}
Docker One-Click Install
</CardTitle>
<CardDescription className="text-blue-600 dark:text-blue-300">
{t('dockerOneClickDesc')}
Automated Docker container installation with system monitoring capabilities
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label className="text-blue-700 dark:text-blue-400">{t('dockerOneClickCommand')}</Label>
<Label className="text-blue-700 dark:text-blue-400">Docker One-Click Command</Label>
<div className="relative">
<pre className="bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 p-4 rounded-md text-sm overflow-x-auto whitespace-pre-wrap break-all text-blue-800 dark:text-blue-200">
<code>{getDockerOneClickCommand()}</code>
@@ -109,18 +107,18 @@ sudo -E bash ./server-docker-agent.sh`;
onClick={handleCopyOneClickCommand}
>
<Copy className="h-4 w-4 mr-1" />
{t('copy')}
Copy
</Button>
</div>
</div>
<div className="text-sm text-blue-700 dark:text-blue-300 bg-blue-50 dark:bg-blue-950/50 border border-blue-200 dark:border-blue-800 p-3 rounded-md">
<p className="font-medium mb-1">{t('dockerScriptWill')}</p>
<p className="font-medium mb-1">This script will automatically:</p>
<ol className="list-decimal list-inside space-y-1 text-xs">
<li>{t('dockerScriptStep1')}</li>
<li>{t('dockerScriptStep2')}</li>
<li>{t('dockerScriptStep3')}</li>
<li>{t('dockerScriptStep4')}</li>
<li>Download and setup the Docker monitoring agent</li>
<li>Configure all required environment variables</li>
<li>Start the container with proper system access</li>
<li>Setup monitoring data persistence</li>
</ol>
</div>
</CardContent>
@@ -131,15 +129,15 @@ sudo -E bash ./server-docker-agent.sh`;
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Container className="h-5 w-5" />
{t('directDockerTitle')}
Direct Docker Run Command
</CardTitle>
<CardDescription>
{t('directDockerDesc')}
If you prefer to run the Docker container directly without the script
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label>{t('dockerRunCommand')}</Label>
<Label>Docker Run Command</Label>
<div className="relative">
<pre className="bg-muted border p-4 rounded-md text-sm overflow-x-auto whitespace-pre-wrap break-all">
<code>{getDirectDockerCommand()}</code>
@@ -152,17 +150,17 @@ sudo -E bash ./server-docker-agent.sh`;
onClick={handleCopyDockerCommand}
>
<Copy className="h-4 w-4 mr-1" />
{t('copy')}
Copy
</Button>
</div>
</div>
<div className="text-sm text-muted-foreground bg-muted/50 border p-3 rounded-md">
<p className="font-medium mb-1">{t('dockerPrerequisites')}</p>
<p className="font-medium mb-1">Prerequisites for direct Docker run:</p>
<ol className="list-decimal list-inside space-y-1 text-xs">
<li>{t('dockerPrereqStep1')}</li>
<li>{t('dockerPrereqStep2')}</li>
<li>{t('dockerPrereqStep3')}</li>
<li>Docker must be installed and running</li>
<li>The operacle/checkcle-server-agent image must be available</li>
<li>Run as root or with sudo privileges</li>
</ol>
</div>
</CardContent>
@@ -170,7 +168,7 @@ sudo -E bash ./server-docker-agent.sh`;
<div className="flex justify-end pt-4">
<Button onClick={onDialogClose}>
{t('done')}
Done
</Button>
</div>
</div>
@@ -14,7 +14,6 @@ import { RefreshCw, X } from "lucide-react";
import { alertConfigService, AlertConfiguration } from "@/services/alertConfigService";
import { templateService, ServerNotificationTemplate } from "@/services/templateService";
import { serverThresholdService, ServerThreshold } from "@/services/serverThresholdService";
import { useLanguage } from "@/contexts/LanguageContext";
interface EditServerDialogProps {
server: Server | null;
@@ -47,7 +46,6 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
onOpenChange,
onServerUpdated,
}) => {
const { t } = useLanguage();
const [formData, setFormData] = useState<ServerFormData>({
name: "",
check_interval: 60,
@@ -116,7 +114,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
// Handle the API response format with proper field names and type conversion
setThresholdFormData({
cpu_threshold: parseInt(String(existingThreshold.cpu_threshold)) || 80,
ram_threshold: parseInt(String((existingThreshold.ram_threshold_message ?? existingThreshold.ram_threshold))) || 80,
ram_threshold: parseInt(String((existingThreshold as any).ram_threshold_message || existingThreshold.ram_threshold)) || 80,
disk_threshold: parseInt(String(existingThreshold.disk_threshold)) || 80,
network_threshold: parseInt(String(existingThreshold.network_threshold)) || 80,
});
@@ -143,7 +141,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
// Handle the API response format with proper field names and type conversion
setThresholdFormData({
cpu_threshold: parseInt(String(threshold.cpu_threshold)) || 80,
ram_threshold: parseInt(String((threshold.ram_threshold_message ?? threshold.ram_threshold))) || 80,
ram_threshold: parseInt(String((threshold as any).ram_threshold_message || threshold.ram_threshold)) || 80,
disk_threshold: parseInt(String(threshold.disk_threshold)) || 80,
network_threshold: parseInt(String(threshold.network_threshold)) || 80,
});
@@ -167,8 +165,8 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
} catch (error) {
toast({
variant: "destructive",
title: t('error', 'instance'),
description: t('failedToLoadChannels', 'instance'),
title: "Error",
description: "Failed to load notification channels",
});
} finally {
setLoadingAlertConfigs(false);
@@ -184,8 +182,8 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
} catch (error) {
toast({
variant: "destructive",
title: t('error', 'instance'),
description: t('failedToLoadTemplates', 'instance'),
title: "Error",
description: "Failed to load templates",
});
} finally {
setLoadingTemplates(false);
@@ -200,8 +198,8 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
} catch (error) {
toast({
variant: "destructive",
title: t('error', 'instance'),
description: t('failedToLoadThresholds', 'instance'),
title: "Error",
description: "Failed to load server thresholds",
});
} finally {
setLoadingThresholds(false);
@@ -276,15 +274,15 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
} catch (error) {
toast({
variant: "destructive",
title: t('warning', 'instance'),
description: t('serverUpdatedButThresholdFailed', 'instance'),
title: "Warning",
description: "Server updated but failed to update threshold values.",
});
}
}
toast({
title: t('serverUpdated', 'instance'),
description: t('serverUpdatedDesc', 'instance', { name: formData.name }),
title: "Server updated",
description: `${formData.name} has been updated successfully.`,
});
onServerUpdated();
@@ -293,8 +291,8 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
} catch (error) {
toast({
variant: "destructive",
title: t('error', 'instance'),
description: t('failedToUpdateServer', 'instance'),
title: "Error",
description: "Failed to update server. Please try again.",
});
} finally {
setIsSubmitting(false);
@@ -325,62 +323,62 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[700px] max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{t('editServerConfiguration', 'instance')}</DialogTitle>
<DialogTitle>Edit Server Configuration</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="serverName">{t('serverNameLabel', 'instance')}</Label>
<Label htmlFor="serverName">Server Name *</Label>
<Input
id="serverName"
value={formData.name}
onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
placeholder={t('serverNamePlaceholder', 'instance')}
placeholder="Enter server name"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="checkInterval">{t('checkIntervalLabel', 'instance')}</Label>
<Label htmlFor="checkInterval">Check Interval</Label>
<Select
value={formData.check_interval.toString()}
onValueChange={(value) => setFormData(prev => ({ ...prev, check_interval: parseInt(value) }))}
>
<SelectTrigger>
<SelectValue placeholder={t('selectInterval', 'instance')} />
<SelectValue placeholder="Select interval" />
</SelectTrigger>
<SelectContent>
<SelectItem value="30">{t('interval30s', 'instance')}</SelectItem>
<SelectItem value="60">{t('interval1m', 'instance')}</SelectItem>
<SelectItem value="120">{t('interval2m', 'instance')}</SelectItem>
<SelectItem value="300">{t('interval5m', 'instance')}</SelectItem>
<SelectItem value="600">{t('interval10m', 'instance')}</SelectItem>
<SelectItem value="30">30 seconds</SelectItem>
<SelectItem value="60">1 minute</SelectItem>
<SelectItem value="120">2 minutes</SelectItem>
<SelectItem value="300">5 minutes</SelectItem>
<SelectItem value="600">10 minutes</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="maxRetries">{t('maxRetriesLabel', 'instance')}</Label>
<Label htmlFor="maxRetries">Max Retries</Label>
<Select
value={formData.max_retries.toString()}
onValueChange={(value) => setFormData(prev => ({ ...prev, max_retries: parseInt(value) }))}
>
<SelectTrigger>
<SelectValue placeholder={t('selectMaxRetries', 'instance')} />
<SelectValue placeholder="Select max retries" />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">{t('retry1', 'instance')}</SelectItem>
<SelectItem value="2">{t('retry2', 'instance')}</SelectItem>
<SelectItem value="3">{t('retry3', 'instance')}</SelectItem>
<SelectItem value="5">{t('retry5', 'instance')}</SelectItem>
<SelectItem value="10">{t('retry10', 'instance')}</SelectItem>
<SelectItem value="1">1 retry</SelectItem>
<SelectItem value="2">2 retries</SelectItem>
<SelectItem value="3">3 retries</SelectItem>
<SelectItem value="5">5 retries</SelectItem>
<SelectItem value="10">10 retries</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="dockerMonitoring">{t('dockerMonitoring', 'instance')}</Label>
<Label htmlFor="dockerMonitoring">Docker Monitoring</Label>
<div className="flex items-center space-x-2">
<Switch
id="dockerMonitoring"
@@ -391,7 +389,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
}))}
/>
<Label htmlFor="dockerMonitoring" className="text-sm text-muted-foreground">
{formData.docker_monitoring ? t('enabled', 'instance') : t('disabled', 'instance')}
{formData.docker_monitoring ? "Enabled" : "Disabled"}
</Label>
</div>
</div>
@@ -409,22 +407,22 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
// Remove the automatic clearing of notification_channels, threshold_id, and template_id
}))}
/>
<Label htmlFor="notificationEnabled">{t('enableNotifications', 'instance')}</Label>
<Label htmlFor="notificationEnabled">Enable Notifications</Label>
</div>
{/* Expanded Notification Settings */}
{formData.notification_enabled && (
<Card className="border-l-4 border-l-blue-500">
<CardHeader>
<CardTitle className="text-lg">{t('notificationSettings', 'instance')}</CardTitle>
<CardTitle className="text-lg">Notification Settings</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* Multiple Notification Channels Selection */}
<div className="space-y-2">
<Label>{t('notificationChannels', 'instance')}</Label>
<Label>Notification Channels</Label>
<div className="space-y-2 max-h-40 overflow-y-auto border rounded-md p-3">
{loadingAlertConfigs ? (
<div className="text-sm text-muted-foreground">{t('loadingChannels', 'instance')}</div>
<div className="text-sm text-muted-foreground">Loading channels...</div>
) : alertConfigs.length > 0 ? (
alertConfigs.map((config) => (
<div key={config.id} className="flex items-center space-x-2">
@@ -444,14 +442,14 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
</div>
))
) : (
<div className="text-sm text-muted-foreground">{t('noChannelsAvailable', 'instance')}</div>
<div className="text-sm text-muted-foreground">No notification channels available</div>
)}
</div>
{/* Selected Channels Display */}
{formData.notification_channels.length > 0 && (
<div className="space-y-2">
<Label className="text-sm font-medium">{t('selectedChannels', 'instance')}</Label>
<Label className="text-sm font-medium">Selected Channels:</Label>
<div className="flex flex-wrap gap-2">
{formData.notification_channels.map((channelId) => {
const channel = alertConfigs.find(c => c.id === channelId);
@@ -480,17 +478,17 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
{/* Server Set Threshold Selection */}
<div className="space-y-2">
<Label htmlFor="thresholdId">{t('serverSetThreshold', 'instance')}</Label>
<Label htmlFor="thresholdId">Server Set Threshold</Label>
<Select
value={formData.threshold_id}
onValueChange={(value) => setFormData(prev => ({ ...prev, threshold_id: value }))}
disabled={loadingThresholds}
>
<SelectTrigger>
<SelectValue placeholder={loadingThresholds ? t('loadingThresholds', 'instance') : t('selectServerThreshold', 'instance')} />
<SelectValue placeholder={loadingThresholds ? "Loading thresholds..." : "Select server threshold"} />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">{t('noThreshold', 'instance')}</SelectItem>
<SelectItem value="none">No threshold (use default)</SelectItem>
{thresholds.map((threshold) => (
<SelectItem key={threshold.id} value={threshold.id}>
{threshold.name}
@@ -504,12 +502,12 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
{selectedThreshold && (
<Card className="bg-muted/50">
<CardHeader>
<CardTitle className="text-base">{t('thresholdDetails', 'instance')}: {selectedThreshold.name}</CardTitle>
<CardTitle className="text-base">Threshold Details: {selectedThreshold.name}</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="grid grid-cols-2 gap-3 text-sm">
<div>
<Label className="text-xs font-medium text-muted-foreground">{t('cpuThresholdPct', 'instance')}</Label>
<Label className="text-xs font-medium text-muted-foreground">CPU Threshold (%)</Label>
<Input
type="number"
min="0"
@@ -523,7 +521,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
/>
</div>
<div>
<Label className="text-xs font-medium text-muted-foreground">{t('ramThresholdPct', 'instance')}</Label>
<Label className="text-xs font-medium text-muted-foreground">RAM Threshold (%)</Label>
<Input
type="number"
min="0"
@@ -537,7 +535,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
/>
</div>
<div>
<Label className="text-xs font-medium text-muted-foreground">{t('diskThresholdPct', 'instance')}</Label>
<Label className="text-xs font-medium text-muted-foreground">Disk Threshold (%)</Label>
<Input
type="number"
min="0"
@@ -551,7 +549,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
/>
</div>
<div>
<Label className="text-xs font-medium text-muted-foreground">{t('networkThresholdPct', 'instance')}</Label>
<Label className="text-xs font-medium text-muted-foreground">Network Threshold (%)</Label>
<Input
type="number"
min="0"
@@ -571,17 +569,17 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
{/* Server Template Selection */}
<div className="space-y-2">
<Label htmlFor="templateId">{t('serverTemplate', 'instance')}</Label>
<Label htmlFor="templateId">Server Template</Label>
<Select
value={formData.template_id}
onValueChange={(value) => setFormData(prev => ({ ...prev, template_id: value }))}
disabled={loadingTemplates}
>
<SelectTrigger>
<SelectValue placeholder={loadingTemplates ? t('loadingTemplates', 'instance') : t('selectServerTemplate', 'instance')} />
<SelectValue placeholder={loadingTemplates ? "Loading templates..." : "Select server template"} />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">{t('noTemplate', 'instance')}</SelectItem>
<SelectItem value="none">No template (use default)</SelectItem>
{templates.map((template) => (
<SelectItem key={template.id} value={template.id}>
{template.name}
@@ -595,44 +593,44 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
{selectedTemplate && (
<Card className="bg-muted/50">
<CardHeader>
<CardTitle className="text-base">{t('templateDetails', 'instance')}: {selectedTemplate.name}</CardTitle>
<CardTitle className="text-base">Template Details: {selectedTemplate.name}</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="grid grid-cols-1 gap-3 text-sm">
<div>
<Label className="text-xs font-medium text-muted-foreground">{t('ramMessage', 'instance')}</Label>
<Label className="text-xs font-medium text-muted-foreground">RAM Message</Label>
<p className="text-sm bg-background p-2 rounded border">
{selectedTemplate.ram_message || t('noMessageDefined', 'instance', { name: 'RAM' })}
{selectedTemplate.ram_message || "No RAM message defined"}
</p>
</div>
<div>
<Label className="text-xs font-medium text-muted-foreground">{t('cpuMessage', 'instance')}</Label>
<Label className="text-xs font-medium text-muted-foreground">CPU Message</Label>
<p className="text-sm bg-background p-2 rounded border">
{selectedTemplate.cpu_message || t('noMessageDefined', 'instance', { name: 'CPU' })}
{selectedTemplate.cpu_message || "No CPU message defined"}
</p>
</div>
<div>
<Label className="text-xs font-medium text-muted-foreground">{t('diskMessage', 'instance')}</Label>
<Label className="text-xs font-medium text-muted-foreground">Disk Message</Label>
<p className="text-sm bg-background p-2 rounded border">
{selectedTemplate.disk_message || t('noMessageDefined', 'instance', { name: 'disk' })}
{selectedTemplate.disk_message || "No disk message defined"}
</p>
</div>
<div>
<Label className="text-xs font-medium text-muted-foreground">{t('networkMessage', 'instance')}</Label>
<Label className="text-xs font-medium text-muted-foreground">Network Message</Label>
<p className="text-sm bg-background p-2 rounded border">
{selectedTemplate.network_message || t('noMessageDefined', 'instance', { name: 'network' })}
{selectedTemplate.network_message || "No network message defined"}
</p>
</div>
<div>
<Label className="text-xs font-medium text-muted-foreground">{t('upMessage', 'instance')}</Label>
<Label className="text-xs font-medium text-muted-foreground">Up Message</Label>
<p className="text-sm bg-background p-2 rounded border">
{selectedTemplate.up_message || t('noMessageDefined', 'instance', { name: 'up' })}
{selectedTemplate.up_message || "No up message defined"}
</p>
</div>
<div>
<Label className="text-xs font-medium text-muted-foreground">{t('downMessage', 'instance')}</Label>
<Label className="text-xs font-medium text-muted-foreground">Down Message</Label>
<p className="text-sm bg-background p-2 rounded border">
{selectedTemplate.down_message || t('noMessageDefined', 'instance', { name: 'down' })}
{selectedTemplate.down_message || "No down message defined"}
</p>
</div>
</div>
@@ -651,16 +649,16 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
onClick={handleCancel}
disabled={isSubmitting}
>
{t('cancel', 'instance')}
Cancel
</Button>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? (
<>
<RefreshCw className="mr-2 h-4 w-4 animate-spin" />
{t('updating', 'instance')}
Updating...
</>
) : (
t('updateServer', 'instance')
"Update Server"
)}
</Button>
</div>
@@ -4,7 +4,6 @@ import { Button } from "@/components/ui/button";
import { Copy, Terminal } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { copyToClipboard } from "@/utils/copyUtils";
import { useLanguage } from "@/contexts/LanguageContext";
interface ManualInstallTabProps {
serverToken: string;
@@ -25,22 +24,20 @@ export const ManualInstallTab: React.FC<ManualInstallTabProps> = ({
serverId,
onDialogClose,
}) => {
const { t } = useLanguage();
const getManualInstallSteps = () => {
const scriptUrl = "https://cdn.checkcle.io/scripts/server-agent.sh";
return [
{
title: t('downloadScript'),
title: "Download the installation script",
command: `curl -L -o server-agent.sh "${scriptUrl}"`
},
{
title: t('makeExecutable'),
title: "Make the script executable",
command: `chmod +x server-agent.sh`
},
{
title: t('runInstall'),
title: "Run the installation with your configuration",
command: `SERVER_TOKEN="${serverToken}" POCKETBASE_URL="${currentPocketBaseUrl}" SERVER_NAME="${formData.serverName}" AGENT_ID="${serverId}" sudo bash server-agent.sh`
}
];
@@ -51,26 +48,26 @@ export const ManualInstallTab: React.FC<ManualInstallTabProps> = ({
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Terminal className="h-5 w-5" />
{t('manualInstallTitle')}
Manual Installation Steps
</CardTitle>
<CardDescription>
{t('manualInstallDesc')}
Step-by-step installation process
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<span className="font-medium">{t('serverName')}:</span> {formData.serverName}
<span className="font-medium">Server Name:</span> {formData.serverName}
</div>
<div>
<span className="font-medium">{t('agentId')}:</span> {serverId}
<span className="font-medium">Agent ID:</span> {serverId}
</div>
<div>
<span className="font-medium">{t('osType')}:</span> {formData.osType}
<span className="font-medium">OS Type:</span> {formData.osType}
</div>
<div>
<span className="font-medium">{t('checkInterval')}:</span> {formData.checkInterval}s
<span className="font-medium">Check Interval:</span> {formData.checkInterval}s
</div>
</div>
</div>
@@ -96,7 +93,7 @@ export const ManualInstallTab: React.FC<ManualInstallTabProps> = ({
onClick={() => copyToClipboard(step.command)}
>
<Copy className="h-4 w-4 mr-1" />
{t('copy')}
Copy
</Button>
</div>
</div>
@@ -104,22 +101,22 @@ export const ManualInstallTab: React.FC<ManualInstallTabProps> = ({
</div>
<div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-md p-4">
<h4 className="font-medium text-blue-900 dark:text-blue-100 mb-2">{t('prerequisites')}</h4>
<h4 className="font-medium text-blue-900 dark:text-blue-100 mb-2">Prerequisites:</h4>
<ul className="text-sm text-blue-800 dark:text-blue-200 space-y-1 list-disc list-inside mb-3">
<li>{t('prereqRoot')}</li>
<li>{t('prereqCurl')}</li>
<li>{t('prereqInternet')}</li>
<li>Ensure you have root/sudo access on the target server</li>
<li>Make sure curl is installed for downloading files</li>
<li>Internet connection required for downloading script</li>
</ul>
<h4 className="font-medium text-blue-900 dark:text-blue-100 mb-2">{t('afterInstall')}</h4>
<h4 className="font-medium text-blue-900 dark:text-blue-100 mb-2">After Installation:</h4>
<p className="text-sm text-blue-800 dark:text-blue-200">
{t('agentWillStart')}
The agent will start automatically and appear in your dashboard within a few minutes.
</p>
</div>
<div className="flex justify-end pt-4">
<Button onClick={onDialogClose}>
{t('done')}
Done
</Button>
</div>
</CardContent>
@@ -5,7 +5,6 @@ import { Label } from "@/components/ui/label";
import { Copy, Download } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { copyToClipboard } from "@/utils/copyUtils";
import { useLanguage } from "@/contexts/LanguageContext";
interface OneClickInstallTabProps {
serverToken: string;
@@ -27,8 +26,6 @@ export const OneClickInstallTab: React.FC<OneClickInstallTabProps> = ({
serverId,
onDialogClose,
}) => {
const { t } = useLanguage();
const getOneClickInstallCommand = () => {
const scriptUrl = "https://cdn.checkcle.io/scripts/server-agent.sh";
@@ -58,15 +55,15 @@ sudo -E bash ./server-agent.sh`;
<CardHeader>
<CardTitle className="flex items-center gap-2 text-green-700 dark:text-green-400">
<Download className="h-5 w-5" />
{t('oneClickInstallTitle')}
One-Click Install (Recommended)
</CardTitle>
<CardDescription className="text-green-600 dark:text-green-300">
{t('oneClickInstallDesc')}
Copy and paste this single command to install the monitoring agent instantly
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label className="text-green-700 dark:text-green-400">{t('quickInstallCommand')}</Label>
<Label className="text-green-700 dark:text-green-400">Quick Install Command</Label>
<div className="relative">
<pre className="bg-black-50 dark:bg-green-100/950 border border-green-200 dark:border-green-800 p-4 rounded-md text-sm overflow-x-auto whitespace-pre-wrap break-all text-green-800 dark:text-green-200">
<code>{getOneClickInstallCommand()}</code>
@@ -79,23 +76,23 @@ sudo -E bash ./server-agent.sh`;
onClick={handleCopyCommand}
>
<Copy className="h-4 w-4 mr-1" />
{t('copy')}
Copy
</Button>
</div>
</div>
<div className="text-sm text-green-700 dark:text-green-300 bg-green-50 dark:bg-green-950/50 border border-green-200 dark:border-green-800 p-3 rounded-md">
<p className="font-medium mb-1">{t('runCommandOnServer')}</p>
<p className="font-medium mb-1">Simply run this command on your server:</p>
<ol className="list-decimal list-inside space-y-1 text-xs">
<li>{t('sshIntoServer')}</li>
<li>{t('pasteAndRun')}</li>
<li>{t('agentInstalled')}</li>
<li>SSH into your target server</li>
<li>Paste and run the command above</li>
<li>The agent will be installed and started automatically</li>
</ol>
</div>
<div className="flex justify-end pt-4">
<Button onClick={onDialogClose}>
{t('done')}
Done
</Button>
</div>
</CardContent>
@@ -7,7 +7,6 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { Copy } from "lucide-react";
import { copyToClipboard } from "@/utils/copyUtils";
import { OSSelector } from "./OSSelector";
import { useLanguage } from "@/contexts/LanguageContext";
interface ServerAgentConfigFormProps {
formData: {
@@ -44,25 +43,23 @@ export const ServerAgentConfigForm: React.FC<ServerAgentConfigFormProps> = ({
isSubmitting,
onSubmit,
}) => {
const { t } = useLanguage();
return (
<form onSubmit={onSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="serverName">{t('serverName')} *</Label>
<Label htmlFor="serverName">Server Name *</Label>
<Input
id="serverName"
placeholder={t('serverNamePlaceholder')}
placeholder="e.g., web-server-01"
value={formData.serverName}
onChange={(e) => setFormData(prev => ({ ...prev, serverName: e.target.value }))}
required
/>
<p className="text-xs text-muted-foreground">{t('serverNameDesc')}</p>
<p className="text-xs text-muted-foreground">What is the name or label used as the identifier</p>
</div>
<div className="space-y-2">
<Label htmlFor="serverId">{t('serverAgentId')}</Label>
<Label htmlFor="serverId">Server Agent ID</Label>
<div className="flex gap-2">
<Input
id="serverId"
@@ -79,13 +76,13 @@ export const ServerAgentConfigForm: React.FC<ServerAgentConfigFormProps> = ({
<Copy className="h-4 w-4" />
</Button>
</div>
<p className="text-xs text-muted-foreground">{t('serverAgentIdDesc')}</p>
<p className="text-xs text-muted-foreground">Auto-generated unique identifier</p>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>{t('operatingSystem')} *</Label>
<Label>Operating System *</Label>
<OSSelector
value={formData.osType}
onValueChange={(value) => setFormData(prev => ({ ...prev, osType: value }))}
@@ -94,45 +91,45 @@ export const ServerAgentConfigForm: React.FC<ServerAgentConfigFormProps> = ({
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="checkInterval">{t('checkInterval')}</Label>
<Label htmlFor="checkInterval">Check Interval</Label>
<Select
value={formData.checkInterval}
onValueChange={(value) => setFormData(prev => ({ ...prev, checkInterval: value }))}
>
<SelectTrigger>
<SelectValue placeholder={t('selectInterval')} />
<SelectValue placeholder="Select interval" />
</SelectTrigger>
<SelectContent>
<SelectItem value="30">{t('interval30s')}</SelectItem>
<SelectItem value="60">{t('interval1m')}</SelectItem>
<SelectItem value="120">{t('interval2m')}</SelectItem>
<SelectItem value="300">{t('interval5m')}</SelectItem>
<SelectItem value="30">30 seconds</SelectItem>
<SelectItem value="60">1 minute</SelectItem>
<SelectItem value="120">2 minutes</SelectItem>
<SelectItem value="300">5 minutes</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">{t('checkIntervalDesc')}</p>
<p className="text-xs text-muted-foreground">How often to check the server and metric status</p>
</div>
<div className="space-y-2">
<Label htmlFor="retryAttempt">{t('retryAttempts')}</Label>
<Label htmlFor="retryAttempt">Retry Attempts</Label>
<Select
value={formData.retryAttempt}
onValueChange={(value) => setFormData(prev => ({ ...prev, retryAttempt: value }))}
>
<SelectTrigger>
<SelectValue placeholder={t('selectRetryAttempts')} />
<SelectValue placeholder="Select retry attempts" />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">{t('attempt1')}</SelectItem>
<SelectItem value="2">{t('attempt2')}</SelectItem>
<SelectItem value="3">{t('attempt3')}</SelectItem>
<SelectItem value="5">{t('attempt5')}</SelectItem>
<SelectItem value="1">1 attempt</SelectItem>
<SelectItem value="2">2 attempts</SelectItem>
<SelectItem value="3">3 attempts</SelectItem>
<SelectItem value="5">5 attempts</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">{t('retryAttemptsDesc')}</p>
<p className="text-xs text-muted-foreground">Number of retry attempts before marking as down</p>
</div>
<div className="space-y-2">
<Label>{t('serverToken')}</Label>
<Label>Server Token</Label>
<div className="flex gap-2">
<Input value={serverToken} readOnly className="font-mono text-sm bg-muted" />
<Button
@@ -144,11 +141,11 @@ export const ServerAgentConfigForm: React.FC<ServerAgentConfigFormProps> = ({
<Copy className="h-4 w-4" />
</Button>
</div>
<p className="text-xs text-muted-foreground">{t('serverTokenDesc')}</p>
<p className="text-xs text-muted-foreground">Auto-generated authentication token</p>
</div>
<div className="space-y-2">
<Label>{t('systemUrl')}</Label>
<Label>System URL</Label>
<div className="flex gap-2">
<Input value={currentPocketBaseUrl} readOnly className="font-mono text-sm bg-muted" />
<Button
@@ -160,14 +157,14 @@ export const ServerAgentConfigForm: React.FC<ServerAgentConfigFormProps> = ({
<Copy className="h-4 w-4" />
</Button>
</div>
<p className="text-xs text-muted-foreground">{t('systemUrlDesc')}</p>
<p className="text-xs text-muted-foreground">Current system API URL</p>
</div>
</div>
</div>
<div className="pt-4">
<Button type="submit" disabled={isSubmitting} className="w-full">
{isSubmitting ? t('creatingAgent') : t('createServerAgent')}
{isSubmitting ? "Creating Agent..." : "Create Server Agent"}
</Button>
</div>
</form>
@@ -8,14 +8,12 @@ import { CPUChart } from "./charts/CPUChart";
import { MemoryChart } from "./charts/MemoryChart";
import { DiskChart } from "./charts/DiskChart";
import { NetworkChart } from "./charts/NetworkChart";
import { useLanguage } from "@/contexts/LanguageContext";
interface ServerHistoryChartsProps {
serverId: string;
}
export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => {
const { t } = useLanguage();
const {
timeRange,
setTimeRange,
@@ -35,15 +33,15 @@ export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => {
// Show skeleton loading state for better UX
if (isLoading) {
return (
return (
<div className="space-y-6">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-2">
<TrendingUp className="h-5 w-5" />
<h2 className="text-lg font-medium">{t("historicalPerformance")}</h2>
<h2 className="text-lg font-medium">Historical Performance</h2>
<div className="flex items-center gap-2 ml-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span className="text-xs text-muted-foreground">{t("loading")}</span>
<span className="text-xs text-muted-foreground">Loading...</span>
</div>
</div>
<TimeRangeSelector value={timeRange} onChange={setTimeRange} />
@@ -79,7 +77,7 @@ export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => {
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<TrendingUp className="h-5 w-5" />
<h2 className="text-lg font-medium">{t("historicalPerformance")}</h2>
<h2 className="text-lg font-medium">Historical Performance</h2>
{isFetching && <Loader2 className="h-4 w-4 animate-spin ml-2" />}
</div>
<TimeRangeSelector value={timeRange} onChange={setTimeRange} />
@@ -87,9 +85,9 @@ export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => {
<Card>
<CardContent className="flex items-center justify-center py-12">
<div className="text-center">
<p className="text-muted-foreground">{t("errorLoadingChartData")}</p>
<p className="text-muted-foreground">Error loading chart data</p>
<p className="text-xs mt-2 font-mono text-red-500">{error?.message}</p>
<p className="text-xs mt-1 text-muted-foreground">{t("serverIdTimeRange", { serverId, timeRange })}</p>
<p className="text-xs mt-1 text-muted-foreground">Server ID: {serverId} Time Range: {timeRange}</p>
</div>
</CardContent>
</Card>
@@ -103,7 +101,7 @@ export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => {
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<TrendingUp className="h-5 w-5" />
<h2 className="text-lg font-medium">{t("historicalPerformance")}</h2>
<h2 className="text-lg font-medium">Historical Performance</h2>
{isFetching && <Loader2 className="h-4 w-4 animate-spin ml-2" />}
</div>
<TimeRangeSelector value={timeRange} onChange={setTimeRange} />
@@ -111,13 +109,11 @@ export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => {
<Card>
<CardContent className="flex items-center justify-center py-12">
<div className="text-center">
<p className="text-muted-foreground">{t("noHistoricalData", { timeRange })}</p>
<p className="text-xs mt-2">{t("rawMetricsCount", { count: metrics.length })}</p>
<p className="text-xs mt-1">{t("serverIdTimeRange", { serverId, timeRange })}</p>
<p className="text-muted-foreground">No historical data available for {timeRange}</p>
<p className="text-xs mt-2">Raw metrics count: {metrics.length}</p>
<p className="text-xs mt-1">Server ID: {serverId} Time Range: {timeRange}</p>
<p className="text-xs mt-1 text-muted-foreground">
{metrics.length > 0
? t("dataExistsOutsideRange")
: t("noMetricsDataFound")}
{metrics.length > 0 ? 'Data exists but may be outside selected time range' : 'No metrics data found'}
</p>
</div>
</CardContent>
@@ -133,13 +129,13 @@ export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => {
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div className="flex items-center gap-2">
<TrendingUp className="h-5 w-5" />
<h2 className="text-lg font-medium">{t("historicalPerformance")}</h2>
<h2 className="text-lg font-medium">Historical Performance</h2>
<span className="text-xs text-muted-foreground">
({chartData.length} data points {timeRange})
{isFetching && (
<span className="inline-flex items-center gap-1 ml-2">
<Loader2 className="h-3 w-3 animate-spin" />
<span className="text-blue-500">{t("updating")}</span>
<span className="text-blue-500">Updating...</span>
</span>
)}
</span>
@@ -3,19 +3,17 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Server, Activity, AlertTriangle, Power } from "lucide-react";
import { ServerStats } from "@/types/server.types";
import { useTheme } from "@/contexts/ThemeContext";
import { useLanguage } from "@/contexts/LanguageContext";
interface ServerStatsCardsProps {
stats: ServerStats;
}
export const ServerStatsCards = ({ stats }: ServerStatsCardsProps) => {
const { t } = useLanguage();
const { theme } = useTheme();
const cards = [
{
title: t('totalServers', 'instance'),
title: "TOTAL SERVERS",
value: stats.total,
icon: Server,
gradient: theme === 'dark'
@@ -23,7 +21,7 @@ export const ServerStatsCards = ({ stats }: ServerStatsCardsProps) => {
: "linear-gradient(135deg, rgba(65, 59, 55, 0.8) 0%, #a0522d 100%)"
},
{
title: t('onlineServers', 'instance'),
title: "ONLINE SERVERS",
value: stats.online,
icon: Activity,
gradient: theme === 'dark'
@@ -31,7 +29,7 @@ export const ServerStatsCards = ({ stats }: ServerStatsCardsProps) => {
: "linear-gradient(135deg, rgba(65, 59, 55, 0.8) 0%, #66bb6a 100%)"
},
{
title: t('offlineServers', 'instance'),
title: "OFFLINE SERVERS",
value: stats.offline,
icon: Power,
gradient: theme === 'dark'
@@ -39,7 +37,7 @@ export const ServerStatsCards = ({ stats }: ServerStatsCardsProps) => {
: "linear-gradient(135deg, rgba(65, 59, 55, 0.8) 0%, #ef5350 100%)"
},
{
title: t('warningServers', 'instance'),
title: "WARNING SERVERS",
value: stats.warning,
icon: AlertTriangle,
gradient: theme === 'dark'
+283 -225
View File
@@ -1,14 +1,45 @@
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { RefreshCw, Search, Eye, Activity, MoreHorizontal, Pause, Play, Edit, Trash2 } from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
RefreshCw,
Search,
Eye,
Activity,
MoreHorizontal,
Pause,
Play,
Edit,
Trash2,
} from "lucide-react";
import { Server } from "@/types/server.types";
import { ServerStatusBadge } from "./ServerStatusBadge";
import { OSTypeIcon } from "./OSTypeIcon";
@@ -17,7 +48,6 @@ import { serverService } from "@/services/serverService";
import { useToast } from "@/hooks/use-toast";
import { pb } from "@/lib/pocketbase";
import { useTheme } from "@/contexts/ThemeContext";
import { useLanguage } from "@/contexts/LanguageContext";
interface ServerTableProps {
servers: Server[];
@@ -25,8 +55,11 @@ interface ServerTableProps {
onRefresh: () => void;
}
export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps) => {
const { t } = useLanguage();
export const ServerTable = ({
servers,
isLoading,
onRefresh,
}: ServerTableProps) => {
const { theme } = useTheme();
const [searchTerm, setSearchTerm] = useState("");
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
@@ -34,37 +67,16 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
const [selectedServer, setSelectedServer] = useState<Server | null>(null);
const [isDeleting, setIsDeleting] = useState(false);
const [pausingServers, setPausingServers] = useState<Set<string>>(new Set());
const [selectedServerIds, setSelectedServerIds] = useState<Set<string>>(new Set());
const [bulkDeleteDialogOpen, setBulkDeleteDialogOpen] = useState(false);
const [isBulkDeleting, setIsBulkDeleting] = useState(false);
const navigate = useNavigate();
const { toast } = useToast();
const filteredServers = servers.filter(server =>
server.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
server.hostname.toLowerCase().includes(searchTerm.toLowerCase()) ||
server.ip_address.toLowerCase().includes(searchTerm.toLowerCase())
const filteredServers = servers.filter(
(server) =>
server.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
server.hostname.toLowerCase().includes(searchTerm.toLowerCase()) ||
server.ip_address.toLowerCase().includes(searchTerm.toLowerCase())
);
const allVisibleSelected = filteredServers.length > 0 && filteredServers.every(s => selectedServerIds.has(s.id));
const someVisibleSelected = filteredServers.some(s => selectedServerIds.has(s.id)) && !allVisibleSelected;
const toggleSelectAllVisible = (checked: boolean) => {
const newSet = new Set(selectedServerIds);
if (checked) {
filteredServers.forEach(s => newSet.add(s.id));
} else {
filteredServers.forEach(s => newSet.delete(s.id));
}
setSelectedServerIds(newSet);
};
const toggleSelectOne = (serverId: string, checked: boolean) => {
const newSet = new Set(selectedServerIds);
if (checked) newSet.add(serverId); else newSet.delete(serverId);
setSelectedServerIds(newSet);
};
const handleViewDetails = (serverId: string) => {
navigate(`/server-detail/${serverId}`);
};
@@ -76,41 +88,44 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
const handlePauseResume = async (server: Server) => {
const serverId = server.id;
const isPaused = server.status === "paused";
if (pausingServers.has(serverId)) {
return; // Already processing this server
}
try {
setPausingServers(prev => new Set(prev).add(serverId));
setPausingServers((prev) => new Set(prev).add(serverId));
// Only update the status field, preserving all other server configuration
const updateData = {
status: isPaused ? "up" : "paused",
last_checked: new Date().toISOString()
last_checked: new Date().toISOString(),
};
await pb.collection('servers').update(serverId, updateData);
await pb.collection("servers").update(serverId, updateData);
toast({
title: isPaused ? t('serverResumed') : t('serverPaused'),
description: isPaused ? t('monitoringResumed', { name: server.name }) : t('monitoringPaused', { name: server.name }),
title: isPaused ? "Server resumed" : "Server paused",
description: `Monitoring ${isPaused ? "resumed" : "paused"} for ${
server.name
}`,
});
// console.log(`${isPaused ? 'Resume' : 'Pause'} server monitoring: ${serverId}`);
// console.log(`${isPaused ? 'Resume' : 'Pause'} server monitoring: ${serverId}`);
// Refresh the server list to show updated status
onRefresh();
} catch (error) {
// console.error('Error updating server status:', error);
// console.error('Error updating server status:', error);
toast({
variant: "destructive",
title: t('error'),
description: isPaused ? t('resumeServerError') : t('pauseServerError'),
title: "Error",
description: `Failed to ${
isPaused ? "resume" : "pause"
} server monitoring. Please try again.`,
});
} finally {
setPausingServers(prev => {
setPausingServers((prev) => {
const newSet = new Set(prev);
newSet.delete(serverId);
return newSet;
@@ -133,24 +148,23 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
try {
setIsDeleting(true);
// Delete the server from the database
await pb.collection('servers').delete(selectedServer.id);
await pb.collection("servers").delete(selectedServer.id);
toast({
title: "Server deleted",
description: `${selectedServer.name} has been deleted successfully.`,
});
// Refresh the server list
onRefresh();
// Close the dialog
setDeleteDialogOpen(false);
setSelectedServer(null);
} catch (error) {
// console.error('Error deleting server:', error);
// console.error('Error deleting server:', error);
toast({
variant: "destructive",
title: "Error",
@@ -161,92 +175,65 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
}
};
const confirmBulkDelete = async () => {
if (selectedServerIds.size === 0 || isBulkDeleting) return;
try {
setIsBulkDeleting(true);
const ids = Array.from(selectedServerIds);
const deletions = ids.map(id => pb.collection('servers').delete(id));
const results = await Promise.allSettled(deletions);
const failed = results.filter(r => r.status === 'rejected').length;
if (failed === 0) {
toast({ title: "Servers deleted", description: `${ids.length} server(s) have been deleted.` });
} else if (failed === ids.length) {
toast({ variant: "destructive", title: "Error", description: "Failed to delete selected servers. Please try again." });
} else {
toast({ variant: "destructive", title: "Partial success", description: `Deleted ${ids.length - failed}, failed ${failed}.` });
}
onRefresh();
setSelectedServerIds(new Set());
setBulkDeleteDialogOpen(false);
} catch (_e) {
toast({ variant: "destructive", title: "Error", description: "Failed to delete selected servers. Please try again." });
} finally {
setIsBulkDeleting(false);
}
};
const CustomProgressBar = ({
value,
label,
subtitle,
type
}: {
value: number;
label: string;
subtitle: string;
type: 'cpu' | 'memory' | 'disk'
const CustomProgressBar = ({
value,
label,
subtitle,
type,
}: {
value: number;
label: string;
subtitle: string;
type: "cpu" | "memory" | "disk";
}) => {
const getGradientColors = (type: string, value: number) => {
if (type === 'cpu') {
if (value > 90) return 'from-red-500 to-red-600';
if (value > 75) return 'from-orange-500 to-orange-600';
if (value > 60) return 'from-yellow-500 to-yellow-600';
return 'from-green-500 to-green-600';
if (type === "cpu") {
if (value > 90) return "from-red-500 to-red-600";
if (value > 75) return "from-orange-500 to-orange-600";
if (value > 60) return "from-yellow-500 to-yellow-600";
return "from-green-500 to-green-600";
}
if (type === 'memory') {
if (value > 90) return 'from-red-500 to-red-600';
if (value > 75) return 'from-yellow-500 to-yellow-600';
return 'from-blue-500 to-blue-600';
if (type === "memory") {
if (value > 90) return "from-red-500 to-red-600";
if (value > 75) return "from-yellow-500 to-yellow-600";
return "from-blue-500 to-blue-600";
}
if (type === 'disk') {
if (value > 95) return 'from-red-500 to-red-600';
if (value > 85) return 'from-yellow-500 to-yellow-600';
return 'from-orange-500 to-orange-600';
if (type === "disk") {
if (value > 95) return "from-red-500 to-red-600";
if (value > 85) return "from-yellow-500 to-yellow-600";
return "from-orange-500 to-orange-600";
}
return 'from-gray-500 to-gray-600';
return "from-gray-500 to-gray-600";
};
const getTextColor = (value: number) => {
if (value > 90) return 'text-red-600 dark:text-red-400';
if (value > 75) return 'text-orange-600 dark:text-orange-400';
if (value > 60) return 'text-yellow-600 dark:text-yellow-400';
return 'text-green-600 dark:text-green-400';
if (value > 90) return "text-red-600 dark:text-red-400";
if (value > 75) return "text-orange-600 dark:text-orange-400";
if (value > 60) return "text-yellow-600 dark:text-yellow-400";
return "text-green-600 dark:text-green-400";
};
return (
<div className="space-y-2 min-w-[120px]">
<div className="space-y-2 min-w-[120px] -mt-20">
<div className="flex justify-between items-center">
<span className={`text-sm font-semibold ${getTextColor(value)}`}>
{label}
</span>
<span className="text-xs text-muted-foreground">
{subtitle}
</span>
<span className="text-xs text-muted-foreground">{subtitle} </span>
</div>
<div className="relative">
<div className="w-full h-3 bg-muted/30 rounded-full overflow-hidden shadow-inner">
<div
className={`h-full bg-gradient-to-r ${getGradientColors(type, value)} rounded-full transition-all duration-700 ease-out relative overflow-hidden`}
<div
className={`h-full bg-gradient-to-r ${getGradientColors(
type,
value
)} rounded-full transition-all duration-700 ease-out relative overflow-hidden`}
style={{ width: `${Math.min(value, 100)}%` }}
>
<div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent animate-pulse opacity-60" />
<div className="absolute inset-0 bg-gradient-to-t from-black/10 to-white/10" />
</div>
</div>
</div>
</div>
);
@@ -254,14 +241,14 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
if (isLoading) {
return (
<Card className="flex-1 flex flex-col">
<Card className="flex-1 flex flex-col ">
<CardHeader className="flex-shrink-0">
<CardTitle>{t('servers')}</CardTitle>
<CardTitle>Servers</CardTitle>
</CardHeader>
<CardContent className="flex-1 flex items-center justify-center">
<div className="flex items-center justify-center h-32">
<RefreshCw className="h-6 w-6 animate-spin" />
<span className="ml-2">{t('loadingServers')}</span>
<span className="ml-2">Loading servers...</span>
</div>
</CardContent>
</Card>
@@ -273,29 +260,17 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
<Card className="bg-transparent border-0 shadow-none">
<CardHeader className="pb-4 px-0">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<CardTitle className="text-xl font-semibold">{t('servers')}</CardTitle>
<CardTitle className="text-xl font-semibold">Servers</CardTitle>
<div className="flex items-center gap-2">
<div className="relative flex-1 sm:w-64">
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder={t('searchServersPlaceholder')}
placeholder="Search servers..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-8"
/>
</div>
{selectedServerIds.size > 0 && (
<div className="hidden sm:block text-sm text-muted-foreground mr-2">
{selectedServerIds.size} selected
</div>
)}
<Button
onClick={() => setBulkDeleteDialogOpen(true)}
variant="destructive"
disabled={selectedServerIds.size === 0}
>
Delete Selected
</Button>
<Button onClick={onRefresh} variant="outline" size="icon">
<RefreshCw className="h-4 w-4" />
</Button>
@@ -305,57 +280,119 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
<CardContent className="p-0">
{filteredServers.length === 0 ? (
<div className="flex items-center justify-center p-8">
<p className="text-muted-foreground">{t('noServersFound')}</p>
<p className="text-muted-foreground">No servers found</p>
</div>
) : (
<div className={`${theme === 'dark' ? 'bg-gray-900' : 'bg-white'} rounded-lg border border-border shadow-sm`}>
<div
className={`${
theme === "dark" ? "bg-gray-900" : "bg-white"
} rounded-lg border border-border shadow-sm`}
>
<Table>
<TableHeader className={`${theme === 'dark' ? 'bg-gray-800' : 'bg-gray-50'}`}>
<TableRow className={`${theme === 'dark' ? 'border-gray-700 hover:bg-gray-800' : 'border-gray-200 hover:bg-gray-100'}`}>
<TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} w-10`}>
<div onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={allVisibleSelected}
onCheckedChange={(v) => toggleSelectAllVisible(Boolean(v))}
aria-label="Select all"
indeterminate={someVisibleSelected}
/>
</div>
<TableHeader
className={`${
theme === "dark" ? "bg-gray-800" : "bg-gray-50"
}`}
>
<TableRow
className={`${
theme === "dark"
? "border-gray-700 hover:bg-gray-800"
: "border-gray-200 hover:bg-gray-100"
}`}
>
<TableHead
className={`${
theme === "dark" ? "text-gray-300" : "text-gray-700"
} font-medium text-base py-4`}
>
Name
</TableHead>
<TableHead
className={`${
theme === "dark" ? "text-gray-300" : "text-gray-700"
} font-medium text-base py-4`}
>
Status
</TableHead>
<TableHead
className={`${
theme === "dark" ? "text-gray-300" : "text-gray-700"
} font-medium text-base py-4`}
>
OS
</TableHead>
<TableHead
className={`${
theme === "dark" ? "text-gray-300" : "text-gray-700"
} font-medium text-base py-4`}
>
IP Address
</TableHead>
<TableHead
className={`${
theme === "dark" ? "text-gray-300" : "text-gray-700"
} font-medium text-base py-4`}
>
CPU
</TableHead>
<TableHead
className={`${
theme === "dark" ? "text-gray-300" : "text-gray-700"
} font-medium text-base py-4`}
>
Memory
</TableHead>
<TableHead
className={`${
theme === "dark" ? "text-gray-300" : "text-gray-700"
} font-medium text-base py-4`}
>
Disk
</TableHead>
<TableHead
className={`${
theme === "dark" ? "text-gray-300" : "text-gray-700"
} font-medium text-base py-4`}
>
Uptime
</TableHead>
<TableHead
className={`${
theme === "dark" ? "text-gray-300" : "text-gray-700"
} font-medium text-base py-4`}
>
Last Checked
</TableHead>
<TableHead
className={`${
theme === "dark" ? "text-gray-300" : "text-gray-700"
} font-medium text-base py-4 text-right`}
>
Actions
</TableHead>
<TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>{t('name')}</TableHead>
<TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>{t('status')}</TableHead>
<TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>{t('OS')}</TableHead>
<TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>{t('IPAddress')}</TableHead>
<TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>{t('CPU')}</TableHead>
<TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>{t('memory')}</TableHead>
<TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>{t('disk')}</TableHead>
<TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>{t('uptime')}</TableHead>
<TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>{t('lastChecked')}</TableHead>
<TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4 text-right`}>{t('actions')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredServers.map((server) => {
const cpuUsage = server.cpu_usage || 0;
const memoryUsage = server.ram_total > 0 ? (server.ram_used / server.ram_total) * 100 : 0;
const diskUsage = server.disk_total > 0 ? (server.disk_used / server.disk_total) * 100 : 0;
const memoryUsage =
server.ram_total > 0
? (server.ram_used / server.ram_total) * 100
: 0;
const diskUsage =
server.disk_total > 0
? (server.disk_used / server.disk_total) * 100
: 0;
const isPaused = server.status === "paused";
const isProcessing = pausingServers.has(server.id);
const isSelected = selectedServerIds.has(server.id);
return (
<TableRow
key={server.id}
className={`hover:bg-muted/50 cursor-pointer ${isSelected ? 'bg-muted/30' : ''}`}
<TableRow
key={server.id}
className="hover:bg-muted/50 cursor-pointer"
onClick={() => handleViewDetails(server.id)}
>
<TableCell onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={isSelected}
onCheckedChange={(v) => toggleSelectOne(server.id, Boolean(v))}
aria-label={`Select ${server.name}`}
/>
</TableCell>
<TableCell className="font-medium">
<div className="truncate" title={server.name}>
{server.name}
@@ -367,7 +404,10 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
<TableCell>
<div className="flex items-center gap-2">
<OSTypeIcon osType={server.os_type} />
<span className="text-sm truncate" title={server.os_type}>
<span
className="text-sm truncate"
title={server.os_type}
>
{server.os_type}
</span>
</div>
@@ -389,7 +429,9 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
<CustomProgressBar
value={memoryUsage}
label={`${memoryUsage.toFixed(1)}%`}
subtitle={serverService.formatBytes(server.ram_total)}
subtitle={serverService.formatBytes(
server.ram_total
)}
type="memory"
/>
</TableCell>
@@ -397,12 +439,17 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
<CustomProgressBar
value={diskUsage}
label={`${diskUsage.toFixed(1)}%`}
subtitle={serverService.formatBytes(server.disk_total)}
subtitle={serverService.formatBytes(
server.disk_total
)}
type="disk"
/>
</TableCell>
<TableCell>
<div className="text-sm truncate" title={server.uptime}>
<div
className="text-sm truncate"
title={server.uptime}
>
{server.uptime}
</div>
</TableCell>
@@ -411,11 +458,18 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
{new Date(server.last_checked).toLocaleString()}
</div>
</TableCell>
<TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
<TableCell
className="text-right"
onClick={(e) => e.stopPropagation()}
>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0" disabled={isProcessing}>
<span className="sr-only">{t('openMenu')}</span>
<Button
variant="ghost"
className="h-8 w-8 p-0"
disabled={isProcessing}
>
<span className="sr-only">Open menu</span>
{isProcessing ? (
<RefreshCw className="h-4 w-4 animate-spin" />
) : (
@@ -423,45 +477,69 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-[200px]">
<DropdownMenuItem onClick={(e) => { e.stopPropagation(); handleViewDetails(server.id); }}>
<DropdownMenuContent
align="end"
className="w-[200px]"
>
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
handleViewDetails(server.id);
}}
>
<Eye className="mr-2 h-4 w-4" />
{t('viewServerDetail')}
View Server Detail
</DropdownMenuItem>
{server.docker === 'true' && (
<DropdownMenuItem onClick={(e) => { e.stopPropagation(); handleViewContainers(server.id); }}>
{server.docker === "true" && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
handleViewContainers(server.id);
}}
>
<Activity className="mr-2 h-4 w-4" />
{t('containerMonitoring')}
Container Monitoring
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={(e) => { e.stopPropagation(); handlePauseResume(server); }}
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
handlePauseResume(server);
}}
disabled={isProcessing}
>
{isPaused ? (
<>
<Play className="mr-2 h-4 w-4" />
{t('resumeMonitoring')}
Resume Monitoring
</>
) : (
<>
<Pause className="mr-2 h-4 w-4" />
{t('pauseMonitoring')}
Pause Monitoring
</>
)}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={(e) => { e.stopPropagation(); handleEdit(server); }}>
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
handleEdit(server);
}}
>
<Edit className="mr-2 h-4 w-4" />
{t('editServer')}
Edit Server
</DropdownMenuItem>
<DropdownMenuItem
onClick={(e) => { e.stopPropagation(); handleDelete(server); }}
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
handleDelete(server);
}}
className="text-red-600 focus:text-red-600"
>
<Trash2 className="mr-2 h-4 w-4" />
{t('deleteServer')}
Delete Server
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -488,45 +566,25 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('deleteServerConfirmTitle')}</AlertDialogTitle>
<AlertDialogTitle>
Are you sure you want to delete this server?
</AlertDialogTitle>
<AlertDialogDescription>
{t('deleteServerConfirmDesc').replace('{name}', selectedServer?.name ?? '')}
This action cannot be undone. This will permanently delete{" "}
<span className="font-semibold text-foreground">
{selectedServer?.name}
</span>{" "}
and all of its monitoring data.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>
{t('cancel')}
</AlertDialogCancel>
<AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={confirmDelete}
disabled={isDeleting}
className="bg-red-600 text-white hover:bg-red-700"
>
{isDeleting ? t('deleting') : t('delete')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Bulk Delete Confirmation Dialog */}
<AlertDialog open={bulkDeleteDialogOpen} onOpenChange={setBulkDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete selected servers?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently delete {selectedServerIds.size} server(s) and all of their monitoring data.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isBulkDeleting}>
{t('cancel')}
</AlertDialogCancel>
<AlertDialogAction
onClick={confirmBulkDelete}
disabled={isBulkDeleting}
className="bg-red-600 text-white hover:bg-red-700"
>
{isBulkDeleting ? t('deleting') : 'Delete Selected'}
{isDeleting ? "Deleting..." : "Delete"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -1,3 +1,4 @@
import React from "react";
import { Sidebar } from "@/components/dashboard/Sidebar";
import { Header } from "@/components/dashboard/Header";
@@ -6,9 +7,11 @@ import { ServiceNotFound } from "@/components/services/ServiceNotFound";
import { Service } from "@/types/service.types";
interface ServiceDetailWrapperProps {
children?: React.ReactNode;
children: React.ReactNode;
isLoading: boolean;
service: Service | null;
sidebarCollapsed: boolean;
toggleSidebar: () => void;
currentUser: any;
handleLogout: () => void;
}
@@ -17,16 +20,20 @@ export const ServiceDetailWrapper = ({
children,
isLoading,
service,
sidebarCollapsed,
toggleSidebar,
currentUser,
handleLogout
}: ServiceDetailWrapperProps) => {
return (
<div className="flex h-screen w-full overflow-hidden bg-background text-foreground">
<Sidebar />
<Sidebar collapsed={sidebarCollapsed} />
<div className="flex flex-col flex-1 min-w-0">
<Header
currentUser={currentUser}
onLogout={handleLogout}
sidebarCollapsed={sidebarCollapsed}
toggleSidebar={toggleSidebar}
/>
{isLoading ? (
@@ -41,4 +48,4 @@ export const ServiceDetailWrapper = ({
</div>
</div>
);
};
};
@@ -1,34 +1,78 @@
import React, { useState, useCallback } from "react";
import { useState, useEffect, useCallback } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { DateRangeOption } from "../DateRangeFilter";
import { authService } from "@/services/authService";
import { ServiceDetailContent } from "../ServiceDetailContent";
import { ServiceDetailWrapper } from "./ServiceDetailWrapper";
import { useServiceData, useRealTimeUpdates } from "./hooks";
import { toast } from "@/components/ui/use-toast";
export const ServiceDetailContainer = () => {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
// Set default to 24h
const [startDate, setStartDate] = useState<Date>(() => {
const date = new Date();
date.setHours(date.getHours() - 24);
date.setHours(date.getHours() - 24); // Go back 24 hours
return date;
});
const [endDate, setEndDate] = useState<Date>(() => {
const date = new Date();
date.setMinutes(date.getMinutes() + 5);
date.setMinutes(date.getMinutes() + 5); // Add 5 minutes buffer to future
return date;
});
const [selectedRange, setSelectedRange] = useState<DateRangeOption>('24h');
// State for sidebar collapse functionality (shared with Dashboard)
const [sidebarCollapsed, setSidebarCollapsed] = useState(() => {
// Check if there's a saved preference in localStorage
const saved = localStorage.getItem("sidebarCollapsed");
return saved ? JSON.parse(saved) : window.innerWidth < 768;
});
// Toggle sidebar and save preference
const toggleSidebar = useCallback(() => {
setSidebarCollapsed(prev => {
const newState = !prev;
localStorage.setItem("sidebarCollapsed", JSON.stringify(newState));
return newState;
});
}, []);
// Get current user for header
const currentUser = authService.getCurrentUser();
useEffect(() => {
// Verify user is authenticated
if (!authService.isAuthenticated()) {
toast({
variant: "destructive",
title: "Authentication required",
description: "Please log in to view service details",
});
navigate("/login");
}
// Auto-collapse sidebar on small screens
const handleResize = () => {
if (window.innerWidth < 768 && !sidebarCollapsed) {
setSidebarCollapsed(true);
localStorage.setItem("sidebarCollapsed", JSON.stringify(true));
}
};
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, [navigate, sidebarCollapsed]);
// Handler for logout (same as Dashboard)
const handleLogout = () => {
authService.logout();
navigate("/login");
};
// Use our custom hooks
const {
service,
uptimeData,
@@ -41,6 +85,7 @@ export const ServiceDetailContainer = () => {
handleRegionalAgentChange
} = useServiceData(id, startDate, endDate);
// Set up real-time updates
useRealTimeUpdates({
serviceId: id,
startDate,
@@ -49,12 +94,18 @@ export const ServiceDetailContainer = () => {
setUptimeData
});
// Handle date range filter changes
const handleDateRangeChange = useCallback((start: Date, end: Date, option: DateRangeOption) => {
console.log(`ServiceDetailContainer: Date range changed: ${start.toISOString()} to ${end.toISOString()}, option: ${option}`);
// Update state which will trigger the useEffect in useServiceData
setStartDate(start);
setEndDate(end);
setSelectedRange(option);
// Also explicitly fetch data with the new range to ensure immediate update
if (id) {
console.log(`ServiceDetailContainer: Explicitly fetching data for service ${id} with new range`);
fetchUptimeData(id, start, end, option, selectedRegionalAgent);
}
}, [id, fetchUptimeData, selectedRegionalAgent]);
@@ -63,10 +114,12 @@ export const ServiceDetailContainer = () => {
<ServiceDetailWrapper
isLoading={isLoading}
service={service}
sidebarCollapsed={sidebarCollapsed}
toggleSidebar={toggleSidebar}
currentUser={currentUser}
handleLogout={handleLogout}
>
{service ? (
{service && (
<ServiceDetailContent
service={service}
uptimeData={uptimeData}
@@ -76,7 +129,7 @@ export const ServiceDetailContainer = () => {
selectedRegionalAgent={selectedRegionalAgent}
onRegionalAgentChange={handleRegionalAgentChange}
/>
) : null}
)}
</ServiceDetailWrapper>
);
};
@@ -63,9 +63,9 @@ export function ServicesPagination({
return (
<div className="flex items-center justify-between py-4 px-4 border-t border-border">
<div className="flex items-center space-x-2">
<span className="text-sm text-muted-foreground whitespace-nowrap">
{t("rowsPerPage") ?? "Rows per page"}:
</span>
<span className="text-sm text-muted-foreground">
{t("rowsPerPage") ?? "Rows per page"}:
</span>
<Select
value={pageSize.toString()}
onValueChange={(value) => onPageSizeChange(parseInt(value) as PageSize)}
@@ -25,10 +25,6 @@ export const useServiceSchema = () => {
type: z.enum(["http", "ping", "tcp", "dns"]),
url: z.string()
.min(1, t("urlDomainHostRequired"))
.refine(
(value) => !/\s/.test(value),
t("spacesNotAllowed")
)
.refine(
(value) => value.trim().length > 0,
t("enterValidUrlHostnameDomain")
@@ -158,14 +158,14 @@ const DataRetentionSettings = () => {
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Database className="h-5 w-5" />
{t("dataRetention")}
{t("dataRetention", "settings")}
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<Alert className="border-blue-200 bg-blue-50 dark:bg-blue-950 dark:border-blue-800">
<AlertTriangle className="h-5 w-5 text-blue-600 dark:text-blue-400" />
<AlertDescription className="text-blue-700 dark:text-blue-300">
<span className="font-medium">{t("permissionNotice")}</span> {t("permissionNoticeDataRetention")}
<span className="font-medium">Permission Notice:</span> As an admin user, you do not have access to data retention settings. These settings can only be accessed and modified by Super Admins.
</AlertDescription>
</Alert>
</CardContent>
@@ -178,7 +178,7 @@ const DataRetentionSettings = () => {
return (
<div className="p-4 flex items-center justify-center">
<Loader2 className="h-6 w-6 animate-spin mr-2" />
{t("loadingRetentionSettings")}
Loading retention settings...
</div>
);
}
@@ -189,16 +189,16 @@ const DataRetentionSettings = () => {
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Database className="h-5 w-5" />
{t("dataRetention")}
Data Retention Settings
</CardTitle>
<CardDescription>
{t("dataRetentionDescription")}
Configure how long monitoring data is kept in the system
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="space-y-4">
<div>
<Label htmlFor="uptimeRetention">{t("uptimeRetentionLabel")}</Label>
<Label htmlFor="uptimeRetention">Uptime Monitoring Retention (days)</Label>
<Input
id="uptimeRetention"
type="number"
@@ -218,12 +218,12 @@ const DataRetentionSettings = () => {
className="mt-1"
/>
<p className="text-sm text-muted-foreground mt-1">
{t("uptimeRetentionHelp")}
Service uptime and incident data older than this will be automatically deleted
</p>
</div>
<div>
<Label htmlFor="serverRetention">{t("serverRetentionLabel")}</Label>
<Label htmlFor="serverRetention">Server Monitoring Retention (days)</Label>
<Input
id="serverRetention"
type="number"
@@ -243,7 +243,7 @@ const DataRetentionSettings = () => {
className="mt-1"
/>
<p className="text-sm text-muted-foreground mt-1">
{t("serverRetentionHelp")}
Server metrics and process data older than this will be automatically deleted
</p>
</div>
</div>
@@ -252,7 +252,7 @@ const DataRetentionSettings = () => {
<Alert>
<Database className="h-4 w-4" />
<AlertDescription>
{t("lastCleanup")}: {new Date(lastCleanup).toLocaleString()}
Last automatic cleanup: {new Date(lastCleanup).toLocaleString()}
</AlertDescription>
</Alert>
)}
@@ -266,7 +266,7 @@ const DataRetentionSettings = () => {
{isSaving ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : null}
{t("save")}
Save Changes
</Button>
</CardFooter>
</Card>
@@ -38,7 +38,7 @@ interface NotificationChannelDialogProps {
const baseSchema = z.object({
notify_name: z.string().min(1, "Name is required"),
notification_type: z.enum(["telegram", "discord", "slack", "signal", "google_chat", "email", "ntfy", "pushover", "notifiarr", "gotify", "webhook", "matrix"]),
notification_type: z.enum(["telegram", "discord", "slack", "signal", "google_chat", "email", "ntfy", "pushover", "notifiarr", "gotify", "webhook"]),
enabled: z.boolean().default(true),
service_id: z.string().default("global"),
template_id: z.string().optional(),
@@ -110,13 +110,6 @@ const gotifySchema = baseSchema.extend({
server_url: z.string().url("Must be a valid server URL"),
});
const matrixSchema = baseSchema.extend({
notification_type: z.literal("matrix"),
matrix_homeserver: z.string().url("Must be a valid homeserver URL"),
matrix_room_id: z.string().min(1, "Room ID is required"),
matrix_access_token: z.string().min(1, "Access token is required"),
});
const formSchema = z.discriminatedUnion("notification_type", [
telegramSchema,
discordSchema,
@@ -129,7 +122,6 @@ const formSchema = z.discriminatedUnion("notification_type", [
notifiarrSchema,
gotifySchema,
webhookSchema,
matrixSchema,
]);
type FormValues = z.infer<typeof formSchema>;
@@ -196,18 +188,12 @@ const notificationTypeOptions = [
description: "Send push notifications via Gotify",
icon: "/upload/notification/gotify.png"
},
{
value: "webhook",
label: "Webhook",
{
value: "webhook",
label: "Webhook",
description: "Send notifications to custom webhook",
icon: "/upload/notification/webhook.png"
},
{
value: "matrix",
label: "Matrix",
description: "Send notifications to a Matrix chat room",
icon: "/upload/notification/matrix.png"
},
];
const webhookPayloadTemplates = {
@@ -261,7 +247,6 @@ export const NotificationChannelDialog = ({
onClose,
editingConfig
}: NotificationChannelDialogProps) => {
const { t } = useLanguage();
const isEditing = !!editingConfig;
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
@@ -340,7 +325,7 @@ export const NotificationChannelDialog = ({
<DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>
{isEditing ? t("editChannel") : t("addChannelDialog")}
{isEditing ? "Edit Notification Channel" : "Add Notification Channel"}
</DialogTitle>
</DialogHeader>
@@ -351,28 +336,28 @@ export const NotificationChannelDialog = ({
name="notify_name"
render={({ field }) => (
<FormItem>
<FormLabel>{t("channelName")}</FormLabel>
<FormLabel>Channel Name</FormLabel>
<FormControl>
<Input placeholder={t("channelNamePlaceholder")} {...field} />
<Input placeholder="My Notification Channel" {...field} />
</FormControl>
<FormDescription>
{t("channelNameDesc")}
A name to identify this notification channel
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="notification_type"
render={({ field }) => (
<FormItem>
<FormLabel>{t("channelType")}</FormLabel>
<FormLabel>Channel Type</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder={t("selectType")} />
<SelectValue placeholder="Select notification type" />
</SelectTrigger>
</FormControl>
<SelectContent>
@@ -385,8 +370,8 @@ export const NotificationChannelDialog = ({
className="w-5 h-5 object-contain"
/>
<div className="flex flex-col">
<span className="font-medium">{t(option.value)}</span>
<span className="text-xs text-muted-foreground">{t(option.description)}</span>
<span className="font-medium">{option.label}</span>
<span className="text-xs text-muted-foreground">{option.description}</span>
</div>
</div>
</SelectItem>
@@ -397,7 +382,7 @@ export const NotificationChannelDialog = ({
</FormItem>
)}
/>
{notificationType === "telegram" && (
<>
<FormField
@@ -405,12 +390,12 @@ export const NotificationChannelDialog = ({
name="telegram_chat_id"
render={({ field }) => (
<FormItem>
<FormLabel>{t("telegramChatId")}</FormLabel>
<FormLabel>Chat ID</FormLabel>
<FormControl>
<Input placeholder={t("telegramChatIdPlaceholder")} {...field} />
<Input placeholder="Telegram Chat ID" {...field} />
</FormControl>
<FormDescription>
{t("telegramChatIdDesc")}
The Telegram chat ID to send notifications to
</FormDescription>
<FormMessage />
</FormItem>
@@ -421,12 +406,12 @@ export const NotificationChannelDialog = ({
name="bot_token"
render={({ field }) => (
<FormItem>
<FormLabel>{t("botToken")}</FormLabel>
<FormLabel>Bot Token</FormLabel>
<FormControl>
<Input placeholder={t("botTokenPlaceholder")} {...field} type="password" />
<Input placeholder="Telegram Bot Token" {...field} type="password" />
</FormControl>
<FormDescription>
{t("botTokenDesc")}
Your Telegram bot token from @BotFather
</FormDescription>
<FormMessage />
</FormItem>
@@ -434,38 +419,38 @@ export const NotificationChannelDialog = ({
/>
</>
)}
{notificationType === "discord" && (
<FormField
control={form.control}
name="discord_webhook_url"
render={({ field }) => (
<FormItem>
<FormLabel>{t("discordWebhookUrl")}</FormLabel>
<FormLabel>Webhook URL</FormLabel>
<FormControl>
<Input placeholder={t("discordWebhookUrlPlaceholder")} {...field} />
<Input placeholder="https://discord.com/api/webhooks/..." {...field} />
</FormControl>
<FormDescription>
{t("discordWebhookUrlDesc")}
Discord webhook URL from your server settings
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
)}
{notificationType === "slack" && (
<FormField
control={form.control}
name="slack_webhook_url"
render={({ field }) => (
<FormItem>
<FormLabel>{t("slackWebhookUrl")}</FormLabel>
<FormLabel>Webhook URL</FormLabel>
<FormControl>
<Input placeholder={t("slackWebhookUrlPlaceholder")} {...field} />
<Input placeholder="https://hooks.slack.com/services/..." {...field} />
</FormControl>
<FormDescription>
{t("slackWebhookUrlDesc")}
Slack incoming webhook URL
</FormDescription>
<FormMessage />
</FormItem>
@@ -480,12 +465,12 @@ export const NotificationChannelDialog = ({
name="signal_number"
render={({ field }) => (
<FormItem>
<FormLabel>{t("signalNumber")}</FormLabel>
<FormLabel>Signal Number</FormLabel>
<FormControl>
<Input placeholder={t("signalNumberPlaceholder")} {...field} />
<Input placeholder="+1234567890" {...field} />
</FormControl>
<FormDescription>
{t("signalNumberDesc")}
Signal phone number to send notifications to
</FormDescription>
<FormMessage />
</FormItem>
@@ -496,12 +481,12 @@ export const NotificationChannelDialog = ({
name="signal_api_endpoint"
render={({ field }) => (
<FormItem>
<FormLabel>{t("signalApiEndpoint")}</FormLabel>
<FormLabel>Signal API Endpoint</FormLabel>
<FormControl>
<Input placeholder={t("signalApiEndpointPlaceholder")} {...field} />
<Input placeholder="https://your-signal-api.com/v2/send" {...field} />
</FormControl>
<FormDescription>
{t("signalApiEndpointDesc")}
The Rest API endpoint for your Signal service
</FormDescription>
<FormMessage />
</FormItem>
@@ -516,12 +501,12 @@ export const NotificationChannelDialog = ({
name="google_chat_webhook_url"
render={({ field }) => (
<FormItem>
<FormLabel>{t("googleChatWebhookUrl")}</FormLabel>
<FormLabel>Google Chat Webhook URL</FormLabel>
<FormControl>
<Input placeholder={t("googleChatWebhookUrlPlaceholder")} {...field} />
<Input placeholder="https://chat.googleapis.com/v1/spaces/..." {...field} />
</FormControl>
<FormDescription>
{t("googleChatWebhookUrlDesc")}
Google Chat webhook URL from your Google Chat space
</FormDescription>
<FormMessage />
</FormItem>
@@ -536,12 +521,12 @@ export const NotificationChannelDialog = ({
name="email_address"
render={({ field }) => (
<FormItem>
<FormLabel>{t("emailAddress")}</FormLabel>
<FormLabel>Email Address</FormLabel>
<FormControl>
<Input placeholder={t("emailAddressPlaceholder")} {...field} type="email" />
<Input placeholder="notifications@example.com" {...field} type="email" />
</FormControl>
<FormDescription>
{t("emailAddressDesc")}
Email address to send notifications to
</FormDescription>
<FormMessage />
</FormItem>
@@ -552,12 +537,12 @@ export const NotificationChannelDialog = ({
name="email_sender_name"
render={({ field }) => (
<FormItem>
<FormLabel>{t("emailSenderName")}</FormLabel>
<FormLabel>Sender Name</FormLabel>
<FormControl>
<Input placeholder={t("emailSenderNamePlaceholder")} {...field} />
<Input placeholder="Alert System" {...field} />
</FormControl>
<FormDescription>
{t("emailSenderNameDesc")}
Display name for outgoing emails
</FormDescription>
<FormMessage />
</FormItem>
@@ -569,9 +554,9 @@ export const NotificationChannelDialog = ({
name="smtp_server"
render={({ field }) => (
<FormItem>
<FormLabel>{t("smtpServer")}</FormLabel>
<FormLabel>SMTP Server</FormLabel>
<FormControl>
<Input placeholder={t("smtpServerPlaceholder")} {...field} />
<Input placeholder="smtp.gmail.com" {...field} />
</FormControl>
<FormMessage />
</FormItem>
@@ -582,9 +567,9 @@ export const NotificationChannelDialog = ({
name="smtp_port"
render={({ field }) => (
<FormItem>
<FormLabel>{t("smtpPort")}</FormLabel>
<FormLabel>SMTP Port</FormLabel>
<FormControl>
<Input placeholder={t("smtpPortPlaceholder")} {...field} />
<Input placeholder="587" {...field} />
</FormControl>
<FormMessage />
</FormItem>
@@ -596,12 +581,12 @@ export const NotificationChannelDialog = ({
name="smtp_password"
render={({ field }) => (
<FormItem>
<FormLabel>{t("smtpPassword")}</FormLabel>
<FormLabel>SMTP Password</FormLabel>
<FormControl>
<Input placeholder={t("smtpPasswordPlaceholder")} {...field} type="password" />
<Input placeholder="Enter your SMTP password" {...field} type="password" />
</FormControl>
<FormDescription>
{t("smtpPasswordDesc")}
Password for authenticating with the SMTP server
</FormDescription>
<FormMessage />
</FormItem>
@@ -617,12 +602,12 @@ export const NotificationChannelDialog = ({
name="ntfy_endpoint"
render={({ field }) => (
<FormItem>
<FormLabel>{t("ntfyEndpoint")}</FormLabel>
<FormLabel>NTFY Endpoint</FormLabel>
<FormControl>
<Input placeholder={t("ntfyEndpointPlaceholder")} {...field} />
<Input placeholder="https://ntfy.sh/your-topic" {...field} />
</FormControl>
<FormDescription>
{t("ntfyEndpointDesc")}
The NTFY endpoint URL including your topic (e.g., https://ntfy.sh/checkcle)
</FormDescription>
<FormMessage />
</FormItem>
@@ -633,12 +618,12 @@ export const NotificationChannelDialog = ({
name="api_token"
render={({ field }) => (
<FormItem>
<FormLabel>{t("apiTokenOptional")}</FormLabel>
<FormLabel>API Token (Optional)</FormLabel>
<FormControl>
<Input placeholder={t("apiTokenPlaceholder")} {...field} type="password" />
<Input placeholder="Enter NTFY API token" {...field} type="password" />
</FormControl>
<FormDescription>
{t("apiTokenDesc")}
Optional API token for authentication with NTFY server
</FormDescription>
<FormMessage />
</FormItem>
@@ -647,19 +632,19 @@ export const NotificationChannelDialog = ({
</>
)}
{notificationType === "pushover" && (
{notificationType === "pushover" && (
<>
<FormField
control={form.control}
name="api_token"
render={({ field }) => (
<FormItem>
<FormLabel>{t("apiToken")}</FormLabel>
<FormLabel>API Token</FormLabel>
<FormControl>
<Input placeholder={t("apiTokenPlaceholder")} {...field} type="password" />
<Input placeholder="Your Pushover API token" {...field} type="password" />
</FormControl>
<FormDescription>
{t("apiTokenDesc")}
Your Pushover application API token
</FormDescription>
<FormMessage />
</FormItem>
@@ -670,12 +655,12 @@ export const NotificationChannelDialog = ({
name="user_key"
render={({ field }) => (
<FormItem>
<FormLabel>{t("pushoverUserKey")}</FormLabel>
<FormLabel>User Key</FormLabel>
<FormControl>
<Input placeholder={t("pushoverUserKeyPlaceholder")} {...field} />
<Input placeholder="Your Pushover user key" {...field} />
</FormControl>
<FormDescription>
{t("pushoverUserKeyDesc")}
Your Pushover user key (or group key)
</FormDescription>
<FormMessage />
</FormItem>
@@ -691,12 +676,12 @@ export const NotificationChannelDialog = ({
name="api_token"
render={({ field }) => (
<FormItem>
<FormLabel>{t("apiToken")}</FormLabel>
<FormLabel>API Token</FormLabel>
<FormControl>
<Input placeholder={t("apiTokenPlaceholder")} {...field} type="password" />
<Input placeholder="Your Notifiarr API token" {...field} type="password" />
</FormControl>
<FormDescription>
{t("apiTokenDesc")}
Your Notifiarr API token for sending notifications
</FormDescription>
<FormMessage />
</FormItem>
@@ -707,12 +692,12 @@ export const NotificationChannelDialog = ({
name="channel_id"
render={({ field }) => (
<FormItem>
<FormLabel>{t("notifiarrChannelId")}</FormLabel>
<FormLabel>Channel ID</FormLabel>
<FormControl>
<Input placeholder={t("notifiarrChannelIdPlaceholder")} {...field} />
<Input placeholder="Discord Channel ID" {...field} />
</FormControl>
<FormDescription>
{t("notifiarrChannelIdDesc")}
The Discord channel ID where notifications will be sent
</FormDescription>
<FormMessage />
</FormItem>
@@ -728,12 +713,12 @@ export const NotificationChannelDialog = ({
name="api_token"
render={({ field }) => (
<FormItem>
<FormLabel>{t("apiToken")}</FormLabel>
<FormLabel>API Token</FormLabel>
<FormControl>
<Input placeholder={t("apiTokenPlaceholder")} {...field} type="password" />
<Input placeholder="Your Gotify API token" {...field} type="password" />
</FormControl>
<FormDescription>
{t("apiTokenDesc")}
Your Gotify application API token
</FormDescription>
<FormMessage />
</FormItem>
@@ -744,12 +729,12 @@ export const NotificationChannelDialog = ({
name="server_url"
render={({ field }) => (
<FormItem>
<FormLabel>{t("gotifyServerUrl")}</FormLabel>
<FormLabel>Server URL</FormLabel>
<FormControl>
<Input placeholder={t("gotifyServerUrlPlaceholder")} {...field} />
<Input placeholder="https://your-gotify-server.com" {...field} />
</FormControl>
<FormDescription>
{t("gotifyServerUrlDesc")}
The URL of your Gotify server
</FormDescription>
<FormMessage />
</FormItem>
@@ -757,7 +742,7 @@ export const NotificationChannelDialog = ({
/>
</>
)}
{notificationType === "webhook" && (
<>
<FormField
@@ -765,12 +750,12 @@ export const NotificationChannelDialog = ({
name="webhook_url"
render={({ field }) => (
<FormItem>
<FormLabel>{t("webhookUrl")}</FormLabel>
<FormLabel>Webhook URL</FormLabel>
<FormControl>
<Input placeholder={t("webhookUrlPlaceholder")} {...field} />
<Input placeholder="https://api.example.com/webhook" {...field} />
</FormControl>
<FormDescription>
{t("webhookUrlDesc")}
The URL where webhook notifications will be sent
</FormDescription>
<FormMessage />
</FormItem>
@@ -783,9 +768,10 @@ export const NotificationChannelDialog = ({
name="webhook_payload_template"
render={({ field }) => (
<FormItem>
<FormLabel>{t("payloadTemplate")}</FormLabel>
<FormLabel>Payload Template (Optional)</FormLabel>
<FormDescription>
{t("payloadTemplateDesc")}
JSON template for the webhook payload. Leave empty to use default template.
</FormDescription>
<FormMessage />
</FormItem>
@@ -794,15 +780,15 @@ export const NotificationChannelDialog = ({
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-medium">{t("payloadTemplates")}</CardTitle>
<CardTitle className="text-sm font-medium">Payload Templates</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
<div className="mt-4">
<h4 className="text-sm font-medium mb-2">{t("availablePlaceholders")}</h4>
<h4 className="text-sm font-medium mb-2">Available Placeholders:</h4>
<div className="grid grid-cols-2 md:grid-cols-4 gap-2 text-xs">
<div className="space-y-1">
<p className="font-medium text-muted-foreground">{t("server")}</p>
<p className="font-medium text-muted-foreground">Server:</p>
<div className="space-y-0.5">
<code className="bg-muted px-1 rounded">${'{server_name}'}</code><br/>
<code className="bg-muted px-1 rounded">${'{cpu_usage}'}</code><br/>
@@ -811,7 +797,7 @@ export const NotificationChannelDialog = ({
</div>
</div>
<div className="space-y-1">
<p className="font-medium text-muted-foreground">{t("service")}</p>
<p className="font-medium text-muted-foreground">Service:</p>
<div className="space-y-0.5">
<code className="bg-muted px-1 rounded">${'{service_name}'}</code><br/>
<code className="bg-muted px-1 rounded">${'{response_time}'}</code><br/>
@@ -820,7 +806,7 @@ export const NotificationChannelDialog = ({
</div>
</div>
<div className="space-y-1">
<p className="font-medium text-muted-foreground">{t("ssl")}</p>
<p className="font-medium text-muted-foreground">SSL:</p>
<div className="space-y-0.5">
<code className="bg-muted px-1 rounded">${'{domain}'}</code><br/>
<code className="bg-muted px-1 rounded">${'{expiry_date}'}</code><br/>
@@ -829,7 +815,7 @@ export const NotificationChannelDialog = ({
</div>
</div>
<div className="space-y-1">
<p className="font-medium text-muted-foreground">{t("common")}</p>
<p className="font-medium text-muted-foreground">Common:</p>
<div className="space-y-0.5">
<code className="bg-muted px-1 rounded">${'{status}'}</code><br/>
<code className="bg-muted px-1 rounded">${'{time}'}</code><br/>
@@ -846,68 +832,15 @@ export const NotificationChannelDialog = ({
</>
)}
{notificationType === "matrix" && (
<>
<FormField
control={form.control}
name="matrix_homeserver"
render={({ field }) => (
<FormItem>
<FormLabel>{t("matrixHomeserver")}</FormLabel>
<FormControl>
<Input placeholder={t("matrixHomeserverPlaceholder")} {...field} />
</FormControl>
<FormDescription>
{t("matrixHomeserverDesc")}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="matrix_room_id"
render={({ field }) => (
<FormItem>
<FormLabel>{t("matrixRoomId")}</FormLabel>
<FormControl>
<Input placeholder={t("matrixRoomIdPlaceholder")} {...field} />
</FormControl>
<FormDescription>
{t("matrixRoomIdDesc")}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="matrix_access_token"
render={({ field }) => (
<FormItem>
<FormLabel>{t("matrixAccessToken")}</FormLabel>
<FormControl>
<Input placeholder={t("matrixAccessTokenPlaceholder")} {...field} type="password" />
</FormControl>
<FormDescription>
{t("matrixAccessTokenDesc")}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</>
)}
<FormField
control={form.control}
name="enabled"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3">
<div className="space-y-0.5">
<FormLabel>{t("enabled")}</FormLabel>
<FormLabel>Enabled</FormLabel>
<FormDescription>
{t("enabledDesc")}
Enable or disable this notification channel
</FormDescription>
</div>
<FormControl>
@@ -922,11 +855,11 @@ export const NotificationChannelDialog = ({
<DialogFooter>
<Button variant="outline" type="button" onClick={handleClose}>
{t("cancel")}
Cancel
</Button>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{isEditing ? t("updateChannel") : t("createChannel")}
{isEditing ? "Update Channel" : "Create Channel"}
</Button>
</DialogFooter>
</form>
@@ -1,7 +1,6 @@
import { AlertConfiguration } from "@/services/alertConfigService";
import { Bell, Edit, Trash2 } from "lucide-react";
import { useState } from "react";
import {
Table,
TableBody,
@@ -34,40 +33,29 @@ export const NotificationChannelList = ({
onEdit,
onDelete
}: NotificationChannelListProps) => {
const [optimisticStates, setOptimisticStates] = useState<Record<string, boolean>>({});
const toggleEnabled = async (config: CombinedChannel) => {
if (!config.id) return;
const currentEnabled = typeof config.enabled === 'string'
? config.enabled === "true" || config.enabled === "on"
: !!config.enabled;
// Apply optimistic update immediately
setOptimisticStates(prev => ({
...prev,
[config.id!]: !currentEnabled
}));
try {
if (config.isWebhook) {
// Handle webhook toggle
const newEnabled = currentEnabled ? "off" : "on";
if (config.isWebhook) {
// Handle webhook toggle
try {
const newEnabled = config.enabled ? "off" : "on";
await pb.collection('webhook').update(config.id, {
enabled: newEnabled
});
} else {
// Handle alert config toggle
await alertConfigService.updateAlertConfiguration(config.id, {
enabled: !currentEnabled
});
// Trigger refresh by calling onEdit with empty config
onEdit({} as AlertConfiguration);
} catch (error) {
console.error("Error updating webhook:", error);
}
} catch (error) {
setOptimisticStates(prev => ({
...prev,
[config.id!]: currentEnabled
}));
} else {
// Handle alert config toggle
await alertConfigService.updateAlertConfiguration(config.id, {
enabled: !config.enabled
});
// The parent component will refresh the list
onEdit(config as AlertConfiguration);
}
};
@@ -82,7 +70,6 @@ export const NotificationChannelList = ({
case "pushover": return "Pushover";
case "notifiarr": return "Notifiarr";
case "webhook": return "Webhook";
case "matrix": return "Matrix";
default: return type || "Unknown";
}
};
@@ -103,8 +90,6 @@ export const NotificationChannelList = ({
return config.signal_number || '';
case "email":
return config.email_address || '';
case "matrix":
return config.matrix_room_id || '';
default:
return '';
}
@@ -145,14 +130,12 @@ export const NotificationChannelList = ({
<TableCell className="max-w-xs truncate text-sm text-muted-foreground">
{getChannelDetails(channel)}
</TableCell>
<TableCell>
<TableCell>
<Switch
checked={
channel.id && optimisticStates.hasOwnProperty(channel.id)
? optimisticStates[channel.id]
: typeof channel.enabled === 'string'
? channel.enabled === "true" || channel.enabled === "on"
: !!channel.enabled
typeof channel.enabled === 'string'
? channel.enabled === "true" || channel.enabled === "on"
: !!channel.enabled
}
onCheckedChange={() => toggleEnabled(channel)}
/>
@@ -166,7 +149,7 @@ export const NotificationChannelList = ({
variant="outline"
size="sm"
onClick={() => onEdit(channel as AlertConfiguration)}
disabled={channel.isWebhook}
disabled={channel.isWebhook} // Disable edit for webhooks for now
>
<Edit className="h-4 w-4" />
</Button>
@@ -9,7 +9,6 @@ import { WebhookConfiguration, webhookService } from "@/services/webhookService"
import { NotificationChannelDialog } from "./NotificationChannelDialog";
import { NotificationChannelList } from "./NotificationChannelList";
import { pb } from "@/lib/pocketbase";
import { useLanguage } from "@/contexts/LanguageContext";
interface CombinedChannel extends Partial<AlertConfiguration> {
isWebhook?: boolean;
@@ -19,7 +18,6 @@ interface CombinedChannel extends Partial<AlertConfiguration> {
}
const NotificationSettings = () => {
const { t } = useLanguage();
const [isLoading, setIsLoading] = useState(true);
const [alertConfigs, setAlertConfigs] = useState<AlertConfiguration[]>([]);
const [webhookConfigs, setWebhookConfigs] = useState<WebhookConfiguration[]>([]);
@@ -128,13 +126,13 @@ const NotificationSettings = () => {
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle>{t("titleNotification")}</CardTitle>
<CardTitle>Notification Settings</CardTitle>
<CardDescription>
{t("descriptionChannelsServices")}
Configure notification channels for your services
</CardDescription>
</div>
<Button onClick={handleAddNew}>
<Plus className="mr-2 h-4 w-4" /> {t("addChannel")}
<Plus className="mr-2 h-4 w-4" /> Add Channel
</Button>
</div>
</CardHeader>
@@ -146,15 +144,14 @@ const NotificationSettings = () => {
className="w-full"
>
<TabsList className="mb-4">
<TabsTrigger value="all">{t("all")}</TabsTrigger>
<TabsTrigger value="telegram">{t("telegram")}</TabsTrigger>
<TabsTrigger value="discord">{t("discord")}</TabsTrigger>
<TabsTrigger value="slack">{t("slack")}</TabsTrigger>
<TabsTrigger value="signal">{t("signal")}</TabsTrigger>
<TabsTrigger value="google_chat">{t("googleChat")}</TabsTrigger>
<TabsTrigger value="email">{t("email")}</TabsTrigger>
<TabsTrigger value="webhook">{t("webhook")}</TabsTrigger>
<TabsTrigger value="matrix">{t("matrix")}</TabsTrigger>
<TabsTrigger value="all">All Channels</TabsTrigger>
<TabsTrigger value="telegram">Telegram</TabsTrigger>
<TabsTrigger value="discord">Discord</TabsTrigger>
<TabsTrigger value="slack">Slack</TabsTrigger>
<TabsTrigger value="signal">Signal</TabsTrigger>
<TabsTrigger value="google_chat">Google Chat</TabsTrigger>
<TabsTrigger value="email">Email</TabsTrigger>
<TabsTrigger value="webhook">Webhook</TabsTrigger>
</TabsList>
<TabsContent value={currentTab} className="mt-0">
@@ -1,3 +1,4 @@
import React from "react";
import {
Dialog,
@@ -16,9 +17,8 @@ import { Loader2, AlertCircle } from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import UserTextField from "./form-fields/UserTextField";
import UserToggleField from "./form-fields/UserToggleField";
import UserProfilePictureField from "./form-fields/UserProfilePictureField";
import UserRoleField from "./form-fields/UserRoleField";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
interface EditUserDialogProps {
isOpen: boolean;
@@ -26,7 +26,6 @@ interface EditUserDialogProps {
form: UseFormReturn<any>;
user: User | null;
onSubmit: (data: any) => void;
onImpersonate: (data: any) => void;
isSubmitting?: boolean;
error?: string | null;
}
@@ -37,18 +36,10 @@ const EditUserDialog = ({
form,
user,
onSubmit,
onImpersonate,
isSubmitting = false,
error = null
}: EditUserDialogProps) => {
if (!user) return null;
const [impersonationDurationSeconds, setImpersonationDurationSeconds] = React.useState<number>(3600);
const handleImpersonateClick = () => {
// Impersonation should not depend on edit form validation.
onImpersonate({ user, durationSeconds: impersonationDurationSeconds });
};
return (
<Dialog open={isOpen} onOpenChange={setIsOpen}>
@@ -71,6 +62,7 @@ const EditUserDialog = ({
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<UserProfilePictureField control={form.control} />
<div className="grid grid-cols-2 gap-4">
<UserTextField
@@ -110,23 +102,6 @@ const EditUserDialog = ({
/>
</form>
</Form>
{/* Impersonation settings are not part of the form to avoid validation */}
<div className="mt-6 space-y-2">
<Label htmlFor="impersonation-duration">Impersonation token duration (seconds)</Label>
<Input
id="impersonation-duration"
type="number"
inputMode="numeric"
min={60}
step={60}
value={impersonationDurationSeconds}
onChange={(e) => setImpersonationDurationSeconds(Number(e.target.value || 0))}
/>
<p className="text-xs text-muted-foreground">
Default is 3600 (1 hour). Minimum 60 seconds.
</p>
</div>
</div>
</ScrollArea>
@@ -152,20 +127,6 @@ const EditUserDialog = ({
"Update User"
)}
</Button>
<Button
type="button"
onClick={handleImpersonateClick}
disabled={isSubmitting}
>
{isSubmitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Impersonating...
</>
) : (
"Impersonate"
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
@@ -1,65 +0,0 @@
import React from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { copyToClipboard } from "@/utils/copyUtils";
interface ImpersonationTokenDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
token: string | null;
impersonatedUserLabel?: string;
}
const ImpersonationTokenDialog = ({
open,
onOpenChange,
token,
impersonatedUserLabel,
}: ImpersonationTokenDialogProps) => {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[650px] w-[95vw]">
<DialogHeader>
<DialogTitle>Impersonation token</DialogTitle>
<DialogDescription>
{impersonatedUserLabel
? `Use this token to impersonate ${impersonatedUserLabel}. Keep it secret.`
: "Use this token to impersonate the selected user. Keep it secret."}
</DialogDescription>
</DialogHeader>
<div className="space-y-2">
<div className="rounded-md border bg-muted p-3">
<pre className="text-sm overflow-x-auto whitespace-pre-wrap break-all">
<code>{token ?? ""}</code>
</pre>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
Close
</Button>
<Button
type="button"
onClick={() => {
if (token) copyToClipboard(token);
}}
disabled={!token}
>
Copy token
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
export default ImpersonationTokenDialog;
@@ -1,9 +1,9 @@
import React from "react";
import UserTable from "./UserTable";
import AddUserDialog from "./AddUserDialog";
import EditUserDialog from "./EditUserDialog";
import DeleteUserDialog from "./DeleteUserDialog";
import ImpersonationTokenDialog from "./ImpersonationTokenDialog";
import { useUserManagement } from "./hooks";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import { UserCog, Loader2, AlertCircle, Info, Users, ShieldAlert } from "lucide-react";
@@ -34,12 +34,8 @@ const UserManagement = () => {
handleDeletePrompt,
handleDeleteUser,
onSubmit,
onImpersonate,
onAddUser,
fetchUsers,
impersonationToken,
isImpersonationTokenDialogOpen,
setIsImpersonationTokenDialogOpen,
fetchUsers
} = useUserManagement();
// Get the current logged in user to check their role
@@ -83,14 +79,7 @@ const UserManagement = () => {
<AddUserDialog isOpen={isAddUserDialogOpen && isSuperAdmin} setIsOpen={setIsAddUserDialogOpen} form={newUserForm} onSubmit={onAddUser} isSubmitting={isSubmitting} />
<EditUserDialog isOpen={isDialogOpen} setIsOpen={setIsDialogOpen} form={form} user={currentUser} onImpersonate={onImpersonate} onSubmit={onSubmit} isSubmitting={isSubmitting} error={updateError} />
<ImpersonationTokenDialog
open={isImpersonationTokenDialogOpen}
onOpenChange={setIsImpersonationTokenDialogOpen}
token={impersonationToken}
impersonatedUserLabel={currentUser?.full_name || currentUser?.username}
/>
<EditUserDialog isOpen={isDialogOpen} setIsOpen={setIsDialogOpen} form={form} user={currentUser} onSubmit={onSubmit} isSubmitting={isSubmitting} error={updateError} />
<DeleteUserDialog isOpen={isDeleting} setIsOpen={setIsDeleting} user={userToDelete} onDelete={handleDeleteUser} isDeleting={isSubmitting} />
</AccordionContent>
@@ -4,6 +4,7 @@ import { Form } from "@/components/ui/form";
import { Button } from "@/components/ui/button";
import { Loader2 } from "lucide-react";
import { UseFormReturn } from "react-hook-form";
import { UserProfilePictureField } from "./";
import { UserTextField } from "./";
import { UserToggleField } from "./";
import { UserRoleField } from "./";
@@ -19,6 +20,7 @@ const AddUserForm = ({ form, onSubmit, isSubmitting }: AddUserFormProps) => {
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<UserProfilePictureField control={form.control} />
<div className="grid grid-cols-2 gap-4">
<UserTextField
@@ -27,7 +27,7 @@ export const useUserForm = () => {
passwordConfirm: "",
isActive: true,
role: "user",
avatar: avatarOptions[Math.floor(Math.random() * avatarOptions.length)].url,
avatar: avatarOptions[0].url,
},
});
@@ -1,10 +1,10 @@
import { useUsersList } from "./useUsersList";
import { useUserForm } from "./useUserForm";
import { useUserDialogs } from "./useUserDialogs";
import { useUserOperations } from "./useUserOperations";
import { User } from "@/services/userService";
import { UserFormValues, NewUserFormValues } from "../userForms";
import { useState } from "react";
export const useUserManagement = () => {
const { users, loading, error, fetchUsers } = useUsersList();
@@ -32,7 +32,6 @@ export const useUserManagement = () => {
handleDeleteUser: baseHandleDeleteUser,
onSubmit: baseOnSubmit,
onAddUser: baseOnAddUser,
onImpersonate: baseOnImpersonate,
} = useUserOperations(
fetchUsers,
setIsDialogOpen,
@@ -43,9 +42,6 @@ export const useUserManagement = () => {
newUserForm.reset
);
const [impersonationToken, setImpersonationToken] = useState<string | null>(null);
const [isImpersonationTokenDialogOpen, setIsImpersonationTokenDialogOpen] = useState(false);
// Wrapper functions to provide the needed arguments
const handleEditUser = (user: User) => {
baseHandleEditUser(user, form);
@@ -60,15 +56,6 @@ export const useUserManagement = () => {
baseOnSubmit(data, currentUser);
};
const onImpersonate = async (data: UserFormValues) => {
const token = await baseOnImpersonate(data, currentUser);
if (token) {
setImpersonationToken(token);
setIsImpersonationTokenDialogOpen(true);
}
};
const onAddUser = (data: NewUserFormValues) => {
baseOnAddUser(data);
};
@@ -94,10 +81,6 @@ export const useUserManagement = () => {
handleDeletePrompt,
handleDeleteUser,
onSubmit,
onImpersonate,
onAddUser,
impersonationToken,
isImpersonationTokenDialogOpen,
setIsImpersonationTokenDialogOpen,
};
};
@@ -1,3 +1,4 @@
import { useState } from "react";
import { useToast } from "@/hooks/use-toast";
import { userService, User, UpdateUserData, CreateUserData } from "@/services/userService";
@@ -120,38 +121,6 @@ export const useUserOperations = (
}
};
const onImpersonate = async (
data: UserFormValues & { durationSeconds?: number },
currentUser: User | null
): Promise<string | undefined> => {
const loggedInUser = authService.getCurrentUser();
if (!currentUser) return;
try {
const token = await authService.impersonateUser(currentUser.id, data?.durationSeconds ?? 3600);
toast({
title: "Impersonation token generated",
description: `Token generated for ${currentUser.full_name || currentUser.username}.`,
});
return token;
} catch (error) {
let description = "Error impersonating user.";
if (loggedInUser?.role !== "superadmin") {
description = "Only superadmin users can impersonate other users.";
}
toast({
title: "Error impersonating user",
description,
variant: "destructive",
});
throw error;
}
};
const onAddUser = async (data: NewUserFormValues) => {
setIsSubmitting(true);
try {
@@ -208,7 +177,6 @@ export const useUserOperations = (
return {
handleDeleteUser,
onSubmit,
onImpersonate,
onAddUser,
};
};
@@ -17,33 +17,27 @@ import { alertConfigService, AlertConfiguration } from "@/services/alertConfigSe
import { sslNotificationTemplateService, SslNotificationTemplate } from "@/services/sslNotificationTemplateService";
import { useLanguage } from "@/contexts/LanguageContext";
const formSchema = z.object({
domain: z.string().min(1, "Domain is required"),
warning_threshold: z.coerce.number().int().min(1).max(365),
expiry_threshold: z.coerce.number().int().min(1).max(30),
notification_channels: z.array(z.string()).optional(),
alert_template: z.string().optional(),
check_interval: z.coerce.number().int().min(1).max(30).optional()
});
interface AddSSLCertificateFormProps {
onSubmit: (data: AddSSLCertificateDto) => Promise<void>;
onCancel: () => void;
isPending?: boolean;
}
export const AddSSLCertificateForm = ({
onSubmit,
export const AddSSLCertificateForm = ({
onSubmit,
onCancel,
isPending = false
isPending = false
}: AddSSLCertificateFormProps) => {
const { t } = useLanguage();
const formSchema = z.object({
domain: z.string()
.min(1, t("domain") + " is required")
.refine(
(value) => !/\s/.test(value),
t("spacesNotAllowed")
),
warning_threshold: z.coerce.number().int().min(1).max(365),
expiry_threshold: z.coerce.number().int().min(1).max(30),
notification_channels: z.array(z.string()).optional(),
alert_template: z.string().optional(),
check_interval: z.coerce.number().int().min(1).max(30).optional()
});
const [alertConfigs, setAlertConfigs] = useState<AlertConfiguration[]>([]);
const [sslTemplates, setSslTemplates] = useState<SslNotificationTemplate[]>([]);
const [isLoading, setIsLoading] = useState(false);
@@ -84,7 +78,7 @@ export const AddSSLCertificateForm = ({
setIsLoading(false);
}
};
fetchData();
}, [t]);
@@ -95,16 +89,16 @@ export const AddSSLCertificateForm = ({
domain: values.domain,
warning_threshold: values.warning_threshold,
expiry_threshold: values.expiry_threshold,
notification_channel: values.notification_channels && values.notification_channels.length > 0
? values.notification_channels.join(',')
notification_channel: values.notification_channels && values.notification_channels.length > 0
? values.notification_channels.join(',')
: '',
notification_id: values.notification_channels && values.notification_channels.length > 0
? values.notification_channels.join(',')
notification_id: values.notification_channels && values.notification_channels.length > 0
? values.notification_channels.join(',')
: '',
template_id: values.alert_template && values.alert_template !== 'none' ? values.alert_template : '',
check_interval: values.check_interval
};
await onSubmit(certData);
form.reset();
} catch (error) {
@@ -142,7 +136,7 @@ export const AddSSLCertificateForm = ({
</FormItem>
)}
/>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
@@ -160,6 +154,7 @@ export const AddSSLCertificateForm = ({
</FormItem>
)}
/>
<FormField
control={form.control}
name="expiry_threshold"
@@ -194,6 +189,7 @@ export const AddSSLCertificateForm = ({
</FormItem>
)}
/>
<FormField
control={form.control}
name="notification_channels"
@@ -201,7 +197,7 @@ export const AddSSLCertificateForm = ({
<FormItem>
<FormLabel>{t('notificationChannel')} (Multi-select)</FormLabel>
<div className="space-y-3">
<Select
<Select
onValueChange={handleAddNotificationChannel}
value=""
>
@@ -251,7 +247,7 @@ export const AddSSLCertificateForm = ({
)}
</div>
<FormDescription className="flex items-center gap-1">
<Bell className="h-4 w-4" />
<Bell className="h-4 w-4" />
{t('whereToSend')}
</FormDescription>
<FormMessage />
@@ -293,6 +289,7 @@ export const AddSSLCertificateForm = ({
</FormItem>
)}
/>
<DialogFooter>
<Button type="button" variant="outline" onClick={onCancel}>{t('cancel')}</Button>
<Button type="submit" disabled={isPending || isLoading}>
@@ -2,13 +2,24 @@ import React, { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Plus, RefreshCw } from "lucide-react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { toast } from "sonner";
import { SSLCertificateStatusCards } from "./SSLCertificateStatusCards";
import { SSLCertificatesTable } from "./SSLCertificatesTable";
import { LoadingState } from "@/components/services/LoadingState";
import { fetchSSLCertificates, addSSLCertificate, checkAndUpdateCertificate, refreshAllCertificates, deleteSSLCertificate } from "@/services/ssl";
import {
fetchSSLCertificates,
addSSLCertificate,
checkAndUpdateCertificate,
refreshAllCertificates,
deleteSSLCertificate,
} from "@/services/ssl";
import { AddSSLCertificateForm } from "./AddSSLCertificateForm";
import { EditSSLCertificateForm } from "./EditSSLCertificateForm";
import type { AddSSLCertificateDto, SSLCertificate } from "@/types/ssl.types";
@@ -21,18 +32,23 @@ export const SSLDomainContent = () => {
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
const [refreshingId, setRefreshingId] = useState<string | null>(null);
const [isRefreshingAll, setIsRefreshingAll] = useState(false);
const [selectedCertificate, setSelectedCertificate] = useState<SSLCertificate | null>(null);
const [selectedCertificate, setSelectedCertificate] =
useState<SSLCertificate | null>(null);
const queryClient = useQueryClient();
// Fetch SSL certificates with explicit error handling
const { data: certificates = [], isLoading, error } = useQuery({
queryKey: ['ssl-certificates'],
const {
data: certificates = [],
isLoading,
error,
} = useQuery({
queryKey: ["ssl-certificates"],
queryFn: async () => {
try {
const result = await fetchSSLCertificates();
return result;
} catch (error) {
toast.error(t('failedToLoadCertificates'));
toast.error(t("failedToLoadCertificates"));
throw error;
}
},
@@ -44,101 +60,114 @@ export const SSLDomainContent = () => {
const addMutation = useMutation({
mutationFn: addSSLCertificate,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['ssl-certificates'] });
queryClient.invalidateQueries({ queryKey: ["ssl-certificates"] });
setIsAddDialogOpen(false);
toast.success(t('sslCertificateAdded'));
toast.success(t("sslCertificateAdded"));
},
onError: (error) => {
toast.error(error instanceof Error ? error.message : t('failedToAddCertificate'));
}
toast.error(
error instanceof Error ? error.message : t("failedToAddCertificate")
);
},
});
// Edit certificate mutation - Updated to include notification_id and template_id
const editMutation = useMutation({
mutationFn: async (certificate: SSLCertificate) => {
// Create the update data object with new fields
const updateData = {
warning_threshold: Number(certificate.warning_threshold),
expiry_threshold: Number(certificate.expiry_threshold),
notification_channel: certificate.notification_channel,
notification_id: certificate.notification_id || '', // Multi notification channels
template_id: certificate.template_id || '', // Alert template ID
notification_id: certificate.notification_id || "", // Multi notification channels
template_id: certificate.template_id || "", // Alert template ID
check_interval: certificate.check_interval,
};
// Update certificate in the database using PocketBase directly
const updated = await pb.collection('ssl_certificates').update(certificate.id, updateData);
const updated = await pb
.collection("ssl_certificates")
.update(certificate.id, updateData);
// After updating the settings, refresh the certificate to ensure it's up to date
// This will also check if notification needs to be sent based on updated thresholds
const refreshedCert = await checkAndUpdateCertificate(certificate.id);
return refreshedCert;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['ssl-certificates'] });
queryClient.invalidateQueries({ queryKey: ["ssl-certificates"] });
setIsEditDialogOpen(false);
setSelectedCertificate(null);
toast.success(t('sslCertificateUpdated'));
toast.success(t("sslCertificateUpdated"));
},
onError: (error) => {
toast.error(error instanceof Error ? error.message : t('failedToUpdateCertificate'));
}
toast.error(
error instanceof Error ? error.message : t("failedToUpdateCertificate")
);
},
});
// Delete certificate mutation
const deleteMutation = useMutation({
mutationFn: deleteSSLCertificate,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['ssl-certificates'] });
toast.success(t('sslCertificateDeleted'));
queryClient.invalidateQueries({ queryKey: ["ssl-certificates"] });
toast.success(t("sslCertificateDeleted"));
},
onError: (error) => {
toast.error(error instanceof Error ? error.message : t('failedToDeleteCertificate'));
}
toast.error(
error instanceof Error ? error.message : t("failedToDeleteCertificate")
);
},
});
// Refresh certificate mutation - Updated to remove individual toast notifications
const refreshMutation = useMutation({
mutationFn: checkAndUpdateCertificate,
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['ssl-certificates'] });
queryClient.invalidateQueries({ queryKey: ["ssl-certificates"] });
setRefreshingId(null);
// Removed individual success toast notification
},
onError: (error) => {
setRefreshingId(null);
// Still refresh the data to show any partial information that was saved
queryClient.invalidateQueries({ queryKey: ['ssl-certificates'] });
queryClient.invalidateQueries({ queryKey: ["ssl-certificates"] });
// Removed individual error toast notification
}
},
});
// Refresh all certificates mutation
const refreshAllMutation = useMutation({
mutationFn: refreshAllCertificates,
onSuccess: (result) => {
queryClient.invalidateQueries({ queryKey: ['ssl-certificates'] });
queryClient.invalidateQueries({ queryKey: ["ssl-certificates"] });
setIsRefreshingAll(false);
if (result.failed === 0) {
toast.success(t('allCertificatesRefreshed').replace('{count}', result.success.toString()));
toast.success(
t("allCertificatesRefreshed").replace(
"{count}",
result.success.toString()
)
);
} else {
toast.info(t('someCertificatesFailed')
.replace('{success}', result.success.toString())
.replace('{failed}', result.failed.toString()));
toast.info(
t("someCertificatesFailed")
.replace("{success}", result.success.toString())
.replace("{failed}", result.failed.toString())
);
}
},
onError: (error) => {
toast.error(t('failedToCheckCertificate'));
toast.error(t("failedToCheckCertificate"));
setIsRefreshingAll(false);
// Still refresh the data to show any partial information
queryClient.invalidateQueries({ queryKey: ['ssl-certificates'] });
}
queryClient.invalidateQueries({ queryKey: ["ssl-certificates"] });
},
});
const handleAddCertificate = async (data: AddSSLCertificateDto) => {
@@ -166,12 +195,14 @@ export const SSLDomainContent = () => {
const handleRefreshAll = async () => {
if (certificates.length === 0) {
toast.info(t('noCertificatesToRefresh'));
toast.info(t("noCertificatesToRefresh"));
return;
}
setIsRefreshingAll(true);
toast.info(t('startingRefreshAll').replace('{count}', certificates.length.toString()));
toast.info(
t("startingRefreshAll").replace("{count}", certificates.length.toString())
);
refreshAllMutation.mutate();
};
@@ -182,48 +213,60 @@ export const SSLDomainContent = () => {
if (error) {
return (
<div className="flex flex-col items-center justify-center h-full gap-4 text-foreground">
<p>{t('failedToLoadCertificates')}</p>
<Button onClick={() => queryClient.invalidateQueries({ queryKey: ['ssl-certificates'] })}>
{t('check')}
<p>{t("failedToLoadCertificates")}</p>
<Button
onClick={() =>
queryClient.invalidateQueries({ queryKey: ["ssl-certificates"] })
}
>
{t("check")}
</Button>
</div>
);
}
return (
<main className="flex-1 flex flex-col overflow-auto bg-background p-6 pb-0">
<div className="flex flex-col flex-1">
<main className="flex-1 flex flex-col overflow-auto bg-background pb-0 dark:bg-black p-2 ">
<div className="flex flex-col flex-1 bg-white dark:bg-black p-6 rounded-xl">
<div className="flex justify-between items-center mb-6">
<div>
<h2 className="text-2xl font-bold text-foreground">{t('sslDomainManagement')}</h2>
<p className="text-sm text-muted-foreground mt-1">{t('monitorSSLCertificates')}</p>
<h2 className="text-2xl font-bold text-foreground">
{t("sslDomainManagement")}
</h2>
<p className="text-sm text-muted-foreground mt-1">
{t("monitorSSLCertificates")}
</p>
</div>
<div className="flex gap-2">
<Button
<Button
variant="outline"
onClick={handleRefreshAll}
disabled={isRefreshingAll || refreshingId !== null}
className="relative"
>
<RefreshCw className={`w-4 h-4 mr-2 ${isRefreshingAll ? 'animate-spin' : ''}`} />
{t('refreshAll')}
<RefreshCw
className={`w-4 h-4 mr-2 ${
isRefreshingAll ? "animate-spin" : ""
}`}
/>
{t("refreshAll")}
{isRefreshingAll && (
<span className="absolute top-0 right-0 -mt-2 -mr-2 bg-primary text-white text-xs rounded-full h-5 w-5 flex items-center justify-center">
...
</span>
)}
</Button>
<Button
<Button
className="text-primary-foreground"
onClick={() => setIsAddDialogOpen(true)}
>
<Plus className="w-4 h-4 mr-2" /> {t('addDomain')}
<Plus className="w-4 h-4 mr-2" /> {t("addDomain")}
</Button>
</div>
</div>
<SSLCertificateStatusCards certificates={certificates} />
<div className="mt-6 flex-1 flex flex-col pb-6">
<SSLCertificatesTable />
</div>
@@ -232,26 +275,29 @@ export const SSLDomainContent = () => {
<Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('addSSLCertificate')}</DialogTitle>
<DialogTitle>{t("addSSLCertificate")}</DialogTitle>
</DialogHeader>
<AddSSLCertificateForm
onSubmit={handleAddCertificate}
onCancel={() => setIsAddDialogOpen(false)}
<AddSSLCertificateForm
onSubmit={handleAddCertificate}
onCancel={() => setIsAddDialogOpen(false)}
isPending={addMutation.isPending}
/>
</DialogContent>
</Dialog>
{selectedCertificate && (
<Dialog open={isEditDialogOpen} onOpenChange={(open) => {
setIsEditDialogOpen(open);
if (!open) setSelectedCertificate(null);
}}>
<Dialog
open={isEditDialogOpen}
onOpenChange={(open) => {
setIsEditDialogOpen(open);
if (!open) setSelectedCertificate(null);
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('editSSLCertificate')}</DialogTitle>
<DialogTitle>{t("editSSLCertificate")}</DialogTitle>
</DialogHeader>
<EditSSLCertificateForm
<EditSSLCertificateForm
certificate={selectedCertificate}
onSubmit={handleUpdateCertificate}
onCancel={() => {
@@ -265,4 +311,4 @@ export const SSLDomainContent = () => {
)}
</main>
);
};
};
@@ -0,0 +1,14 @@
// src/contexts/FontSizeContext.js
import { useEffect } from "react";
const useDynamicFontSize = (size) => {
useEffect(() => {
if (typeof size === "number") {
// Apply font size to the root HTML element
document.documentElement.style.fontSize = `${size}px`;
localStorage.setItem("fontSize", size.toString());
}
}, [size]);
};
export default useDynamicFontSize;
+19 -48
View File
@@ -1,77 +1,48 @@
import React, { createContext, useContext, useState, useEffect } from 'react';
import React, { createContext, useContext, useState, useEffect } from "react";
type SideBar = boolean;
interface SidebarContextType {
sidebarCollapsed: boolean;
setSidebarCollapsed: (collapsed: boolean) => void;
sidebarCollapsed: SideBar;
setSidebarCollapsed: React.Dispatch<React.SetStateAction<SideBar>>;
toggleSidebar: () => void;
isMobileOpen: boolean;
setIsMobileOpen: (open: boolean) => void;
toggleMobileMenu: () => void;
}
const SidebarContext = createContext<SidebarContextType | undefined>(undefined);
export const SidebarProvider: React.FC<{ children?: React.ReactNode }> = ({ children }) => {
// Initialize sidebar collapsed state from localStorage with window check for safety
const [sidebarCollapsed, setSidebarCollapsed] = useState(() => {
if (typeof window !== 'undefined') {
const saved = localStorage.getItem("sidebarCollapsed");
return saved ? JSON.parse(saved) : false;
}
return false;
interface SidebarProviderProps {
children: React.ReactNode;
}
export const SidebarProvider: React.FC<SidebarProviderProps> = ({
children,
}) => {
// Initialize the state
const [sidebarCollapsed, setSidebarCollapsed] = useState<SideBar>(() => {
const saved = localStorage.getItem("sidebarCollapsed");
return saved === "true";
});
// Fix: added isMobileOpen state for responsive mobile menu
const [isMobileOpen, setIsMobileOpen] = useState(false);
const toggleSidebar = () => {
setSidebarCollapsed(prev => {
setSidebarCollapsed((prev) => {
const newState = !prev;
if (typeof window !== 'undefined') {
localStorage.setItem("sidebarCollapsed", JSON.stringify(newState));
}
localStorage.setItem("sidebarCollapsed", newState.toString());
return newState;
});
};
// Fix: added toggleMobileMenu function to manage mobile drawer state
const toggleMobileMenu = () => {
setIsMobileOpen(prev => !prev);
};
// Fix: added resize listener to close mobile menu when switching to desktop view
useEffect(() => {
if (typeof window === 'undefined') return;
const handleResize = () => {
if (window.innerWidth >= 1024) {
setIsMobileOpen(false);
}
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
const value = {
sidebarCollapsed,
setSidebarCollapsed,
toggleSidebar,
isMobileOpen,
setIsMobileOpen,
toggleMobileMenu
};
return (
<SidebarContext.Provider value={value}>
{children}
</SidebarContext.Provider>
<SidebarContext.Provider value={value}>{children}</SidebarContext.Provider>
);
};
// A custom hook to consume the sidebar context.
export const useSidebar = () => {
const context = useContext(SidebarContext);
if (context === undefined) {
throw new Error('useSidebar must be used within a SidebarProvider');
throw new Error("useSidebar must be used within a SidebarProvider");
}
return context;
};
+26 -6
View File
@@ -1,4 +1,4 @@
import PocketBase, { BaseAuthStore } from 'pocketbase';
import PocketBase from 'pocketbase';
// Dynamically detect API base URL from current host (for use in browser)
const dynamicBaseUrl =
@@ -28,9 +28,8 @@ export const setApiEndpoint = (endpoint: string): void => {
}
};
// Initialize the PocketBase client with an in-memory auth store so auth tokens
// are not persisted in localStorage where XSS can trivially exfiltrate them.
export const pb = new PocketBase(getCurrentEndpoint(), new BaseAuthStore());
// Initialize the PocketBase client with the current API URL
export const pb = new PocketBase(getCurrentEndpoint());
// Helper to check if user is authenticated
export const isAuthenticated = () => {
@@ -40,7 +39,28 @@ export const isAuthenticated = () => {
// Export the auth store for use in components
export const authStore = pb.authStore;
// Remove any auth tokens that may have been persisted by earlier versions.
// Configure PocketBase to persist authentication between page reloads
if (typeof window !== 'undefined') {
localStorage.removeItem('pocketbase_auth');
const storedAuthData = localStorage.getItem('pocketbase_auth');
if (storedAuthData) {
try {
const parsedData = JSON.parse(storedAuthData);
pb.authStore.save(parsedData.token, parsedData.model);
} catch (error) {
console.error('Failed to parse stored auth data:', error);
localStorage.removeItem('pocketbase_auth');
}
}
// Subscribe to authStore changes to persist authentication
pb.authStore.onChange(() => {
if (pb.authStore.isValid) {
localStorage.setItem('pocketbase_auth', JSON.stringify({
token: pb.authStore.token,
model: pb.authStore.model
}));
} else {
localStorage.removeItem('pocketbase_auth');
}
});
}
@@ -85,19 +85,19 @@ const ContainerMonitoring = () => {
/>
<main className="flex-1 flex flex-col items-center justify-center p-4 sm:p-6">
<div className="text-center max-w-md w-full">
<h2 className="text-xl sm:text-2xl font-bold mb-4">{t('errorLoadingContainers')}</h2>
<h2 className="text-xl sm:text-2xl font-bold mb-4">Error loading containers</h2>
<p className="text-muted-foreground mb-4 text-sm sm:text-base">
{t('unableToFetchContainerData')}
Unable to fetch container data. Please check your connection and try again.
</p>
<div className="text-xs text-muted-foreground mb-4 font-mono">
{t('errorUnknown')}: {error?.message || t('errorUnknown')}
Error: {error?.message || 'Unknown error'}
</div>
<div className="flex gap-2 justify-center">
<Button onClick={handleRefresh} className="text-sm sm:text-base">
{t('retry')}
Retry
</Button>
<Button onClick={handleBackToServers} variant="outline" className="text-sm sm:text-base">
{t('backToServers')}
Back to Servers
</Button>
</div>
</div>
@@ -131,17 +131,17 @@ const ContainerMonitoring = () => {
className="flex items-center gap-2"
>
<ArrowLeft className="h-4 w-4" />
{t('backToServers')}
Back to Servers
</Button>
</div>
<h1 className="text-2xl font-bold text-foreground">
{t('containerMonitoring')}
Container Monitoring
</h1>
<p className={`text-muted-foreground mt-1 sm:mt-2 transition-all duration-300 ${sidebarCollapsed ? 'text-base sm:text-lg' : 'text-sm sm:text-base'}`}>
{t('monitorAndManageContainers')}
Monitor and manage your Docker containers in real-time
{serverId && (
<span className="block text-xs text-muted-foreground/70 mt-1">
{t('serverIdLabel')}: {serverId}
Server ID: {serverId}
</span>
)}
</p>
+40 -6
View File
@@ -1,3 +1,4 @@
import React, { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { Header } from "@/components/dashboard/Header";
@@ -10,39 +11,72 @@ import { LoadingState } from "@/components/services/LoadingState";
import { useSidebar } from "@/contexts/SidebarContext";
const Dashboard = () => {
// Use shared sidebar state
const { sidebarCollapsed, toggleSidebar } = useSidebar();
// Get current user
const currentUser = authService.getCurrentUser();
const navigate = useNavigate();
// For debugging user data
useEffect(() => {
// console.log("Current user data:", currentUser);
}, [currentUser]);
// Handle logout
const handleLogout = () => {
authService.logout();
navigate("/login");
};
// Fetch all services with 1-minute polling for real-time updates
const { data: services = [], isLoading, error } = useQuery({
queryKey: ['services'],
queryFn: serviceService.getServices,
refetchInterval: 60000,
refetchInterval: 60000, // 1 minute as requested
staleTime: 30000, // Data is fresh for 30 seconds
gcTime: 120000, // Keep in cache for 2 minutes
refetchOnWindowFocus: true, // Refetch when window gains focus
refetchOnMount: true, // Refetch on mount
refetchOnReconnect: true, // Refetch on reconnect
retry: 2,
retryDelay: 3000,
});
// Start monitoring all active services when the dashboard loads - only once
useEffect(() => {
let hasStarted = false;
const startActiveServices = async () => {
if (hasStarted) return;
hasStarted = true;
await serviceService.startAllActiveServices();
// console.log("Active services monitoring started");
};
const timeoutId = setTimeout(startActiveServices, 2000);
return () => clearTimeout(timeoutId);
}, []);
// Only start once and add a delay to prevent immediate execution
const timeoutId = setTimeout(startActiveServices, 2000);
return () => {
clearTimeout(timeoutId);
};
}, []); // Remove services dependency to prevent re-runs
// Show the loading state while fetching data
if (isLoading) {
return <LoadingState />;
}
return (
<div className="flex h-screen overflow-hidden bg-background text-foreground">
<Sidebar />
<div className="flex flex-col flex-1 min-w-0">
<Sidebar collapsed={sidebarCollapsed} />
<div className="flex flex-col flex-1">
<Header
currentUser={currentUser}
onLogout={handleLogout}
sidebarCollapsed={sidebarCollapsed}
toggleSidebar={toggleSidebar}
/>
<DashboardContent
services={services}
+105 -37
View File
@@ -9,69 +9,137 @@ import { ServerTable } from "@/components/servers/ServerTable";
import { AddServerAgentDialog } from "@/components/servers/AddServerAgentDialog";
import { serverService } from "@/services/serverService";
import { Server, ServerStats } from "@/types/server.types";
import { useSidebar } from "@/contexts/SidebarContext";
import { authService } from "@/services/authService";
import { useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Plus } from "lucide-react";
const InstanceMonitoring = () => {
const { theme } = useTheme();
const { t } = useLanguage();
const { sidebarCollapsed, toggleSidebar } = useSidebar();
const navigate = useNavigate();
const [stats, setStats] = useState<ServerStats>({
total: 0,
online: 0,
offline: 0,
warning: 0
warning: 0,
});
const [currentUser] = useState(authService.getCurrentUser());
const [currentUser, setCurrentUser] = useState(authService.getCurrentUser());
const [addDialogOpen, setAddDialogOpen] = useState(false);
const { data: servers = [], isLoading, error, refetch } = useQuery<Server[]>({
queryKey: ['servers'],
const {
data: servers = [],
isLoading,
error,
refetch,
} = useQuery({
queryKey: ["servers"],
queryFn: serverService.getServers,
refetchInterval: 30000
refetchInterval: 30000, // Refetch every 30 seconds
});
useEffect(() => {
if (servers.length > 0) {
serverService.getServerStats(servers).then(setStats);
}
}, [servers]);
const handleLogout = () => {
authService.logout();
navigate('/login');
const handleRefresh = () => {
refetch();
};
const handleLogout = () => {
authService.logout();
navigate("/login");
};
const handleAgentAdded = () => {
refetch();
};
if (error) {
return (
<div className="flex h-screen overflow-hidden bg-background text-foreground">
<Sidebar collapsed={sidebarCollapsed} />
<div className="flex flex-col flex-1 min-w-0">
<Header
currentUser={currentUser}
onLogout={handleLogout}
sidebarCollapsed={sidebarCollapsed}
toggleSidebar={toggleSidebar}
/>
<main className="flex-1 flex flex-col items-center justify-center p-4 sm:p-6 ">
<div className="text-center max-w-md w-full">
<h2 className="text-xl sm:text-2xl font-bold mb-4">
Error loading servers
</h2>
<p className="text-muted-foreground mb-4 text-sm sm:text-base">
Unable to fetch server data. Please check your connection and
try again.
</p>
<button
onClick={handleRefresh}
className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 text-sm sm:text-base"
>
Retry
</button>
</div>
</main>
</div>
</div>
);
}
return (
<div className="flex h-screen overflow-hidden bg-background text-foreground">
<Sidebar />
<div className="flex flex-col flex-1 min-w-0">
<Header
currentUser={currentUser}
onLogout={handleLogout}
<div className="flex h-screen overflow-hidden bg-background text-foreground ">
<Sidebar collapsed={sidebarCollapsed} />
<div className="flex flex-col flex-1 min-w-0 ">
<Header
currentUser={currentUser}
onLogout={handleLogout}
sidebarCollapsed={sidebarCollapsed}
toggleSidebar={toggleSidebar}
/>
<main className="flex-1 overflow-auto">
<div className="p-4 lg:p-8 space-y-6">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div className="min-w-0 flex-1">
<h1 className="text-2xl font-bold text-foreground">
{t('instanceMonitoring')}
</h1>
<p className="text-muted-foreground mt-1 text-sm">
{t('describeMonitorInstance')}
</p>
<main className="flex-1 overflow-auto dark:bg-black p-2 shadow">
<div className="p-4 sm:p-2 lg:p-2 space-y-6 h-full bg-white dark:bg-black p-4 rounded-xl">
{/* Header Section */}
<div>
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 p-2 ">
<div className="min-w-0 flex-1">
<h1 className="text-2xl lg:text-2xl font-bold text-foreground">
Instance Monitoring
</h1>
<p className="text-muted-foreground mt-1 text-xs sm:text-sm">
Monitor and manage your server instances in real-time
</p>
</div>
<Button
onClick={() => setAddDialogOpen(true)}
className="flex-shrink-0"
>
<Plus className="mr-2 h-4 w-4" />
Add Server Agent
</Button>
</div>
<Button onClick={() => setAddDialogOpen(true)} className="flex-shrink-0">
<Plus className="mr-2 h-4 w-4" />
{t('addServerAgent')}
</Button>
</div>
<ServerStatsCards stats={stats} />
<ServerTable servers={servers} isLoading={isLoading} onRefresh={refetch} />
{/* Stats Cards Section */}
<div className="p-2 ">
<ServerStatsCards stats={stats} />
</div>
{/* Server Table Section */}
<div className="p-3">
<ServerTable
servers={servers}
isLoading={isLoading}
onRefresh={handleRefresh}
/>
</div>
</div>
</main>
</div>
@@ -79,10 +147,10 @@ const InstanceMonitoring = () => {
<AddServerAgentDialog
open={addDialogOpen}
onOpenChange={setAddDialogOpen}
onAgentAdded={refetch}
onAgentAdded={handleAgentAdded}
/>
</div>
);
};
export default InstanceMonitoring;
export default InstanceMonitoring;
+8 -11
View File
@@ -120,15 +120,15 @@ const ServerDetail = () => {
/>
<main className="flex-1 flex flex-col items-center justify-center p-4 sm:p-6">
<div className="text-center max-w-md w-full">
<h2 className="text-xl sm:text-2xl font-bold mb-4">{t('errorLoadingServer')}</h2>
<h2 className="text-xl sm:text-2xl font-bold mb-4">Error loading server</h2>
<p className="text-muted-foreground mb-4 text-sm sm:text-base">
{t('unableToFetchServerData')}
Unable to fetch server data. Please check your connection and try again.
</p>
<div className="text-xs text-muted-foreground mb-4 font-mono">
Error: {serverError?.message || 'Unknown error'}
</div>
<Button onClick={handleBackToServers} variant="outline" className="text-sm sm:text-base">
{t('backToServers')}
Back to Servers
</Button>
</div>
</main>
@@ -151,7 +151,7 @@ const ServerDetail = () => {
<main className="flex-1 flex flex-col items-center justify-center p-4 sm:p-6">
<div className="text-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
<p className="text-muted-foreground">{t('loadingServerDetails')}</p>
<p className="text-muted-foreground">Loading server details...</p>
</div>
</main>
</div>
@@ -183,7 +183,7 @@ const ServerDetail = () => {
className="flex items-center gap-2"
>
<ArrowLeft className="h-4 w-4" />
{t('backToServers')}
Back to Servers
</Button>
</div>
<div className="flex items-center gap-3 mb-2">
@@ -199,17 +199,14 @@ const ServerDetail = () => {
)}
</div>
<h1 className="text-2xl font-bold text-foreground">
{server?.name || t('serverDetail')}
{server?.name || 'Server Detail'}
</h1>
</div>
<p className="text-muted-foreground mt-1 sm:mt-2 text-sm sm:text-base">
{t('monitorServerMetrics')}
Monitor server performance metrics and system health
{server && (
<span className="block text-xs text-muted-foreground/70 mt-1">
{t('serverHostnameIpOs')
.replace('{hostname}', server.hostname)
.replace('{ip_address}', server.ip_address)
.replace('{os_type}', server.os_type)}
{server.hostname} {server.ip_address} {server.os_type}
</span>
)}
</p>
+46 -36
View File
@@ -1,4 +1,3 @@
import React, { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { authService } from "@/services/authService";
@@ -7,32 +6,41 @@ import { Header } from "@/components/dashboard/Header";
import { Sidebar } from "@/components/dashboard/Sidebar";
import { SSLDomainContent } from "@/components/ssl-domain/SSLDomainContent";
import { LoadingState } from "@/components/services/LoadingState";
import { fetchSSLCertificates, shouldRunDailyCheck, checkAllCertificatesAndNotify } from "@/services/sslCertificateService";
import {
fetchSSLCertificates,
shouldRunDailyCheck,
checkAllCertificatesAndNotify,
} from "@/services/sslCertificateService";
import { useLanguage } from "@/contexts/LanguageContext";
import { useSidebar } from "@/contexts/SidebarContext";
const SslDomain = () => {
// Get language context for translations
const { t } = useLanguage();
// Use shared sidebar state
const { sidebarCollapsed, toggleSidebar } = useSidebar();
// Get current user
const currentUser = authService.getCurrentUser();
const navigate = useNavigate();
// Fetch SSL certificates with error handling and debugging
const { data: certificates = [], isLoading, error, refetch } = useQuery({
queryKey: ['ssl-certificates'],
const {
data: certificates = [],
isLoading,
error,
refetch,
} = useQuery({
queryKey: ["ssl-certificates"],
queryFn: async () => {
// console.log("Fetching SSL certificates from SslDomain page...");
// console.log("Fetching SSL certificates from SslDomain page...");
try {
const result = await fetchSSLCertificates();
// console.log("SSL certificates fetch successful, count:", result.length);
// console.log("SSL certificates fetch successful, count:", result.length);
return result;
} catch (err) {
// console.error("Error fetching SSL certificates from page:", err);
// console.error("Error fetching SSL certificates from page:", err);
throw err;
}
},
@@ -40,23 +48,23 @@ const SslDomain = () => {
refetchInterval: 300000, // Refresh every 5 minutes
retry: 3, // Retry failed requests 3 times
});
// Check all SSL certificates once per day
useEffect(() => {
const checkCertificates = async () => {
// Check if we should run daily check
if (shouldRunDailyCheck()) {
// console.log("Running daily SSL certificate check...");
// console.log("Running daily SSL certificate check...");
await checkAllCertificatesAndNotify();
// Refresh certificate list after daily check
refetch();
}
};
// Run check when component mounts
checkCertificates();
}, [refetch]);
// Handle logout
const handleLogout = () => {
authService.logout();
@@ -69,11 +77,11 @@ const SslDomain = () => {
<div className="flex h-screen overflow-hidden bg-background text-foreground">
<Sidebar collapsed={sidebarCollapsed} />
<div className="flex flex-col flex-1">
<Header
currentUser={currentUser}
onLogout={handleLogout}
sidebarCollapsed={sidebarCollapsed}
toggleSidebar={toggleSidebar}
<Header
currentUser={currentUser}
onLogout={handleLogout}
sidebarCollapsed={sidebarCollapsed}
toggleSidebar={toggleSidebar}
/>
<LoadingState />
</div>
@@ -86,23 +94,25 @@ const SslDomain = () => {
return (
<div className="flex h-screen overflow-hidden bg-background text-foreground">
<Sidebar collapsed={sidebarCollapsed} />
<div className="flex flex-col flex-1">
<Header
currentUser={currentUser}
onLogout={handleLogout}
sidebarCollapsed={sidebarCollapsed}
toggleSidebar={toggleSidebar}
<div className="flex flex-col flex-1 ">
<Header
currentUser={currentUser}
onLogout={handleLogout}
sidebarCollapsed={sidebarCollapsed}
toggleSidebar={toggleSidebar}
/>
<div className="flex flex-col items-center justify-center h-full p-6">
<h2 className="text-xl font-bold mb-2">{t('failedToLoadCertificates')}</h2>
<div className="flex flex-col items-center justify-center h-full p-6 ">
<h2 className="text-xl font-bold mb-2">
{t("failedToLoadCertificates")}
</h2>
<p className="text-muted-foreground mb-4">
{error instanceof Error ? error.message : t('unknown')}
{error instanceof Error ? error.message : t("unknown")}
</p>
<button
<button
className="px-4 py-2 bg-primary text-primary-foreground rounded-md"
onClick={() => refetch()}
>
{t('check')}
{t("check")}
</button>
</div>
</div>
@@ -114,12 +124,12 @@ const SslDomain = () => {
return (
<div className="flex h-screen overflow-hidden bg-background text-foreground">
<Sidebar collapsed={sidebarCollapsed} />
<div className="flex flex-col flex-1">
<Header
currentUser={currentUser}
onLogout={handleLogout}
sidebarCollapsed={sidebarCollapsed}
toggleSidebar={toggleSidebar}
<div className="flex flex-col flex-1 ">
<Header
currentUser={currentUser}
onLogout={handleLogout}
sidebarCollapsed={sidebarCollapsed}
toggleSidebar={toggleSidebar}
/>
<SSLDomainContent />
</div>
@@ -127,4 +137,4 @@ const SslDomain = () => {
);
};
export default SslDomain;
export default SslDomain;
+3 -11
View File
@@ -7,7 +7,7 @@ export interface AlertConfiguration {
collectionId?: string;
collectionName?: string;
service_id: string;
notification_type: "telegram" | "discord" | "slack" | "signal" | "google_chat" | "email" | "ntfy" | "pushover" | "notifiarr" | "gotify" | "webhook" | "matrix";
notification_type: "telegram" | "discord" | "slack" | "signal" | "google_chat" | "email" | "ntfy" | "pushover" | "notifiarr" | "gotify" | "webhook";
telegram_chat_id?: string;
discord_webhook_url?: string;
signal_number?: string;
@@ -34,9 +34,6 @@ export interface AlertConfiguration {
server_url?: string;
webhook_url?: string;
webhook_payload_template?: string;
matrix_homeserver?: string;
matrix_room_id?: string;
matrix_access_token?: string;
}
export const alertConfigService = {
@@ -108,13 +105,8 @@ export const alertConfigService = {
} else if (config.notification_type === "webhook") {
cleanConfig.webhook_url = config.webhook_url || "";
cleanConfig.webhook_payload_template = config.webhook_payload_template || "";
} else if (config.notification_type === "matrix") {
cleanConfig.matrix_homeserver = config.matrix_homeserver || "";
cleanConfig.matrix_room_id = config.matrix_room_id || "";
cleanConfig.matrix_access_token = config.matrix_access_token || "";
}
}
const result = await pb.collection('alert_configurations').create(cleanConfig);
toast({
+1 -5
View File
@@ -1,3 +1,4 @@
import { pb } from '@/lib/pocketbase';
export interface LoginCredentials {
@@ -97,10 +98,5 @@ export const authService = {
} catch (error) {
// console.error('Failed to refresh user data:', error);
}
},
async impersonateUser(userId: string, durationSeconds: number = 3600): Promise<string | undefined> {
const impersonateClient = await pb.collection("users").impersonate(userId, durationSeconds);
return impersonateClient.authStore?.token;
}
};
@@ -6,8 +6,6 @@ export interface ServerThreshold {
name: string;
cpu_threshold: number;
ram_threshold: number;
// Some API responses may use a different field name; include it as optional
ram_threshold_message?: number;
disk_threshold: number;
network_threshold: number;
created: string;
-1
View File
@@ -17,7 +17,6 @@ export const loginTranslations: LoginTranslations = {
loginSuccessMessage: "Sie wurden erfolgreich angemeldet.",
loginFailed: "Anmeldung fehlgeschlagen",
authenticationFailed: "Authentifizierung fehlgeschlagen",
invalidCredentials: "Ungültige E-Mail oder Passwort",
bySigningIn: "Durch die Anmeldung stimmen Sie unseren",
termsAndConditions: "Allgemeinen Geschäftsbedingungen",
and: "und",
@@ -1,4 +1,3 @@
import { MaintenanceTranslations } from '../types/maintenance';
export const maintenanceTranslations: MaintenanceTranslations = {
@@ -78,12 +77,4 @@ export const maintenanceTranslations: MaintenanceTranslations = {
selectNotificationChannel: 'Benachrichtigungskanal hinzufügen',
enableNotificationsFirst: 'Aktivieren Sie zuerst Benachrichtigungen, um einen Kanal auszuwählen',
updateMaintenance: 'Wartung aktualisieren',
loginToViewProfile: 'Bitte melden Sie sich an, um Ihr Profil anzuzeigen',
goToLogin: 'Zum Login',
loadingUserData: 'Benutzerdaten werden geladen...',
retry: 'Erneut versuchen',
loadingServerData: 'Serverdaten werden geladen...',
retrievingYourInformation: 'Bitte warten Sie, während wir Ihre Informationen abrufen...',
servicesPagination: '{startItem}-{endItem} von {totalItems} Diensten',
servicesPaginationNoService: '0 Dienste',
};
-71
View File
@@ -1,71 +0,0 @@
import { DockerTranslations } from '../types/docker';
export const dockerTranslations: DockerTranslations = {
dockerContainers: "Docker Containers",
container: "Container",
status: "Status",
cpuUsage: "CPU Usage",
memory: "Memory",
disk: "Disk",
uptime: "Uptime",
lastChecked: "Last Checked",
actions: "Actions",
searchContainersPlaceholder: "Search containers...",
refresh: "Refresh",
openMenu: "Open menu",
viewMetrics: "View Metrics",
viewDetails: "View Details",
running: "Running",
stopped: "Stopped",
warning: "Warning",
unknown: "Unknown",
totalContainers: "Total Containers",
containersLabel: "Containers",
noContainersFound: "No containers found",
noContainersRunning: "No containers running",
tryAdjustSearch: "Try adjusting your search terms.",
startSomeContainers: "Start some containers to see them here.",
containerMetricsTitle: "Container Metrics: {name}",
dockerId: "Docker ID",
loadingMetrics: "Loading metrics...",
errorLoadingMetrics: "Error loading metrics",
noMetricsAvailable: "No metrics data available for this container",
minutes60: "60 minutes",
day1: "1 day",
days7: "7 days",
month1: "1 month",
months3: "3 months",
used: "Used:",
free: "Free:",
total: "Total:",
usage: "Usage:",
cpu: "CPU",
memoryTitle: "Memory",
diskTitle: "Disk",
network: "Network",
cpuUsagePct: "CPU Usage (%)",
cpuUsageVsAvailable: "CPU Usage vs Available",
cpuAvailablePct: "CPU Available (%)",
ramUsagePct: "RAM Usage (%)",
memoryUsageBytes: "Memory Usage (Bytes)",
usedMemory: "Used Memory",
totalMemory: "Total Memory",
diskUsagePct: "Disk Usage (%)",
diskUsageBytes: "Disk Usage (Bytes)",
usedDisk: "Used Disk",
totalDisk: "Total Disk",
networkTraffic: "Network Traffic",
networkSpeedKbs: "Network Speed (KB/s)",
rxBytes: "RX Bytes",
txBytes: "TX Bytes",
rxSpeedKbs: "RX Speed (KB/s)",
txSpeedKbs: "TX Speed (KB/s)",
};
+1 -11
View File
@@ -9,11 +9,6 @@ import { maintenanceTranslations } from './maintenance';
import { incidentTranslations } from './incident';
import { sslTranslations } from './ssl';
import { settingsTranslations } from './settings';
import { instanceTranslations } from './instance';
import { operationTranslations } from './operation';
import { regionTranslations } from './region';
import { dockerTranslations } from './docker';
import { publicTranslations } from './public';
const enTranslations: Translations = {
common: commonTranslations,
@@ -24,12 +19,7 @@ const enTranslations: Translations = {
maintenance: maintenanceTranslations,
incident: incidentTranslations,
ssl: sslTranslations,
settings: settingsTranslations,
instance: instanceTranslations,
operation: operationTranslations,
region: regionTranslations,
docker: dockerTranslations,
public: publicTranslations
settings: settingsTranslations
};
export default enTranslations;
-176
View File
@@ -1,176 +0,0 @@
import { InstanceTranslations } from '../types/instance';
export const instanceTranslations: InstanceTranslations = {
// InstanceMonitoring.tsx
instanceMonitoring: "Instance Monitoring",
describeMonitorInstance: "Monitor and manage your server instances in real-time",
addServerAgent: "Add Server Agent",
errorLoadingServers: "Error loading servers",
unableToFetchServerData: "Unable to fetch server data. Please check your connection and try again.",
retry: "Retry",
// ServerTable.tsx
servers: "Servers",
loadingServers: "Loading servers...",
searchServersPlaceholder: "Search servers...",
noServersFound: "No servers found",
deleteSelected: "Delete Selected",
deleteSelectedConfirmTitle: "Delete selected servers?",
deleteSelectedConfirmDesc: "This action cannot be undone. This will permanently delete {count} server(s) and all of their monitoring data.",
selectedCount: "{count} selected",
serversDeleted: "Servers deleted",
serversDeletedDesc: "{count} server(s) have been deleted.",
partialSuccess: "Partial success",
name: "Name",
status: "Status",
OS: "OS",
IPAddress: "IP Address",
CPU: "CPU",
memory: "Memory",
disk: "Disk",
uptime: "Uptime",
lastChecked: "Last Checked",
actions: "Actions",
viewServerDetail: "View Server Detail",
containerMonitoring: "Container Monitoring",
resumeMonitoring: "Resume Monitoring",
pauseMonitoring: "Pause Monitoring",
editServer: "Edit Server",
deleteServer: "Delete Server",
deleteServerConfirmTitle: "Are you sure you want to delete this server?",
deleteServerConfirmDesc: "This action cannot be undone. This will permanently delete {name} and all of its monitoring data.",
cancel: "Cancel",
deleting: "Deleting...",
delete: "Delete",
serverDeleted: "Server deleted",
serverDeletedDesc: "{name} has been deleted successfully.",
error: "Error",
deleteServerError: "Failed to delete server. Please try again.",
serverPaused: "Server paused",
serverResumed: "Server resumed",
monitoringPaused: "Monitoring paused for {name}",
monitoringResumed: "Monitoring resumed for {name}",
pauseServerError: "Failed to pause server monitoring. Please try again.",
resumeServerError: "Failed to resume server monitoring. Please try again.",
// server cards
totalServers: "TOTAL SERVERS",
onlineServers: "ONLINE SERVERS",
offlineServers: "OFFLINE SERVERS",
warningServers: "WARNING SERVERS",
// AddServerAgentDialog.tsx
addServerMonitoringAgent: "Add Server Monitoring Agent",
configureAgentDesc: "Configure a new server monitoring agent to track system metrics and performance.",
configureAgent: "Configure Agent",
oneClickInstall: "One-Click Install",
dockerOneClick: "Docker One-Click",
manualInstallation: "Manual Installation",
validationError: "Validation Error",
fillRequiredFields: "Please fill in all required fields.",
serverAgentCreated: "Server Agent Created",
serverAgentCreatedDesc: "{name} monitoring agent has been configured successfully.",
failedToCreateAgent: "Failed to create server monitoring agent.",
// ServerAgentConfigForm.tsx
serverName: "Server Name",
serverNamePlaceholder: "e.g., web-server-01",
serverNameDesc: "What is the name or label used as the identifier",
serverAgentId: "Server Agent ID",
serverAgentIdDesc: "Auto-generated unique identifier",
operatingSystem: "Operating System",
checkInterval: "Check Interval",
selectInterval: "Select interval",
interval30s: "30 seconds",
interval1m: "1 minute",
interval2m: "2 minutes",
interval5m: "5 minutes",
checkIntervalDesc: "How often to check the server and metric status",
retryAttempts: "Retry Attempts",
selectRetryAttempts: "Select retry attempts",
attempt1: "1 attempt",
attempt2: "2 attempts",
attempt3: "3 attempts",
attempt5: "5 attempts",
retryAttemptsDesc: "Number of retry attempts before marking as down",
serverToken: "Server Token",
serverTokenDesc: "Auto-generated authentication token",
systemUrl: "System URL",
systemUrlDesc: "Current system API URL",
creatingAgent: "Creating Agent...",
createServerAgent: "Create Server Agent"
,
// EditServerDialog.tsx
editServerConfiguration: "Edit Server Configuration",
serverNameLabel: "Server Name *",
enterServerNamePlaceholder: "Enter server name",
checkIntervalLabel: "Check Interval",
interval10m: "10 minutes",
maxRetriesLabel: "Max Retries",
selectMaxRetries: "Select max retries",
retry1: "1 retry",
retry2: "2 retries",
retry3: "3 retries",
retry5: "5 retries",
retry10: "10 retries",
dockerMonitoring: "Docker Monitoring",
enabled: "Enabled",
disabled: "Disabled",
enableNotifications: "Enable Notifications",
notificationSettings: "Notification Settings",
notificationChannels: "Notification Channels",
loadingChannels: "Loading channels...",
noChannelsAvailable: "No notification channels available",
selectedChannels: "Selected Channels:",
serverSetThreshold: "Server Set Threshold",
loadingThresholds: "Loading thresholds...",
selectServerThreshold: "Select server threshold",
noThreshold: "No threshold (use default)",
thresholdDetails: "Threshold Details",
cpuThresholdPct: "CPU Threshold (%)",
ramThresholdPct: "RAM Threshold (%)",
diskThresholdPct: "Disk Threshold (%)",
networkThresholdPct: "Network Threshold (%)",
serverTemplate: "Server Template",
loadingTemplates: "Loading templates...",
selectServerTemplate: "Select server template",
noTemplate: "No template (use default)",
templateDetails: "Template Details",
ramMessage: "RAM Message",
cpuMessage: "CPU Message",
diskMessage: "Disk Message",
networkMessage: "Network Message",
upMessage: "Up Message",
downMessage: "Down Message",
noMessageDefined: "No {name} message defined",
serverUpdated: "Server updated",
serverUpdatedDesc: "{name} has been updated successfully.",
updating: "Updating...",
updateServer: "Update Server",
failedToLoadChannels: "Failed to load notification channels",
failedToLoadTemplates: "Failed to load templates",
failedToLoadThresholds: "Failed to load server thresholds",
warning: "Warning",
serverUpdatedButThresholdFailed: "Server updated but failed to update threshold values.",
failedToUpdateServer: "Failed to update server. Please try again.",
// ServerHistoryCharts.tsx
historicalPerformance: "Historical Performance",
loading: "Loading...",
errorLoadingChartData: "Error loading chart data",
noHistoricalData: "No historical data available for {{timeRange}}",
rawMetricsCount: "Raw metrics count: {{count}}",
serverIdTimeRange: "Server ID: {{serverId}} • Time Range: {{timeRange}}",
dataExistsOutsideRange: "Data exists but may be outside selected time range",
noMetricsDataFound: "No metrics data found",
dataPointsTimeRange: "{{count}} data points • {{timeRange}}",
// updating: "Updating...",
};
-1
View File
@@ -16,7 +16,6 @@ export const loginTranslations: LoginTranslations = {
loginSuccessMessage: "You have been logged in successfully.",
loginFailed: "Login failed",
authenticationFailed: "Authentication failed",
invalidCredentials: "Invalid email or password",
bySigningIn: "By signing in, you agree to our",
termsAndConditions: "Terms & Conditions",
and: "and",
@@ -1,87 +0,0 @@
import { OperationTranslations } from '../types/operation';
export const operationTranslations: OperationTranslations = {
// OperationalPageContent.tsx
failedToLoadOperationalPages: "Failed to load operational pages",
loadingoperationalPages: "There was an error loading your operational pages. Please try again.",
tryagain: "Try Again",
operationalPages: "Operational Pages",
describeOperation: "Manage your public status pages and monitor service health",
refresh: "Refresh",
noOperationalPagesFound: "No operational pages found",
createYourFirstOperationalPage: "Create your first operational page to start monitoring your services and communicate status to your users.",
totalPages: "Total Pages",
publicPages: "Public Pages",
operational: "Operational",
deleteOperationalPage: "Delete Operational Page",
deleteOperationalPageConfirm: 'Are you sure you want to delete "{title}"? This action cannot be undone and will permanently remove the operational page and all its components.',
cancel: "Cancel",
delete: "Delete",
deleting: "Deleting...",
// EditOperationalPageDialog.tsx
editOperationalPage: "Edit Operational Page",
updateYourOperationalPage: "Update your operational status page settings and manage components.",
title: "Title",
myServiceStatusPlaceholder: "My Service Status",
slug: "Slug",
myServiceStatusSlugPlaceholder: "my-service-status",
description: "Description",
operationalPageDescriptionPlaceholder: "A brief description of your operational page",
theme: "Theme",
selectTheme: "Select theme",
themeDefault: "Default",
themeDark: "Dark",
themeLight: "Light",
status: "Status",
selectStatus: "Select status",
statusOperational: "Operational",
statusDegraded: "Degraded Performance",
statusMaintenance: "Under Maintenance",
statusMajorOutage: "Major Outage",
publicPage: "Public Page",
makePagePublic: "Make this page publicly accessible",
customDomainOptional: "Custom Domain (Optional)",
customDomainPlaceholder: "status.yourdomain.com",
customDomainDescription: "Custom domain for your status page",
cancelUpdate: "Cancel",
updating: "Updating...",
updatePage: "Update Page",
// ComponentsSelector.tsx
statusPageComponents: "Status Page Components",
addMonitoringComponentsDesc: "Add monitoring components like uptime services, SSL certificates, and incident tracking",
selectedComponents: "Selected Components",
service: "Service",
server: "Server",
addComponent: "Add Component",
componentName: "Component Name",
componentNamePlaceholder: "e.g., Main Website",
displayOrder: "Display Order",
descriptionOptional: "Description (Optional)",
descriptionPlaceholder: "Brief description of this component",
uptimeServiceOptional: "Uptime Service (Optional)",
selectUptimeService: "Select an uptime service",
serverIdOptional: "Server ID (Optional)",
serverIdPlaceholder: "server_456",
cancelComponent: "Cancel",
// OperationalPageCard.tsx
public: "Public",
yes: "Yes",
no: "No",
updated: "Updated",
view: "View",
edit: "Edit",
// CreateOperationalPageDialog.tsx
createOperationalPage: "Create Operational Page",
createOperationalPageDesc: "Create a new operational status page to monitor your services and components.",
createPage: "Create Page",
creating: "Creating...",
initialStatus: "Initial Status",
};
-23
View File
@@ -1,23 +0,0 @@
import { PublicTranslations } from '../types/public';
export const publicTranslations: PublicTranslations = {
systemStatus: "System Status",
allOperational: "All systems are operational",
degradedPerformance: "Some systems are experiencing degraded performance",
underMaintenance: "Systems are currently under maintenance",
majorOutage: "We are experiencing a major service outage",
statusUnknown: "Status unknown",
autoUpdatedByHealth: "Status automatically updated based on component health",
lastUpdatedAt: "Last updated: {time} UTC",
liveStatusMonitoring: "Live status monitoring",
loadingStatusPage: "Loading Status Page",
fetchingRealtimeStatus: "Fetching real-time system status...",
slugLabel: "Slug",
statusPageNotFound: "Status Page Not Found",
notFoundDescription: "The requested status page could not be found or is not publicly accessible.",
goBack: "Go Back",
retry: "Retry",
};
-95
View File
@@ -1,95 +0,0 @@
import { RegionTranslations } from '../types/region';
export const regionTranslations: RegionTranslations = {
//RegionalMonitoringContent.tsx
regionalmonitoring: "Regional Monitoring",
descriptRegionPage: "Monitor your infrastructure from multiple regions for better reliability.",
addRegionalAgent: "Add Regional Agent",
totalAgents: "Total Agents",
regionalMonitoringAgents: "Regional monitoring agents",
onlineAgents: "Online Agents",
currentlyConnected: "Currently connected",
offlineAgents: "Offline Agents",
disconnectedAgents: "Disconnected agents",
regionalAgents: "Regional Agents",
noRegionalAgents: "No Regional Agents",
getStartedAddAgent: "Get started by adding your first regional monitoring agent to extend your monitoring coverage.",
addFirstAgent: "Add First Agent",
agentRemoved: "Agent Removed",
agentRemovedDesc: "The regional monitoring agent has been removed.",
regionalAgentAdded: "Regional Agent Added",
regionalAgentAddedDesc: "The regional monitoring agent has been successfully configured.",
error: "Error",
failedToRemoveAgent: "Failed to remove the regional monitoring agent.",
//AddRegionalAgentDialog.tsx
addRegionalMonitoringAgent: "Add Regional Monitoring Agent",
deployRegionalMonitoringAgent: "Deploy a regional monitoring agent with automatic one-click installation.",
regionName: "Region Name",
regionNamePlaceholder: "e.g., us-east-1, europe-west-1, asia-pacific-1",
agentServerIpAddress: "Agent Server IP Address",
agentIpPlaceholder: "e.g., 192.168.1.100 or your-server.example.com",
cancel: "Cancel",
generateInstallation: "Generate Installation",
generating: "Generating...",
agentConfigurationReady: "Agent Configuration Ready!",
oneClickInstallScriptGenerated: "One-click installation script generated with automatic configuration.",
oneClickInstallTab: "One-Click Install",
agentDetailsTab: "Agent Details",
manualInstallTab: "Manual Install",
oneClickAutomaticInstallation: "One-Click Automatic Installation",
completeInstallationDescription: "Complete installation, configuration, and service startup in one command",
whatThisScriptDoes: "What this script does automatically:",
scriptActionDownload: "Downloads the latest .deb package",
scriptActionInstall: "Installs the regional monitoring agent",
scriptActionConfigure: "Creates configuration file with your settings",
scriptActionStart: "Starts and enables the service",
scriptActionHealthChecks: "Runs health checks",
runCommandOnServer: "Run this command on your target server:",
downloadCompleteScript: "Download Complete Script",
copyFullScript: "Copy Full Script",
localDevelopmentNotice: "<strong>Local Development Notice:</strong> If clipboard copying fails, this is normal in local development. You can use the 'Download Complete Script' button instead or manually copy the text.",
generatedAgentConfiguration: "Generated Agent Configuration",
autoConfiguredDuringInstallation: "These values will be automatically configured during installation",
agentId: "Agent ID",
regionNameDetail: "Region Name",
serverIp: "Server IP",
apiEndpoint: "API Endpoint",
authenticationToken: "Server Token",
createAgent: "Create Agent",
configurationFileLocation: "<strong>Configuration file location:</strong> /etc/regional-check-agent/regional-check-agent.env",
manualInstallationSteps: "Manual Installation Steps",
stepByStepManualInstallation: "Step-by-step manual installation process",
step1DownloadPackage: "Step 1: Download Package",
downloadAmd64Notice: "✅ If youre using the amd64 architecture, please download this package.",
downloadArm64Notice: "✅ If youre using the arm64 architecture, please download this package.",
step2InstallPackage: "Step 2: Install Package",
step3ConfigureAgent: "Step 3: Configure Agent",
copySampleConfiguration: "Copy sample configuration from https://github.com/operacle/Distributed-Regional-Monitoring/blob/main/packaging/regional-check-agent.conf",
addConfigurationValues: "Add the configuration values shown in the Agent Details tab",
step4StartService: "Step 4: Start Service",
step5VerifyInstallation: "Step 5: Verify Installation",
addAnotherAgent: "Add Another Agent",
completeSetup: "Complete Setup",
copied: "Copied!",
copiedDescription: "{description} copied to clipboard.",
copyFailed: "Copy failed",
copyFailedDescription: "Failed to copy to clipboard.",
copyFailedLocalhost: "This is common in local development. Please manually copy the text.",
copyFailedChrome: "Try using HTTPS or enable clipboard permissions.",
downloaded: "Downloaded!",
downloadedDescription: "Installation script downloaded successfully.",
failedToCreateAgent: "Failed to create regional agent configuration.",
//RegionalAgentCard.tsx
defaultBadge: "Default",
copyAgentId: "Copy Agent ID",
removeAgent: "Remove Agent",
online: "Online",
offline: "Offline",
lastUpdated: "Last Updated:",
activeMonitoring: "Active monitoring",
connectionLost: "Connection lost",
};
@@ -88,7 +88,6 @@ export const servicesTranslations: ServicesTranslations = {
serviceNameRequired: "Service name is required",
urlDomainHostRequired: "URL/Domain/Host is required",
enterValidUrlHostnameDomain: "Please enter a valid URL, hostname, or domain",
spacesNotAllowed: "Spaces are not allowed",
// Dashboard
upServices: "UP SERVICES",
@@ -137,65 +136,4 @@ export const servicesTranslations: ServicesTranslations = {
processing: "Processing",
back: "Back",
last20Checks: "Last 20 checks",
//OneClickInstallTab.tsx
oneClickInstallTitle: "One-Click Install (Recommended)",
oneClickInstallDesc: "Copy and paste this single command to install the monitoring agent instantly",
quickInstallCommand: "Quick Install Command",
copy: "Copy",
runCommandOnServer: "Simply run this command on your server:",
sshIntoServer: "SSH into your target server",
pasteAndRun: "Paste and run the command above",
agentInstalled: "The agent will be installed and started automatically",
done: "Done",
// DockerOneClickTab.tsx
dockerOneClickTitle: "Docker One-Click Install",
dockerOneClickDesc: "Automated Docker container installation with system monitoring capabilities",
dockerOneClickCommand: "Docker One-Click Command",
dockerScriptWill: "This script will automatically:",
dockerScriptStep1: "Download and setup the Docker monitoring agent",
dockerScriptStep2: "Configure all required environment variables",
dockerScriptStep3: "Start the container with proper system access",
dockerScriptStep4: "Setup monitoring data persistence",
directDockerTitle: "Direct Docker Run Command",
directDockerDesc: "If you prefer to run the Docker container directly without the script",
dockerRunCommand: "Docker Run Command",
dockerPrerequisites: "Prerequisites for direct Docker run:",
dockerPrereqStep1: "Docker must be installed and running",
dockerPrereqStep2: "The operacle/checkcle-server-agent image must be available",
dockerPrereqStep3: "Run as root or with sudo privileges",
// ManualInstallTab.tsx
manualInstallTitle: "Manual Installation Steps",
manualInstallDesc: "Step-by-step installation process",
serverName: "Server Name",
agentId: "Agent ID",
osType: "OS Type",
downloadScript: "Download the installation script",
makeExecutable: "Make the script executable",
runInstall: "Run the installation with your configuration",
prerequisites: "Prerequisites:",
prereqRoot: "Ensure you have root/sudo access on the target server",
prereqCurl: "Make sure curl is installed for downloading files",
prereqInternet: "Internet connection required for downloading script",
afterInstall: "After Installation:",
agentWillStart: "The agent will start automatically and appear in your dashboard within a few minutes.",
// ServerDetail.tsx
errorLoadingServer: "Error loading server",
unableToFetchServerData: "Unable to fetch server data. Please check your connection and try again.",
backToServers: "Back to Servers",
loadingServerDetails: "Loading server details...",
serverDetail: "Server Detail",
monitorServerMetrics: "Monitor server performance metrics and system health",
serverHostnameIpOs: "{hostname} • {ip_address} • {os_type}",
// ContainerMonitoring.tsx
errorLoadingContainers: "Error loading containers",
unableToFetchContainerData: "Unable to fetch container data. Please check your connection and try again.",
errorUnknown: "Unknown error",
containerMonitoring: "Container Monitoring",
monitorAndManageContainers: "Monitor and manage your Docker containers in real-time",
serverIdLabel: "Server ID",
};
-114
View File
@@ -60,118 +60,4 @@ export const settingsTranslations: SettingsTranslations = {
permissionNoticeAddUser: "As an admin user, you do not have access to view or modify system and mail settings. These settings can only be accessed and modified by Super Admins. Contact your Super Admin if you need to make changes to system configuration or mail settings.",
loadingSettings: "Loading settings...",
loadingSettingsError: "Error loading settings",
//NotificationSettings.ts
titleNotification: "Notification Settings",
descriptionChannelsServices: "Configure notification channels for your services",
addChannel: "Add Channel",
all: "All Channels",
telegram: "Telegram",
discord: "Discord",
slack: "Slack",
signal: "Signal",
googleChat: "Google Chat",
email: "Email",
webhook: "Webhook",
matrix: "Matrix",
// NotificationChannelDialog.tsx
editChannel: "Edit Notification Channel",
addChannelDialog: "Add Notification Channel",
channelName: "Channel Name",
channelNameDesc: "A name to identify this notification channel",
channelType: "Channel Type",
selectType: "Select notification type",
enabled: "Enabled",
enabledDesc: "Enable or disable this notification channel",
cancel: "Cancel",
updateChannel: "Update Channel",
createChannel: "Create Channel",
payloadTemplates: "Payload Templates",
availablePlaceholders: "Available Placeholders:",
server: "Server",
service: "Service",
ssl: "SSL",
common: "Common",
webhookUrl: "Webhook URL",
webhookUrlDesc: "The URL where webhook notifications will be sent",
payloadTemplate: "Payload Template (Optional)",
payloadTemplateDesc: "JSON template for the webhook payload. Leave empty to use default template.",
telegramChatId: "Chat ID",
telegramChatIdDesc: "The Telegram chat ID to send notifications to",
botToken: "Bot Token",
botTokenDesc: "Your Telegram bot token from @BotFather",
discordWebhookUrl: "Webhook URL",
discordWebhookUrlDesc: "Discord webhook URL from your server settings",
slackWebhookUrl: "Webhook URL",
slackWebhookUrlDesc: "Slack incoming webhook URL",
signalNumber: "Signal Number",
signalNumberDesc: "Signal phone number to send notifications to",
signalApiEndpoint: "Signal API Endpoint",
signalApiEndpointDesc: "The Rest API endpoint for your Signal service",
googleChatWebhookUrl: "Google Chat Webhook URL",
googleChatWebhookUrlDesc: "Google Chat webhook URL from your Google Chat space",
emailAddress: "Email Address",
emailAddressDesc: "Email address to send notifications to",
emailSenderName: "Sender Name",
emailSenderNameDesc: "Display name for outgoing emails",
smtpServer: "SMTP Server",
// smtpPort: "SMTP Port",
// smtpPassword: "SMTP Password",
smtpPasswordDesc: "Password for authenticating with the SMTP server",
ntfyEndpoint: "NTFY Endpoint",
ntfyEndpointDesc: "The NTFY endpoint URL including your topic (e.g., https://ntfy.sh/checkcle)",
apiToken: "API Token",
apiTokenOptional: "API Token (Optional)",
apiTokenDesc: "Optional API token for authentication with NTFY server",
pushoverUserKey: "User Key",
pushoverUserKeyDesc: "Your Pushover user key (or group key)",
notifiarrChannelId: "Channel ID",
notifiarrChannelIdDesc: "The Discord channel ID where notifications will be sent",
gotifyServerUrl: "Server URL",
gotifyServerUrlDesc: "The URL of your Gotify server",
matrixHomeserver: "Homeserver URL",
matrixHomeserverDesc: "The URL of your Matrix homeserver (e.g. https://matrix.org)",
matrixRoomId: "Room ID",
matrixRoomIdDesc: "The Matrix room ID to send notifications to (e.g. !abc123:matrix.org)",
matrixAccessToken: "Access Token",
matrixAccessTokenDesc: "The access token of your Matrix bot account",
errorSaveChannel: "Failed to save notification channel",
channelNamePlaceholder: "My Notification Channel",
telegramChatIdPlaceholder: "Telegram Chat ID",
botTokenPlaceholder: "Telegram Bot Token",
discordWebhookUrlPlaceholder: "https://discord.com/api/webhooks/...",
slackWebhookUrlPlaceholder: "https://hooks.slack.com/services/...",
signalNumberPlaceholder: "+1234567890",
signalApiEndpointPlaceholder: "https://your-signal-api.com/v2/send",
googleChatWebhookUrlPlaceholder: "https://chat.googleapis.com/v1/spaces/...",
emailAddressPlaceholder: "notifications@example.com",
emailSenderNamePlaceholder: "Alert System",
smtpServerPlaceholder: "smtp.gmail.com",
smtpPortPlaceholder: "587",
smtpPasswordPlaceholder: "Enter your SMTP password",
ntfyEndpointPlaceholder: "https://ntfy.sh/your-topic",
apiTokenPlaceholder: "Enter API token",
pushoverUserKeyPlaceholder: "Your Pushover user key",
notifiarrChannelIdPlaceholder: "Discord Channel ID",
gotifyServerUrlPlaceholder: "https://your-gotify-server.com",
webhookUrlPlaceholder: "https://api.example.com/webhook",
matrixHomeserverPlaceholder: "https://matrix.org",
matrixRoomIdPlaceholder: "!roomid:matrix.org",
matrixAccessTokenPlaceholder: "syt_...",
// DataRetentionSettings.tsx
// permissionNotice: "Permission Notice:",
permissionNoticeDataRetention: "As an admin user, you do not have access to data retention settings. These settings can only be accessed and modified by Super Admins.",
loadingRetentionSettings: "Loading retention settings...",
dataRetention: "Data Retention Settings",
dataRetentionDescription: "Configure how long monitoring data is kept in the system",
uptimeRetentionLabel: "Uptime Monitoring Retention (days)",
uptimeRetentionHelp: "Service uptime and incident data older than this will be automatically deleted",
serverRetentionLabel: "Server Monitoring Retention (days)",
serverRetentionHelp: "Server metrics and process data older than this will be automatically deleted",
lastCleanup: "Last automatic cleanup",
// save: "Save Changes"
};
-1
View File
@@ -15,7 +15,6 @@ export const loginTranslations: LoginTranslations = {
loginSuccessMessage: "正常にログインしました。",
loginFailed: "ログイン失敗",
authenticationFailed: "認証に失敗しました",
invalidCredentials: "メールアドレスまたはパスワードが正しくありません",
bySigningIn: "サインインすることで、",
termsAndConditions: "利用規約",
and: "と",
+1 -22
View File
@@ -64,25 +64,4 @@ export const maintenanceTranslations: MaintenanceTranslations = {
noScheduledMaintenance: 'スケジュール済みメンテナンスなし',
noMaintenanceWindows: 'この期間にメンテナンスウィンドウはありません。「メンテナンス作成」ボタンをクリックして作成してください。',
maintenanceCreatedSuccess: 'メンテナンスウィンドウが正常に作成されました',
assignedPersonnelDescription: '現在割り当てられているユーザー',
editMaintenanceDesc: 'メンテナンス詳細を編集',
editMaintenanceWindow: 'メンテナンス編集',
enableNotificationsFirst: 'チャンネルを選択するには先に通知を有効にしてください',
goToLogin: 'ログインへ',
impactLevel: '影響レベル',
impactLevelDescription: '影響レベルを選択',
loadingServerData: 'サーバーデータを読み込み中...',
loadingUserData: 'ユーザーデータを読み込み中...',
loginToViewProfile: 'プロフィールを表示するにはログインしてください',
mutedNotifications: '通知が無効になっています',
notificationsAreMuted: 'このメンテナンスでは現在通知がミュートされています',
priorityDescription: 'メンテナンス優先度を選択',
retrievingYourInformation: '情報を取得しています。しばらくお待ちください...',
retry: '再試行',
selectAssignedUsers: '割り当てユーザーを選択',
selectNotificationChannel: '通知チャンネルを追加',
servicesPagination: '{startItem}-{endItem} / {totalItems} サービス',
servicesPaginationNoService: '0 サービス',
statusDescription: 'メンテナンスステータスを選択',
updateMaintenance: 'メンテナンスを更新',
};
};
-15
View File
@@ -16,19 +16,4 @@ export const aboutTranslations: AboutTranslations = {
quickActionsDescription: "ចូលប្រើប្រតិបត្តិការត្រួតពិនិត្យ និងមុខងារទូទៅយ៉ាងរហ័ស។ ជ្រើសរើសសកម្មភាពខាងក្រោមដើម្បីចាប់ផ្តើម។",
quickTips: "គន្លឹះរហ័ស",
releasedOn: "បានចេញផ្សាយនៅថ្ងៃទី",
updateSchema: "ធ្វើបច្ចុប្បន្នភាព Schema",
updateSchemaDesc: "បញ្ចូល Schema នៃការប្រមូលដោយស្វ័យប្រវត្តិ",
mergeFieldsLabel: "បញ្ចូល fields ជាមួយនឹងការប្រមូលដែលមានស្រាប់ (សុវត្ថិភាព - រក្សាទិន្នន័យ)",
importing: "កំពុងបញ្ចូល...",
clickToUpdateSchema: "ចុចដើម្បីធ្វើបច្ចុប្បន្នភាព Schema",
importSuccessful: "បញ្ចូលជោគជ័យ",
importFailed: "បញ្ចូលបរាជ័យ",
instructions: "ការណែនាំ",
mergeFields: "បញ្ចូល fields",
instructionsMergeFields: "បន្ថែម fields ថ្មីទៅក្នុងការប្រមូលដែលមានស្រាប់ដោយសុវត្ថិភាព រក្សាទុកទិន្នន័យទាំងអស់",
instructionsCollections: "ការប្រមូលប្រព័ន្ធ (ចាប់ផ្តើមដោយ _) និងការប្រមូលអ្នកប្រើប្រាស់នឹងត្រូវរំលងដោយស្វ័យប្រវត្តិ",
instructionsImportAuth: "មានតែអ្នកគ្រប់គ្រងដែលបានផ្ទៀងផ្ទាត់អត្តសញ្ញាណប៉ុណ្ណោះអាចធ្វើការបញ្ចូល Schema",
collectionsUpdatedCount: "ការប្រមូលចំនួន {count} ត្រូវបានធ្វើបច្ចុប្បន្នភាព",
collectionsCreatedCount: "ការប្រមូលចំនួន {count} ត្រូវបានបង្កើត",
collectionsSkippedCount: "ការប្រមូលចំនួន {count} ត្រូវបានរំលង"
};
-71
View File
@@ -1,71 +0,0 @@
import { DockerTranslations } from '../types/docker';
export const dockerTranslations: DockerTranslations = {
dockerContainers: "Containers Docker",
container: "Containers",
status: "ស្ថានភាព",
cpuUsage: "ការប្រើប្រាស់ CPU",
memory: "អង្គចងចាំ",
disk: "ថាស",
uptime: "ពេលដំណើរការ",
lastChecked: "បានពិនិត្យចុងក្រោយ",
actions: "សកម្មភាព",
searchContainersPlaceholder: "ស្វែងរកContainers...",
refresh: "ធ្វើបច្ចុប្បន្នភាព",
openMenu: "បើកម៉ឺនុយ",
viewMetrics: "មើលមេត្រីក",
viewDetails: "មើលព័ត៌មានលម្អិត",
running: "ដំណើរការ",
stopped: "បានបញ្ឈប់",
warning: "ការព្រមាន",
unknown: "មិនស្គាល់",
totalContainers: "Containers សរុប",
containersLabel: "Containers",
noContainersFound: "រកមិនឃើញContainers",
noContainersRunning: "គ្មានContainersកំពុងដំណើរការ",
tryAdjustSearch: "សូមព្យាយាមកែសម្រួលពាក្យស្វែងរករបស់អ្នក។",
startSomeContainers: "ចាប់ផ្តើមContainersខ្លះៗ ដើម្បីមើលពួកវានៅទីនេះ។",
containerMetricsTitle: "មេត្រីកContainers: {name}",
dockerId: "Docker ID",
loadingMetrics: "កំពុងផ្ទុកមេត្រីក...",
errorLoadingMetrics: "កំហុសក្នុងការផ្ទុកមេត្រីក",
noMetricsAvailable: "គ្មានទិន្នន័យមេត្រីកសម្រាប់Containersនេះ",
minutes60: "៦០ នាទី",
day1: "១ ថ្ងៃ",
days7: "៧ ថ្ងៃ",
month1: "១ ខែ",
months3: "៣ ខែ",
used: "បានប្រើ:",
free: "ទំនេរ:",
total: "សរុប:",
usage: "ការប្រើប្រាស់:",
cpu: "CPU",
memoryTitle: "អង្គចងចាំ",
diskTitle: "ថាស",
network: "បណ្តាញ",
cpuUsagePct: "ការប្រើប្រាស់ CPU (%)",
cpuUsageVsAvailable: "ការប្រើប្រាស់ CPU នឹង អាចប្រើបាន",
cpuAvailablePct: "CPU អាចប្រើបាន (%)",
ramUsagePct: "ការប្រើប្រាស់ RAM (%)",
memoryUsageBytes: "ការប្រើប្រាស់អង្គចងចាំ (បៃ)",
usedMemory: "អង្គចងចាំបានប្រើ",
totalMemory: "អង្គចងចាំសរុប",
diskUsagePct: "ការប្រើប្រាស់ថាស (%)",
diskUsageBytes: "ការប្រើប្រាស់ថាស (បៃ)",
usedDisk: "ថាសបានប្រើ",
totalDisk: "ថាសសរុប",
networkTraffic: "ចរាចរបណ្តាញ",
networkSpeedKbs: "ល្បឿនបណ្តាញ (KB/s)",
rxBytes: "RX បៃ",
txBytes: "TX បៃ",
rxSpeedKbs: "ល្បឿន RX (KB/s)",
txSpeedKbs: "ល្បឿន TX (KB/s)",
};
@@ -53,13 +53,4 @@ export const incidentTranslations: IncidentTranslations = {
failedToUpdateStatus: "បរាជ័យក្នុងការធ្វើបច្ចុប្បន្នភាពស្ថានភាព",
inProgress: "កំពុងដំណើរការ",
enterRootCause: 'បញ្ចូលហេតុផលដើម',
enterIncidentTitle: "បញ្ចូលចំណងជើងឧបទ្ទវហេតុ",
enterIncidentDescription: "បញ្ចូលការពិពណ៌នាអំពីឧបទ្ទវហេតុ",
enterServiceId: "បញ្ចូលលេខសម្គាល់សេវាកម្ម ដោយបំបែកដោយសញ្ញាក្បៀស",
selectAssignedUser: "ជ្រើសរើសអ្នកប្រើប្រាស់ដែលត្រូវបានចាត់តាំង",
noAssignedUser: "ឧបទ្ទវហេតុបច្ចុប្បន្នមិនត្រូវបានចាត់តាំងទៅអ្នកប្រើប្រាស់ណាមួយទេ",
affectedSystems: "ប្រព័ន្ធដែលរងផលប៉ះពាល់",
enterAffectedSystems: "បញ្ចូលប្រព័ន្ធដែលរងផលប៉ះពាល់",
separateSystemsWithComma: "បញ្ចូលប្រព័ន្ធដែលរងផលប៉ះពាល់ ដោយបំបែកដោយសញ្ញាក្បៀស",
createIncidentDesc: "បង្កើតឧបទ្ទវហេតុថ្មី"
};
+1 -12
View File
@@ -9,11 +9,6 @@ import { maintenanceTranslations } from './maintenance';
import { incidentTranslations } from './incident';
import { sslTranslations } from './ssl';
import { settingsTranslations } from './settings';
import { instanceTranslations } from './instance';
import { operationTranslations } from './operation';
import { regionTranslations } from './region';
import { dockerTranslations } from './docker';
import { publicTranslations } from './public';
const enTranslations: Translations = {
common: commonTranslations,
@@ -24,13 +19,7 @@ const enTranslations: Translations = {
maintenance: maintenanceTranslations,
incident: incidentTranslations,
ssl: sslTranslations,
settings: settingsTranslations,
instance: instanceTranslations,
operation: operationTranslations,
region: regionTranslations,
docker: dockerTranslations,
public: publicTranslations
settings: settingsTranslations
};
export default enTranslations;
-165
View File
@@ -1,165 +0,0 @@
import { InstanceTranslations } from '../types/instance';
export const instanceTranslations: InstanceTranslations = {
// InstanceMonitoring.tsx
instanceMonitoring: "ការត្រួតពិនិត្យឧទាហរណ៍",
describeMonitorInstance: "ត្រួតពិនិត្យនិងគ្រប់គ្រងឧទាហរណ៍ម៉ាស៊ីនមេរបស់អ្នកក្នុងពេលជាក់ស្តែង",
addServerAgent: "បន្ថែមភ្នាក់ងារម៉ាស៊ីនមេ",
errorLoadingServers: "កំហុសក្នុងការផ្ទុកម៉ាស៊ីនមេ",
unableToFetchServerData: "មិនអាចទាញយកទិន្នន័យម៉ាស៊ីនមេបានទេ។ សូមពិនិត្យការតភ្ជាប់របស់អ្នក ហើយព្យាយាមម្តងទៀត។",
retry: "ព្យាយាមម្តងទៀត",
// ServerTable.tsx
servers: "ម៉ាស៊ីនមេ",
loadingServers: "កំពុងផ្ទុកម៉ាស៊ីនមេ...",
searchServersPlaceholder: "ស្វែងរកម៉ាស៊ីនមេ...",
noServersFound: "រកមិនឃើញម៉ាស៊ីនមេ",
name: "ឈ្មោះ",
status: "ស្ថានភាព",
OS: "ប្រព័ន្ធប្រតិបត្តិការ",
IPAddress: "អាសយដ្ឋាន IP",
CPU: "ស៊ីភីយូ",
memory: "អង្គចងចាំ",
disk: "ថាស",
uptime: "ពេលវេលាដំណើរការ",
lastChecked: "បានពិនិត្យចុងក្រោយ",
actions: "សកម្មភាព",
viewServerDetail: "មើលព័ត៌មានលម្អិតម៉ាស៊ីនមេ",
containerMonitoring: "ការត្រួតពិនិត្យ Container",
resumeMonitoring: "បន្តការត្រួតពិនិត្យ",
pauseMonitoring: "ផ្អាកការត្រួតពិនិត្យ",
editServer: "កែសម្រួលម៉ាស៊ីនមេ",
deleteServer: "លុបម៉ាស៊ីនមេ",
deleteServerConfirmTitle: "តើអ្នកប្រាកដថាចង់លុបម៉ាស៊ីនមេនេះទេ?",
deleteServerConfirmDesc: "សកម្មភាពនេះមិនអាចត្រឡប់វិញបានទេ។ វានឹងលុប {name} និងទិន្នន័យត្រួតពិនិត្យទាំងអស់របស់វាជាអចិន្ត្រៃយ៍។",
cancel: "បោះបង់",
deleting: "កំពុងលុប...",
delete: "លុប",
serverDeleted: "ម៉ាស៊ីនមេត្រូវបានលុប",
serverDeletedDesc: "{name} ត្រូវបានលុបដោយជោគជ័យ។",
error: "កំហុស",
deleteServerError: "បរាជ័យក្នុងការលុបម៉ាស៊ីនមេ។ សូមព្យាយាមម្តងទៀត។",
serverPaused: "ម៉ាស៊ីនមេត្រូវបានផ្អាក",
serverResumed: "ម៉ាស៊ីនមេត្រូវបានបន្ត",
monitoringPaused: "ការត្រួតពិនិត្យត្រូវបានផ្អាកសម្រាប់ {name}",
monitoringResumed: "ការត្រួតពិនិត្យត្រូវបានបន្តសម្រាប់ {name}",
pauseServerError: "បរាជ័យក្នុងការផ្អាកការត្រួតពិនិត្យម៉ាស៊ីនមេ។ សូមព្យាយាមម្តងទៀត។",
resumeServerError: "បរាជ័យក្នុងការបន្តការត្រួតពិនិត្យម៉ាស៊ីនមេ। សូមព្យាយាមម្តងទៀត។",
// ServerStatsCards.tsx
totalServers: "ម៉ាស៊ីនមេសរុប",
onlineServers: "ម៉ាស៊ីនមេដំណើរការ",
offlineServers: "ម៉ាស៊ីនមេផ្អាកដំណើរការ",
warningServers: "ម៉ាស៊ីនមេដែលមានការព្រមាន",
// AddServerAgentDialog.tsx
addServerMonitoringAgent: "បន្ថែមភ្នាក់ងារត្រួតពិនិត្យម៉ាស៊ីនមេ",
configureAgentDesc: "កំណត់រចនាសម្ព័ន្ធភ្នាក់ងារត្រួតពិនិត្យម៉ាស៊ីនមេថ្មីដើម្បីតាមដានម៉ែត្រប្រព័ន្ធ និងប្រសិទ្ធភាព។",
configureAgent: "កំណត់រចនាសម្ព័ន្ធភ្នាក់ងារ",
oneClickInstall: "ការដំឡើងតែមួយចុច",
dockerOneClick: "Docker ការដំឡើងតែមួយចុច",
manualInstallation: "ការដំឡើងដោយដៃ",
validationError: "កំហុសក្នុងការផ្ទៀងផ្ទាត់",
fillRequiredFields: "សូមបំពេញចន្លោះទាំងអស់ដែលតម្រូវឱ្យមាន។",
serverAgentCreated: "ភ្នាក់ងារម៉ាស៊ីនមេត្រូវបានបង្កើត",
serverAgentCreatedDesc: "ភ្នាក់ងារត្រួតពិនិត្យ {name} ត្រូវបានកំណត់រចនាសម្ព័ន្ធដោយជោគជ័យ។",
failedToCreateAgent: "បរាជ័យក្នុងការបង្កើតភ្នាក់ងារត្រួតពិនិត្យម៉ាស៊ីនមេ។",
// ServerAgentConfigForm.tsx
serverName: "ឈ្មោះម៉ាស៊ីនមេ",
serverNamePlaceholder: "ឧ. web-server-01",
serverNameDesc: "ឈ្មោះ ឬស្លាកដែលប្រើជាអត្តសញ្ញាណ",
serverAgentId: "លេខសម្គាល់ភ្នាក់ងារម៉ាស៊ីនមេ",
serverAgentIdDesc: "លេខសម្គាល់តែមួយគត់ដែលបង្កើតដោយស្វ័យប្រវត្តិ",
operatingSystem: "ប្រព័ន្ធប្រតិបត្តិការ",
checkInterval: "ចន្លោះពេលពិនិត្យ",
selectInterval: "ជ្រើសរើសចន្លោះពេល",
interval30s: "៣០ វិនាទី",
interval1m: "១ នាទី",
interval2m: "២ នាទី",
interval5m: "៥ នាទី",
checkIntervalDesc: "ភាពញឹកញាប់នៃការពិនិត្យស្ថានភាពម៉ាស៊ីនមេ និងម៉ែត្រ",
retryAttempts: "ការព្យាយាមឡើងវិញ",
selectRetryAttempts: "ជ្រើសរើសចំនួនការព្យាយាមឡើងវិញ",
attempt1: "១ ការព្យាយាម",
attempt2: "២ ការព្យាយាម",
attempt3: "៣ ការព្យាយាម",
attempt5: "៥ ការព្យាយាម",
retryAttemptsDesc: "ចំនួនការព្យាយាមឡើងវិញមុនពេលសម្គាល់ថាដាច់",
serverToken: "សញ្ញាសម្ងាត់ម៉ាស៊ីនមេ",
serverTokenDesc: "សញ្ញាសម្ងាត់ផ្ទៀងផ្ទាត់ដែលបង្កើតដោយស្វ័យប្រវត្តិ",
systemUrl: "URL ប្រព័ន្ធ",
systemUrlDesc: "URL API ប្រព័ន្ធបច្ចុប្បន្ន",
creatingAgent: "កំពុងបង្កើតភ្នាក់ងារ...",
createServerAgent: "បង្កើតភ្នាក់ងារម៉ាស៊ីនមេ",
// EditServerDialog.tsx
editServerConfiguration: "កែសម្រួលការកំណត់រចនាសម្ព័ន្ធម៉ាស៊ីនមេ",
serverNameLabel: "ឈ្មោះម៉ាស៊ីនមេ *",
enterServerNamePlaceholder: "បញ្ចូលឈ្មោះម៉ាស៊ីនមេ",
checkIntervalLabel: "ចន្លោះពេលពិនិត្យ",
// selectInterval: "ជ្រើសរើសចន្លោះពេល",
interval10m: "១០ នាទី",
maxRetriesLabel: "ការព្យាយាមឡើងវិញអតិបរិមា",
selectMaxRetries: "ជ្រើសរើសការព្យាយាមអតិបរិមា",
retry1: "១ ដង",
retry2: "២ ដង",
retry3: "៣ ដង",
retry5: "៥ ដង",
retry10: "១០ ដង",
dockerMonitoring: "ការត្រួតពិនិត្យ Docker",
enabled: "បានបើក",
disabled: "បានបិទ",
enableNotifications: "បើកការជូនដំណឹង",
notificationSettings: "ការកំណត់ការជូនដំណឹង",
notificationChannels: "ឆានែលការជូនដំណឹង",
loadingChannels: "កំពុងផ្ទុកឆានែល...",
noChannelsAvailable: "មិនមានឆានែលការជូនដំណឹង",
selectedChannels: "ឆានែលដែលបានជ្រើស:",
serverSetThreshold: "កំណត់កម្រិតម៉ាស៊ីនមេ",
loadingThresholds: "កំពុងផ្ទុកកម្រិត...",
selectServerThreshold: "ជ្រើសរើសកម្រិតម៉ាស៊ីនមេ",
noThreshold: "គ្មានកម្រិត (ប្រើលំនាំដើម)",
thresholdDetails: "ព័ត៌មានលម្អិតអំពីកម្រិត",
cpuThresholdPct: "កម្រិត CPU (%)",
ramThresholdPct: "កម្រិត RAM (%)",
diskThresholdPct: "កម្រិតថាស (%)",
networkThresholdPct: "កម្រិតបណ្តាញ (%)",
serverTemplate: "គម្រូម៉ាស៊ីនមេ",
loadingTemplates: "កំពុងផ្ទុកគម្រូ...",
selectServerTemplate: "ជ្រើសរើសគម្រូម៉ាស៊ីនមេ",
noTemplate: "គ្មានគម្រូ (ប្រើលំនាំដើម)",
templateDetails: "ព័ត៌មានលម្អិតអំពីគម្រូ",
ramMessage: "សារ RAM",
cpuMessage: "សារ CPU",
diskMessage: "សារ ថាស",
networkMessage: "សារ បណ្តាញ",
upMessage: "សារដំណើរការ",
downMessage: "សារផ្អាក",
noMessageDefined: "គ្មានសារសម្រាប់ {name}",
serverUpdated: "បានធ្វើបច្ចុប្បន្នភាពម៉ាស៊ីនមេ",
serverUpdatedDesc: "{name} ត្រូវបានធ្វើបច្ចុប្បន្នភាពដោយជោគជ័យ។",
updating: "កំពុងធ្វើបច្ចុប្បន្នភាព...",
updateServer: "ធ្វើបច្ចុប្បន្នភាពម៉ាស៊ីនមេ",
failedToLoadChannels: "បានបរាជ័យក្នុងការផ្ទុកឆានែលការជូនដំណឹង",
failedToLoadTemplates: "បានបរាជ័យក្នុងការផ្ទុកគម្រូ",
failedToLoadThresholds: "បានបរាជ័យក្នុងការផ្ទុកកម្រិតម៉ាស៊ីនមេ",
warning: "ការព្រមាន",
serverUpdatedButThresholdFailed: "ម៉ាស៊ីនមេត្រូវបានធ្វើបច្ចុប្បន្នភាព ប៉ុន្តែបរាជ័យក្នុងការធ្វើបច្ចុប្បន្នភាពតម្លៃកម្រិត។",
failedToUpdateServer: "បរាជ័យក្នុងការធ្វើបច្ចុប្បន្នភាពម៉ាស៊ីនមេ។ សូមព្យាយាមម្តងទៀត।",
// ServerDetail.tsx
historicalPerformance: "សម្ដែងប្រវត្តិប្រតិបត្តិការ",
loading: "កំពុងផ្ទុក...",
errorLoadingChartData: "មានបញ្ហាក្នុងការផ្ទុកទិន្នន័យតារាង",
noHistoricalData: "មិនមានទិន្នន័យចាស់សម្រាប់ {{timeRange}}",
rawMetricsCount: "ចំនួនមេត្រដើម៖ {{count}}",
serverIdTimeRange: "លេខសម្គាល់ម៉ាស៊ីនបម្រើ៖ {{serverId}} • ជួរពេលវេលា៖ {{timeRange}}",
dataExistsOutsideRange: "ទិន្នន័យមាន ប៉ុន្តែអាចនៅខាងក្រៅជួរពេលវេលាដែលបានជ្រើស",
noMetricsDataFound: "រកមិនឃើញទិន្នន័យមេត្រទេ",
dataPointsTimeRange: "{{count}} ចំណុចទិន្នន័យ • {{timeRange}}",
// updating: "កំពុងធ្វើបច្ចុប្បន្នភាព...",
};

Some files were not shown because too many files have changed in this diff Show More