HH/docs/COMMAND_CENTER_IMPLEMENTATION.md
2026-01-05 19:40:24 +03:00

13 KiB

PX360 Command Center - Implementation Guide

Overview

The PX360 Command Center is a comprehensive, unified dashboard that consolidates all analytics, KPIs, and metrics from across the PX360 system into a single, powerful command center interface. This document provides detailed information about the implementation, features, and usage of the Command Center.

Features

1. Unified KPI Display

  • Complaints KPIs: Total complaints, open complaints, overdue complaints, resolved complaints
  • Actions KPIs: Total actions, overdue actions
  • Surveys KPIs: Average survey score, negative surveys
  • Trend Indicators: Visual indicators showing percentage changes vs. previous period

2. Interactive Charts (ApexCharts)

All charts use ApexCharts library for modern, responsive, and interactive visualizations:

  • Complaints Trend: Line/Area chart showing complaint volume over time
  • Complaints by Category: Donut chart showing distribution across categories
  • Survey Satisfaction Trend: Line chart showing satisfaction scores over time
  • Survey Distribution: Donut chart showing positive/neutral/negative split
  • Department Performance: Bar chart ranking departments by performance
  • Physician Leaderboard: Bar chart showing top-performing physicians

3. Advanced Filtering System

Users can filter data by:

  • Date Range: Preset options (7 days, 30 days, 90 days, this month, last month, quarter, year) or custom range
  • Hospital: Filter by specific hospital (role-based access control)
  • Department: Filter by specific department
  • KPI Category: Filter by category (complaints, surveys, actions, physicians)

4. Data Tables

  • Overdue Complaints Table: Shows all overdue complaints with quick action links
  • Physician Leaderboard Table: Detailed ranking with ratings, survey counts, and sentiment breakdown

5. Export Functionality

  • Excel Export: Download dashboard data in Excel (.xlsx) format
  • PDF Export: Generate professional PDF reports with all KPIs and data
  • Both exports respect current filter settings

Architecture

Backend Components

1. UnifiedAnalyticsService (apps/analytics/services/analytics_service.py)

A comprehensive service class that handles all data aggregation and KPI calculations.

Key Methods:

class UnifiedAnalyticsService:
    @staticmethod
    def get_all_kpis(user, date_range, hospital_id, department_id, ...)
        """Returns all KPIs based on filters"""
        
    @staticmethod
    def get_chart_data(user, chart_type, date_range, ...)
        """Returns chart data for specific chart type"""
        
    @staticmethod
    def get_date_range_filter(date_range, custom_start, custom_end)
        """Returns (start_date, end_date) tuple"""
        
    @staticmethod
    def get_complaints_trend(user, start_date, end_date, ...)
        """Returns complaints trend chart data"""
        
    @staticmethod
    def get_complaints_by_category(user, start_date, end_date, ...)
        """Returns complaints by category chart data"""
        
    # ... additional chart data methods

2. ExportService (apps/analytics/services/export_service.py)

Handles Excel and PDF export generation.

Key Methods:

class ExportService:
    @staticmethod
    def prepare_dashboard_data(user, kpis, charts, tables)
        """Prepares data structure for export"""
        
    @staticmethod
    def export_to_excel(data)
        """Generates Excel file and returns HttpResponse"""
        
    @staticmethod
    def export_to_pdf(data)
        """Generates PDF file and returns HttpResponse"""

3. UI Views (apps/analytics/ui_views.py)

Django views for rendering the dashboard and handling API requests.

Key Views:

@login_required
def command_center(request)
    """Main dashboard view - renders the HTML template"""
    
@login_required
def command_center_api(request)
    """API endpoint - returns JSON data for dynamic updates"""
    
@login_required
def export_command_center(request, export_format)
    """Handles Excel and PDF export requests"""

Frontend Components

1. Command Center Template (templates/analytics/command_center.html)

The main dashboard template includes:

  • Filter panel with collapsible form
  • KPI cards with trend indicators
  • Chart containers for ApexCharts
  • Data tables with sorting and actions
  • Loading overlay
  • JavaScript for dynamic updates

2. JavaScript Functionality

Key JavaScript Functions:

