137 Commits

Author SHA1 Message Date
Tola Leng 250f5bd62e Merge pull request #235 from narithum/develop
Add missing maintenance translations
2026-07-17 09:51:25 +07:00
Um Narith c484ac5567 Add missing maintenance translations 2026-07-17 00:38:10 +07:00
Tola Leng e2b20fef2e Merge pull request #224 from sebastiondev/fix/cwe922-pocketbase-authentica-a417
fix(auth): stop persisting PocketBase JWT in localStorage (CWE-922)
2026-05-04 23:01:18 +07:00
Sebastion 03cead6102 fix: avoid localStorage auth persistence 2026-04-30 20:32:20 +01:00
Tola Leng 5ac6f16fb5 Merge pull request #222 from cniry/alpine-icon
Alpine icon
2026-04-13 12:54:27 +07:00
Pavel Sieder 681efc4383 Alpine icon 2026-04-12 18:33:58 +02:00
Tola Leng 8740f35728 Merge pull request #219 from operacle/feature/multi-db-support
add new functionality and improve backend server structure
2026-03-09 17:39:17 +07:00
Tola Leng f5a985ff1e add new functionality and improve backend server structure
- Enhance server functionality and optimize backend code
- Add multi-database support (PostgreSQL, MySQL, SQLite)
2026-03-09 17:36:42 +07:00
Tola Leng 4b27b85038 Merge pull request #215 from MrSchneemann/feat/matrix-notification
feat: add Matrix chat notification support (#211)
2026-03-08 14:41:01 +07:00
MrSchneemann 463299fa73 feat(matrix): add HTML formatted messages with severity colors
Matrix notifications now send both a plain-text fallback and an
HTML formatted_body (org.matrix.custom.html) so Element and other
Matrix clients render rich, colored alerts:

- Down/failed/error → red (#E74C3C)
- Warning/expiring  → yellow (#F39C12)
- Maintenance/paused → orange (#E67E22)
- Up/resolved       → green (#2ECC71)
- Default/info      → blue (#3498DB)

Detail lines from the plain-text message are rendered as a <ul>
bullet list beneath the colored heading. Plain Body is preserved
for clients without HTML support.

Also includes resource type (CPU/DISK/etc.) in fallback server
alert messages to improve context.
2026-03-01 10:56:56 +01:00
MrSchneemann 91ceddc489 feat: add Matrix chat notification support (#211)
Implements native Matrix notification channel support, allowing users
to receive service alerts in any Matrix room via the Client-Server API.

Changes:
- server/service-operation/notification/matrix.go: new Matrix service
  implementing the NotificationService interface (PUT /_matrix/client/v3/...)
- server/service-operation/notification/types.go: add MatrixHomeserver,
  MatrixRoomID, MatrixAccessToken fields to AlertConfiguration
- server/service-operation/notification/manager.go: register MatrixService
- server/pb_migrations/1772200000_updated_alert_configurations_matrix.js:
  PocketBase migration adding matrix fields and notification_type value
- application: Matrix option in channel dialog with homeserver/room/token
  fields, tab filter, list display, type definitions and translations (en, km)
- application/public/upload/notification/matrix.png: Matrix channel icon
2026-03-01 10:48:01 +01:00
Tola Leng f2c338ced9 fix(security): enforce API authentication rules on collection (#214)
- Add authentication and authorization rules to prevent unauthorized access via REST API endpoints.
2026-02-27 00:17:45 +07:00
Tola Leng 9dbd267a22 docs: update progress and add implement multi-database support (PostgreSQL, MySQL, SQLite) 2026-02-15 16:16:58 +07:00
Tola Leng 2394243cb9 Merge pull request #207 from giriparus/impersonate-user
feat: implement user impersonation
2026-02-09 14:14:25 +07:00
giriparus bc38dba859 feat: implement user impersonation 2026-02-03 11:51:35 +05:30
Tola Leng 8f84fbf562 Update X platform URL 2026-01-31 15:38:44 +07:00
Tola Leng 6b8ee741b3 Fix server agent ID & token refresh when adding multiple agents (closes #165) 2026-01-24 21:16:10 +07:00
Tola Leng 370f613080 Fix hostname/IP validation to prevent whitespace input in the SSL and Create New Service form (closes #114) 2026-01-24 20:58:33 +07:00
Tola Leng 4f367b92da Fix responsive breakpoints and flex layout for sidebar menu 2026-01-13 01:28:57 +07:00
Tola Leng 6ab3be6fe4 Merge pull request #203 from aalhendi/fix/invalid-credentials-translation
fix: add missing invalidCredentials translation key
2026-01-05 03:19:43 +07:00
Abdulrazaq Alhendi 4221c4751a fix: add missing invalidCredentials translation key 2026-01-04 21:27:39 +03:00
Tola Leng a39b326f0e ci: disable frontend image build in build-frontend-image.yml 2025-12-02 00:45:44 +07:00
Tola Leng 84916f705a Refactor Menu Item to fix multi-line wrapping and spacing 2025-12-02 00:39:33 +07:00
Tola Leng e4e87abac5 Remove dockerfile of frontend from root directory 2025-11-28 17:01:41 +07:00
Tola Leng f528f6eaea reactor the Dockerfile.frontend to locate in Docker folder 2025-11-21 22:14:03 +07:00
Tola Leng b8966fe743 Merge pull request #193 from gnsworks/develop
Update : Japanese documents translation
2025-10-26 17:15:22 +07:00
gnsworks 2a4a6cea48 Update : Japanese documents translation 2025-10-25 21:15:22 +09:00
Tola Leng 3a3dc020fd refactor: update the Regional Monitoring Agent dialog structure with tabs and proper form layout. 2025-10-24 21:48:14 +07:00
Tola Leng ed5cff5026 refactor: Add the ENG translation string for the regional agent 2025-10-24 21:47:22 +07:00
Tola Leng bf45f896bd 🔐 docs(security): update version supported in Security terms 2025-10-23 02:23:19 +07:00
Tola Leng 00430b6cb7 refactor: update docker image for frontend development 2025-10-22 21:07:19 +07:00
Tola Leng feb65edee5 refactor: X url link in header 2025-10-22 21:06:32 +07:00
Tola Leng 04f125ac1e Merge pull request #188 from diptamahardhika/chore/dev-compose-persist-pb-data
feat(instance): multi-select & bulk delete; dev compose; persist pocketbase data volume in dev compose
2025-10-22 21:01:16 +07:00
Pradipta Mahardika 435694f694 chore(dev): persist pocketbase data volume in dev compose and docs 2025-10-16 23:43:31 +07:00
Tola Leng c33328f977 chore(project): Update development status and progress
- fix(server): regenerate Server Agent ID and Token after each agent creation without page refresh
2025-10-15 20:07:26 +07:00
Tola Leng 17e0d0a794 fix(server): regenerate Server Agent ID and Token after each agent creation without page refresh
- Previously, the Add Server Monitoring Agent dialog required a manual page refresh to show the new Server Agent ID and Server Token. This update automatically  generates and displays new credentials after each agent creation.
2025-10-13 14:57:51 +07:00
Tola Leng d408658b69 refactor: update database schema to align with UI date field changes 2025-10-11 20:57:09 +07:00
Tola Leng 682ce84ef7 docs: update contribution guidelines in CONTRIBUTING.md 2025-10-11 20:52:16 +07:00
Tola Leng 7392580db8 refactor: update database schema and migration files 2025-10-11 20:45:10 +07:00
Tola Leng ee5e66eb44 chore(project): Update development status and progress
- Fixed incorrect recovery time display in incident history
- Added a configuration option to delay downtime alert notifications
2025-10-11 20:24:47 +07:00
Tola Leng ed220b9a27 Merge pull request #178 from lyker189/develop
feat(i18n): localize frontend components and add missing translations
2025-10-02 22:31:03 +07:00
lyker189 b6ef4ff7a5 feat(i18n): localize frontend components and add missing translations
- Replaced hardcoded UI strings with translation keys across frontend files
- Added and updated English(en) and Khmer(km) translation files for settings, notifications, and server components
- Improved localization and multi-language support throughout the frontend
2025-10-02 05:10:11 +07:00
Tola Leng a4364936e3 style(sidebar): update menu items to use normal font weight 2025-10-01 22:59:21 +07:00
Tola Leng f5a8d989cc fix(ui): make "Rows per page" label display on a single line 2025-10-01 22:46:01 +07:00
Tola Leng 2e2df30b85 docs(readme): add JetBrains as a community supporter 2025-10-01 15:26:50 +07:00
Tola Leng 498b26dbd5 chore(project): Update development status and progress 2025-09-29 15:38:03 +07:00
Tola Leng 79fda8105f refactor: profile picture selection
- Removed profile picture selection UI from create/edit user forms. We will use the randome avatar instead.
2025-09-15 22:08:29 +07:00
Tola Leng 8d8e871b9f Fix: Enable/Disable notifications directly
- Make the status switch functional to toggle notifications directly from the notification channel list.
2025-09-15 21:04:10 +07:00
Tola Leng 6887dc291b Merge pull request #172 from EchtkPvL/develop
Fix YAML syntax error
2025-09-14 21:01:03 +07:00
Jonas Berner 29daddfc3b Fix YAML syntax error 2025-09-14 12:32:54 +02:00
Tola Leng 9c44ba6d7f Fix: Improve Uptime History Bar Display Speed Immediately
- Optimize the UptimeBar component to display uptime data immediately and reduce loading delays and background updates
2025-09-14 02:52:55 +07:00
Tola Leng c61a740725 feat: Add schema database update for release v1.6.0
- Applied new database schema updates.
- Ensured compatibility with data retention service and notification features.
- Keeps database in sync with new features introduced in v1.6.0.
2025-09-13 22:24:37 +07:00
Tola Leng a9d3d86394 chore(project): Update development status and progress 2025-09-13 22:22:08 +07:00
Tola Leng 9b0b2663ec refactor: Remove manual cleanup buttons from Data Retention Settings
- The three manual cleanup buttons have been removed from the dashboard.
- The data retention service now automatically runs once per day, cleaning up older data based on the configured retention settings.
2025-09-13 02:28:52 +07:00
Tola Leng 0b04034141 Merge pull request #159 from sqkkyzx/develop
feat(i18n): Refactored i18n function to support multiple parameter combinations
2025-09-12 15:57:24 +07:00
Tola Leng 0a635ab3aa feat: Integrate data retention service
- Implemented the data retention service in Go (service-operation) that manages cleanup of old records based on configured retention periods. The service runs once per day to ensure outdated data is removed automatically.
2025-09-11 22:43:07 +07:00
YiZixuan 175d2b6329 docs(README_zhcn): Update documentation content and sponsorship policy
- Update image links in the documentation
- Revise the sponsorship policy to no longer accept individual sponsorships, only enterprise-level collaborations
- Update the display method for supporters and partners
- Add Cloudflare and DigitalOcean as new partners
2025-09-10 00:19:14 +08:00
YiZixuan 3d6c4151b8 Merge branch 'operacle:develop' into develop 2025-09-09 22:40:37 +08:00
YiZixuan 5f893e3b20 refactor(i18n): Optimize service pagination internationalization copy
- Added service pagination related copy in English and Chinese translation files
- Updated type definitions to include new translation fields
- Modified the ServicesPagination component to use the newly added translation fields
2025-09-09 22:39:17 +08:00
YiZixuan 1296cf6a32 feat(i18n): Enhanced internationalization support with variable interpolation
- Refactored the `t` function in LanguageContext to support multiple parameter combinations
- Added variable interpolation feature, allowing variables in translated texts
- Optimized translation logic to improve accuracy and performance
- Enhanced type safety by using TypeScript generics to ensure correct typing
2025-09-09 22:38:43 +08:00
Tola Leng 31e5335aac docs(readme): deactivate donations, accept only infra support (cloud, domain, hosting) 2025-09-09 20:50:33 +07:00
YiZixuan b6d4ca5269 refactor(i18n): Optimize internationalization configuration and add new translation items
- Add internationalization support to the LoadingState component
- Implement internationalization translations in the Profile page
- Use internationalized text in the TestEmailDialog component
- Update English and Chinese translation files by adding new translation entries
2025-09-09 21:48:35 +08:00
Tola Leng 7e7522608a chore: deactivate GitHub donation 2025-09-09 20:39:09 +07:00
YiZixuan 43957f65d2 refactor(i18n): Added Chinese translations for Create Event and Maintenance
- Supplemented missing Chinese translations
- Added translation entries related to Create Event and Maintenance in both English and Chinese translation files
2025-09-09 21:21:34 +08:00
Tola Leng 09ece0a77e feat(auth): add token support for ntfy
- Updated the NTFY service to support API token authentication by adding Authorization Bearer header when api_token is provided.

Closes: #89
2025-09-09 20:21:20 +07:00
Tola Leng 06ba38aa15 feat: Add NTFY API token field for Token-based authentication to ntfy server
- Add the api_token field for NTFY notifications in both the dialog and service to save it to PB. NTFY schema to include api_token field.
2025-09-09 17:48:25 +07:00
Tola Leng abd878fe6c Merge pull request #158 from sqkkyzx/develop
refactory(i18n): Improve internationalization configuration and add new translations
2025-09-09 02:31:34 +07:00
YiZixuan f4d47bbd45 refactory(i18n): Add internationalization support for the service statistics card 2025-09-08 21:35:48 +08:00
YiZixuan b675fddc92 refactory(i18n): Added architecture import function translation for the "About" page
- Added translation items related to schema import in English, Chinese, and type definition files
- Replaced hard-coded text with new translation items in the AboutSystem component
2025-09-08 20:54:56 +08:00
YiZixuan 0a70ed2143 refactory(i18n): Added architecture import function translation for the "About" page
- Added translation items related to schema import in English, Chinese, and type definition files
- Replaced hard-coded text with new translation items in the AboutSystem component
2025-09-08 19:35:41 +08:00
YiZixuan 4e07279a54 refactory(i18n): Improve internationalization configuration and add new translations
- Added multiple new translation items
- Updated the two language files: en and zhcn
- Added type definitions for new translation items in types/services.ts
- Modified some components to use the new translation items
2025-09-08 14:18:05 +08:00
Tola Leng 020cdec912 chore(project): update development status and progress
- feat: Add server_url field for Gotify
- feat: Implement Gotify notification service
2025-09-06 20:44:28 +07:00
Tola Leng 4771b2ead0 feat: Implement Gotify notification service
- The Gotify notification functionality has been implemented. The alert configuration channel will now use the `api_token` and `server_url` field for send to the Gotify API endpoint.
2025-09-06 20:42:22 +07:00
Tola Leng 87c829e100 feat: Add Gotify to notification channels
- Add Gotify  as a new channel type in the notification settings. The Gotify channel will use the `api_token` and `server_url` field for API key storage in PB.
2025-09-06 19:33:14 +07:00
Tola Leng e6093f9fe2 Fix: Remove duplicate close button
- Removed the duplicate close button from the test email dialog.
2025-09-04 22:05:18 +07:00
Tola Leng 956786a859 feat: add SSL history and Notifiarr notification channel schema 2025-09-03 22:31:20 +07:00
Tola Leng 6a0169e4d8 chore(project): update development status and progress
- feat: Add channel_id field for Notifiarr
- feat: Implement Notifiarr notification service

Closes: #133
2025-09-03 22:05:11 +07:00
Tola Leng 92959945f3 feat: Implement Notifiarr notification service
- The Notifiarr notification functionality has been implemented. The alert configuration channel will now use the `api_token` and `channel_id` field for send to the Notifiarr API endpoint.
2025-09-03 21:58:40 +07:00
Tola Leng b2269187d8 feat: Add channel_id field for Notifiarr
- Add channel_id field for Notifiarr to store record of the discord channel_id into the PB.
2025-09-03 21:48:59 +07:00
Tola Leng 05f46969c4 feat: Add Notifiarr to notification channels (UI)
- Add Notifiarr as a new channel type in the notification settings. The Notifiarr channel will use the `api_token` field for API key storage in PB.
2025-09-02 21:37:54 +07:00
Tola Leng ab168b440e chore(project): update development status and progress
- fix(ssl): ensure edit form saves notification_id and template_id in DB
- feat(notifications): add Notifiarr notification channel (planned)
2025-08-29 19:58:24 +07:00
Tola Leng 2e866d7a95 chore(partners): add Cloudflare to Ecosystem & Community Partner section
- Cloudflare has been added to the Ecosystem & Community Partner list to acknowledge their support and contribution.
2025-08-29 19:53:39 +07:00
Tola Leng b372131978 fix(ssl): Ensure edit form saves notification_id and template_id in DB.
- The SSL edit form was not saving the `notification_id` and `template_id` fields to the PB database when re-assigning the Notification Channel and Alert Template.
2025-08-29 19:50:36 +07:00
Tola Leng 5f7c451fc0 feat: add Pushover notification channel schema 2025-08-27 17:24:02 +07:00
Tola Leng 3d7172d9aa Update Project Development Status and Progress
- feat: Implement Pushover notification
- fix(services-form): max retry attempts
2025-08-24 16:58:52 +07:00
Tola Leng 22d4597f88 Merge pull request #147 from ghotso/develop-fix_max_retries_issue
fix(services-form): make retry attempts select controlled and synced with form state
2025-08-24 13:49:31 +07:00
Tola Leng d4423e328b feat: Implement Pushover notification
- Implement Pushover notification functionality to send messages similar to Telegram. This includes adding `api_token` and `user_key` fields to the alert configuration for Pushover. Closes #135 #95
2025-08-23 20:47:46 +07:00
Tola Leng b3b64806f6 feat: Add Pushover notification channel
- Adds Pushover as a new notification channel option. Includes fields for `api_token` and `user_key` in the `alert_configurations` schema and integrates it into the channel type dropdown and form handling.
2025-08-23 20:10:03 +07:00
ghotso 001f6f8783 fix: update ServiceConfigFields to set default value for retry attempts and enhance delete migration scripts for server processes and notifications with error handling for deleting non existing collections 2025-08-22 12:10:01 +02:00
Tola Leng d01f682a83 Update Project Development Status and Progress 2025-08-22 16:44:27 +07:00
Tola Leng bce523bdf1 Merge pull request #142 from ghotso/develop-fix-incident_assigned_user
fix(incident): unify assigned user handling with fallback and UI update 🎯
2025-08-22 02:47:15 +07:00
Tola Leng 623e3d5ebf Add schema JSON file locally to allow direct updates from the UI. This schema is for CheckCle version v1.5.0. 2025-08-22 02:39:01 +07:00
Tola Leng e3a7865e40 feat: Allow user to update the schema directly from the dashboard
Includes:
- Dashboard "Update Schema" action
- Multiple notification/alert fixes and enhancements
- This allow to update the schema for the latest update of environment, this update include with multiple fixes

Closes The notification function is not available #138 Still can't enable and create notifications, And A new problems #136 Can not turn on notification (Telegram , Mail....) #120 Notification type 'slack' not supported #26 REQUEST: webhook notification #43 Notification can't be enabled (Discord) #77
2025-08-22 02:37:11 +07:00
ghotso 3c93354c7d Merge branch 'operacle:develop' into develop-fix-incident_assigned_user 2025-08-21 17:15:02 +02:00
ghotso 323ac36b65 chore: add server/pb_data/ to .gitignore 2025-08-21 16:53:56 +02:00
ghotso c437704007 chore: remove pb_data runtime files and ignore directory 2025-08-21 16:49:04 +02:00
ghotso 1953d54dc5 fix(types): refine user type definitions for assigned users in incident handling 2025-08-21 16:48:57 +02:00
ghotso b574073294 fix(incidents): update detail dialog and PDF generation to prefer assigned_users over assigned_to for assignee 2025-08-21 16:48:57 +02:00
ghotso b164602ee5 fix(pdf): render assignee using assigned_users with fallback to assigned_to 2025-08-21 16:48:57 +02:00
ghotso 4bd08efc9a fix(incidents): display assignee in BasicInfoSection via assigned_users fallback 2025-08-21 16:48:57 +02:00
ghotso 58fa09bea7 fix(incidents): show assignee in AssignmentSection via assigned_users with fallback to assigned_to 2025-08-21 16:48:57 +02:00
ghotso 7ff180bea4 fix(incidents): fetch and display assignee in detail dialog via assigned_users with fallback 2025-08-21 16:48:57 +02:00
ghotso 7b18806066 fix(incidents): show assignee in table using assigned_users with fallback to assigned_to 2025-08-21 16:48:56 +02:00
ghotso d4434a64e1 fix(types): add assigned_users to incident types for server persistence 2025-08-21 16:48:56 +02:00
ghotso 08580794da fix(incidents): ensure assignee is prefilled and persisted on edit (assigned_to → assigned_users) 2025-08-21 16:48:56 +02:00
ghotso 70fdcc9ea6 fix(incidents): include assigned_users in form submit so assignee is persisted 2025-08-21 16:48:56 +02:00
ghotso aba3120235 fix(incidents): persist assignee correctly via assigned_users
- map form field `assigned_to` to backend field `assigned_users`
- ensure assignee is stored when creating or updating incidents
- keep `assigned_to` for backward compatibility
2025-08-21 16:48:56 +02:00
Tola Leng b038d87848 Database Schema Update
- Database schema up to date with the latest features and improvements
2025-08-21 14:53:52 +07:00
Tola Leng 87588a9127 Added more notification channel (GoogleChat, ntfy, webhook) into the collections configuration 2025-08-21 02:19:44 +07:00
Tola Leng 4090fa5aef Merge pull request #143 from taking/develop
feat(i18n): Add Korean translations and update types
2025-08-21 01:46:43 +07:00
taking c04561dd99 Merge branch 'operacle:develop' into develop 2025-08-20 22:56:41 +09:00
Ubuntu 7f1dfcdd42 feat(i18n): Add translation fields for de, en, ja, km, zhcn
- Update translation index to support Korean
  `application/src/translation/index.ts`
- Update translation indexes
  `application/src/translation/{de,en,ja,km,zhcn}/index.ts`
- Update dropdown menu item in dashboard header
  `application/src/components/dashboard/Header.tsx`
2025-08-20 22:54:31 +09:00
Tola Leng 6f753f2901 Merge pull request #141 from ghotso/develop
feat(i18n): 🌐 sync German translations across incident, maintenance, services & settings
2025-08-20 20:25:44 +07:00
taking c39296cee6 feat(i18n): Add Korean translations and update types
- Added Korean (ko) translations for all modules (incident, login, maintenance, menu, service, settings, ssl)
- Added previously empty strings in `application/src/translations/types`
- Followed existing style and naming conventions
2025-08-19 14:54:51 +09:00
ghotso a1a8a8443e feat(i18n): 🌐 add missing German translations for settings module
Added missing German translation keys to align with the English settings module:
- addUser
- permissionNotice
- permissionNoticeAddUser
- loadingSettings
- loadingSettingsError

Ensured all existing German translations remain unchanged. 🚀
2025-08-18 21:26:11 +02:00
ghotso f866d36db4 feat(i18n): 🌐 add missing German translations for services module
Added missing German translation keys to align with the English services module.
Also imported section comments from the English file for better structure.

Now the German translation file has full feature parity with English 🚀
2025-08-18 21:20:47 +02:00
ghotso 98ec911281 feat(i18n): 🌐 add missing German translations for incident module
Added the missing German translation keys to align with the English incident module:
- enterIncidentTitle
- enterIncidentDescription
- enterServiceId
- selectAssignedUser
- noAssignedUser
- affectedSystems
- enterAffectedSystems
- separateSystemsWithComma

This ensures feature parity between the English and German translation files.
2025-08-18 21:15:04 +02:00
ghotso 046db61326 feat(i18n): 🌐 add missing German translations for maintenance module
Added the missing German translation keys to align with the English maintenance module.

Now the German translation file is complete and feature-parity with English 🌟
2025-08-18 21:14:22 +02:00
Tola Leng 3c00d0933e Merge pull request #140 from ghotso/develop
Added missing English translations to incidents.ts and maintenance.ts
2025-08-19 01:08:54 +07:00
ghotso 8e013f0b0b Added missing EN translations to maintenance.ts
Added missing translations
2025-08-18 19:04:20 +02:00
ghotso f686134525 Added missing EN translations in incident.ts
Added missing translations
2025-08-18 18:56:17 +02:00
ghotso 98d33a609e Update translations in maintenance.ts
Added missing trranslations
2025-08-18 18:49:21 +02:00
Tola Leng d33244956e Merge pull request #137 from sqkkyzx/develop
improve i18n and add new translations
2025-08-18 21:06:03 +07:00
YiZixuan 572c572c14 refactor(i18n): improvements in Chinese translation 2025-08-17 23:22:08 +08:00
YiZixuan f9743407a4 refactor(i18n): Add internationalization support for the dashboard service status card
- Add new translation items to multiple language files, including Chinese and English
- Implement internationalization support in the StatusCards component
2025-08-17 23:21:39 +08:00
YiZixuan fa3ad9b2e1 refactor(add-service): Refactor ServiceForm.tsx to support internationalization
- Extract ServiceForm.tsx validation logic into the custom hook useServiceSchema
- Add internationalization support and move error messages to translation files
2025-08-17 23:13:25 +08:00
YiZixuan 6bf75b2bf7 refactor(i18n): Extracted multiple fields in the Service component for translation.
- Extracted multiple fields in the Service component for translation.
- Optimized the structure of the translation file, categorizing it by functional modules.
2025-08-17 15:19:01 +08:00
YiZixuan b068c0cd51 refactor(i18n): improve translation handling and add English fallback
- Add English as the default fallback language; automatically use English when a translation for the current language is missing.
2025-08-16 16:21:28 +08:00
YiZixuan 92617038f0 refactor(i18n): Improve multilingual support 2025-08-16 15:59:00 +08:00
YiZixuan 40488a5a53 feat(i18n): improve i18n copy and add new translations
- Add new translation entries
- Fix several language files
2025-08-16 15:25:35 +08:00
Tola Leng 35fe0b9071 feat: Implement NTFY notification functionality
- Implement NTFY push notification functionality to send messages to ntfy toptics.
2025-08-15 17:17:29 +07:00
Tola Leng 3bc1fd7c02 feat: Add NTFY notification channel
- Adds NTFY as a new option to the notification channel type dropdown
- This includes updating the form schema and related components to support the ntfy_endpoint field for NTFY configurations.
2025-08-15 16:47:26 +07:00
Tola Leng ee4ce50193 📜 Correct the DigitalOcean logo URL 2025-08-15 14:07:57 +07:00
Tola Leng 67a0d1d7f4 📜 Adds some default styling to table cells. 2025-08-15 14:00:01 +07:00
Tola Leng f006df3b02 📜 Use a simple HTML table for image layout fo sponsorship logo 2025-08-15 13:56:16 +07:00
Tola Leng 5234303565 📌 Update on Project Development Status and Progress 2025-08-15 13:48:51 +07:00
Tola Leng 4ff0457966 📜 Wrap display logo in a flex container 2025-08-15 13:45:31 +07:00
798 changed files with 174506 additions and 5938 deletions
+10
View File
@@ -0,0 +1,10 @@
.git
server/
**/node_modules
**/dist
**/.next
**/.turbo
**/.cache
**/coverage
**/*.log
+1 -1
View File
@@ -1,6 +1,6 @@
# These are supported funding model platforms
github: [tolaleng]
github: #[tolaleng]
patreon: # Replace with a single Patreon username
open_collective: #checkcle
ko_fi: # Replace with a single Ko-fi username
+2 -1
View File
@@ -85,7 +85,8 @@ body:
id: terms
attributes:
label: Checklist
description: Please confirm the following before submitting:
description: |
Please confirm the following before submitting:
options:
- label: I have searched existing issues to avoid creating duplicates.
required: true
+2 -1
View File
@@ -51,7 +51,8 @@ body:
id: checklist
attributes:
label: Checklist
description: Before submitting, please confirm:
description: |
Before submitting, please confirm:
options:
- label: I have searched existing issues to make sure this feature hasnt been requested yet.
required: true
+2 -1
View File
@@ -45,7 +45,8 @@ body:
id: checklist
attributes:
label: Checklist
description: Before submitting, please confirm the following:
description: |
Before submitting, please confirm the following:
options:
- label: I have searched existing issues and discussions for a solution.
required: true
@@ -0,0 +1,59 @@
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,6 +22,8 @@ dist-ssr
*.njsproj
*.sln
*.sw?
pocketbase.exe
application/src/lib/pocketbase.ts
server/pb_data/
Dockerfile
application/src/lib/pocketbase-prod.ts
+4
View File
@@ -0,0 +1,4 @@
fileignoreconfig:
- filename: application/package-lock.json
checksum: 3253a06ef27a634ec2b8a8fe9c156288b9fcf57024623c7ddc3d321f2568e498
version: "1.0"
+2 -2
View File
@@ -79,7 +79,7 @@ Click "Fork" on [GitHub](https://github.com/operacle/checkcle) to create your ow
### 2. Clone Your Fork
```bash
git clone --branch develop https://github.com/operacle/checkcle.git
git clone https://github.com/yourusername/checkcle.git
cd checkcle
```
@@ -116,7 +116,7 @@ go run main.go (you do not need to change the .env while it's the localhost conn
Click "Fork" on [GitHub](https://github.com/operacle/Distributed-Regional-Monitoring) to create your own copy.
#### 2. Clone Your Fork
git clone --branch main https://github.com/operacle/Distributed-Regional-Monitoring.git
git clone https://github.com/yourusername/Distributed-Regional-Monitoring.git
cd Distributed-Regional-Monitoring
#### 3. Install Go Service (make sure you have installed the Go Service)
+26 -22
View File
@@ -60,7 +60,7 @@ CheckCle is an Open Source solution for seamless, real-time monitoring of full-s
- Infrastructure Server Monitoring, Supports Linux (🐧 Debian, Ubuntu, CentOS, Red Hat, etc.) and Windows (Beta). And Servers metrics like CPU, RAM, disk usage, and network activity) with an one-line installation angent script.
- Schedule Maintenance & Incident Management
- Operational Status / Public Status Pages
- Notifications via email, Telegram, Discord, and Slack
- Notifications via email, Telegram, Discord, Slack, Matrix, and more
- Reports & Analytics
- Settings Panel (User Management, Data Retention, Multi-language, Themes (Dark & Light Mode), Notification and channels and alert templates).
@@ -128,32 +128,36 @@ docker run -d \
---
## Sponsors
🙏 We're incredibly thankful to our sponsors. Your contributions enable us to maintain infrastructure (hosting, domains), run tests, and continue developing valuable features.
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.
### 🥈 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>
If youre a tech company interested in supporting CheckCle, please contact the author directly at tolaleng@checkcle.io
### 🤝 Ecosystem & Community Partner
<a href="https://github.com/gitbookio" style="display: inline-block; margin-right: 10px; vertical-align: middle;">
<div style="display: flex; align-items: center; gap: 10px;">
<a href="https://github.com/gitbookio">
<img src="https://avatars.githubusercontent.com/u/7111340?s=200&v=4"
width="75" height="75"
style="border-radius: 50%;" />
</a>
<a href="https://m.do.co/c/0c27ef82475f" style="display: inline-block; vertical-align: middle;">
<img src="https://opensource.nyc3.cdn.digitaloceanspaces.com/attribution/assets/SVG/DO_Logo_horizontal_blue.svg"
height="45"
alt="DigitalOcean Logo">
</a>
style="border-radius: 50%;"
alt="GitBook 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>
---
@@ -181,7 +185,7 @@ Here are some ways you can help improve CheckCle:
- Website: [checkcle.io](https://checkcle.io)
- Documentation: [docs.checkcle.io](https://docs.checkcle.io) | Big thanks to [GitBook](https://github.com/gitbookio) for sponsoring the OSS site plan for CheckCle!
- Chat on Discord: Join our community [@discord](https://discord.gg/xs9gbubGwX)
- Follow us on X: [@checkcle_oss](https://x.com/checkcle_oss)
- Follow us on X: [@asqrm_io](https://x.com/asqrm_io)
## 📜 License
+1
View File
@@ -39,6 +39,7 @@ We support the latest stable release of `checkcle`. Security patches may also be
| Version | Supported |
|---------|-----------|
| `develop` (latest) | ✅ Yes |
| `main` (latest) | ✅ Yes |
| Older versions | ⚠️ Best-effort |
| Pre-release or forks | ❌ No |
+6
View File
@@ -0,0 +1,6 @@
.git
node_modules
dist
.cache
*.log
+18
View File
@@ -0,0 +1,18 @@
# 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;"]
+404 -22
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",
"lucide-react": "^0.462.0",
"next-themes": "^0.3.0",
"pocketbase": "^0.19.0",
"pocketbase": "^0.26.8",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 250 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

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

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