diff --git a/src/Features/InfrastructureMonitors/infrastructureMonitorsSlice.js b/src/Features/InfrastructureMonitors/infrastructureMonitorsSlice.js index af453a7ee..62bdf4811 100644 --- a/src/Features/InfrastructureMonitors/infrastructureMonitorsSlice.js +++ b/src/Features/InfrastructureMonitors/infrastructureMonitorsSlice.js @@ -96,19 +96,20 @@ export const getInfrastructureMonitorsByTeamId = createAsyncThunk( export const updateInfrastructureMonitor = createAsyncThunk( "infrastructureMonitors/updateMonitor", - async (data, thunkApi) => { + async ({ monitorId, monitor }, thunkApi) => { try { - const { monitor } = data; const updatedFields = { name: monitor.name, description: monitor.description, interval: monitor.interval, notifications: monitor.notifications, - threshold: monitor.threshold, + thresholds: monitor.thresholds, + secret: monitor.secret, }; const res = await networkService.updateMonitor({ - monitorId: monitor._id, - updatedFields: updatedFields, + monitorId, + monitor, + updatedFields, }); return res.data; } catch (error) { diff --git a/src/Pages/Infrastructure/Create/index.jsx b/src/Pages/Infrastructure/Create/index.jsx index 2c2a5505f..144f499fd 100644 --- a/src/Pages/Infrastructure/Create/index.jsx +++ b/src/Pages/Infrastructure/Create/index.jsx @@ -1,12 +1,13 @@ // React, Redux, Router import { useTheme } from "@emotion/react"; -import { useNavigate } from "react-router-dom"; -import { useState } from "react"; +import { useNavigate, useParams } from "react-router-dom"; +import { useState, useEffect } from "react"; import { useSelector, useDispatch } from "react-redux"; // Utility and Network import { infrastructureMonitorValidation } from "../../../Validation/validation"; -import { createInfrastructureMonitor } from "../../../Features/InfrastructureMonitors/infrastructureMonitorsSlice"; +import { createInfrastructureMonitor, updateInfrastructureMonitor } from "../../../Features/InfrastructureMonitors/infrastructureMonitorsSlice"; +import { useHardwareMonitorsFetch } from "../Details/Hooks/useHardwareMonitorsFetch"; import { capitalizeFirstLetter } from "../../../Utils/stringUtils"; import { useTranslation } from "react-i18next"; @@ -53,7 +54,14 @@ const CreateInfrastructureMonitor = () => { const monitorState = useSelector((state) => state.infrastructureMonitor); const dispatch = useDispatch(); const navigate = useNavigate(); - const { t } = useTranslation(); + const { monitorId } = useParams(); + const { t } = useTranslation(); + + // Determine if we are creating or editing + const isCreate = typeof monitorId === "undefined"; + + // Fetch monitor details if editing + const { monitor, isLoading, networkError } = useHardwareMonitorsFetch({ monitorId }); // State const [errors, setErrors] = useState({}); @@ -62,6 +70,7 @@ const CreateInfrastructureMonitor = () => { url: "", name: "", notifications: [], + notify_email: false, interval: 0.25, cpu: false, usage_cpu: "", @@ -74,10 +83,44 @@ const CreateInfrastructureMonitor = () => { secret: "", }); + // Populate form fields if editing + useEffect(() => { + if (isCreate || !monitor) return; + + setInfrastructureMonitor({ + url: monitor.url.replace(/^https?:\/\//, ""), + name: monitor.name || "", + notifications: monitor.notifications?.filter(n => typeof n === "object") || [], + notify_email: (monitor.notifications?.length ?? 0) > 0, + interval: monitor.interval / MS_PER_MINUTE, + cpu: monitor.thresholds?.usage_cpu !== undefined, + usage_cpu: monitor.thresholds?.usage_cpu ? monitor.thresholds.usage_cpu * 100 : "", + + memory: monitor.thresholds?.usage_memory !== undefined, + usage_memory: monitor.thresholds?.usage_memory ? monitor.thresholds.usage_memory * 100 : "", + + disk: monitor.thresholds?.usage_disk !== undefined, + usage_disk: monitor.thresholds?.usage_disk ? monitor.thresholds.usage_disk * 100 : "", + + temperature: monitor.thresholds?.usage_temperature !== undefined, + usage_temperature: monitor.thresholds?.usage_temperature ? monitor.thresholds.usage_temperature * 100 : "", + secret: monitor.secret || "", + }); + setHttps(monitor.url.startsWith("https")); + }, [isCreate, monitor]); + // Handlers const handleCreateInfrastructureMonitor = async (event) => { event.preventDefault(); + const formattedNotifications = infrastructureMonitor.notifications.map((n) => + typeof n === "string" ? { type: "email", address: n } : n + ); + + if (infrastructureMonitor.notify_email) { + formattedNotifications.push({ type: "email", address: user.email }); + } + // Build the form let form = { url: `http${https ? "s" : ""}://` + infrastructureMonitor.url, @@ -103,6 +146,7 @@ const CreateInfrastructureMonitor = () => { ? { usage_temperature: infrastructureMonitor.usage_temperature } : {}), secret: infrastructureMonitor.secret, + notifications: formattedNotifications, }; const { error } = infrastructureMonitorValidation.validate(form, { @@ -149,12 +193,17 @@ const CreateInfrastructureMonitor = () => { thresholds, }; - const action = await dispatch(createInfrastructureMonitor({ monitor: form })); + // Handle create or update + const action = isCreate + ? await dispatch(createInfrastructureMonitor({ monitor: form })) + : await dispatch(updateInfrastructureMonitor({ monitorId, monitor: form })); if (action.meta.requestStatus === "fulfilled") { - createToast({ body: "Infrastructure monitor created successfully!" }); + createToast({ + body: isCreate ? t("infrastructureMonitorCreated") : t("infrastructureMonitorUpdated"), + }); navigate("/infrastructure"); } else { - createToast({ body: "Failed to create monitor." }); + createToast({ body: "Failed to save monitor." }); } }; @@ -185,37 +234,34 @@ const CreateInfrastructureMonitor = () => { }; const handleNotifications = (event, type) => { - const { value } = event.target; + const { value, checked } = event.target; let notifications = [...infrastructureMonitor.notifications]; - const notificationExists = notifications.some((notification) => { - if (notification.type === type && notification.address === value) { - return true; + + if (checked) { + if (!notifications.some((n) => n.type === type && n.address === value)) { + notifications.push({ type, address: value }); } - return false; - }); - if (notificationExists) { - notifications = notifications.filter((notification) => { - if (notification.type === type && notification.address === value) { - return false; - } - return true; - }); } else { - notifications.push({ type, address: value }); + notifications = notifications.filter((n) => !(n.type === type && n.address === value)); } - + setInfrastructureMonitor((prev) => ({ ...prev, notifications, + ...(type === "email" ? { notify_email: checked } : {}) })); }; + return ( { component="span" fontSize="inherit" > - {t("infrastructureCreateYour")}{" "} + {t(isCreate? "infrastructureCreateYour": "infrastructureEditYour")}{" "} { onChange={handleChange} error={errors["url"] ? true : false} helperText={errors["url"]} + disabled={!isCreate} /> + {isCreate && ( {t("infrastructureProtocol")} @@ -294,6 +342,7 @@ const CreateInfrastructureMonitor = () => { + )} { notification.type === "email" - )} + isChecked={infrastructureMonitor.notify_email} value={user?.email} onChange={(event) => handleNotifications(event, "email")} /> @@ -361,7 +408,7 @@ const CreateInfrastructureMonitor = () => { isChecked={infrastructureMonitor[metric]} fieldId={METRIC_PREFIX + metric} fieldName={METRIC_PREFIX + metric} - fieldValue={infrastructureMonitor[METRIC_PREFIX + metric]} + fieldValue={String(infrastructureMonitor[METRIC_PREFIX + metric])} onFieldChange={handleChange} alertUnit={metric == "temperature" ? "°C" : "%"} /> @@ -408,7 +455,7 @@ const CreateInfrastructureMonitor = () => { onClick={handleCreateInfrastructureMonitor} loading={monitorState?.isLoading} > - {t("infrastructureCreateMonitor")} + {t(isCreate? "infrastructureCreateMonitor": "infrastructureEditMonitor")} diff --git a/src/Pages/Infrastructure/Details/Hooks/useHardwareMonitorsFetch.jsx b/src/Pages/Infrastructure/Details/Hooks/useHardwareMonitorsFetch.jsx index a5b84cfa4..dfdf92715 100644 --- a/src/Pages/Infrastructure/Details/Hooks/useHardwareMonitorsFetch.jsx +++ b/src/Pages/Infrastructure/Details/Hooks/useHardwareMonitorsFetch.jsx @@ -2,6 +2,11 @@ import { useEffect, useState } from "react"; import { networkService } from "../../../../main"; const useHardwareMonitorsFetch = ({ monitorId, dateRange }) => { + + // Abort early if creating monitor + if (!monitorId) { + return { monitor: undefined, isLoading: false, networkError: undefined }; + } const [isLoading, setIsLoading] = useState(true); const [networkError, setNetworkError] = useState(false); const [monitor, setMonitor] = useState(undefined); diff --git a/src/Pages/Infrastructure/Details/index.jsx b/src/Pages/Infrastructure/Details/index.jsx index 0006caf4e..f7f96f931 100644 --- a/src/Pages/Infrastructure/Details/index.jsx +++ b/src/Pages/Infrastructure/Details/index.jsx @@ -31,6 +31,7 @@ const InfrastructureDetails = () => { const theme = useTheme(); const { monitorId } = useParams(); const { t } = useTranslation(); + const isAdmin = useIsAdmin(); const { isLoading, networkError, monitor } = useHardwareMonitorsFetch({ monitorId, @@ -74,7 +75,7 @@ const InfrastructureDetails = () => { diff --git a/src/Routes/index.jsx b/src/Routes/index.jsx index bf88c92f0..82d7af7ca 100644 --- a/src/Routes/index.jsx +++ b/src/Routes/index.jsx @@ -148,6 +148,10 @@ const Routes = () => { path="infrastructure/create" element={} /> + } + /> } diff --git a/src/Utils/NetworkService.js b/src/Utils/NetworkService.js index 8924d6466..58e887f6e 100644 --- a/src/Utils/NetworkService.js +++ b/src/Utils/NetworkService.js @@ -257,14 +257,14 @@ class NetworkService { * @returns {Promise} The response from the axios PUT request. */ async updateMonitor(config) { - const { monitorId, monitor } = config; - const updatedFields = { + const { monitorId, monitor, updatedFields } = config; + const payload = updatedFields ?? { name: monitor.name, description: monitor.description, interval: monitor.interval, notifications: monitor.notifications, }; - return this.axiosInstance.put(`/monitors/${monitorId}`, updatedFields, { + return this.axiosInstance.put(`/monitors/${monitorId}`, payload, { headers: { "Content-Type": "application/json", }, diff --git a/src/Validation/validation.js b/src/Validation/validation.js index ed0aaf6b8..6e8ff76cb 100644 --- a/src/Validation/validation.js +++ b/src/Validation/validation.js @@ -349,6 +349,12 @@ const infrastructureMonitorValidation = joi.object({ "number.base": "Frequency must be a number.", "any.required": "Frequency is required.", }), + notifications: joi.array().items( + joi.object({ + type: joi.string().valid("email").required(), + address: joi.string().email({ tlds: { allow: false } }).required(), + }) + ) }); export { diff --git a/src/locales/gb.json b/src/locales/gb.json index 5b8bed597..73ece5bc3 100644 --- a/src/locales/gb.json +++ b/src/locales/gb.json @@ -225,11 +225,15 @@ "incidentsOptionsHeaderLastWeek": "Last week", "incidentsOptionsPlaceholderAllServers": "All servers", "infrastructureCreateYour": "Create your", + "infrastructureEditYour": "Edit your", "infrastructureCreateGeneralSettingsDescription": "Here you can select the URL of the host, together with the friendly name and authorization secret to connect to the server agent.", "infrastructureServerRequirement": "The server you are monitoring must be running the", "infrastructureCustomizeAlerts": "Customize alerts", "infrastructureAlertNotificationDescription": "Send a notification to user(s) when thresholds exceed a specified percentage.", "infrastructureCreateMonitor": "Create Infrastructure Monitor", + "infrastructureEditMonitor": "Save Infrastructure Monitor", + "infrastructureMonitorCreated": "Infrastructure monitor created successfully!", + "infrastructureMonitorUpdated": "Infrastructure monitor updated successfully!", "infrastructureProtocol": "Protocol", "infrastructureServerUrlLabel": "Server URL", "infrastructureDisplayNameLabel": "Display name",