Skip to content

Conversation

@igennova
Copy link
Contributor

@igennova igennova commented Mar 17, 2025

Fixes: #3977
image

Summary by CodeRabbit

  • New Features

    • Overhauled the statistics dashboard with a modern, responsive layout featuring interactive KPI cards, dynamic charts, and animated counters.
    • Enhanced data presentation with percentage metrics for improved insights.
    • Introduced new charts for "Activity Over Time" and "Issue Status Breakdown".
    • Redesigned time period selector for improved usability.
    • Added a hidden form for syncing projects with a submission button.
  • Refactor

    • Streamlined underlying data processing to support the enriched visualizations and detailed statistics.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2025

Walkthrough

The changes update the statistics dashboard by overhauling the HTML template and backend view function. The UI is restructured with new blocks for external JavaScript libraries, improved layout with KPI cards, responsive design, and additional charts. On the backend, the function calculating statistics has been enhanced to include percentage metrics for various data points, ensuring more detailed analytics are provided to the dashboard.

Changes

Files Change Summary
website/templates/stats_dashboard.html Added new <head> and <script> blocks; restructured content with a dashboardContainer, updated header, time period selector, and KPI cards; integrated external JavaScript libraries (ApexCharts, CountUp.js); introduced new charts and an additional form for syncing projects.
website/views/core.py Refactored the stats_dashboard function to include percentage calculations for users, issues, domains, points, and projects by restructuring the stats dictionary and replacing simple count metrics with detailed entries.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant B as Browser
    participant V as Django View
    participant T as Template Engine
    participant JS as JavaScript Libraries
    U->>B: Request Dashboard Page
    B->>V: GET /stats_dashboard
    V->>V: Calculate statistics with percentages
    V->>T: Render updated dashboard template with stats
    T->>B: Send rendered HTML
    B->>JS: Load ApexCharts and CountUp.js
    JS->>B: Initialize charts and animated counters
Loading

Assessment against linked issues

