31 Commits

Author SHA1 Message Date
Tola Leng 6462e5c551 Merge pull request #129 from operacle/develop
feat: Implement comprehensive powerful multi-channel notification system with templating:
- Add robust notification system supporting 7+ communication channels with intelligent message templating, resource monitoring, and SSL certificate alerts. Notification Channels: (Telegram, Discord, Slack, Signal, Email, Google Chat, Webhooks).
- This notification system provides enterprise-grade alerting capabilities with extensive customization options and multi-channel redundancy for critical service monitoring.
- Chinese language added
- Server and Service Table row clickable to detail page.
- Implement pagination for the SSL dashboard table
- Server Agent (RPM, Docker container, and general binary package) 
- Improve Uptime Service and Server connection update based on status and notification.
- Improve SSL perform the initial check automatically after creation 
- Backend Rate limiting and abuse protection
2025-08-14 23:01:14 +07:00
Tola Leng 80a2eb383d Merge pull request #112 from operacle/develop
feat: add docker compose for server docker agent and Fix: Add tar.gz fallback for unsupported systems
and other improvement
2025-07-31 04:10:06 +07:00
Tola Leng 27ee133e92 Merge pull request #84 from operacle/develop
Updated GitHub issue templates for Bug Report, Help Request,...
2025-07-23 22:56:43 +07:00
Tola Leng af64ac31ea Merge pull request #83 from operacle/develop
Fix: Display new service immediately
2025-07-23 22:29:48 +07:00
Tola Leng 72984f5da4 Merge pull request #79 from operacle/develop
feat: Add create instance monitoring agent and Add Uptime Heatmap to service detail page
2025-07-22 16:08:14 +07:00
Tola Leng cc132a66d9 Merge pull request #70 from operacle/develop
- Improve service listing to display all records correctly
- Fetch all data and handle pagination for better UX
- Improve SSL Certs listing to display all records correctly
- Added ISSUE TEMPLATE 
- Added CODE OF CONDUCT
2025-07-15 22:18:48 +07:00
Tola Leng 3f975db568 Merge pull request #68 from operacle/develop
- feat: Implement notification channels based on status (Service dialog form) and refactor Service form into smaller components
- feat: Allow multiple selections for regional agents and support multiple notifications in the Service form
- feat: Add Japanese language support. Thank you @gnsworks for the contribution!
2025-07-13 18:44:44 +07:00
Tola Leng 547a4c4041 Merge pull request #65 from operacle/develop
feat: Implement notification channel based on status(multi selection) and Refactor Split ServiceForm into smaller components.
2025-07-10 22:17:02 +07:00
Tola Leng e29f60447d Merge pull request #64 from operacle/develop
feat: Improve server overview cards and fix regional_status to Service type
2025-07-08 22:03:15 +07:00
Tola Leng ad869c17aa add codeowners and pull request workflow 2025-07-03 21:03:09 +07:00
Tola Leng 6702bfa5e3 Merge pull request #62 from operacle/develop
Fix: Instance monitoring dashboard styling and Improved docker compose configuration
2025-07-03 20:59:59 +07:00
Tola Leng cb6946b7dd Create FUNDING.yml 2025-07-03 20:56:11 +07:00
Tola Leng 8bd8ae25e6 Merge pull request #61 from operacle/develop
Fix: Server Historical Performance Metrics date filter and improved the container entrypoint script pipeline
2025-07-02 20:05:50 +07:00
Tola Leng eddc12018f Merge pull request #60 from operacle/develop
Fix: Server history chart and date filter and Added Distributed Regional Monitoring Dockerfile
2025-07-01 20:07:23 +07:00
Tola Leng 474a439515 Merge pull request #59 from operacle/develop
feat: Implement instance and docker monitoring dashboard and detail metrics page
2025-06-30 23:07:58 +07:00
Tola Leng 9a4cc7c3db Merge pull request #57 from operacle/develop
Refactor: Separate data display by monitoring source and feat: Implement "Regional Monitoring" option
2025-06-26 16:28:32 +07:00
Tola Leng 23f3c5b8ca Merge pull request #53 from operacle/develop
Integrate regional agents in service-operation and Enhance Regional Agent Installation
2025-06-21 21:49:19 +07:00
Tola Leng f88cc32cf9 Merge pull request #52 from operacle/develop
Implement SSL certificate checker in Go instead of TS and feat: Add error message and details columns
2025-06-20 20:24:55 +07:00
Tola Leng 9f4e759b01 Merge pull request #51 from operacle/develop
Implement CheckCle Microservice Operation
2025-06-19 17:51:39 +07:00
Tola Leng 9ed4d4c7ac Merge pull request #50 from operacle/develop
feat: New Create Service Form and  Split UptimeBar.tsx into smaller components
2025-06-19 15:04:07 +07:00
Tola Leng 9a001f6aec Merge pull request #49 from operacle/develop
Remove HTTP service check and Refactor: Split settings API into modules
2025-06-18 22:09:40 +07:00
Tola Leng cfdedb9636 Merge pull request #45 from operacle/develop
Fix: Implement public status page functionality
2025-06-15 20:49:51 +07:00
Tola Leng 9d5fa805c9 Merge pull request #42 from operacle/develop
Implement password reset functionality.
2025-06-12 17:15:08 +07:00
Tola Leng 68a4ad5478 Merge pull request #38 from operacle/develop
Refactor: Split Sidebar.tsx into smaller components
2025-06-08 21:46:27 +07:00
Tola Leng 9b1918e25a Merge pull request #36 from operacle/develop
feat: Implement Operational and Public Status Page Feature
2025-06-06 19:23:54 +07:00
Tola Leng 1dc25cc461 Merge pull request #35 from operacle/develop
feat: Add mail test functionality
2025-06-06 16:48:46 +07:00
Tola Leng 4dc005c7e4 Merge pull request #33 from operacle/develop
Add SMTP password field in Mail Settings and  Fix: Ensure Add Service dialog respects theme
2025-06-05 17:40:17 +07:00
Tola Leng 4ec0c7a8fa Merge pull request #32 from operacle/develop
Fix: Improve email change flow and auto-logout and feat: Implement uptime monitoring data retention
2025-06-04 16:33:42 +07:00
Tola Leng dd758b9334 Merge pull request #27 from operacle/develop
feat: Implement uptime monitoring data retention
2025-05-31 17:44:43 +07:00
Tola Leng aec7118496 Merge pull request #25 from operacle/develop
feat: Auto logout after password change
2025-05-28 15:37:53 +07:00
Tola Leng 759c3249e1 Merge pull request #22 from operacle/develop
feat: release maintenance and incident management features; apply hotfixes
2025-05-26 21:57:45 +07:00
795 changed files with 5913 additions and 174463 deletions
-10
View File
@@ -1,10 +0,0 @@
.git
server/
**/node_modules
**/dist
**/.next
**/.turbo
**/.cache
**/coverage
**/*.log
+1 -1
View File
@@ -1,6 +1,6 @@
# These are supported funding model platforms # These are supported funding model platforms
github: #[tolaleng] github: [tolaleng]
patreon: # Replace with a single Patreon username patreon: # Replace with a single Patreon username
open_collective: #checkcle open_collective: #checkcle
ko_fi: # Replace with a single Ko-fi username ko_fi: # Replace with a single Ko-fi username
+1 -2
View File
@@ -85,8 +85,7 @@ body:
id: terms id: terms
attributes: attributes:
label: Checklist label: Checklist
description: | description: Please confirm the following before submitting:
Please confirm the following before submitting:
options: options:
- label: I have searched existing issues to avoid creating duplicates. - label: I have searched existing issues to avoid creating duplicates.
required: true required: true
+1 -2
View File
@@ -51,8 +51,7 @@ body:
id: checklist id: checklist
attributes: attributes:
label: Checklist label: Checklist
description: | description: Before submitting, please confirm:
Before submitting, please confirm:
options: options:
- label: I have searched existing issues to make sure this feature hasnt been requested yet. - label: I have searched existing issues to make sure this feature hasnt been requested yet.
required: true required: true
+1 -2
View File
@@ -45,8 +45,7 @@ body:
id: checklist id: checklist
attributes: attributes:
label: Checklist label: Checklist
description: | description: Before submitting, please confirm the following:
Before submitting, please confirm the following:
options: options:
- label: I have searched existing issues and discussions for a solution. - label: I have searched existing issues and discussions for a solution.
required: true required: true
@@ -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
-2
View File
@@ -22,8 +22,6 @@ dist-ssr
*.njsproj *.njsproj
*.sln *.sln
*.sw? *.sw?
pocketbase.exe
application/src/lib/pocketbase.ts application/src/lib/pocketbase.ts
server/pb_data/
Dockerfile Dockerfile
application/src/lib/pocketbase-prod.ts application/src/lib/pocketbase-prod.ts
-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 ### 2. Clone Your Fork
```bash ```bash
git clone https://github.com/yourusername/checkcle.git git clone --branch develop https://github.com/operacle/checkcle.git
cd checkcle 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. Click "Fork" on [GitHub](https://github.com/operacle/Distributed-Regional-Monitoring) to create your own copy.
#### 2. Clone Your Fork #### 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 cd Distributed-Regional-Monitoring
#### 3. Install Go Service (make sure you have installed the Go Service) #### 3. Install Go Service (make sure you have installed the Go Service)
+24 -28
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. - 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 - Schedule Maintenance & Incident Management
- Operational Status / Public Status Pages - Operational Status / Public Status Pages
- Notifications via email, Telegram, Discord, Slack, Matrix, and more - Notifications via email, Telegram, Discord, and Slack
- Reports & Analytics - Reports & Analytics
- Settings Panel (User Management, Data Retention, Multi-language, Themes (Dark & Light Mode), Notification and channels and alert templates). - Settings Panel (User Management, Data Retention, Multi-language, Themes (Dark & Light Mode), Notification and channels and alert templates).
@@ -128,36 +128,32 @@ docker run -d \
--- ---
## Sponsors ## Sponsors
Sponsorships will no longer be accepted. From now on, support will only be accepted in the form of ecosystem and community partnerships that provide infrastructure such as cloud servers, domains, or hosting credits. 🙏 We're incredibly thankful to our sponsors. Your contributions enable us to maintain infrastructure (hosting, domains), run tests, and continue developing valuable features.
If youre a tech company interested in supporting CheckCle, please contact the author directly at tolaleng@checkcle.io ### 🥈 Silver Uptime Ally
<a href="https://github.com/michaelortnerit">
<img src="https://avatars.githubusercontent.com/u/135371107?v=4" width="75" height="75" style="border-radius: 50%; display: block;" />
</a>
### 🧡 Ping Supporter
<a href="https://github.com/samang-dauth">
<img src="https://avatars.githubusercontent.com/u/4575656?v=4" width="75" height="75" style="border-radius: 50%; display: block;" />
</a>
### 🤝 Ecosystem & Community Partner ### 🤝 Ecosystem & Community Partner
<div style="display: flex; align-items: center; gap: 10px;"> <a href="https://github.com/gitbookio" style="display: inline-block; margin-right: 10px; vertical-align: middle;">
<a href="https://github.com/gitbookio"> <img src="https://avatars.githubusercontent.com/u/7111340?s=200&v=4"
<img src="https://avatars.githubusercontent.com/u/7111340?s=200&v=4" width="75" height="75"
width="75" height="75" style="border-radius: 50%;" />
style="border-radius: 50%;" </a>
alt="GitBook Logo" /> <a href="https://m.do.co/c/0c27ef82475f" style="display: inline-block; vertical-align: middle;">
</a> <img src="https://opensource.nyc3.cdn.digitaloceanspaces.com/attribution/assets/SVG/DO_Logo_horizontal_blue.svg"
height="45"
alt="DigitalOcean Logo">
</a>
<a href="https://www.cloudflare.com">
<img src="https://cdn.checkcle.io/images/sponsor/cloudflare-checkcle_logo.png"
height="60"
alt="Cloudflare Logo" />
</a>
<a href="https://m.do.co/c/0c27ef82475f">
<img src="https://cdn.checkcle.io/images/sponsor/digitalocean_checkcle.png"
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 +181,7 @@ Here are some ways you can help improve CheckCle:
- Website: [checkcle.io](https://checkcle.io) - 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! - 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) - 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 ## 📜 License
-1
View File
@@ -39,7 +39,6 @@ We support the latest stable release of `checkcle`. Security patches may also be
| Version | Supported | | Version | Supported |
|---------|-----------| |---------|-----------|
| `develop` (latest) | ✅ Yes |
| `main` (latest) | ✅ Yes | | `main` (latest) | ✅ Yes |
| Older versions | ⚠️ Best-effort | | Older versions | ⚠️ Best-effort |
| Pre-release or forks | ❌ No | | 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;"]
+22 -404
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -50,7 +50,7 @@
"jspdf-autotable": "^5.0.2", "jspdf-autotable": "^5.0.2",
"lucide-react": "^0.462.0", "lucide-react": "^0.462.0",
"next-themes": "^0.3.0", "next-themes": "^0.3.0",
"pocketbase": "^0.26.8", "pocketbase": "^0.19.0",
"react": "^18.3.1", "react": "^18.3.1",
"react-day-picker": "^8.10.1", "react-day-picker": "^8.10.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
File diff suppressed because it is too large Load Diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 250 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

@@ -7,7 +7,6 @@ import { StatusCards } from "./StatusCards";
import { ServiceFilters } from "./ServiceFilters"; import { ServiceFilters } from "./ServiceFilters";
import { ServicesTable } from "./ServicesTable"; import { ServicesTable } from "./ServicesTable";
import { AddServiceDialog } from "@/components/services/AddServiceDialog"; import { AddServiceDialog } from "@/components/services/AddServiceDialog";
import { useLanguage } from "@/contexts/LanguageContext";
interface DashboardContentProps { interface DashboardContentProps {
services: Service[]; services: Service[];
@@ -16,7 +15,6 @@ interface DashboardContentProps {
} }
export const DashboardContent = ({ services, isLoading, error }: DashboardContentProps) => { export const DashboardContent = ({ services, isLoading, error }: DashboardContentProps) => {
const { t } = useLanguage();
const [filter, setFilter] = useState<string>("all"); const [filter, setFilter] = useState<string>("all");
const [searchTerm, setSearchTerm] = useState<string>(""); const [searchTerm, setSearchTerm] = useState<string>("");
const [isAddDialogOpen, setIsAddDialogOpen] = useState<boolean>(false); const [isAddDialogOpen, setIsAddDialogOpen] = useState<boolean>(false);
@@ -33,7 +31,7 @@ export const DashboardContent = ({ services, isLoading, error }: DashboardConten
return ( return (
<div className="flex flex-col items-center justify-center h-full gap-4 text-foreground"> <div className="flex flex-col items-center justify-center h-full gap-4 text-foreground">
<p>Error loading service data.</p> <p>Error loading service data.</p>
<Button onClick={() => window.location.reload()}>{t('retry')}</Button> <Button onClick={() => window.location.reload()}>Retry</Button>
</div> </div>
); );
} }
@@ -42,12 +40,12 @@ export const DashboardContent = ({ services, isLoading, error }: DashboardConten
<main className="flex-1 flex flex-col overflow-auto bg-background p-6 pb-0"> <main className="flex-1 flex flex-col overflow-auto bg-background p-6 pb-0">
<div className="flex flex-col flex-1"> <div className="flex flex-col flex-1">
<div className="flex justify-between items-center mb-6"> <div className="flex justify-between items-center mb-6">
<h2 className="text-2xl font-bold text-foreground">{t('overview')}</h2> <h2 className="text-2xl font-bold text-foreground">Overview</h2>
<Button <Button
className="text-primary-foreground" className="text-primary-foreground"
onClick={() => setIsAddDialogOpen(true)} onClick={() => setIsAddDialogOpen(true)}
> >
<Plus className="w-4 h-4 mr-2" /> {t('newService')} <Plus className="w-4 h-4 mr-2" /> New Service
</Button> </Button>
</div> </div>
+106 -95
View File
@@ -1,59 +1,75 @@
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { AuthUser } from "@/services/authService"; import { AuthUser } from "@/services/authService";
import { useTheme } from "@/contexts/ThemeContext"; import { useTheme } from "@/contexts/ThemeContext";
import { import { Moon, PanelLeft, PanelLeftClose, Sun, Globe, FileText, Github, Twitter, MessageSquare, Bell, User, Settings, LogOut } from "lucide-react";
Moon, PanelLeft, PanelLeftClose, Sun, Globe, FileText,
Github, Twitter, MessageSquare, Bell, User, Settings,
LogOut, Menu, X
} from "lucide-react";
import { useLanguage } from "@/contexts/LanguageContext"; import { useLanguage } from "@/contexts/LanguageContext";
import { import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
DropdownMenu, DropdownMenuContent, DropdownMenuItem,
DropdownMenuTrigger, DropdownMenuSeparator
} from "@/components/ui/dropdown-menu";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useSystemSettings } from "@/hooks/useSystemSettings"; import { useSystemSettings } from "@/hooks/useSystemSettings";
import { useSidebar } from "@/contexts/SidebarContext";
import { cn } from "@/lib/utils";
interface HeaderProps { interface HeaderProps {
currentUser: AuthUser | null; currentUser: AuthUser | null;
onLogout: () => void; onLogout: () => void;
sidebarCollapsed: boolean;
toggleSidebar: () => void;
} }
export const Header = ({ export const Header = ({
currentUser, currentUser,
onLogout, onLogout,
sidebarCollapsed,
toggleSidebar
}: HeaderProps) => { }: HeaderProps) => {
const { theme, toggleTheme } = useTheme(); const { theme, toggleTheme } = useTheme();
const { language, setLanguage, t } = useLanguage(); const { language, setLanguage, t } = useLanguage();
const { sidebarCollapsed, toggleSidebar, isMobileOpen, toggleMobileMenu } = useSidebar();
const [greeting, setGreeting] = useState<string>(""); const [greeting, setGreeting] = useState<string>("");
const { systemName } = useSystemSettings(); const { systemName } = useSystemSettings();
const navigate = useNavigate(); const navigate = useNavigate();
// Set greeting based on time of day
useEffect(() => { useEffect(() => {
const updateGreeting = () => { const updateGreeting = () => {
const hour = new Date().getHours(); const hour = new Date().getHours();
if (hour >= 5 && hour < 12) setGreeting(t("goodMorning")); if (hour >= 5 && hour < 12) {
else if (hour >= 12 && hour < 18) setGreeting(t("goodAfternoon")); setGreeting(t("goodMorning"));
else setGreeting(t("goodEvening")); } else if (hour >= 12 && hour < 18) {
setGreeting(t("goodAfternoon"));
} else {
setGreeting(t("goodEvening"));
}
}; };
updateGreeting(); 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]); }, [language, t]);
const avatarUrl = currentUser?.avatar || ''; // Log avatar data for debugging
useEffect(() => {
if (currentUser) {
//console.log("Avatar URL in Header:", currentUser.avatar);
}
}, [currentUser]);
const openExternalLink = (url: string) => { // Prepare avatar URL - ensure it displays correctly if it's a local profile image
window.open(url, '_blank'); 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);
}
return ( 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"> <header className="relative bg-background border-b border-border px-6 flex justify-between items-center py-[12px] overflow-hidden">
{/* Grid Pattern Overlay */} {/* Grid Pattern Overlay - Similar to StatusCards */}
<div className="absolute inset-0 z-0 pointer-events-none opacity-20"> <div className="absolute inset-0 z-0">
<div <div
className="w-full h-full" className="w-full h-full"
style={{ style={{
@@ -66,74 +82,19 @@ export const Header = ({
</div> </div>
</div> </div>
<div className="flex items-center gap-2 lg:gap-4 z-10"> {/* Header Content */}
{/* Mobile Toggle */} <div className="flex items-center gap-4 z-10">
<Button variant="ghost" size="icon" onClick={toggleMobileMenu} className="lg:hidden h-9 w-9"> <Button variant="ghost" size="icon" onClick={toggleSidebar} className="mr-2">
{isMobileOpen ? <X className="h-5 w-5" /> : <Menu 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" />} {sidebarCollapsed ? <PanelLeft className="h-5 w-5" /> : <PanelLeftClose className="h-5 w-5" />}
</Button> </Button>
<div className="flex items-center"> <div className="flex items-center space-x-2">
<h1 className="text-sm lg:text-lg font-medium truncate max-w-[150px] lg:max-w-none"> <h1 className="text-lg font-medium">{greeting}, {currentUser?.name || currentUser?.email?.split('@')[0] || 'User'} 👋 </h1>
{greeting}, {currentUser?.name || currentUser?.email?.split('@')[0] || 'User'} 👋
</h1>
</div> </div>
</div> </div>
<div className="flex items-center space-x-1 lg:space-x-3 z-10"> <div className="flex items-center space-x-4 z-10">
{/* External Links - Hidden on small screens */} <Button variant="outline" size="icon" className="rounded-full w-8 h-8 border-border" onClick={toggleTheme}>
<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}>
<span className="sr-only">Toggle theme</span> <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> </Button>
@@ -145,7 +106,7 @@ export const Header = ({
<Globe className="w-4 h-4" /> <Globe className="w-4 h-4" />
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40"> <DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setLanguage("en")} className={language === "en" ? "bg-accent" : ""}> <DropdownMenuItem onClick={() => setLanguage("en")} className={language === "en" ? "bg-accent" : ""}>
{t("english")} {t("english")}
</DropdownMenuItem> </DropdownMenuItem>
@@ -153,10 +114,7 @@ export const Header = ({
{t("khmer")} {t("khmer")}
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={() => setLanguage("de")} className={language === "de" ? "bg-accent" : ""}> <DropdownMenuItem onClick={() => setLanguage("de")} className={language === "de" ? "bg-accent" : ""}>
{t("german")} {t("Deutsch")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setLanguage("ko")} className={language === "ko" ? "bg-accent" : ""}>
{t("korean")}
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={() => setLanguage("ja")} className={language === "ja" ? "bg-accent" : ""}> <DropdownMenuItem onClick={() => setLanguage("ja")} className={language === "ja" ? "bg-accent" : ""}>
{t("japanese")} {t("japanese")}
@@ -167,21 +125,74 @@ export const Header = ({
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </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>
{/* User Profile Dropdown */}
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<Avatar className="h-8 w-8 cursor-pointer border hover:ring-2 hover:ring-primary/20 transition-all"> <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="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> </Avatar>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56"> <DropdownMenuContent align="end" className="w-56">
<div className="flex items-center gap-3 p-2"> <div className="flex items-center gap-3 p-2">
<Avatar className="h-10 w-10"> <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> </Avatar>
<div className="flex flex-col space-y-0.5"> <div className="flex flex-col space-y-1">
<span className="text-sm font-medium truncate">{currentUser?.name || 'User'}</span> <span className="font-medium">{currentUser?.name || 'User'}</span>
<span className="text-xs text-muted-foreground truncate">{currentUser?.email}</span> <span className="text-xs text-muted-foreground truncate">{currentUser?.email}</span>
</div> </div>
</div> </div>
@@ -3,7 +3,6 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; 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 { Plus } from "lucide-react";
import { useLanguage } from "@/contexts/LanguageContext";
interface ServiceFiltersProps { interface ServiceFiltersProps {
filter: string; filter: string;
@@ -20,11 +19,10 @@ export const ServiceFilters = ({
setSearchTerm, setSearchTerm,
servicesCount servicesCount
}: ServiceFiltersProps) => { }: ServiceFiltersProps) => {
const { t } = useLanguage();
return ( return (
<div className="mb-6 flex justify-between items-center"> <div className="mb-6 flex justify-between items-center">
<div className="flex 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">Currently Monitoring</h3>
<span className="bg-secondary text-secondary-foreground px-2 py-0.5 rounded text-sm"> <span className="bg-secondary text-secondary-foreground px-2 py-0.5 rounded text-sm">
{servicesCount} {servicesCount}
</span> </span>
@@ -32,10 +30,10 @@ export const ServiceFilters = ({
<div className="flex space-x-4"> <div className="flex space-x-4">
<Select value={filter} onValueChange={setFilter}> <Select value={filter} onValueChange={setFilter}>
<SelectTrigger className="w-40 bg-card border-border"> <SelectTrigger className="w-40 bg-card border-border">
<SelectValue placeholder={t('allTypes')} /> <SelectValue placeholder="All Types" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="all">{t('allTypes')}</SelectItem> <SelectItem value="all">All Types</SelectItem>
<SelectItem value="HTTP">HTTP</SelectItem> <SelectItem value="HTTP">HTTP</SelectItem>
<SelectItem value="PING">PING</SelectItem> <SelectItem value="PING">PING</SelectItem>
<SelectItem value="TCP">TCP</SelectItem> <SelectItem value="TCP">TCP</SelectItem>
@@ -45,7 +43,7 @@ export const ServiceFilters = ({
<div className="relative"> <div className="relative">
<Input <Input
className="w-72 bg-card border-border" className="w-72 bg-card border-border"
placeholder={t('search')} placeholder="Search"
value={searchTerm} value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)} onChange={(e) => setSearchTerm(e.target.value)}
/> />
@@ -1,44 +1,28 @@
import React from "react"; import React from "react";
import { useTheme } from "@/contexts/ThemeContext"; import { useTheme } from "@/contexts/ThemeContext";
import { SidebarHeader } from "./sidebar/SidebarHeader"; import { SidebarHeader } from "./sidebar/SidebarHeader";
import { MainNavigation } from "./sidebar/MainNavigation"; import { MainNavigation } from "./sidebar/MainNavigation";
import { SettingsPanel } from "./sidebar/SettingsPanel"; 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 { theme } = useTheme();
const { sidebarCollapsed, isMobileOpen, toggleMobileMenu } = useSidebar();
return ( return (
<> <div
{/* Mobile Overlay */} className={`
{isMobileOpen && ( ${theme === 'dark' ? 'bg-[#121212] border-[#1e1e1e]' : 'bg-sidebar border-sidebar-border'}
<div border-r flex flex-col h-full
className="fixed inset-0 bg-black/60 z-40 lg:hidden backdrop-blur-sm transition-opacity animate-in fade-in" ${collapsed ? 'w-16' : 'w-64'}
onClick={toggleMobileMenu} `}
/> >
)} <SidebarHeader collapsed={collapsed} />
<MainNavigation collapsed={collapsed} />
{/* Sidebar Container */} <SettingsPanel collapsed={collapsed} />
<aside </div>
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>
</>
); );
}; };
@@ -3,15 +3,12 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ArrowUp, ArrowDown, Pause, AlertTriangle } from "lucide-react"; import { ArrowUp, ArrowDown, Pause, AlertTriangle } from "lucide-react";
import { Service } from "@/services/serviceService"; import { Service } from "@/services/serviceService";
import { useTheme } from "@/contexts/ThemeContext"; import { useTheme } from "@/contexts/ThemeContext";
import {useLanguage} from "@/contexts/LanguageContext.tsx";
interface StatusCardsProps { interface StatusCardsProps {
services: Service[]; services: Service[];
} }
export const StatusCards = ({ services }: StatusCardsProps) => { export const StatusCards = ({ services }: StatusCardsProps) => {
const { t } = useLanguage();
// Count services by status // Count services by status
const upServices = services.filter(s => s.status === "up").length; const upServices = services.filter(s => s.status === "up").length;
const downServices = services.filter(s => s.status === "down").length; const downServices = services.filter(s => s.status === "down").length;
@@ -45,7 +42,7 @@ export const StatusCards = ({ services }: StatusCardsProps) => {
></div> ></div>
</div> </div>
<CardHeader className="pb-2 relative z-10"> <CardHeader className="pb-2 relative z-10">
<CardTitle className="text-sm font-medium text-white">{t("upServices")}</CardTitle> <CardTitle className="text-sm font-medium text-white">UP SERVICES</CardTitle>
</CardHeader> </CardHeader>
<CardContent className="flex items-center justify-between relative z-10"> <CardContent className="flex items-center justify-between relative z-10">
<span className="text-5xl font-bold text-white">{upServices}</span> <span className="text-5xl font-bold text-white">{upServices}</span>
@@ -77,7 +74,7 @@ export const StatusCards = ({ services }: StatusCardsProps) => {
></div> ></div>
</div> </div>
<CardHeader className="pb-2 relative z-10"> <CardHeader className="pb-2 relative z-10">
<CardTitle className="text-sm font-medium text-white">{t("downServices")}</CardTitle> <CardTitle className="text-sm font-medium text-white">DOWN SERVICES</CardTitle>
</CardHeader> </CardHeader>
<CardContent className="flex items-center justify-between relative z-10"> <CardContent className="flex items-center justify-between relative z-10">
<span className="text-5xl font-bold text-white">{downServices}</span> <span className="text-5xl font-bold text-white">{downServices}</span>
@@ -109,7 +106,7 @@ export const StatusCards = ({ services }: StatusCardsProps) => {
></div> ></div>
</div> </div>
<CardHeader className="pb-2 relative z-10"> <CardHeader className="pb-2 relative z-10">
<CardTitle className="text-sm font-medium text-white">{t("pausedServices")}</CardTitle> <CardTitle className="text-sm font-medium text-white">PAUSED SERVICES</CardTitle>
</CardHeader> </CardHeader>
<CardContent className="flex items-center justify-between relative z-10"> <CardContent className="flex items-center justify-between relative z-10">
<span className="text-5xl font-bold text-white">{pausedServices}</span> <span className="text-5xl font-bold text-white">{pausedServices}</span>
@@ -141,7 +138,7 @@ export const StatusCards = ({ services }: StatusCardsProps) => {
></div> ></div>
</div> </div>
<CardHeader className="pb-2 relative z-10"> <CardHeader className="pb-2 relative z-10">
<CardTitle className="text-sm font-medium text-white">{t("warningServices")}</CardTitle> <CardTitle className="text-sm font-medium text-white">WARNING SERVICES</CardTitle>
</CardHeader> </CardHeader>
<CardContent className="flex items-center justify-between relative z-10"> <CardContent className="flex items-center justify-between relative z-10">
<span className="text-5xl font-bold text-white">{warningServices}</span> <span className="text-5xl font-bold text-white">{warningServices}</span>
@@ -1,9 +1,9 @@
import React from "react"; import React from "react";
import { useLocation, useNavigate } from "react-router-dom"; import { useLocation, useNavigate } from "react-router-dom";
import { useTheme } from "@/contexts/ThemeContext"; import { useTheme } from "@/contexts/ThemeContext";
import { useLanguage } from "@/contexts/LanguageContext"; import { useLanguage } from "@/contexts/LanguageContext";
import { LucideIcon } from "lucide-react"; import { LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";
interface MenuItemProps { interface MenuItemProps {
id: string; id: string;
@@ -16,6 +16,7 @@ interface MenuItemProps {
} }
export const MenuItem: React.FC<MenuItemProps> = ({ export const MenuItem: React.FC<MenuItemProps> = ({
id,
path, path,
icon: Icon, icon: Icon,
translationKey, translationKey,
@@ -28,39 +29,36 @@ export const MenuItem: React.FC<MenuItemProps> = ({
const location = useLocation(); const location = useLocation();
const navigate = useNavigate(); const navigate = useNavigate();
const isActive = path && location.pathname === path;
const handleClick = (e: React.MouseEvent) => { const handleClick = (e: React.MouseEvent) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation();
if (hasNavigation && path) { if (hasNavigation && path) {
navigate(path); navigate(path, { replace: false });
} }
}; };
const isActive = path && location.pathname === path;
const mainIconSize = "h-6 w-6";
return ( return (
<div <div
className={cn( className={`
"group relative flex items-center mb-1 rounded-lg cursor-pointer transition-all duration-200", ${collapsed ? 'p-3' : 'p-2 pl-3'}
collapsed ? "p-3 justify-center" : "p-2.5 px-4", mb-1 rounded-lg
isActive ${isActive ? (theme === 'dark' ? 'bg-gray-800' : 'bg-sidebar-accent') : `hover:${theme === 'dark' ? 'bg-gray-800' : 'bg-sidebar-accent'}`}
? (theme === 'dark' ? 'bg-zinc-800 text-white' : 'bg-primary/10 text-primary') flex items-center
: (theme === 'dark' ? 'text-zinc-400 hover:bg-zinc-800/50 hover:text-white' : 'text-zinc-600 hover:bg-zinc-100') ${collapsed ? 'justify-center' : ''}
)} cursor-pointer
`}
onClick={handleClick} 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 && ( {!collapsed && (
<span className="ml-3 font-medium tracking-wide text-sm truncate"> <span className="ml-2.5 font-medium text-foreground tracking-wide text-[15px]">
{t(translationKey)} {t(translationKey)}
</span> </span>
)} )}
{/* Small Indicator for active state */}
{isActive && !collapsed && (
<div className="absolute left-0 w-1 h-6 bg-primary rounded-r-full" />
)}
</div> </div>
); );
}; };
@@ -4,7 +4,6 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody } from "@/components/ui/table"; import { Table, TableBody } from "@/components/ui/table";
import { DockerContainer } from "@/types/docker.types"; import { DockerContainer } from "@/types/docker.types";
import { DockerMetricsDialog } from "./DockerMetricsDialog"; import { DockerMetricsDialog } from "./DockerMetricsDialog";
import { useLanguage } from "@/contexts/LanguageContext";
import { import {
DockerTableSearch, DockerTableSearch,
DockerTableHeader, DockerTableHeader,
@@ -19,7 +18,6 @@ interface DockerContainersTableProps {
} }
export const DockerContainersTable = ({ containers, isLoading, onRefresh }: DockerContainersTableProps) => { export const DockerContainersTable = ({ containers, isLoading, onRefresh }: DockerContainersTableProps) => {
const { t } = useLanguage();
const [searchTerm, setSearchTerm] = useState(""); const [searchTerm, setSearchTerm] = useState("");
const [selectedContainer, setSelectedContainer] = useState<DockerContainer | null>(null); const [selectedContainer, setSelectedContainer] = useState<DockerContainer | null>(null);
const [metricsDialogOpen, setMetricsDialogOpen] = useState(false); const [metricsDialogOpen, setMetricsDialogOpen] = useState(false);
@@ -51,7 +49,7 @@ export const DockerContainersTable = ({ containers, isLoading, onRefresh }: Dock
<CardHeader className="pb-4 px-0"> <CardHeader className="pb-4 px-0">
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between 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 <DockerTableSearch
searchTerm={searchTerm} searchTerm={searchTerm}
onSearchChange={setSearchTerm} onSearchChange={setSearchTerm}
@@ -10,7 +10,6 @@ import { DockerContainer, DockerMetrics } from "@/types/docker.types";
import { dockerService } from "@/services/dockerService"; import { dockerService } from "@/services/dockerService";
import { Loader2, Cpu, HardDrive, Network, MemoryStick } from "lucide-react"; import { Loader2, Cpu, HardDrive, Network, MemoryStick } from "lucide-react";
import { useTheme } from "@/contexts/ThemeContext"; import { useTheme } from "@/contexts/ThemeContext";
import { useLanguage } from "@/contexts/LanguageContext";
interface DockerMetricsDialogProps { interface DockerMetricsDialogProps {
container: DockerContainer | null; container: DockerContainer | null;
@@ -21,17 +20,16 @@ interface DockerMetricsDialogProps {
type TimeRange = '60m' | '1d' | '7d' | '1m' | '3m'; type TimeRange = '60m' | '1d' | '7d' | '1m' | '3m';
const timeRangeOptions = [ const timeRangeOptions = [
{ value: '60m' as TimeRange, label: 'minutes60', hours: 1 }, { value: '60m' as TimeRange, label: '60 minutes', hours: 1 },
{ value: '1d' as TimeRange, label: 'day1', hours: 24 }, { value: '1d' as TimeRange, label: '1 day', hours: 24 },
{ value: '7d' as TimeRange, label: 'days7', hours: 24 * 7 }, { value: '7d' as TimeRange, label: '7 days', hours: 24 * 7 },
{ value: '1m' as TimeRange, label: 'month1', hours: 24 * 30 }, { value: '1m' as TimeRange, label: '1 month', hours: 24 * 30 },
{ value: '3m' as TimeRange, label: 'months3', hours: 24 * 90 }, { value: '3m' as TimeRange, label: '3 months', hours: 24 * 90 },
]; ];
export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMetricsDialogProps) => { export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMetricsDialogProps) => {
const [timeRange, setTimeRange] = useState<TimeRange>("1d"); const [timeRange, setTimeRange] = useState<TimeRange>("1d");
const { theme } = useTheme(); const { theme } = useTheme();
const { t } = useLanguage();
const { const {
data: metrics = [], 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"> <DialogContent className="max-w-7xl max-h-[95vh] overflow-y-auto bg-background text-foreground">
<DialogHeader> <DialogHeader>
<DialogTitle className="flex items-center justify-between"> <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"> <div className="h-8 w-8 rounded bg-primary/10 flex items-center justify-center">
<Cpu className="h-4 w-4 text-primary" /> <Cpu className="h-4 w-4 text-primary" />
</div> </div>
{t('containerMetricsTitle', 'docker', { name: container.name })} Container Metrics: {container.name}
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Select value={timeRange} onValueChange={(value: TimeRange) => setTimeRange(value)}> <Select value={timeRange} onValueChange={(value: TimeRange) => setTimeRange(value)}>
@@ -248,7 +246,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<SelectContent> <SelectContent>
{timeRangeOptions.map((option) => ( {timeRangeOptions.map((option) => (
<SelectItem key={option.value} value={option.value}> <SelectItem key={option.value} value={option.value}>
{t(option.label, 'docker')} {option.label}
</SelectItem> </SelectItem>
))} ))}
</SelectContent> </SelectContent>
@@ -256,22 +254,22 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
</div> </div>
</DialogTitle> </DialogTitle>
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
{t('dockerId', 'docker')}: {container.docker_id} {container.hostname} Docker ID: {container.docker_id} {container.hostname}
</p> </p>
</DialogHeader> </DialogHeader>
{isLoading ? ( {isLoading ? (
<div className="flex items-center justify-center h-96"> <div className="flex items-center justify-center h-96">
<Loader2 className="h-8 w-8 animate-spin" /> <Loader2 className="h-8 w-8 animate-spin" />
<span className="ml-2">{t('loadingMetrics', 'docker')}</span> <span className="ml-2">Loading metrics...</span>
</div> </div>
) : error ? ( ) : error ? (
<div className="flex items-center justify-center h-96 text-muted-foreground"> <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> </div>
) : chartData.length === 0 ? ( ) : chartData.length === 0 ? (
<div className="flex items-center justify-center h-96 text-muted-foreground"> <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> </div>
) : ( ) : (
<> <>
@@ -279,7 +277,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
{latestMetric && ( {latestMetric && (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
<MetricCard <MetricCard
title={t('cpu', 'docker')} title="CPU"
used={`${latestMetric.cpuUsage}%`} used={`${latestMetric.cpuUsage}%`}
total={`${latestMetric.cpuCores} cores`} total={`${latestMetric.cpuCores} cores`}
free={`${(100 - latestMetric.cpuUsage).toFixed(1)}%`} free={`${(100 - latestMetric.cpuUsage).toFixed(1)}%`}
@@ -288,7 +286,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
color={chartConfig.cpuUsage.color} color={chartConfig.cpuUsage.color}
/> />
<MetricCard <MetricCard
title={t('memoryTitle', 'docker')} title="Memory"
used={latestMetric.ramUsed} used={latestMetric.ramUsed}
total={latestMetric.ramTotal} total={latestMetric.ramTotal}
free={latestMetric.ramFree} free={latestMetric.ramFree}
@@ -297,7 +295,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
color={chartConfig.ramUsagePercent.color} color={chartConfig.ramUsagePercent.color}
/> />
<MetricCard <MetricCard
title={t('diskTitle', 'docker')} title="Disk"
used={latestMetric.diskUsed} used={latestMetric.diskUsed}
total={latestMetric.diskTotal} total={latestMetric.diskTotal}
free={latestMetric.diskFree} free={latestMetric.diskFree}
@@ -306,10 +304,10 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
color={chartConfig.diskUsagePercent.color} color={chartConfig.diskUsagePercent.color}
/> />
<MetricCard <MetricCard
title={t('network', 'docker')} title="Network"
used={`RX: ${latestMetric.networkRx}`} used={`RX: ${latestMetric.networkRx}`}
total={`TX: ${latestMetric.networkTx}`} total={`TX: ${latestMetric.networkTx}`}
free={`${t('networkSpeedKbs', 'docker').replace('(KB/s)', '')}: ${latestMetric.networkRxSpeed} KB/s`} free={`Speed: ${latestMetric.networkRxSpeed} KB/s`}
percentage={0} percentage={0}
icon={Network} icon={Network}
color={chartConfig.networkRx.color} 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"> <TabsList className="grid w-full grid-cols-4 bg-muted">
<TabsTrigger value="cpu" className="flex items-center gap-2 data-[state=active]:bg-background"> <TabsTrigger value="cpu" className="flex items-center gap-2 data-[state=active]:bg-background">
<Cpu className="h-4 w-4" /> <Cpu className="h-4 w-4" />
{t('cpu', 'docker')} CPU
</TabsTrigger> </TabsTrigger>
<TabsTrigger value="memory" className="flex items-center gap-2 data-[state=active]:bg-background"> <TabsTrigger value="memory" className="flex items-center gap-2 data-[state=active]:bg-background">
<MemoryStick className="h-4 w-4" /> <MemoryStick className="h-4 w-4" />
{t('memoryTitle', 'docker')} Memory
</TabsTrigger> </TabsTrigger>
<TabsTrigger value="disk" className="flex items-center gap-2 data-[state=active]:bg-background"> <TabsTrigger value="disk" className="flex items-center gap-2 data-[state=active]:bg-background">
<HardDrive className="h-4 w-4" /> <HardDrive className="h-4 w-4" />
{t('diskTitle', 'docker')} Disk
</TabsTrigger> </TabsTrigger>
<TabsTrigger value="network" className="flex items-center gap-2 data-[state=active]:bg-background"> <TabsTrigger value="network" className="flex items-center gap-2 data-[state=active]:bg-background">
<Network className="h-4 w-4" /> <Network className="h-4 w-4" />
{t('network', 'docker')} Network
</TabsTrigger> </TabsTrigger>
</TabsList> </TabsList>
@@ -341,7 +339,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Card className="bg-card border-border"> <Card className="bg-card border-border">
<CardHeader> <CardHeader>
<CardTitle className="text-foreground">{t('cpuUsagePct', 'docker')}</CardTitle> <CardTitle className="text-foreground">CPU Usage (%)</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<ChartContainer config={chartConfig} className="h-80"> <ChartContainer config={chartConfig} className="h-80">
@@ -367,7 +365,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={chartConfig.cpuUsage.color} stroke={chartConfig.cpuUsage.color}
strokeWidth={2} strokeWidth={2}
dot={{ r: 3, fill: chartConfig.cpuUsage.color }} dot={{ r: 3, fill: chartConfig.cpuUsage.color }}
name={t('cpuUsagePct', 'docker')} name="CPU Usage (%)"
/> />
</LineChart> </LineChart>
</ChartContainer> </ChartContainer>
@@ -376,7 +374,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<Card className="bg-card border-border"> <Card className="bg-card border-border">
<CardHeader> <CardHeader>
<CardTitle className="text-foreground">{t('cpuUsageVsAvailable', 'docker')}</CardTitle> <CardTitle className="text-foreground">CPU Usage vs Available</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<ChartContainer config={chartConfig} className="h-80"> <ChartContainer config={chartConfig} className="h-80">
@@ -403,7 +401,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={theme === 'dark' ? "#6b7280" : "#9ca3af"} stroke={theme === 'dark' ? "#6b7280" : "#9ca3af"}
fill={theme === 'dark' ? "#6b7280" : "#9ca3af"} fill={theme === 'dark' ? "#6b7280" : "#9ca3af"}
fillOpacity={0.3} fillOpacity={0.3}
name={t('cpuAvailablePct', 'docker')} name="CPU Available (%)"
/> />
<Area <Area
type="monotone" type="monotone"
@@ -412,7 +410,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={chartConfig.cpuUsage.color} stroke={chartConfig.cpuUsage.color}
fill={chartConfig.cpuUsage.color} fill={chartConfig.cpuUsage.color}
fillOpacity={0.6} fillOpacity={0.6}
name={t('cpuUsagePct', 'docker')} name="CPU Usage (%)"
/> />
</AreaChart> </AreaChart>
</ChartContainer> </ChartContainer>
@@ -425,7 +423,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Card className="bg-card border-border"> <Card className="bg-card border-border">
<CardHeader> <CardHeader>
<CardTitle className="text-foreground">{t('ramUsagePct', 'docker')}</CardTitle> <CardTitle className="text-foreground">Memory Usage (%)</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<ChartContainer config={chartConfig} className="h-80"> <ChartContainer config={chartConfig} className="h-80">
@@ -461,7 +459,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<Card className="bg-card border-border"> <Card className="bg-card border-border">
<CardHeader> <CardHeader>
<CardTitle className="text-foreground">{t('memoryUsageBytes', 'docker')}</CardTitle> <CardTitle className="text-foreground">Memory Usage (Bytes)</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<ChartContainer config={chartConfig} className="h-80"> <ChartContainer config={chartConfig} className="h-80">
@@ -481,8 +479,8 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
content={<ChartTooltipContent className="bg-popover border-border" />} content={<ChartTooltipContent className="bg-popover border-border" />}
cursor={{ stroke: getGridColor() }} cursor={{ stroke: getGridColor() }}
formatter={(value, name) => [ formatter={(value, name) => [
name === t('usedMemory', 'docker') ? formatBytes(Number(value)) : name === 'Used Memory' ? formatBytes(Number(value)) :
name === t('totalMemory', 'docker') ? formatBytes(Number(value)) : value, name === 'Total Memory' ? formatBytes(Number(value)) : value,
name name
]} ]}
/> />
@@ -493,7 +491,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={theme === 'dark' ? "#6b7280" : "#9ca3af"} stroke={theme === 'dark' ? "#6b7280" : "#9ca3af"}
fill={theme === 'dark' ? "#6b7280" : "#9ca3af"} fill={theme === 'dark' ? "#6b7280" : "#9ca3af"}
fillOpacity={0.3} fillOpacity={0.3}
name={t('totalMemory', 'docker')} name="Total Memory"
/> />
<Area <Area
type="monotone" type="monotone"
@@ -502,7 +500,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={chartConfig.ramUsagePercent.color} stroke={chartConfig.ramUsagePercent.color}
fill={chartConfig.ramUsagePercent.color} fill={chartConfig.ramUsagePercent.color}
fillOpacity={0.6} fillOpacity={0.6}
name={t('usedMemory', 'docker')} name="Used Memory"
/> />
</AreaChart> </AreaChart>
</ChartContainer> </ChartContainer>
@@ -515,7 +513,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Card className="bg-card border-border"> <Card className="bg-card border-border">
<CardHeader> <CardHeader>
<CardTitle className="text-foreground">{t('diskUsagePct', 'docker')}</CardTitle> <CardTitle className="text-foreground">Disk Usage (%)</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<ChartContainer config={chartConfig} className="h-80"> <ChartContainer config={chartConfig} className="h-80">
@@ -542,7 +540,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={chartConfig.diskUsagePercent.color} stroke={chartConfig.diskUsagePercent.color}
fill={chartConfig.diskUsagePercent.color} fill={chartConfig.diskUsagePercent.color}
fillOpacity={0.6} fillOpacity={0.6}
name={t('diskUsagePct', 'docker')} name="Disk Usage (%)"
/> />
</AreaChart> </AreaChart>
</ChartContainer> </ChartContainer>
@@ -551,7 +549,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<Card className="bg-card border-border"> <Card className="bg-card border-border">
<CardHeader> <CardHeader>
<CardTitle className="text-foreground">{t('diskUsageBytes', 'docker')}</CardTitle> <CardTitle className="text-foreground">Disk Usage (Bytes)</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<ChartContainer config={chartConfig} className="h-80"> <ChartContainer config={chartConfig} className="h-80">
@@ -571,8 +569,8 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
content={<ChartTooltipContent className="bg-popover border-border" />} content={<ChartTooltipContent className="bg-popover border-border" />}
cursor={{ stroke: getGridColor() }} cursor={{ stroke: getGridColor() }}
formatter={(value, name) => [ formatter={(value, name) => [
name === t('usedDisk', 'docker') ? formatBytes(Number(value)) : name === 'Used Disk' ? formatBytes(Number(value)) :
name === t('totalDisk', 'docker') ? formatBytes(Number(value)) : value, name === 'Total Disk' ? formatBytes(Number(value)) : value,
name name
]} ]}
/> />
@@ -583,7 +581,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={theme === 'dark' ? "#6b7280" : "#9ca3af"} stroke={theme === 'dark' ? "#6b7280" : "#9ca3af"}
fill={theme === 'dark' ? "#6b7280" : "#9ca3af"} fill={theme === 'dark' ? "#6b7280" : "#9ca3af"}
fillOpacity={0.3} fillOpacity={0.3}
name={t('totalDisk', 'docker')} name="Total Disk"
/> />
<Area <Area
type="monotone" type="monotone"
@@ -592,7 +590,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
stroke={chartConfig.diskUsagePercent.color} stroke={chartConfig.diskUsagePercent.color}
fill={chartConfig.diskUsagePercent.color} fill={chartConfig.diskUsagePercent.color}
fillOpacity={0.6} fillOpacity={0.6}
name={t('usedDisk', 'docker')} name="Used Disk"
/> />
</AreaChart> </AreaChart>
</ChartContainer> </ChartContainer>
@@ -605,7 +603,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Card className="bg-card border-border"> <Card className="bg-card border-border">
<CardHeader> <CardHeader>
<CardTitle className="text-foreground">{t('networkTraffic', 'docker')}</CardTitle> <CardTitle className="text-foreground">Network Traffic</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<ChartContainer config={chartConfig} className="h-64"> <ChartContainer config={chartConfig} className="h-64">
@@ -629,7 +627,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
dataKey="networkRxBytes" dataKey="networkRxBytes"
stroke={chartConfig.networkRx.color} stroke={chartConfig.networkRx.color}
strokeWidth={2} strokeWidth={2}
name={t('rxBytes', 'docker')} name="RX Bytes"
dot={{ r: 2 }} dot={{ r: 2 }}
/> />
<Line <Line
@@ -637,7 +635,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
dataKey="networkTxBytes" dataKey="networkTxBytes"
stroke={chartConfig.networkTx.color} stroke={chartConfig.networkTx.color}
strokeWidth={2} strokeWidth={2}
name={t('txBytes', 'docker')} name="TX Bytes"
dot={{ r: 2 }} dot={{ r: 2 }}
/> />
</LineChart> </LineChart>
@@ -647,7 +645,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
<Card className="bg-card border-border"> <Card className="bg-card border-border">
<CardHeader> <CardHeader>
<CardTitle className="text-foreground">{t('networkSpeedKbs', 'docker')}</CardTitle> <CardTitle className="text-foreground">Network Speed (KB/s)</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<ChartContainer config={chartConfig} className="h-64"> <ChartContainer config={chartConfig} className="h-64">
@@ -671,7 +669,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
dataKey="networkRxSpeed" dataKey="networkRxSpeed"
stroke={chartConfig.networkRx.color} stroke={chartConfig.networkRx.color}
strokeWidth={2} strokeWidth={2}
name={t('rxSpeedKbs', 'docker')} name="RX Speed (KB/s)"
dot={{ r: 2 }} dot={{ r: 2 }}
/> />
<Line <Line
@@ -679,7 +677,7 @@ export const DockerMetricsDialog = ({ container, open, onOpenChange }: DockerMet
dataKey="networkTxSpeed" dataKey="networkTxSpeed"
stroke={chartConfig.networkTx.color} stroke={chartConfig.networkTx.color}
strokeWidth={2} strokeWidth={2}
name={t('txSpeedKbs', 'docker')} name="TX Speed (KB/s)"
dot={{ r: 2 }} dot={{ r: 2 }}
/> />
</LineChart> </LineChart>
@@ -4,7 +4,6 @@ import { Badge } from "@/components/ui/badge";
import { Container, Play, Square, AlertTriangle } from "lucide-react"; import { Container, Play, Square, AlertTriangle } from "lucide-react";
import { DockerStats } from "@/types/docker.types"; import { DockerStats } from "@/types/docker.types";
import { useTheme } from "@/contexts/ThemeContext"; import { useTheme } from "@/contexts/ThemeContext";
import { useLanguage } from "@/contexts/LanguageContext";
interface DockerStatsCardsProps { interface DockerStatsCardsProps {
stats: DockerStats; stats: DockerStats;
@@ -12,11 +11,10 @@ interface DockerStatsCardsProps {
export const DockerStatsCards = ({ stats }: DockerStatsCardsProps) => { export const DockerStatsCards = ({ stats }: DockerStatsCardsProps) => {
const { theme } = useTheme(); const { theme } = useTheme();
const { t } = useLanguage();
const cards = [ const cards = [
{ {
title: t('totalContainers', 'docker'), title: "Total Containers",
value: stats.total, value: stats.total,
icon: Container, icon: Container,
color: "text-blue-600", 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%)" : "linear-gradient(135deg, rgba(65, 59, 55, 0.8) 0%, #3b82f6 100%)"
}, },
{ {
title: t('running', 'docker'), title: "Running",
value: stats.running, value: stats.running,
icon: Play, icon: Play,
color: "text-green-600", 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%)" : "linear-gradient(135deg, rgba(65, 59, 55, 0.8) 0%, #10b981 100%)"
}, },
{ {
title: t('stopped', 'docker'), title: "Stopped",
value: stats.stopped, value: stats.stopped,
icon: Square, icon: Square,
color: "text-gray-600", 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%)" : "linear-gradient(135deg, rgba(65, 59, 55, 0.8) 0%, #6b7280 100%)"
}, },
{ {
title: t('warning', 'docker'), title: "Warning",
value: stats.warning, value: stats.warning,
icon: AlertTriangle, icon: AlertTriangle,
color: "text-amber-600", color: "text-amber-600",
@@ -92,7 +90,7 @@ export const DockerStatsCards = ({ stats }: DockerStatsCardsProps) => {
variant="outline" 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" 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> </Badge>
</div> </div>
</CardContent> </CardContent>
@@ -1,38 +1,36 @@
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { useLanguage } from "@/contexts/LanguageContext";
interface DockerStatusBadgeProps { interface DockerStatusBadgeProps {
status: 'running' | 'stopped' | 'warning'; status: 'running' | 'stopped' | 'warning';
} }
export const DockerStatusBadge = ({ status }: DockerStatusBadgeProps) => { export const DockerStatusBadge = ({ status }: DockerStatusBadgeProps) => {
const { t } = useLanguage();
const getStatusConfig = (status: string) => { const getStatusConfig = (status: string) => {
switch (status) { switch (status) {
case 'running': case 'running':
return { return {
variant: 'default' as const, variant: 'default' as const,
className: 'bg-emerald-100 text-emerald-800 border-emerald-200 hover:bg-emerald-200', className: 'bg-emerald-100 text-emerald-800 border-emerald-200 hover:bg-emerald-200',
label: t('running', 'docker') label: 'Running'
}; };
case 'stopped': case 'stopped':
return { return {
variant: 'secondary' as const, variant: 'secondary' as const,
className: 'bg-gray-100 text-gray-800 border-gray-200 hover:bg-gray-200', className: 'bg-gray-100 text-gray-800 border-gray-200 hover:bg-gray-200',
label: t('stopped', 'docker') label: 'Stopped'
}; };
case 'warning': case 'warning':
return { return {
variant: 'destructive' as const, variant: 'destructive' as const,
className: 'bg-amber-100 text-amber-800 border-amber-200 hover:bg-amber-200', className: 'bg-amber-100 text-amber-800 border-amber-200 hover:bg-amber-200',
label: t('warning', 'docker') label: 'Warning'
}; };
default: default:
return { return {
variant: 'outline' as const, variant: 'outline' as const,
className: 'bg-gray-100 text-gray-600 border-gray-200', 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 { TableCell, TableRow } from "@/components/ui/table";
import { useLanguage } from "@/contexts/LanguageContext";
interface DockerEmptyStateProps { interface DockerEmptyStateProps {
searchTerm: string; searchTerm: string;
} }
export const DockerEmptyState = ({ searchTerm }: DockerEmptyStateProps) => { export const DockerEmptyState = ({ searchTerm }: DockerEmptyStateProps) => {
const { t } = useLanguage();
return ( return (
<TableRow> <TableRow>
<TableCell colSpan={8} className="text-center py-12 text-muted-foreground"> <TableCell colSpan={8} className="text-center py-12 text-muted-foreground">
<div className="flex flex-col items-center gap-2"> <div className="flex flex-col items-center gap-2">
<div className="text-lg font-medium"> <div className="text-lg font-medium">
{searchTerm ? t('noContainersFound', 'docker') : t('noContainersRunning', 'docker')} {searchTerm ? "No containers found" : "No containers running"}
</div> </div>
<div className="text-sm"> <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>
</div> </div>
</TableCell> </TableCell>
@@ -3,7 +3,6 @@ import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, DropdownMenuSeparator } from "@/components/ui/dropdown-menu"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
import { MoreHorizontal, Eye, Play, Pause, Square, Trash2, BarChart3, RefreshCw } from "lucide-react"; import { MoreHorizontal, Eye, Play, Pause, Square, Trash2, BarChart3, RefreshCw } from "lucide-react";
import { DockerContainer } from "@/types/docker.types"; import { DockerContainer } from "@/types/docker.types";
import { useLanguage } from "@/contexts/LanguageContext";
interface DockerRowActionsProps { interface DockerRowActionsProps {
container: DockerContainer; container: DockerContainer;
@@ -13,12 +12,11 @@ interface DockerRowActionsProps {
} }
export const DockerRowActions = ({ container, containerStatus, onContainerAction, onViewMetrics }: DockerRowActionsProps) => { export const DockerRowActions = ({ container, containerStatus, onContainerAction, onViewMetrics }: DockerRowActionsProps) => {
const { t } = useLanguage();
return ( return (
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0 hover:bg-muted"> <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" /> <MoreHorizontal className="h-4 w-4" />
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
@@ -28,14 +26,14 @@ export const DockerRowActions = ({ container, containerStatus, onContainerAction
className="cursor-pointer hover:bg-muted" className="cursor-pointer hover:bg-muted"
> >
<BarChart3 className="mr-2 h-4 w-4" /> <BarChart3 className="mr-2 h-4 w-4" />
{t('viewMetrics', 'docker')} View Metrics
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem <DropdownMenuItem
onClick={() => onContainerAction('view-detail', container.id, container.name)} onClick={() => onContainerAction('view-detail', container.id, container.name)}
className="cursor-pointer hover:bg-muted" className="cursor-pointer hover:bg-muted"
> >
<Eye className="mr-2 h-4 w-4" /> <Eye className="mr-2 h-4 w-4" />
{t('viewDetails', 'docker')} View Details
</DropdownMenuItem> </DropdownMenuItem>
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
@@ -1,20 +1,18 @@
import { TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useLanguage } from "@/contexts/LanguageContext";
export const DockerTableHeader = () => { export const DockerTableHeader = () => {
const { t } = useLanguage();
return ( return (
<TableHeader> <TableHeader>
<TableRow className="border-border bg-muted/30"> <TableRow className="border-border bg-muted/30">
<TableHead className="min-w-[200px] font-semibold">{t('container', 'docker')}</TableHead> <TableHead className="min-w-[200px] font-semibold">Container</TableHead>
<TableHead className="min-w-[100px] font-semibold">{t('status', 'docker')}</TableHead> <TableHead className="min-w-[100px] font-semibold">Status</TableHead>
<TableHead className="min-w-[140px] font-semibold">{t('cpuUsage', 'docker')}</TableHead> <TableHead className="min-w-[140px] font-semibold">CPU Usage</TableHead>
<TableHead className="min-w-[160px] font-semibold">{t('memory', 'docker')}</TableHead> <TableHead className="min-w-[160px] font-semibold">Memory</TableHead>
<TableHead className="min-w-[160px] font-semibold">{t('disk', 'docker')}</TableHead> <TableHead className="min-w-[160px] font-semibold">Disk</TableHead>
<TableHead className="min-w-[100px] font-semibold">{t('uptime', 'docker')}</TableHead> <TableHead className="min-w-[100px] font-semibold">Uptime</TableHead>
<TableHead className="min-w-[160px] font-semibold">{t('lastChecked', 'docker')}</TableHead> <TableHead className="min-w-[160px] font-semibold">Last Checked</TableHead>
<TableHead className="min-w-[80px] text-center font-semibold">{t('actions', 'docker')}</TableHead> <TableHead className="min-w-[80px] text-center font-semibold">Actions</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
); );
@@ -2,7 +2,6 @@
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Search, RefreshCw } from "lucide-react"; import { Search, RefreshCw } from "lucide-react";
import { useLanguage } from "@/contexts/LanguageContext";
interface DockerTableSearchProps { interface DockerTableSearchProps {
searchTerm: string; searchTerm: string;
@@ -12,13 +11,12 @@ interface DockerTableSearchProps {
} }
export const DockerTableSearch = ({ searchTerm, onSearchChange, onRefresh, isLoading }: DockerTableSearchProps) => { export const DockerTableSearch = ({ searchTerm, onSearchChange, onRefresh, isLoading }: DockerTableSearchProps) => {
const { t } = useLanguage();
return ( return (
<div className="flex flex-col sm:flex-row gap-3 w-full sm:w-auto"> <div className="flex flex-col sm:flex-row gap-3 w-full sm:w-auto">
<div className="relative flex-1 sm:flex-initial"> <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" /> <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
<Input <Input
placeholder={t('searchContainersPlaceholder', 'docker')} placeholder="Search containers..."
value={searchTerm} value={searchTerm}
onChange={(e) => onSearchChange(e.target.value)} onChange={(e) => onSearchChange(e.target.value)}
className="pl-10 sm:w-64 bg-background border-border" 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" className="w-full sm:w-auto bg-background border-border hover:bg-muted"
> >
<RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? 'animate-spin' : ''}`} /> <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> </Button>
</div> </div>
); );
@@ -11,7 +11,6 @@ import { Plus, X, Server } from 'lucide-react';
import { StatusPageComponentRecord } from '@/types/statusPageComponents.types'; import { StatusPageComponentRecord } from '@/types/statusPageComponents.types';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { serviceService } from '@/services/serviceService'; import { serviceService } from '@/services/serviceService';
import { useLanguage } from "@/contexts/LanguageContext";
interface ComponentsSelectorProps { interface ComponentsSelectorProps {
selectedComponents: Partial<StatusPageComponentRecord>[]; selectedComponents: Partial<StatusPageComponentRecord>[];
@@ -20,7 +19,6 @@ interface ComponentsSelectorProps {
} }
export const ComponentsSelector = ({ selectedComponents, onComponentsChange, onComponentDelete }: ComponentsSelectorProps) => { export const ComponentsSelector = ({ selectedComponents, onComponentsChange, onComponentDelete }: ComponentsSelectorProps) => {
const { t } = useLanguage();
const [showAddForm, setShowAddForm] = useState(false); const [showAddForm, setShowAddForm] = useState(false);
const [newComponent, setNewComponent] = useState({ const [newComponent, setNewComponent] = useState({
name: '', name: '',
@@ -73,16 +71,16 @@ export const ComponentsSelector = ({ selectedComponents, onComponentsChange, onC
<CardHeader> <CardHeader>
<CardTitle className="flex items-center gap-2"> <CardTitle className="flex items-center gap-2">
<Server className="h-5 w-5" /> <Server className="h-5 w-5" />
{t('statusPageComponents')} Status Page Components
</CardTitle> </CardTitle>
<CardDescription> <CardDescription>
{t('addMonitoringComponentsDesc')} Add monitoring components like uptime services, SSL certificates, and incident tracking
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
{selectedComponents.length > 0 && ( {selectedComponents.length > 0 && (
<div className="space-y-2"> <div className="space-y-2">
<Label>{t('selectedComponents')}</Label> <Label>Selected Components</Label>
<div className="space-y-2"> <div className="space-y-2">
{selectedComponents.map((component, index) => ( {selectedComponents.map((component, index) => (
<div key={component.id || index} className="flex items-center justify-between p-3 border rounded-lg"> <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"> <div className="flex gap-2 mt-1">
{component.service_id && ( {component.service_id && (
<Badge variant="secondary" className="text-xs"> <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> </Badge>
)} )}
{component.server_id && ( {component.server_id && (
<Badge variant="secondary" className="text-xs"> <Badge variant="secondary" className="text-xs">
{t('server')}: {component.server_id} Server: {component.server_id}
</Badge> </Badge>
)} )}
</div> </div>
@@ -124,22 +122,22 @@ export const ComponentsSelector = ({ selectedComponents, onComponentsChange, onC
className="w-full" className="w-full"
> >
<Plus className="h-4 w-4 mr-2" /> <Plus className="h-4 w-4 mr-2" />
{t('addComponent')} Add Component
</Button> </Button>
) : ( ) : (
<div className="border rounded-lg p-4 space-y-4"> <div className="border rounded-lg p-4 space-y-4">
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div> <div>
<Label htmlFor="component-name">{t('componentName')}</Label> <Label htmlFor="component-name">Component Name</Label>
<Input <Input
id="component-name" id="component-name"
placeholder={t('componentNamePlaceholder')} placeholder="e.g., Main Website"
value={newComponent.name} value={newComponent.name}
onChange={(e) => setNewComponent({ ...newComponent, name: e.target.value })} onChange={(e) => setNewComponent({ ...newComponent, name: e.target.value })}
/> />
</div> </div>
<div> <div>
<Label htmlFor="display-order">{t('displayOrder')}</Label> <Label htmlFor="display-order">Display Order</Label>
<Input <Input
id="display-order" id="display-order"
type="number" type="number"
@@ -150,10 +148,10 @@ export const ComponentsSelector = ({ selectedComponents, onComponentsChange, onC
</div> </div>
<div> <div>
<Label htmlFor="component-description">{t('descriptionOptional')}</Label> <Label htmlFor="component-description">Description (Optional)</Label>
<Textarea <Textarea
id="component-description" id="component-description"
placeholder={t('descriptionPlaceholder')} placeholder="Brief description of this component"
value={newComponent.description} value={newComponent.description}
onChange={(e) => setNewComponent({ ...newComponent, description: e.target.value })} 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 className="grid grid-cols-2 gap-4">
<div> <div>
<Label htmlFor="service-id">{t('uptimeServiceOptional')}</Label> <Label htmlFor="service-id">Uptime Service (Optional)</Label>
<Select onValueChange={(value) => setNewComponent({ ...newComponent, service_id: value })}> <Select onValueChange={(value) => setNewComponent({ ...newComponent, service_id: value })}>
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder={t('selectUptimeService')} /> <SelectValue placeholder="Select an uptime service" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{services.map((service) => ( {services.map((service) => (
@@ -183,10 +181,10 @@ export const ComponentsSelector = ({ selectedComponents, onComponentsChange, onC
</Select> </Select>
</div> </div>
<div> <div>
<Label htmlFor="server-id">{t('serverIdOptional')}</Label> <Label htmlFor="server-id">Server ID (Optional)</Label>
<Input <Input
id="server-id" id="server-id"
placeholder={t('serverIdPlaceholder')} placeholder="server_456"
value={newComponent.server_id} value={newComponent.server_id}
onChange={(e) => setNewComponent({ ...newComponent, server_id: e.target.value })} onChange={(e) => setNewComponent({ ...newComponent, server_id: e.target.value })}
/> />
@@ -195,10 +193,10 @@ export const ComponentsSelector = ({ selectedComponents, onComponentsChange, onC
<div className="flex gap-2"> <div className="flex gap-2">
<Button onClick={addComponent} disabled={!newComponent.name.trim()}> <Button onClick={addComponent} disabled={!newComponent.name.trim()}>
{t('addComponent')} Add Component
</Button> </Button>
<Button variant="outline" onClick={() => setShowAddForm(false)}> <Button variant="outline" onClick={() => setShowAddForm(false)}>
{t('cancel')} Cancel
</Button> </Button>
</div> </div>
</div> </div>
@@ -14,7 +14,6 @@ import { useCreateStatusPageComponent } from '@/hooks/useStatusPageComponents';
import { ComponentsSelector } from './ComponentsSelector'; import { ComponentsSelector } from './ComponentsSelector';
import { Plus } from 'lucide-react'; import { Plus } from 'lucide-react';
import { StatusPageComponentRecord } from '@/types/statusPageComponents.types'; import { StatusPageComponentRecord } from '@/types/statusPageComponents.types';
import { useLanguage } from "@/contexts/LanguageContext";
const formSchema = z.object({ const formSchema = z.object({
title: z.string().min(1, 'Title is required'), title: z.string().min(1, 'Title is required'),
@@ -32,7 +31,6 @@ const formSchema = z.object({
type FormData = z.infer<typeof formSchema>; type FormData = z.infer<typeof formSchema>;
export const CreateOperationalPageDialog = () => { export const CreateOperationalPageDialog = () => {
const { t } = useLanguage();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [selectedComponents, setSelectedComponents] = useState<Partial<StatusPageComponentRecord>[]>([]); const [selectedComponents, setSelectedComponents] = useState<Partial<StatusPageComponentRecord>[]>([]);
const createMutation = useCreateOperationalPage(); const createMutation = useCreateOperationalPage();
@@ -104,14 +102,14 @@ export const CreateOperationalPageDialog = () => {
<DialogTrigger asChild> <DialogTrigger asChild>
<Button className="gap-2"> <Button className="gap-2">
<Plus className="h-4 w-4" /> <Plus className="h-4 w-4" />
{t('createPage')} Create Page
</Button> </Button>
</DialogTrigger> </DialogTrigger>
<DialogContent className="sm:max-w-[800px] max-h-[90vh] overflow-y-auto"> <DialogContent className="sm:max-w-[800px] max-h-[90vh] overflow-y-auto">
<DialogHeader> <DialogHeader>
<DialogTitle>{t('createOperationalPage')}</DialogTitle> <DialogTitle>Create Operational Page</DialogTitle>
<DialogDescription> <DialogDescription>
{t('createOperationalPageDesc')} Create a new operational status page to monitor your services and components.
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
@@ -123,9 +121,9 @@ export const CreateOperationalPageDialog = () => {
name="title" name="title"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t('title')}</FormLabel> <FormLabel>Title</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t('myServiceStatusPlaceholder')} {...field} /> <Input placeholder="My Service Status" {...field} />
</FormControl> </FormControl>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -137,9 +135,9 @@ export const CreateOperationalPageDialog = () => {
name="slug" name="slug"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t('slug')}</FormLabel> <FormLabel>Slug</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t('myServiceStatusSlugPlaceholder')} {...field} /> <Input placeholder="my-service-status" {...field} />
</FormControl> </FormControl>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -152,10 +150,10 @@ export const CreateOperationalPageDialog = () => {
name="description" name="description"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t('description')}</FormLabel> <FormLabel>Description</FormLabel>
<FormControl> <FormControl>
<Textarea <Textarea
placeholder={t('operationalPageDescriptionPlaceholder')} placeholder="A brief description of your operational page"
className="min-h-[80px]" className="min-h-[80px]"
{...field} {...field}
/> />
@@ -171,17 +169,17 @@ export const CreateOperationalPageDialog = () => {
name="theme" name="theme"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t('theme')}</FormLabel> <FormLabel>Theme</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}> <Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl> <FormControl>
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder={t('selectTheme')} /> <SelectValue placeholder="Select theme" />
</SelectTrigger> </SelectTrigger>
</FormControl> </FormControl>
<SelectContent> <SelectContent>
<SelectItem value="default">{t('themeDefault')}</SelectItem> <SelectItem value="default">Default</SelectItem>
<SelectItem value="dark">{t('themeDark')}</SelectItem> <SelectItem value="dark">Dark</SelectItem>
<SelectItem value="light">{t('themeLight')}</SelectItem> <SelectItem value="light">Light</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
<FormMessage /> <FormMessage />
@@ -194,18 +192,18 @@ export const CreateOperationalPageDialog = () => {
name="status" name="status"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t('initialStatus')}</FormLabel> <FormLabel>Initial Status</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}> <Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl> <FormControl>
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder={t('selectStatus')} /> <SelectValue placeholder="Select status" />
</SelectTrigger> </SelectTrigger>
</FormControl> </FormControl>
<SelectContent> <SelectContent>
<SelectItem value="operational">{t('statusOperational')}</SelectItem> <SelectItem value="operational">Operational</SelectItem>
<SelectItem value="degraded">{t('statusDegraded')}</SelectItem> <SelectItem value="degraded">Degraded Performance</SelectItem>
<SelectItem value="maintenance">{t('statusMaintenance')}</SelectItem> <SelectItem value="maintenance">Under Maintenance</SelectItem>
<SelectItem value="major_outage">{t('statusMajorOutage')}</SelectItem> <SelectItem value="major_outage">Major Outage</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
<FormMessage /> <FormMessage />
@@ -220,9 +218,9 @@ export const CreateOperationalPageDialog = () => {
render={({ field }) => ( render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm"> <FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm">
<div className="space-y-0.5"> <div className="space-y-0.5">
<FormLabel>{t('publicPage')}</FormLabel> <FormLabel>Public Page</FormLabel>
<FormDescription> <FormDescription>
{t('makePagePublic')} Make this page publicly accessible
</FormDescription> </FormDescription>
</div> </div>
<FormControl> <FormControl>
@@ -240,12 +238,12 @@ export const CreateOperationalPageDialog = () => {
name="custom_domain" name="custom_domain"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t('customDomainOptional')}</FormLabel> <FormLabel>Custom Domain (Optional)</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t('customDomainPlaceholder')} {...field} /> <Input placeholder="status.yourdomain.com" {...field} />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
{t('customDomainDescription')} Custom domain for your status page
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -263,13 +261,13 @@ export const CreateOperationalPageDialog = () => {
variant="outline" variant="outline"
onClick={() => setOpen(false)} onClick={() => setOpen(false)}
> >
{t('cancel')} Cancel
</Button> </Button>
<Button <Button
type="submit" type="submit"
disabled={createMutation.isPending || createComponentMutation.isPending} disabled={createMutation.isPending || createComponentMutation.isPending}
> >
{createMutation.isPending || createComponentMutation.isPending ? t('creating') : t('createPage')} {createMutation.isPending || createComponentMutation.isPending ? 'Creating...' : 'Create Page'}
</Button> </Button>
</div> </div>
</form> </form>
@@ -14,7 +14,6 @@ import { useCreateStatusPageComponent, useStatusPageComponentsByOperationalId, u
import { ComponentsSelector } from './ComponentsSelector'; import { ComponentsSelector } from './ComponentsSelector';
import { OperationalPageRecord } from '@/types/operational.types'; import { OperationalPageRecord } from '@/types/operational.types';
import { StatusPageComponentRecord } from '@/types/statusPageComponents.types'; import { StatusPageComponentRecord } from '@/types/statusPageComponents.types';
import { useLanguage } from "@/contexts/LanguageContext";
const formSchema = z.object({ const formSchema = z.object({
title: z.string().min(1, 'Title is required'), title: z.string().min(1, 'Title is required'),
@@ -38,7 +37,6 @@ interface EditOperationalPageDialogProps {
} }
export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOperationalPageDialogProps) => { export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOperationalPageDialogProps) => {
const { t } = useLanguage();
const [selectedComponents, setSelectedComponents] = useState<Partial<StatusPageComponentRecord>[]>([]); const [selectedComponents, setSelectedComponents] = useState<Partial<StatusPageComponentRecord>[]>([]);
const [isFormSubmitting, setIsFormSubmitting] = useState(false); const [isFormSubmitting, setIsFormSubmitting] = useState(false);
const [componentsLoaded, setComponentsLoaded] = useState(false); const [componentsLoaded, setComponentsLoaded] = useState(false);
@@ -197,9 +195,9 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[800px] max-h-[90vh] overflow-y-auto"> <DialogContent className="sm:max-w-[800px] max-h-[90vh] overflow-y-auto">
<DialogHeader> <DialogHeader>
<DialogTitle>{t('editOperationalPage')}</DialogTitle> <DialogTitle>Edit Operational Page</DialogTitle>
<DialogDescription> <DialogDescription>
{t('updateYourOperationalPage')} Update your operational status page settings and manage components.
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
@@ -211,9 +209,9 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
name="title" name="title"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t('title')}</FormLabel> <FormLabel>Title</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t('myServiceStatusPlaceholder')} {...field} /> <Input placeholder="My Service Status" {...field} />
</FormControl> </FormControl>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -225,9 +223,9 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
name="slug" name="slug"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t('slug')}</FormLabel> <FormLabel>Slug</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t('myServiceStatusSlugPlaceholder')} {...field} /> <Input placeholder="my-service-status" {...field} />
</FormControl> </FormControl>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -240,10 +238,10 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
name="description" name="description"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t('description')}</FormLabel> <FormLabel>Description</FormLabel>
<FormControl> <FormControl>
<Textarea <Textarea
placeholder={t('operationalPageDescriptionPlaceholder')} placeholder="A brief description of your operational page"
className="min-h-[80px]" className="min-h-[80px]"
{...field} {...field}
/> />
@@ -259,17 +257,17 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
name="theme" name="theme"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t('theme')}</FormLabel> <FormLabel>Theme</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}> <Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl> <FormControl>
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder={t('selectTheme')} /> <SelectValue placeholder="Select theme" />
</SelectTrigger> </SelectTrigger>
</FormControl> </FormControl>
<SelectContent> <SelectContent>
<SelectItem value="default">{t('themeDefault')}</SelectItem> <SelectItem value="default">Default</SelectItem>
<SelectItem value="dark">{t('themeDark')}</SelectItem> <SelectItem value="dark">Dark</SelectItem>
<SelectItem value="light">{t('themeLight')}</SelectItem> <SelectItem value="light">Light</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
<FormMessage /> <FormMessage />
@@ -282,18 +280,18 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
name="status" name="status"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t('status')}</FormLabel> <FormLabel>Status</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}> <Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl> <FormControl>
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder={t('selectStatus')} /> <SelectValue placeholder="Select status" />
</SelectTrigger> </SelectTrigger>
</FormControl> </FormControl>
<SelectContent> <SelectContent>
<SelectItem value="operational">{t('statusOperational')}</SelectItem> <SelectItem value="operational">Operational</SelectItem>
<SelectItem value="degraded">{t('statusDegraded')}</SelectItem> <SelectItem value="degraded">Degraded Performance</SelectItem>
<SelectItem value="maintenance">{t('statusMaintenance')}</SelectItem> <SelectItem value="maintenance">Under Maintenance</SelectItem>
<SelectItem value="major_outage">{t('statusMajorOutage')}</SelectItem> <SelectItem value="major_outage">Major Outage</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
<FormMessage /> <FormMessage />
@@ -308,9 +306,9 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
render={({ field }) => ( render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm"> <FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm">
<div className="space-y-0.5"> <div className="space-y-0.5">
<FormLabel>{t('publicPage')}</FormLabel> <FormLabel>Public Page</FormLabel>
<FormDescription> <FormDescription>
{t('makePagePublic')} Make this page publicly accessible
</FormDescription> </FormDescription>
</div> </div>
<FormControl> <FormControl>
@@ -328,12 +326,12 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
name="custom_domain" name="custom_domain"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t('customDomainOptional')}</FormLabel> <FormLabel>Custom Domain (Optional)</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t('customDomainPlaceholder')} {...field} /> <Input placeholder="status.yourdomain.com" {...field} />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
{t('customDomainDescription')} Custom domain for your status page
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -352,13 +350,13 @@ export const EditOperationalPageDialog = ({ page, open, onOpenChange }: EditOper
variant="outline" variant="outline"
onClick={() => onOpenChange(false)} onClick={() => onOpenChange(false)}
> >
{t('cancel')} Cancel
</Button> </Button>
<Button <Button
type="submit" type="submit"
disabled={isFormSubmitting || updateMutation.isPending || createComponentMutation.isPending} disabled={isFormSubmitting || updateMutation.isPending || createComponentMutation.isPending}
> >
{isFormSubmitting || updateMutation.isPending || createComponentMutation.isPending ? t('updating') : t('updatePage')} {isFormSubmitting || updateMutation.isPending || createComponentMutation.isPending ? 'Updating...' : 'Update Page'}
</Button> </Button>
</div> </div>
</form> </form>
@@ -6,7 +6,6 @@ import { OperationalPageRecord } from '@/types/operational.types';
import { StatusBadge } from './StatusBadge'; import { StatusBadge } from './StatusBadge';
import { Globe, ExternalLink, Eye, Settings, Trash2 } from 'lucide-react'; import { Globe, ExternalLink, Eye, Settings, Trash2 } from 'lucide-react';
import { format } from 'date-fns'; import { format } from 'date-fns';
import { useLanguage } from "@/contexts/LanguageContext";
interface OperationalPageCardProps { interface OperationalPageCardProps {
page: OperationalPageRecord; page: OperationalPageRecord;
@@ -16,8 +15,6 @@ interface OperationalPageCardProps {
} }
export const OperationalPageCard = ({ page, onEdit, onView, onDelete }: OperationalPageCardProps) => { export const OperationalPageCard = ({ page, onEdit, onView, onDelete }: OperationalPageCardProps) => {
const { t } = useLanguage();
return ( return (
<Card className="hover:shadow-lg transition-shadow duration-200"> <Card className="hover:shadow-lg transition-shadow duration-200">
<CardHeader className="pb-3"> <CardHeader className="pb-3">
@@ -35,23 +32,23 @@ export const OperationalPageCard = ({ page, onEdit, onView, onDelete }: Operatio
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4 text-sm"> <div className="grid grid-cols-2 gap-4 text-sm">
<div> <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> <p className="mt-1">{page.slug}</p>
</div> </div>
<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> <p className="mt-1 capitalize">{page.theme}</p>
</div> </div>
<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"> <div className="mt-1">
<Badge variant={page.is_public === 'true' ? 'default' : 'secondary'}> <Badge variant={page.is_public === 'true' ? 'default' : 'secondary'}>
{page.is_public === 'true' ? t('yes') : t('no')} {page.is_public === 'true' ? 'Yes' : 'No'}
</Badge> </Badge>
</div> </div>
</div> </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> <p className="mt-1">{format(new Date(page.updated), 'MMM dd, yyyy')}</p>
</div> </div>
</div> </div>
@@ -73,7 +70,7 @@ export const OperationalPageCard = ({ page, onEdit, onView, onDelete }: Operatio
className="flex-1" className="flex-1"
> >
<Eye className="h-4 w-4 mr-2" /> <Eye className="h-4 w-4 mr-2" />
{t('view')} View
</Button> </Button>
)} )}
{onEdit && ( {onEdit && (
@@ -84,7 +81,7 @@ export const OperationalPageCard = ({ page, onEdit, onView, onDelete }: Operatio
className="flex-1" className="flex-1"
> >
<Settings className="h-4 w-4 mr-2" /> <Settings className="h-4 w-4 mr-2" />
{t('edit')} Edit
</Button> </Button>
)} )}
{onDelete && ( {onDelete && (
@@ -9,8 +9,6 @@ import { Button } from '@/components/ui/button';
import { OperationalPageRecord } from '@/types/operational.types'; import { OperationalPageRecord } from '@/types/operational.types';
import { Activity, Plus, RefreshCw } from 'lucide-react'; import { Activity, Plus, RefreshCw } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton'; import { Skeleton } from '@/components/ui/skeleton';
import { useLanguage } from "@/contexts/LanguageContext";
import { import {
AlertDialog, AlertDialog,
AlertDialogAction, AlertDialogAction,
@@ -23,7 +21,6 @@ import {
} from '@/components/ui/alert-dialog'; } from '@/components/ui/alert-dialog';
export const OperationalPageContent = () => { export const OperationalPageContent = () => {
const { t } = useLanguage();
const navigate = useNavigate(); const navigate = useNavigate();
const { data: pages, isLoading, error, refetch, isRefetching } = useOperationalPages(); const { data: pages, isLoading, error, refetch, isRefetching } = useOperationalPages();
const deleteMutation = useDeleteOperationalPage(); const deleteMutation = useDeleteOperationalPage();
@@ -71,13 +68,13 @@ export const OperationalPageContent = () => {
<div className="mb-4"> <div className="mb-4">
<Activity className="h-12 w-12 text-muted-foreground mx-auto" /> <Activity className="h-12 w-12 text-muted-foreground mx-auto" />
</div> </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"> <p className="text-muted-foreground mb-4">
{t('loadingoperationalPages')} There was an error loading your operational pages. Please try again.
</p> </p>
<Button onClick={() => refetch()} variant="outline"> <Button onClick={() => refetch()} variant="outline">
<RefreshCw className="h-4 w-4 mr-2" /> <RefreshCw className="h-4 w-4 mr-2" />
{t('tryagain')} Try Again
</Button> </Button>
</div> </div>
</div> </div>
@@ -89,9 +86,9 @@ export const OperationalPageContent = () => {
{/* Header */} {/* 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> <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"> <p className="text-muted-foreground">
{t('describeOperation')} Manage your public status pages and monitor service health
</p> </p>
</div> </div>
@@ -103,7 +100,7 @@ export const OperationalPageContent = () => {
disabled={isRefetching} disabled={isRefetching}
> >
<RefreshCw className={`h-4 w-4 mr-2 ${isRefetching ? 'animate-spin' : ''}`} /> <RefreshCw className={`h-4 w-4 mr-2 ${isRefetching ? 'animate-spin' : ''}`} />
{t('refresh')} Refresh
</Button> </Button>
<CreateOperationalPageDialog /> <CreateOperationalPageDialog />
</div> </div>
@@ -138,9 +135,9 @@ export const OperationalPageContent = () => {
<div className="mb-4"> <div className="mb-4">
<Activity className="h-12 w-12 text-muted-foreground mx-auto" /> <Activity className="h-12 w-12 text-muted-foreground mx-auto" />
</div> </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"> <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> </p>
<CreateOperationalPageDialog /> <CreateOperationalPageDialog />
</CardContent> </CardContent>
@@ -167,14 +164,14 @@ export const OperationalPageContent = () => {
<div className="mt-8 pt-6 border-t"> <div className="mt-8 pt-6 border-t">
<div className="flex flex-wrap gap-6 text-sm text-muted-foreground"> <div className="flex flex-wrap gap-6 text-sm text-muted-foreground">
<div> <div>
<span className="font-medium">{t('totalPages')}:</span> {pages.length} <span className="font-medium">Total Pages:</span> {pages.length}
</div> </div>
<div> <div>
<span className="font-medium">{t('totalPages')}:</span>{' '} <span className="font-medium">Public Pages:</span>{' '}
{pages.filter(p => p.is_public === 'true').length} {pages.filter(p => p.is_public === 'true').length}
</div> </div>
<div> <div>
<span className="font-medium">{t('operational')}:</span>{' '} <span className="font-medium">Operational:</span>{' '}
{pages.filter(p => p.status === 'operational').length} {pages.filter(p => p.status === 'operational').length}
</div> </div>
</div> </div>
@@ -192,19 +189,19 @@ export const OperationalPageContent = () => {
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}> <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent> <AlertDialogContent>
<AlertDialogHeader> <AlertDialogHeader>
<AlertDialogTitle>{t('deleteOperationalPage')}</AlertDialogTitle> <AlertDialogTitle>Delete Operational Page</AlertDialogTitle>
<AlertDialogDescription> <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> </AlertDialogDescription>
</AlertDialogHeader> </AlertDialogHeader>
<AlertDialogFooter> <AlertDialogFooter>
<AlertDialogCancel>{t('cancel')}</AlertDialogCancel> <AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction <AlertDialogAction
onClick={confirmDelete} onClick={confirmDelete}
className="bg-red-600 hover:bg-red-700" className="bg-red-600 hover:bg-red-700"
disabled={deleteMutation.isPending} disabled={deleteMutation.isPending}
> >
{deleteMutation.isPending ? t('deleting') : t('delete')} {deleteMutation.isPending ? 'Deleting...' : 'Delete'}
</AlertDialogAction> </AlertDialogAction>
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
@@ -5,7 +5,6 @@ import { format } from 'date-fns';
import { OperationalPageRecord } from '@/types/operational.types'; import { OperationalPageRecord } from '@/types/operational.types';
import { StatusPageComponentRecord } from '@/types/statusPageComponents.types'; import { StatusPageComponentRecord } from '@/types/statusPageComponents.types';
import { Service } from '@/types/service.types'; import { Service } from '@/types/service.types';
import { useLanguage } from '@/contexts/LanguageContext';
interface CurrentStatusSectionProps { interface CurrentStatusSectionProps {
page: OperationalPageRecord; page: OperationalPageRecord;
@@ -46,18 +45,18 @@ const getActualStatus = (components: StatusPageComponentRecord[], services: Serv
return 'operational'; return 'operational';
}; };
const getStatusMessage = (status: OperationalPageRecord['status'], t: (k: string, m?: string) => string) => { const getStatusMessage = (status: OperationalPageRecord['status']) => {
switch (status) { switch (status) {
case 'operational': case 'operational':
return t('allOperational', 'public'); return 'All systems are operational';
case 'degraded': case 'degraded':
return t('degradedPerformance', 'public'); return 'Some systems are experiencing degraded performance';
case 'maintenance': case 'maintenance':
return t('underMaintenance', 'public'); return 'Systems are currently under maintenance';
case 'major_outage': case 'major_outage':
return t('majorOutage', 'public'); return 'We are experiencing a major service outage';
default: default:
return t('statusUnknown', 'public'); return 'Status unknown';
} }
}; };
@@ -107,7 +106,6 @@ const getStatusBackground = (status: OperationalPageRecord['status']) => {
}; };
export const CurrentStatusSection = ({ page, components, services }: CurrentStatusSectionProps) => { export const CurrentStatusSection = ({ page, components, services }: CurrentStatusSectionProps) => {
const { t } = useLanguage();
const actualStatus = getActualStatus(components, services); const actualStatus = getActualStatus(components, services);
const displayStatus = actualStatus; // Use actual status for real-time accuracy const displayStatus = actualStatus; // Use actual status for real-time accuracy
@@ -116,7 +114,7 @@ export const CurrentStatusSection = ({ page, components, services }: CurrentStat
<CardHeader> <CardHeader>
<CardTitle className="flex items-center gap-3 text-card-foreground text-xl"> <CardTitle className="flex items-center gap-3 text-card-foreground text-xl">
<Shield className="h-6 w-6" /> <Shield className="h-6 w-6" />
{t('systemStatus', 'public')} System Status
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent className="space-y-6"> <CardContent className="space-y-6">
@@ -125,10 +123,10 @@ export const CurrentStatusSection = ({ page, components, services }: CurrentStat
{getStatusIcon(displayStatus)} {getStatusIcon(displayStatus)}
<div> <div>
<h3 className={`text-2xl font-bold ${getStatusColor(displayStatus)}`}> <h3 className={`text-2xl font-bold ${getStatusColor(displayStatus)}`}>
{getStatusMessage(displayStatus, t)} {getStatusMessage(displayStatus)}
</h3> </h3>
<p className="text-sm text-muted-foreground mt-1"> <p className="text-sm text-muted-foreground mt-1">
{t('autoUpdatedByHealth', 'public')} Status automatically updated based on component health
</p> </p>
</div> </div>
</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' : 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' 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
}`}> }`}>
{displayStatus === 'operational' ? t('allOperational', 'public') : {displayStatus === 'operational' ? 'All Systems Operational' :
displayStatus === 'degraded' ? t('degradedPerformance', 'public') : displayStatus === 'degraded' ? 'Degraded Performance' :
displayStatus === 'maintenance' ? t('underMaintenance', 'public') : t('majorOutage', 'public')} displayStatus === 'maintenance' ? 'Under Maintenance' : 'Major Outage'}
</div> </div>
</div> </div>
<div className="flex items-center justify-between text-sm text-muted-foreground border-t pt-4"> <div className="flex items-center justify-between text-sm text-muted-foreground border-t pt-4">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Clock className="h-4 w-4" /> <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>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<div className="h-2 w-2 bg-green-500 rounded-full animate-pulse"></div> <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>
</div> </div>
</CardContent> </CardContent>
@@ -9,10 +9,8 @@ import { CurrentStatusSection } from './CurrentStatusSection';
import { ComponentsStatusSection } from './ComponentsStatusSection'; import { ComponentsStatusSection } from './ComponentsStatusSection';
import { OverallUptimeSection } from './OverallUptimeSection'; import { OverallUptimeSection } from './OverallUptimeSection';
import { PublicStatusPageFooter } from './PublicStatusPageFooter'; import { PublicStatusPageFooter } from './PublicStatusPageFooter';
import { useLanguage } from '@/contexts/LanguageContext';
export const PublicStatusPage = () => { export const PublicStatusPage = () => {
const { t } = useLanguage();
const { slug } = useParams<{ slug: string }>(); const { slug } = useParams<{ slug: string }>();
// console.log('PublicStatusPage - slug from params:', slug); // console.log('PublicStatusPage - slug from params:', slug);
@@ -61,9 +59,9 @@ export const PublicStatusPage = () => {
<div className="text-center space-y-4"> <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="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"></div>
<div className="space-y-2"> <div className="space-y-2">
<p className="text-lg font-medium text-foreground">{t('loadingStatusPage', 'public')}</p> <p className="text-lg font-medium text-foreground">Loading Status Page</p>
<p className="text-sm text-muted-foreground">{t('fetchingRealtimeStatus', 'public')}</p> <p className="text-sm text-muted-foreground">Fetching real-time system status...</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>
</div> </div>
</div> </div>
@@ -78,19 +76,19 @@ export const PublicStatusPage = () => {
<AlertCircle className="h-8 w-8 text-red-600 dark:text-red-400" /> <AlertCircle className="h-8 w-8 text-red-600 dark:text-red-400" />
</div> </div>
<div className="space-y-2"> <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"> <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>
<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>
<div className="flex gap-3 justify-center"> <div className="flex gap-3 justify-center">
<Button onClick={() => window.history.back()} variant="outline"> <Button onClick={() => window.history.back()} variant="outline">
{t('goBack', 'public')} Go Back
</Button> </Button>
<Button onClick={() => window.location.reload()} className="gap-2"> <Button onClick={() => window.location.reload()} className="gap-2">
<RefreshCw className="h-4 w-4" /> <RefreshCw className="h-4 w-4" />
{t('retry', 'public')} Retry
</Button> </Button>
</div> </div>
</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 { 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 { 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 { 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 { interface AddRegionalAgentDialogProps {
open: boolean; open: boolean;
@@ -19,54 +22,30 @@ export const AddRegionalAgentDialog: React.FC<AddRegionalAgentDialogProps> = ({
onOpenChange, onOpenChange,
onAgentAdded onAgentAdded
}) => { }) => {
const { t } = useLanguage(); const [step, setStep] = useState(1);
const { toast } = useToast(); const [regionName, setRegionName] = useState("");
const [activeTab, setActiveTab] = useState("configure"); const [agentIp, setAgentIp] = useState("");
const [formData, setFormData] = useState({ const [installCommand, setInstallCommand] = useState<InstallCommand | null>(null);
regionName: "",
agentIp: "",
});
const [agentToken, setAgentToken] = useState("");
const [agentId, setAgentId] = useState("");
const [currentPocketBaseUrl, setCurrentPocketBaseUrl] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
const { toast } = useToast();
// Generate new credentials when dialog opens or after successful creation const handleCreateAgent = async (e: React.FormEvent) => {
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) => {
e.preventDefault(); e.preventDefault();
if (!formData.regionName.trim() || !formData.agentIp.trim()) return; if (!regionName.trim() || !agentIp.trim()) return;
setIsSubmitting(true); setIsSubmitting(true);
try { try {
await new Promise(resolve => setTimeout(resolve, 1000)); const result = await regionalService.createRegionalService({
region_name: regionName,
toast({ agent_ip_address: agentIp,
title: t('success'),
description: t('agentCreatedSuccessfully'),
}); });
setActiveTab("one-click");
generateNewCredentials();
onAgentAdded(); setInstallCommand(result.installCommand);
setStep(2);
} catch (error) { } catch (error) {
toast({ toast({
title: t('error'), title: "Error",
description: t('failedToCreateAgent'), description: "Failed to create regional agent configuration.",
variant: "destructive", variant: "destructive",
}); });
} finally { } finally {
@@ -74,65 +53,407 @@ export const AddRegionalAgentDialog: React.FC<AddRegionalAgentDialogProps> = ({
} }
}; };
const handleDialogClose = () => { const copyToClipboard = async (text: string, description: string = "Content") => {
setFormData({ try {
regionName: "", // Try the modern clipboard API first
agentIp: "", 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); onOpenChange(false);
}; };
const resetDialog = () => {
setStep(1);
setRegionName("");
setAgentIp("");
setInstallCommand(null);
};
return ( return (
<Dialog open={open} onOpenChange={handleDialogClose}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[900px] max-h-[90vh] overflow-auto"> <DialogContent className="sm:max-w-[900px] max-h-[90vh] overflow-auto">
<DialogHeader> <DialogHeader>
<DialogTitle>{t('addRegionalMonitoringAgent')}</DialogTitle> <DialogTitle>Add Regional Monitoring Agent</DialogTitle>
<DialogDescription> <DialogDescription>
{t('deployRegionalMonitoringAgent')} Deploy a regional monitoring agent with automatic one-click installation.
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full"> {step === 1 && (
<TabsList className="grid w-full grid-cols-3"> <form onSubmit={handleCreateAgent} className="space-y-6">
<TabsTrigger value="configure">{t('configureAgent')}</TabsTrigger> <div className="space-y-4">
<TabsTrigger value="one-click">{t('oneClickInstallTab')}</TabsTrigger> <div>
<TabsTrigger value="manual">{t('manualInstallTab')}</TabsTrigger> <Label htmlFor="regionName">Region Name</Label>
</TabsList> <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>
<TabsContent value="configure" className="space-y-6"> <div>
<RegionalAgentConfigForm <Label htmlFor="agentIp">Agent Server IP Address</Label>
formData={formData} <Input
setFormData={setFormData} id="agentIp"
agentId={agentId} placeholder="e.g., 192.168.1.100 or your-server.example.com"
agentToken={agentToken} value={agentIp}
currentPocketBaseUrl={currentPocketBaseUrl} onChange={(e) => setAgentIp(e.target.value)}
isSubmitting={isSubmitting} required
onSubmit={handleSubmit} />
/> </div>
</TabsContent> </div>
<TabsContent value="one-click" className="space-y-6"> <div className="flex justify-end space-x-2">
<RegionalOneClickTab <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
agentToken={agentToken} Cancel
currentPocketBaseUrl={currentPocketBaseUrl} </Button>
formData={formData} <Button type="submit" disabled={isSubmitting}>
agentId={agentId} {isSubmitting ? "Generating..." : "Generate Installation"}
onDialogClose={handleDialogClose} </Button>
/> </div>
</TabsContent> </form>
)}
<TabsContent value="manual" className="space-y-6"> {step === 2 && installCommand && (
<RegionalManualTab <div className="space-y-6">
agentToken={agentToken} <div className="text-center space-y-2">
currentPocketBaseUrl={currentPocketBaseUrl} <CheckCircle className="h-12 w-12 text-green-600 mx-auto" />
formData={formData} <h3 className="text-lg font-semibold">Agent Configuration Ready!</h3>
agentId={agentId} <p className="text-muted-foreground">
onDialogClose={handleDialogClose} One-click installation script generated with automatic configuration.
/> </p>
</TabsContent> </div>
</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> </DialogContent>
</Dialog> </Dialog>
); );
@@ -8,7 +8,6 @@ import { MapPin, Wifi, WifiOff, MoreVertical, Trash2, Terminal, Copy } from "luc
import { RegionalService } from "@/types/regional.types"; import { RegionalService } from "@/types/regional.types";
import { formatDistanceToNow } from "date-fns"; import { formatDistanceToNow } from "date-fns";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { useLanguage } from "@/contexts/LanguageContext";
interface RegionalAgentCardProps { interface RegionalAgentCardProps {
agent: RegionalService; agent: RegionalService;
@@ -17,7 +16,6 @@ interface RegionalAgentCardProps {
export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onDelete }) => { export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onDelete }) => {
const { toast } = useToast(); const { toast } = useToast();
const { t } = useLanguage();
// Check if this is the default agent that cannot be removed // Check if this is the default agent that cannot be removed
const isDefaultAgent = agent.agent_id === "1" || agent.region_name === "Default"; const isDefaultAgent = agent.agent_id === "1" || agent.region_name === "Default";
@@ -26,13 +24,13 @@ export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onD
try { try {
await navigator.clipboard.writeText(agent.agent_id); await navigator.clipboard.writeText(agent.agent_id);
toast({ toast({
title: t('copied'), title: "Copied!",
description: t('copiedDescription'), description: "Agent ID copied to clipboard.",
}); });
} catch (error) { } catch (error) {
toast({ toast({
title: t('copyFailed'), title: "Copy failed",
description: t('copyFailedDescription'), description: "Failed to copy agent ID.",
variant: "destructive", variant: "destructive",
}); });
} }
@@ -42,14 +40,14 @@ export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onD
if (agent.connection === 'online') { if (agent.connection === 'online') {
return { return {
icon: <Wifi className="h-4 w-4" />, icon: <Wifi className="h-4 w-4" />,
label: t('online'), label: 'Online',
variant: 'default' as const, variant: 'default' as const,
className: 'bg-green-100 text-green-800 hover:bg-green-100' className: 'bg-green-100 text-green-800 hover:bg-green-100'
}; };
} else { } else {
return { return {
icon: <WifiOff className="h-4 w-4" />, icon: <WifiOff className="h-4 w-4" />,
label: t('offline'), label: 'Offline',
variant: 'secondary' as const, variant: 'secondary' as const,
className: 'bg-red-100 text-red-800 hover:bg-red-100' 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} {agent.region_name}
{isDefaultAgent && ( {isDefaultAgent && (
<Badge variant="outline" className="text-xs bg-blue-50 text-blue-700 border-blue-200"> <Badge variant="outline" className="text-xs bg-blue-50 text-blue-700 border-blue-200">
{t('defaultBadge')} Default
</Badge> </Badge>
)} )}
</CardTitle> </CardTitle>
@@ -88,12 +86,12 @@ export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onD
<DropdownMenuContent align="end"> <DropdownMenuContent align="end">
<DropdownMenuItem onClick={copyAgentId}> <DropdownMenuItem onClick={copyAgentId}>
<Copy className="mr-2 h-4 w-4" /> <Copy className="mr-2 h-4 w-4" />
{t('copyAgentId')} Copy Agent ID
</DropdownMenuItem> </DropdownMenuItem>
{!isDefaultAgent && ( {!isDefaultAgent && (
<DropdownMenuItem onClick={onDelete} className="text-red-600"> <DropdownMenuItem onClick={onDelete} className="text-red-600">
<Trash2 className="mr-2 h-4 w-4" /> <Trash2 className="mr-2 h-4 w-4" />
{t('removeAgent')} Remove Agent
</DropdownMenuItem> </DropdownMenuItem>
)} )}
</DropdownMenuContent> </DropdownMenuContent>
@@ -118,12 +116,12 @@ export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onD
<div className="space-y-2"> <div className="space-y-2">
<div className="flex justify-between text-sm"> <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> <span className="font-mono text-xs">{agent.agent_id.substring(0, 12)}...</span>
</div> </div>
<div className="flex justify-between text-sm"> <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"> <span className="text-xs">
{formatDistanceToNow(new Date(agent.updated), { addSuffix: true })} {formatDistanceToNow(new Date(agent.updated), { addSuffix: true })}
</span> </span>
@@ -134,7 +132,7 @@ export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onD
<div className="pt-2 border-t"> <div className="pt-2 border-t">
<div className="flex items-center text-xs text-green-600"> <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> <div className="w-2 h-2 bg-green-600 rounded-full mr-2 animate-pulse"></div>
{t('activeMonitoring')} Active monitoring
</div> </div>
</div> </div>
)} )}
@@ -143,7 +141,7 @@ export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onD
<div className="pt-2 border-t"> <div className="pt-2 border-t">
<div className="flex items-center text-xs text-red-600"> <div className="flex items-center text-xs text-red-600">
<div className="w-2 h-2 bg-red-600 rounded-full mr-2"></div> <div className="w-2 h-2 bg-red-600 rounded-full mr-2"></div>
{t('connectionLost')} Connection lost
</div> </div>
</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>
);
};
@@ -9,10 +9,8 @@ import { RegionalService } from "@/types/regional.types";
import { AddRegionalAgentDialog } from "./AddRegionalAgentDialog"; import { AddRegionalAgentDialog } from "./AddRegionalAgentDialog";
import { RegionalAgentCard } from "./RegionalAgentCard"; import { RegionalAgentCard } from "./RegionalAgentCard";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { useLanguage } from "@/contexts/LanguageContext";
export const RegionalMonitoringContent = () => { export const RegionalMonitoringContent = () => {
const { t } = useLanguage();
const [addDialogOpen, setAddDialogOpen] = useState(false); const [addDialogOpen, setAddDialogOpen] = useState(false);
const { toast } = useToast(); const { toast } = useToast();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
@@ -26,8 +24,8 @@ export const RegionalMonitoringContent = () => {
const handleAgentAdded = () => { const handleAgentAdded = () => {
queryClient.invalidateQueries({ queryKey: ['regional-services'] }); queryClient.invalidateQueries({ queryKey: ['regional-services'] });
toast({ toast({
title: t('regionalAgentAdded'), title: "Regional Agent Added",
description: t('regionalAgentAddedDesc'), description: "The regional monitoring agent has been successfully configured.",
}); });
}; };
@@ -36,13 +34,13 @@ export const RegionalMonitoringContent = () => {
await regionalService.deleteRegionalService(id); await regionalService.deleteRegionalService(id);
queryClient.invalidateQueries({ queryKey: ['regional-services'] }); queryClient.invalidateQueries({ queryKey: ['regional-services'] });
toast({ toast({
title: t('agentRemoved'), title: "Agent Removed",
description: t('agentRemovedDesc'), description: "The regional monitoring agent has been removed.",
}); });
} catch (error) { } catch (error) {
toast({ toast({
title: t('error'), title: "Error",
description: t('failedToRemoveAgent'), description: "Failed to remove the regional monitoring agent.",
variant: "destructive", variant: "destructive",
}); });
} }
@@ -55,14 +53,14 @@ export const RegionalMonitoringContent = () => {
<div className="p-6 space-y-6"> <div className="p-6 space-y-6">
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
<div> <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"> <p className="text-muted-foreground">
{t('descriptRegionPage')} Manage distributed monitoring agents across different regions
</p> </p>
</div> </div>
<Button onClick={() => setAddDialogOpen(true)}> <Button onClick={() => setAddDialogOpen(true)}>
<Plus className="mr-2 h-4 w-4" /> <Plus className="mr-2 h-4 w-4" />
{t('addRegionalAgent')} Add Regional Agent
</Button> </Button>
</div> </div>
@@ -70,39 +68,39 @@ export const RegionalMonitoringContent = () => {
<div className="grid grid-cols-1 md:grid-cols-3 gap-6"> <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<Card> <Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2"> <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" /> <MapPin className="h-4 w-4 text-muted-foreground" />
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="text-2xl font-bold">{totalAgents}</div> <div className="text-2xl font-bold">{totalAgents}</div>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
{t('regionalMonitoringAgents')} Regional monitoring agents
</p> </p>
</CardContent> </CardContent>
</Card> </Card>
<Card> <Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2"> <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" /> <Wifi className="h-4 w-4 text-green-600" />
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="text-2xl font-bold text-green-600">{onlineAgents}</div> <div className="text-2xl font-bold text-green-600">{onlineAgents}</div>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
{t('currentlyConnected')} Currently connected
</p> </p>
</CardContent> </CardContent>
</Card> </Card>
<Card> <Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2"> <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" /> <WifiOff className="h-4 w-4 text-red-600" />
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="text-2xl font-bold text-red-600">{totalAgents - onlineAgents}</div> <div className="text-2xl font-bold text-red-600">{totalAgents - onlineAgents}</div>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
{t('disconnectedAgents')} Disconnected agents
</p> </p>
</CardContent> </CardContent>
</Card> </Card>
@@ -110,7 +108,7 @@ export const RegionalMonitoringContent = () => {
{/* Agents List */} {/* Agents List */}
<div className="space-y-4"> <div className="space-y-4">
<h2 className="text-xl font-semibold">{t('regionalAgents')}</h2> <h2 className="text-xl font-semibold">Regional Agents</h2>
{isLoading ? ( {isLoading ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
@@ -133,13 +131,13 @@ export const RegionalMonitoringContent = () => {
<Card> <Card>
<CardContent className="flex flex-col items-center justify-center py-12"> <CardContent className="flex flex-col items-center justify-center py-12">
<MapPin className="h-12 w-12 text-muted-foreground mb-4" /> <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"> <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> </p>
<Button onClick={() => setAddDialogOpen(true)}> <Button onClick={() => setAddDialogOpen(true)}>
<Plus className="mr-2 h-4 w-4" /> <Plus className="mr-2 h-4 w-4" />
{t('addFirstAgent')} Add First Agent
</Button> </Button>
</CardContent> </CardContent>
</Card> </Card>
@@ -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>
);
};
@@ -25,20 +25,19 @@ export const IncidentDetailContent = ({
onClose, onClose,
assignedUser assignedUser
}: IncidentDetailContentProps) => { }: IncidentDetailContentProps) => {
// Fetch assigned user details if none was provided; prefer server field // Fetch assigned user details if one wasn't provided and there's an assigned_to field
const assigneeId = incident?.assigned_users || incident?.assigned_to;
const { data: fetchedUser } = useQuery({ const { data: fetchedUser } = useQuery({
queryKey: ['user', assigneeId], queryKey: ['user', incident?.assigned_to],
queryFn: async () => { queryFn: async () => {
if (!assigneeId) return null; if (!incident?.assigned_to) return null;
try { try {
return await userService.getUser(assigneeId); return await userService.getUser(incident.assigned_to);
} catch (error) { } catch (error) {
console.error("Failed to fetch assigned user:", error); console.error("Failed to fetch assigned user:", error);
return null; return null;
} }
}, },
enabled: !!assigneeId && !assignedUser, enabled: !!incident?.assigned_to && !assignedUser,
staleTime: 300000 // Cache for 5 minutes staleTime: 300000 // Cache for 5 minutes
}); });
@@ -17,7 +17,7 @@ export const IncidentDetailDialog = ({
onOpenChange, onOpenChange,
incident incident
}: IncidentDetailDialogProps) => { }: IncidentDetailDialogProps) => {
// Fetch user data for assigned field (prefer assigned_users, fallback to assigned_to) // Fetch user data for assigned_to field
const { data: users = [] } = useQuery({ const { data: users = [] } = useQuery({
queryKey: ['users'], queryKey: ['users'],
queryFn: async () => { queryFn: async () => {
@@ -25,12 +25,12 @@ export const IncidentDetailDialog = ({
return Array.isArray(usersList) ? usersList : []; return Array.isArray(usersList) ? usersList : [];
}, },
staleTime: 300000, // Cache for 5 minutes staleTime: 300000, // Cache for 5 minutes
enabled: !!(incident?.assigned_users || incident?.assigned_to) && open // Only run query if there's an assigned value and dialog is open enabled: !!incident?.assigned_to && open // Only run query if there's an assigned_to value and dialog is open
}); });
// Find the assigned user (prefer assigned_users, fallback to assigned_to) // Find the assigned user
const assignedUser = (incident?.assigned_users || incident?.assigned_to) const assignedUser = incident?.assigned_to
? users.find(user => user.id === (incident?.assigned_users || incident?.assigned_to)) ? users.find(user => user.id === incident.assigned_to)
: null; : null;
if (!incident) return null; if (!incident) return null;
@@ -23,19 +23,19 @@ export {
// Legacy component - keeping this for backward compatibility with other imports // Legacy component - keeping this for backward compatibility with other imports
export const IncidentDetailSections = ({ incident }: { incident: IncidentItem | null }) => { export const IncidentDetailSections = ({ incident }: { incident: IncidentItem | null }) => {
// Fetch assigned user details if there's an assigned field (prefer assigned_users, fallback to assigned_to) // Fetch assigned user details if there's an assigned_to field
const { data: assignedUser } = useQuery({ const { data: assignedUser } = useQuery({
queryKey: ['user', incident?.assigned_users || incident?.assigned_to], queryKey: ['user', incident?.assigned_to],
queryFn: async () => { queryFn: async () => {
if (!(incident?.assigned_users || incident?.assigned_to)) return null; if (!incident?.assigned_to) return null;
try { try {
return await userService.getUser(incident?.assigned_users || incident?.assigned_to); return await userService.getUser(incident.assigned_to);
} catch (error) { } catch (error) {
console.error("Failed to fetch assigned user:", error); console.error("Failed to fetch assigned user:", error);
return null; return null;
} }
}, },
enabled: !!(incident?.assigned_users || incident?.assigned_to), enabled: !!incident?.assigned_to,
staleTime: 300000 // Cache for 5 minutes staleTime: 300000 // Cache for 5 minutes
}); });
@@ -31,8 +31,8 @@ export const AssignmentSection: React.FC<AssignmentSectionProps> = ({ incident,
</Avatar> </Avatar>
<span>{assignedUser.full_name || assignedUser.username}</span> <span>{assignedUser.full_name || assignedUser.username}</span>
</div> </div>
) : (incident.assigned_users || incident.assigned_to) ? ( ) : incident.assigned_to ? (
<span>{incident.assigned_users || incident.assigned_to}</span> <span>{incident.assigned_to}</span>
) : ( ) : (
<span className="text-muted-foreground italic">{t('unassigned')}</span> <span className="text-muted-foreground italic">{t('unassigned')}</span>
)} )}
@@ -50,8 +50,8 @@ export const BasicInfoSection: React.FC<BasicInfoSectionProps> = ({ incident, as
</Avatar> </Avatar>
<span>{assignedUser.full_name || assignedUser.username}</span> <span>{assignedUser.full_name || assignedUser.username}</span>
</div> </div>
) : (incident.assigned_users || incident.assigned_to) ? ( ) : incident.assigned_to ? (
<span>{incident.assigned_users || incident.assigned_to}</span> <span>{incident.assigned_to}</span>
) : ( ) : (
<span className="text-muted-foreground italic">{t('unassigned')}</span> <span className="text-muted-foreground italic">{t('unassigned')}</span>
)} )}
@@ -68,7 +68,7 @@ export const IncidentBasicFields: React.FC = () => {
const selectedUser = users.find(user => user.id === form.getValues('assigned_to')); const selectedUser = users.find(user => user.id === form.getValues('assigned_to'));
// Function to get user initials from name // Function to get user initials from name
const getUserInitials = (user: { full_name?: string; username: string }): string => { const getUserInitials = (user: any): string => {
if (user.full_name) { if (user.full_name) {
const nameParts = user.full_name.split(' '); const nameParts = user.full_name.split(' ');
if (nameParts.length > 1) { if (nameParts.length > 1) {
@@ -25,7 +25,7 @@ export const useIncidentEditForm = (
impact: (incident.impact?.toLowerCase() || 'minor') as any, impact: (incident.impact?.toLowerCase() || 'minor') as any,
priority: (incident.priority?.toLowerCase() || 'medium') as any, priority: (incident.priority?.toLowerCase() || 'medium') as any,
service_id: incident.service_id || '', service_id: incident.service_id || '',
assigned_to: incident.assigned_users || incident.assigned_to || '', assigned_to: incident.assigned_to || '',
root_cause: incident.root_cause || '', root_cause: incident.root_cause || '',
resolution_steps: incident.resolution_steps || '', resolution_steps: incident.resolution_steps || '',
lessons_learned: incident.lessons_learned || '', lessons_learned: incident.lessons_learned || '',
@@ -45,15 +45,12 @@ export const useIncidentEditForm = (
impact: data.impact, impact: data.impact,
priority: data.priority, priority: data.priority,
service_id: data.service_id, service_id: data.service_id,
...(data.assigned_to assigned_to: data.assigned_to, // This is the user ID from the form
? { assigned_to: data.assigned_to, assigned_users: data.assigned_to }
: {}),
root_cause: data.root_cause, root_cause: data.root_cause,
resolution_steps: data.resolution_steps, resolution_steps: data.resolution_steps,
lessons_learned: data.lessons_learned, lessons_learned: data.lessons_learned,
}); });
toast({ toast({
title: t('incidentUpdated'), title: t('incidentUpdated'),
description: t('incidentUpdatedDesc'), description: t('incidentUpdatedDesc'),
@@ -57,7 +57,6 @@ export const useIncidentForm = (onSuccess: () => void, onClose: () => void) => {
priority: data.priority, priority: data.priority,
service_id: data.service_id, service_id: data.service_id,
assigned_to: data.assigned_to, assigned_to: data.assigned_to,
assigned_users: data.assigned_to, // map to server field
root_cause: data.root_cause, root_cause: data.root_cause,
resolution_steps: data.resolution_steps, resolution_steps: data.resolution_steps,
lessons_learned: data.lessons_learned, lessons_learned: data.lessons_learned,
@@ -86,7 +86,7 @@ export const IncidentTableRow = memo(({
</Badge> </Badge>
</TableCell> </TableCell>
<TableCell> <TableCell>
<AssignedUserCell userId={localItem.assigned_users || localItem.assigned_to} /> <AssignedUserCell userId={localItem.assigned_to} />
</TableCell> </TableCell>
<TableCell className="text-right" onClick={(e) => e.stopPropagation()}> <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
<div className="flex justify-end items-center space-x-2"> <div className="flex justify-end items-center space-x-2">
@@ -16,7 +16,6 @@ import { ServerAgentConfigForm } from "./ServerAgentConfigForm";
import { OneClickInstallTab } from "./OneClickInstallTab"; import { OneClickInstallTab } from "./OneClickInstallTab";
import { DockerOneClickTab } from "./DockerOneClickTab"; import { DockerOneClickTab } from "./DockerOneClickTab";
import { ManualInstallTab } from "./ManualInstallTab"; import { ManualInstallTab } from "./ManualInstallTab";
import { useLanguage } from "@/contexts/LanguageContext";
interface AddServerAgentDialogProps { interface AddServerAgentDialogProps {
open: boolean; open: boolean;
@@ -29,13 +28,15 @@ export const AddServerAgentDialog: React.FC<AddServerAgentDialogProps> = ({
onOpenChange, onOpenChange,
onAgentAdded, onAgentAdded,
}) => { }) => {
const { t } = useLanguage();
const { toast } = useToast(); const { toast } = useToast();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
const [activeTab, setActiveTab] = useState("configure"); const [activeTab, setActiveTab] = useState("configure");
// Get current PocketBase URL
const currentPocketBaseUrl = getCurrentEndpoint(); const currentPocketBaseUrl = getCurrentEndpoint();
// Form state
const [formData, setFormData] = useState({ const [formData, setFormData] = useState({
serverName: "", serverName: "",
description: "", description: "",
@@ -46,46 +47,23 @@ export const AddServerAgentDialog: React.FC<AddServerAgentDialogProps> = ({
notificationEnabled: true, notificationEnabled: true,
}); });
const generateNewCredentials = () => ({ // Generated server token and agent ID
serverToken: `srv_${Math.random().toString(36).substring(2, 15)}${Math.random().toString(36).substring(2, 15)}`, const [serverToken] = useState(() =>
serverId: `agent_${Math.random().toString(36).substring(2, 15)}${Math.random().toString(36).substring(2, 15)}`
});
const [serverToken, setServerToken] = useState(() =>
`srv_${Math.random().toString(36).substring(2, 15)}${Math.random().toString(36).substring(2, 15)}` `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)}` `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) => { const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
if (isSubmitting) return; if (isSubmitting) return;
if (!formData.serverName || !formData.osType) { if (!formData.serverName || !formData.osType) {
toast({ toast({
title: t('validationError'), title: "Validation Error",
description: t('fillRequiredFields'), description: "Please fill in all required fields.",
variant: "destructive", variant: "destructive",
}); });
return; return;
@@ -94,18 +72,22 @@ export const AddServerAgentDialog: React.FC<AddServerAgentDialogProps> = ({
setIsSubmitting(true); setIsSubmitting(true);
try { try {
// Here you would typically create the server monitoring configuration
// For now, we'll simulate the process
await new Promise(resolve => setTimeout(resolve, 1500)); await new Promise(resolve => setTimeout(resolve, 1500));
toast({ toast({
title: t('serverAgentCreated'), title: "Server Agent Created",
description: t('serverAgentCreatedDesc').replace('{name}', formData.serverName), description: `${formData.serverName} monitoring agent has been configured successfully.`,
}); });
// Switch to one-click install tab after successful creation
setActiveTab("one-click"); setActiveTab("one-click");
onAgentAdded(); onAgentAdded();
} catch (error) { } catch (error) {
toast({ toast({
title: t('error'), title: "Error",
description: t('failedToCreateAgent'), description: "Failed to create server monitoring agent.",
variant: "destructive", variant: "destructive",
}); });
} finally { } finally {
@@ -114,6 +96,17 @@ export const AddServerAgentDialog: React.FC<AddServerAgentDialogProps> = ({
}; };
const handleDialogClose = () => { 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); onOpenChange(false);
}; };
@@ -123,19 +116,19 @@ export const AddServerAgentDialog: React.FC<AddServerAgentDialogProps> = ({
<DialogHeader> <DialogHeader>
<DialogTitle className="flex items-center gap-2"> <DialogTitle className="flex items-center gap-2">
<Server className="h-5 w-5" /> <Server className="h-5 w-5" />
{t('addServerMonitoringAgent')} Add Server Monitoring Agent
</DialogTitle> </DialogTitle>
<DialogDescription> <DialogDescription>
{t('configureAgentDesc')} Configure a new server monitoring agent to track system metrics and performance.
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full"> <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
<TabsList className="grid w-full grid-cols-4"> <TabsList className="grid w-full grid-cols-4">
<TabsTrigger value="configure">{t('configureAgent')}</TabsTrigger> <TabsTrigger value="configure">Configure Agent</TabsTrigger>
<TabsTrigger value="one-click">{t('oneClickInstall')}</TabsTrigger> <TabsTrigger value="one-click">One-Click Install</TabsTrigger>
<TabsTrigger value="docker-one-click">{t('dockerOneClick')}</TabsTrigger> <TabsTrigger value="docker-one-click">Docker One-Click</TabsTrigger>
<TabsTrigger value="manual">{t('manualInstallation')}</TabsTrigger> <TabsTrigger value="manual">Manual Installation</TabsTrigger>
</TabsList> </TabsList>
<TabsContent value="configure" className="space-y-6"> <TabsContent value="configure" className="space-y-6">
@@ -5,7 +5,6 @@ import { Label } from "@/components/ui/label";
import { Copy, Download, Container } from "lucide-react"; import { Copy, Download, Container } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { copyToClipboard } from "@/utils/copyUtils"; import { copyToClipboard } from "@/utils/copyUtils";
import { useLanguage } from "@/contexts/LanguageContext";
interface DockerOneClickTabProps { interface DockerOneClickTabProps {
serverToken: string; serverToken: string;
@@ -27,7 +26,6 @@ export const DockerOneClickTab: React.FC<DockerOneClickTabProps> = ({
serverId, serverId,
onDialogClose, onDialogClose,
}) => { }) => {
const { t } = useLanguage();
const getDockerOneClickCommand = () => { const getDockerOneClickCommand = () => {
const scriptUrl = "https://cdn.checkcle.io/scripts/server-docker-agent.sh"; const scriptUrl = "https://cdn.checkcle.io/scripts/server-docker-agent.sh";
@@ -88,15 +86,15 @@ sudo -E bash ./server-docker-agent.sh`;
<CardHeader> <CardHeader>
<CardTitle className="flex items-center gap-2 text-blue-700 dark:text-blue-400"> <CardTitle className="flex items-center gap-2 text-blue-700 dark:text-blue-400">
<Container className="h-5 w-5" /> <Container className="h-5 w-5" />
{t('dockerOneClickTitle')} Docker One-Click Install
</CardTitle> </CardTitle>
<CardDescription className="text-blue-600 dark:text-blue-300"> <CardDescription className="text-blue-600 dark:text-blue-300">
{t('dockerOneClickDesc')} Automated Docker container installation with system monitoring capabilities
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<div className="space-y-2"> <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"> <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"> <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> <code>{getDockerOneClickCommand()}</code>
@@ -109,18 +107,18 @@ sudo -E bash ./server-docker-agent.sh`;
onClick={handleCopyOneClickCommand} onClick={handleCopyOneClickCommand}
> >
<Copy className="h-4 w-4 mr-1" /> <Copy className="h-4 w-4 mr-1" />
{t('copy')} Copy
</Button> </Button>
</div> </div>
</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"> <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"> <ol className="list-decimal list-inside space-y-1 text-xs">
<li>{t('dockerScriptStep1')}</li> <li>Download and setup the Docker monitoring agent</li>
<li>{t('dockerScriptStep2')}</li> <li>Configure all required environment variables</li>
<li>{t('dockerScriptStep3')}</li> <li>Start the container with proper system access</li>
<li>{t('dockerScriptStep4')}</li> <li>Setup monitoring data persistence</li>
</ol> </ol>
</div> </div>
</CardContent> </CardContent>
@@ -131,15 +129,15 @@ sudo -E bash ./server-docker-agent.sh`;
<CardHeader> <CardHeader>
<CardTitle className="flex items-center gap-2"> <CardTitle className="flex items-center gap-2">
<Container className="h-5 w-5" /> <Container className="h-5 w-5" />
{t('directDockerTitle')} Direct Docker Run Command
</CardTitle> </CardTitle>
<CardDescription> <CardDescription>
{t('directDockerDesc')} If you prefer to run the Docker container directly without the script
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<div className="space-y-2"> <div className="space-y-2">
<Label>{t('dockerRunCommand')}</Label> <Label>Docker Run Command</Label>
<div className="relative"> <div className="relative">
<pre className="bg-muted border p-4 rounded-md text-sm overflow-x-auto whitespace-pre-wrap break-all"> <pre className="bg-muted border p-4 rounded-md text-sm overflow-x-auto whitespace-pre-wrap break-all">
<code>{getDirectDockerCommand()}</code> <code>{getDirectDockerCommand()}</code>
@@ -152,17 +150,17 @@ sudo -E bash ./server-docker-agent.sh`;
onClick={handleCopyDockerCommand} onClick={handleCopyDockerCommand}
> >
<Copy className="h-4 w-4 mr-1" /> <Copy className="h-4 w-4 mr-1" />
{t('copy')} Copy
</Button> </Button>
</div> </div>
</div> </div>
<div className="text-sm text-muted-foreground bg-muted/50 border p-3 rounded-md"> <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"> <ol className="list-decimal list-inside space-y-1 text-xs">
<li>{t('dockerPrereqStep1')}</li> <li>Docker must be installed and running</li>
<li>{t('dockerPrereqStep2')}</li> <li>The operacle/checkcle-server-agent image must be available</li>
<li>{t('dockerPrereqStep3')}</li> <li>Run as root or with sudo privileges</li>
</ol> </ol>
</div> </div>
</CardContent> </CardContent>
@@ -170,7 +168,7 @@ sudo -E bash ./server-docker-agent.sh`;
<div className="flex justify-end pt-4"> <div className="flex justify-end pt-4">
<Button onClick={onDialogClose}> <Button onClick={onDialogClose}>
{t('done')} Done
</Button> </Button>
</div> </div>
</div> </div>
@@ -14,7 +14,6 @@ import { RefreshCw, X } from "lucide-react";
import { alertConfigService, AlertConfiguration } from "@/services/alertConfigService"; import { alertConfigService, AlertConfiguration } from "@/services/alertConfigService";
import { templateService, ServerNotificationTemplate } from "@/services/templateService"; import { templateService, ServerNotificationTemplate } from "@/services/templateService";
import { serverThresholdService, ServerThreshold } from "@/services/serverThresholdService"; import { serverThresholdService, ServerThreshold } from "@/services/serverThresholdService";
import { useLanguage } from "@/contexts/LanguageContext";
interface EditServerDialogProps { interface EditServerDialogProps {
server: Server | null; server: Server | null;
@@ -47,7 +46,6 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
onOpenChange, onOpenChange,
onServerUpdated, onServerUpdated,
}) => { }) => {
const { t } = useLanguage();
const [formData, setFormData] = useState<ServerFormData>({ const [formData, setFormData] = useState<ServerFormData>({
name: "", name: "",
check_interval: 60, 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 // Handle the API response format with proper field names and type conversion
setThresholdFormData({ setThresholdFormData({
cpu_threshold: parseInt(String(existingThreshold.cpu_threshold)) || 80, 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, disk_threshold: parseInt(String(existingThreshold.disk_threshold)) || 80,
network_threshold: parseInt(String(existingThreshold.network_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 // Handle the API response format with proper field names and type conversion
setThresholdFormData({ setThresholdFormData({
cpu_threshold: parseInt(String(threshold.cpu_threshold)) || 80, 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, disk_threshold: parseInt(String(threshold.disk_threshold)) || 80,
network_threshold: parseInt(String(threshold.network_threshold)) || 80, network_threshold: parseInt(String(threshold.network_threshold)) || 80,
}); });
@@ -167,8 +165,8 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
} catch (error) { } catch (error) {
toast({ toast({
variant: "destructive", variant: "destructive",
title: t('error', 'instance'), title: "Error",
description: t('failedToLoadChannels', 'instance'), description: "Failed to load notification channels",
}); });
} finally { } finally {
setLoadingAlertConfigs(false); setLoadingAlertConfigs(false);
@@ -184,8 +182,8 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
} catch (error) { } catch (error) {
toast({ toast({
variant: "destructive", variant: "destructive",
title: t('error', 'instance'), title: "Error",
description: t('failedToLoadTemplates', 'instance'), description: "Failed to load templates",
}); });
} finally { } finally {
setLoadingTemplates(false); setLoadingTemplates(false);
@@ -200,8 +198,8 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
} catch (error) { } catch (error) {
toast({ toast({
variant: "destructive", variant: "destructive",
title: t('error', 'instance'), title: "Error",
description: t('failedToLoadThresholds', 'instance'), description: "Failed to load server thresholds",
}); });
} finally { } finally {
setLoadingThresholds(false); setLoadingThresholds(false);
@@ -276,15 +274,15 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
} catch (error) { } catch (error) {
toast({ toast({
variant: "destructive", variant: "destructive",
title: t('warning', 'instance'), title: "Warning",
description: t('serverUpdatedButThresholdFailed', 'instance'), description: "Server updated but failed to update threshold values.",
}); });
} }
} }
toast({ toast({
title: t('serverUpdated', 'instance'), title: "Server updated",
description: t('serverUpdatedDesc', 'instance', { name: formData.name }), description: `${formData.name} has been updated successfully.`,
}); });
onServerUpdated(); onServerUpdated();
@@ -293,8 +291,8 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
} catch (error) { } catch (error) {
toast({ toast({
variant: "destructive", variant: "destructive",
title: t('error', 'instance'), title: "Error",
description: t('failedToUpdateServer', 'instance'), description: "Failed to update server. Please try again.",
}); });
} finally { } finally {
setIsSubmitting(false); setIsSubmitting(false);
@@ -325,62 +323,62 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[700px] max-h-[80vh] overflow-y-auto"> <DialogContent className="sm:max-w-[700px] max-h-[80vh] overflow-y-auto">
<DialogHeader> <DialogHeader>
<DialogTitle>{t('editServerConfiguration', 'instance')}</DialogTitle> <DialogTitle>Edit Server Configuration</DialogTitle>
</DialogHeader> </DialogHeader>
<form onSubmit={handleSubmit} className="space-y-6"> <form onSubmit={handleSubmit} className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="serverName">{t('serverNameLabel', 'instance')}</Label> <Label htmlFor="serverName">Server Name *</Label>
<Input <Input
id="serverName" id="serverName"
value={formData.name} value={formData.name}
onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))} onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
placeholder={t('serverNamePlaceholder', 'instance')} placeholder="Enter server name"
required required
/> />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="checkInterval">{t('checkIntervalLabel', 'instance')}</Label> <Label htmlFor="checkInterval">Check Interval</Label>
<Select <Select
value={formData.check_interval.toString()} value={formData.check_interval.toString()}
onValueChange={(value) => setFormData(prev => ({ ...prev, check_interval: parseInt(value) }))} onValueChange={(value) => setFormData(prev => ({ ...prev, check_interval: parseInt(value) }))}
> >
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder={t('selectInterval', 'instance')} /> <SelectValue placeholder="Select interval" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="30">{t('interval30s', 'instance')}</SelectItem> <SelectItem value="30">30 seconds</SelectItem>
<SelectItem value="60">{t('interval1m', 'instance')}</SelectItem> <SelectItem value="60">1 minute</SelectItem>
<SelectItem value="120">{t('interval2m', 'instance')}</SelectItem> <SelectItem value="120">2 minutes</SelectItem>
<SelectItem value="300">{t('interval5m', 'instance')}</SelectItem> <SelectItem value="300">5 minutes</SelectItem>
<SelectItem value="600">{t('interval10m', 'instance')}</SelectItem> <SelectItem value="600">10 minutes</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="maxRetries">{t('maxRetriesLabel', 'instance')}</Label> <Label htmlFor="maxRetries">Max Retries</Label>
<Select <Select
value={formData.max_retries.toString()} value={formData.max_retries.toString()}
onValueChange={(value) => setFormData(prev => ({ ...prev, max_retries: parseInt(value) }))} onValueChange={(value) => setFormData(prev => ({ ...prev, max_retries: parseInt(value) }))}
> >
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder={t('selectMaxRetries', 'instance')} /> <SelectValue placeholder="Select max retries" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="1">{t('retry1', 'instance')}</SelectItem> <SelectItem value="1">1 retry</SelectItem>
<SelectItem value="2">{t('retry2', 'instance')}</SelectItem> <SelectItem value="2">2 retries</SelectItem>
<SelectItem value="3">{t('retry3', 'instance')}</SelectItem> <SelectItem value="3">3 retries</SelectItem>
<SelectItem value="5">{t('retry5', 'instance')}</SelectItem> <SelectItem value="5">5 retries</SelectItem>
<SelectItem value="10">{t('retry10', 'instance')}</SelectItem> <SelectItem value="10">10 retries</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
<div className="space-y-2"> <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"> <div className="flex items-center space-x-2">
<Switch <Switch
id="dockerMonitoring" id="dockerMonitoring"
@@ -391,7 +389,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
}))} }))}
/> />
<Label htmlFor="dockerMonitoring" className="text-sm text-muted-foreground"> <Label htmlFor="dockerMonitoring" className="text-sm text-muted-foreground">
{formData.docker_monitoring ? t('enabled', 'instance') : t('disabled', 'instance')} {formData.docker_monitoring ? "Enabled" : "Disabled"}
</Label> </Label>
</div> </div>
</div> </div>
@@ -409,22 +407,22 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
// Remove the automatic clearing of notification_channels, threshold_id, and template_id // 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> </div>
{/* Expanded Notification Settings */} {/* Expanded Notification Settings */}
{formData.notification_enabled && ( {formData.notification_enabled && (
<Card className="border-l-4 border-l-blue-500"> <Card className="border-l-4 border-l-blue-500">
<CardHeader> <CardHeader>
<CardTitle className="text-lg">{t('notificationSettings', 'instance')}</CardTitle> <CardTitle className="text-lg">Notification Settings</CardTitle>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
{/* Multiple Notification Channels Selection */} {/* Multiple Notification Channels Selection */}
<div className="space-y-2"> <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"> <div className="space-y-2 max-h-40 overflow-y-auto border rounded-md p-3">
{loadingAlertConfigs ? ( {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.length > 0 ? (
alertConfigs.map((config) => ( alertConfigs.map((config) => (
<div key={config.id} className="flex items-center space-x-2"> <div key={config.id} className="flex items-center space-x-2">
@@ -444,14 +442,14 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
</div> </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> </div>
{/* Selected Channels Display */} {/* Selected Channels Display */}
{formData.notification_channels.length > 0 && ( {formData.notification_channels.length > 0 && (
<div className="space-y-2"> <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"> <div className="flex flex-wrap gap-2">
{formData.notification_channels.map((channelId) => { {formData.notification_channels.map((channelId) => {
const channel = alertConfigs.find(c => c.id === channelId); const channel = alertConfigs.find(c => c.id === channelId);
@@ -480,17 +478,17 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
{/* Server Set Threshold Selection */} {/* Server Set Threshold Selection */}
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="thresholdId">{t('serverSetThreshold', 'instance')}</Label> <Label htmlFor="thresholdId">Server Set Threshold</Label>
<Select <Select
value={formData.threshold_id} value={formData.threshold_id}
onValueChange={(value) => setFormData(prev => ({ ...prev, threshold_id: value }))} onValueChange={(value) => setFormData(prev => ({ ...prev, threshold_id: value }))}
disabled={loadingThresholds} disabled={loadingThresholds}
> >
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder={loadingThresholds ? t('loadingThresholds', 'instance') : t('selectServerThreshold', 'instance')} /> <SelectValue placeholder={loadingThresholds ? "Loading thresholds..." : "Select server threshold"} />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="none">{t('noThreshold', 'instance')}</SelectItem> <SelectItem value="none">No threshold (use default)</SelectItem>
{thresholds.map((threshold) => ( {thresholds.map((threshold) => (
<SelectItem key={threshold.id} value={threshold.id}> <SelectItem key={threshold.id} value={threshold.id}>
{threshold.name} {threshold.name}
@@ -504,12 +502,12 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
{selectedThreshold && ( {selectedThreshold && (
<Card className="bg-muted/50"> <Card className="bg-muted/50">
<CardHeader> <CardHeader>
<CardTitle className="text-base">{t('thresholdDetails', 'instance')}: {selectedThreshold.name}</CardTitle> <CardTitle className="text-base">Threshold Details: {selectedThreshold.name}</CardTitle>
</CardHeader> </CardHeader>
<CardContent className="space-y-3"> <CardContent className="space-y-3">
<div className="grid grid-cols-2 gap-3 text-sm"> <div className="grid grid-cols-2 gap-3 text-sm">
<div> <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 <Input
type="number" type="number"
min="0" min="0"
@@ -523,7 +521,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
/> />
</div> </div>
<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 <Input
type="number" type="number"
min="0" min="0"
@@ -537,7 +535,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
/> />
</div> </div>
<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 <Input
type="number" type="number"
min="0" min="0"
@@ -551,7 +549,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
/> />
</div> </div>
<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 <Input
type="number" type="number"
min="0" min="0"
@@ -571,17 +569,17 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
{/* Server Template Selection */} {/* Server Template Selection */}
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="templateId">{t('serverTemplate', 'instance')}</Label> <Label htmlFor="templateId">Server Template</Label>
<Select <Select
value={formData.template_id} value={formData.template_id}
onValueChange={(value) => setFormData(prev => ({ ...prev, template_id: value }))} onValueChange={(value) => setFormData(prev => ({ ...prev, template_id: value }))}
disabled={loadingTemplates} disabled={loadingTemplates}
> >
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder={loadingTemplates ? t('loadingTemplates', 'instance') : t('selectServerTemplate', 'instance')} /> <SelectValue placeholder={loadingTemplates ? "Loading templates..." : "Select server template"} />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="none">{t('noTemplate', 'instance')}</SelectItem> <SelectItem value="none">No template (use default)</SelectItem>
{templates.map((template) => ( {templates.map((template) => (
<SelectItem key={template.id} value={template.id}> <SelectItem key={template.id} value={template.id}>
{template.name} {template.name}
@@ -595,44 +593,44 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
{selectedTemplate && ( {selectedTemplate && (
<Card className="bg-muted/50"> <Card className="bg-muted/50">
<CardHeader> <CardHeader>
<CardTitle className="text-base">{t('templateDetails', 'instance')}: {selectedTemplate.name}</CardTitle> <CardTitle className="text-base">Template Details: {selectedTemplate.name}</CardTitle>
</CardHeader> </CardHeader>
<CardContent className="space-y-3"> <CardContent className="space-y-3">
<div className="grid grid-cols-1 gap-3 text-sm"> <div className="grid grid-cols-1 gap-3 text-sm">
<div> <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"> <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> </p>
</div> </div>
<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"> <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> </p>
</div> </div>
<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"> <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> </p>
</div> </div>
<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"> <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> </p>
</div> </div>
<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"> <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> </p>
</div> </div>
<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"> <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> </p>
</div> </div>
</div> </div>
@@ -651,16 +649,16 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
onClick={handleCancel} onClick={handleCancel}
disabled={isSubmitting} disabled={isSubmitting}
> >
{t('cancel', 'instance')} Cancel
</Button> </Button>
<Button type="submit" disabled={isSubmitting}> <Button type="submit" disabled={isSubmitting}>
{isSubmitting ? ( {isSubmitting ? (
<> <>
<RefreshCw className="mr-2 h-4 w-4 animate-spin" /> <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
{t('updating', 'instance')} Updating...
</> </>
) : ( ) : (
t('updateServer', 'instance') "Update Server"
)} )}
</Button> </Button>
</div> </div>
@@ -4,7 +4,6 @@ import { Button } from "@/components/ui/button";
import { Copy, Terminal } from "lucide-react"; import { Copy, Terminal } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { copyToClipboard } from "@/utils/copyUtils"; import { copyToClipboard } from "@/utils/copyUtils";
import { useLanguage } from "@/contexts/LanguageContext";
interface ManualInstallTabProps { interface ManualInstallTabProps {
serverToken: string; serverToken: string;
@@ -25,22 +24,20 @@ export const ManualInstallTab: React.FC<ManualInstallTabProps> = ({
serverId, serverId,
onDialogClose, onDialogClose,
}) => { }) => {
const { t } = useLanguage();
const getManualInstallSteps = () => { const getManualInstallSteps = () => {
const scriptUrl = "https://cdn.checkcle.io/scripts/server-agent.sh"; const scriptUrl = "https://cdn.checkcle.io/scripts/server-agent.sh";
return [ return [
{ {
title: t('downloadScript'), title: "Download the installation script",
command: `curl -L -o server-agent.sh "${scriptUrl}"` command: `curl -L -o server-agent.sh "${scriptUrl}"`
}, },
{ {
title: t('makeExecutable'), title: "Make the script executable",
command: `chmod +x server-agent.sh` 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` 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> <CardHeader>
<CardTitle className="flex items-center gap-2"> <CardTitle className="flex items-center gap-2">
<Terminal className="h-5 w-5" /> <Terminal className="h-5 w-5" />
{t('manualInstallTitle')} Manual Installation Steps
</CardTitle> </CardTitle>
<CardDescription> <CardDescription>
{t('manualInstallDesc')} Step-by-step installation process
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<div className="space-y-2"> <div className="space-y-2">
<div className="grid grid-cols-2 gap-4 text-sm"> <div className="grid grid-cols-2 gap-4 text-sm">
<div> <div>
<span className="font-medium">{t('serverName')}:</span> {formData.serverName} <span className="font-medium">Server Name:</span> {formData.serverName}
</div> </div>
<div> <div>
<span className="font-medium">{t('agentId')}:</span> {serverId} <span className="font-medium">Agent ID:</span> {serverId}
</div> </div>
<div> <div>
<span className="font-medium">{t('osType')}:</span> {formData.osType} <span className="font-medium">OS Type:</span> {formData.osType}
</div> </div>
<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> </div>
</div> </div>
@@ -96,7 +93,7 @@ export const ManualInstallTab: React.FC<ManualInstallTabProps> = ({
onClick={() => copyToClipboard(step.command)} onClick={() => copyToClipboard(step.command)}
> >
<Copy className="h-4 w-4 mr-1" /> <Copy className="h-4 w-4 mr-1" />
{t('copy')} Copy
</Button> </Button>
</div> </div>
</div> </div>
@@ -104,22 +101,22 @@ export const ManualInstallTab: React.FC<ManualInstallTabProps> = ({
</div> </div>
<div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-md p-4"> <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"> <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>Ensure you have root/sudo access on the target server</li>
<li>{t('prereqCurl')}</li> <li>Make sure curl is installed for downloading files</li>
<li>{t('prereqInternet')}</li> <li>Internet connection required for downloading script</li>
</ul> </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"> <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> </p>
</div> </div>
<div className="flex justify-end pt-4"> <div className="flex justify-end pt-4">
<Button onClick={onDialogClose}> <Button onClick={onDialogClose}>
{t('done')} Done
</Button> </Button>
</div> </div>
</CardContent> </CardContent>
@@ -5,7 +5,6 @@ import { Label } from "@/components/ui/label";
import { Copy, Download } from "lucide-react"; import { Copy, Download } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { copyToClipboard } from "@/utils/copyUtils"; import { copyToClipboard } from "@/utils/copyUtils";
import { useLanguage } from "@/contexts/LanguageContext";
interface OneClickInstallTabProps { interface OneClickInstallTabProps {
serverToken: string; serverToken: string;
@@ -27,8 +26,6 @@ export const OneClickInstallTab: React.FC<OneClickInstallTabProps> = ({
serverId, serverId,
onDialogClose, onDialogClose,
}) => { }) => {
const { t } = useLanguage();
const getOneClickInstallCommand = () => { const getOneClickInstallCommand = () => {
const scriptUrl = "https://cdn.checkcle.io/scripts/server-agent.sh"; const scriptUrl = "https://cdn.checkcle.io/scripts/server-agent.sh";
@@ -58,15 +55,15 @@ sudo -E bash ./server-agent.sh`;
<CardHeader> <CardHeader>
<CardTitle className="flex items-center gap-2 text-green-700 dark:text-green-400"> <CardTitle className="flex items-center gap-2 text-green-700 dark:text-green-400">
<Download className="h-5 w-5" /> <Download className="h-5 w-5" />
{t('oneClickInstallTitle')} One-Click Install (Recommended)
</CardTitle> </CardTitle>
<CardDescription className="text-green-600 dark:text-green-300"> <CardDescription className="text-green-600 dark:text-green-300">
{t('oneClickInstallDesc')} Copy and paste this single command to install the monitoring agent instantly
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<div className="space-y-2"> <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"> <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"> <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> <code>{getOneClickInstallCommand()}</code>
@@ -79,23 +76,23 @@ sudo -E bash ./server-agent.sh`;
onClick={handleCopyCommand} onClick={handleCopyCommand}
> >
<Copy className="h-4 w-4 mr-1" /> <Copy className="h-4 w-4 mr-1" />
{t('copy')} Copy
</Button> </Button>
</div> </div>
</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"> <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"> <ol className="list-decimal list-inside space-y-1 text-xs">
<li>{t('sshIntoServer')}</li> <li>SSH into your target server</li>
<li>{t('pasteAndRun')}</li> <li>Paste and run the command above</li>
<li>{t('agentInstalled')}</li> <li>The agent will be installed and started automatically</li>
</ol> </ol>
</div> </div>
<div className="flex justify-end pt-4"> <div className="flex justify-end pt-4">
<Button onClick={onDialogClose}> <Button onClick={onDialogClose}>
{t('done')} Done
</Button> </Button>
</div> </div>
</CardContent> </CardContent>
@@ -7,7 +7,6 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { Copy } from "lucide-react"; import { Copy } from "lucide-react";
import { copyToClipboard } from "@/utils/copyUtils"; import { copyToClipboard } from "@/utils/copyUtils";
import { OSSelector } from "./OSSelector"; import { OSSelector } from "./OSSelector";
import { useLanguage } from "@/contexts/LanguageContext";
interface ServerAgentConfigFormProps { interface ServerAgentConfigFormProps {
formData: { formData: {
@@ -44,25 +43,23 @@ export const ServerAgentConfigForm: React.FC<ServerAgentConfigFormProps> = ({
isSubmitting, isSubmitting,
onSubmit, onSubmit,
}) => { }) => {
const { t } = useLanguage();
return ( return (
<form onSubmit={onSubmit} className="space-y-4"> <form onSubmit={onSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="serverName">{t('serverName')} *</Label> <Label htmlFor="serverName">Server Name *</Label>
<Input <Input
id="serverName" id="serverName"
placeholder={t('serverNamePlaceholder')} placeholder="e.g., web-server-01"
value={formData.serverName} value={formData.serverName}
onChange={(e) => setFormData(prev => ({ ...prev, serverName: e.target.value }))} onChange={(e) => setFormData(prev => ({ ...prev, serverName: e.target.value }))}
required 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>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="serverId">{t('serverAgentId')}</Label> <Label htmlFor="serverId">Server Agent ID</Label>
<div className="flex gap-2"> <div className="flex gap-2">
<Input <Input
id="serverId" id="serverId"
@@ -79,13 +76,13 @@ export const ServerAgentConfigForm: React.FC<ServerAgentConfigFormProps> = ({
<Copy className="h-4 w-4" /> <Copy className="h-4 w-4" />
</Button> </Button>
</div> </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> </div>
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div className="space-y-2"> <div className="space-y-2">
<Label>{t('operatingSystem')} *</Label> <Label>Operating System *</Label>
<OSSelector <OSSelector
value={formData.osType} value={formData.osType}
onValueChange={(value) => setFormData(prev => ({ ...prev, osType: value }))} 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-4">
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="checkInterval">{t('checkInterval')}</Label> <Label htmlFor="checkInterval">Check Interval</Label>
<Select <Select
value={formData.checkInterval} value={formData.checkInterval}
onValueChange={(value) => setFormData(prev => ({ ...prev, checkInterval: value }))} onValueChange={(value) => setFormData(prev => ({ ...prev, checkInterval: value }))}
> >
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder={t('selectInterval')} /> <SelectValue placeholder="Select interval" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="30">{t('interval30s')}</SelectItem> <SelectItem value="30">30 seconds</SelectItem>
<SelectItem value="60">{t('interval1m')}</SelectItem> <SelectItem value="60">1 minute</SelectItem>
<SelectItem value="120">{t('interval2m')}</SelectItem> <SelectItem value="120">2 minutes</SelectItem>
<SelectItem value="300">{t('interval5m')}</SelectItem> <SelectItem value="300">5 minutes</SelectItem>
</SelectContent> </SelectContent>
</Select> </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>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="retryAttempt">{t('retryAttempts')}</Label> <Label htmlFor="retryAttempt">Retry Attempts</Label>
<Select <Select
value={formData.retryAttempt} value={formData.retryAttempt}
onValueChange={(value) => setFormData(prev => ({ ...prev, retryAttempt: value }))} onValueChange={(value) => setFormData(prev => ({ ...prev, retryAttempt: value }))}
> >
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder={t('selectRetryAttempts')} /> <SelectValue placeholder="Select retry attempts" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="1">{t('attempt1')}</SelectItem> <SelectItem value="1">1 attempt</SelectItem>
<SelectItem value="2">{t('attempt2')}</SelectItem> <SelectItem value="2">2 attempts</SelectItem>
<SelectItem value="3">{t('attempt3')}</SelectItem> <SelectItem value="3">3 attempts</SelectItem>
<SelectItem value="5">{t('attempt5')}</SelectItem> <SelectItem value="5">5 attempts</SelectItem>
</SelectContent> </SelectContent>
</Select> </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>
<div className="space-y-2"> <div className="space-y-2">
<Label>{t('serverToken')}</Label> <Label>Server Token</Label>
<div className="flex gap-2"> <div className="flex gap-2">
<Input value={serverToken} readOnly className="font-mono text-sm bg-muted" /> <Input value={serverToken} readOnly className="font-mono text-sm bg-muted" />
<Button <Button
@@ -144,11 +141,11 @@ export const ServerAgentConfigForm: React.FC<ServerAgentConfigFormProps> = ({
<Copy className="h-4 w-4" /> <Copy className="h-4 w-4" />
</Button> </Button>
</div> </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>
<div className="space-y-2"> <div className="space-y-2">
<Label>{t('systemUrl')}</Label> <Label>System URL</Label>
<div className="flex gap-2"> <div className="flex gap-2">
<Input value={currentPocketBaseUrl} readOnly className="font-mono text-sm bg-muted" /> <Input value={currentPocketBaseUrl} readOnly className="font-mono text-sm bg-muted" />
<Button <Button
@@ -160,14 +157,14 @@ export const ServerAgentConfigForm: React.FC<ServerAgentConfigFormProps> = ({
<Copy className="h-4 w-4" /> <Copy className="h-4 w-4" />
</Button> </Button>
</div> </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>
</div> </div>
<div className="pt-4"> <div className="pt-4">
<Button type="submit" disabled={isSubmitting} className="w-full"> <Button type="submit" disabled={isSubmitting} className="w-full">
{isSubmitting ? t('creatingAgent') : t('createServerAgent')} {isSubmitting ? "Creating Agent..." : "Create Server Agent"}
</Button> </Button>
</div> </div>
</form> </form>
@@ -8,14 +8,12 @@ import { CPUChart } from "./charts/CPUChart";
import { MemoryChart } from "./charts/MemoryChart"; import { MemoryChart } from "./charts/MemoryChart";
import { DiskChart } from "./charts/DiskChart"; import { DiskChart } from "./charts/DiskChart";
import { NetworkChart } from "./charts/NetworkChart"; import { NetworkChart } from "./charts/NetworkChart";
import { useLanguage } from "@/contexts/LanguageContext";
interface ServerHistoryChartsProps { interface ServerHistoryChartsProps {
serverId: string; serverId: string;
} }
export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => { export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => {
const { t } = useLanguage();
const { const {
timeRange, timeRange,
setTimeRange, setTimeRange,
@@ -35,15 +33,15 @@ export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => {
// Show skeleton loading state for better UX // Show skeleton loading state for better UX
if (isLoading) { if (isLoading) {
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="flex items-center justify-between mb-4"> <div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<TrendingUp className="h-5 w-5" /> <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"> <div className="flex items-center gap-2 ml-2">
<Loader2 className="h-4 w-4 animate-spin" /> <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>
</div> </div>
<TimeRangeSelector value={timeRange} onChange={setTimeRange} /> <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 justify-between">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<TrendingUp className="h-5 w-5" /> <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" />} {isFetching && <Loader2 className="h-4 w-4 animate-spin ml-2" />}
</div> </div>
<TimeRangeSelector value={timeRange} onChange={setTimeRange} /> <TimeRangeSelector value={timeRange} onChange={setTimeRange} />
@@ -87,9 +85,9 @@ export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => {
<Card> <Card>
<CardContent className="flex items-center justify-center py-12"> <CardContent className="flex items-center justify-center py-12">
<div className="text-center"> <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-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> </div>
</CardContent> </CardContent>
</Card> </Card>
@@ -103,7 +101,7 @@ export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => {
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<TrendingUp className="h-5 w-5" /> <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" />} {isFetching && <Loader2 className="h-4 w-4 animate-spin ml-2" />}
</div> </div>
<TimeRangeSelector value={timeRange} onChange={setTimeRange} /> <TimeRangeSelector value={timeRange} onChange={setTimeRange} />
@@ -111,13 +109,11 @@ export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => {
<Card> <Card>
<CardContent className="flex items-center justify-center py-12"> <CardContent className="flex items-center justify-center py-12">
<div className="text-center"> <div className="text-center">
<p className="text-muted-foreground">{t("noHistoricalData", { timeRange })}</p> <p className="text-muted-foreground">No historical data available for {timeRange}</p>
<p className="text-xs mt-2">{t("rawMetricsCount", { count: metrics.length })}</p> <p className="text-xs mt-2">Raw metrics count: {metrics.length}</p>
<p className="text-xs mt-1">{t("serverIdTimeRange", { serverId, timeRange })}</p> <p className="text-xs mt-1">Server ID: {serverId} Time Range: {timeRange}</p>
<p className="text-xs mt-1 text-muted-foreground"> <p className="text-xs mt-1 text-muted-foreground">
{metrics.length > 0 {metrics.length > 0 ? 'Data exists but may be outside selected time range' : 'No metrics data found'}
? t("dataExistsOutsideRange")
: t("noMetricsDataFound")}
</p> </p>
</div> </div>
</CardContent> </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 flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<TrendingUp className="h-5 w-5" /> <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"> <span className="text-xs text-muted-foreground">
({chartData.length} data points {timeRange}) ({chartData.length} data points {timeRange})
{isFetching && ( {isFetching && (
<span className="inline-flex items-center gap-1 ml-2"> <span className="inline-flex items-center gap-1 ml-2">
<Loader2 className="h-3 w-3 animate-spin" /> <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>
)} )}
</span> </span>
@@ -3,19 +3,17 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Server, Activity, AlertTriangle, Power } from "lucide-react"; import { Server, Activity, AlertTriangle, Power } from "lucide-react";
import { ServerStats } from "@/types/server.types"; import { ServerStats } from "@/types/server.types";
import { useTheme } from "@/contexts/ThemeContext"; import { useTheme } from "@/contexts/ThemeContext";
import { useLanguage } from "@/contexts/LanguageContext";
interface ServerStatsCardsProps { interface ServerStatsCardsProps {
stats: ServerStats; stats: ServerStats;
} }
export const ServerStatsCards = ({ stats }: ServerStatsCardsProps) => { export const ServerStatsCards = ({ stats }: ServerStatsCardsProps) => {
const { t } = useLanguage();
const { theme } = useTheme(); const { theme } = useTheme();
const cards = [ const cards = [
{ {
title: t('totalServers', 'instance'), title: "TOTAL SERVERS",
value: stats.total, value: stats.total,
icon: Server, icon: Server,
gradient: theme === 'dark' gradient: theme === 'dark'
@@ -23,7 +21,7 @@ export const ServerStatsCards = ({ stats }: ServerStatsCardsProps) => {
: "linear-gradient(135deg, rgba(65, 59, 55, 0.8) 0%, #a0522d 100%)" : "linear-gradient(135deg, rgba(65, 59, 55, 0.8) 0%, #a0522d 100%)"
}, },
{ {
title: t('onlineServers', 'instance'), title: "ONLINE SERVERS",
value: stats.online, value: stats.online,
icon: Activity, icon: Activity,
gradient: theme === 'dark' gradient: theme === 'dark'
@@ -31,7 +29,7 @@ export const ServerStatsCards = ({ stats }: ServerStatsCardsProps) => {
: "linear-gradient(135deg, rgba(65, 59, 55, 0.8) 0%, #66bb6a 100%)" : "linear-gradient(135deg, rgba(65, 59, 55, 0.8) 0%, #66bb6a 100%)"
}, },
{ {
title: t('offlineServers', 'instance'), title: "OFFLINE SERVERS",
value: stats.offline, value: stats.offline,
icon: Power, icon: Power,
gradient: theme === 'dark' gradient: theme === 'dark'
@@ -39,7 +37,7 @@ export const ServerStatsCards = ({ stats }: ServerStatsCardsProps) => {
: "linear-gradient(135deg, rgba(65, 59, 55, 0.8) 0%, #ef5350 100%)" : "linear-gradient(135deg, rgba(65, 59, 55, 0.8) 0%, #ef5350 100%)"
}, },
{ {
title: t('warningServers', 'instance'), title: "WARNING SERVERS",
value: stats.warning, value: stats.warning,
icon: AlertTriangle, icon: AlertTriangle,
gradient: theme === 'dark' gradient: theme === 'dark'
@@ -3,7 +3,6 @@ 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 { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
@@ -17,7 +16,6 @@ import { serverService } from "@/services/serverService";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { pb } from "@/lib/pocketbase"; import { pb } from "@/lib/pocketbase";
import { useTheme } from "@/contexts/ThemeContext"; import { useTheme } from "@/contexts/ThemeContext";
import { useLanguage } from "@/contexts/LanguageContext";
interface ServerTableProps { interface ServerTableProps {
servers: Server[]; servers: Server[];
@@ -26,7 +24,6 @@ interface ServerTableProps {
} }
export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps) => { export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps) => {
const { t } = useLanguage();
const { theme } = useTheme(); const { theme } = useTheme();
const [searchTerm, setSearchTerm] = useState(""); const [searchTerm, setSearchTerm] = useState("");
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
@@ -34,9 +31,6 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
const [selectedServer, setSelectedServer] = useState<Server | null>(null); const [selectedServer, setSelectedServer] = useState<Server | null>(null);
const [isDeleting, setIsDeleting] = useState(false); const [isDeleting, setIsDeleting] = useState(false);
const [pausingServers, setPausingServers] = useState<Set<string>>(new Set()); 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 navigate = useNavigate();
const { toast } = useToast(); const { toast } = useToast();
@@ -46,25 +40,6 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
server.ip_address.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) => { const handleViewDetails = (serverId: string) => {
navigate(`/server-detail/${serverId}`); navigate(`/server-detail/${serverId}`);
}; };
@@ -93,8 +68,8 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
await pb.collection('servers').update(serverId, updateData); await pb.collection('servers').update(serverId, updateData);
toast({ toast({
title: isPaused ? t('serverResumed') : t('serverPaused'), title: isPaused ? "Server resumed" : "Server paused",
description: isPaused ? t('monitoringResumed', { name: server.name }) : t('monitoringPaused', { name: server.name }), description: `Monitoring ${isPaused ? 'resumed' : 'paused'} for ${server.name}`,
}); });
// console.log(`${isPaused ? 'Resume' : 'Pause'} server monitoring: ${serverId}`); // console.log(`${isPaused ? 'Resume' : 'Pause'} server monitoring: ${serverId}`);
@@ -106,8 +81,8 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
// console.error('Error updating server status:', error); // console.error('Error updating server status:', error);
toast({ toast({
variant: "destructive", variant: "destructive",
title: t('error'), title: "Error",
description: isPaused ? t('resumeServerError') : t('pauseServerError'), description: `Failed to ${isPaused ? 'resume' : 'pause'} server monitoring. Please try again.`,
}); });
} finally { } finally {
setPausingServers(prev => { setPausingServers(prev => {
@@ -161,33 +136,6 @@ 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 = ({ const CustomProgressBar = ({
value, value,
label, label,
@@ -256,12 +204,12 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
return ( return (
<Card className="flex-1 flex flex-col"> <Card className="flex-1 flex flex-col">
<CardHeader className="flex-shrink-0"> <CardHeader className="flex-shrink-0">
<CardTitle>{t('servers')}</CardTitle> <CardTitle>Servers</CardTitle>
</CardHeader> </CardHeader>
<CardContent className="flex-1 flex items-center justify-center"> <CardContent className="flex-1 flex items-center justify-center">
<div className="flex items-center justify-center h-32"> <div className="flex items-center justify-center h-32">
<RefreshCw className="h-6 w-6 animate-spin" /> <RefreshCw className="h-6 w-6 animate-spin" />
<span className="ml-2">{t('loadingServers')}</span> <span className="ml-2">Loading servers...</span>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
@@ -273,29 +221,17 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
<Card className="bg-transparent border-0 shadow-none"> <Card className="bg-transparent border-0 shadow-none">
<CardHeader className="pb-4 px-0"> <CardHeader className="pb-4 px-0">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4"> <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="flex items-center gap-2">
<div className="relative flex-1 sm:w-64"> <div className="relative flex-1 sm:w-64">
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" /> <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
<Input <Input
placeholder={t('searchServersPlaceholder')} placeholder="Search servers..."
value={searchTerm} value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)} onChange={(e) => setSearchTerm(e.target.value)}
className="pl-8" className="pl-8"
/> />
</div> </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"> <Button onClick={onRefresh} variant="outline" size="icon">
<RefreshCw className="h-4 w-4" /> <RefreshCw className="h-4 w-4" />
</Button> </Button>
@@ -305,33 +241,23 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
<CardContent className="p-0"> <CardContent className="p-0">
{filteredServers.length === 0 ? ( {filteredServers.length === 0 ? (
<div className="flex items-center justify-center p-8"> <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>
) : ( ) : (
<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> <Table>
<TableHeader className={`${theme === 'dark' ? 'bg-gray-800' : 'bg-gray-50'}`}> <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'}`}> <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`}> <TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>Name</TableHead>
<div onClick={(e) => e.stopPropagation()}> <TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>Status</TableHead>
<Checkbox <TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>OS</TableHead>
checked={allVisibleSelected} <TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>IP Address</TableHead>
onCheckedChange={(v) => toggleSelectAllVisible(Boolean(v))} <TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>CPU</TableHead>
aria-label="Select all" <TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>Memory</TableHead>
indeterminate={someVisibleSelected} <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>
</div> <TableHead className={`${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} font-medium text-base py-4`}>Last Checked</TableHead>
</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> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
@@ -342,20 +268,12 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
const isPaused = server.status === "paused"; const isPaused = server.status === "paused";
const isProcessing = pausingServers.has(server.id); const isProcessing = pausingServers.has(server.id);
const isSelected = selectedServerIds.has(server.id);
return ( return (
<TableRow <TableRow
key={server.id} key={server.id}
className={`hover:bg-muted/50 cursor-pointer ${isSelected ? 'bg-muted/30' : ''}`} className="hover:bg-muted/50 cursor-pointer"
onClick={() => handleViewDetails(server.id)} 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"> <TableCell className="font-medium">
<div className="truncate" title={server.name}> <div className="truncate" title={server.name}>
{server.name} {server.name}
@@ -415,7 +333,7 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0" disabled={isProcessing}> <Button variant="ghost" className="h-8 w-8 p-0" disabled={isProcessing}>
<span className="sr-only">{t('openMenu')}</span> <span className="sr-only">Open menu</span>
{isProcessing ? ( {isProcessing ? (
<RefreshCw className="h-4 w-4 animate-spin" /> <RefreshCw className="h-4 w-4 animate-spin" />
) : ( ) : (
@@ -426,12 +344,12 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
<DropdownMenuContent align="end" className="w-[200px]"> <DropdownMenuContent align="end" className="w-[200px]">
<DropdownMenuItem onClick={(e) => { e.stopPropagation(); handleViewDetails(server.id); }}> <DropdownMenuItem onClick={(e) => { e.stopPropagation(); handleViewDetails(server.id); }}>
<Eye className="mr-2 h-4 w-4" /> <Eye className="mr-2 h-4 w-4" />
{t('viewServerDetail')} View Server Detail
</DropdownMenuItem> </DropdownMenuItem>
{server.docker === 'true' && ( {server.docker === 'true' && (
<DropdownMenuItem onClick={(e) => { e.stopPropagation(); handleViewContainers(server.id); }}> <DropdownMenuItem onClick={(e) => { e.stopPropagation(); handleViewContainers(server.id); }}>
<Activity className="mr-2 h-4 w-4" /> <Activity className="mr-2 h-4 w-4" />
{t('containerMonitoring')} Container Monitoring
</DropdownMenuItem> </DropdownMenuItem>
)} )}
<DropdownMenuSeparator /> <DropdownMenuSeparator />
@@ -442,26 +360,26 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
{isPaused ? ( {isPaused ? (
<> <>
<Play className="mr-2 h-4 w-4" /> <Play className="mr-2 h-4 w-4" />
{t('resumeMonitoring')} Resume Monitoring
</> </>
) : ( ) : (
<> <>
<Pause className="mr-2 h-4 w-4" /> <Pause className="mr-2 h-4 w-4" />
{t('pauseMonitoring')} Pause Monitoring
</> </>
)} )}
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuSeparator /> <DropdownMenuSeparator />
<DropdownMenuItem onClick={(e) => { e.stopPropagation(); handleEdit(server); }}> <DropdownMenuItem onClick={(e) => { e.stopPropagation(); handleEdit(server); }}>
<Edit className="mr-2 h-4 w-4" /> <Edit className="mr-2 h-4 w-4" />
{t('editServer')} Edit Server
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem <DropdownMenuItem
onClick={(e) => { e.stopPropagation(); handleDelete(server); }} onClick={(e) => { e.stopPropagation(); handleDelete(server); }}
className="text-red-600 focus:text-red-600" className="text-red-600 focus:text-red-600"
> >
<Trash2 className="mr-2 h-4 w-4" /> <Trash2 className="mr-2 h-4 w-4" />
{t('deleteServer')} Delete Server
</DropdownMenuItem> </DropdownMenuItem>
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
@@ -488,45 +406,25 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}> <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent> <AlertDialogContent>
<AlertDialogHeader> <AlertDialogHeader>
<AlertDialogTitle>{t('deleteServerConfirmTitle')}</AlertDialogTitle> <AlertDialogTitle>Are you sure you want to delete this server?</AlertDialogTitle>
<AlertDialogDescription> <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> </AlertDialogDescription>
</AlertDialogHeader> </AlertDialogHeader>
<AlertDialogFooter> <AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}> <AlertDialogCancel disabled={isDeleting}>
{t('cancel')} Cancel
</AlertDialogCancel> </AlertDialogCancel>
<AlertDialogAction <AlertDialogAction
onClick={confirmDelete} onClick={confirmDelete}
disabled={isDeleting} disabled={isDeleting}
className="bg-red-600 text-white hover:bg-red-700" className="bg-red-600 text-white hover:bg-red-700"
> >
{isDeleting ? t('deleting') : t('delete')} {isDeleting ? "Deleting..." : "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'}
</AlertDialogAction> </AlertDialogAction>
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
@@ -9,7 +9,6 @@ import {
import { ServiceForm } from "./ServiceForm"; import { ServiceForm } from "./ServiceForm";
import { ScrollArea } from "@/components/ui/scroll-area"; import { ScrollArea } from "@/components/ui/scroll-area";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
import { useLanguage } from "@/contexts/LanguageContext";
interface AddServiceDialogProps { interface AddServiceDialogProps {
open: boolean; open: boolean;
@@ -17,7 +16,6 @@ interface AddServiceDialogProps {
} }
export function AddServiceDialog({ open, onOpenChange }: AddServiceDialogProps) { export function AddServiceDialog({ open, onOpenChange }: AddServiceDialogProps) {
const { t } = useLanguage();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const handleSuccess = async () => { const handleSuccess = async () => {
// Immediately invalidate and refetch services data // Immediately invalidate and refetch services data
@@ -34,9 +32,9 @@ export function AddServiceDialog({ open, onOpenChange }: AddServiceDialogProps)
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[700px] max-h-[90vh] flex flex-col"> <DialogContent className="sm:max-w-[700px] max-h-[90vh] flex flex-col">
<DialogHeader> <DialogHeader>
<DialogTitle className="text-xl">{t("createNewService")}</DialogTitle> <DialogTitle className="text-xl">Create New Service</DialogTitle>
<DialogDescription> <DialogDescription>
{t("createNewServiceDesc")} Fill in the details to create a new service to monitor.
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<ScrollArea className="flex-1 pr-4 overflow-auto" style={{ height: "calc(80vh - 180px)" }}> <ScrollArea className="flex-1 pr-4 overflow-auto" style={{ height: "calc(80vh - 180px)" }}>
@@ -2,7 +2,6 @@
import React from "react"; import React from "react";
import { Clock, TimerOff } from "lucide-react"; import { Clock, TimerOff } from "lucide-react";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { useLanguage } from "@/contexts/LanguageContext";
interface LastCheckedTimeProps { interface LastCheckedTimeProps {
lastCheckedTime: string; lastCheckedTime: string;
@@ -11,7 +10,6 @@ interface LastCheckedTimeProps {
} }
export const LastCheckedTime = ({ lastCheckedTime, status, interval }: LastCheckedTimeProps) => { export const LastCheckedTime = ({ lastCheckedTime, status, interval }: LastCheckedTimeProps) => {
const { t } = useLanguage();
// Format the time without seconds to display a static time // Format the time without seconds to display a static time
const formatTimeWithoutSeconds = (timeString: string) => { const formatTimeWithoutSeconds = (timeString: string) => {
try { try {
@@ -57,7 +55,7 @@ export const LastCheckedTime = ({ lastCheckedTime, status, interval }: LastCheck
<Clock className="h-4 w-4" /> <Clock className="h-4 w-4" />
)} )}
<span> <span>
{isPaused ? t("pausedAt") : ""} {isPaused ? "Paused at " : ""}
{formattedTime} {formattedTime}
</span> </span>
</div> </div>
@@ -68,14 +66,14 @@ export const LastCheckedTime = ({ lastCheckedTime, status, interval }: LastCheck
> >
<div className="flex flex-col gap-1 text-xs"> <div className="flex flex-col gap-1 text-xs">
<div className="font-medium"> <div className="font-medium">
{isPaused ? t("monitoringPaused") : t("lastCheckDetails")} {isPaused ? "Monitoring Paused" : "Last Check Details"}
</div> </div>
<div> <div>
{isPaused ? t("noAutomaticChecks") : t("checkedAt") + `${formattedTime}`} {isPaused ? "No automatic checks" : `Checked at ${formattedTime}`}
</div> </div>
{interval && !isPaused && ( {interval && !isPaused && (
<div> <div>
{t("checkInterval")}: {formatInterval(interval)} Check interval: {formatInterval(interval)}
</div> </div>
)} )}
<div className="text-gray-400 text-[10px]"> <div className="text-gray-400 text-[10px]">
@@ -1,7 +1,5 @@
import {useLanguage} from "@/contexts/LanguageContext.tsx";
export function LoadingState() { export function LoadingState() {
const { t } = useLanguage();
return ( return (
<div className="flex items-center justify-center h-screen bg-background text-foreground"> <div className="flex items-center justify-center h-screen bg-background text-foreground">
<div className="flex flex-col items-center text-center py-8 px-4 rounded-lg shadow-lg bg-card animate-fade-in"> <div className="flex flex-col items-center text-center py-8 px-4 rounded-lg shadow-lg bg-card animate-fade-in">
@@ -9,8 +7,8 @@ export function LoadingState() {
<div className="absolute w-12 h-12 rounded-full border-4 border-primary/20"></div> <div className="absolute w-12 h-12 rounded-full border-4 border-primary/20"></div>
<div className="w-12 h-12 rounded-full border-4 border-t-primary border-r-transparent border-b-transparent border-l-transparent animate-spin"></div> <div className="w-12 h-12 rounded-full border-4 border-t-primary border-r-transparent border-b-transparent border-l-transparent animate-spin"></div>
</div> </div>
<h3 className="text-xl font-medium mb-1">{t("loadingServerData")}</h3> <h3 className="text-xl font-medium mb-1">Loading server data</h3>
<p className="text-muted-foreground">{t("retrievingYourInformation")}</p> <p className="text-muted-foreground">Please wait while we retrieve your information...</p>
</div> </div>
</div> </div>
); );
@@ -1,3 +1,4 @@
import React from "react"; import React from "react";
import { Sidebar } from "@/components/dashboard/Sidebar"; import { Sidebar } from "@/components/dashboard/Sidebar";
import { Header } from "@/components/dashboard/Header"; import { Header } from "@/components/dashboard/Header";
@@ -6,9 +7,11 @@ import { ServiceNotFound } from "@/components/services/ServiceNotFound";
import { Service } from "@/types/service.types"; import { Service } from "@/types/service.types";
interface ServiceDetailWrapperProps { interface ServiceDetailWrapperProps {
children?: React.ReactNode; children: React.ReactNode;
isLoading: boolean; isLoading: boolean;
service: Service | null; service: Service | null;
sidebarCollapsed: boolean;
toggleSidebar: () => void;
currentUser: any; currentUser: any;
handleLogout: () => void; handleLogout: () => void;
} }
@@ -17,16 +20,20 @@ export const ServiceDetailWrapper = ({
children, children,
isLoading, isLoading,
service, service,
sidebarCollapsed,
toggleSidebar,
currentUser, currentUser,
handleLogout handleLogout
}: ServiceDetailWrapperProps) => { }: ServiceDetailWrapperProps) => {
return ( return (
<div className="flex h-screen w-full overflow-hidden bg-background text-foreground"> <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"> <div className="flex flex-col flex-1 min-w-0">
<Header <Header
currentUser={currentUser} currentUser={currentUser}
onLogout={handleLogout} onLogout={handleLogout}
sidebarCollapsed={sidebarCollapsed}
toggleSidebar={toggleSidebar}
/> />
{isLoading ? ( {isLoading ? (
@@ -1,34 +1,78 @@
import React, { useState, useCallback } from "react"; import { useState, useEffect, useCallback } from "react";
import { useParams, useNavigate } from "react-router-dom"; import { useParams, useNavigate } from "react-router-dom";
import { DateRangeOption } from "../DateRangeFilter"; import { DateRangeOption } from "../DateRangeFilter";
import { authService } from "@/services/authService"; import { authService } from "@/services/authService";
import { ServiceDetailContent } from "../ServiceDetailContent"; import { ServiceDetailContent } from "../ServiceDetailContent";
import { ServiceDetailWrapper } from "./ServiceDetailWrapper"; import { ServiceDetailWrapper } from "./ServiceDetailWrapper";
import { useServiceData, useRealTimeUpdates } from "./hooks"; import { useServiceData, useRealTimeUpdates } from "./hooks";
import { toast } from "@/components/ui/use-toast";
export const ServiceDetailContainer = () => { export const ServiceDetailContainer = () => {
const { id } = useParams<{ id: string }>(); const { id } = useParams<{ id: string }>();
const navigate = useNavigate(); const navigate = useNavigate();
// Set default to 24h
const [startDate, setStartDate] = useState<Date>(() => { const [startDate, setStartDate] = useState<Date>(() => {
const date = new Date(); const date = new Date();
date.setHours(date.getHours() - 24); date.setHours(date.getHours() - 24); // Go back 24 hours
return date; return date;
}); });
const [endDate, setEndDate] = useState<Date>(() => { const [endDate, setEndDate] = useState<Date>(() => {
const date = new Date(); const date = new Date();
date.setMinutes(date.getMinutes() + 5); date.setMinutes(date.getMinutes() + 5); // Add 5 minutes buffer to future
return date; return date;
}); });
const [selectedRange, setSelectedRange] = useState<DateRangeOption>('24h'); 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(); 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 = () => { const handleLogout = () => {
authService.logout(); authService.logout();
navigate("/login"); navigate("/login");
}; };
// Use our custom hooks
const { const {
service, service,
uptimeData, uptimeData,
@@ -41,6 +85,7 @@ export const ServiceDetailContainer = () => {
handleRegionalAgentChange handleRegionalAgentChange
} = useServiceData(id, startDate, endDate); } = useServiceData(id, startDate, endDate);
// Set up real-time updates
useRealTimeUpdates({ useRealTimeUpdates({
serviceId: id, serviceId: id,
startDate, startDate,
@@ -49,12 +94,18 @@ export const ServiceDetailContainer = () => {
setUptimeData setUptimeData
}); });
// Handle date range filter changes
const handleDateRangeChange = useCallback((start: Date, end: Date, option: DateRangeOption) => { 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); setStartDate(start);
setEndDate(end); setEndDate(end);
setSelectedRange(option); setSelectedRange(option);
// Also explicitly fetch data with the new range to ensure immediate update
if (id) { if (id) {
console.log(`ServiceDetailContainer: Explicitly fetching data for service ${id} with new range`);
fetchUptimeData(id, start, end, option, selectedRegionalAgent); fetchUptimeData(id, start, end, option, selectedRegionalAgent);
} }
}, [id, fetchUptimeData, selectedRegionalAgent]); }, [id, fetchUptimeData, selectedRegionalAgent]);
@@ -63,10 +114,12 @@ export const ServiceDetailContainer = () => {
<ServiceDetailWrapper <ServiceDetailWrapper
isLoading={isLoading} isLoading={isLoading}
service={service} service={service}
sidebarCollapsed={sidebarCollapsed}
toggleSidebar={toggleSidebar}
currentUser={currentUser} currentUser={currentUser}
handleLogout={handleLogout} handleLogout={handleLogout}
> >
{service ? ( {service && (
<ServiceDetailContent <ServiceDetailContent
service={service} service={service}
uptimeData={uptimeData} uptimeData={uptimeData}
@@ -76,7 +129,7 @@ export const ServiceDetailContainer = () => {
selectedRegionalAgent={selectedRegionalAgent} selectedRegionalAgent={selectedRegionalAgent}
onRegionalAgentChange={handleRegionalAgentChange} onRegionalAgentChange={handleRegionalAgentChange}
/> />
) : null} )}
</ServiceDetailWrapper> </ServiceDetailWrapper>
); );
}; };
@@ -11,7 +11,6 @@ import { Service } from "@/types/service.types";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { ScrollArea } from "@/components/ui/scroll-area"; import { ScrollArea } from "@/components/ui/scroll-area";
import { useLanguage } from "@/contexts/LanguageContext";
interface ServiceEditDialogProps { interface ServiceEditDialogProps {
open: boolean; open: boolean;
@@ -20,7 +19,6 @@ interface ServiceEditDialogProps {
} }
export function ServiceEditDialog({ open, onOpenChange, service }: ServiceEditDialogProps) { export function ServiceEditDialog({ open, onOpenChange, service }: ServiceEditDialogProps) {
const { t } = useLanguage();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
@@ -55,9 +53,9 @@ export function ServiceEditDialog({ open, onOpenChange, service }: ServiceEditDi
}}> }}>
<DialogContent className="sm:max-w-[700px] max-h-[90vh] flex flex-col"> <DialogContent className="sm:max-w-[700px] max-h-[90vh] flex flex-col">
<DialogHeader> <DialogHeader>
<DialogTitle className="text-xl">{t("editService")}</DialogTitle> <DialogTitle className="text-xl">Edit Service</DialogTitle>
<DialogDescription> <DialogDescription>
{t("editServiceDesc")} Update the details of your monitored service.
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
{open && service && ( {open && service && (
@@ -4,7 +4,6 @@ import { Service, UptimeData } from "@/types/service.types";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useMemo } from "react"; import { useMemo } from "react";
import { formatDistanceStrict } from "date-fns"; import { formatDistanceStrict } from "date-fns";
import {useLanguage} from "@/contexts/LanguageContext.tsx";
interface ServiceStatsCardsProps { interface ServiceStatsCardsProps {
service: Service; service: Service;
@@ -12,8 +11,6 @@ interface ServiceStatsCardsProps {
} }
export function ServiceStatsCards({ service, uptimeData }: ServiceStatsCardsProps) { export function ServiceStatsCards({ service, uptimeData }: ServiceStatsCardsProps) {
const { t } = useLanguage();
// Calculate uptime percentage // Calculate uptime percentage
const calculateUptimePercentage = () => { const calculateUptimePercentage = () => {
if (uptimeData.length === 0) return 100; if (uptimeData.length === 0) return 100;
@@ -112,46 +109,41 @@ export function ServiceStatsCards({ service, uptimeData }: ServiceStatsCardsProp
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8"> <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
<Card className="border-blue-400 dark:border-blue-700 bg-blue-50 dark:bg-blue-900/50 shadow-md"> <Card className="border-blue-400 dark:border-blue-700 bg-blue-50 dark:bg-blue-900/50 shadow-md">
<CardHeader className="pb-2"> <CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-blue-800 dark:text-blue-100">{t('responseTime')}</CardTitle> <CardTitle className="text-sm font-medium text-blue-800 dark:text-blue-100">Response Time</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="text-2xl font-bold text-blue-700 dark:text-white"> <div className="text-2xl font-bold text-blue-700 dark:text-white">
{service.responseTime}ms {service.responseTime}ms
</div> </div>
<p className="text-xs text-blue-600 dark:text-blue-200 mt-1">{t('lastCheckedAt').replace('{datetime}', service.lastChecked)}</p> <p className="text-xs text-blue-600 dark:text-blue-200 mt-1">Last checked at {service.lastChecked}</p>
{avgResponseTime > 0 && avgResponseTime !== service.responseTime && ( {avgResponseTime > 0 && avgResponseTime !== service.responseTime && (
<p className="text-xs text-blue-600 dark:text-blue-200 mt-1">{t('avg')}: {avgResponseTime}ms ({t('lastUpChecksCount').replace('{count}', String(upChecks.length))})</p> <p className="text-xs text-blue-600 dark:text-blue-200 mt-1">Avg: {avgResponseTime}ms (last {upChecks.length} up checks)</p>
)} )}
</CardContent> </CardContent>
</Card> </Card>
<Card className="border-green-400 dark:border-green-700 bg-green-50 dark:bg-green-900/50 shadow-md"> <Card className="border-green-400 dark:border-green-700 bg-green-50 dark:bg-green-900/50 shadow-md">
<CardHeader className="pb-2"> <CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-green-800 dark:text-green-100">{t('uptime')}</CardTitle> <CardTitle className="text-sm font-medium text-green-800 dark:text-green-100">Uptime</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="text-2xl font-bold text-green-700 dark:text-white"> <div className="text-2xl font-bold text-green-700 dark:text-white">
{uptimePercentage}% {uptimePercentage}%
</div> </div>
<p className="text-xs text-green-600 dark:text-green-200 mt-1">{t('basedOnlastChecksCount').replace('{count}', String(uptimeData.length))}</p> <p className="text-xs text-green-600 dark:text-green-200 mt-1">Based on last {uptimeData.length} checks</p>
<div className="flex flex-col space-y-1 mt-2"> <div className="flex flex-col space-y-1 mt-2">
<div className="flex items-center text-xs text-green-600 dark:text-green-200"> <div className="flex items-center text-xs text-green-600 dark:text-green-200">
<ArrowUp className="h-3 w-3 mr-1 text-green-600 dark:text-green-400" /> <ArrowUp className="h-3 w-3 mr-1 text-green-600 dark:text-green-400" />
<span>{t("totalUptime")}: {uptimeStats.totalUptimeFormatted}</span> <span>Total uptime: {uptimeStats.totalUptimeFormatted}</span>
</div> </div>
<div className="flex items-center text-xs text-red-600 dark:text-red-200"> <div className="flex items-center text-xs text-red-600 dark:text-red-200">
<ArrowDown className="h-3 w-3 mr-1 text-red-600 dark:text-red-400" /> <ArrowDown className="h-3 w-3 mr-1 text-red-600 dark:text-red-400" />
<span>{t("totalDowntime")}: {uptimeStats.totalDowntimeFormatted}</span> <span>Total downtime: {uptimeStats.totalDowntimeFormatted}</span>
</div> </div>
{service.status !== "paused" && ( {service.status !== "paused" && (
<div className="flex items-center text-xs font-medium mt-1"> <div className="flex items-center text-xs font-medium mt-1">
<span className={service.status === "up" ? "text-green-600 dark:text-green-400" : "text-red-600 dark:text-red-400"}> <span className={service.status === "up" ? "text-green-600 dark:text-green-400" : "text-red-600 dark:text-red-400"}>
{ {service.status === "up" ? "Up" : "Down"} for {uptimeStats.currentStatusDuration}
service.status === "up" ?
t('upStatusDuration').replace("{duration}", uptimeStats.currentStatusDuration)
:
t('downStatusDuration').replace("{duration}", uptimeStats.currentStatusDuration)
}
</span> </span>
</div> </div>
)} )}
@@ -161,16 +153,16 @@ export function ServiceStatsCards({ service, uptimeData }: ServiceStatsCardsProp
<Card className="border-purple-400 dark:border-purple-700 bg-purple-50 dark:bg-purple-900/50 shadow-md"> <Card className="border-purple-400 dark:border-purple-700 bg-purple-50 dark:bg-purple-900/50 shadow-md">
<CardHeader className="pb-2"> <CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-purple-800 dark:text-purple-100">{t('monitoringSettings')}</CardTitle> <CardTitle className="text-sm font-medium text-purple-800 dark:text-purple-100">Monitoring Settings</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="flex items-center text-sm text-purple-700 dark:text-purple-200"> <div className="flex items-center text-sm text-purple-700 dark:text-purple-200">
<Clock className="h-4 w-4 mr-2 text-purple-600 dark:text-purple-400" /> <Clock className="h-4 w-4 mr-2 text-purple-600 dark:text-purple-400" />
<span>{t('monitoringSettingsInterval').replace('{interval}', String(service.interval))}</span> <span>Checked every {service.interval} seconds</span>
</div> </div>
<div className="flex items-center text-sm text-purple-700 dark:text-purple-200 mt-1"> <div className="flex items-center text-sm text-purple-700 dark:text-purple-200 mt-1">
<Server className="h-4 w-4 mr-2 text-purple-600 dark:text-purple-400" /> <Server className="h-4 w-4 mr-2 text-purple-600 dark:text-purple-400" />
<span>{service.type} {t('monitoringSettingsType')}</span> <span>{service.type} monitoring</span>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
@@ -63,9 +63,9 @@ export function ServicesPagination({
return ( return (
<div className="flex items-center justify-between py-4 px-4 border-t border-border"> <div className="flex items-center justify-between py-4 px-4 border-t border-border">
<div className="flex items-center space-x-2"> <div className="flex items-center space-x-2">
<span className="text-sm text-muted-foreground whitespace-nowrap"> <span className="text-sm text-muted-foreground">
{t("rowsPerPage") ?? "Rows per page"}: {t("rowsPerPage") ?? "Rows per page"}:
</span> </span>
<Select <Select
value={pageSize.toString()} value={pageSize.toString()}
onValueChange={(value) => onPageSizeChange(parseInt(value) as PageSize)} onValueChange={(value) => onPageSizeChange(parseInt(value) as PageSize)}
@@ -80,9 +80,9 @@ export function ServicesPagination({
</SelectContent> </SelectContent>
</Select> </Select>
<span className="text-sm text-muted-foreground whitespace-nowrap"> <span className="text-sm text-muted-foreground whitespace-nowrap">
{totalItems > 0 {totalItems > 0
? t("servicesPagination", {"startItem": startItem, "endItem": endItem, "totalItems": totalItems}) ? `${startItem}-${endItem} of ${totalItems} ${t("services") || "services"}`
: t("servicesPaginationNoService") : `0 ${t("services") || "services"}`
} }
</span> </span>
</div> </div>
@@ -5,7 +5,6 @@ import { TooltipProvider } from '@/components/ui/tooltip';
import { UptimeStatusItem } from './uptime/UptimeStatusItem'; import { UptimeStatusItem } from './uptime/UptimeStatusItem';
import { uptimeService } from '@/services/uptimeService'; import { uptimeService } from '@/services/uptimeService';
import { UptimeData } from '@/types/service.types'; import { UptimeData } from '@/types/service.types';
import {useLanguage} from "@/contexts/LanguageContext.tsx";
interface UptimeBarProps { interface UptimeBarProps {
uptime: number; uptime: number;
@@ -16,7 +15,6 @@ interface UptimeBarProps {
} }
const UptimeBarComponent = ({ uptime, status, serviceId, interval, serviceType = "HTTP" }: UptimeBarProps) => { const UptimeBarComponent = ({ uptime, status, serviceId, interval, serviceType = "HTTP" }: UptimeBarProps) => {
const { t } = useLanguage();
// Calculate date range for last 20 checks with much more aggressive caching // Calculate date range for last 20 checks with much more aggressive caching
const endDate = useMemo(() => new Date(), []); const endDate = useMemo(() => new Date(), []);
const startDate = useMemo(() => { const startDate = useMemo(() => {
@@ -25,21 +23,19 @@ const UptimeBarComponent = ({ uptime, status, serviceId, interval, serviceType =
return start; return start;
}, [endDate, interval]); }, [endDate, interval]);
// Fetch uptime data with immediate display and background updates // Fetch uptime data with very aggressive caching to reduce API calls
const { data: uptimeData = [] } = useQuery({ const { data: uptimeData = [] } = useQuery({
queryKey: ['uptime-bar', serviceId, serviceType], queryKey: ['uptime-bar', serviceId, serviceType],
queryFn: () => uptimeService.getUptimeHistory(serviceId, 20, startDate, endDate, serviceType), queryFn: () => uptimeService.getUptimeHistory(serviceId, 20, startDate, endDate, serviceType),
enabled: !!serviceId, enabled: !!serviceId,
staleTime: 300000, // Data stays fresh for 5 minutes - display immediately from cache staleTime: 30000, // Data is fresh for 30 seconds
gcTime: 900000, // Keep in cache for 15 minutes gcTime: 600000, // Keep in cache for 10 minutes
refetchInterval: 300000, // Reduced to 5 minute polling refetchInterval: 60000, // 1 minute polling
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
refetchOnMount: false, refetchOnMount: false,
refetchOnReconnect: false, refetchOnReconnect: false,
retry: 1, // Reduce retries for faster failure retry: 3,
retryDelay: 1000, // Faster retry delay retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 10000),
refetchIntervalInBackground: true, // Allow background updates
placeholderData: (previousData) => previousData, // Keep showing previous data while refetching
}); });
// Memoize the uptime calculation to prevent unnecessary recalculations // Memoize the uptime calculation to prevent unnecessary recalculations
@@ -88,7 +84,7 @@ const UptimeBarComponent = ({ uptime, status, serviceId, interval, serviceType =
</div> </div>
<span className="text-xs text-muted-foreground"> <span className="text-xs text-muted-foreground">
{t('last20Checks')} Last 20 checks
</span> </span>
</TooltipProvider> </TooltipProvider>
); );
@@ -3,24 +3,22 @@ import { FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/comp
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { UseFormReturn } from "react-hook-form"; import { UseFormReturn } from "react-hook-form";
import { ServiceFormData } from "./types"; import { ServiceFormData } from "./types";
import {useLanguage} from "@/contexts/LanguageContext.tsx";
interface ServiceBasicFieldsProps { interface ServiceBasicFieldsProps {
form: UseFormReturn<ServiceFormData>; form: UseFormReturn<ServiceFormData>;
} }
export function ServiceBasicFields({ form }: ServiceBasicFieldsProps) { export function ServiceBasicFields({ form }: ServiceBasicFieldsProps) {
const { t } = useLanguage();
return ( return (
<FormField <FormField
control={form.control} control={form.control}
name="name" name="name"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t('serviceName')}</FormLabel> <FormLabel>Service Name</FormLabel>
<FormControl> <FormControl>
<Input <Input
placeholder={t('serviceNameDesc')} placeholder="Enter a descriptive name for your service"
{...field} {...field}
/> />
</FormControl> </FormControl>
@@ -6,14 +6,12 @@ import { UseFormReturn } from "react-hook-form";
import { ServiceFormData } from "./types"; import { ServiceFormData } from "./types";
import { ServiceUrlField } from "./ServiceUrlField"; import { ServiceUrlField } from "./ServiceUrlField";
import { useState } from "react"; import { useState } from "react";
import {useLanguage} from "@/contexts/LanguageContext.tsx";
interface ServiceConfigFieldsProps { interface ServiceConfigFieldsProps {
form: UseFormReturn<ServiceFormData>; form: UseFormReturn<ServiceFormData>;
} }
export function ServiceConfigFields({ form }: ServiceConfigFieldsProps) { export function ServiceConfigFields({ form }: ServiceConfigFieldsProps) {
const { t } = useLanguage();
const [isCustomInterval, setIsCustomInterval] = useState(false); const [isCustomInterval, setIsCustomInterval] = useState(false);
const intervalValue = form.watch("interval"); const intervalValue = form.watch("interval");
@@ -37,7 +35,7 @@ export function ServiceConfigFields({ form }: ServiceConfigFieldsProps) {
name="interval" name="interval"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("checkInterval")}</FormLabel> <FormLabel>Check Interval</FormLabel>
{!isCustomInterval ? ( {!isCustomInterval ? (
<FormControl> <FormControl>
<Select onValueChange={handleIntervalChange} value={isCustomInterval ? "custom" : field.value}> <Select onValueChange={handleIntervalChange} value={isCustomInterval ? "custom" : field.value}>
@@ -45,13 +43,13 @@ export function ServiceConfigFields({ form }: ServiceConfigFieldsProps) {
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="30">30 {t("seconds")}</SelectItem> <SelectItem value="30">30 seconds</SelectItem>
<SelectItem value="60">1 {t("minute")}</SelectItem> <SelectItem value="60">1 minute</SelectItem>
<SelectItem value="300">5 {t("minutes")}</SelectItem> <SelectItem value="300">5 minutes</SelectItem>
<SelectItem value="900">15 {t("minutes")}</SelectItem> <SelectItem value="900">15 minutes</SelectItem>
<SelectItem value="1800">30 {t("minutes")}</SelectItem> <SelectItem value="1800">30 minutes</SelectItem>
<SelectItem value="3600">1 {t("hour")}</SelectItem> <SelectItem value="3600">1 hour</SelectItem>
<SelectItem value="custom">{t("custom")}</SelectItem> <SelectItem value="custom">Custom</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</FormControl> </FormControl>
@@ -60,7 +58,7 @@ export function ServiceConfigFields({ form }: ServiceConfigFieldsProps) {
<FormControl> <FormControl>
<Input <Input
type="number" type="number"
placeholder={t("checkIntervalPlaceholder")} placeholder="Enter interval in seconds"
value={field.value} value={field.value}
onChange={field.onChange} onChange={field.onChange}
min="10" min="10"
@@ -74,14 +72,14 @@ export function ServiceConfigFields({ form }: ServiceConfigFieldsProps) {
}} }}
className="text-sm text-blue-600 hover:text-blue-800" className="text-sm text-blue-600 hover:text-blue-800"
> >
{t("backToPresets")} Back to presets
</button> </button>
</div> </div>
)} )}
<FormDescription className="text-xs"> <FormDescription className="text-xs">
{isCustomInterval {isCustomInterval
? t("checkIntervalDescCustom") ? "Enter custom interval in seconds (minimum 10 seconds)"
: t("checkIntervalDesc") : "How often to check the service status"
} }
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
@@ -94,22 +92,22 @@ export function ServiceConfigFields({ form }: ServiceConfigFieldsProps) {
name="retries" name="retries"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("retryAttempts")}</FormLabel> <FormLabel>Retry Attempts</FormLabel>
<FormControl> <FormControl>
<Select onValueChange={field.onChange} value={field.value ?? "3"}> <Select onValueChange={field.onChange} defaultValue={field.value}>
<SelectTrigger> <SelectTrigger>
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="1">1 {t("attempt")}</SelectItem> <SelectItem value="1">1 attempt</SelectItem>
<SelectItem value="2">2 {t("attempts")}</SelectItem> <SelectItem value="2">2 attempts</SelectItem>
<SelectItem value="3">3 {t("attempts")}</SelectItem> <SelectItem value="3">3 attempts</SelectItem>
<SelectItem value="5">5 {t("attempts")}</SelectItem> <SelectItem value="5">5 attempts</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</FormControl> </FormControl>
<FormDescription className="text-xs"> <FormDescription className="text-xs">
{t("retryAttemptsDesc")} Number of retry attempts before marking as down
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -3,7 +3,7 @@ import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { useServiceSchema, ServiceFormData } from "./types"; import { serviceSchema, ServiceFormData } from "./types";
import { ServiceBasicFields } from "./ServiceBasicFields"; import { ServiceBasicFields } from "./ServiceBasicFields";
import { ServiceTypeField } from "./ServiceTypeField"; import { ServiceTypeField } from "./ServiceTypeField";
import { ServiceConfigFields } from "./ServiceConfigFields"; import { ServiceConfigFields } from "./ServiceConfigFields";
@@ -14,7 +14,6 @@ import { Service } from "@/types/service.types";
import { ServiceRegionalFields } from "./ServiceRegionalFields"; import { ServiceRegionalFields } from "./ServiceRegionalFields";
import { getServiceFormDefaults, mapServiceToFormData, mapFormDataToServiceData } from "./serviceFormUtils"; import { getServiceFormDefaults, mapServiceToFormData, mapFormDataToServiceData } from "./serviceFormUtils";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
import {useLanguage} from "@/contexts/LanguageContext.tsx";
interface ServiceFormProps { interface ServiceFormProps {
onSuccess: () => void; onSuccess: () => void;
@@ -31,13 +30,10 @@ export function ServiceForm({
isEdit = false, isEdit = false,
onSubmitStart onSubmitStart
}: ServiceFormProps) { }: ServiceFormProps) {
const { t } = useLanguage();
const { toast } = useToast(); const { toast } = useToast();
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const serviceSchema = useServiceSchema();
// Initialize form with default values // Initialize form with default values
const form = useForm<ServiceFormData>({ const form = useForm<ServiceFormData>({
resolver: zodResolver(serviceSchema), resolver: zodResolver(serviceSchema),
@@ -128,23 +124,23 @@ export function ServiceForm({
<form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6 pb-6"> <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6 pb-6">
<div className="space-y-6"> <div className="space-y-6">
<div className="space-y-4"> <div className="space-y-4">
<h3 className="text-sm font-medium text-muted-foreground border-b pb-2">{t('basicInformation')}</h3> <h3 className="text-sm font-medium text-muted-foreground border-b pb-2">Basic Information</h3>
<ServiceBasicFields form={form} /> <ServiceBasicFields form={form} />
<ServiceTypeField form={form} /> <ServiceTypeField form={form} />
</div> </div>
<div className="space-y-4"> <div className="space-y-4">
<h3 className="text-sm font-medium text-muted-foreground border-b pb-2">{t('configuration')}</h3> <h3 className="text-sm font-medium text-muted-foreground border-b pb-2">Configuration</h3>
<ServiceConfigFields form={form} /> <ServiceConfigFields form={form} />
</div> </div>
<div className="space-y-4"> <div className="space-y-4">
<h3 className="text-sm font-medium text-muted-foreground border-b pb-2">{t('regionalMonitoring')}</h3> <h3 className="text-sm font-medium text-muted-foreground border-b pb-2">Regional Monitoring</h3>
<ServiceRegionalFields form={form} /> <ServiceRegionalFields form={form} />
</div> </div>
<div className="space-y-4"> <div className="space-y-4">
<h3 className="text-sm font-medium text-muted-foreground border-b pb-2">{t('notifications')}</h3> <h3 className="text-sm font-medium text-muted-foreground border-b pb-2">Notifications</h3>
<ServiceNotificationFields form={form} /> <ServiceNotificationFields form={form} />
</div> </div>
</div> </div>
@@ -152,7 +148,7 @@ export function ServiceForm({
<ServiceFormActions <ServiceFormActions
isSubmitting={isSubmitting} isSubmitting={isSubmitting}
onCancel={onCancel} onCancel={onCancel}
submitLabel={isEdit ? t("updateService") : t("createService")} submitLabel={isEdit ? "Update Service" : "Create Service"}
/> />
</form> </form>
</Form> </Form>
@@ -2,7 +2,6 @@
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Loader2 } from "lucide-react"; import { Loader2 } from "lucide-react";
import { MouseEvent } from "react"; import { MouseEvent } from "react";
import {useLanguage} from "@/contexts/LanguageContext.tsx";
interface ServiceFormActionsProps { interface ServiceFormActionsProps {
isSubmitting: boolean; isSubmitting: boolean;
@@ -15,8 +14,6 @@ export function ServiceFormActions({
onCancel, onCancel,
submitLabel = "Create Service" submitLabel = "Create Service"
}: ServiceFormActionsProps) { }: ServiceFormActionsProps) {
const {t} = useLanguage();
const handleCancel = (e: MouseEvent<HTMLButtonElement>) => { const handleCancel = (e: MouseEvent<HTMLButtonElement>) => {
e.preventDefault(); e.preventDefault();
if (!isSubmitting) { if (!isSubmitting) {
@@ -32,7 +29,7 @@ export function ServiceFormActions({
variant="outline" variant="outline"
disabled={isSubmitting} disabled={isSubmitting}
> >
{t("cancel")} Cancel
</Button> </Button>
<Button <Button
type="submit" type="submit"
@@ -41,7 +38,7 @@ export function ServiceFormActions({
{isSubmitting ? ( {isSubmitting ? (
<> <>
<Loader2 className="mr-2 h-4 w-4 animate-spin" /> <Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t("processing")}... Processing...
</> </>
) : ( ) : (
submitLabel submitLabel
@@ -9,14 +9,12 @@ import { useQuery } from "@tanstack/react-query";
import { alertConfigService, AlertConfiguration } from "@/services/alertConfigService"; import { alertConfigService, AlertConfiguration } from "@/services/alertConfigService";
import { serviceNotificationTemplateService, ServiceNotificationTemplate } from "@/services/serviceNotificationTemplateService"; import { serviceNotificationTemplateService, ServiceNotificationTemplate } from "@/services/serviceNotificationTemplateService";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useLanguage } from "@/contexts/LanguageContext.tsx";
interface ServiceNotificationFieldsProps { interface ServiceNotificationFieldsProps {
form: UseFormReturn<ServiceFormData>; form: UseFormReturn<ServiceFormData>;
} }
export function ServiceNotificationFields({ form }: ServiceNotificationFieldsProps) { export function ServiceNotificationFields({ form }: ServiceNotificationFieldsProps) {
const { t } = useLanguage();
const [alertConfigs, setAlertConfigs] = useState<AlertConfiguration[]>([]); const [alertConfigs, setAlertConfigs] = useState<AlertConfiguration[]>([]);
// Get the current form values for debugging // Get the current form values for debugging
@@ -90,10 +88,10 @@ export function ServiceNotificationFields({ form }: ServiceNotificationFieldsPro
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4"> <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5"> <div className="space-y-0.5">
<FormLabel className="text-base"> <FormLabel className="text-base">
{t("enableNotifications")} Enable Notifications
</FormLabel> </FormLabel>
<FormDescription> <FormDescription>
{t("enableNotificationsDesc")} Enable or disable notifications for this service
</FormDescription> </FormDescription>
</div> </div>
<FormControl> <FormControl>
@@ -117,11 +115,11 @@ export function ServiceNotificationFields({ form }: ServiceNotificationFieldsPro
name="notificationChannels" name="notificationChannels"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("notificationChannels")}</FormLabel> <FormLabel>Notification Channels</FormLabel>
<FormDescription> <FormDescription>
{notificationStatus === "enabled" {notificationStatus === "enabled"
? t("notificationChannelsEnabledDesc") ? "Select notification channels for this service"
: t("notificationChannelsDesc")} : "Enable notifications first to select channels"}
</FormDescription> </FormDescription>
{/* Display selected channels as badges */} {/* Display selected channels as badges */}
@@ -146,7 +144,7 @@ export function ServiceNotificationFields({ form }: ServiceNotificationFieldsPro
value="" // Always reset to empty after selection value="" // Always reset to empty after selection
> >
<SelectTrigger className={notificationStatus !== "enabled" ? 'opacity-50' : ''}> <SelectTrigger className={notificationStatus !== "enabled" ? 'opacity-50' : ''}>
<SelectValue placeholder={t("notificationChannelsPlaceholder")} /> <SelectValue placeholder="Add a notification channel" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{alertConfigs {alertConfigs
@@ -171,7 +169,7 @@ export function ServiceNotificationFields({ form }: ServiceNotificationFieldsPro
return ( return (
<FormItem> <FormItem>
<FormLabel>{t("alertTemplate")}</FormLabel> <FormLabel>Alert Template</FormLabel>
<FormControl> <FormControl>
<Select <Select
onValueChange={(value) => { onValueChange={(value) => {
@@ -181,7 +179,7 @@ export function ServiceNotificationFields({ form }: ServiceNotificationFieldsPro
disabled={notificationStatus !== "enabled" || isLoadingTemplates} disabled={notificationStatus !== "enabled" || isLoadingTemplates}
> >
<SelectTrigger className={notificationStatus !== "enabled" ? 'opacity-50' : ''}> <SelectTrigger className={notificationStatus !== "enabled" ? 'opacity-50' : ''}>
<SelectValue placeholder={isLoadingTemplates ? t("alertTemplateLoading") : t("alertTemplatePlaceholder")} /> <SelectValue placeholder={isLoadingTemplates ? "Loading templates..." : "Select an alert template"} />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{serviceTemplates?.map((template) => ( {serviceTemplates?.map((template) => (
@@ -194,8 +192,8 @@ export function ServiceNotificationFields({ form }: ServiceNotificationFieldsPro
</FormControl> </FormControl>
<FormDescription> <FormDescription>
{notificationStatus === "enabled" {notificationStatus === "enabled"
? t("alertTemplateEnabledDesc") ? "Choose a template for alert messages"
: t("alertTemplateDesc")} : "Enable notifications first to select template"}
</FormDescription> </FormDescription>
</FormItem> </FormItem>
); );
@@ -9,14 +9,12 @@ import { regionalService } from "@/services/regionalService";
import { MapPin, Loader2, X, Plus } from "lucide-react"; import { MapPin, Loader2, X, Plus } from "lucide-react";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { useLanguage } from "@/contexts/LanguageContext.tsx";
interface ServiceRegionalFieldsProps { interface ServiceRegionalFieldsProps {
form: UseFormReturn<ServiceFormData>; form: UseFormReturn<ServiceFormData>;
} }
export function ServiceRegionalFields({ form }: ServiceRegionalFieldsProps) { export function ServiceRegionalFields({ form }: ServiceRegionalFieldsProps) {
const { t } = useLanguage();
const regionalMonitoringEnabled = form.watch("regionalMonitoringEnabled"); const regionalMonitoringEnabled = form.watch("regionalMonitoringEnabled");
const currentRegionalAgents = form.watch("regionalAgents") || []; const currentRegionalAgents = form.watch("regionalAgents") || [];
@@ -81,10 +79,10 @@ export function ServiceRegionalFields({ form }: ServiceRegionalFieldsProps) {
<div className="space-y-0.5"> <div className="space-y-0.5">
<FormLabel className="text-base font-medium flex items-center gap-2"> <FormLabel className="text-base font-medium flex items-center gap-2">
<MapPin className="h-4 w-4" /> <MapPin className="h-4 w-4" />
{t("regionalMonitoring")} Regional Monitoring
</FormLabel> </FormLabel>
<div className="text-sm text-muted-foreground"> <div className="text-sm text-muted-foreground">
{t("regionalMonitoringDesc")} Assign this service to regional monitoring agents for distributed monitoring
</div> </div>
</div> </div>
<FormControl> <FormControl>
@@ -109,7 +107,7 @@ export function ServiceRegionalFields({ form }: ServiceRegionalFieldsProps) {
name="regionalAgents" name="regionalAgents"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("regionalAgents")}</FormLabel> <FormLabel>Regional Agents</FormLabel>
{/* Display selected agents */} {/* Display selected agents */}
{currentRegionalAgents.length > 0 && ( {currentRegionalAgents.length > 0 && (
@@ -142,12 +140,12 @@ export function ServiceRegionalFields({ form }: ServiceRegionalFieldsProps) {
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder={ <SelectValue placeholder={
isLoading isLoading
? t("regionalAgentsLoading") ? "Loading agents..."
: availableAgents.length > 0 : availableAgents.length > 0
? t("regionalAgentsAvailablePlaceholder") ? "Select additional regional agents..."
: currentRegionalAgents.length > 0 : currentRegionalAgents.length > 0
? t("regionalAgentsAllSelected") ? "All available agents selected"
: t("regionalAgentsNoAvailable") : "No regional agents available"
} /> } />
</SelectTrigger> </SelectTrigger>
</FormControl> </FormControl>
@@ -156,14 +154,14 @@ export function ServiceRegionalFields({ form }: ServiceRegionalFieldsProps) {
<SelectItem value="loading" disabled> <SelectItem value="loading" disabled>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" /> <Loader2 className="h-4 w-4 animate-spin" />
t("regionalAgentsLoading") Loading agents...
</div> </div>
</SelectItem> </SelectItem>
) : availableAgents.length === 0 ? ( ) : availableAgents.length === 0 ? (
<SelectItem value="no-agents" disabled> <SelectItem value="no-agents" disabled>
{currentRegionalAgents.length > 0 {currentRegionalAgents.length > 0
? t("regionalAgentsAllSelected") ? "All available agents selected"
: t("regionalAgentsNoOnlineAvailable") : "No online regional agents available"
} }
</SelectItem> </SelectItem>
) : ( ) : (
@@ -192,13 +190,13 @@ export function ServiceRegionalFields({ form }: ServiceRegionalFieldsProps) {
{regionalMonitoringEnabled && onlineAgents.length === 0 && !isLoading && ( {regionalMonitoringEnabled && onlineAgents.length === 0 && !isLoading && (
<p className="text-sm text-amber-600"> <p className="text-sm text-amber-600">
{t("regionalAgentsNotFoundMessage")} No online regional agents found. Services will use default monitoring.
</p> </p>
)} )}
{currentRegionalAgents.length === 0 && regionalMonitoringEnabled && ( {currentRegionalAgents.length === 0 && regionalMonitoringEnabled && (
<p className="text-sm text-orange-600"> <p className="text-sm text-orange-600">
{t("regionalAgentsNotSelectedMessage")} No regional agents selected. Service will use default monitoring.
</p> </p>
)} )}
@@ -4,14 +4,12 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { Globe, Wifi, Server, Globe2 } from "lucide-react"; import { Globe, Wifi, Server, Globe2 } from "lucide-react";
import { UseFormReturn } from "react-hook-form"; import { UseFormReturn } from "react-hook-form";
import { ServiceFormData } from "./types"; import { ServiceFormData } from "./types";
import { useLanguage } from "@/contexts/LanguageContext.tsx";
interface ServiceTypeFieldProps { interface ServiceTypeFieldProps {
form: UseFormReturn<ServiceFormData>; form: UseFormReturn<ServiceFormData>;
} }
export function ServiceTypeField({ form }: ServiceTypeFieldProps) { export function ServiceTypeField({ form }: ServiceTypeFieldProps) {
const { t } = useLanguage();
const getServiceIcon = (type: string) => { const getServiceIcon = (type: string) => {
switch (type) { switch (type) {
case "http": case "http":
@@ -33,7 +31,7 @@ export function ServiceTypeField({ form }: ServiceTypeFieldProps) {
name="type" name="type"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("serviceType")}</FormLabel> <FormLabel>Service Type</FormLabel>
<FormControl> <FormControl>
<Select <Select
onValueChange={field.onChange} onValueChange={field.onChange}
@@ -58,7 +56,7 @@ export function ServiceTypeField({ form }: ServiceTypeFieldProps) {
<span>HTTP/S</span> <span>HTTP/S</span>
</div> </div>
<p className="text-xs text-muted-foreground mt-1"> <p className="text-xs text-muted-foreground mt-1">
{t("serviceTypeHTTPDesc")} Monitor websites and REST APIs with HTTP/HTTPS Protocol
</p> </p>
</div> </div>
</SelectItem> </SelectItem>
@@ -69,7 +67,7 @@ export function ServiceTypeField({ form }: ServiceTypeFieldProps) {
<span>PING</span> <span>PING</span>
</div> </div>
<p className="text-xs text-muted-foreground mt-1"> <p className="text-xs text-muted-foreground mt-1">
{t("serviceTypePINGDesc")} Monitor host availability with PING Protocol
</p> </p>
</div> </div>
</SelectItem> </SelectItem>
@@ -80,7 +78,7 @@ export function ServiceTypeField({ form }: ServiceTypeFieldProps) {
<span>TCP</span> <span>TCP</span>
</div> </div>
<p className="text-xs text-muted-foreground mt-1"> <p className="text-xs text-muted-foreground mt-1">
{t("serviceTypeTCPDesc")} Monitor TCP port connectivity with TCP Protocol
</p> </p>
</div> </div>
</SelectItem> </SelectItem>
@@ -91,7 +89,7 @@ export function ServiceTypeField({ form }: ServiceTypeFieldProps) {
<span>DNS</span> <span>DNS</span>
</div> </div>
<p className="text-xs text-muted-foreground mt-1"> <p className="text-xs text-muted-foreground mt-1">
{t("serviceTypeDNSDesc")} Monitor DNS resolution
</p> </p>
</div> </div>
</SelectItem> </SelectItem>
@@ -3,14 +3,12 @@ import { FormControl, FormField, FormItem, FormLabel, FormMessage, FormDescripti
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { UseFormReturn } from "react-hook-form"; import { UseFormReturn } from "react-hook-form";
import { ServiceFormData } from "./types"; import { ServiceFormData } from "./types";
import { useLanguage } from "@/contexts/LanguageContext.tsx";
interface ServiceUrlFieldProps { interface ServiceUrlFieldProps {
form: UseFormReturn<ServiceFormData>; form: UseFormReturn<ServiceFormData>;
} }
export function ServiceUrlField({ form }: ServiceUrlFieldProps) { export function ServiceUrlField({ form }: ServiceUrlFieldProps) {
const { t } = useLanguage();
const serviceType = form.watch("type"); const serviceType = form.watch("type");
const getPlaceholder = () => { const getPlaceholder = () => {
@@ -24,35 +22,35 @@ export function ServiceUrlField({ form }: ServiceUrlFieldProps) {
case "dns": case "dns":
return "example.com"; return "example.com";
default: default:
return t("targetDefaultPlaceholder"); return "Enter URL or hostname";
} }
}; };
const getDescription = () => { const getDescription = () => {
switch (serviceType) { switch (serviceType) {
case "http": case "http":
return t("targetHTTPDesc"); return "Enter the full URL including protocol (http:// or https://)";
case "ping": case "ping":
return t("targetPINGDesc"); return "Enter hostname or IP address to ping";
case "tcp": case "tcp":
return t("targetTCPDesc"); return "Enter hostname or IP address for TCP connection test";
case "dns": case "dns":
return t("targetDNSDesc"); return "Enter domain name for DNS record monitoring (A, AAAA, MX, etc.)";
default: default:
return t("targetDefaultDesc"); return "Enter the target URL or hostname for monitoring";
} }
}; };
const getFieldLabel = () => { const getFieldLabel = () => {
switch (serviceType) { switch (serviceType) {
case "dns": case "dns":
return t("targetDNS"); return "Domain Name";
case "ping": case "ping":
return "Hostname/IP"; return "Hostname/IP";
case "tcp": case "tcp":
return "Hostname/IP"; return "Hostname/IP";
default: default:
return t("targetDefault"); return "Target URL/Host";
} }
}; };
@@ -101,7 +99,7 @@ export function ServiceUrlField({ form }: ServiceUrlFieldProps) {
/> />
</FormControl> </FormControl>
<FormDescription className="text-xs"> <FormDescription className="text-xs">
{t("targetTCPPortDesc")} Enter the port number for TCP connection test
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -1,46 +1,22 @@
import { z } from "zod"; import { z } from "zod";
import type { ZodSchema } from "zod";
import { useLanguage } from "@/contexts/LanguageContext";
export const serviceSchema = z.object({
name: z.string().min(1, "Service name is required"),
type: z.enum(["http", "ping", "tcp", "dns"]),
url: z.string().min(1, "URL/Domain/Host is required").refine((value) => {
// Basic validation - more specific validation can be added per type
return value.trim().length > 0;
}, "Please enter a valid URL, hostname, or domain"),
port: z.string().optional(),
interval: z.string(),
retries: z.string(),
notificationStatus: z.enum(["enabled", "disabled"]).optional(),
notificationChannels: z.array(z.string()).optional(),
alertTemplate: z.string().optional(),
// Regional monitoring fields - now supports multiple agents
regionalMonitoringEnabled: z.boolean().optional(),
regionalAgents: z.array(z.string()).optional(),
});
export type ServiceFormData = { export type ServiceFormData = z.infer<typeof serviceSchema>;
name: string;
type: "http" | "ping" | "tcp" | "dns";
url: string;
port?: string;
interval: string;
retries: string;
notificationStatus?: "enabled" | "disabled";
notificationChannels?: string[];
alertTemplate?: string;
regionalMonitoringEnabled?: boolean;
regionalAgents?: string[];
};
// Hook to use the schema with translations
export const useServiceSchema = () => {
const { t } = useLanguage();
return z.object({
name: z.string().min(1, t("serviceNameRequired")),
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")
),
port: z.string().optional(),
interval: z.string(),
retries: z.string(),
notificationStatus: z.enum(["enabled", "disabled"]).optional(),
notificationChannels: z.array(z.string()).optional(),
alertTemplate: z.string().optional(),
// Regional monitoring fields - now supports multiple agents
regionalMonitoringEnabled: z.boolean().optional(),
regionalAgents: z.array(z.string()).optional(),
});
};
@@ -25,8 +25,8 @@ export function IncidentTable({ incidents }: IncidentTableProps) {
<TableHead className={theme === 'dark' ? 'text-gray-300' : 'text-gray-700'}>{t("time")}</TableHead> <TableHead className={theme === 'dark' ? 'text-gray-300' : 'text-gray-700'}>{t("time")}</TableHead>
<TableHead className={theme === 'dark' ? 'text-gray-300' : 'text-gray-700'}>{t("status")}</TableHead> <TableHead className={theme === 'dark' ? 'text-gray-300' : 'text-gray-700'}>{t("status")}</TableHead>
<TableHead className={theme === 'dark' ? 'text-gray-300' : 'text-gray-700'}>{t("responseTime")}</TableHead> <TableHead className={theme === 'dark' ? 'text-gray-300' : 'text-gray-700'}>{t("responseTime")}</TableHead>
<TableHead className={theme === 'dark' ? 'text-gray-300' : 'text-gray-700'}>{t("errorMessage")}</TableHead> <TableHead className={theme === 'dark' ? 'text-gray-300' : 'text-gray-700'}>Error Message</TableHead>
<TableHead className={theme === 'dark' ? 'text-gray-300' : 'text-gray-700'}>{t("details")}</TableHead> <TableHead className={theme === 'dark' ? 'text-gray-300' : 'text-gray-700'}>Details</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
@@ -9,12 +9,10 @@ import { IncidentTable } from "./IncidentTable";
import { StatusFilter, PageSize } from "./types"; import { StatusFilter, PageSize } from "./types";
import { getStatusChangeEvents } from "./utils"; import { getStatusChangeEvents } from "./utils";
import { useTheme } from "@/contexts/ThemeContext"; import { useTheme } from "@/contexts/ThemeContext";
import { useLanguage } from "@/contexts/LanguageContext";
export function LatestChecksTable({ uptimeData }: { uptimeData: UptimeData[] }) { export function LatestChecksTable({ uptimeData }: { uptimeData: UptimeData[] }) {
// Get current theme // Get current theme
const { theme } = useTheme(); const { theme } = useTheme();
const { t } = useLanguage();
// Filter state // Filter state
const [statusFilter, setStatusFilter] = useState<StatusFilter>("all"); const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");
@@ -67,7 +65,7 @@ export function LatestChecksTable({ uptimeData }: { uptimeData: UptimeData[] })
<CardHeader> <CardHeader>
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4"> <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<CardTitle className="text-card-foreground"> <CardTitle className="text-card-foreground">
<span>{t("incidentHistory")}</span> <span>Incident History</span>
</CardTitle> </CardTitle>
<StatusFilterTabs statusFilter={statusFilter} onStatusFilterChange={setStatusFilter} /> <StatusFilterTabs statusFilter={statusFilter} onStatusFilterChange={setStatusFilter} />
</div> </div>
@@ -15,7 +15,6 @@ import {
SelectValue SelectValue
} from "@/components/ui/select"; } from "@/components/ui/select";
import { PageSize } from "./types"; import { PageSize } from "./types";
import {useLanguage} from "@/contexts/LanguageContext.tsx";
interface TablePaginationProps { interface TablePaginationProps {
currentPage: number; currentPage: number;
@@ -36,7 +35,6 @@ export function TablePagination({
onPageChange, onPageChange,
onPageSizeChange, onPageSizeChange,
}: TablePaginationProps) { }: TablePaginationProps) {
const {t} = useLanguage()
// Generate page numbers // Generate page numbers
const getPageNumbers = () => { const getPageNumbers = () => {
const pages = []; const pages = [];
@@ -60,7 +58,7 @@ export function TablePagination({
return ( return (
<div className="mt-4 flex items-center justify-between"> <div className="mt-4 flex items-center justify-between">
<div className="flex items-center space-x-2"> <div className="flex items-center space-x-2">
<span className="text-sm text-muted-foreground">{t("rowsPerPage")}:</span> <span className="text-sm text-muted-foreground">Rows per page:</span>
<Select <Select
value={pageSize} value={pageSize}
onValueChange={(value) => onPageSizeChange(value as PageSize)} onValueChange={(value) => onPageSizeChange(value as PageSize)}
@@ -12,7 +12,6 @@ import {
import { Service } from "@/types/service.types"; import { Service } from "@/types/service.types";
import { serviceService } from "@/services/serviceService"; import { serviceService } from "@/services/serviceService";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { useLanguage } from "@/contexts/LanguageContext";
interface ServiceRowActionsProps { interface ServiceRowActionsProps {
service: Service; service: Service;
@@ -32,7 +31,6 @@ export const ServiceRowActions = ({
onMuteAlerts onMuteAlerts
}: ServiceRowActionsProps) => { }: ServiceRowActionsProps) => {
const { toast } = useToast(); const { toast } = useToast();
const { t } = useLanguage();
// Handle pause/resume directly from dropdown // Handle pause/resume directly from dropdown
const handlePauseResume = async (e: React.MouseEvent) => { const handlePauseResume = async (e: React.MouseEvent) => {
@@ -124,7 +122,7 @@ export const ServiceRowActions = ({
}} }}
> >
<Eye className="h-4 w-4" /> <Eye className="h-4 w-4" />
<span>{t("viewDetail")}</span> <span>View Detail</span>
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem <DropdownMenuItem
className="flex items-center gap-2 cursor-pointer text-base py-2.5" className="flex items-center gap-2 cursor-pointer text-base py-2.5"
@@ -133,12 +131,12 @@ export const ServiceRowActions = ({
{service.status === "paused" ? ( {service.status === "paused" ? (
<> <>
<Play className="h-4 w-4" /> <Play className="h-4 w-4" />
<span>{t("resumeMonitoring")}</span> <span>Resume Monitoring</span>
</> </>
) : ( ) : (
<> <>
<Pause className="h-4 w-4" /> <Pause className="h-4 w-4" />
<span>{t("pauseMonitoring")}</span> <span>Pause Monitoring</span>
</> </>
)} )}
</DropdownMenuItem> </DropdownMenuItem>
@@ -150,7 +148,7 @@ export const ServiceRowActions = ({
}} }}
> >
<Edit className="h-4 w-4" /> <Edit className="h-4 w-4" />
<span>{t("edit")}</span> <span>Edit</span>
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem <DropdownMenuItem
className="flex items-center gap-2 cursor-pointer text-base py-2.5" className="flex items-center gap-2 cursor-pointer text-base py-2.5"
@@ -159,12 +157,12 @@ export const ServiceRowActions = ({
{alertsMuted ? ( {alertsMuted ? (
<> <>
<Bell className="h-4 w-4" /> <Bell className="h-4 w-4" />
<span>{t("unmuteAlerts")}</span> <span>Unmute Alerts</span>
</> </>
) : ( ) : (
<> <>
<BellOff className="h-4 w-4" /> <BellOff className="h-4 w-4" />
<span>{t("muteAlerts")}</span> <span>Mute Alerts</span>
</> </>
)} )}
</DropdownMenuItem> </DropdownMenuItem>
@@ -177,7 +175,7 @@ export const ServiceRowActions = ({
}} }}
> >
<Trash2 className="h-4 w-4" /> <Trash2 className="h-4 w-4" />
<span>{t("delete")}</span> <span>Delete</span>
</DropdownMenuItem> </DropdownMenuItem>
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
@@ -1,6 +1,5 @@
import React from 'react'; import React from 'react';
import {useLanguage} from "@/contexts/LanguageContext.tsx";
interface UptimeSummaryProps { interface UptimeSummaryProps {
uptime: number; uptime: number;
@@ -8,14 +7,13 @@ interface UptimeSummaryProps {
} }
export const UptimeSummary = ({ uptime, interval }: UptimeSummaryProps) => { export const UptimeSummary = ({ uptime, interval }: UptimeSummaryProps) => {
const { t } = useLanguage();
return ( return (
<div className="flex items-center justify-between text-xs mt-1"> <div className="flex items-center justify-between text-xs mt-1">
<span className="text-muted-foreground"> <span className="text-muted-foreground">
{Math.round(uptime)}% uptime {Math.round(uptime)}% uptime
</span> </span>
<span className="text-xs text-muted-foreground"> <span className="text-xs text-muted-foreground">
{t('last20Checks')} Last 20 checks
</span> </span>
</div> </div>
); );
@@ -1,289 +1,46 @@
import React, { useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { format } from 'date-fns';
import {
Card, CardContent, CardDescription, CardHeader, CardTitle,
} from "@/components/ui/card";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
import { Github, FileText, Twitter, MessageCircle, Code2, ServerIcon, FolderOpen, Database, CheckCircle } from "lucide-react"; import {
Github, FileText, Twitter, MessageCircle, Code2, ServerIcon,
} from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { useLanguage } from "@/contexts/LanguageContext"; import { useLanguage } from "@/contexts/LanguageContext";
import { useTheme } from "@/contexts/ThemeContext"; import { useTheme } from "@/contexts/ThemeContext";
import { useSystemSettings } from "@/hooks/useSystemSettings"; import { useSystemSettings } from "@/hooks/useSystemSettings";
import { pb } from "@/lib/pocketbase";
import { toast } from "@/components/ui/use-toast";
export const AboutSystem: React.FC = () => { export const AboutSystem: React.FC = () => {
const { t } = useLanguage(); const { t } = useLanguage();
const { theme } = useTheme(); const { theme } = useTheme();
const { systemName } = useSystemSettings(); const { systemName } = useSystemSettings();
const [isImporting, setIsImporting] = useState(false);
const [mergeFields, setMergeFields] = useState(true);
const [importResult, setImportResult] = useState<{
success: boolean;
created: number;
updated: number;
skipped: number;
} | null>(null);
// Helper function to check if a collection is a system collection const [version, setVersion] = useState<string>('...');
const isSystemCollection = (name: string): boolean => { const [releaseDate, setReleaseDate] = useState<string>('...');
return name.startsWith('_') || ['users'].includes(name);
};
// Helper function to validate collection schema useEffect(() => {
const validateCollectionSchema = (collection: any): string | null => { const fetchLatestRelease = async () => {
if (!collection.name) return "Collection name is required"; try {
if (typeof collection.name !== 'string') return "Collection name must be a string"; const res = await fetch('https://api.github.com/repos/operacle/checkcle/releases/latest');
if (!/^[a-z][a-z0-9_]*$/.test(collection.name)) { const data = await res.json();
return "Collection name must start with a letter and contain only lowercase letters, numbers, and underscores"; setVersion(data.tag_name || 'v1.x.x');
} setReleaseDate(data.published_at ? format(new Date(data.published_at), 'MMMM d, yyyy') : t('unknown'));
if (collection.name.length < 3 || collection.name.length > 32) { } catch (err) {
return "Collection name must be between 3 and 32 characters"; setVersion('v1.x.x');
} setReleaseDate(t('unknown'));
// Validate schema array if present
if (collection.schema && !Array.isArray(collection.schema)) {
return "Collection schema must be an array";
}
// Validate each field in the schema
if (collection.schema) {
for (const field of collection.schema) {
if (!field.name || typeof field.name !== 'string') {
return `Invalid field name in collection '${collection.name}'`;
}
if (!field.type || typeof field.type !== 'string') {
return `Invalid field type for '${field.name}' in collection '${collection.name}'`;
}
} }
} };
fetchLatestRelease();
return null; }, [t]);
};
const handleSchemaImport = async (schemaData: string) => {
if (!schemaData.trim()) {
toast({
title: "Error",
description: "No schema data provided",
variant: "destructive",
});
return;
}
try {
setIsImporting(true);
setImportResult(null);
// Parse the JSON to validate it
const collections = JSON.parse(schemaData);
if (!Array.isArray(collections)) {
throw new Error("Schema must be an array of collections");
}
// Check if user is authenticated as admin
if (!pb.authStore.isValid) {
throw new Error("Authentication required. Please log in as an admin.");
}
// Create/update collections one by one using PocketBase client
let successCount = 0;
let errorCount = 0;
let updatedCount = 0;
let skippedCount = 0;
const errors = [];
for (const collection of collections) {
try {
// Skip system collections
if (isSystemCollection(collection.name)) {
skippedCount++;
continue;
}
// Validate collection schema
const validationError = validateCollectionSchema(collection);
if (validationError) {
throw new Error(validationError);
}
// Check if collection already exists
const existingCollections = await pb.collections.getFullList();
const existingCollection = existingCollections.find(c => c.name === collection.name);
if (existingCollection) {
if (mergeFields) {
try {
// Get existing schema
const existingSchema = existingCollection.schema || [];
const newSchema = collection.schema || [];
// Merge schemas - add new fields, keep existing ones
const mergedSchema = [...existingSchema];
let fieldsAdded = 0;
for (const newField of newSchema) {
const existingFieldIndex = mergedSchema.findIndex(f => f.name === newField.name);
if (existingFieldIndex >= 0) {
} else {
// Add new field
mergedSchema.push(newField);
fieldsAdded++;
}
}
// Update the collection with merged schema
const updateData = {
...collection,
schema: mergedSchema
};
const updatedCollection = await pb.collections.update(existingCollection.id, updateData);
updatedCount++;
} catch (mergeError) {
throw new Error(`Failed to merge fields: ${mergeError.message || mergeError}`);
}
} else {
skippedCount++;
continue;
}
} else {
// Create new collection
try {
const newCollection = await pb.collections.create(collection);
successCount++;
} catch (createError) {
// Extract more detailed error information
let errorMessage = createError.message || createError;
if (createError.data) {
// Try to extract field-specific errors
if (createError.data.data) {
const fieldErrors = Object.entries(createError.data.data).map(([field, msgs]) =>
`${field}: ${Array.isArray(msgs) ? msgs.join(', ') : msgs}`
).join('; ');
if (fieldErrors) {
errorMessage += ` - Field errors: ${fieldErrors}`;
}
}
}
throw new Error(`Failed to create collection: ${errorMessage}`);
}
}
} catch (error) {
errorCount++;
const errorMsg = `Failed to process collection '${collection.name}': ${error.message || error}`;
errors.push(errorMsg);
}
}
// Set import result for display
setImportResult({
success: successCount + updatedCount > 0,
created: successCount,
updated: updatedCount,
skipped: skippedCount
});
// Show results
const totalProcessed = successCount + updatedCount;
if (totalProcessed > 0 || skippedCount > 0) {
let description = '';
if (totalProcessed > 0) {
description = `Successfully processed ${totalProcessed} collection(s)`;
if (successCount > 0) description += ` (${successCount} created)`;
if (updatedCount > 0) description += ` (${updatedCount} updated)`;
}
if (skippedCount > 0) {
if (description) description += `, `;
description += `${skippedCount} skipped (system collections or existing)`;
}
if (errorCount > 0) description += `. ${errorCount} failed.`;
toast({
title: "Import Complete",
description,
variant: totalProcessed > errorCount ? "default" : "destructive",
});
} else if (errorCount > 0) {
toast({
title: "Import Failed",
description: "No collections were processed successfully.",
variant: "destructive",
});
} else {
toast({
title: "No Changes",
description: "All collections already exist and no changes were made.",
variant: "default",
});
}
if (errors.length > 0) {
// Show detailed errors for debugging
if (errors.length <= 3) {
toast({
title: "Detailed Errors",
description: errors.join('; '),
variant: "destructive",
});
}
}
} catch (error) {
toast({
title: "Import Failed",
description: error instanceof Error ? error.message : "Failed to import schema",
variant: "destructive",
});
setImportResult({
success: false,
created: 0,
updated: 0,
skipped: 0
});
} finally {
setIsImporting(false);
}
};
const handleLoadLocalSchema = async () => {
try {
setIsImporting(true);
setImportResult(null);
const response = await fetch('/upload/data/pb_schema_latest.json');
if (!response.ok) {
throw new Error(`Failed to load local schema: ${response.status} ${response.statusText}`);
}
const schemaText = await response.text();
// Validate that it's valid JSON
JSON.parse(schemaText);
// Directly import the schema
await handleSchemaImport(schemaText);
} catch (error) {
toast({
title: "Import Failed",
description: error instanceof Error ? error.message : "Failed to load and import local schema file",
variant: "destructive",
});
setImportResult({
success: false,
created: 0,
updated: 0,
skipped: 0
});
setIsImporting(false);
}
};
return ( return (
<div className="space-y-6 animate-fade-in"> <div className="space-y-6 animate-fade-in">
<div> <div>
<h1 className="text-3xl font-bold tracking-tight">{t('aboutSystem')}</h1> <h1 className="text-3xl font-bold tracking-tight">{t('aboutSystem')}</h1>
<p className="text-muted-foreground text-base leading-relaxed mt-2">
</p>
</div> </div>
<Separator /> <Separator />
@@ -301,7 +58,7 @@ export const AboutSystem: React.FC = () => {
<div className="flex flex-col space-y-3 pt-2"> <div className="flex flex-col space-y-3 pt-2">
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
<span className="text-muted-foreground">{t('systemVersion')}</span> <span className="text-muted-foreground">{t('systemVersion')}</span>
<span className="text-foreground font-medium">{t('version')} 1.5.1</span> <span className="text-foreground font-medium">{version}</span>
</div> </div>
<Separator className="my-1" /> <Separator className="my-1" />
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
@@ -311,7 +68,7 @@ export const AboutSystem: React.FC = () => {
<Separator className="my-1" /> <Separator className="my-1" />
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
<span className="text-muted-foreground">{t('releasedOn')}</span> <span className="text-muted-foreground">{t('releasedOn')}</span>
<span className="text-foreground font-medium">Auguest 21, 2025</span> <span className="text-foreground font-medium">{releaseDate}</span>
</div> </div>
</div> </div>
</div> </div>
@@ -324,7 +81,9 @@ export const AboutSystem: React.FC = () => {
<Code2 className={`h-5 w-5 ${theme === 'dark' ? 'text-emerald-400' : 'text-emerald-600'}`} /> <Code2 className={`h-5 w-5 ${theme === 'dark' ? 'text-emerald-400' : 'text-emerald-600'}`} />
<span>{t('links')}</span> <span>{t('links')}</span>
</CardTitle> </CardTitle>
<CardDescription className="font-medium text-base">{systemName || 'CheckCle'} {t('resources').toLowerCase()}</CardDescription> <CardDescription className="font-medium text-base">
{systemName || 'CheckCle'} {t('resources').toLowerCase()}
</CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-4 pt-6"> <CardContent className="space-y-4 pt-6">
<div className="grid grid-cols-1 gap-3"> <div className="grid grid-cols-1 gap-3">
@@ -348,88 +107,6 @@ export const AboutSystem: React.FC = () => {
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
<Separator />
<Card className="overflow-hidden border border-border transition-all duration-300 hover:shadow-md">
<CardHeader className="bg-muted/50 pb-4">
<CardTitle className="flex items-center gap-2">
<Database className={`h-5 w-5 ${theme === 'dark' ? 'text-blue-400' : 'text-blue-600'}`} />
<span>{t('updateSchema')}</span>
</CardTitle>
<CardDescription className="font-medium text-base">{t('updateSchemaDesc')}</CardDescription>
</CardHeader>
<CardContent className="space-y-4 pt-6">
<div className="space-y-3">
<div className="flex items-center space-x-2">
<Checkbox
id="merge-fields"
checked={mergeFields}
onCheckedChange={(checked) => setMergeFields(checked === true)}
/>
<Label htmlFor="merge-fields" className="text-sm font-medium">
{t('mergeFieldsLabel')}
</Label>
</div>
</div>
<div className="flex gap-2 flex-wrap">
<Button
onClick={handleLoadLocalSchema}
disabled={isImporting}
className={`flex items-center gap-2 transition-all duration-200 ${
isImporting ? 'animate-pulse' : ''
}`}
>
<Database className={`h-4 w-4 ${isImporting ? 'animate-spin' : ''}`} />
{isImporting ? t('importing') : t('clickToUpdateSchema')}
</Button>
</div>
{importResult && (
<div className={`mt-4 p-4 rounded-lg border ${
importResult.success
? 'bg-green-50 border-green-200 dark:bg-green-900/20 dark:border-green-800'
: 'bg-red-50 border-red-200 dark:bg-red-900/20 dark:border-red-800'
} animate-in fade-in-0 slide-in-from-bottom-2 duration-300`}>
<div className="flex items-center gap-2">
<CheckCircle className={`h-5 w-5 ${
importResult.success
? 'text-green-600 dark:text-green-400'
: 'text-red-600 dark:text-red-400'
}`} />
<span className={`font-medium ${
importResult.success
? 'text-green-800 dark:text-green-200'
: 'text-red-800 dark:text-red-200'
}`}>
{importResult.success ? t('importSuccessful') : t('importFailed')}
</span>
</div>
<div className={`mt-2 text-sm ${
importResult.success
? 'text-green-700 dark:text-green-300'
: 'text-red-700 dark:text-red-300'
}`}>
{importResult.created > 0 && t('collectionsCreatedCount').replace('{count}', String(importResult.created))}
{importResult.updated > 0 && (importResult.created > 0 ? ', ' : '') + t('collectionsUpdatedCount').replace('{count}', String(importResult.updated))}
{importResult.skipped > 0 && ((importResult.created > 0 || importResult.updated > 0) ? ', ' : '') + t('collectionsSkippedCount').replace('{count}', String(importResult.skipped))}
</div>
</div>
)}
<div className="text-sm text-muted-foreground">
<p className="mb-2">
<strong>{t('instructions')}:</strong>
</p>
<ul className="list-disc list-inside space-y-1 ml-2">
<li><strong>{t('mergeFields')}:</strong> {t('instructionsMergeFields')}</li>
<li>{t('instructionsCollections')}</li>
<li>{t('instructionsImportAuth')}</li>
</ul>
</div>
</CardContent>
</Card>
</div> </div>
); );
}; };
@@ -16,7 +16,6 @@ import { ScrollArea } from "@/components/ui/scroll-area";
import { TemplateType, templateTypeConfigs } from "@/services/templateService"; import { TemplateType, templateTypeConfigs } from "@/services/templateService";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import {z} from "zod";
interface TemplateDialogProps { interface TemplateDialogProps {
open: boolean; open: boolean;
@@ -82,7 +81,6 @@ export const TemplateDialog: React.FC<TemplateDialogProps> = ({
}; };
const renderPlaceholderGuide = () => { const renderPlaceholderGuide = () => {
const config = templateTypeConfigs[selectedTemplateType]; const config = templateTypeConfigs[selectedTemplateType];
if (!config) return null; if (!config) return null;
@@ -52,6 +52,7 @@ const DataRetentionSettings = () => {
setLastCleanup(result.lastCleanup); setLastCleanup(result.lastCleanup);
} }
} catch (error) { } catch (error) {
console.error("Error loading retention settings:", error);
toast({ toast({
title: "Error", title: "Error",
description: "Failed to load retention settings", description: "Failed to load retention settings",
@@ -71,6 +72,7 @@ const DataRetentionSettings = () => {
description: "Data retention settings have been updated", description: "Data retention settings have been updated",
}); });
} catch (error) { } catch (error) {
console.error("Error saving retention settings:", error);
toast({ toast({
title: "Error", title: "Error",
description: "Failed to save retention settings", description: "Failed to save retention settings",
@@ -94,6 +96,7 @@ const DataRetentionSettings = () => {
// Reload settings to get updated last cleanup time // Reload settings to get updated last cleanup time
await loadSettings(); await loadSettings();
} catch (error) { } catch (error) {
console.error("Error during uptime cleanup:", error);
toast({ toast({
title: "Error", title: "Error",
description: "Failed to perform uptime data cleanup", description: "Failed to perform uptime data cleanup",
@@ -117,6 +120,7 @@ const DataRetentionSettings = () => {
// Reload settings to get updated last cleanup time // Reload settings to get updated last cleanup time
await loadSettings(); await loadSettings();
} catch (error) { } catch (error) {
console.error("Error during server cleanup:", error);
toast({ toast({
title: "Error", title: "Error",
description: "Failed to perform server data cleanup", description: "Failed to perform server data cleanup",
@@ -140,6 +144,7 @@ const DataRetentionSettings = () => {
// Reload settings to get updated last cleanup time // Reload settings to get updated last cleanup time
await loadSettings(); await loadSettings();
} catch (error) { } catch (error) {
console.error("Error during manual cleanup:", error);
toast({ toast({
title: "Error", title: "Error",
description: "Failed to perform database cleanup", description: "Failed to perform database cleanup",
@@ -158,14 +163,14 @@ const DataRetentionSettings = () => {
<CardHeader> <CardHeader>
<CardTitle className="flex items-center gap-2"> <CardTitle className="flex items-center gap-2">
<Database className="h-5 w-5" /> <Database className="h-5 w-5" />
{t("dataRetention")} {t("dataRetention", "settings")}
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<Alert className="border-blue-200 bg-blue-50 dark:bg-blue-950 dark:border-blue-800"> <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" /> <AlertTriangle className="h-5 w-5 text-blue-600 dark:text-blue-400" />
<AlertDescription className="text-blue-700 dark:text-blue-300"> <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> </AlertDescription>
</Alert> </Alert>
</CardContent> </CardContent>
@@ -178,7 +183,7 @@ const DataRetentionSettings = () => {
return ( return (
<div className="p-4 flex items-center justify-center"> <div className="p-4 flex items-center justify-center">
<Loader2 className="h-6 w-6 animate-spin mr-2" /> <Loader2 className="h-6 w-6 animate-spin mr-2" />
{t("loadingRetentionSettings")} Loading retention settings...
</div> </div>
); );
} }
@@ -189,61 +194,49 @@ const DataRetentionSettings = () => {
<CardHeader> <CardHeader>
<CardTitle className="flex items-center gap-2"> <CardTitle className="flex items-center gap-2">
<Database className="h-5 w-5" /> <Database className="h-5 w-5" />
{t("dataRetention")} Data Retention Settings
</CardTitle> </CardTitle>
<CardDescription> <CardDescription>
{t("dataRetentionDescription")} Configure how long monitoring data is kept in the system
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-6"> <CardContent className="space-y-6">
<div className="space-y-4"> <div className="space-y-4">
<div> <div>
<Label htmlFor="uptimeRetention">{t("uptimeRetentionLabel")}</Label> <Label htmlFor="uptimeRetention">Uptime Monitoring Retention (days)</Label>
<Input <Input
id="uptimeRetention" id="uptimeRetention"
type="number" type="number"
min="1" min="1"
max="365" max="365"
value={settings.uptimeRetentionDays} value={settings.uptimeRetentionDays}
onChange={(e) => { onChange={(e) => setSettings(prev => ({
const value = e.target.value; ...prev,
if (value === '' || isNaN(Number(value))) { uptimeRetentionDays: parseInt(e.target.value) || 30
return; }))}
}
setSettings(prev => ({
...prev,
uptimeRetentionDays: Number(value)
}));
}}
className="mt-1" className="mt-1"
/> />
<p className="text-sm text-muted-foreground 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> </p>
</div> </div>
<div> <div>
<Label htmlFor="serverRetention">{t("serverRetentionLabel")}</Label> <Label htmlFor="serverRetention">Server Monitoring Retention (days)</Label>
<Input <Input
id="serverRetention" id="serverRetention"
type="number" type="number"
min="1" min="1"
max="365" max="365"
value={settings.serverRetentionDays} value={settings.serverRetentionDays}
onChange={(e) => { onChange={(e) => setSettings(prev => ({
const value = e.target.value; ...prev,
if (value === '' || isNaN(Number(value))) { serverRetentionDays: parseInt(e.target.value) || 30
return; }))}
}
setSettings(prev => ({
...prev,
serverRetentionDays: Number(value)
}));
}}
className="mt-1" className="mt-1"
/> />
<p className="text-sm text-muted-foreground 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> </p>
</div> </div>
</div> </div>
@@ -252,22 +245,68 @@ const DataRetentionSettings = () => {
<Alert> <Alert>
<Database className="h-4 w-4" /> <Database className="h-4 w-4" />
<AlertDescription> <AlertDescription>
{t("lastCleanup")}: {new Date(lastCleanup).toLocaleString()} Last automatic cleanup: {new Date(lastCleanup).toLocaleString()}
</AlertDescription> </AlertDescription>
</Alert> </Alert>
)} )}
</CardContent> </CardContent>
<CardFooter className="flex justify-end"> <CardFooter className="flex flex-col gap-4">
<Button <div className="flex flex-wrap gap-2 w-full">
onClick={handleSave} <Button
disabled={isSaving} variant="outline"
className="flex items-center gap-2" onClick={handleUptimeShrink}
> disabled={isUptimeShrinking}
{isSaving ? ( className="flex items-center gap-2"
<Loader2 className="h-4 w-4 animate-spin" /> >
) : null} {isUptimeShrinking ? (
{t("save")} <Loader2 className="h-4 w-4 animate-spin" />
</Button> ) : (
<Globe className="h-4 w-4" />
)}
Shrink Uptime Data
</Button>
<Button
variant="outline"
onClick={handleServerShrink}
disabled={isServerShrinking}
className="flex items-center gap-2"
>
{isServerShrinking ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Server className="h-4 w-4" />
)}
Shrink Server Data
</Button>
<Button
variant="outline"
onClick={handleFullShrink}
disabled={isFullShrinking}
className="flex items-center gap-2"
>
{isFullShrinking ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Trash2 className="h-4 w-4" />
)}
Full Database Shrink
</Button>
</div>
<div className="flex justify-end w-full">
<Button
onClick={handleSave}
disabled={isSaving}
className="flex items-center gap-2"
>
{isSaving ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : null}
Save Changes
</Button>
</div>
</CardFooter> </CardFooter>
</Card> </Card>
</div> </div>
@@ -143,7 +143,7 @@ const GeneralSettingsPanel: React.FC<GeneralSettingsPanelProps> = () => {
<Alert className="border-blue-200 bg-blue-50 dark:bg-blue-950 dark:border-blue-800"> <Alert className="border-blue-200 bg-blue-50 dark:bg-blue-950 dark:border-blue-800">
<ShieldAlert className="h-5 w-5 text-blue-600 dark:text-blue-400" /> <ShieldAlert className="h-5 w-5 text-blue-600 dark:text-blue-400" />
<AlertDescription className="text-blue-700 dark:text-blue-300"> <AlertDescription className="text-blue-700 dark:text-blue-300">
<span className="font-medium">{t("permissionNotice")}</span> {t("permissionNoticeAddUser")} <span className="font-medium">Permission Notice:</span> 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.
</AlertDescription> </AlertDescription>
</Alert> </Alert>
</CardContent> </CardContent>
@@ -153,11 +153,11 @@ const GeneralSettingsPanel: React.FC<GeneralSettingsPanelProps> = () => {
} }
if (isLoading) { if (isLoading) {
return <div className="p-4">{t("loadingSettings")}</div>; return <div className="p-4">Loading settings...</div>;
} }
if (error) { if (error) {
return <div className="p-4 text-red-500">{t("loadingSettingsError")}</div>; return <div className="p-4 text-red-500">Error loading settings</div>;
} }
return ( return (
@@ -126,6 +126,15 @@ const TestEmailDialog: React.FC<TestEmailDialogProps> = ({
<Mail className="h-5 w-5" /> <Mail className="h-5 w-5" />
{t("sendTestEmail", "settings")} {t("sendTestEmail", "settings")}
</DialogTitle> </DialogTitle>
<Button
variant="ghost"
size="icon"
className="absolute right-4 top-4"
onClick={handleClose}
disabled={isLoading}
>
<X className="h-4 w-4" />
</Button>
</DialogHeader> </DialogHeader>
<div className="space-y-4 py-4"> <div className="space-y-4 py-4">
@@ -194,7 +203,9 @@ const TestEmailDialog: React.FC<TestEmailDialogProps> = ({
{/* Info message */} {/* Info message */}
<Alert> <Alert>
<AlertCircle className="h-4 w-4" /> <AlertCircle className="h-4 w-4" />
<AlertDescription>{t("testEmailAlert", "settings")}</AlertDescription> <AlertDescription>
This will send a test email using your configured SMTP settings. Make sure SMTP is properly configured first.
</AlertDescription>
</Alert> </Alert>
</div> </div>
@@ -212,7 +223,7 @@ const TestEmailDialog: React.FC<TestEmailDialogProps> = ({
) : ( ) : (
<Mail className="h-4 w-4" /> <Mail className="h-4 w-4" />
)} )}
{isLoading ? t("sending", "settings") : t("send", "settings")} {isLoading ? t("sending", "settings") : t("send", "common")}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
@@ -27,7 +27,6 @@ import { Switch } from "@/components/ui/switch";
import { Loader2, Copy } from "lucide-react"; import { Loader2, Copy } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { toast } from "@/hooks/use-toast"; import { toast } from "@/hooks/use-toast";
import { useLanguage } from "@/contexts/LanguageContext";
interface NotificationChannelDialogProps { interface NotificationChannelDialogProps {
open: boolean; open: boolean;
@@ -35,10 +34,9 @@ interface NotificationChannelDialogProps {
editingConfig: AlertConfiguration | null; editingConfig: AlertConfiguration | null;
} }
const baseSchema = z.object({ const baseSchema = z.object({
notify_name: z.string().min(1, "Name is required"), 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", "webhook"]),
enabled: z.boolean().default(true), enabled: z.boolean().default(true),
service_id: z.string().default("global"), service_id: z.string().default("global"),
template_id: z.string().optional(), template_id: z.string().optional(),
@@ -80,43 +78,12 @@ const emailSchema = baseSchema.extend({
smtp_password: z.string().min(1, "SMTP password is required"), smtp_password: z.string().min(1, "SMTP password is required"),
}); });
const ntfySchema = baseSchema.extend({
notification_type: z.literal("ntfy"),
ntfy_endpoint: z.string().url("Must be a valid NTFY endpoint URL"),
api_token: z.string().optional(),
});
const pushoverSchema = baseSchema.extend({
notification_type: z.literal("pushover"),
api_token: z.string().min(1, "API token is required"),
user_key: z.string().min(1, "User key is required"),
});
const notifiarrSchema = baseSchema.extend({
notification_type: z.literal("notifiarr"),
api_token: z.string().min(1, "API token is required"),
channel_id: z.string().min(1, "Channel ID is required"),
});
const webhookSchema = baseSchema.extend({ const webhookSchema = baseSchema.extend({
notification_type: z.literal("webhook"), notification_type: z.literal("webhook"),
webhook_url: z.string().url("Must be a valid URL"), webhook_url: z.string().url("Must be a valid URL"),
webhook_payload_template: z.string().optional(), webhook_payload_template: z.string().optional(),
}); });
const gotifySchema = baseSchema.extend({
notification_type: z.literal("gotify"),
api_token: z.string().min(1, "API token is required"),
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", [ const formSchema = z.discriminatedUnion("notification_type", [
telegramSchema, telegramSchema,
discordSchema, discordSchema,
@@ -124,12 +91,7 @@ const formSchema = z.discriminatedUnion("notification_type", [
signalSchema, signalSchema,
googleChatSchema, googleChatSchema,
emailSchema, emailSchema,
ntfySchema, webhookSchema
pushoverSchema,
notifiarrSchema,
gotifySchema,
webhookSchema,
matrixSchema,
]); ]);
type FormValues = z.infer<typeof formSchema>; type FormValues = z.infer<typeof formSchema>;
@@ -171,43 +133,12 @@ const notificationTypeOptions = [
description: "Send notifications via email", description: "Send notifications via email",
icon: "/upload/notification/email.png" icon: "/upload/notification/email.png"
}, },
{
value: "ntfy",
label: "NTFY",
description: "Send notifications via NTFY push service",
icon: "/upload/notification/ntfy.png"
},
{
value: "pushover",
label: "Pushover",
description: "Send push notifications via Pushover",
icon: "/upload/notification/pushover.png"
},
{
value: "notifiarr",
label: "Notifiarr",
description: "Send notifications via Notifiarr",
icon: "/upload/notification/notifiarr.png"
},
{
value: "gotify",
label: "Gotify",
description: "Send push notifications via Gotify",
icon: "/upload/notification/gotify.png"
},
{ {
value: "webhook", value: "webhook",
label: "Webhook", label: "Webhook",
description: "Send notifications to custom webhook", description: "Send notifications to custom webhook",
icon: "/upload/notification/webhook.png" icon: "/upload/notification/webhook.png"
}, },
{
value: "matrix",
label: "Matrix",
description: "Send notifications to a Matrix chat room",
icon: "/upload/notification/matrix.png"
},
]; ];
const webhookPayloadTemplates = { const webhookPayloadTemplates = {
@@ -261,7 +192,6 @@ export const NotificationChannelDialog = ({
onClose, onClose,
editingConfig editingConfig
}: NotificationChannelDialogProps) => { }: NotificationChannelDialogProps) => {
const { t } = useLanguage();
const isEditing = !!editingConfig; const isEditing = !!editingConfig;
const form = useForm<FormValues>({ const form = useForm<FormValues>({
resolver: zodResolver(formSchema), resolver: zodResolver(formSchema),
@@ -340,7 +270,7 @@ export const NotificationChannelDialog = ({
<DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto"> <DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
<DialogHeader> <DialogHeader>
<DialogTitle> <DialogTitle>
{isEditing ? t("editChannel") : t("addChannelDialog")} {isEditing ? "Edit Notification Channel" : "Add Notification Channel"}
</DialogTitle> </DialogTitle>
</DialogHeader> </DialogHeader>
@@ -351,12 +281,12 @@ export const NotificationChannelDialog = ({
name="notify_name" name="notify_name"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("channelName")}</FormLabel> <FormLabel>Channel Name</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t("channelNamePlaceholder")} {...field} /> <Input placeholder="My Notification Channel" {...field} />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
{t("channelNameDesc")} A name to identify this notification channel
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -368,11 +298,11 @@ export const NotificationChannelDialog = ({
name="notification_type" name="notification_type"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("channelType")}</FormLabel> <FormLabel>Channel Type</FormLabel>
<Select onValueChange={field.onChange} value={field.value}> <Select onValueChange={field.onChange} value={field.value}>
<FormControl> <FormControl>
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder={t("selectType")} /> <SelectValue placeholder="Select notification type" />
</SelectTrigger> </SelectTrigger>
</FormControl> </FormControl>
<SelectContent> <SelectContent>
@@ -385,8 +315,8 @@ export const NotificationChannelDialog = ({
className="w-5 h-5 object-contain" className="w-5 h-5 object-contain"
/> />
<div className="flex flex-col"> <div className="flex flex-col">
<span className="font-medium">{t(option.value)}</span> <span className="font-medium">{option.label}</span>
<span className="text-xs text-muted-foreground">{t(option.description)}</span> <span className="text-xs text-muted-foreground">{option.description}</span>
</div> </div>
</div> </div>
</SelectItem> </SelectItem>
@@ -405,12 +335,12 @@ export const NotificationChannelDialog = ({
name="telegram_chat_id" name="telegram_chat_id"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("telegramChatId")}</FormLabel> <FormLabel>Chat ID</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t("telegramChatIdPlaceholder")} {...field} /> <Input placeholder="Telegram Chat ID" {...field} />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
{t("telegramChatIdDesc")} The Telegram chat ID to send notifications to
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -421,12 +351,12 @@ export const NotificationChannelDialog = ({
name="bot_token" name="bot_token"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("botToken")}</FormLabel> <FormLabel>Bot Token</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t("botTokenPlaceholder")} {...field} type="password" /> <Input placeholder="Telegram Bot Token" {...field} type="password" />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
{t("botTokenDesc")} Your Telegram bot token from @BotFather
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -441,12 +371,12 @@ export const NotificationChannelDialog = ({
name="discord_webhook_url" name="discord_webhook_url"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("discordWebhookUrl")}</FormLabel> <FormLabel>Webhook URL</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t("discordWebhookUrlPlaceholder")} {...field} /> <Input placeholder="https://discord.com/api/webhooks/..." {...field} />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
{t("discordWebhookUrlDesc")} Discord webhook URL from your server settings
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -460,12 +390,12 @@ export const NotificationChannelDialog = ({
name="slack_webhook_url" name="slack_webhook_url"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("slackWebhookUrl")}</FormLabel> <FormLabel>Webhook URL</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t("slackWebhookUrlPlaceholder")} {...field} /> <Input placeholder="https://hooks.slack.com/services/..." {...field} />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
{t("slackWebhookUrlDesc")} Slack incoming webhook URL
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -480,12 +410,12 @@ export const NotificationChannelDialog = ({
name="signal_number" name="signal_number"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("signalNumber")}</FormLabel> <FormLabel>Signal Number</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t("signalNumberPlaceholder")} {...field} /> <Input placeholder="+1234567890" {...field} />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
{t("signalNumberDesc")} Signal phone number to send notifications to
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -496,12 +426,12 @@ export const NotificationChannelDialog = ({
name="signal_api_endpoint" name="signal_api_endpoint"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("signalApiEndpoint")}</FormLabel> <FormLabel>Signal API Endpoint</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t("signalApiEndpointPlaceholder")} {...field} /> <Input placeholder="https://your-signal-api.com/v2/send" {...field} />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
{t("signalApiEndpointDesc")} The Rest API endpoint for your Signal service
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -516,12 +446,12 @@ export const NotificationChannelDialog = ({
name="google_chat_webhook_url" name="google_chat_webhook_url"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("googleChatWebhookUrl")}</FormLabel> <FormLabel>Google Chat Webhook URL</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t("googleChatWebhookUrlPlaceholder")} {...field} /> <Input placeholder="https://chat.googleapis.com/v1/spaces/..." {...field} />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
{t("googleChatWebhookUrlDesc")} Google Chat webhook URL from your Google Chat space
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -536,12 +466,12 @@ export const NotificationChannelDialog = ({
name="email_address" name="email_address"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("emailAddress")}</FormLabel> <FormLabel>Email Address</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t("emailAddressPlaceholder")} {...field} type="email" /> <Input placeholder="notifications@example.com" {...field} type="email" />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
{t("emailAddressDesc")} Email address to send notifications to
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -552,12 +482,12 @@ export const NotificationChannelDialog = ({
name="email_sender_name" name="email_sender_name"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("emailSenderName")}</FormLabel> <FormLabel>Sender Name</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t("emailSenderNamePlaceholder")} {...field} /> <Input placeholder="Alert System" {...field} />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
{t("emailSenderNameDesc")} Display name for outgoing emails
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -569,9 +499,9 @@ export const NotificationChannelDialog = ({
name="smtp_server" name="smtp_server"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("smtpServer")}</FormLabel> <FormLabel>SMTP Server</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t("smtpServerPlaceholder")} {...field} /> <Input placeholder="smtp.gmail.com" {...field} />
</FormControl> </FormControl>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -582,9 +512,9 @@ export const NotificationChannelDialog = ({
name="smtp_port" name="smtp_port"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("smtpPort")}</FormLabel> <FormLabel>SMTP Port</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t("smtpPortPlaceholder")} {...field} /> <Input placeholder="587" {...field} />
</FormControl> </FormControl>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -596,160 +526,12 @@ export const NotificationChannelDialog = ({
name="smtp_password" name="smtp_password"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("smtpPassword")}</FormLabel> <FormLabel>SMTP Password</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t("smtpPasswordPlaceholder")} {...field} type="password" /> <Input placeholder="Enter your SMTP password" {...field} type="password" />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
{t("smtpPasswordDesc")} Password for authenticating with the SMTP server
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</>
)}
{notificationType === "ntfy" && (
<>
<FormField
control={form.control}
name="ntfy_endpoint"
render={({ field }) => (
<FormItem>
<FormLabel>{t("ntfyEndpoint")}</FormLabel>
<FormControl>
<Input placeholder={t("ntfyEndpointPlaceholder")} {...field} />
</FormControl>
<FormDescription>
{t("ntfyEndpointDesc")}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="api_token"
render={({ field }) => (
<FormItem>
<FormLabel>{t("apiTokenOptional")}</FormLabel>
<FormControl>
<Input placeholder={t("apiTokenPlaceholder")} {...field} type="password" />
</FormControl>
<FormDescription>
{t("apiTokenDesc")}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</>
)}
{notificationType === "pushover" && (
<>
<FormField
control={form.control}
name="api_token"
render={({ field }) => (
<FormItem>
<FormLabel>{t("apiToken")}</FormLabel>
<FormControl>
<Input placeholder={t("apiTokenPlaceholder")} {...field} type="password" />
</FormControl>
<FormDescription>
{t("apiTokenDesc")}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="user_key"
render={({ field }) => (
<FormItem>
<FormLabel>{t("pushoverUserKey")}</FormLabel>
<FormControl>
<Input placeholder={t("pushoverUserKeyPlaceholder")} {...field} />
</FormControl>
<FormDescription>
{t("pushoverUserKeyDesc")}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</>
)}
{notificationType === "notifiarr" && (
<>
<FormField
control={form.control}
name="api_token"
render={({ field }) => (
<FormItem>
<FormLabel>{t("apiToken")}</FormLabel>
<FormControl>
<Input placeholder={t("apiTokenPlaceholder")} {...field} type="password" />
</FormControl>
<FormDescription>
{t("apiTokenDesc")}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="channel_id"
render={({ field }) => (
<FormItem>
<FormLabel>{t("notifiarrChannelId")}</FormLabel>
<FormControl>
<Input placeholder={t("notifiarrChannelIdPlaceholder")} {...field} />
</FormControl>
<FormDescription>
{t("notifiarrChannelIdDesc")}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</>
)}
{notificationType === "gotify" && (
<>
<FormField
control={form.control}
name="api_token"
render={({ field }) => (
<FormItem>
<FormLabel>{t("apiToken")}</FormLabel>
<FormControl>
<Input placeholder={t("apiTokenPlaceholder")} {...field} type="password" />
</FormControl>
<FormDescription>
{t("apiTokenDesc")}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="server_url"
render={({ field }) => (
<FormItem>
<FormLabel>{t("gotifyServerUrl")}</FormLabel>
<FormControl>
<Input placeholder={t("gotifyServerUrlPlaceholder")} {...field} />
</FormControl>
<FormDescription>
{t("gotifyServerUrlDesc")}
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -765,12 +547,12 @@ export const NotificationChannelDialog = ({
name="webhook_url" name="webhook_url"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("webhookUrl")}</FormLabel> <FormLabel>Webhook URL</FormLabel>
<FormControl> <FormControl>
<Input placeholder={t("webhookUrlPlaceholder")} {...field} /> <Input placeholder="https://api.example.com/webhook" {...field} />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
{t("webhookUrlDesc")} The URL where webhook notifications will be sent
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -783,9 +565,10 @@ export const NotificationChannelDialog = ({
name="webhook_payload_template" name="webhook_payload_template"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>{t("payloadTemplate")}</FormLabel> <FormLabel>Payload Template (Optional)</FormLabel>
<FormDescription> <FormDescription>
{t("payloadTemplateDesc")} JSON template for the webhook payload. Leave empty to use default template.
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -794,15 +577,15 @@ export const NotificationChannelDialog = ({
<Card> <Card>
<CardHeader className="pb-3"> <CardHeader className="pb-3">
<CardTitle className="text-sm font-medium">{t("payloadTemplates")}</CardTitle> <CardTitle className="text-sm font-medium">Payload Templates</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="space-y-3"> <div className="space-y-3">
<div className="mt-4"> <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="grid grid-cols-2 md:grid-cols-4 gap-2 text-xs">
<div className="space-y-1"> <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"> <div className="space-y-0.5">
<code className="bg-muted px-1 rounded">${'{server_name}'}</code><br/> <code className="bg-muted px-1 rounded">${'{server_name}'}</code><br/>
<code className="bg-muted px-1 rounded">${'{cpu_usage}'}</code><br/> <code className="bg-muted px-1 rounded">${'{cpu_usage}'}</code><br/>
@@ -811,7 +594,7 @@ export const NotificationChannelDialog = ({
</div> </div>
</div> </div>
<div className="space-y-1"> <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"> <div className="space-y-0.5">
<code className="bg-muted px-1 rounded">${'{service_name}'}</code><br/> <code className="bg-muted px-1 rounded">${'{service_name}'}</code><br/>
<code className="bg-muted px-1 rounded">${'{response_time}'}</code><br/> <code className="bg-muted px-1 rounded">${'{response_time}'}</code><br/>
@@ -820,7 +603,7 @@ export const NotificationChannelDialog = ({
</div> </div>
</div> </div>
<div className="space-y-1"> <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"> <div className="space-y-0.5">
<code className="bg-muted px-1 rounded">${'{domain}'}</code><br/> <code className="bg-muted px-1 rounded">${'{domain}'}</code><br/>
<code className="bg-muted px-1 rounded">${'{expiry_date}'}</code><br/> <code className="bg-muted px-1 rounded">${'{expiry_date}'}</code><br/>
@@ -829,7 +612,7 @@ export const NotificationChannelDialog = ({
</div> </div>
</div> </div>
<div className="space-y-1"> <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"> <div className="space-y-0.5">
<code className="bg-muted px-1 rounded">${'{status}'}</code><br/> <code className="bg-muted px-1 rounded">${'{status}'}</code><br/>
<code className="bg-muted px-1 rounded">${'{time}'}</code><br/> <code className="bg-muted px-1 rounded">${'{time}'}</code><br/>
@@ -846,68 +629,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 <FormField
control={form.control} control={form.control}
name="enabled" name="enabled"
render={({ field }) => ( render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3"> <FormItem className="flex flex-row items-center justify-between rounded-lg border p-3">
<div className="space-y-0.5"> <div className="space-y-0.5">
<FormLabel>{t("enabled")}</FormLabel> <FormLabel>Enabled</FormLabel>
<FormDescription> <FormDescription>
{t("enabledDesc")} Enable or disable this notification channel
</FormDescription> </FormDescription>
</div> </div>
<FormControl> <FormControl>
@@ -922,11 +652,11 @@ export const NotificationChannelDialog = ({
<DialogFooter> <DialogFooter>
<Button variant="outline" type="button" onClick={handleClose}> <Button variant="outline" type="button" onClick={handleClose}>
{t("cancel")} Cancel
</Button> </Button>
<Button type="submit" disabled={isSubmitting}> <Button type="submit" disabled={isSubmitting}>
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />} {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{isEditing ? t("updateChannel") : t("createChannel")} {isEditing ? "Update Channel" : "Create Channel"}
</Button> </Button>
</DialogFooter> </DialogFooter>
</form> </form>
@@ -1,7 +1,6 @@
import { AlertConfiguration } from "@/services/alertConfigService"; import { AlertConfiguration } from "@/services/alertConfigService";
import { Bell, Edit, Trash2 } from "lucide-react"; import { Bell, Edit, Trash2 } from "lucide-react";
import { useState } from "react";
import { import {
Table, Table,
TableBody, TableBody,
@@ -34,40 +33,29 @@ export const NotificationChannelList = ({
onEdit, onEdit,
onDelete onDelete
}: NotificationChannelListProps) => { }: NotificationChannelListProps) => {
const [optimisticStates, setOptimisticStates] = useState<Record<string, boolean>>({});
const toggleEnabled = async (config: CombinedChannel) => { const toggleEnabled = async (config: CombinedChannel) => {
if (!config.id) return; if (!config.id) return;
const currentEnabled = typeof config.enabled === 'string' if (config.isWebhook) {
? config.enabled === "true" || config.enabled === "on" // Handle webhook toggle
: !!config.enabled; try {
const newEnabled = config.enabled ? "off" : "on";
// Apply optimistic update immediately
setOptimisticStates(prev => ({
...prev,
[config.id!]: !currentEnabled
}));
try {
if (config.isWebhook) {
// Handle webhook toggle
const newEnabled = currentEnabled ? "off" : "on";
await pb.collection('webhook').update(config.id, { await pb.collection('webhook').update(config.id, {
enabled: newEnabled enabled: newEnabled
}); });
} else { // Trigger refresh by calling onEdit with empty config
// Handle alert config toggle onEdit({} as AlertConfiguration);
await alertConfigService.updateAlertConfiguration(config.id, { } catch (error) {
enabled: !currentEnabled console.error("Error updating webhook:", error);
});
} }
} else {
// Handle alert config toggle
await alertConfigService.updateAlertConfiguration(config.id, {
enabled: !config.enabled
});
} catch (error) { // The parent component will refresh the list
setOptimisticStates(prev => ({ onEdit(config as AlertConfiguration);
...prev,
[config.id!]: currentEnabled
}));
} }
}; };
@@ -79,10 +67,7 @@ export const NotificationChannelList = ({
case "signal": return "Signal"; case "signal": return "Signal";
case "google_chat": return "Google Chat"; case "google_chat": return "Google Chat";
case "email": return "Email"; case "email": return "Email";
case "pushover": return "Pushover";
case "notifiarr": return "Notifiarr";
case "webhook": return "Webhook"; case "webhook": return "Webhook";
case "matrix": return "Matrix";
default: return type || "Unknown"; default: return type || "Unknown";
} }
}; };
@@ -103,8 +88,6 @@ export const NotificationChannelList = ({
return config.signal_number || ''; return config.signal_number || '';
case "email": case "email":
return config.email_address || ''; return config.email_address || '';
case "matrix":
return config.matrix_room_id || '';
default: default:
return ''; return '';
} }
@@ -145,14 +128,12 @@ export const NotificationChannelList = ({
<TableCell className="max-w-xs truncate text-sm text-muted-foreground"> <TableCell className="max-w-xs truncate text-sm text-muted-foreground">
{getChannelDetails(channel)} {getChannelDetails(channel)}
</TableCell> </TableCell>
<TableCell> <TableCell>
<Switch <Switch
checked={ checked={
channel.id && optimisticStates.hasOwnProperty(channel.id) typeof channel.enabled === 'string'
? optimisticStates[channel.id] ? channel.enabled === "true" || channel.enabled === "on"
: typeof channel.enabled === 'string' : !!channel.enabled
? channel.enabled === "true" || channel.enabled === "on"
: !!channel.enabled
} }
onCheckedChange={() => toggleEnabled(channel)} onCheckedChange={() => toggleEnabled(channel)}
/> />
@@ -166,7 +147,7 @@ export const NotificationChannelList = ({
variant="outline" variant="outline"
size="sm" size="sm"
onClick={() => onEdit(channel as AlertConfiguration)} onClick={() => onEdit(channel as AlertConfiguration)}
disabled={channel.isWebhook} disabled={channel.isWebhook} // Disable edit for webhooks for now
> >
<Edit className="h-4 w-4" /> <Edit className="h-4 w-4" />
</Button> </Button>
@@ -9,7 +9,6 @@ import { WebhookConfiguration, webhookService } from "@/services/webhookService"
import { NotificationChannelDialog } from "./NotificationChannelDialog"; import { NotificationChannelDialog } from "./NotificationChannelDialog";
import { NotificationChannelList } from "./NotificationChannelList"; import { NotificationChannelList } from "./NotificationChannelList";
import { pb } from "@/lib/pocketbase"; import { pb } from "@/lib/pocketbase";
import { useLanguage } from "@/contexts/LanguageContext";
interface CombinedChannel extends Partial<AlertConfiguration> { interface CombinedChannel extends Partial<AlertConfiguration> {
isWebhook?: boolean; isWebhook?: boolean;
@@ -19,7 +18,6 @@ interface CombinedChannel extends Partial<AlertConfiguration> {
} }
const NotificationSettings = () => { const NotificationSettings = () => {
const { t } = useLanguage();
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [alertConfigs, setAlertConfigs] = useState<AlertConfiguration[]>([]); const [alertConfigs, setAlertConfigs] = useState<AlertConfiguration[]>([]);
const [webhookConfigs, setWebhookConfigs] = useState<WebhookConfiguration[]>([]); const [webhookConfigs, setWebhookConfigs] = useState<WebhookConfiguration[]>([]);
@@ -128,13 +126,13 @@ const NotificationSettings = () => {
<CardHeader> <CardHeader>
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<CardTitle>{t("titleNotification")}</CardTitle> <CardTitle>Notification Settings</CardTitle>
<CardDescription> <CardDescription>
{t("descriptionChannelsServices")} Configure notification channels for your services
</CardDescription> </CardDescription>
</div> </div>
<Button onClick={handleAddNew}> <Button onClick={handleAddNew}>
<Plus className="mr-2 h-4 w-4" /> {t("addChannel")} <Plus className="mr-2 h-4 w-4" /> Add Channel
</Button> </Button>
</div> </div>
</CardHeader> </CardHeader>
@@ -146,15 +144,14 @@ const NotificationSettings = () => {
className="w-full" className="w-full"
> >
<TabsList className="mb-4"> <TabsList className="mb-4">
<TabsTrigger value="all">{t("all")}</TabsTrigger> <TabsTrigger value="all">All Channels</TabsTrigger>
<TabsTrigger value="telegram">{t("telegram")}</TabsTrigger> <TabsTrigger value="telegram">Telegram</TabsTrigger>
<TabsTrigger value="discord">{t("discord")}</TabsTrigger> <TabsTrigger value="discord">Discord</TabsTrigger>
<TabsTrigger value="slack">{t("slack")}</TabsTrigger> <TabsTrigger value="slack">Slack</TabsTrigger>
<TabsTrigger value="signal">{t("signal")}</TabsTrigger> <TabsTrigger value="signal">Signal</TabsTrigger>
<TabsTrigger value="google_chat">{t("googleChat")}</TabsTrigger> <TabsTrigger value="google_chat">Google Chat</TabsTrigger>
<TabsTrigger value="email">{t("email")}</TabsTrigger> <TabsTrigger value="email">Email</TabsTrigger>
<TabsTrigger value="webhook">{t("webhook")}</TabsTrigger> <TabsTrigger value="webhook">Webhook</TabsTrigger>
<TabsTrigger value="matrix">{t("matrix")}</TabsTrigger>
</TabsList> </TabsList>
<TabsContent value={currentTab} className="mt-0"> <TabsContent value={currentTab} className="mt-0">
@@ -1,3 +1,4 @@
import React from "react"; import React from "react";
import { import {
Dialog, Dialog,
@@ -16,9 +17,8 @@ import { Loader2, AlertCircle } from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert"; import { Alert, AlertDescription } from "@/components/ui/alert";
import UserTextField from "./form-fields/UserTextField"; import UserTextField from "./form-fields/UserTextField";
import UserToggleField from "./form-fields/UserToggleField"; import UserToggleField from "./form-fields/UserToggleField";
import UserProfilePictureField from "./form-fields/UserProfilePictureField";
import UserRoleField from "./form-fields/UserRoleField"; import UserRoleField from "./form-fields/UserRoleField";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
interface EditUserDialogProps { interface EditUserDialogProps {
isOpen: boolean; isOpen: boolean;
@@ -26,7 +26,6 @@ interface EditUserDialogProps {
form: UseFormReturn<any>; form: UseFormReturn<any>;
user: User | null; user: User | null;
onSubmit: (data: any) => void; onSubmit: (data: any) => void;
onImpersonate: (data: any) => void;
isSubmitting?: boolean; isSubmitting?: boolean;
error?: string | null; error?: string | null;
} }
@@ -37,19 +36,11 @@ const EditUserDialog = ({
form, form,
user, user,
onSubmit, onSubmit,
onImpersonate,
isSubmitting = false, isSubmitting = false,
error = null error = null
}: EditUserDialogProps) => { }: EditUserDialogProps) => {
if (!user) return null; 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 ( return (
<Dialog open={isOpen} onOpenChange={setIsOpen}> <Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogContent className="sm:max-w-[700px] w-[95vw] max-h-[95vh] flex flex-col"> <DialogContent className="sm:max-w-[700px] w-[95vw] max-h-[95vh] flex flex-col">
@@ -71,6 +62,7 @@ const EditUserDialog = ({
<Form {...form}> <Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4"> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<UserProfilePictureField control={form.control} />
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<UserTextField <UserTextField
@@ -110,23 +102,6 @@ const EditUserDialog = ({
/> />
</form> </form>
</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> </div>
</ScrollArea> </ScrollArea>
@@ -152,20 +127,6 @@ const EditUserDialog = ({
"Update User" "Update User"
)} )}
</Button> </Button>
<Button
type="button"
onClick={handleImpersonateClick}
disabled={isSubmitting}
>
{isSubmitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Impersonating...
</>
) : (
"Impersonate"
)}
</Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </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,19 +1,16 @@
import React from "react"; import React from "react";
import UserTable from "./UserTable"; import UserTable from "./UserTable";
import AddUserDialog from "./AddUserDialog"; import AddUserDialog from "./AddUserDialog";
import EditUserDialog from "./EditUserDialog"; import EditUserDialog from "./EditUserDialog";
import DeleteUserDialog from "./DeleteUserDialog"; import DeleteUserDialog from "./DeleteUserDialog";
import ImpersonationTokenDialog from "./ImpersonationTokenDialog";
import { useUserManagement } from "./hooks"; import { useUserManagement } from "./hooks";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion"; import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import { UserCog, Loader2, AlertCircle, Info, Users, ShieldAlert } from "lucide-react"; import { UserCog, Loader2, AlertCircle, Info, Users, ShieldAlert } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Alert, AlertDescription } from "@/components/ui/alert"; import { Alert, AlertDescription } from "@/components/ui/alert";
import { authService } from "@/services/authService"; import { authService } from "@/services/authService";
import { useLanguage } from "@/contexts/LanguageContext.tsx";
const UserManagement = () => { const UserManagement = () => {
const { t } = useLanguage();
const { const {
users, users,
loading, loading,
@@ -34,12 +31,8 @@ const UserManagement = () => {
handleDeletePrompt, handleDeletePrompt,
handleDeleteUser, handleDeleteUser,
onSubmit, onSubmit,
onImpersonate,
onAddUser, onAddUser,
fetchUsers, fetchUsers
impersonationToken,
isImpersonationTokenDialogOpen,
setIsImpersonationTokenDialogOpen,
} = useUserManagement(); } = useUserManagement();
// Get the current logged in user to check their role // Get the current logged in user to check their role
@@ -51,21 +44,21 @@ const UserManagement = () => {
<AccordionTrigger className="py-4 px-5 bg-card hover:bg-card/90 hover:no-underline rounded-lg text-lg font-medium flex items-center w-full"> <AccordionTrigger className="py-4 px-5 bg-card hover:bg-card/90 hover:no-underline rounded-lg text-lg font-medium flex items-center w-full">
<div className="flex items-center"> <div className="flex items-center">
<UserCog className="h-5 w-5 mr-2 text-green-500" /> <UserCog className="h-5 w-5 mr-2 text-green-500" />
<span>{t("userManagement")}</span> <span>User Management</span>
</div> </div>
</AccordionTrigger> </AccordionTrigger>
<AccordionContent className="p-4 pt-6 bg-background rounded-b-lg"> <AccordionContent className="p-4 pt-6 bg-background rounded-b-lg">
<div className="flex justify-between items-center mb-6"> <div className="flex justify-between items-center mb-6">
<h2 className="text-2xl font-bold">{t("userManagement")}</h2> <h2 className="text-2xl font-bold">User Management</h2>
{isSuperAdmin && <button onClick={() => setIsAddUserDialogOpen(true)} className="bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-md flex items-center"> {isSuperAdmin && <button onClick={() => setIsAddUserDialogOpen(true)} className="bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-md flex items-center">
<span className="mr-1">+</span> {t("addUser")} <span className="mr-1">+</span> Add User
</button>} </button>}
</div> </div>
{!isSuperAdmin && <Alert className="mb-6 border-blue-200 bg-blue-50 dark:bg-blue-950 dark:border-blue-800"> {!isSuperAdmin && <Alert className="mb-6 border-blue-200 bg-blue-50 dark:bg-blue-950 dark:border-blue-800">
<ShieldAlert className="h-5 w-5 text-blue-600 dark:text-blue-400" /> <ShieldAlert className="h-5 w-5 text-blue-600 dark:text-blue-400" />
<AlertDescription className="text-blue-700 dark:text-blue-300"> <AlertDescription className="text-blue-700 dark:text-blue-300">
<span className="font-medium">{t("permissionNotice")}</span> As an admin user, you have access to view and modify existing user details. However, only Super Admins have permission to create new user accounts. Contact your Super Admin if you need to add a new user. <span className="font-medium">Permission Notice:</span> As an admin user, you have access to view and modify existing user details. However, only Super Admins have permission to create new user accounts. Contact your Super Admin if you need to add a new user.
</AlertDescription> </AlertDescription>
</Alert>} </Alert>}
@@ -83,14 +76,7 @@ const UserManagement = () => {
<AddUserDialog isOpen={isAddUserDialogOpen && isSuperAdmin} setIsOpen={setIsAddUserDialogOpen} form={newUserForm} onSubmit={onAddUser} isSubmitting={isSubmitting} /> <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} /> <EditUserDialog isOpen={isDialogOpen} setIsOpen={setIsDialogOpen} form={form} user={currentUser} onSubmit={onSubmit} isSubmitting={isSubmitting} error={updateError} />
<ImpersonationTokenDialog
open={isImpersonationTokenDialogOpen}
onOpenChange={setIsImpersonationTokenDialogOpen}
token={impersonationToken}
impersonatedUserLabel={currentUser?.full_name || currentUser?.username}
/>
<DeleteUserDialog isOpen={isDeleting} setIsOpen={setIsDeleting} user={userToDelete} onDelete={handleDeleteUser} isDeleting={isSubmitting} /> <DeleteUserDialog isOpen={isDeleting} setIsOpen={setIsDeleting} user={userToDelete} onDelete={handleDeleteUser} isDeleting={isSubmitting} />
</AccordionContent> </AccordionContent>

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