Merge branch 'bluewave-labs:develop' into network-page-BE-part-1

This commit is contained in:
ThetaOI authored and GitHub committed 2025-06-19 22:36:57 +05:30
commit 5675990504
15 files changed
+356 -213

No files matched your search

+86 -4
View File
@@ -1,7 +1,17 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { Box, ListItem, Autocomplete, TextField, Stack, Typography } from "@mui/material"; import {
Box,
ListItem,
Autocomplete,
TextField,
Stack,
Typography,
Checkbox,
} from "@mui/material";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import SearchIcon from "../../../assets/icons/search.svg?react"; import SearchIcon from "../../../assets/icons/search.svg?react";
import React, { useEffect } from "react";
import { useTranslation } from "react-i18next";
/** /**
* Search component using Material UI's Autocomplete. * Search component using Material UI's Autocomplete.
@@ -60,24 +70,72 @@ const Search = ({
onBlur, onBlur,
}) => { }) => {
const theme = useTheme(); const theme = useTheme();
const { t } = useTranslation();
const [selectAll, setSelectAll] = React.useState(false);
const [open, setOpen] = React.useState(false);
const enhancedOptions = React.useMemo(() => {
return multiple && isAdorned
? [
{ [filteredBy]: t("selectAll"), isSelectAll: true, _id: "select_all" },
...options,
]
: options;
}, [multiple, isAdorned, options, filteredBy]);
const isOptionSelected = (option) => {
if (!multiple && !isAdorned) return false;
if (Array.isArray(value)) {
return value.some((item) => item._id === option._id);
}
return false;
};
const handleSelectAll = (isSelectAll) => {
const newValue = isSelectAll ? [...options] : [];
handleChange(newValue);
setSelectAll(isSelectAll);
};
useEffect(() => {
const allSelected =
Array.isArray(value) && Array.isArray(options) && value.length === options.length;
if (selectAll !== allSelected) setSelectAll(allSelected);
}, [value, options]);
return ( return (
<Autocomplete <Autocomplete
onBlur={onBlur} onBlur={onBlur}
multiple={multiple} multiple={multiple}
id={id} id={id}
value={value} value={value}
open={open}
onOpen={() => setOpen(true)}
onClose={(event, reason) => {
if (reason === "blur" || reason === "escape") {
setOpen(false);
}
}}
inputValue={inputValue} inputValue={inputValue}
onInputChange={(_, newValue) => { onInputChange={(_, newValue) => {
handleInputChange(newValue); handleInputChange(newValue);
}} }}
onChange={(_, newValue) => { onChange={(_, newValue) => {
handleChange(newValue); if (multiple && isAdorned) {
const hasSelectAllSelected =
Array.isArray(newValue) && newValue.some((item) => item.isSelectAll);
if (hasSelectAllSelected) {
handleSelectAll(!selectAll);
} else {
handleChange(newValue);
setSelectAll(Array.isArray(newValue) && newValue.length === options.length);
}
} else {
handleChange(newValue);
setOpen(false);
}
}} }}
fullWidth fullWidth
freeSolo freeSolo
disabled={disabled} disabled={disabled}
disableClearable disableClearable
options={options} options={enhancedOptions}
getOptionLabel={(option) => option[filteredBy]} getOptionLabel={(option) => option[filteredBy]}
isOptionEqualToValue={(option, value) => option._id === value._id} // Compare by unique identifier isOptionEqualToValue={(option, value) => option._id === value._id} // Compare by unique identifier
renderInput={(params) => ( renderInput={(params) => (
@@ -120,6 +178,9 @@ const Search = ({
</Stack> </Stack>
)} )}
filterOptions={(options, { inputValue }) => { filterOptions={(options, { inputValue }) => {
if (inputValue.trim() === "" && multiple && isAdorned) {
return enhancedOptions;
}
const filtered = options.filter((option) => const filtered = options.filter((option) =>
option[filteredBy].toLowerCase().includes(inputValue.toLowerCase()) option[filteredBy].toLowerCase().includes(inputValue.toLowerCase())
); );
@@ -136,6 +197,7 @@ const Search = ({
const { key, ...optionProps } = props; const { key, ...optionProps } = props;
const hasSecondaryLabel = secondaryLabel && option[secondaryLabel] !== undefined; const hasSecondaryLabel = secondaryLabel && option[secondaryLabel] !== undefined;
const port = option["port"]; const port = option["port"];
const selected = isOptionSelected(option);
return ( return (
<ListItem <ListItem
key={key} key={key}
@@ -146,9 +208,29 @@ const Search = ({
pointerEvents: "none", pointerEvents: "none",
backgroundColor: theme.palette.primary.main, backgroundColor: theme.palette.primary.main,
} }
: {} : option.isSelectAll
? {
fontWeight: "bold",
backgroundColor: theme.palette.primary.light,
"&:hover": {
backgroundColor: theme.palette.primary.light,
},
}
: {}
} }
> >
{multiple && isAdorned && !option.noOptions && (
<Checkbox
checked={option.isSelectAll ? selectAll : selected}
sx={{
color: theme.palette.primary.contrastTextSecondary,
"&.Mui-checked": {
color: theme.palette.secondary.main,
},
padding: 0,
}}
/>
)}
{option[filteredBy] + {option[filteredBy] +
(hasSecondaryLabel (hasSecondaryLabel
? ` (${option[secondaryLabel]}${port ? `: ${port}` : ""})` ? ` (${option[secondaryLabel]}${port ? `: ${port}` : ""})`
@@ -68,6 +68,9 @@ const MonitorDetailsControlHeader = ({
onClick={() => { onClick={() => {
testAllNotifications({ monitorId: monitor?._id }); testAllNotifications({ monitorId: monitor?._id });
}} }}
sx={{
whiteSpace: "nowrap",
}}
> >
{t("sendTestNotifications")} {t("sendTestNotifications")}
</Button> </Button>
@@ -8,6 +8,7 @@ import { formatDurationRounded } from "../../Utils/timeUtils";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useMonitorUtils } from "../../Hooks/useMonitorUtils"; import { useMonitorUtils } from "../../Hooks/useMonitorUtils";
import { formatMonitorUrl } from "../../Utils/utils";
/** /**
* Status component displays the status information of a monitor. * Status component displays the status information of a monitor.
* It includes the monitor's name, URL, and check interval. * It includes the monitor's name, URL, and check interval.
@@ -33,9 +34,7 @@ const Status = ({ monitor }) => {
gap={theme.spacing(4)} gap={theme.spacing(4)}
> >
<PulseDot color={statusColor[determineState(monitor)]} /> <PulseDot color={statusColor[determineState(monitor)]} />
<Typography variant="monitorUrl"> <Typography variant="monitorUrl">{formatMonitorUrl(monitor?.url)}</Typography>
{monitor?.url?.replace(/^https?:\/\//, "") || "..."}
</Typography>
<Dot /> <Dot />
<Typography> <Typography>
Checking every {formatDurationRounded(monitor?.interval)}. Checking every {formatDurationRounded(monitor?.interval)}.
+67 -32
View File
@@ -2,8 +2,57 @@ import { useState, useEffect } from "react";
import { networkService } from "../main"; import { networkService } from "../main";
import { createToast } from "../Utils/toastUtils"; import { createToast } from "../Utils/toastUtils";
const useFetchChecks = ({ const useFetchChecksTeam = ({
teamId, status,
sortOrder,
limit,
dateRange,
filter,
page,
rowsPerPage,
enabled = true,
}) => {
const [checks, setChecks] = useState(undefined);
const [checksCount, setChecksCount] = useState(undefined);
const [isLoading, setIsLoading] = useState(false);
const [networkError, setNetworkError] = useState(false);
useEffect(() => {
const fetchChecks = async () => {
if (!enabled) {
return;
}
const config = {
status,
sortOrder,
limit,
dateRange,
filter,
page,
rowsPerPage,
};
try {
setIsLoading(true);
const res = await networkService.getChecksByTeam(config);
setChecks(res.data.data.checks);
setChecksCount(res.data.data.checksCount);
} catch (error) {
setNetworkError(true);
createToast({ body: error.message });
} finally {
setIsLoading(false);
}
};
fetchChecks();
}, [status, sortOrder, limit, dateRange, filter, page, rowsPerPage, enabled]);
return [checks, checksCount, isLoading, networkError];
};
const useFetchChecksByMonitor = ({
monitorId, monitorId,
type, type,
status, status,
@@ -13,6 +62,7 @@ const useFetchChecks = ({
filter, filter,
page, page,
rowsPerPage, rowsPerPage,
enabled = true,
}) => { }) => {
const [checks, setChecks] = useState(undefined); const [checks, setChecks] = useState(undefined);
const [checksCount, setChecksCount] = useState(undefined); const [checksCount, setChecksCount] = useState(undefined);
@@ -21,40 +71,25 @@ const useFetchChecks = ({
useEffect(() => { useEffect(() => {
const fetchChecks = async () => { const fetchChecks = async () => {
if (!type && !teamId) { if (!enabled || !type) {
return; return;
} }
const method = monitorId const config = {
? networkService.getChecksByMonitor monitorId,
: networkService.getChecksByTeam; type,
status,
const config = monitorId sortOrder,
? { limit,
monitorId, dateRange,
type, filter,
status, page,
sortOrder, rowsPerPage,
limit, };
dateRange,
filter,
page,
rowsPerPage,
}
: {
status,
teamId,
sortOrder,
limit,
dateRange,
filter,
page,
rowsPerPage,
};
try { try {
setIsLoading(true); setIsLoading(true);
const res = await method(config); const res = await networkService.getChecksByMonitor(config);
setChecks(res.data.data.checks); setChecks(res.data.data.checks);
setChecksCount(res.data.data.checksCount); setChecksCount(res.data.data.checksCount);
} catch (error) { } catch (error) {
@@ -68,7 +103,6 @@ const useFetchChecks = ({
fetchChecks(); fetchChecks();
}, [ }, [
monitorId, monitorId,
teamId,
type, type,
status, status,
sortOrder, sortOrder,
@@ -77,9 +111,10 @@ const useFetchChecks = ({
filter, filter,
page, page,
rowsPerPage, rowsPerPage,
enabled,
]); ]);
return [checks, checksCount, isLoading, networkError]; return [checks, checksCount, isLoading, networkError];
}; };
export { useFetchChecks }; export { useFetchChecksByMonitor, useFetchChecksTeam };
@@ -10,10 +10,11 @@ import NetworkError from "../../../../Components/GenericFallback/NetworkError";
//Utils //Utils
import { formatDateWithTz } from "../../../../Utils/timeUtils"; import { formatDateWithTz } from "../../../../Utils/timeUtils";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { useState, useEffect } from "react"; import { useState } from "react";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useFetchChecks } from "../../../../Hooks/checkHooks"; import { useFetchChecksTeam } from "../../../../Hooks/checkHooks";
import { useFetchChecksByMonitor } from "../../../../Hooks/checkHooks";
const IncidentTable = ({ const IncidentTable = ({
shouldRender, shouldRender,
@@ -26,26 +27,41 @@ const IncidentTable = ({
const uiTimezone = useSelector((state) => state.ui.timezone); const uiTimezone = useSelector((state) => state.ui.timezone);
//Local state //Local state
const [teamId, setTeamId] = useState(undefined);
const [monitorId, setMonitorId] = useState(undefined);
const [page, setPage] = useState(0); const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10); const [rowsPerPage, setRowsPerPage] = useState(10);
const selectedMonitorDetails = monitors?.[selectedMonitor]; const selectedMonitorDetails = monitors?.[selectedMonitor];
const selectedMonitorType = selectedMonitorDetails?.type; const selectedMonitorType = selectedMonitorDetails?.type;
const [checks, checksCount, isLoading, networkError] = useFetchChecks({ const [checksMonitor, checksCountMonitor, isLoadingMonitor, networkErrorMonitor] =
status: false, useFetchChecksByMonitor({
monitorId, monitorId: selectedMonitor === "0" ? undefined : selectedMonitor,
teamId, type: selectedMonitorType,
type: selectedMonitorType, status: false,
sortOrder: "desc", sortOrder: "desc",
limit: null, limit: null,
dateRange, dateRange,
filter: filter, filter: filter,
page: page, page: page,
rowsPerPage: rowsPerPage, rowsPerPage: rowsPerPage,
}); enabled: selectedMonitor !== "0",
});
const [checksTeam, checksCountTeam, isLoadingTeam, networkErrorTeam] =
useFetchChecksTeam({
status: false,
sortOrder: "desc",
limit: null,
dateRange,
filter: filter,
page: page,
rowsPerPage: rowsPerPage,
enabled: selectedMonitor === "0",
});
const checks = selectedMonitor === "0" ? checksTeam : checksMonitor;
const checksCount = selectedMonitor === "0" ? checksCountTeam : checksCountMonitor;
const isLoading = isLoadingTeam || isLoadingMonitor;
const networkError = selectedMonitor === "0" ? networkErrorTeam : networkErrorMonitor;
const { t } = useTranslation(); const { t } = useTranslation();
@@ -58,16 +74,6 @@ const IncidentTable = ({
setRowsPerPage(event.target.value); setRowsPerPage(event.target.value);
}; };
useEffect(() => {
if (selectedMonitor === "0") {
setTeamId("placeholder"); // TODO this isn't needed any longer, fix hook
setMonitorId(undefined);
} else {
setMonitorId(selectedMonitor);
setTeamId(undefined);
}
}, [selectedMonitor]);
const headers = [ const headers = [
{ {
id: "monitorName", id: "monitorName",
+12 -11
View File
@@ -18,7 +18,7 @@ import { useTheme } from "@emotion/react";
import { useIsAdmin } from "../../../Hooks/useIsAdmin"; import { useIsAdmin } from "../../../Hooks/useIsAdmin";
import { useFetchUptimeMonitorById } from "../../../Hooks/monitorHooks"; import { useFetchUptimeMonitorById } from "../../../Hooks/monitorHooks";
import useCertificateFetch from "./Hooks/useCertificateFetch"; import useCertificateFetch from "./Hooks/useCertificateFetch";
import { useFetchChecks } from "../../../Hooks/checkHooks"; import { useFetchChecksByMonitor } from "../../../Hooks/checkHooks";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
// Constants // Constants
@@ -66,16 +66,17 @@ const UptimeDetails = () => {
const monitorType = monitor?.type; const monitorType = monitor?.type;
const [checks, checksCount, checksAreLoading, checksNetworkError] = useFetchChecks({ const [checks, checksCount, checksAreLoading, checksNetworkError] =
monitorId, useFetchChecksByMonitor({
type: monitorType, monitorId,
sortOrder: "desc", type: monitorType,
limit: null, sortOrder: "desc",
dateRange, limit: null,
filter: null, dateRange,
page, filter: null,
rowsPerPage, page,
}); rowsPerPage,
});
// Handlers // Handlers
const triggerUpdate = () => { const triggerUpdate = () => {
+8
View File
@@ -5,3 +5,11 @@ export const safelyParseFloat = (value) => {
} }
return parsedValue; return parsedValue;
}; };
export const formatMonitorUrl = (url, maxLength = 55) => {
if (!url) return "";
const strippedUrl = url.replace(/^https?:\/\//, "");
return strippedUrl.length > maxLength
? `${strippedUrl.slice(0, maxLength)}…`
: strippedUrl;
};
+2 -1
View File
@@ -744,5 +744,6 @@
"settingsEmailRejectUnauthorized": "Reject Unauthorized", "settingsEmailRejectUnauthorized": "Reject Unauthorized",
"settingsEmailSecure": "Secure - Use SSL", "settingsEmailSecure": "Secure - Use SSL",
"settingsEmailPool": "Pool - Enable connection pooling", "settingsEmailPool": "Pool - Enable connection pooling",
"sendTestNotifications": "Send test notifications" "sendTestNotifications": "Send test notifications",
"selectAll": "Select all"
} }
+32 -24
View File
@@ -7,7 +7,6 @@ import {
recoveryTokenValidation, recoveryTokenValidation,
newPasswordValidation, newPasswordValidation,
} from "../validation/joi.js"; } from "../validation/joi.js";
import logger from "../utils/logger.js";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import { getTokenFromHeaders } from "../utils/utils.js"; import { getTokenFromHeaders } from "../utils/utils.js";
import crypto from "crypto"; import crypto from "crypto";
@@ -15,12 +14,13 @@ import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "authController"; const SERVICE_NAME = "authController";
class AuthController { class AuthController {
constructor(db, settingsService, emailService, jobQueue, stringService) { constructor({ db, settingsService, emailService, jobQueue, stringService, logger }) {
this.db = db; this.db = db;
this.settingsService = settingsService; this.settingsService = settingsService;
this.emailService = emailService; this.emailService = emailService;
this.jobQueue = jobQueue; this.jobQueue = jobQueue;
this.stringService = stringService; this.stringService = stringService;
this.logger = logger;
} }
/** /**
@@ -96,21 +96,28 @@ class AuthController {
const token = this.issueToken(userForToken, appSettings); const token = this.issueToken(userForToken, appSettings);
this.emailService try {
.buildAndSendEmail( const html = await this.emailService.buildEmail("welcomeEmailTemplate", {
"welcomeEmailTemplate", name: newUser.firstName,
{ name: newUser.firstName },
newUser.email,
"Welcome to Uptime Monitor"
)
.catch((error) => {
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "registerUser",
stack: error.stack,
});
}); });
this.emailService
.sendEmail(newUser.email, "Welcome to Uptime Monitor", html)
.catch((error) => {
this.logger.warn({
message: error.message,
service: SERVICE_NAME,
method: "registerUser",
stack: error.stack,
});
});
} catch (error) {
logger.warn({
message: error.message,
service: SERVICE_NAME,
method: "registerUser",
stack: error.stack,
});
}
res.success({ res.success({
msg: this.stringService.authCreateUser, msg: this.stringService.authCreateUser,
@@ -300,15 +307,16 @@ class AuthController {
const name = user.firstName; const name = user.firstName;
const { clientHost } = this.settingsService.getSettings(); const { clientHost } = this.settingsService.getSettings();
const url = `${clientHost}/set-new-password/${recoveryToken.token}`; const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
const msgId = await this.emailService.buildAndSendEmail(
"passwordResetTemplate", const html = await this.emailService.buildEmail("passwordResetTemplate", {
{ name,
name,
email,
url,
},
email, email,
"Checkmate Password Reset" url,
});
const msgId = await this.emailService.sendEmail(
email,
"Checkmate Password Reset",
html
); );
return res.success({ return res.success({
+18 -17
View File
@@ -71,24 +71,25 @@ class InviteController {
const inviteToken = await this.db.requestInviteToken({ ...req.body }); const inviteToken = await this.db.requestInviteToken({ ...req.body });
const { clientHost } = this.settingsService.getSettings(); const { clientHost } = this.settingsService.getSettings();
this.emailService
.buildAndSendEmail( try {
"employeeActivationTemplate", const html = await this.emailService.buildEmail("employeeActivationTemplate", {
{ name: firstname,
name: firstname, link: `${clientHost}/register/${inviteToken.token}`,
link: `${clientHost}/register/${inviteToken.token}`,
},
req.body.email,
"Welcome to Uptime Monitor"
)
.catch((error) => {
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "issueInvitation",
stack: error.stack,
});
}); });
await this.emailService.sendEmail(
req.body.email,
"Welcome to Uptime Monitor",
html
);
} catch (error) {
logger.warn({
message: error.message,
service: SERVICE_NAME,
method: "sendInviteEmail",
stack: error.stack,
});
}
return res.success({ return res.success({
msg: this.stringService.inviteIssued, msg: this.stringService.inviteIssued,
+2 -6
View File
@@ -580,12 +580,8 @@ class MonitorController {
const subject = this.stringService.testEmailSubject; const subject = this.stringService.testEmailSubject;
const context = { testName: "Monitoring System" }; const context = { testName: "Monitoring System" };
const messageId = await this.emailService.buildAndSendEmail( const html = await this.emailService.buildEmail("testEmailTemplate", context);
"testEmailTemplate", const messageId = await this.emailService.sendEmail(to, subject, html);
context,
to,
subject
);
if (!messageId) { if (!messageId) {
return res.error({ return res.error({
+16 -21
View File
@@ -90,26 +90,21 @@ class SettingsController {
const subject = this.stringService.testEmailSubject; const subject = this.stringService.testEmailSubject;
const context = { testName: "Monitoring System" }; const context = { testName: "Monitoring System" };
const messageId = await this.emailService.buildAndSendEmail( const html = await this.emailService.buildEmail("testEmailTemplate", context);
"testEmailTemplate", const messageId = await this.emailService.sendEmail(to, subject, html, {
context, systemEmailHost,
to, systemEmailPort,
subject, systemEmailUser,
{ systemEmailAddress,
systemEmailHost, systemEmailPassword,
systemEmailPort, systemEmailConnectionHost,
systemEmailUser, systemEmailSecure,
systemEmailAddress, systemEmailPool,
systemEmailPassword, systemEmailIgnoreTLS,
systemEmailConnectionHost, systemEmailRequireTLS,
systemEmailSecure, systemEmailRejectUnauthorized,
systemEmailPool, systemEmailTLSServername,
systemEmailIgnoreTLS, });
systemEmailRequireTLS,
systemEmailRejectUnauthorized,
systemEmailTLSServername,
}
);
if (!messageId) { if (!messageId) {
return res.error({ return res.error({
@@ -122,7 +117,7 @@ class SettingsController {
data: { messageId }, data: { messageId },
}); });
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleError(error, SERVICE_NAME));
return; return;
} }
}; };
+8 -7
View File
@@ -239,13 +239,14 @@ const startApp = async () => {
process.on("SIGTERM", shutdown); process.on("SIGTERM", shutdown);
//Create controllers //Create controllers
const authController = new AuthController( const authController = new AuthController({
ServiceRegistry.get(MongoDB.SERVICE_NAME), db: ServiceRegistry.get(MongoDB.SERVICE_NAME),
ServiceRegistry.get(SettingsService.SERVICE_NAME), settingsService: ServiceRegistry.get(SettingsService.SERVICE_NAME),
ServiceRegistry.get(EmailService.SERVICE_NAME), emailService: ServiceRegistry.get(EmailService.SERVICE_NAME),
ServiceRegistry.get(JobQueue.SERVICE_NAME), jobQueue: ServiceRegistry.get(JobQueue.SERVICE_NAME),
ServiceRegistry.get(StringService.SERVICE_NAME) stringService: ServiceRegistry.get(StringService.SERVICE_NAME),
); logger: logger,
});
const monitorController = new MonitorController( const monitorController = new MonitorController(
ServiceRegistry.get(MongoDB.SERVICE_NAME), ServiceRegistry.get(MongoDB.SERVICE_NAME),
+32 -49
View File
@@ -80,24 +80,28 @@ class EmailService {
*/ */
}; };
/** buildEmail = async (template, context) => {
* Asynchronously builds and sends an email using a specified template and context. try {
* const mjml = this.templateLookup[template](context);
* @param {string} template - The name of the template to use for the email body. const html = await this.mjml2html(mjml);
* @param {Object} context - The data context to render the template with. return html.html;
* @param {string} to - The recipient's email address. } catch (error) {
* @param {string} subject - The subject of the email. this.logger.error({
* @returns {Promise<string>} A promise that resolves to the messageId of the sent email. message: error.message,
*/ service: SERVICE_NAME,
buildAndSendEmail = async (template, context, to, subject, transportConfig) => { method: "buildEmail",
// TODO - Consider an update transporter method so this only needs to be recreated when smtp settings change stack: error.stack,
});
}
};
sendEmail = async (to, subject, html, transportConfig) => {
let config; let config;
if (typeof transportConfig !== "undefined") { if (typeof transportConfig !== "undefined") {
config = transportConfig; config = transportConfig;
} else { } else {
config = await this.settingsService.getDBSettings(); config = await this.settingsService.getDBSettings();
} }
const { const {
systemEmailHost, systemEmailHost,
systemEmailPort, systemEmailPort,
@@ -131,45 +135,24 @@ class EmailService {
servername: systemEmailTLSServername, servername: systemEmailTLSServername,
}, },
}; };
this.transporter = this.nodemailer.createTransport(emailConfig); this.transporter = this.nodemailer.createTransport(emailConfig);
const buildHtml = async (template, context) => { try {
try { const info = await this.transporter.sendMail({
const mjml = this.templateLookup[template](context); to: to,
const html = await this.mjml2html(mjml); from: systemEmailAddress,
return html.html; subject: subject,
} catch (error) { html: html,
this.logger.error({ });
message: error.message, return info?.messageId;
service: SERVICE_NAME, } catch (error) {
method: "buildAndSendEmail", this.logger.error({
stack: error.stack, message: error.message,
}); service: SERVICE_NAME,
} method: "sendEmail",
}; stack: error.stack,
});
const sendEmail = async (to, subject, html) => { }
try {
const info = await this.transporter.sendMail({
to: to,
from: systemEmailAddress,
subject: subject,
html: html,
});
return info;
} catch (error) {
this.logger.error({
message: error.message,
service: SERVICE_NAME,
method: "sendEmail",
stack: error.stack,
});
}
};
const html = await buildHtml(template, context);
const info = await sendEmail(to, subject, html);
return info?.messageId;
}; };
} }
+35 -11
View File
@@ -218,7 +218,16 @@ class NotificationService {
const template = "hardwareIncidentTemplate"; const template = "hardwareIncidentTemplate";
const context = { monitor: monitor.name, url: monitor.url, alerts }; const context = { monitor: monitor.name, url: monitor.url, alerts };
const subject = `Monitor ${monitor.name} infrastructure alerts`; const subject = `Monitor ${monitor.name} infrastructure alerts`;
this.emailService.buildAndSendEmail(template, context, address, subject); const html = await this.emailService.buildEmail(template, context);
this.emailService.sendEmail(address, subject, html).catch((error) => {
this.logger.warn({
message: error.message,
service: this.SERVICE_NAME,
method: "sendHardwareEmail",
stack: error.stack,
});
});
return true; return true;
} }
@@ -231,17 +240,22 @@ class NotificationService {
const subject = this.stringService.testEmailSubject; const subject = this.stringService.testEmailSubject;
const context = { testName: "Monitoring System" }; const context = { testName: "Monitoring System" };
const messageId = await this.emailService.buildAndSendEmail( try {
"testEmailTemplate", const html = await this.emailService.buildEmail("testEmailTemplate", context);
context, const messageId = await this.emailService.sendEmail(to, subject, html);
to,
subject
);
if (messageId) { if (messageId) {
return true; return true;
}
} catch (error) {
this.logger.warn({
message: error.message,
service: this.SERVICE_NAME,
method: "sendTestEmail",
stack: error.stack,
});
return false;
} }
return false;
}; };
/** /**
@@ -259,7 +273,17 @@ class NotificationService {
const template = prevStatus === false ? "serverIsUpTemplate" : "serverIsDownTemplate"; const template = prevStatus === false ? "serverIsUpTemplate" : "serverIsDownTemplate";
const context = { monitor: monitor.name, url: monitor.url }; const context = { monitor: monitor.name, url: monitor.url };
const subject = `Monitor ${monitor.name} is ${status === true ? "up" : "down"}`; const subject = `Monitor ${monitor.name} is ${status === true ? "up" : "down"}`;
this.emailService.buildAndSendEmail(template, context, address, subject);
const html = await this.emailService.buildEmail(template, context);
this.emailService.sendEmail(address, subject, html).catch((error) => {
this.logger.warn({
message: error.message,
service: this.SERVICE_NAME,
method: "sendEmail",
stack: error.stack,
});
});
return true; return true;
} }