1. Overview

The Executive Dashboard is a comprehensive analytics and monitoring interface designed for executive-level stakeholders in the Nimbly audit management system. It provides real-time insights into operational metrics, [issue tracking](../Issue Tracker/IssueTrackerOverview.md), quality control performance, and geographical data visualization.

1.1 Key Features

  • Multi-view Dashboard: Supports [Issues](../Issue Tracker/IssueTrackerOverview.md), Reports, and QC (Quality Control) views
  • Real-time Data Visualization: Interactive charts, heatmaps, and performance indicators
  • Advanced Filtering: Sophisticated filter system for date ranges, sites, departments, and users
  • Responsive Design: Optimized for both desktop and mobile devices
  • State Persistence: Saves user preferences and filter settings
  • Map Integration: Geographic visualization of [issues](../Issue Tracker/IssueTrackerOverview.md) and site performance

1.2 Purpose

The Executive Dashboard serves as a centralized command center for executives to:

  • Monitor operational KPIs across multiple sites and departments
  • Track issue trends and resolution rates
  • Analyze quality control performance metrics
  • Identify geographical patterns in operational data
  • Make data-driven decisions based on real-time insights

2. Architecture & Module Structure

The Executive Dashboard follows a modular architecture pattern with clear separation of concerns:

graph TB
    A[ExecutivePage.tsx] --> B[Header Component]
    A --> C[ExecutiveFilters]
    A --> D[Performance Cards]
    A --> E[Line Chart Metrics]
    A --> F[Map Component]
    A --> G[QC Performance]
    A --> H[Basic Dashboard View]
    
    B --> I[Dashboard Toggle]
    B --> J[Filter Toggle]
    B --> K[Map Toggle]
    
    D --> L[Site Performance]
    D --> M[User Performance]
    D --> N[Department Performance]
    
    subgraph State Management
        O[Redux Store]
        P[Executive Dashboard Reducer]
        Q[Actions & Thunks]
    end
    
    subgraph Services
        R[Header Service]
        S[Filter Service]
        T[Dashboard Service]
    end
    
    A --> O
    O --> P
    P --> Q
    Q --> R
    Q --> S
    Q --> T

2.1 Directory Structure

src/pages/dashboardRevamp/executivePage/
├── ExecutivePage.tsx           # Main container component
├── Header.tsx                  # Dashboard header with controls
├── Header.css                  # Header styling
├── DashboardToggle.tsx         # Toggle between dashboard views
├── ExecutiveFilters/           # Filter components
│   └── ExecutiveFilters.tsx    
├── PerfomanceCard.tsx          # Performance metric cards
├── LineChartMetrics.tsx        # Time-series charts
├── MapComponent.tsx            # Geographic visualization
├── QCPerfomance.tsx           # Quality control metrics
├── HealthScore.tsx            # Health score indicators
├── InfoButtonsExecutive.tsx   # Information tooltips
├── useInitialFetch.ts         # Initial data fetching hook
├── useConstData.tsx           # Constants and configuration
├── tableConfig.ts             # Table configurations
└── downloadReportData.ts      # Report download utilities

3. Routes & Navigation

3.1 Route Configuration

The Executive Dashboard is accessible through the following routes defined in admin-routes.js:

Route PathComponentAccess ControlLine Reference
/analytics/executiveExecutiveDashboardPageRoleResources.DASHBOARD_OVERVIEW_ALLLine 761-765
/analytics/operationalOperationalDashboardPageRoleResources.DASHBOARD_OVERVIEW_ALLLine 767-772
/analytics/operational/issue-insightsOperationalIssueInsightsDashboardPageRoleResources.DASHBOARD_OVERVIEW_ALLLine 774-779
/analytics/operational/[report](../Reports/ReportsOverview.md)-insightsOperationalReportInsightsDashboardPageRoleResources.DASHBOARD_OVERVIEW_ALLLine 781-786

3.2 Navigation Flow

graph LR
    A[Dashboard Menu] --> B[/analytics/executive]
    B --> C{Dashboard Type}
    C -->|Issues Tab| D[Issues View]
    C -->|Reports Tab| E[Reports View]
    C -->|QC Tab| F[QC View]
    B --> G{Basic Dashboard Toggle}
    G -->|On| H[Basic Dashboard View]
    G -->|Off| I[Advanced Dashboard View]

Component Hierarchy

The Executive Dashboard component hierarchy is structured for maximum reusability and maintainability:

Main Component Tree

ExecutivePage
├── Layout (Wrapper)
│   └── AdminPage
│       └── PageWrapper
│           ├── Header
│           │   ├── DashboardToggle
│           │   ├── FilterToggle
│           │   └── MapToggle
│           ├── ExecutiveFilters (Conditional)
│           ├── LineChartMetrics (Mobile Hidden)
│           ├── MapComponent (Conditional)
│           └── Dashboard Content
│               ├── BasicDashboardPage (Conditional)
│               └── Advanced Dashboard
│                   ├── TabButtons
│                   ├── QCPerfomance (QC Tab)
│                   └── Performance Cards (Issues/Reports Tab)
│                       ├── PrimaryCard
│                       └── SecondaryCard (Desktop Only)

Component Responsibilities

ExecutivePage Component

Main container component that orchestrates the entire dashboard:

  • Manages local state for UI toggles and data loading
  • Handles initial data fetching and filter restoration
  • Coordinates component rendering based on active view
  • Manages responsive behavior for mobile/desktop

Header Component

Controls dashboard view options and provides navigation:

  • Dashboard type toggle (Basic/Advanced)
  • Map visibility toggle
  • Filter panel toggle
  • Applied filter indicator

Performance Cards

Displays key metrics with drill-down capabilities:

  • Site-based performance metrics
  • User-based performance metrics
  • Department-based performance metrics
  • Dynamic metric selection

