Files

169 lines
5.9 KiB
JavaScript

// backend/routes/categoryDetail.js
// ─────────────────────────────────────────────────────────────────────────────
// Category Detail endpoint for the BackOne Network Intelligence page.
// Returns the real MongoDB breakdown for a clicked category.
// GET /api/dashboard/category-detail?category=<CategoryName>
// ─────────────────────────────────────────────────────────────────────────────
const express = require('express');
const router = express.Router();
const { DeviceAppStat, DeviceStat, LookupApp } = require('../models/Schemas');
const { getTimeFilter, getBaseFilter } = require('./dashboard/helpers');
function buildBaseFilter(req) {
return getBaseFilter(req, getTimeFilter(req));
}
// ─── GET /api/dashboard/category-detail ───────────────────────────────────────
router.get('/', async (req, res) => {
const { category } = req.query;
if (!category) return res.status(400).json({ ok: false, error: 'category is required' });
const base = buildBaseFilter(req);
try {
// Lookup all application labels that belong to this category
const appsInCategory = await LookupApp.find({
$or: [
{ 'application_category.label': category },
{ 'category.label': category }
]
}).lean();
const appLabels = new Set();
for (const app of appsInCategory) {
if (app.tag) {
appLabels.add(app.tag);
appLabels.add(app.tag.replace(/^netify\./i, 'backone.'));
appLabels.add(app.tag.replace(/^netify\./i, 'siab.'));
appLabels.add(app.tag.replace(/^netify\./i, ''));
}
if (app.label) {
appLabels.add(app.label);
}
}
const { APP_CATEGORY_MAP } = require('../utils/categoryDictionary');
for (const [appKey, catName] of Object.entries(APP_CATEGORY_MAP)) {
if (catName.toLowerCase() === category.toLowerCase()) {
appLabels.add(appKey);
appLabels.add(`netify.${appKey}`);
appLabels.add(`backone.${appKey}`);
appLabels.add(`siab.${appKey}`);
}
}
const labelList = Array.from(appLabels);
if (labelList.length === 0) {
return res.json({ ok: true, category, apps: [], devices: [] });
}
const filter = { ...base, app_label: { $in: labelList } };
// 1. Get Top Apps for this category
let topAppsData = await DeviceAppStat.aggregate([
{ $match: filter },
{ $group: {
_id: '$app_label',
download: { $sum: '$download' },
upload: { $sum: '$upload' },
flows: { $sum: '$flows' },
agent_uuid: { $first: '$agent_uuid' },
last_seen: { $max: '$timestamp' }
}},
{ $sort: { download: -1 } },
{ $limit: 200 }
]);
// Fallback to Flow if DeviceAppStat is empty
if (topAppsData.length === 0) {
const { Flow } = require('../models/Schemas');
topAppsData = await Flow.aggregate([
{ $match: filter },
{ $group: {
_id: '$app_label',
download: { $sum: '$download' },
upload: { $sum: '$upload' },
flows: { $sum: 1 },
agent_uuid: { $first: '$agent_uuid' },
last_seen: { $max: '$timestamp' }
}},
{ $sort: { download: -1 } },
{ $limit: 200 }
]);
}
const apps = topAppsData.map(r => ({
app_label: r._id,
download: r.download,
upload: r.upload,
flows: r.flows,
agent_uuid: r.agent_uuid,
last_seen: r.last_seen
}));
// 2. Get Top Devices for this category
const topDevicesData = await DeviceAppStat.aggregate([
{ $match: filter },
{ $group: {
_id: '$ip_address',
download: { $sum: '$download' },
upload: { $sum: '$upload' },
flows: { $sum: '$flows' },
agent_uuid: { $first: '$agent_uuid' },
last_seen: { $max: '$timestamp' }
}},
{ $sort: { download: -1 } },
{ $limit: 200 }
]);
// Enrich devices with DeviceStat info (mac, os, manufacturer)
const { generateMacFromIp, resolveVendorFromIp, resolveDeviceTypeFromIp, resolveOSFromIp, generateAutoLabel } = require('../deviceResolver');
const ips = topDevicesData.map(r => r._id).filter(Boolean);
const agentFilter = {};
if (base.agent_uuid) agentFilter.agent_uuid = base.agent_uuid;
if (base.site_uuid) agentFilter.site_uuid = base.site_uuid;
const devicesInfo = await DeviceStat.find({ ip_address: { $in: ips }, ...agentFilter }).lean();
const deviceMap = {};
for (const d of devicesInfo) deviceMap[d.ip_address] = d;
const devices = topDevicesData.map(r => {
const ip = r._id;
const d = deviceMap[ip];
const mac = d?.mac_address && d.mac_address !== '-' ? d.mac_address : generateMacFromIp(ip);
const manufacturer = resolveVendorFromIp(ip, mac);
const type = resolveDeviceTypeFromIp(ip, mac);
const os = resolveOSFromIp(ip, mac);
const label = generateAutoLabel(ip, mac, manufacturer, type);
return {
src_ip: ip,
device_label: label,
mac_address: mac,
manufacturer: manufacturer,
os_label: os,
download: r.download,
upload: r.upload,
flows: r.flows,
agent_uuid: r.agent_uuid,
last_seen: r.last_seen
};
});
res.json({
ok: true,
category,
apps,
devices
});
} catch (error) {
console.error(`[CategoryDetail] Error:`, error);
res.status(500).json({ ok: false, error: 'Internal Server Error' });
}
});
module.exports = router;