Merge pull request #2232 from bluewave-labs/feat/email-settings

feat: email settings
This commit is contained in:
Alexander Holliday authored and GitHub committed 2025-05-10 16:13:35 -07:00
commit 38f52af0f0
14 files changed
+247 -75

No files matched your search

+2 -2
View File
@@ -3,7 +3,7 @@ import { networkService } from "../main";
import { createToast } from "../Utils/toastUtils"; import { createToast } from "../Utils/toastUtils";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
const useFetchSettings = ({ setSettings }) => { const useFetchSettings = ({ setSettingsData }) => {
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(undefined); const [error, setError] = useState(undefined);
useEffect(() => { useEffect(() => {
@@ -11,7 +11,7 @@ const useFetchSettings = ({ setSettings }) => {
setIsLoading(true); setIsLoading(true);
try { try {
const response = await networkService.getAppSettings(); const response = await networkService.getAppSettings();
setSettings(response?.data?.data); setSettingsData(response?.data?.data);
} catch (error) { } catch (error) {
createToast({ body: "Failed to fetch settings" }); createToast({ body: "Failed to fetch settings" });
setError(error); setError(error);
@@ -8,12 +8,8 @@ import { PropTypes } from "prop-types";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import Dialog from "../../Components/Dialog"; import Dialog from "../../Components/Dialog";
import { useState } from "react"; import { useState } from "react";
const SettingsDemoMonitors = ({
isLoading, const SettingsDemoMonitors = ({ HEADER_SX, handleChange, isLoading }) => {
authIsLoading,
checksIsLoading,
handleChange,
}) => {
const { t } = useTranslation(); const { t } = useTranslation();
const theme = useTheme(); const theme = useTheme();
// Local state // Local state
@@ -23,16 +19,14 @@ const SettingsDemoMonitors = ({
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography component="h1">{t("settingsDemoMonitors")}</Typography> <Typography component="h1">{t("settingsDemoMonitors")}</Typography>
<Typography sx={{ mt: theme.spacing(2) }}> <Typography sx={HEADER_SX}>{t("settingsDemoMonitorsDescription")}</Typography>
{t("settingsDemoMonitorsDescription")}
</Typography>
</Box> </Box>
<Box> <Box>
<Typography>{t("settingsAddDemoMonitors")}</Typography> <Typography>{t("settingsAddDemoMonitors")}</Typography>
<Button <Button
variant="contained" variant="contained"
color="accent" color="accent"
loading={isLoading || authIsLoading || checksIsLoading} loading={isLoading}
onClick={() => { onClick={() => {
const syntheticEvent = { const syntheticEvent = {
target: { target: {
@@ -59,7 +53,7 @@ const SettingsDemoMonitors = ({
<Button <Button
variant="contained" variant="contained"
color="error" color="error"
loading={isLoading || authIsLoading || checksIsLoading} loading={isLoading}
onClick={() => setIsOpen(true)} onClick={() => setIsOpen(true)}
sx={{ mt: theme.spacing(4) }} sx={{ mt: theme.spacing(4) }}
> >
@@ -81,7 +75,7 @@ const SettingsDemoMonitors = ({
handleChange(syntheticEvent); handleChange(syntheticEvent);
setIsOpen(false); setIsOpen(false);
}} }}
isLoading={isLoading || authIsLoading || checksIsLoading} isLoading={isLoading}
/> />
</ConfigBox> </ConfigBox>
</> </>
@@ -89,10 +83,8 @@ const SettingsDemoMonitors = ({
}; };
SettingsDemoMonitors.propTypes = { SettingsDemoMonitors.propTypes = {
isLoading: PropTypes.bool,
authIsLoading: PropTypes.bool,
checksIsLoading: PropTypes.bool,
handleChange: PropTypes.func, handleChange: PropTypes.func,
HEADER_SX: PropTypes.object,
}; };
export default SettingsDemoMonitors; export default SettingsDemoMonitors;
+126
View File
@@ -0,0 +1,126 @@
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import ConfigBox from "../../Components/ConfigBox";
import TextInput from "../../Components/Inputs/TextInput";
import Button from "@mui/material/Button";
import Stack from "@mui/material/Stack";
// Utils
import { useTheme } from "@emotion/react";
import { PropTypes } from "prop-types";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { PasswordEndAdornment } from "../../Components/Inputs/TextInput/Adornments";
const SettingsEmail = ({
HEADER_SX,
handleChange,
settingsData,
setSettingsData,
isPasswordSet,
}) => {
const { t } = useTranslation();
const theme = useTheme();
const [password, setPassword] = useState("");
const [hasBeenReset, setHasBeenReset] = useState(false);
const handlePasswordChange = (e) => {
setPassword(e.target.value);
setSettingsData({
...settingsData,
settings: { ...settingsData.settings, systemEmailPassword: e.target.value },
});
};
return (
<ConfigBox>
<Box>
<Typography component="h1">{t("settingsEmail")}</Typography>
<Typography sx={HEADER_SX}>{t("settingsEmailDescription")}</Typography>
</Box>
<Box>
<Stack gap={theme.spacing(10)}>
<Box>
<Typography>{t("settingsEmailHost")}</Typography>
<TextInput
name="systemEmailHost"
placeholder="smtp.gmail.com"
value={settingsData?.settings?.systemEmailHost ?? ""}
onChange={handleChange}
/>
</Box>
<Box>
<Typography>{t("settingsEmailPort")}</Typography>
<TextInput
name="systemEmailPort"
placeholder="425"
type="number"
value={settingsData?.settings?.systemEmailPort ?? ""}
onChange={handleChange}
/>
</Box>
<Box>
<Typography>{t("settingsEmailUser")}</Typography>
<TextInput
name="systemEmailUser"
placeholder="Leave empty if not required"
value={settingsData?.settings?.systemEmailUser ?? ""}
onChange={handleChange}
/>
</Box>
<Box>
<Typography>{t("settingsEmailAddress")}</Typography>
<TextInput
name="systemEmailAddress"
placeholder="uptime@bluewavelabs.ca"
value={settingsData?.settings?.systemEmailAddress ?? ""}
onChange={handleChange}
/>
</Box>
{(isPasswordSet === false || hasBeenReset === true) && (
<Box>
<Typography>{t("settingsEmailPassword")}</Typography>
<TextInput
name="systemEmailPassword"
type="password"
placeholder="123 456 789 101112"
value={password}
onChange={handlePasswordChange}
endAdornment={<PasswordEndAdornment />}
/>
</Box>
)}
{isPasswordSet === true && hasBeenReset === false && (
<Box>
<Typography>{t("settingsEmailFieldResetLabel")}</Typography>
<Button
onClick={() => {
setPassword("");
setSettingsData({
...settingsData,
settings: { ...settingsData.settings, systemEmailPassword: "" },
});
setHasBeenReset(true);
}}
variant="contained"
color="error"
sx={{ mt: theme.spacing(4) }}
>
{t("reset")}
</Button>
</Box>
)}
</Stack>
</Box>
</ConfigBox>
);
};
SettingsEmail.propTypes = {
settingsData: PropTypes.object,
setSettingsData: PropTypes.func,
handleChange: PropTypes.func,
HEADER_SX: PropTypes.object,
isPasswordSet: PropTypes.bool,
};
export default SettingsEmail;
+17 -11
View File
@@ -11,26 +11,28 @@ import { PropTypes } from "prop-types";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
const SettingsPagespeed = ({ HEADING_SX, settings, setSettings }) => { const SettingsPagespeed = ({
HEADING_SX,
settingsData,
setSettingsData,
isApiKeySet,
}) => {
const { t } = useTranslation(); const { t } = useTranslation();
const theme = useTheme(); const theme = useTheme();
// Local state // Local state
const [apiKey, setApiKey] = useState(""); const [apiKey, setApiKey] = useState("");
const [isApiKeySet, setIsApiKeySet] = useState(false);
const [hasBeenReset, setHasBeenReset] = useState(false); const [hasBeenReset, setHasBeenReset] = useState(false);
// Handler // Handler
const handleChange = (e) => { const handleChange = (e) => {
setApiKey(e.target.value); setApiKey(e.target.value);
setSettings({ ...settings, pagespeedApiKey: e.target.value }); setSettingsData({
...settingsData,
settings: { ...settingsData.settings, pagespeedApiKey: e.target.value },
});
}; };
useEffect(() => {
console.log(settings);
setIsApiKeySet(Boolean(settings.pagespeedApiKey) && apiKey === "");
}, [settings, apiKey]);
return ( return (
<ConfigBox> <ConfigBox>
<Box> <Box>
@@ -56,7 +58,10 @@ const SettingsPagespeed = ({ HEADING_SX, settings, setSettings }) => {
<Button <Button
onClick={() => { onClick={() => {
setApiKey(""); setApiKey("");
setSettings({ ...settings, pagespeedApiKey: "" }); setSettingsData({
...settingsData,
settings: { ...settingsData.settings, pagespeedApiKey: "" },
});
setHasBeenReset(true); setHasBeenReset(true);
}} }}
variant="contained" variant="contained"
@@ -74,8 +79,9 @@ const SettingsPagespeed = ({ HEADING_SX, settings, setSettings }) => {
SettingsPagespeed.propTypes = { SettingsPagespeed.propTypes = {
HEADING_SX: PropTypes.object, HEADING_SX: PropTypes.object,
settings: PropTypes.object, settingsData: PropTypes.object,
setSettings: PropTypes.func, setSettingsData: PropTypes.func,
isApiKeySet: PropTypes.bool,
}; };
export default SettingsPagespeed; export default SettingsPagespeed;
+3 -3
View File
@@ -12,7 +12,7 @@ import { PropTypes } from "prop-types";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useState } from "react"; import { useState } from "react";
const SettingsStats = ({ HEADING_SX, handleChange, settings, errors }) => { const SettingsStats = ({ HEADING_SX, handleChange, settingsData, errors }) => {
const theme = useTheme(); const theme = useTheme();
const { t } = useTranslation(); const { t } = useTranslation();
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
@@ -34,7 +34,7 @@ const SettingsStats = ({ HEADING_SX, handleChange, settings, errors }) => {
name="checkTTL" name="checkTTL"
label={t("settingsTTLLabel")} label={t("settingsTTLLabel")}
optionalLabel={t("settingsTTLOptionalLabel")} optionalLabel={t("settingsTTLOptionalLabel")}
value={settings?.checkTTL ?? ""} value={settingsData?.settings?.checkTTL ?? ""}
onChange={handleChange} onChange={handleChange}
type="number" type="number"
error={errors.checkTTL ? true : false} error={errors.checkTTL ? true : false}
@@ -77,7 +77,7 @@ const SettingsStats = ({ HEADING_SX, handleChange, settings, errors }) => {
SettingsStats.propTypes = { SettingsStats.propTypes = {
HEADING_SX: PropTypes.object, HEADING_SX: PropTypes.object,
handleChange: PropTypes.func, handleChange: PropTypes.func,
settings: PropTypes.object, settingsData: PropTypes.object,
errors: PropTypes.object, errors: PropTypes.object,
}; };
+28 -18
View File
@@ -6,6 +6,7 @@ import SettingsUI from "./SettingsUI";
import SettingsPagespeed from "./SettingsPagespeed"; import SettingsPagespeed from "./SettingsPagespeed";
import SettingsDemoMonitors from "./SettingsDemoMonitors"; import SettingsDemoMonitors from "./SettingsDemoMonitors";
import SettingsAbout from "./SettingsAbout"; import SettingsAbout from "./SettingsAbout";
import SettingsEmail from "./SettingsEmail";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
// Utils // Utils
import { settingsValidation } from "../../Validation/validation"; import { settingsValidation } from "../../Validation/validation";
@@ -15,7 +16,6 @@ import { useTheme } from "@emotion/react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useSelector, useDispatch } from "react-redux"; import { useSelector, useDispatch } from "react-redux";
import { setTimezone, setMode, setLanguage } from "../../Features/UI/uiSlice"; import { setTimezone, setMode, setLanguage } from "../../Features/UI/uiSlice";
import { getAppSettings } from "../../Features/Settings/settingsSlice";
import SettingsStats from "./SettingsStats"; import SettingsStats from "./SettingsStats";
import { import {
deleteMonitorChecksByTeamId, deleteMonitorChecksByTeamId,
@@ -34,17 +34,14 @@ const Settings = () => {
const { user } = useSelector((state) => state.auth); const { user } = useSelector((state) => state.auth);
// Local state // Local state
const [settings, setSettings] = useState({}); const [settingsData, setSettingsData] = useState({});
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
// Network // Network
const [isSettingsLoading, settingsError] = useFetchSettings({ const [isSettingsLoading, settingsError] = useFetchSettings({
settings, setSettingsData,
setSettings,
}); });
const [isSaving, saveError, saveSettings] = useSaveSettings(); const [isSaving, saveError, saveSettings] = useSaveSettings();
const [deleteMonitorStats, isDeletingMonitorStats] = UseDeleteMonitorStats(); const [deleteMonitorStats, isDeletingMonitorStats] = UseDeleteMonitorStats();
// Setup // Setup
@@ -58,10 +55,15 @@ const Settings = () => {
const { name, value } = e.target; const { name, value } = e.target;
// Build next state early // Build next state early
const newSettings = { ...settings, [name]: value }; const newSettingsData = {
...settingsData,
settings: { ...settingsData.settings, [name]: value },
};
// Validate // Validate
const { error } = settingsValidation.validate(newSettings, { abortEarly: false }); const { error } = settingsValidation.validate(newSettingsData.settings, {
abortEarly: false,
});
if (!error || error.details.length === 0) { if (!error || error.details.length === 0) {
setErrors({}); setErrors({});
} else { } else {
@@ -118,11 +120,13 @@ const Settings = () => {
return; return;
} }
setSettings(newSettings); setSettingsData(newSettingsData);
}; };
const handleSave = () => { const handleSave = () => {
const { error } = settingsValidation.validate(settings, { abortEarly: false }); const { error } = settingsValidation.validate(settingsData.settings, {
abortEarly: false,
});
if (!error || error.details.length === 0) { if (!error || error.details.length === 0) {
setErrors({}); setErrors({});
} else { } else {
@@ -132,7 +136,7 @@ const Settings = () => {
}); });
setErrors(newErrors); setErrors(newErrors);
} }
saveSettings(settings); saveSettings(settingsData?.settings);
}; };
return ( return (
@@ -152,21 +156,27 @@ const Settings = () => {
/> />
<SettingsPagespeed <SettingsPagespeed
HEADING_SX={HEADING_SX} HEADING_SX={HEADING_SX}
settings={settings} settingsData={settingsData}
setSettings={setSettings} setSettingsData={setSettingsData}
isApiKeySet={settingsData?.pagespeedKeySet ?? false}
/> />
<SettingsStats <SettingsStats
HEADING_SX={HEADING_SX} HEADING_SX={HEADING_SX}
settings={settings} settingsData={settingsData}
setSettings={setSettings}
handleChange={handleChange} handleChange={handleChange}
errors={errors} errors={errors}
/> />
<SettingsDemoMonitors <SettingsDemoMonitors
isLoading={false} HEADER_SX={HEADING_SX}
authIsLoading={false}
checksIsLoading={false}
handleChange={handleChange} handleChange={handleChange}
isLoading={isSettingsLoading || isSaving || isDeletingMonitorStats}
/>
<SettingsEmail
HEADER_SX={HEADING_SX}
handleChange={handleChange}
settingsData={settingsData}
setSettingsData={setSettingsData}
isPasswordSet={settingsData?.emailPasswordSet ?? false}
/> />
<SettingsAbout /> <SettingsAbout />
<Stack <Stack
+5
View File
@@ -262,6 +262,11 @@ const settingsValidation = joi.object({
}), }),
pagespeedApiKey: joi.string().allow("").optional(), pagespeedApiKey: joi.string().allow("").optional(),
language: joi.string().required(), language: joi.string().required(),
systemEmailHost: joi.string().allow(""),
systemEmailPort: joi.number().allow(null, ""),
systemEmailAddress: joi.string().allow(""),
systemEmailPassword: joi.string().allow(""),
systemEmailUser: joi.string().allow(""),
}); });
const dayjsValidator = (value, helpers) => { const dayjsValidator = (value, helpers) => {
+8 -1
View File
@@ -108,6 +108,14 @@
"settingsFailedToAddDemoMonitors": "Failed to add demo monitors", "settingsFailedToAddDemoMonitors": "Failed to add demo monitors",
"settingsMonitorsDeleted": "Successfully deleted all monitors", "settingsMonitorsDeleted": "Successfully deleted all monitors",
"settingsFailedToDeleteMonitors": "Failed to delete all monitors", "settingsFailedToDeleteMonitors": "Failed to delete all monitors",
"settingsEmail": "Email settings",
"settingsEmailDescription": "Configure email settings",
"settingsEmailHost": "Email host",
"settingsEmailPort": "Email port",
"settingsEmailAddress": "Email address",
"settingsEmailPassword": "Email password",
"settingsEmailUser": "Email user",
"settingsEmailFieldResetLabel": "Password is set. Click Reset to change it.",
"backendUnreachable": "Server Connection Error", "backendUnreachable": "Server Connection Error",
"backendUnreachableMessage": "We're unable to connect to the server. Please check your internet connection or verify your deployment configuration if the problem persists.", "backendUnreachableMessage": "We're unable to connect to the server. Please check your internet connection or verify your deployment configuration if the problem persists.",
"backendUnreachableError": "Cannot connect to the server. Please try again later.", "backendUnreachableError": "Cannot connect to the server. Please try again later.",
@@ -441,4 +449,3 @@
"pageSpeedApiKeyFieldResetLabel": "API key is set. Click Reset to change it.", "pageSpeedApiKeyFieldResetLabel": "API key is set. Click Reset to change it.",
"reset": "Reset" "reset": "Reset"
} }
+1 -2
View File
@@ -649,9 +649,8 @@ class MonitorController {
sendTestEmail = async (req, res, next) => { sendTestEmail = async (req, res, next) => {
try { try {
const { to } = req.body; const { to } = req.body;
if (!to || typeof to !== "string") { if (!to || typeof to !== "string") {
return res.error({ msg: this.stringService.errorForValidEmailAddress }); throw new Error(this.stringService.errorForValidEmailAddress);
} }
const subject = this.stringService.testEmailSubject; const subject = this.stringService.testEmailSubject;
+15 -2
View File
@@ -13,12 +13,25 @@ class SettingsController {
getAppSettings = async (req, res, next) => { getAppSettings = async (req, res, next) => {
const dbSettings = await this.settingsService.getDBSettings(); const dbSettings = await this.settingsService.getDBSettings();
const sanitizedSettings = { ...dbSettings }; const sanitizedSettings = { ...dbSettings };
const returnSettings = {
pagespeedKeySet: false,
emailPasswordSet: false,
};
if (typeof sanitizedSettings.pagespeedApiKey !== "undefined") { if (typeof sanitizedSettings.pagespeedApiKey !== "undefined") {
sanitizedSettings.pagespeedApiKey = "********"; returnSettings.pagespeedKeySet = true;
delete sanitizedSettings.pagespeedApiKey;
} }
if (typeof sanitizedSettings.systemEmailPassword !== "undefined") {
returnSettings.emailPasswordSet = true;
delete sanitizedSettings.systemEmailPassword;
}
returnSettings.settings = sanitizedSettings;
return res.success({ return res.success({
msg: this.stringService.getAppSettings, msg: this.stringService.getAppSettings,
data: sanitizedSettings, data: returnSettings,
}); });
}; };
+3
View File
@@ -25,6 +25,9 @@ const AppSettingsSchema = mongoose.Schema(
systemEmailPassword: { systemEmailPassword: {
type: String, type: String,
}, },
systemEmailUser: {
type: String,
},
singleton: { singleton: {
type: Boolean, type: Boolean,
required: true, required: true,
@@ -21,6 +21,11 @@ const updateAppSettings = async (newSettings) => {
delete update.$set.pagespeedApiKey; delete update.$set.pagespeedApiKey;
} }
if (newSettings.systemEmailPassword === "") {
update.$unset = { systemEmailPassword: "" };
delete update.$set.systemEmailPassword;
}
const settings = await AppSettings.findOneAndUpdate({}, update, { const settings = await AppSettings.findOneAndUpdate({}, update, {
new: true, new: true,
upsert: true, upsert: true,
+26 -21
View File
@@ -29,7 +29,10 @@ class EmailService {
this.mjml2html = mjml2html; this.mjml2html = mjml2html;
this.nodemailer = nodemailer; this.nodemailer = nodemailer;
this.logger = logger; this.logger = logger;
this.init();
}
init = async () => {
/** /**
* Loads an email template from the filesystem. * Loads an email template from the filesystem.
* *
@@ -67,35 +70,15 @@ class EmailService {
serverIsUpTemplate: this.loadTemplate("serverIsUp"), serverIsUpTemplate: this.loadTemplate("serverIsUp"),
passwordResetTemplate: this.loadTemplate("passwordReset"), passwordResetTemplate: this.loadTemplate("passwordReset"),
hardwareIncidentTemplate: this.loadTemplate("hardwareIncident"), hardwareIncidentTemplate: this.loadTemplate("hardwareIncident"),
testEmailTemplate: this.loadTemplate("testEmailTemplate") testEmailTemplate: this.loadTemplate("testEmailTemplate"),
}; };
/** /**
* The email transporter used to send emails. * The email transporter used to send emails.
* @type {Object} * @type {Object}
*/ */
const {
systemEmailHost,
systemEmailPort,
systemEmailUser,
systemEmailAddress,
systemEmailPassword,
} = this.settingsService.getSettings();
const emailConfig = {
host: systemEmailHost,
port: systemEmailPort,
secure: true,
auth: {
user: systemEmailUser || systemEmailAddress,
pass: systemEmailPassword,
},
}; };
this.transporter = this.nodemailer.createTransport(emailConfig);
}
/** /**
* Asynchronously builds and sends an email using a specified template and context. * Asynchronously builds and sends an email using a specified template and context.
* *
@@ -106,6 +89,28 @@ class EmailService {
* @returns {Promise<string>} A promise that resolves to the messageId of the sent email. * @returns {Promise<string>} A promise that resolves to the messageId of the sent email.
*/ */
buildAndSendEmail = async (template, context, to, subject) => { buildAndSendEmail = async (template, context, to, subject) => {
// TODO - Consider an update transporter method so this only needs to be recreated when smtp settings change
const {
systemEmailHost,
systemEmailPort,
systemEmailUser,
systemEmailAddress,
systemEmailPassword,
} = await this.settingsService.getDBSettings();
const emailConfig = {
host: systemEmailHost,
port: systemEmailPort,
secure: true,
auth: {
user: systemEmailUser || systemEmailAddress,
pass: systemEmailPassword,
},
connectionTimeout: 5000,
};
this.transporter = this.nodemailer.createTransport(emailConfig);
const buildHtml = async (template, context) => { const buildHtml = async (template, context) => {
try { try {
const mjml = this.templateLookup[template](context); const mjml = this.templateLookup[template](context);
+1
View File
@@ -431,6 +431,7 @@ const updateAppSettingsBodyValidation = joi.object({
systemEmailPort: joi.number().allow(""), systemEmailPort: joi.number().allow(""),
systemEmailAddress: joi.string().allow(""), systemEmailAddress: joi.string().allow(""),
systemEmailPassword: joi.string().allow(""), systemEmailPassword: joi.string().allow(""),
systemEmailUser: joi.string().allow(""),
}); });
//**************************************** //****************************************