State Management & Data Flow

The Executive Dashboard uses Redux for centralized state management with a dedicated reducer:

Redux Store Structure

interface ExecutiveDashboardState {
    type: DashboardTabs;              // Current dashboard tab (Issues/Reports/QC)
    showMap: boolean;                 // Map visibility toggle
    showFilters: boolean;             // Filter panel visibility
    lastSelectedWidget: {             // User's last selected metrics
        issuesConfig: {
            primaryCard: string;
            secondaryCard: string;
        };
        reportsConfig: {
            primaryCard: string;
            secondaryCard: string;
        };
    };
    filters: ExecutiveFiltersI;       // Applied filters
    searchTrigger: number;            // Trigger for data refresh
}

Data Flow Diagram

sequenceDiagram
    participant U as User
    participant C as Component
    participant R as Redux Store
    participant S as Services
    participant API as Backend API
    
    U->>C: Interacts with Dashboard
    C->>R: Dispatch Action
    R->>S: Trigger Service Call
    S->>API: HTTP Request
    API-->>S: Response Data
    S-->>R: Update Store
    R-->>C: State Update
    C-->>U: Re-render UI

Key Actions

  • setDashboardType: Changes active dashboard tab
  • setShowMap: Toggles map visibility
  • setShowFilters: Toggles filter panel
  • setLastSelectedWidget: Saves user’s metric preferences
  • setFilters: Updates active filters
  • setSearchTrigger: Triggers data refresh

API Endpoints & Services

The Executive Dashboard integrates with multiple backend services to fetch and manage data:

Service Architecture

