// controllers/analyticsController.js
const { z } = require('zod');
const mongoose = require('mongoose');
const User = require('../models/User');
const Log = require('../models/Log');
const monitorService = require('../services/monitorService');
const logger = require('../utils/logger');
/**
* Zod Schema for Analytics with Advanced Filters
*/
const analyticsSchema = z.object({
startDate: z
.string()
.optional()
.refine((date) => !date || !isNaN(Date.parse(date)), {
message: 'startDate must be a valid ISO date string',
}),
endDate: z
.string()
.optional()
.refine((date) => !date || !isNaN(Date.parse(date)), {
message: 'endDate must be a valid ISO date string',
}),
urls: z
.string()
.optional()
.refine(
(urls) => {
if (!urls) return true;
const urlsArray = urls.split(',');
return urlsArray.every((url) => {
try {
new URL(url.trim());
return true;
} catch {
return false;
}
});
},
{ message: 'urls must be a comma-separated list of valid URLs' }
),
statusCodes: z
.string()
.optional()
.refine(
(codes) => {
if (!codes) return true;
const codesArray = codes.split(',');
return codesArray.every((code) => /^\d+$/.test(code.trim()));
},
{ message: 'statusCodes must be a comma-separated list of numbers' }
),
groupBy: z
.enum(['day', 'week', 'month', 'hour'])
.optional()
.default('day'),
deviceTypes: z
.string()
.optional()
.refine(
(types) => {
if (!types) return true;
const typesArray = types.split(',');
const allowed = ['Desktop', 'Mobile', 'Tablet', 'Other'];
return typesArray.every((type) => allowed.includes(type.trim()));
},
{ message: 'deviceTypes must be a comma-separated list of Desktop, Mobile, Tablet, Other' }
),
countries: z
.string()
.optional()
.refine(
(countries) => {
if (!countries) return true;
const countriesArray = countries.split(',');
return countriesArray.every((country) => typeof country.trim() === 'string');
},
{ message: 'countries must be a comma-separated list of country names' }
),
minResponseTime: z
.string()
.optional()
.refine((val) => !val || /^\d+$/.test(val), {
message: 'minResponseTime must be a non-negative integer representing milliseconds',
}),
maxResponseTime: z
.string()
.optional()
.refine((val) => !val || /^\d+$/.test(val), {
message: 'maxResponseTime must be a non-negative integer representing milliseconds',
}),
sortBy: z
.string()
.optional()
.refine((val) => !val || ['checkedAt', 'responseTime'].includes(val), {
message: 'sortBy must be one of checkedAt or responseTime',
})
.default('checkedAt'),
sortOrder: z
.string()
.optional()
.refine((val) => !val || ['asc', 'desc'].includes(val.toLowerCase()), {
message: 'sortOrder must be either asc or desc',
})
.default('desc'),
page: z
.string()
.optional()
.refine((val) => !val || /^\d+$/.test(val), {
message: 'page must be a positive integer',
})
.default('1'),
limit: z
.string()
.optional()
.refine((val) => !val || (/^\d+$/.test(val) && parseInt(val) <= 1000), {
message: 'limit must be an integer between 1 and 1000',
})
.default('100'),
});
/**
* Get Advanced Analytics
* GET /api/user/analytics
*/
exports.getAnalytics = async (req, res) => {
try {
const userId = req.user.id;
// Validate and parse query parameters
const parsed = analyticsSchema.parse(req.query);
const {
startDate,
endDate,
urls,
statusCodes,
groupBy,
deviceTypes,
countries,
minResponseTime,
maxResponseTime,
sortBy,
sortOrder,
page,
limit,
} = parsed;
// Build the match criteria for MongoDB aggregation
const matchCriteria = { user: new mongoose.Types.ObjectId(userId) };
if (startDate || endDate) {
matchCriteria.checkedAt = {};
if (startDate) {
matchCriteria.checkedAt.$gte = new Date(startDate);
}
if (endDate) {
matchCriteria.checkedAt.$lte = new Date(endDate);
}
}
if (urls) {
const urlsArray = urls.split(',').map((url) => url.trim());
matchCriteria.url = { $in: urlsArray };
}
if (statusCodes) {
const statusCodesArray = statusCodes.split(',').map((code) => parseInt(code.trim()));
matchCriteria.statusCode = { $in: statusCodesArray };
}
if (deviceTypes) {
const deviceTypesArray = deviceTypes.split(',').map((type) => type.trim());
matchCriteria.deviceType = { $in: deviceTypesArray };
}
if (countries) {
const countriesArray = countries.split(',').map((country) => country.trim());
matchCriteria['location.country'] = { $in: countriesArray };
}
if (minResponseTime) {
matchCriteria.responseTime = { ...matchCriteria.responseTime, $gte: parseInt(minResponseTime) };
}
if (maxResponseTime) {
matchCriteria.responseTime = { ...matchCriteria.responseTime, $lte: parseInt(maxResponseTime) };
}
/**
* Aggregation Pipelines for Various Metrics
*/
// Total Checks
const totalChecksPromise = Log.countDocuments(matchCriteria).exec();
// Successful Checks (2xx)
const successfulChecksPromise = Log.countDocuments({
...matchCriteria,
statusCode: { $gte: 200, $lt: 300 },
}).exec();
// Failed Checks (non-2xx)
const failedChecksPromise = Log.countDocuments({
...matchCriteria,
statusCode: { $gte: 400 }, // Considering 4xx and 5xx as failures
}).exec();
// Status Code Distribution
const statusCodeDistributionPromise = Log.aggregate([
{ $match: matchCriteria },
{
$group: {
_id: '$statusCode',
count: { $sum: 1 },
},
},
{ $sort: { count: -1 } },
]).exec();
// Uptime Percentage per URL
const uptimePerUrlPromise = Log.aggregate([
{ $match: { ...matchCriteria, statusCode: { $gte: 200, $lt: 300 } } },
{
$group: {
_id: '$url',
successCount: { $sum: 1 },
},
},
{
$lookup: {
from: 'logs',
let: { url: '$_id' },
pipeline: [
{ $match: {
$expr: { $eq: ['$url', '$$url'] },
...(startDate || endDate ? {
...(startDate ? { $gte: ['$checkedAt', new Date(startDate)] } : {}),
...(endDate ? { $lte: ['$checkedAt', new Date(endDate)] } : {}),
} : {})
} },
{ $count: 'totalCount' },
],
as: 'total',
},
},
{
$addFields: {
totalCount: { $arrayElemAt: ['$total.totalCount', 0] },
},
},
{
$project: {
_id: 1,
successCount: 1,
totalCount: { $ifNull: ['$totalCount', 0] },
uptimePercentage: {
$cond: [
{ $eq: ['$totalCount', 0] },
0,
{ $multiply: [{ $divide: ['$successCount', '$totalCount'] }, 100] },
],
},
},
},
]).exec();
// Checks Over Time
const checksOverTimePromise = Log.aggregate([
{ $match: matchCriteria },
{
$group: {
_id: {
year: { $year: '$checkedAt' },
month: { $month: '$checkedAt' },
week: { $week: '$checkedAt' },
day: { $dayOfMonth: '$checkedAt' },
hour: { $hour: '$checkedAt' },
},
count: { $sum: 1 },
},
},
{
$project: {
_id: 0,
period: getPeriodExpression(groupBy),
count: 1,
},
},
{
$sort: { 'period': 1 },
},
]).exec();
// Response Time Metrics (Avg, Min, Max)
const responseTimeMetricsPromise = Log.aggregate([
{ $match: matchCriteria },
{
$group: {
_id: null,
averageResponseTime: { $avg: '$responseTime' },
minResponseTime: { $min: '$responseTime' },
maxResponseTime: { $max: '$responseTime' },
},
},
]).exec();
// Geographic Distribution
const geographicDistributionPromise = Log.aggregate([
{ $match: matchCriteria },
{
$group: {
_id: '$location.country',
count: { $sum: 1 },
},
},
{ $sort: { count: -1 } },
]).exec();
// Device Types Distribution
const deviceTypesDistributionPromise = Log.aggregate([
{ $match: matchCriteria },
{
$group: {
_id: '$deviceType',
count: { $sum: 1 },
},
},
{ $sort: { count: -1 } },
]).exec();
// Status Code Trends Over Time (e.g., per day)
const statusCodeTrendsPromise = Log.aggregate([
{ $match: matchCriteria },
{
$group: {
_id: {
statusCode: '$statusCode',
...getPeriodExpression(groupBy),
},
count: { $sum: 1 },
},
},
{
$sort: { '_id.year': 1, '_id.month': 1, '_id.day': 1, '_id.week': 1, '_id.hour': 1, '_id.statusCode': 1 },
},
]).exec();
// Recent Issues with Detailed Information
const recentIssuesPromise = Log.find({
...matchCriteria,
statusCode: { $gte: 400 }, // Client and Server errors
})
.sort({ checkedAt: -1 })
.limit(20)
.select('url statusCode checkedAt screenshotUrl responseTime ipAddress location userAgent deviceType')
.exec();
// Execute all aggregation promises concurrently
const [
totalChecks,
successfulChecks,
failedChecks,
statusCodeDistribution,
uptimePerUrl,
checksOverTime,
responseTimeMetrics,
geographicDistribution,
deviceTypesDistribution,
statusCodeTrends,
recentIssues,
] = await Promise.all([
totalChecksPromise,
successfulChecksPromise,
failedChecksPromise,
statusCodeDistributionPromise,
uptimePerUrlPromise,
checksOverTimePromise,
responseTimeMetricsPromise,
geographicDistributionPromise,
deviceTypesDistributionPromise,
statusCodeTrendsPromise,
recentIssuesPromise,
]);
// Calculate success and failure percentages
const successPercentage = totalChecks > 0 ? ((successfulChecks / totalChecks) * 100).toFixed(2) : '0';
const failurePercentage = totalChecks > 0 ? ((failedChecks / totalChecks) * 100).toFixed(2) : '0';
// Format Checks Over Time based on groupBy
const formattedChecksOverTime = checksOverTime.map((item) => ({
period: formatPeriod(item.period, groupBy),
count: item.count,
}));
// Format Status Code Trends
const formattedStatusCodeTrends = statusCodeTrends.map((item) => ({
statusCode: item._id.statusCode,
period: formatPeriod(item._id, groupBy),
count: item.count,
}));
// Structure the analytics response
const analytics = {
overview: {
totalChecks,
successfulChecks,
successPercentage: `${successPercentage}%`,
failedChecks,
failurePercentage: `${failurePercentage}%`,
},
statusCodeDistribution: statusCodeDistribution.map((item) => ({
statusCode: item._id,
count: item.count,
percentage: totalChecks > 0 ? `${((item.count / totalChecks) * 100).toFixed(2)}%` : '0%',
})),
uptimePerUrl: uptimePerUrl.map((item) => ({
url: item._id,
successCount: item.successCount,
totalCount: item.totalCount,
uptimePercentage: `${item.uptimePercentage.toFixed(2)}%`,
})),
checksOverTime: formattedChecksOverTime,
responseTimeMetrics: responseTimeMetrics[0]
? {
averageResponseTime: `${responseTimeMetrics[0].averageResponseTime.toFixed(2)} ms`,
minResponseTime: `${responseTimeMetrics[0].minResponseTime} ms`,
maxResponseTime: `${responseTimeMetrics[0].maxResponseTime} ms`,
}
: { averageResponseTime: '0 ms', minResponseTime: '0 ms', maxResponseTime: '0 ms' },
geographicDistribution: geographicDistribution.map((item) => ({
country: item._id,
count: item.count,
percentage: totalChecks > 0 ? `${((item.count / totalChecks) * 100).toFixed(2)}%` : '0%',
})),
deviceTypesDistribution: deviceTypesDistribution.map((item) => ({
deviceType: item._id,
count: item.count,
percentage: totalChecks > 0 ? `${((item.count / totalChecks) * 100).toFixed(2)}%` : '0%',
})),
statusCodeTrends: formattedStatusCodeTrends,
recentIssues,
pagination: {
currentPage: parseInt(page),
limit: parseInt(limit),
},
};
res.status(200).json({ analytics });
} catch (error) {
if (error instanceof z.ZodError) {
return res.status(400).json({
message: 'Invalid query parameters',
errors: error.errors.map((err) => ({
field: err.path.join('.'),
message: err.message,
})),
});
}
logger.error('Get Advanced Analytics Error:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
/**
* Helper Functions
*/
/**
* Formats the period based on the groupBy parameter.
* @param {Object} periodObj - The period object from aggregation.
* @param {string} groupBy - 'day', 'week', 'month', 'hour'.
* @returns {string} - Formatted period string.
*/
const formatPeriod = (periodObj, groupBy) => {
const { year, month, week, day, hour } = periodObj;
switch (groupBy) {
case 'day':
return `${month}/${day}/${year}`;
case 'week':
return `Week ${week}, ${year}`;
case 'month':
return `${month}/${year}`;
case 'hour':
return `${month}/${day}/${year} ${hour}:00`;
default:
return `${month}/${day}/${year}`;
}
};
/**
* Constructs the period expression based on groupBy.
* @param {string} groupBy - 'day', 'week', 'month', 'hour'.
* @returns {Object} - MongoDB aggregation projection object.
*/
const getPeriodExpression = (groupBy) => {
switch (groupBy) {
case 'day':
return {
day: { $dayOfMonth: '$checkedAt' },
month: { $month: '$checkedAt' },
year: { $year: '$checkedAt' },
};
case 'week':
return {
week: { $week: '$checkedAt' },
year: { $year: '$checkedAt' },
};
case 'month':
return {
month: { $month: '$checkedAt' },
year: { $year: '$checkedAt' },
};
case 'hour':
return {
day: { $dayOfMonth: '$checkedAt' },
month: { $month: '$checkedAt' },
year: { $year: '$checkedAt' },
hour: { $hour: '$checkedAt' },
};
default:
return {
day: { $dayOfMonth: '$checkedAt' },
month: { $month: '$checkedAt' },
year: { $year: '$checkedAt' },
};
}
};