This commit is contained in:
Alex Holliday committed 2026-01-20 18:56:06 +00:00
1 parent adb2a383cf
commit 3cf7243c93
9 files changed
+237 -53

No files matched your search

@@ -1,4 +1,5 @@
import type { Incident } from "@/types/index.js";
import type { IncidentSummary } from "@/types/index.js";
export interface IIncidentsRepository {
// create
create(incident: Partial<Incident>): Promise<Incident>;
@@ -7,17 +8,19 @@ export interface IIncidentsRepository {
findActiveByMonitorId(monitorId: string, teamId: string): Promise<Incident | null>;
findByTeamId(
teamId: string,
startDate: Date,
endDate: Date,
startDate: Date | undefined,
page: number,
rowsPerPage: number,
sortOrder?: string,
status?: string,
status?: boolean,
monitorId?: string,
resolutionType?: string
): Promise<Incident[]>;
findSummaryByTeamId(teamId: string, limit?: number): Promise<IncidentSummary>;
countByTeamId(teamId: string, startDate: Date | undefined, status?: boolean, monitorId?: string, resolutionType?: string): Promise<number>;
// update
updateById(incidentId: string, teamId: string, updateData: Partial<Incident>): Promise<Incident>;
// delete
// other
}
@@ -1,6 +1,6 @@
import { IncidentModel } from "@/db/models/index.js";
import type { IncidentDocument } from "@/db/models/Incident.js";
import type { Incident } from "@/types/index.js";
import type { Incident, IncidentSummary } from "@/types/index.js";
import type { IIncidentsRepository } from "@/repositories/index.js";
import mongoose from "mongoose";
import { AppError } from "@/utils/AppError.js";
@@ -20,6 +20,32 @@ class MongoIncidentRepository implements IIncidentsRepository {
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
};
private buildMatchStage({
teamId,
startDate,
status,
monitorId,
resolutionType,
}: {
teamId: string;
startDate: Date | undefined;
status?: boolean;
monitorId?: string;
resolutionType?: string;
}): Record<string, any> {
const matchStage: Record<string, any> = {
teamId: new mongoose.Types.ObjectId(teamId),
...(status !== undefined && { status }),
...(monitorId && { monitorId: new mongoose.Types.ObjectId(monitorId) }),
...(resolutionType && { resolutionType }),
};
if (startDate) {
matchStage.createdAt = { $gte: startDate };
}
return matchStage;
}
protected toEntity = (doc: IncidentDocument): Incident => {
return {
id: this.toStringId(doc._id),
@@ -79,22 +105,15 @@ class MongoIncidentRepository implements IIncidentsRepository {
findByTeamId = async (
teamId: string,
startDate: Date,
endDate: Date,
startDate: Date | undefined,
page: number,
rowsPerPage: number,
sortOrder?: string,
status?: string,
status?: boolean,
monitorId?: string,
resolutionType?: string
): Promise<Incident[]> => {
const matchStage: Record<string, any> = {
teamId: new mongoose.Types.ObjectId(teamId),
...(status !== undefined && { status: status }),
...(monitorId && { monitorId: new mongoose.Types.ObjectId(monitorId) }),
...(resolutionType && { resolutionType }),
createdAt: { $gte: startDate, $lte: endDate },
};
const matchStage = this.buildMatchStage({ teamId, startDate, status, monitorId, resolutionType });
const incidents = await IncidentModel.find(matchStage)
.sort({ createdAt: sortOrder === "asc" ? 1 : -1 })
.skip(page * rowsPerPage)
@@ -117,5 +136,130 @@ class MongoIncidentRepository implements IIncidentsRepository {
}
return this.toEntity(updatedIncident);
};
countByTeamId = async (
teamId: string,
startDate: Date | undefined,
status?: boolean,
monitorId?: string,
resolutionType?: string
): Promise<number> => {
const matchStage = this.buildMatchStage({ teamId, startDate, status, monitorId, resolutionType });
return IncidentModel.countDocuments(matchStage);
};
findSummaryByTeamId = async (teamId: string, limit: number): Promise<IncidentSummary> => {
const matchStage = { teamId: new mongoose.Types.ObjectId(teamId) };
const counts = await IncidentModel.aggregate([
{ $match: matchStage },
{
$group: {
_id: "$status",
count: { $sum: 1 },
manualResolutions: {
$sum: { $cond: [{ $eq: ["$resolutionType", "manual"] }, 1, 0] },
},
automaticResolutions: {
$sum: { $cond: [{ $eq: ["$resolutionType", "automatic"] }, 1, 0] },
},
},
},
]);
let total = 0;
let active = 0;
let manual = 0;
let automatic = 0;
counts.forEach((item) => {
total += item.count;
if (item._id === true) {
active = item.count;
}
manual += item.manualResolutions;
automatic += item.automaticResolutions;
});
const resolutionTimeResult = await IncidentModel.aggregate([
{ $match: { ...matchStage, status: false, endTime: { $exists: true, $ne: null } } },
{ $project: { resolutionTime: { $subtract: ["$endTime", "$startTime"] } } },
{ $group: { _id: null, avgResolutionTime: { $avg: "$resolutionTime" } } },
]);
const avgResolutionTimeMs = resolutionTimeResult[0]?.avgResolutionTime || 0;
const avgResolutionTimeHours = Math.round((avgResolutionTimeMs / (1000 * 60 * 60) || 0) * 100) / 100;
const monitorResult = await IncidentModel.aggregate([
{ $match: matchStage },
{ $group: { _id: "$monitorId", count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $limit: 1 },
{
$lookup: {
from: "monitors",
localField: "_id",
foreignField: "_id",
as: "monitor",
},
},
{ $project: { monitorId: "$_id", count: 1, monitorName: { $arrayElemAt: ["$monitor.name", 0] } } },
]);
const latestLimit = Math.max(1, Number.isFinite(Number(limit)) ? Number(limit) : 10);
const latestIncidents = await IncidentModel.aggregate([
{ $match: matchStage },
{ $sort: { createdAt: -1 } },
{ $limit: latestLimit },
{
$lookup: {
from: "monitors",
localField: "monitorId",
foreignField: "_id",
as: "monitor",
},
},
{
$project: {
_id: 1,
monitorId: 1,
monitorName: { $arrayElemAt: ["$monitor.name", 0] },
status: 1,
startTime: 1,
endTime: 1,
resolutionType: 1,
message: 1,
statusCode: 1,
createdAt: 1,
},
},
]);
return {
total,
totalActive: active,
totalManualResolutions: manual,
totalAutomaticResolutions: automatic,
avgResolutionTimeHours,
topMonitor: monitorResult[0]
? {
monitorId: this.toStringId(monitorResult[0].monitorId),
monitorName: monitorResult[0].monitorName ?? null,
incidentCount: monitorResult[0].count,
}
: null,
latestIncidents: latestIncidents.map((incident) => ({
id: this.toStringId(incident._id),
monitorId: this.toStringId(incident.monitorId),
monitorName: incident.monitorName ?? null,
status: incident.status,
startTime: this.toDateString(incident.startTime),
endTime: incident.endTime ? this.toDateString(incident.endTime) : null,
resolutionType: incident.resolutionType ?? null,
message: incident.message ?? null,
statusCode: incident.statusCode ?? null,
createdAt: this.toDateString(incident.createdAt),
})),
};
};
}
export default MongoIncidentRepository;