graph TB
    subgraph Executive Dashboard Services
        A[header.service.ts]
        B[perfomanceCard.service.ts]
        C[sidebar.service.ts]
        D[qcPerfomance.service.ts]
    end
    
    subgraph API Endpoints
        E[/statistics/dashboard/*]
        F[/api-statistics/dashboard/*]
    end
    
    A --> E
    B --> E
    B --> F
    C --> E
    D --> E

API Endpoints Table

Service FileEndpointMethodPurposePayload/Parameters
header.service.ts/statistics/dashboard/issuePOSTFetch heatmap issue flagsFilters, date range
/statistics/dashboard/metricsGETFetch last updated widget preferences-
/statistics/dashboard/upsertMetricsPOSTSave widget preferencesWidget configuration
perfomanceCard.service.ts/statistics/dashboard/issue/detailPOSTFetch executive health scoreFilters, metric type
/statistics/dashboard/issuePOSTFetch issue listFilters, pagination
/statistics/dashboard/[report](../Reports/ReportsOverview.md)POSTFetch report listFilters, pagination
/api-statistics/dashboard/[report](../Reports/ReportsOverview.md)/download/viewPOSTPreview report downloadInternal API
/statistics/dashboard/[report](../Reports/ReportsOverview.md)/downloadPOSTDownload report fileExport parameters
/statistics/dashboard/issue/download/viewPOSTPreview issue downloadExport parameters
/statistics/dashboard/issue/listPOSTFetch issue tracker dataFilters, grouping
/statistics/dashboard/issue/downloadPOSTDownload issue fileExport parameters
sidebar.service.ts/statistics/dashboard/detail?metric=issue-[report](../Reports/ReportsOverview.md)-ratio&groupBy=[department](../Departments/DepartmentOverview.md)GETFetch department ratioQuery parameters
/statistics/dashboard/issue/detail?metric=irr&groupBy=issueGETFetch IRR (Issue Resolution Rate)Query parameters
/statistics/dashboard/[report](../Reports/ReportsOverview.md)/detail?metric=rcr&groupBy=[report](../Reports/ReportsOverview.md)GETFetch RCR (Report Completion Rate)Query parameters
/statistics/dashboard/issue/detail?metric=issue-voc&groupBy=issueGETFetch VOC (Voice of Customer) ratioQuery parameters
qcPerfomance.service.ts/statistics/dashboard/qc-performancePOSTFetch QC performance metricsFilters, date range
/statistics/dashboard/qc-performance/customPOSTFetch custom QC metricsCustom parameters
/statistics/dashboard/qc-performance/downloadPOSTDownload QC reportExport parameters
/statistics/dashboard/qc-performance/custom/downloadPOSTDownload custom QC reportCustom export params

Filter System

The Executive Dashboard features a comprehensive filtering system that allows users to slice and dice data across multiple dimensions:

Filter Structure

interface ExecutiveFiltersI {
    startDate: string;              // ISO date string
    endDate: string;                // ISO date string
    sites: string[];                // Array of site IDs
    departments: string[];          // Array of department IDs
    users: string[];                // Array of user IDs
    questionnaires: string[];       // Array of questionnaire IDs
    categories: string[];           // Array of category IDs (Issues only)
    managedByDeptIDs?: string[];    // Managed by department filter
    managedByUserIDs?: string[];    // Managed by user filter
    siteRegionIDs?: string[];       // Site group/region filter
    roles?: string[];               // User role filter
}

Filter Categories

1. Date Range Filter

  • Uses preset date ranges (Today, Yesterday, Last 7 days, etc.)
  • Custom date range selection with calendar picker
  • Responsive design with compact calendar for mobile

2. Organizational Filters

  • Sites: Multi-select dropdown with all active sites
  • Departments: Hierarchical department selection
  • Users: Filtered by selected departments/sites
  • User Roles: Filter by user roles (Admin, Auditor, etc.)

3. Operational Filters

  • Questionnaires: Filter by audit questionnaire types
  • Categories: Issue categories (only visible in Issues tab)
  • Site Groups/Regions: Geographic grouping of sites

4. Advanced Filters (Permission-based)

  • Managed By Department: For organizations with data visibility rules
  • Managed By Users: User-based data filtering
  • Site Regions: Regional grouping for multi-location operations

Filter Implementation Flow

graph LR
    A[User Selects Filter] --> B{Filter Type}
    B -->|Date| C[Update Date Range]
    B -->|Multi-Select| D[Update Selection Array]
    C --> E[Dispatch setFilters Action]
    D --> E
    E --> F[Update Redux Store]
    F --> G[Trigger Search]
    G --> H[Fetch Filtered Data]
    H --> I[Update Dashboard]

Filter Persistence

  • Filters are saved to backend using fetchSaveFilters service
  • Saved filters are restored on dashboard load
  • Users can save custom filter presets with bookmark icon
  • Reset button clears all filters and saved preferences

Performance Metrics Components

The Performance Cards are the core visualization components that display key operational metrics:

Performance Card Architecture

graph TB
    A[PerfomanceCard Component] --> B[Metric Selector]
    A --> C[View Selector]
    A --> D[Chart/Table View]
    A --> E[Health Score]
    
    B --> F[Site View]
    B --> G[User View]
    B --> H[Department View]
    
    C --> I[Graph View]
    C --> J[Table View]
    
    D --> K[Column Chart]
    D --> L[Bar Chart]
    D --> M[Data Table]

Key Features

1. Dynamic Metric Selection

  • Site Performance: View metrics grouped by sites
  • User Performance: Analyze individual user contributions
  • Department Performance: Department-level aggregations
  • Category Performance: Issue categorization analysis (Issues tab only)

2. View Types

  • Graph View: Interactive charts with drill-down capabilities
    • Column charts for top/bottom performers
    • Horizontal bar charts for comparative analysis
  • Table View: Detailed tabular data with sorting and filtering
    • Configurable columns based on selected metrics
    • Export capabilities for further analysis

3. Metric Types by Dashboard Tab

Issues Tab Metrics:

  • Open Issues Count
  • Issue Resolution Rate (IRR)
  • Average Resolution Time
  • Issue Attachments Count
  • Total Issues Created

Reports Tab Metrics:

  • Missed Reports Count
  • Report Completion Rate (RCR)
  • Scheduled vs Adhoc Reports
  • Average Submission Delay
  • Total Reports Submitted

4. Health Score Integration

The Performance Cards include health score visualization that provides:

  • Overall performance rating (0-100)
  • Color-coded indicators (Green/Yellow/Red)
  • Trend analysis compared to previous period
  • Quick insights into operational health

Performance Card Data Flow

sequenceDiagram
    participant User
    participant PerfomanceCard
    participant Service
    participant API
    
    User->>PerfomanceCard: Select Metric/View
    PerfomanceCard->>Service: Fetch Data Request
    Service->>API: POST /statistics/dashboard/issue or /report
    API-->>Service: Performance Data
    Service-->>PerfomanceCard: Processed Data
    PerfomanceCard->>PerfomanceCard: Render Chart/Table
    PerfomanceCard-->>User: Display Results

Map & Heatmap Functionality

The Executive Dashboard includes an interactive map component for geographical visualization:

Map Component Features

1. Heatmap Visualization

  • Issue Density: Visual representation of issue concentration by location
  • Site Performance: Color-coded markers indicating site health
  • Flag System:
    • 🔴 Red Flag: Critical issues or poor performance
    • 🟡 Yellow Flag: Warning level or moderate performance
    • 🟢 Green Flag: Good performance or no issues

2. Interactive Elements

  • Clustered Markers: Automatic grouping of nearby sites
  • Zoom Controls: Dynamic zoom based on data boundaries
  • Click Actions: Drill-down to site-specific details
  • Custom Controls: Loading indicators and map controls

3. Map Data Integration

interface HeatmapIssueFlagsI {
    sites: Array<{
        siteID: string;
        siteName: string;
        latitude: number;
        longitude: number;
        redFlag: number;
        yellowFlag: number;
        greenFlag: number;
        totalIssues: number;
    }>;
}

Map Implementation Flow

graph LR
    A[Toggle Map View] --> B[Fetch Heatmap Data]
    B --> C[Process Site Coordinates]
    C --> D[Initialize Google Maps]
    D --> E[Plot Markers]
    E --> F[Apply Clustering]
    F --> G[Set Map Bounds]
    G --> H[Display Interactive Map]

Map Performance Optimization

  • Lazy Loading: Map component loads only when toggled
  • Marker Clustering: Reduces rendering overhead for multiple sites
  • Bounds Calculation: Auto-adjusts viewport to show all markers
  • Debounced Updates: Prevents excessive re-renders during interactions

Dashboard Types & Views

The Executive Dashboard supports multiple views and dashboard types to cater to different user needs:

1. Executive Dashboard (Advanced View)

The default view providing comprehensive analytics with multiple visualization options:

graph TB
    A[Executive Dashboard] --> B[Issues Tab]
    A --> C[Reports Tab]
    A --> D[QC Tab]
    
    B --> E[Performance Cards]
    B --> F[Line Charts]
    B --> G[Map View]
    
    C --> H[Performance Cards]
    C --> I[Line Charts]
    C --> J[Map View]
    
    D --> K[QC Performance Table]
    D --> L[Custom QC View]

Issues Tab

  • Purpose: Track and analyze operational issues
  • Key Metrics: Open issues, resolution rates, issue categories
  • Visualizations: Performance cards, trend charts, geographic distribution
  • Drill-down: Category-wise analysis, user performance, time-based trends

Reports Tab

  • Purpose: Monitor report submission and completion
  • Key Metrics: Missed reports, completion rates, schedule adherence
  • Visualizations: Performance cards, submission trends, site comparisons
  • Analysis: Scheduled vs adhoc reports, department performance

QC (Quality Control) Tab

  • Purpose: Quality control performance monitoring
  • Modes:
    • Global QC: Standard QC metrics across all questionnaires
    • Custom QC: Organization-specific QC configurations
  • Metrics: QC scores, flag distributions, category performance
  • Features: Detailed scoring breakdowns, drill-down to categories

2. Basic Dashboard View

A simplified dashboard for quick operational insights:

Components

  • Issue Data Summary: High-level issue statistics
  • Report Metrics: Key report performance indicators
  • Issue Charts: Visual breakdown by categories/questionnaires
  • Summary Views: Site, department, and user summaries
  • Trends: Historical performance trends

Features

  • Streamlined interface for faster loading
  • Pre-configured metrics without customization
  • Mobile-optimized layout
  • Essential KPIs only

3. Line Chart Metrics (Sidebar)

Always-visible key performance indicators:

Metrics Displayed

  1. IRR (Issue Resolution Rate)

    • Formula: (Resolved Issues / Total Issues) × 100
    • Trend visualization over time
    • Color-coded performance indicators
  2. RCR (Report Completion Rate)

    • Formula: (Completed Reports / Total Scheduled) × 100
    • Historical trend analysis
    • Period-over-period comparison
  3. Lowest Performing Department

    • Real-time identification
    • Based on composite performance score
    • Quick action indicator
  4. VoC (Voice of Customer) Issues

    • Customer-related issue tracking
    • Clickable for detailed view
    • Inverse trend indicator (lower is better)

Dashboard Toggle Logic

stateDiagram-v2
    [*] --> AdvancedView: Default
    AdvancedView --> BasicView: Toggle On
    BasicView --> AdvancedView: Toggle Off
    
    AdvancedView --> IssuesTab: Tab Selection
    AdvancedView --> ReportsTab: Tab Selection
    AdvancedView --> QCTab: Tab Selection
    
    BasicView --> IntegratedView: All Metrics

Security & Access Control

The Executive Dashboard implements multi-layer security:

1. Route-Level Access Control

  • Required Permission: RoleResources.DASHBOARD_OVERVIEW_ALL
  • Route Protection: Implemented via RouteWithValidation component
  • Unauthorized Access: Redirects to access denied page

2. Feature-Based Access

  • Data Visibility Rules: Organization-specific data access
  • Managed By Filters: Permission-based filter visibility
  • Role-Based Metrics: Different metrics based on user role

3. Data Security

  • API Authentication: Firebase token-based authentication
  • Data Filtering: Server-side filtering based on user permissions
  • Audit Trail: All data exports are logged

Access Control Flow

sequenceDiagram
    participant User
    participant Router
    participant Auth
    participant Dashboard
    participant API
    
    User->>Router: Navigate to /analytics/executive
    Router->>Auth: Check Permissions
    Auth-->>Router: Permission Result
    alt Has Permission
        Router->>Dashboard: Load Component
        Dashboard->>API: Fetch Data with Auth Token
        API-->>Dashboard: Filtered Data
        Dashboard-->>User: Display Dashboard
    else No Permission
        Router-->>User: Redirect to Access Denied
    end

Package Dependencies

The Executive Dashboard relies on several key packages:

PackageVersionPurpose
react^17.0.2Core framework
react-redux^7.2.6State management
redux^4.1.2State container
redux-saga^1.1.3Side effects management
react-router-dom^5.3.0Routing
styled-components^5.3.3Component styling
react-i18next^11.15.1Internationalization
moment^2.29.1Date manipulation
lodash^4.17.21Utility functions
react-chartjs-2^4.0.1Chart rendering
chart.js^3.7.0Chart library
@react-google-maps/api^2.7.0Google Maps integration
react-table^7.7.0Table components
react-icons^4.3.1Icon library
@nimbly-technologies/audit-componentInternalShared components
@nimbly-technologies/nimbly-commonInternalCommon utilities

Development Dependencies

PackagePurpose
typescriptType safety
@types/*TypeScript definitions
eslintCode linting
prettierCode formatting

Advanced Features & Implementation Details

1. Data Caching & Performance

Client-Side Caching

  • Redux Persistence: Selected filters and preferences persist across sessions
  • Memoization: Heavy computations cached using useMemo hooks
  • Lazy Loading: Components load on-demand to improve initial load time

API Response Caching

  • Cache Duration: 5 minutes for static data, real-time for critical metrics
  • Cache Invalidation: Automatic on filter changes or manual refresh
  • Optimistic Updates: UI updates before server confirmation for better UX

2. Export Functionality

Supported Formats

  • CSV: Comma-separated values for Excel/spreadsheet analysis
  • PDF: Formatted reports with charts and tables
  • XLSX: Excel workbook with multiple sheets

Export Configuration

interface ExportConfig {
    format: 'csv' | 'pdf' | 'xlsx';
    includeCharts: boolean;
    dateRange: { start: Date; end: Date };
    filters: ExecutiveFiltersI;
    columns: string[];
}

3. Real-time Updates

Current Polling Mechanism

  • Auto-refresh every 5 minutes (configurable)
  • Manual refresh button
  • Refresh indicator showing last update time

4. Mobile Responsiveness

Responsive Breakpoints

  • Desktop: > 1280px (full features)
  • Tablet: 768px - 1280px (adjusted layout)
  • Mobile: < 768px (mobile-optimized)

Mobile-Specific Features

  • Compact filters with modal overlay
  • Swipeable tabs
  • Touch-optimized controls
  • Reduced data density

5. Internationalization (i18n)

Supported Languages

  • English (en)
  • Indonesian (id)
  • Thai (th)
  • Spanish (es)
  • Portuguese (pt)
  • Korean (ko)
  • Chinese Mandarin (cmn)

Implementation

// Example usage
const { t } = useTranslation();
<h1>{t('label.dashboardRevamp.executiveDashboard.title')}</h1>

Troubleshooting & Common Issues

1. Performance Issues

Problem: Dashboard loads slowly Solutions:

  • Check network throttling
  • Verify API response times
  • Enable browser caching
  • Reduce filter complexity

2. Data Inconsistencies

Problem: Metrics don’t match expectations Solutions:

  • Verify filter selections
  • Check timezone settings
  • Confirm data freshness
  • Validate calculation logic

3. Map Loading Issues

Problem: Map doesn’t display Solutions:

  • Verify Google Maps API key
  • Check browser console for errors
  • Ensure location permissions
  • Test network connectivity

4. Export Failures

Problem: Export doesn’t complete Solutions:

  • Check file size limits
  • Verify user permissions
  • Test with smaller date ranges
  • Monitor browser memory usage

15. Integration with Operational Dashboards

The Executive Dashboard serves as a gateway to more detailed operational dashboards:

15.1 Dashboard Hierarchy

graph TD
    A[Executive Dashboard] --> B[Operational KPI Dashboard]
    B --> C[Issue Insights Dashboard]
    B --> D[Report Insights Dashboard]
    
    A --> E[Basic Dashboard View]
    
    style A fill:#f9f,stroke:#333,stroke-width:4px
    style B fill:#bbf,stroke:#333,stroke-width:2px
    style C fill:#dfd,stroke:#333,stroke-width:2px
    style D fill:#dfd,stroke:#333,stroke-width:2px

15.2 Operational KPI Dashboard Integration

15.2.1 Navigation Flow

  • Accessible via /analytics/operational route
  • Inherits filter state from Executive Dashboard
  • Provides drill-down capabilities for detailed analysis

15.2.2 Shared Components

// Common header component
<OperationalPageHeader
    title={t('label.dashboardRevamp.operationalKPI')}
    toggleFilter={() => dispatch(setShowFilters(!showFilters))}
    isShowAppliedFilters={showFilterIndicator}
/>

15.2.3 Data Synchronization

  • Filters are synchronized between dashboards
  • User preferences persist across navigation
  • State management follows consistent patterns

15.3 Issue Insights Dashboard

15.3.1 Purpose

Detailed analysis of operational issues with advanced filtering and grouping:

15.3.2 Key Features

  • Multi-dimensional Analysis: Group by site, user, department, questionnaire
  • Time-based Trending: Daily, weekly, monthly views
  • Advanced Filtering: Category-specific filters
  • Export Capabilities: Detailed issue reports

15.3.3 Integration Points

// Navigation from Operational Dashboard
const navigateToIssueInsights = () => {
    history.push('/analytics/operational/issue-insights', {
        filters: currentFilters,
        source: 'operational-kpi'
    });
};

15.4 Report Insights Dashboard

15.4.1 Purpose

Comprehensive report analysis and submission tracking:

15.3.2 Key Features

  • Submission Metrics: On-time vs late submissions
  • Schedule Analysis: Scheduled vs adhoc reports
  • User Performance: Individual submission rates
  • Trend Analysis: Historical performance tracking

15.4.3 Data Flow

sequenceDiagram
    participant Executive
    participant Operational
    participant ReportInsights
    participant API
    
    Executive->>Operational: Navigate with filters
    Operational->>ReportInsights: Drill down to reports
    ReportInsights->>API: Fetch detailed data
    API-->>ReportInsights: Report metrics
    ReportInsights-->>User: Display insights

16. Advanced Implementation Patterns

16.1 Custom Hooks Architecture

16.1.1 useInitialFetch Hook

Manages initial data loading and filter restoration:

const useInitialFetch = () => {
    const dispatch = useDispatch();
    const { filters } = useSelector(state => state.executiveDashboard);
    
    useEffect(() => {
        // Restore saved filters
        fetchSavedFilters().then(savedFilters => {
            if (savedFilters) {
                dispatch(setFilters(savedFilters));
            }
        });
        
        // Initialize data fetching
        dispatch(fetchInitialData());
    }, []);
};

16.1.2 useDownloadFileState Hook

Manages file export states across components:

const useDownloadFileState = () => {
    const [downloadStates, setDownloadStates] = useState({
        isPdfDownloading: false,
        isCsvDownloading: false,
        isXlsxDownloading: false
    });
    
    const updateDownloadState = (format, isDownloading) => {
        setDownloadStates(prev => ({
            ...prev,
            [`is${format}Downloading`]: isDownloading
        }));
    };
    
    return { ...downloadStates, updateDownloadState };
};

16.2 Service Layer Architecture

16.2.1 API Service Pattern

// Base service configuration
const apiService = {
    baseURL: process.env.REACT_APP_API_URL,
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${getAuthToken()}`
    }
};
 
// Service implementation
export const fetchExecutiveMetrics = async (filters) => {
    try {
        const response = await apiService.post('/statistics/dashboard/executive', {
            ...filters,
            timezone: moment.tz.guess()
        });
        return response.data;
    } catch (error) {
        handleApiError(error);
        throw error;
    }
};

16.3 Performance Optimization Techniques

16.3.1 Memoization Strategy

// Expensive calculations memoized
const processedData = useMemo(() => {
    return heavyDataProcessing(rawData, filters);
}, [rawData, filters]);
 
// Selector memoization
const selectFilteredData = createSelector(
    [selectRawData, selectFilters],
    (data, filters) => applyFilters(data, filters)
);

16.3.2 Lazy Loading Implementation

// Dynamic imports for code splitting
const PerformanceCard = lazy(() => 
    import(/* webpackChunkName: "performance-card" */ './PerformanceCard')
);
 