// Global state
let charts = {};
let currentFilters = { ... };

// Core functions
loadDashboardData()              // Loads all dashboard data via AJAX
updateKPIs(kpis)                 // Updates KPI cards
updateCharts(chartData)          // Renders/updates ApexCharts
renderChart(elementId, chartData, chartType)  // Renders individual chart
updateTables(tableData)          // Updates data tables

// Filter functions
handleDateRangeChange()          // Shows/hides custom date range
updateFilters()                  // Updates currentFilters object
resetFilters()                   // Resets all filters to defaults

// Export functions
exportDashboard(format)          // Initiates Excel/PDF export

URL Structure

/analytics/command-center/                    # Main dashboard
/analytics/api/command-center/                # API endpoint for data
/analytics/api/command-center/export/excel/   # Excel export
/analytics/api/command-center/export/pdf/     # PDF export

Data Flow

1. Initial Page Load

User Request → command_center view
    ↓
Render template with initial filters and KPIs
    ↓
Return HTML to browser
    ↓
JavaScript loads data via AJAX
    ↓
command_center_api returns JSON
    ↓
Dashboard updates with data

2. Filter Change

User applies filter
    ↓
JavaScript updates currentFilters
    ↓
loadDashboardData() called
    ↓
AJAX request to command_center_api with filters
    ↓
Backend aggregates data based on filters
    ↓
JSON response with kpis, charts, tables
    ↓
JavaScript updates UI components

3. Export Request

User clicks Export → Excel/PDF
    ↓
exportDashboard(format) called
    ↓
AJAX request to export_command_center
    ↓
ExportService generates file
    ↓
Browser downloads file

Role-Based Access Control

The Command Center respects user roles:

PX Admin

  • Can view data across all hospitals
  • Can filter by any hospital or department
  • Full access to all KPIs and charts

Hospital Manager

  • Can only view data for their hospital
  • Hospital filter pre-selected to their hospital
  • Can filter by departments within their hospital

Department Manager

  • Can only view data for their department
  • Hospital and department filters pre-selected
  • Limited to department-specific KPIs

Chart Configurations

1. Line Charts (Trend Data)

{
    chart: { type: 'line', height: 350, toolbar: { show: true } },
    stroke: { curve: 'smooth', width: 3 },
    fill: { type: 'gradient', gradient: { ... } },
    xaxis: { categories: [...] },
    yaxis: { min: 0, forceNiceScale: true }
}

2. Donut Charts (Distribution Data)

{
    chart: { type: 'donut', height: 350 },
    labels: [...],
    dataLabels: { enabled: true },
    legend: { position: 'bottom' }
}

3. Bar Charts (Ranking Data)

{
    chart: { type: 'bar', height: 350 },
    plotOptions: { bar: { horizontal: true } },
    xaxis: { categories: [...] }
}

Export Formats

Excel Export (.xlsx)

  • Contains separate sheets for:
    • Executive Summary (KPIs)
    • Detailed Charts Data
    • Overdue Complaints List
    • Physician Leaderboard
  • Formatted with proper headers and styling
  • Includes timestamp and filter information

PDF Export (.pdf)

  • Professional report format
  • Executive summary with key KPIs
  • Charts rendered as high-quality images using Matplotlib:
    • Line charts with markers and trend lines
    • Bar charts with value labels
    • Donut/Pie charts with percentage labels
    • Professional styling and colors
    • 150 DPI resolution for print quality
  • Data tables with proper formatting
  • Includes report metadata (date, filters applied)

Performance Optimizations

  1. Database Query Optimization

    • Uses select_related() and prefetch_related() for efficient queries
    • Aggregates data at database level where possible
    • Limits result sets for tables (20-100 rows)
  2. Caching

    • Consider adding Redis caching for frequently accessed data
    • Cache chart data for common filter combinations
  3. AJAX Loading

    • Initial page load shows skeleton with filters
    • Data loads asynchronously via AJAX
    • Prevents page timeout on large datasets
  4. Pagination

    • Table results are paginated
    • Chart data limits to top N items (e.g., top 10 departments)

Dependencies

Required Python Packages