Objective Addressed Explanation
Fix text overflow and layout issues on the Stats Dashboard [#3977]

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (5)
website/views/core.py (1)

1494-1494: Consider adding error handling for potential division by zero.

While the code checks if users["total"] > 0 before division, I'd recommend extracting the percentage calculation logic into a helper function for better maintainability and consistency across all metrics.

+ def calculate_percentage(numerator, denominator):
+     """Calculate percentage with zero division protection"""
+     return round((numerator / denominator * 100) if denominator > 0 else 0)
+
  # Then in the stats dictionary:
- "active_percentage": round((users["active"] / users["total"] * 100) if users["total"] > 0 else 0),
+ "active_percentage": calculate_percentage(users["active"], users["total"]),
website/templates/stats_dashboard.html (4)

251-256: Consider adding feedback mechanism for sync operation.

The sync button should provide visual feedback after the operation completes, indicating success or failure.

  <button id="syncProjectsBtn"
          type="button"
          class="mt-1 inline-flex items-center px-2 py-1 bg-[#e74c3c] hover:bg-red-600 text-white text-xs rounded">
      <i class="fas fa-sync-alt mr-1"></i> Sync Now
  </button>
+ {% if messages %}
+     {% for message in messages %}
+         <div class="text-xs mt-1 {% if message.tags == 'success' %}text-green-600{% else %}text-red-600{% endif %}">
+             {{ message }}
+         </div>
+     {% endfor %}
+ {% endif %}

423-424: Use dynamic date ranges for the activity chart.

The x-axis categories are hard-coded to months instead of being dynamically generated based on the selected time period.

Pass date labels from the backend and use them in the chart configuration:

  xaxis: {
-     categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
+     categories: {{ date_labels|safe }},
      labels: {
          style: {
              colors: '#9ca3af'
          }
      },

496-496: Consider using a more diverse color palette for better accessibility.

Using variations of red for all chart elements may make it difficult for users with color vision deficiencies to distinguish between different data points.

Use a more diverse and accessible color palette:

- colors: ['#e74c3c', '#e76c3c', '#e74c6c', '#e7463c'],
+ colors: ['#e74c3c', '#3498db', '#2ecc71', '#f39c12'],

287-349: Add error handling for JavaScript libraries.

There's no error handling for cases where the external libraries (ApexCharts or CountUp.js) fail to load.

Add error handling to gracefully degrade functionality when libraries are unavailable:

  document.addEventListener('DOMContentLoaded', function() {
+     // Check if required libraries are available
+     if (typeof CountUp === 'undefined' || typeof ApexCharts === 'undefined') {
+         console.error('Required libraries not loaded. Some dashboard features will be disabled.');
+         document.querySelectorAll('.requires-js').forEach(el => {
+             el.innerHTML = 'Chart unavailable (JavaScript library not loaded)';
+             el.classList.add('bg-gray-100', 'text-gray-500', 'p-4', 'text-center');
+         });
+         return;
+     }
      
      // Rest of the initialization code...
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 62bc81e and 615c7bf.

📒 Files selected for processing (2)
  • website/templates/stats_dashboard.html (1 hunks)
  • website/views/core.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
🔇 Additional comments (4)
website/views/core.py (1)

1490-1531: Improved stats structure with new percentage metrics!

The updated stats dictionary structure now includes percentage calculations for active users, open issues, active domains, and more. This enhances the data visualization capabilities on the dashboard.

website/templates/stats_dashboard.html (3)

7-12: Good addition of external libraries in the head block!

Adding ApexCharts and CountUp.js will enhance the data visualization capabilities of the dashboard. This is a great improvement.


44-182: Great implementation of KPI summary cards!

The new KPI card design with animated counters, percentage indicators, and progress bars greatly improves the user experience and data readability.


278-283: Good implementation of hidden form for sync action.

Using a hidden form for the sync operation is a clean approach for handling the POST request.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
website/templates/stats_dashboard.html (3)

362-366: Ensure time series data aligns with selected time period.

The chart uses a static 12-month display regardless of the selected time period. Consider dynamically adjusting the chart's x-axis labels based on the selected period for improved accuracy.

series: [{
    name: 'Issues',
    data: {{ issues_time_series|safe|default:'[0,0,0,0,0,0,0,0,0,0,0,0]' }}
}, {
    name: 'Users',
    data: {{ users_time_series|safe|default:'[0,0,0,0,0,0,0,0,0,0,0,0]' }}
}],

Additionally, pass the actual time period labels from the backend:

xaxis: {
-   categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
+   categories: {{ time_period_labels|safe|default:"['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']" }},

352-356: Add error handling for the sync projects operation.

The button is correctly disabled during the sync operation, but there's no mechanism to re-enable it or show an error message if the operation fails.

document.getElementById('syncProjectsBtn').addEventListener('click', function() {
+   const button = this;
    document.getElementById('syncProjectsForm').submit();
    this.disabled = true;
    this.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Syncing...';
+   
+   // Add listener for form submission result
+   window.addEventListener('load', function() {
+       button.disabled = false;
+       button.innerHTML = '<i class="fas fa-sync-alt mr-1"></i> Sync Now';
+       
+       // Check for Django messages to display success/error
+       const messages = document.querySelectorAll('.django-messages .alert');
+       if (messages.length > 0) {
+           // Handle messages accordingly
+       }
+   }, { once: true });
});

498-499: Improve color differentiation in the issue status pie chart.

The current colors are all similar shades of red, which might make it difficult to distinguish between different statuses.

-colors: ['#e74c3c', '#e76c3c', '#e74c6c', '#e7463c'],
+colors: ['#e74c3c', '#3498db', '#2ecc71', '#f39c12'],
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 615c7bf and 8fefe60.

📒 Files selected for processing (2)
  • website/templates/stats_dashboard.html (1 hunks)
  • website/views/core.py (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
🔇 Additional comments (7)
website/views/core.py (3)

1490-1534: Well-structured enhancement of the stats dictionary with percentage metrics!

The addition of percentage metrics for active users, open issues, active domains, etc. provides more meaningful insights in the dashboard. The code correctly handles potential division by zero cases.


1542-1573: Good implementation of time series data for visualization.

The time series data generation for issues and users is well implemented. It appropriately handles various time period selections and fills in missing months with zeros.


1589-1591: Properly exposing time series data to the template for chart consumption.

The addition of context variables for JSON-encoded time series data ensures the frontend can easily consume this data for visualization.

website/templates/stats_dashboard.html (4)

44-182: Excellent implementation of KPI cards with animated counters!

The KPI cards follow a consistent design pattern with good use of Tailwind CSS for styling. The data binding to the backend statistics is well implemented, and the progress bars visually represent the percentage metrics.


201-207: Well-structured chart containers.

The chart containers are properly sized and structured for optimal data visualization. The use of responsive design principles ensures good display across different screen sizes.


210-274: Good implementation of secondary metric cards.

The implementation of additional metrics (domains, bug hunts, projects, activities) with consistent styling and counter animations enhances the dashboard's completeness. The sync projects button is a useful feature for data refresh.


278-283: Properly implemented form for GitHub projects synchronization.

The hidden form with CSRF token for project synchronization follows best practices for Django form submissions.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (5)
website/templates/stats_dashboard.html (5)

188-213: Charts & Secondary Metrics Section

The integration of the "Activity Over Time" area chart and the "Issue Status Breakdown" pie chart enhances data visualization. One suggestion: for the activity chart, both data series currently use the same color (#e74c3c) which may reduce clarity. Consider assigning distinct colors to differentiate between “Issues” and “Users” data.


281-287: Sync Projects Form Integration

The hidden sync projects form and the associated button are correctly implemented. For increased robustness, consider adding error handling (and perhaps re-enabling the button) if the form submission fails.


330-350: Animated Counters Initialization

The function initializeCounters() efficiently iterates over the counter elements—retrieving the starting values from data attributes and initializing the CountUp animations. For future maintainability, you might consider encapsulating this logic into a module if similar functionality is needed elsewhere.


355-360: Sync Projects Button Event Handling

The event listener for the “Sync Projects” button disables the button and updates its inner HTML to indicate a loading state. It works as intended, though adding error handling for failed submissions could further improve user feedback.


362-394: Activity Over Time Chart Configuration

The configuration for the Activity Over Time chart correctly sets up dynamic series data and responsive styling. However, both the “Issues” and “Users” series are assigned the same color (#e74c3c), which might lead to visual confusion. Consider using a distinct color (for example, a blue tone for one series) to enhance clarity.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8fefe60 and 397ca84.

📒 Files selected for processing (1)
  • website/templates/stats_dashboard.html (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
🔇 Additional comments (6)
website/templates/stats_dashboard.html (6)

7-16: External Scripts with SRI Attributes

The newly added {% block head %} correctly includes ApexCharts and CountUp.js with explicit integrity and crossorigin attributes, which enhances security by ensuring resource integrity.


17-30: Dashboard Header & Container Structure

The dashboard header now dynamically displays the title, description, and current period. The use of a dedicated container (#dashboardContainer) and responsive spacing is well executed.


31-42: Time Period Selector Implementation

The redesigned time period selector makes use of a loop over period_options and applies conditional styling based on the selected period. This approach improves usability.


47-83: KPI Summary Cards for Core Metrics

The KPI cards for Users, Issues, Organizations, and Points are effectively structured. They dynamically render key stats using Django template variables with appropriate fallback defaults.


214-278: Additional Metrics Grid

The grid displaying Domains, Bug Hunts, Projects, and Activities is well designed and consistently styled. Dynamic values and layout classes are used effectively.


476-483: Issue Status Pie Chart Setup

The Issue Status Pie Chart is configured well by combining dynamic values from the template with a clear set of labels and differentiated colors for each issue status. Verify that the order of series data (Open, Fixed, In Review, Invalid) aligns with backend computations.

@DonnieBLT DonnieBLT enabled auto-merge (squash) March 18, 2025 04:34
@DonnieBLT DonnieBLT merged commit 965810b into OWASP-BLT:main Mar 18, 2025
10 checks passed
This was referenced Mar 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

The Stats Dashboard is broken (text is overflowing)

2 participants