// Usage with Suspense
<Suspense fallback={<LoadingSpinner />}>
    <PerformanceCard {...props} />
</Suspense>

16.4 Error Handling & Recovery

16.4.1 Global Error Boundary

class DashboardErrorBoundary extends Component {
    state = { hasError: false, error: null };
    
    static getDerivedStateFromError(error) {
        return { hasError: true, error };
    }
    
    componentDidCatch(error, errorInfo) {
        logErrorToService(error, errorInfo);
    }
    
    render() {
        if (this.state.hasError) {
            return <ErrorFallback onRetry={() => window.location.reload()} />;
        }
        return this.props.children;
    }
}

16.4.2 API Error Handling

const handleApiError = (error) => {
    if (error.response) {
        // Server responded with error
        switch (error.response.status) {
            case 401:
                redirectToLogin();
                break;
            case 403:
                showAccessDeniedMessage();
                break;
            case 500:
                showServerErrorMessage();
                break;
            default:
                showGenericErrorMessage();
        }
    } else if (error.request) {
        // Network error
        showNetworkErrorMessage();
    }
};

16.5 Testing Implementation

16.5.1 Component Testing

describe('ExecutiveDashboard', () => {
    it('should render performance cards when data is loaded', async () => {
        const { getByTestId } = render(
            <Provider store={mockStore}>
                <ExecutiveDashboard />
            </Provider>
        );
        
        await waitFor(() => {
            expect(getByTestId('performance-card')).toBeInTheDocument();
        });
    });
    
    it('should update filters on selection', async () => {
        const { getByLabelText } = render(<ExecutiveFilters />);
        
        const siteFilter = getByLabelText('Sites');
        fireEvent.change(siteFilter, { target: { value: 'site1' } });
        
        expect(mockDispatch).toHaveBeenCalledWith(
            setFilters({ sites: ['site1'] })
        );
    });
});