openpyxl>=3.1.0      # Excel export
reportlab>=4.0.0     # PDF export
Pillow>=10.0.0       # Image processing for PDF
matplotlib>=3.8.0     # Chart image generation for PDF export

Required JavaScript Libraries

<!-- Already included in base.html -->
<script src="https://cdn.jsdelivr.net/npm/apexcharts@3.45.1/dist/apexcharts.min.js"></script>

Customization Guide

Adding a New KPI

  1. Add KPI calculation in UnifiedAnalyticsService:
@staticmethod
def get_all_kpis(user, date_range, ...):
    kpis = {
        # existing KPIs
        'new_kpi': self._calculate_new_kpi(user, date_range, ...),
    }
    return kpis
  1. Add KPI card to template:
<div class="col-md-3">
    <div class="card kpi-card">
        <div class="card-body">
            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                {% trans "New KPI" %}
            </div>
            <div class="kpi-value text-primary" id="newKpi">0</div>
        </div>
    </div>
</div>
  1. Update JavaScript:
function updateKPIs(kpis) {
    // existing updates
    document.getElementById('newKpi').textContent = kpis.new_kpi || 0;
}

Adding a New Chart

  1. Add chart data method in UnifiedAnalyticsService:
@staticmethod
def get_new_chart(user, start_date, end_date, hospital_id, department_id):
    # Query and aggregate data
    return {
        'series': [...],
        'labels': [...],
        'chart_type': 'bar',  # or 'line', 'donut', etc.
        'metadata': {...}
    }
  1. Add chart method call:
charts = {}
for chart_type in chart_types + ['new_chart']:
    charts[chart_type] = UnifiedAnalyticsService.get_chart_data(
        user=user, chart_type=chart_type, ...
    )
  1. Add chart container to template:
<div class="col-lg-6">
    <div class="card">
        <div class="card-header">
            <h6 class="m-0 font-weight-bold">{% trans "New Chart" %}</h6>
        </div>
        <div class="card-body">
            <div class="chart-container" id="newChart"></div>
        </div>
    </div>
</div>

Troubleshooting

Issue: Charts not rendering

Solution:

  • Check browser console for JavaScript errors
  • Verify ApexCharts library is loaded (base.html)
  • Ensure chart data is properly formatted (check API response)

Issue: Filters not working

Solution:

  • Verify filter parameters are being sent in AJAX request
  • Check backend is processing filters correctly
  • Ensure date parsing is working for custom ranges

Issue: Export fails

Solution:

  • Verify openpyxl and reportlab are installed
  • Check file permissions for temporary directories
  • Review export service logs for errors

Issue: Slow page load

Solution:

  • Add database indexes on frequently queried fields
  • Implement caching for common filter combinations
  • Consider pagination for large datasets

Security Considerations

  1. Authentication: All views require @login_required decorator
  2. Authorization: Role-based filtering applied at model level
  3. SQL Injection: Uses Django ORM parameterized queries
  4. XSS Protection: Template auto-escaping enabled
  5. CSRF Protection: Django CSRF middleware enabled

Future Enhancements

  1. Real-time Updates: WebSocket integration for live data
  2. Advanced Analytics: Predictive analytics and AI insights
  3. Custom Dashboards: User-defined dashboard layouts
  4. Scheduled Reports: Automated email reports on schedule
  5. Drill-down Capability: Click on chart to view detailed data
  6. Comparison Mode: Compare multiple time periods side-by-side
  7. KPI Thresholds: Alert system when KPIs exceed thresholds
  8. Annotations: Add notes to specific data points

Support and Maintenance

For issues, questions, or feature requests:

  • Check this documentation first
  • Review the codebase implementation
  • Consult with the development team
  • Create detailed bug reports with steps to reproduce

Version History

  • v1.1.0 (2026-01-05): Enhanced PDF export with chart images

    • Added Matplotlib integration for generating actual chart images in PDF
    • Charts now render as visual graphics instead of text data
    • Improved PDF readability and professionalism
    • Fallback to text representation if image generation fails
  • v1.0.0 (2024-01-05): Initial implementation

    • Unified KPI dashboard
    • Interactive ApexCharts
    • Advanced filtering
    • Excel/PDF export
    • Role-based access control