diff --git a/server/src/config/services.ts b/server/src/config/services.ts index cec2ad2c3..9076e226d 100644 --- a/server/src/config/services.ts +++ b/server/src/config/services.ts @@ -75,6 +75,7 @@ import { MongoNotificationsRepository, MongoIncidentRepository, MongoTeamsRepository, + MongoMaintenanceWindowsRepository, IMonitorsRepository, IChecksRepository, IMonitorStatsRepository, @@ -86,6 +87,7 @@ import { INotificationsRepository, IIncidentsRepository, ITeamsRepository, + IMaintenanceWindowsRepository, } from "@/repositories/index.js"; import { ILogger } from "@/utils/logger.js"; import { EnvConfig } from "@/service/system/settingsService.js"; @@ -121,6 +123,7 @@ export type InitializedServices = { notificationsRepository: INotificationsRepository; incidentsRepository: IIncidentsRepository; teamsRepository: ITeamsRepository; + maintenanceWindowsRepository: IMaintenanceWindowsRepository; }; export const initializeServices = async ({ @@ -160,6 +163,7 @@ export const initializeServices = async ({ const notificationsRepository = new MongoNotificationsRepository(); const incidentsRepository = new MongoIncidentRepository(); const teamsRepository = new MongoTeamsRepository(); + const maintenanceWindowsRepository = new MongoMaintenanceWindowsRepository(); const networkService = new NetworkService({ axios, @@ -256,9 +260,9 @@ export const initializeServices = async ({ errorService, }); const maintenanceWindowService = new MaintenanceWindowService({ - db, errorService, monitorsRepository, + maintenanceWindowsRepository, }); const monitorService = new MonitorService({ jobQueue: superSimpleQueue, @@ -304,6 +308,7 @@ export const initializeServices = async ({ notificationsRepository, incidentsRepository, teamsRepository, + maintenanceWindowsRepository, }; return services; diff --git a/server/src/controllers/maintenanceWindowController.ts b/server/src/controllers/maintenanceWindowController.ts index 3d212769f..0cc9610ea 100644 --- a/server/src/controllers/maintenanceWindowController.ts +++ b/server/src/controllers/maintenanceWindowController.ts @@ -1,5 +1,4 @@ import { Request, Response, NextFunction } from "express"; -import { AppError } from "@/utils/AppError.js"; import { createMaintenanceWindowBodyValidation, editMaintenanceWindowByIdParamValidation, @@ -9,6 +8,7 @@ import { getMaintenanceWindowsByTeamIdQueryValidation, deleteMaintenanceWindowByIdParamValidation, } from "@/validation/joi.js"; +import { requireTeamId } from "@/controllers/controllerUtils.js"; const SERVICE_NAME = "maintenanceWindowController"; @@ -26,11 +26,7 @@ class MaintenanceWindowController { createMaintenanceWindows = async (req: Request, res: Response, next: NextFunction) => { try { await createMaintenanceWindowBodyValidation.validateAsync(req.body); - - const teamId = req?.user?.teamId; - if (!teamId) { - throw new AppError({ message: "Team ID is required", status: 400 }); - } + const teamId = requireTeamId(req?.user?.teamId); await this.maintenanceWindowService.createMaintenanceWindow({ teamId, body: req.body }); @@ -46,10 +42,7 @@ class MaintenanceWindowController { try { await getMaintenanceWindowByIdParamValidation.validateAsync(req.params); - const teamId = req.user?.teamId; - if (!teamId) { - throw new AppError({ message: "Team ID is required", status: 400 }); - } + const teamId = requireTeamId(req.user?.teamId); const maintenanceWindow = await this.maintenanceWindowService.getMaintenanceWindowById({ id: req.params.id, teamId }); @@ -67,11 +60,7 @@ class MaintenanceWindowController { try { await getMaintenanceWindowsByTeamIdQueryValidation.validateAsync(req.query); - const teamId = req?.user?.teamId; - - if (!teamId) { - throw new AppError({ message: "Team ID is required", status: 400 }); - } + const teamId = requireTeamId(req?.user?.teamId); const maintenanceWindows = await this.maintenanceWindowService.getMaintenanceWindowsByTeamId({ teamId, query: req.query }); @@ -89,10 +78,7 @@ class MaintenanceWindowController { try { await getMaintenanceWindowsByMonitorIdParamValidation.validateAsync(req.params); - const teamId = req?.user?.teamId; - if (!teamId) { - throw new AppError({ message: "Team ID is required", status: 400 }); - } + const teamId = requireTeamId(req?.user?.teamId); const maintenanceWindows = await this.maintenanceWindowService.getMaintenanceWindowsByMonitorId({ monitorId: req.params.monitorId, teamId }); @@ -109,10 +95,7 @@ class MaintenanceWindowController { try { await deleteMaintenanceWindowByIdParamValidation.validateAsync(req.params); - const teamId = req?.user?.teamId; - if (!teamId) { - throw new AppError({ message: "Team ID is required", status: 400 }); - } + const teamId = requireTeamId(req?.user?.teamId); await this.maintenanceWindowService.deleteMaintenanceWindow({ id: req.params.id, teamId }); @@ -130,10 +113,7 @@ class MaintenanceWindowController { await editMaintenanceWindowByIdParamValidation.validateAsync(req.params); await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body); - const teamId = req.user?.teamId; - if (!teamId) { - throw new AppError({ message: "Team ID is required", status: 400 }); - } + const teamId = requireTeamId(req.user?.teamId); const editedMaintenanceWindow = await this.maintenanceWindowService.editMaintenanceWindow({ id: req.params.id, body: req.body, teamId }); return res.status(200).json({ diff --git a/server/src/db/models/MaintenanceWindow.js b/server/src/db/models/MaintenanceWindow.js deleted file mode 100755 index b68abb413..000000000 --- a/server/src/db/models/MaintenanceWindow.js +++ /dev/null @@ -1,68 +0,0 @@ -import mongoose from "mongoose"; -/** - * MaintenanceWindow Schema - * @module MaintenanceWindow - * @typedef {Object} MaintenanceWindow - * @property {mongoose.Schema.Types.ObjectId} monitorId - The ID of the monitor. This is a reference to the Monitor model and is immutable. - * @property {Boolean} active - Indicates whether the maintenance window is active. - * @property {Number} repeat - Indicates how often this maintenance window should repeat. - * @property {Date} start - The start date and time of the maintenance window. - * @property {Date} end - The end date and time of the maintenance window. - * @property {Date} expiry - The expiry date and time of the maintenance window. This is used for MongoDB's TTL index to automatically delete the document at this time. This field is set to the same value as `end` when `oneTime` is `true`. - * - * @example - * - * let maintenanceWindow = new MaintenanceWindow({ - * monitorId: monitorId, - * active: active, - * repeat: repeat, - * start: start, - * end: end, - * }); - * - * if (repeat === 0) { - * maintenanceWindow.expiry = end; - * } - * - */ - -const MaintenanceWindow = mongoose.Schema( - { - monitorId: { - type: mongoose.Schema.Types.ObjectId, - ref: "Monitor", - immutable: true, - }, - teamId: { - type: mongoose.Schema.Types.ObjectId, - ref: "Team", - immutable: true, - }, - active: { - type: Boolean, - default: true, - }, - name: { - type: String, - }, - repeat: { - type: Number, - }, - start: { - type: Date, - }, - end: { - type: Date, - }, - expiry: { - type: Date, - index: { expires: "0s" }, - }, - }, - - { - timestamps: true, - } -); - -export default mongoose.model("MaintenanceWindow", MaintenanceWindow); diff --git a/server/src/db/models/MaintenanceWindow.ts b/server/src/db/models/MaintenanceWindow.ts new file mode 100644 index 000000000..bccdc6a71 --- /dev/null +++ b/server/src/db/models/MaintenanceWindow.ts @@ -0,0 +1,63 @@ +import { Schema, model, type Types } from "mongoose"; +import type { MaintenanceWindow } from "@/types/maintenanceWindow.js"; + +type MaintenanceWindowDocumentBase = Omit< + MaintenanceWindow, + "id" | "monitorId" | "teamId" | "start" | "end" | "createdAt" | "updatedAt" +> & { + monitorId: Types.ObjectId; + teamId: Types.ObjectId; + start: Date; + end: Date; + expiry?: Date; + createdAt: Date; + updatedAt: Date; +}; + +interface MaintenanceWindowDocument extends MaintenanceWindowDocumentBase { + _id: Types.ObjectId; +} + +const MaintenanceWindowSchema = new Schema( + { + monitorId: { + type: Schema.Types.ObjectId, + ref: "Monitor", + immutable: true, + }, + teamId: { + type: Schema.Types.ObjectId, + ref: "Team", + immutable: true, + }, + active: { + type: Boolean, + default: true, + }, + name: { + type: String, + }, + repeat: { + type: Number, + }, + start: { + type: Date, + }, + end: { + type: Date, + }, + expiry: { + type: Date, + index: { expires: "0s" }, + }, + }, + { + timestamps: true, + } +); + +const MaintenanceWindowModel = model("MaintenanceWindow", MaintenanceWindowSchema); + +export type { MaintenanceWindowDocument }; +export { MaintenanceWindowModel }; +export default MaintenanceWindowModel; diff --git a/server/src/db/models/index.ts b/server/src/db/models/index.ts index f762027ec..fee369e2b 100644 --- a/server/src/db/models/index.ts +++ b/server/src/db/models/index.ts @@ -30,3 +30,6 @@ export { default as IncidentModel } from "@/db/models/Incident.js"; export * from "@/db/models/Team.js"; export { default as TeamModel } from "@/db/models/Team.js"; + +export * from "@/db/models/MaintenanceWindow.js"; +export { default as MaintenanceWindowModel } from "@/db/models/MaintenanceWindow.js"; diff --git a/server/src/repositories/maintenance-windows/IMaintenanceWindowsRepository.ts b/server/src/repositories/maintenance-windows/IMaintenanceWindowsRepository.ts index b69d79a2d..b71b8d257 100644 --- a/server/src/repositories/maintenance-windows/IMaintenanceWindowsRepository.ts +++ b/server/src/repositories/maintenance-windows/IMaintenanceWindowsRepository.ts @@ -1 +1,14 @@ -export interface IMaintenanceWindowsRepository {} +import type { MaintenanceWindow } from "@/types/index.js"; +export interface IMaintenanceWindowsRepository { + // create + create(data: Partial): Promise; + // fetch + findById(id: string, teamId: string): Promise; + + findByTeamId(teamId: string, active: boolean, page: number, rowsPerPage: number, field: string, order: string): Promise; + + // update + // delete + // other + countByTeamId(teamId: string, active: boolean): Promise; +} diff --git a/server/src/repositories/maintenance-windows/MongoMaintenanceWindowsRepository.ts b/server/src/repositories/maintenance-windows/MongoMaintenanceWindowsRepository.ts index fab135da4..7f41b4e0c 100644 --- a/server/src/repositories/maintenance-windows/MongoMaintenanceWindowsRepository.ts +++ b/server/src/repositories/maintenance-windows/MongoMaintenanceWindowsRepository.ts @@ -1,5 +1,103 @@ +import type { MaintenanceWindow } from "@/types/index.js"; +import { type MaintenanceWindowDocument, MaintenanceWindowModel } from "@/db/models/index.js"; import { IMaintenanceWindowsRepository } from "./IMaintenanceWindowsRepository.js"; +import mongoose from "mongoose"; +import { AppError } from "@/utils/AppError.js"; -class MongoMaintenanceWindowsRepository implements IMaintenanceWindowsRepository {} +class MongoMaintenanceWindowsRepository implements IMaintenanceWindowsRepository { + private toStringId = (value?: mongoose.Types.ObjectId | string | null): string => { + if (!value) { + return ""; + } + return value instanceof mongoose.Types.ObjectId ? value.toString() : String(value); + }; + + private toDateString = (value?: Date | string | null): string => { + if (!value) { + return new Date(0).toISOString(); + } + return value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + }; + + private mapDocuments = (documents: MaintenanceWindowDocument[]): MaintenanceWindow[] => { + if (!documents?.length) { + return []; + } + return documents.map((doc) => this.toEntity(doc)); + }; + + private toEntity = (doc: MaintenanceWindowDocument): MaintenanceWindow => { + return { + id: this.toStringId(doc._id), + monitorId: this.toStringId(doc.monitorId), + teamId: this.toStringId(doc.teamId), + active: doc.active, + name: doc.name, + repeat: doc.repeat, + start: this.toDateString(doc.start), + end: this.toDateString(doc.end), + createdAt: this.toDateString(doc.createdAt), + updatedAt: this.toDateString(doc.updatedAt), + }; + }; + + create = async (data: Partial): Promise => { + const maintenanceWindow = new MaintenanceWindowModel(data); + + // If the maintenance window is a one time window, set the expiry to the end date + if (maintenanceWindow.repeat === 0) { + maintenanceWindow.expiry = maintenanceWindow.end; + } + const result = await maintenanceWindow.save(); + return this.toEntity(result); + }; + + findById = async (id: string, teamId: string): Promise => { + const maintenanceWindow = await MaintenanceWindowModel.findOne({ + _id: id, + teamId: teamId, + }); + if (!maintenanceWindow) { + throw new AppError({ message: "Maintenance Window not found", status: 404 }); + } + return this.toEntity(maintenanceWindow); + }; + + findByTeamId = async ( + teamId: string, + active: boolean, + page: number, + rowsPerPage: number, + field: string, + order: string + ): Promise => { + const maintenanceQuery: Record = { teamId }; + + if (active !== undefined) maintenanceQuery.active = active; + + // Pagination + let skip = 0; + if (page && rowsPerPage) { + skip = page * rowsPerPage; + } + + // Sorting + let sort: Record = {}; + if (field !== undefined && order !== undefined) { + sort[field] = order === "asc" ? 1 : -1; + } + + const maintenanceWindows = await MaintenanceWindowModel.find(maintenanceQuery).skip(skip).limit(rowsPerPage).sort(sort); + return this.mapDocuments(maintenanceWindows); + }; + + countByTeamId = async (teamId: string, active: boolean) => { + const maintenanceQuery: Record = { teamId }; + + if (active !== undefined) maintenanceQuery.active = active; + + return await MaintenanceWindowModel.countDocuments(maintenanceQuery); + }; +} export default MongoMaintenanceWindowsRepository; diff --git a/server/src/service/business/maintenanceWindowService.ts b/server/src/service/business/maintenanceWindowService.ts index c1ba5b8d7..ade7edf0f 100644 --- a/server/src/service/business/maintenanceWindowService.ts +++ b/server/src/service/business/maintenanceWindowService.ts @@ -1,17 +1,26 @@ -import { IMonitorsRepository } from "@/repositories/index.js"; +import { IMaintenanceWindowsRepository, IMonitorsRepository } from "@/repositories/index.js"; +import { ParseBoolean } from "@/utils/utils.js"; const SERVICE_NAME = "maintenanceWindowService"; class MaintenanceWindowService { static SERVICE_NAME = SERVICE_NAME; - private db: any; private errorService: any; private monitorsRepository: IMonitorsRepository; + private maintenanceWindowsRepository: IMaintenanceWindowsRepository; - constructor({ db, errorService, monitorsRepository }: { db: any; errorService: any; monitorsRepository: IMonitorsRepository }) { - this.db = db; + constructor({ + errorService, + monitorsRepository, + maintenanceWindowsRepository, + }: { + errorService: any; + monitorsRepository: IMonitorsRepository; + maintenanceWindowsRepository: IMaintenanceWindowsRepository; + }) { this.errorService = errorService; this.monitorsRepository = monitorsRepository; + this.maintenanceWindowsRepository = maintenanceWindowsRepository; } get serviceName() { @@ -29,7 +38,7 @@ class MaintenanceWindowService { } const dbTransactions = monitorIds.map((monitorId: string) => { - return this.db.maintenanceWindowModule.createMaintenanceWindow({ + return this.maintenanceWindowsRepository.create({ teamId, monitorId, name: body.name, @@ -43,13 +52,19 @@ class MaintenanceWindowService { }; getMaintenanceWindowById = async ({ id, teamId }: { id: string; teamId: string }) => { - const maintenanceWindow = await this.db.maintenanceWindowModule.getMaintenanceWindowById({ id, teamId }); - return maintenanceWindow; + return await this.maintenanceWindowsRepository.findById(id, teamId); }; getMaintenanceWindowsByTeamId = async ({ teamId, query }: { teamId: string; query: any }) => { - const maintenanceWindows = await this.db.maintenanceWindowModule.getMaintenanceWindowsByTeamId(teamId, query); - return maintenanceWindows; + let { active, page, rowsPerPage, field, order } = query || {}; + + active = typeof active === "undefined" ? undefined : ParseBoolean(active); + page = parseInt(page) || 0; + rowsPerPage = parseInt(rowsPerPage) || 10; + + const maintenanceWindows = await this.maintenanceWindowsRepository.findByTeamId(teamId, active, page, rowsPerPage, field, order); + const maintenanceWindowCount = await this.maintenanceWindowsRepository.countByTeamId(teamId, active); + return { maintenanceWindows, maintenanceWindowCount }; }; getMaintenanceWindowsByMonitorId = async ({ monitorId, teamId }: { monitorId: string; teamId: string }) => { diff --git a/server/src/types/index.ts b/server/src/types/index.ts index 9464622ac..ad92ea1fe 100644 --- a/server/src/types/index.ts +++ b/server/src/types/index.ts @@ -12,3 +12,4 @@ export * from "@/types/alert.js"; export * from "@/types/incident.js"; export * from "@/types/email.js"; export * from "@/types/team.js"; +export * from "@/types/maintenanceWindow.js"; diff --git a/server/src/types/maintenanceWindow.ts b/server/src/types/maintenanceWindow.ts index bb7d8f2f9..33285b8e4 100644 --- a/server/src/types/maintenanceWindow.ts +++ b/server/src/types/maintenanceWindow.ts @@ -1,4 +1,5 @@ export interface MaintenanceWindow { + id: string; monitorId: String; teamId: string; active: boolean;