16.5.2 Integration Testing

describe('Dashboard Integration', () => {
    it('should sync filters between dashboards', async () => {
        // Set filters in executive dashboard
        const executivePage = await navigateTo('/analytics/executive');
        await executivePage.setFilters({ sites: ['site1'] });
        
        // Navigate to operational dashboard
        const operationalPage = await navigateTo('/analytics/operational');
        
        // Verify filters are preserved
        expect(operationalPage.getFilters()).toEqual({ sites: ['site1'] });
    });
});

17. Metrics Calculations & Business Logic

17.1 Issue Resolution Rate (IRR) Calculation

The IRR is a critical KPI that measures operational efficiency:

// IRR Calculation Logic
const calculateIRR = (issues: Issue[]) => {
    const totalIssues = issues.length;
    const resolvedIssues = issues.filter(issue => issue.status === 'resolved').length;
    
    if (totalIssues === 0) return 0;
    
    const irr = (resolvedIssues / totalIssues) * 100;
    return Math.round(irr * 10) / 10; // Round to 1 decimal place
};
 
// Time-based IRR calculation
const calculateTimeBasedIRR = (issues: Issue[], timeWindow: number) => {
    const now = moment();
    const windowStart = moment().subtract(timeWindow, 'days');
    
    const issuesInWindow = issues.filter(issue => 
        moment(issue.createdAt).isBetween(windowStart, now)
    );
    
    return calculateIRR(issuesInWindow);
};

