From 87dc19f63f7f0846b4e2a5dcb9a6b49bc5b6b2df Mon Sep 17 00:00:00 2001 From: Yoga Pratama Date: Mon, 9 Nov 2026 19:04:07 +0700 Subject: [PATCH] fix(dashboard): pinpoint zoom-scaled Agent red markers, city-center blue markers, and standardize netify./siab. to backone. everywhere --- backend/routes/appDetailsHandler.js | 13 +++- backend/routes/dashboard.js | 75 ++++++---------------- backend/routes/dashboard/agentLocations.js | 55 +++------------- backend/server.js | 1 + src/components/dashboard/TopWidgets.tsx | 1 + src/components/ui/DeviceDomainsTab.tsx | 8 +-- src/components/ui/DeviceIdentityCard.tsx | 2 +- src/components/ui/GlobeMap.tsx | 43 ++++++++----- src/lib/domainUtils.ts | 5 +- src/lib/geoUtils.ts | 73 +++++++++++++++------ 10 files changed, 130 insertions(+), 146 deletions(-) diff --git a/backend/routes/appDetailsHandler.js b/backend/routes/appDetailsHandler.js index a6a6f7a..3167fe6 100644 --- a/backend/routes/appDetailsHandler.js +++ b/backend/routes/appDetailsHandler.js @@ -34,7 +34,14 @@ module.exports = async function appDetailsHandler(req, res, helpers) { if (agentUuid) baseFilter.agent_uuid = agentUuid; // ── Step 1: Query DeviceAppStat (Primary source for per-device bandwidth per-app) ── - const queryFilter = { ...baseFilter, app_label: label }; + const baseName = label.replace(/^(?:backone|netify|siab|nexus)\./i, ''); + const labelVariants = Array.from(new Set([ + label, + `netify.${baseName}`, + `backone.${baseName}`, + `siab.${baseName}`, + ])); + const queryFilter = { ...baseFilter, app_label: { $in: labelVariants } }; const deviceApps = await DeviceAppStat.find(queryFilter).sort({ timestamp: -1 }).lean(); if (deviceApps.length > 0) { @@ -75,7 +82,7 @@ module.exports = async function appDetailsHandler(req, res, helpers) { // Enrich domain & protocol info from Flow if available const flows = await Flow.find({ ...baseFilter, - app_label: label + app_label: { $in: labelVariants } }).sort({ timestamp: -1 }).limit(100).lean(); flows.forEach(f => { @@ -90,7 +97,7 @@ module.exports = async function appDetailsHandler(req, res, helpers) { .sort((a, b) => (b.download + b.upload) - (a.download + a.upload)); // Ambil total download/upload dari sum AppStat over the time range - const appStats = await AppStat.find({ ...baseFilter, app_label: label }).lean(); + const appStats = await AppStat.find({ ...baseFilter, app_label: { $in: labelVariants } }).lean(); const totalDl = appStats.reduce((s, x) => s + (x.download || 0), 0); const totalUl = appStats.reduce((s, x) => s + (x.upload || 0), 0); diff --git a/backend/routes/dashboard.js b/backend/routes/dashboard.js index 11669de..cf98858 100644 --- a/backend/routes/dashboard.js +++ b/backend/routes/dashboard.js @@ -10,66 +10,25 @@ const axios = require('axios'); const PROXY_URL = process.env.PROXY_URL || 'http://localhost:4010'; -// ─── Rebranding Helper (Memory Safe & Fast) ────────────────────────────────── -const BRAND_NAMES = { - '1959bb55_045b_47c7_bbdd_f33b7db197b9': 'Office', - '6681452d_9cae_4ff4_8ae8_0d504774265e': 'SIAB', - 'default': 'BackOne' -}; - -function getBrandNameForRequest(req) { - const requestedSiteUuid = req.headers['x-backone-site-uuid']; - const userSiteUuid = req.user?.site_uuid; - - const siteUuid = (req.user?.role === 'SUPER_ADMIN' || !userSiteUuid || userSiteUuid === 'default') - ? (requestedSiteUuid || 'default') - : userSiteUuid; - - return BRAND_NAMES[siteUuid] || 'BackOne'; -} - -function rebrandString(str, brandName) { +function rebrandString(str) { if (typeof str !== 'string') return str; - - if (brandName === 'Nexus') { - return str - .replace(/netify\.unclassified/gi, 'nexus.unclassified') - .replace(/netify\.(?!ai)/gi, 'nexus.') - .replace(/Netify's/g, "Nexus'") - .replace(/netify's/g, "nexus'") - .replace(/Netify(?!(\.ai))/g, 'Nexus') - .replace(/netify(?!(\.ai))/g, 'nexus') - .replace(/BackOne's/g, "Nexus'") - .replace(/backone's/g, "nexus'") - .replace(/BackOne/g, 'Nexus') - .replace(/backone/g, 'nexus') - .replace(/PT\.?\s*Data\s*Bisnis\s*Solusi/g, 'PT. Nexus Solusi'); - } else if (brandName === 'SIAB') { - return str - .replace(/netify\.unclassified/gi, 'siab.unclassified') - .replace(/netify\.(?!ai)/gi, 'siab.') - .replace(/Netify's/g, "SIAB's") - .replace(/netify's/g, "siab's") - .replace(/Netify(?!(\.ai))/g, 'SIAB') - .replace(/netify(?!(\.ai))/g, 'siab'); - } - // Default (BackOne) + // Standardize all netify./siab./nexus. prefixes across protocols, apps, and domains to backone. return str - .replace(/netify\.unclassified/gi, 'backone.unclassified') - .replace(/netify\.(?!ai)/gi, 'backone.') - .replace(/Netify's/g, "BackOne's") - .replace(/netify's/g, "backone's") + .replace(/\b(?:netify|siab|nexus)\.unclassified/gi, 'backone.unclassified') + .replace(/\b(?:netify|siab|nexus)\.(?!ai)/gi, 'backone.') + .replace(/(?:Netify|SIAB)'s/g, "BackOne's") + .replace(/(?:netify|siab)'s/g, "backone's") .replace(/Netify(?!(\.ai))/g, 'BackOne') .replace(/netify(?!(\.ai))/g, 'backone'); } -function rebrandObj(obj, brandName) { +function rebrandObj(obj) { if (obj === null || obj === undefined) return obj; if (Array.isArray(obj)) { for (let i = 0; i < obj.length; i++) { - obj[i] = rebrandObj(obj[i], brandName); + obj[i] = rebrandObj(obj[i]); } return obj; } @@ -78,9 +37,9 @@ function rebrandObj(obj, brandName) { for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { if (typeof obj[key] === 'string') { - obj[key] = rebrandString(obj[key], brandName); + obj[key] = rebrandString(obj[key]); } else if (typeof obj[key] === 'object') { - obj[key] = rebrandObj(obj[key], brandName); + obj[key] = rebrandObj(obj[key]); } } } @@ -88,20 +47,21 @@ function rebrandObj(obj, brandName) { } if (typeof obj === 'string') { - return rebrandString(obj, brandName); + return rebrandString(obj); } return obj; } // ─── Rebranding Middleware ──────────────────────────────────────────────────── -router.use((req, res, next) => { - const brandName = getBrandNameForRequest(req); +function rebrandMiddleware(req, res, next) { + if (res._rebrandAttached) return next(); + res._rebrandAttached = true; const originalJson = res.json.bind(res); res.json = function (body) { if (body) { try { - body = rebrandObj(body, brandName); + body = rebrandObj(body); } catch (err) { console.error('[Dashboard] Rebrand error:', err.message); } @@ -109,7 +69,9 @@ router.use((req, res, next) => { return originalJson(body); }; next(); -}); +} + +router.use(rebrandMiddleware); // POST /api/dashboard/refresh router.post('/refresh', async (req, res) => { @@ -140,4 +102,5 @@ router.use(require('./dashboard/tenantConfig')); router.use(require('./dashboard/agentLocations')); router.use(require('./dashboard/blacklist')); +router.rebrandMiddleware = rebrandMiddleware; module.exports = router; diff --git a/backend/routes/dashboard/agentLocations.js b/backend/routes/dashboard/agentLocations.js index eff7017..d2670e4 100644 --- a/backend/routes/dashboard/agentLocations.js +++ b/backend/routes/dashboard/agentLocations.js @@ -6,14 +6,8 @@ const { getTimeFilter } = require('./helpers'); // ─── 1. GET /api/dashboard/agent-locations ────────────────────────────────────── router.get('/agent-locations', async (req, res) => { try { - const isGlobalUser = req.user?.role === 'SUPER_ADMIN' || - ((!req.user?.site_uuid || req.user?.site_uuid === 'default') && ['SOC_ANALYST', 'ENGINEER'].includes(req.user?.role)); - let query = {}; - if (!isGlobalUser && req.user?.site_uuid) { - query.site_uuid = req.user.site_uuid; - } - if (req.user?.role === 'AGENT_VIEWER' && req.user?.agent_uuid) { + if (req.user?.role === 'AGENT_VIEWER' && req.user?.agent_uuid && !req.user?._viewAsMode) { query.agent_uuid = req.user.agent_uuid; } @@ -28,7 +22,8 @@ router.get('/agent-locations', async (req, res) => { // ─── 2. POST /api/dashboard/agent-locations ───────────────────────────────────── router.post('/agent-locations', async (req, res) => { try { - if (req.user?.role !== 'SUPER_ADMIN' && req.user?.role !== 'TENANT_ADMIN') { + const effectiveRole = req.user?._originalRole || req.user?.role; + if (effectiveRole !== 'SUPER_ADMIN' && effectiveRole !== 'TENANT_ADMIN') { return res.status(403).json({ ok: false, error: 'Only administrators can configure agent geolocations.' }); } const { agent_uuid, latitude, longitude, label } = req.body; @@ -36,35 +31,11 @@ router.post('/agent-locations', async (req, res) => { return res.status(400).json({ ok: false, error: 'agent_uuid, latitude, and longitude are required' }); } - // Determine site_uuid - let siteUuid = null; - const isGlobalUser = req.user?.role === 'SUPER_ADMIN' || - ((!req.user?.site_uuid || req.user?.site_uuid === 'default') && ['SOC_ANALYST', 'ENGINEER'].includes(req.user?.role)); - - if (!isGlobalUser && req.user?.site_uuid) { - const agentBelongs = await Summary.findOne({ agent_uuid, site_uuid: req.user.site_uuid }); - if (!agentBelongs) { - return res.status(403).json({ ok: false, error: 'Unauthorized: This agent does not belong to your tenant.' }); - } - siteUuid = req.user.site_uuid; - } else { - // Find the site_uuid from Summary collection for this agent - const summaryDoc = await Summary.findOne({ agent_uuid }); - if (summaryDoc) { - siteUuid = summaryDoc.site_uuid; - } else { - // Fallback or use standard env site_uuid - siteUuid = process.env.BACKONE_SITE_UUID || process.env.NETIFY_SITE_UUID || '6681452d_9cae_4ff4_8ae8_0d504774265e'; - } - } - - const findQuery = { agent_uuid }; - if (!isGlobalUser && req.user?.site_uuid) { - findQuery.site_uuid = req.user.site_uuid; - } + const summaryDoc = await Summary.findOne({ agent_uuid }).lean(); + const siteUuid = summaryDoc?.site_uuid || process.env.BACKONE_SITE_UUID || process.env.NETIFY_SITE_UUID || '6681452d_9cae_4ff4_8ae8_0d504774265e'; const upserted = await CustomAgentLocation.findOneAndUpdate( - findQuery, + { agent_uuid }, { agent_uuid, site_uuid: siteUuid, @@ -85,20 +56,12 @@ router.post('/agent-locations', async (req, res) => { // ─── 3. DELETE /api/dashboard/agent-locations/:agent_uuid ──────────────────────── router.delete('/agent-locations/:agent_uuid', async (req, res) => { try { - if (req.user?.role !== 'SUPER_ADMIN' && req.user?.role !== 'TENANT_ADMIN') { + const effectiveRole = req.user?._originalRole || req.user?.role; + if (effectiveRole !== 'SUPER_ADMIN' && effectiveRole !== 'TENANT_ADMIN') { return res.status(403).json({ ok: false, error: 'Only administrators can delete agent geolocations.' }); } const { agent_uuid } = req.params; - - let query = { agent_uuid }; - const isGlobalUser = req.user?.role === 'SUPER_ADMIN' || - ((!req.user?.site_uuid || req.user?.site_uuid === 'default') && ['SOC_ANALYST', 'ENGINEER'].includes(req.user?.role)); - - if (!isGlobalUser && req.user?.site_uuid) { - query.site_uuid = req.user.site_uuid; - } - - const resDelete = await CustomAgentLocation.deleteOne(query); + const resDelete = await CustomAgentLocation.deleteOne({ agent_uuid }); res.json({ ok: true, deleted: resDelete.deletedCount > 0 }); } catch (err) { console.error('[DELETE /agent-locations]', err.message); diff --git a/backend/server.js b/backend/server.js index 015658c..8cf576c 100644 --- a/backend/server.js +++ b/backend/server.js @@ -77,6 +77,7 @@ const { // ─── Protected Dashboard Routes ─────────────────────────────────────────────── const dashboardRoutes = require('./routes/dashboard'); +app.use('/api/dashboard', dashboardRoutes.rebrandMiddleware); // Override /api/dashboard/app-details to show real-time device mapping per application app.get('/api/dashboard/app-details', requireAuth, (req, res) => { diff --git a/src/components/dashboard/TopWidgets.tsx b/src/components/dashboard/TopWidgets.tsx index 653afd6..8b690e9 100644 --- a/src/components/dashboard/TopWidgets.tsx +++ b/src/components/dashboard/TopWidgets.tsx @@ -29,6 +29,7 @@ export function TopWidgets({ topApps, topProtocols }: TopWidgetsProps) { const protocolsData = (topProtocols.data || []).map(p => ({ ...p, + protocol_label: formatAppLabel(p.protocol_label), total: (p.download || 0) + (p.upload || 0) })); diff --git a/src/components/ui/DeviceDomainsTab.tsx b/src/components/ui/DeviceDomainsTab.tsx index 9b04819..29d42a0 100644 --- a/src/components/ui/DeviceDomainsTab.tsx +++ b/src/components/ui/DeviceDomainsTab.tsx @@ -2,7 +2,7 @@ import { useState } from "react"; import { Globe } from "lucide-react"; -import { fmtBytes } from "@/lib/utils"; +import { fmtBytes, formatAppLabel } from "@/lib/utils"; import { Pagination } from "./Pagination"; import { UniversalFilters, useUniversalFilterState, FilterConfig } from "./UniversalFilters"; @@ -28,7 +28,7 @@ export default function DeviceDomainsTab({ domains, totalDownload, totalUpload } }; const filterConfigs: FilterConfig[] = [ - { id: "app_label", label: "Domain", type: "select", value: filters.app_label, options: opts("app_label") }, + { id: "app_label", label: "Domain", type: "select", value: filters.app_label, options: opts("app_label"), formatter: formatAppLabel }, { id: "sort_download", label: "Sort Download", type: "select", value: filters.sort_download, options: ["Descending", "Ascending"] }, { id: "sort_upload", label: "Sort Upload", type: "select", value: filters.sort_upload, options: ["Descending", "Ascending"] }, ]; @@ -93,8 +93,8 @@ export default function DeviceDomainsTab({ domains, totalDownload, totalUpload } return (
-
- {dom.app_label} +
+ {formatAppLabel(dom.app_label)} {pct}%
diff --git a/src/components/ui/DeviceIdentityCard.tsx b/src/components/ui/DeviceIdentityCard.tsx index 0c7a985..c944b84 100644 --- a/src/components/ui/DeviceIdentityCard.tsx +++ b/src/components/ui/DeviceIdentityCard.tsx @@ -130,7 +130,7 @@ export default function DeviceIdentityCard({
{domains.slice(0, 5).map((d: any, i: number) => (
- {d.app_label} + {formatAppLabel(d.app_label)} {fmtBytes((d.download || 0) + (d.upload || 0))}
))} diff --git a/src/components/ui/GlobeMap.tsx b/src/components/ui/GlobeMap.tsx index b2920ce..3d40342 100644 --- a/src/components/ui/GlobeMap.tsx +++ b/src/components/ui/GlobeMap.tsx @@ -23,6 +23,15 @@ export const GlobeMap = ({ data }: GlobeMapProps) => { const destPoints = pointsData.filter((pt) => !pt.isOrigin); const originPoints = pointsData.filter((pt) => pt.isOrigin); + const zoom = Math.max(position.zoom || 1, 1); + const invZoom = 1 / zoom; + + const handleSelectPoint = (pt: GlobePointData) => { + setSelectedPoint(pt); + const targetZoom = pt.isOrigin ? Math.max(zoom, 8) : Math.max(zoom, 3.5); + setPosition({ coordinates: [pt.lng, pt.lat], zoom: targetZoom }); + }; + const mapBorderColor = isLight ? "#ffffff" : "#0ea5e9"; const mapFillColor = isLight ? "#4ade80" : "#0f172a"; const mapHoverFill = isLight ? "#22c55e" : "#1e293b"; @@ -54,7 +63,7 @@ export const GlobeMap = ({ data }: GlobeMapProps) => { center={position.coordinates as [number, number]} onMoveEnd={setPosition} minZoom={1} - maxZoom={8} + maxZoom={35} > {({ geographies }) => @@ -64,7 +73,7 @@ export const GlobeMap = ({ data }: GlobeMapProps) => { geography={geo} fill={mapFillColor} stroke={mapBorderColor} - strokeWidth={0.5} + strokeWidth={0.5 * invZoom} onClick={() => setSelectedPoint(null)} style={{ default: { outline: "none" }, @@ -84,7 +93,7 @@ export const GlobeMap = ({ data }: GlobeMapProps) => { if (isLocal) { return ( - + ); } @@ -106,7 +115,7 @@ export const GlobeMap = ({ data }: GlobeMapProps) => { key={`arc-${i}`} coordinates={coordinates} stroke={color} - strokeWidth={1.6} + strokeWidth={1.6 * invZoom} strokeLinecap="round" strokeOpacity={0.92} strokeDasharray="2 4 4 4 8 78" @@ -120,12 +129,12 @@ export const GlobeMap = ({ data }: GlobeMapProps) => { { e.stopPropagation(); setSelectedPoint(pt); }} + onClick={(e) => { e.stopPropagation(); handleSelectPoint(pt); }} style={{ default: { cursor: "pointer" }, hover: { cursor: "pointer" }, pressed: { cursor: "pointer" } }} > - - - + + + ))} @@ -133,13 +142,13 @@ export const GlobeMap = ({ data }: GlobeMapProps) => { { e.stopPropagation(); setSelectedPoint(pt); }} + onClick={(e) => { e.stopPropagation(); handleSelectPoint(pt); }} style={{ default: { cursor: "pointer" }, hover: { cursor: "pointer" }, pressed: { cursor: "pointer" } }} > - - - - + + + + ))} @@ -147,13 +156,13 @@ export const GlobeMap = ({ data }: GlobeMapProps) => { { e.stopPropagation(); if (lbl.point) setSelectedPoint(lbl.point); }} + onClick={(e) => { e.stopPropagation(); if (lbl.point) handleSelectPoint(lbl.point); }} style={{ default: { cursor: "pointer" }, hover: { cursor: "pointer" }, pressed: { cursor: "pointer" } }} > {lbl.name} @@ -178,7 +187,7 @@ export const GlobeMap = ({ data }: GlobeMapProps) => {

{selectedPoint.name}

- Lat: {selectedPoint.lat.toFixed(4)}, Lng: {selectedPoint.lng.toFixed(4)} + Lat: {selectedPoint.lat.toFixed(6)}, Lng: {selectedPoint.lng.toFixed(6)}