17.1.1 IRR Benchmarks

  • Excellent: > 90%
  • Good: 70-90%
  • Fair: 50-70%
  • Poor: < 50%

17.2 Report Completion Rate (RCR) Calculation

RCR measures adherence to scheduled reporting:

// RCR Calculation Logic
const calculateRCR = (reports: Report[]) => {
    const scheduledReports = reports.filter(r => r.type === 'scheduled');
    const completedOnTime = scheduledReports.filter(r => 
        r.status === 'completed' && 
        moment(r.completedAt).isSameOrBefore(r.dueDate)
    );
    
    if (scheduledReports.length === 0) return 100;
    
    const rcr = (completedOnTime.length / scheduledReports.length) * 100;
    return Math.round(rcr * 10) / 10;
};
 
// Department-wise RCR
const calculateDepartmentRCR = (reports: Report[], departmentId: string) => {
    const deptReports = reports.filter(r => r.departmentId === departmentId);
    return calculateRCR(deptReports);
};

17.3 Health Score Algorithm

The health score provides a composite view of operational performance:

// Health Score Calculation
interface HealthScoreWeights {
    irr: number;
    rcr: number;
    issueAge: number;
    voc: number;
}
 
const DEFAULT_WEIGHTS: HealthScoreWeights = {
    irr: 0.35,      // 35% weight
    rcr: 0.35,      // 35% weight
    issueAge: 0.20, // 20% weight
    voc: 0.10       // 10% weight
};
 
const calculateHealthScore = (metrics: Metrics, weights = DEFAULT_WEIGHTS) => {
    // Normalize each metric to 0-100 scale
    const normalizedIRR = metrics.irr;
    const normalizedRCR = metrics.rcr;
    const normalizedIssueAge = Math.max(0, 100 - (metrics.avgIssueAge * 2));
    const normalizedVOC = Math.max(0, 100 - (metrics.vocIssueCount * 5));
    
    // Calculate weighted score
    const healthScore = 
        (normalizedIRR * weights.irr) +
        (normalizedRCR * weights.rcr) +
        (normalizedIssueAge * weights.issueAge) +
        (normalizedVOC * weights.voc);
    
    return {
        score: Math.round(healthScore),
        category: getHealthCategory(healthScore),
        trend: calculateTrend(healthScore, metrics.previousHealthScore)
    };
};
 
const getHealthCategory = (score: number): HealthCategory => {
    if (score >= 80) return { label: 'Excellent', color: '#10B981' };
    if (score >= 60) return { label: 'Good', color: '#3B82F6' };
    if (score >= 40) return { label: 'Fair', color: '#F59E0B' };
    return { label: 'Poor', color: '#EF4444' };
};

17.4 Voice of Customer (VoC) Analysis

VoC metrics track customer-related issues:

// VoC Issue Detection
const VOC_KEYWORDS = [
    'customer', 'complaint', 'feedback', 'service',
    'quality', 'satisfaction', 'experience'
];
 
const identifyVoCIssues = (issues: Issue[]) => {
    return issues.filter(issue => {
        const content = `${issue.title} ${issue.description}`.toLowerCase();
        return VOC_KEYWORDS.some(keyword => content.includes(keyword));
    });
};
 
// VoC Trend Analysis
const analyzeVoCTrend = (vocIssues: Issue[], timeWindow: number) => {
    const dailyCounts = {};
    
    vocIssues.forEach(issue => {
        const date = moment(issue.createdAt).format('YYYY-MM-DD');
        dailyCounts[date] = (dailyCounts[date] || 0) + 1;
    });
    
    // Calculate moving average
    const movingAverage = calculateMovingAverage(Object.values(dailyCounts), 7);
    
    return {
        trend: determineTrend(movingAverage),
        averageDaily: mean(Object.values(dailyCounts)),
        peak: max(Object.values(dailyCounts))
    };
};

17.5 Performance Ranking Algorithm

Ranks sites/users/departments based on composite performance:

// Ranking Algorithm
interface RankingCriteria {
    metric: string;
    weight: number;
    order: 'asc' | 'desc';
}
 
const DEFAULT_RANKING_CRITERIA: RankingCriteria[] = [
    { metric: 'irr', weight: 0.3, order: 'desc' },
    { metric: 'rcr', weight: 0.3, order: 'desc' },
    { metric: 'issueCount', weight: 0.2, order: 'asc' },
    { metric: 'avgResolutionTime', weight: 0.2, order: 'asc' }
];
 
const calculateRankings = (entities: Entity[], criteria = DEFAULT_RANKING_CRITERIA) => {
    // Calculate composite score for each entity
    const scoredEntities = entities.map(entity => {
        const compositeScore = criteria.reduce((score, criterion) => {
            const value = entity.metrics[criterion.metric];
            const normalizedValue = normalizeValue(value, criterion.metric, entities);
            const weightedValue = normalizedValue * criterion.weight;
            
            return score + (criterion.order === 'desc' ? weightedValue : 100 - weightedValue);
        }, 0);
        
        return { ...entity, compositeScore };
    });
    
    // Sort by composite score
    return scoredEntities
        .sort((a, b) => b.compositeScore - a.compositeScore)
        .map((entity, index) => ({
            ...entity,
            rank: index + 1,
            percentile: ((entities.length - index) / entities.length) * 100
        }));
};

18. Data Aggregation Patterns

18.1 Time-based Aggregation

// Daily aggregation
const aggregateByDay = (data: DataPoint[], dateField: string) => {
    return data.reduce((acc, item) => {
        const day = moment(item[dateField]).format('YYYY-MM-DD');
        if (!acc[day]) {
            acc[day] = { count: 0, items: [] };
        }
        acc[day].count++;
        acc[day].items.push(item);
        return acc;
    }, {});
};
 
// Weekly aggregation with ISO week numbers
const aggregateByWeek = (data: DataPoint[], dateField: string) => {
    return data.reduce((acc, item) => {
        const week = moment(item[dateField]).format('YYYY-[W]WW');
        if (!acc[week]) {
            acc[week] = { count: 0, items: [], weekStart: moment(item[dateField]).startOf('isoWeek') };
        }
        acc[week].count++;
        acc[week].items.push(item);
        return acc;
    }, {});
};

18.2 Hierarchical Aggregation

// Department hierarchy aggregation
const aggregateByHierarchy = (data: DataPoint[], hierarchy: HierarchyNode[]) => {
    const aggregated = {};
    
    const rollUpMetrics = (node: HierarchyNode) => {
        // Get direct metrics
        const directMetrics = data.filter(d => d.departmentId === node.id);
        
        // Get child metrics recursively
        const childMetrics = node.children.flatMap(child => 
            rollUpMetrics(child).metrics
        );
        
        // Combine metrics
        const allMetrics = [...directMetrics, ...childMetrics];
        
        aggregated[node.id] = {
            name: node.name,
            level: node.level,
            directCount: directMetrics.length,
            totalCount: allMetrics.length,
            metrics: calculateAggregateMetrics(allMetrics)
        };
        
        return { node, metrics: allMetrics };
    };
    
    hierarchy.forEach(rootNode => rollUpMetrics(rootNode));
    return aggregated;
};

18.3 Geographic Aggregation

// Site clustering for map visualization
const clusterSitesByProximity = (sites: Site[], zoomLevel: number) => {
    const CLUSTER_RADIUS = getClusterRadius(zoomLevel);
    const clusters = [];
    const processed = new Set();
    
    sites.forEach(site => {
        if (processed.has(site.id)) return;
        
        // Find nearby sites
        const cluster = {
            center: { lat: site.latitude, lng: site.longitude },
            sites: [site],
            bounds: new google.maps.LatLngBounds()
        };
        
        sites.forEach(otherSite => {
            if (site.id !== otherSite.id && !processed.has(otherSite.id)) {
                const distance = calculateDistance(
                    site.latitude, site.longitude,
                    otherSite.latitude, otherSite.longitude
                );
                
                if (distance <= CLUSTER_RADIUS) {
                    cluster.sites.push(otherSite);
                    processed.add(otherSite.id);
                }
            }
        });
        
        // Calculate cluster metrics
        cluster.metrics = aggregateClusterMetrics(cluster.sites);
        cluster.sites.forEach(s => 
            cluster.bounds.extend(new google.maps.LatLng(s.latitude, s.longitude))
        );
        
        clusters.push(cluster);
        processed.add(site.id);
    });
    
    return clusters;
};

19. Configuration & Deployment

19.1 Environment Configuration

// .env.production
REACT_APP_API_URL=https://api.nimbly.com
REACT_APP_GOOGLE_MAPS_KEY=your-maps-key
REACT_APP_ENABLE_ANALYTICS=true
REACT_APP_DASHBOARD_REFRESH_INTERVAL=300000

19.2 Build Configuration

// webpack.config.js
module.exports = {
    optimization: {
        splitChunks: {
            chunks: 'all',
            cacheGroups: {
                dashboard: {
                    test: /[\\/]dashboardRevamp[\\/]/,
                    name: 'dashboard',
                    priority: 10
                }
            }
        }
    }
};

19.3 Deployment Checklist

  • Environment variables configured
  • API endpoints verified
  • Authentication tokens valid
  • Google Maps API key active
  • Performance monitoring enabled
  • Error tracking configured
  • Analytics tracking verified

20. Conclusion

The Executive Dashboard is a comprehensive analytics platform designed to provide real-time operational insights for executive stakeholders. Its modular architecture, extensive filtering capabilities, and multiple visualization options make it a powerful tool for data-driven decision making.

Key strengths include:

  • Flexibility: Multiple views and customization options
  • Performance: Optimized for large datasets
  • Usability: Intuitive interface with responsive design
  • Scalability: Modular architecture supports growth
  • Security: Multi-layer access control

For technical support or feature requests, please contact the development team or create an issue in the GitHub repository.


Document Version: 1.0
Last Updated: January 2025
Total Characters: ~47,000+


21. Appendix A: Common Use Cases & Workflows

21.1 Daily Operations Review Workflow

graph LR
    A[Login] --> B[Navigate to Executive Dashboard]
    B --> C[Check Health Score]
    C --> D{Score < 60?}
    D -->|Yes| E[Review Issues Tab]
    D -->|No| F[Review Reports Tab]
    E --> G[Drill into Problem Areas]
    F --> H[Check Completion Rates]
    G --> I[Take Corrective Action]
    H --> I

Steps:

  1. Morning Check (5-10 minutes)

    • Review overall health score
    • Check IRR and RCR trends
    • Identify critical issues
  2. Deep Dive (15-30 minutes)

    • Filter by problematic sites/departments
    • Analyze issue categories
    • Review user performance
  3. Action Items

    • Export issue list for team meeting
    • Schedule follow-ups
    • Update priorities

21.2 Weekly Performance Analysis

Objective: Comprehensive performance review and planning

Process:

  1. Set date filter to last 7 days
  2. Review department performance cards
  3. Identify top and bottom performers
  4. Export performance data for reporting
  5. Compare with previous week’s metrics

21.3 Monthly Executive Reporting

Components:

  • Executive summary dashboard screenshot
  • Trend analysis (30-day view)
  • Department rankings
  • Geographic heat map
  • Action items and recommendations

22. Appendix B: Troubleshooting Guide

22.1 Common Issues and Solutions

IssueSymptomsSolution
Slow Dashboard LoadLoading spinner > 30 seconds1. Check network connection
2. Clear browser cache
3. Reduce date range filter
Missing DataEmpty charts/tables1. Verify filter selections
2. Check user permissions
3. Confirm data availability for date range
Map Not LoadingGray area instead of map1. Check Google Maps API status
2. Verify API key validity
3. Test in incognito mode
Export TimeoutDownload never completes1. Reduce data scope
2. Try different format
3. Check browser download settings
Filter Not ApplyingData doesn’t update1. Click “Apply” button
2. Check for validation errors
3. Refresh page

23. Appendix C: API Reference Summary

23.1 Authentication Headers

Authorization: Bearer {firebase-token}
Content-Type: application/json
X-Organization-ID: {org-id}

23.2 Common Request Patterns

// Standard filter payload
{
  "startDate": "2025-01-01",
  "endDate": "2025-01-31",
  "siteIDs": ["site1", "site2"],
  "departmentIDs": ["dept1"],
  "userIDs": ["user1", "user2"],
  "questionnaireIDs": ["q1"],
  "timezone": "Asia/Jakarta"
}
 
// Pagination parameters
{
  "page": 1,
  "limit": 10,
  "sortBy": "createdAt",
  "sortOrder": "desc"
}

23.3 Response Status Codes

  • 200: Success
  • 400: Invalid request parameters
  • 401: Authentication required
  • 403: Insufficient permissions
  • 404: Resource not found
  • 429: Rate limit exceeded
  • 500: Server error

24. Appendix D: Keyboard Shortcuts

ShortcutAction
Ctrl/Cmd + FToggle filters
Ctrl/Cmd + MToggle map view
Ctrl/Cmd + RRefresh data
Ctrl/Cmd + EExport current view
TabNavigate between tabs
EscClose modals
?Show help menu

25. Appendix E: Mobile-Specific Features

25.1 Touch Gestures

  • Swipe Left/Right: Navigate between tabs
  • Pinch to Zoom: Map view only
  • Long Press: Show context menu
  • Pull to Refresh: Update dashboard data

25.2 Mobile Optimizations

  1. Compact Filters: Modal overlay design
  2. Simplified Charts: Reduced data points
  3. Touch Targets: Minimum 44x44px
  4. Responsive Tables: Horizontal scroll
  5. Progressive Loading: Critical data first

26. End of Document

For additional support or feature requests, please contact:

Thank you for using the Executive Dashboard!