Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@sidd190
Copy link
Contributor

@sidd190 sidd190 commented Nov 7, 2025

PR Review Leaderboard Fix

Issue

Fixes #4569 & #4660 - PR review tracking for TOP BLT PRs leaderboard was broken - showed "No code review data available!" despite existing data.

Root Cause

Incorrect ORM query using wrong model and field relationships.

Files Changed

  1. website/views/user.py - Fixed query logic
  2. website/templates/leaderboard_global.html - Fixed template field names and styling
Screencast.from.2025-11-09.19-54-36.webm

Key Changes

1. Fixed ORM Query

# Before (broken)
GitHubIssue.objects.filter(type="pull_request").values("reviews__reviewer__user__username").annotate(total_reviews=Count("id"))

# After (fixed)  
GitHubReview.objects.values("reviewer__user__username").annotate(total_reviews=Count("id")) 

2. Fixed Template Field Names

  • leader.reviews__reviewer__user__username β†’ leader.reviewer__user__username
  • leader.reviews__reviewer__user__email β†’ leader.reviewer__user__email
  • leader.reviews__reviewer__github_url β†’ leader.reviewer__github_url

3. Updated Styling

  • All colors changed to custom red: #e74c3c
  • Complete borders around leaderboard sections
  • Added null safety checks

Result

Leaderboard now displays actual review data with proper styling and complete borders.

The PR by copilot missed some of the edge cases and error handling. This is tested with hardcoded data for now, it functions correctly on my system.

Summary by CodeRabbit

  • Bug Fixes

    • Fixed avatar display with improved GitHub profile integration and fallback options.
    • Enhanced user display logic to show usernames properly and handle missing data gracefully.
  • Style Updates

    • Redesigned leaderboard sections with red accent colors and refined typography.
    • Improved visual hierarchy and spacing for better readability across all leaderboard modules.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 7, 2025

Walkthrough

This PR fixes PR review leaderboard tracking and improves data handling across leaderboard sections. Backend changes refine database queries for PR and review data with fallback handling and GitHub username extraction. Template updates improve styling, user avatar display logic, and presentation consistency with red accent colors.

Changes

Cohort / File(s) Summary
Backend Query & Data Enrichment
website/views/user.py
Added extract_github_username() utility to parse GitHub URLs. Refined PR leaderboard query to filter only tracked repos and valid user profiles via repo__isnull=False and exclude(user_profile__isnull=True). Updated code review leaderboard query with reviewer__user__isnull=False filter. Both leaderboards now inject github_username into entries during post-processing.
Leaderboard Template Styling & Display
website/templates/leaderboard_global.html
Replaced gray borders with red accent color (#e74c3c) throughout. Refactored avatar display logic to prioritize github_username with GitHub URL avatars, fallback to gravatar, and default avatar when unavailable. Enhanced username display to show explicit usernames or "Unknown User" with conditional GitHub link icons. Updated section headers with rounded styling and bottom borders. Applied consistent "No data" messaging in red accent across all leaderboard sections (Points, Pull Requests, Code Review, Top Visitors, Issue Bounties, Bug Bounties).

Sequence Diagram(s)

sequenceDiagram
    participant Backend as User.py<br/>(Leaderboard Query)
    participant DB as Database
    participant Template as leaderboard_global.html<br/>(Render)
    participant Client as Browser

    Backend->>DB: Query PR leaderboard<br/>(repo__isnull=False)
    DB-->>Backend: PR data + user_profile
    Backend->>Backend: extract_github_username()<br/>from user_profile.github_url
    Backend->>Backend: Inject github_username<br/>into leaderboard entry
    Backend->>Template: Context with enriched<br/>leaderboard data

    Backend->>DB: Query code_review_leaderboard<br/>(reviewer__user__isnull=False)
    DB-->>Backend: Review data + reviewer profile
    Backend->>Backend: extract_github_username()<br/>from reviewer.github_url
    Backend->>Backend: Inject github_username<br/>into entry
    Backend->>Template: Context with enriched<br/>review data

    Template->>Template: For each leaderboard entry:<br/>resolve avatar source
    alt github_username available
        Template->>Template: Use GitHub avatar URL
    else no github_username
        Template->>Template: Fallback to gravatar
    else no email
        Template->>Template: Use default avatar
    end
    Template->>Template: Render username or<br/>"Unknown User"
    Template->>Client: Render leaderboard<br/>with red accent styling
    Client-->>Client: Display final HTML
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20–28 minutes

  • Template logic refactoring: Avatar resolution with multiple fallback paths and conditional GitHub links require careful verification that all data shapes are handled correctly.
  • Query optimization: PR and review leaderboard queries have multiple filters and joins; ensure select_related optimization does not introduce N+1 queries and that filtered results match expected template data structure.
  • GitHub username extraction: Utility function parsing must handle edge cases (malformed URLs, None values) correctly across both leaderboard contexts.
  • Data flow validation: Verify that github_username injection happens consistently for both PR and review leaderboards, and that template fallbacks align with possible null/missing values from backend.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
βœ… Passed checks (4 passed)
Check name Status Explanation
Title check βœ… Passed The PR title 'Code Review leaderboard fix' directly reflects the main objective of fixing the broken code review leaderboard functionality addressed in issues #4569 and #4660.
Linked Issues check βœ… Passed The code changes comprehensively address issue #4569 requirements: fixed the ORM query from GitHubIssue to GitHubReview, corrected template field references, updated styling to use #e74c3c, added null-safety checks, and ensured review data displays in the leaderboard.
Out of Scope Changes check βœ… Passed Changes are limited to fixing the code review leaderboard: updates to user.py for query/extraction logic and template styling adjustments in leaderboard_global.html are all directly related to the stated objectives.
Description Check βœ… Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • πŸ“ Generate docstrings
πŸ§ͺ Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❀️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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 (1)
website/views/user.py (1)

61-92: Validate GitHub host before deriving avatar handles

Right now any URL containing a slash (e.g., Twitter, LinkedIn, company blogs) passes through and we emit https://github.com/<last-segment>.png, which produces broken or misleading avatars. Previously those entries fell back to Gravatar, so this regresses the display. Please bail out unless the netloc is really GitHub (include www./api. variants) before we lift the final path component. Remember to add the urlparse import alongside the existing ones.

+from urllib.parse import urlparse
+
 def extract_github_username(github_url):
@@
-    # Strip trailing slashes and whitespace
-    github_url = github_url.strip().rstrip("/")  # Clean URL format
-
-    # Remove query parameters and fragments if present
-    github_url = github_url.split("?")[0].split("#")[0]
-
-    # Ensure URL contains at least one slash
-    if "/" not in github_url:
-        return None
-
-    # Split on "/" and get the last segment
-    segments = github_url.split("/")
-    username = segments[-1] if segments else None
-
-    # Return username only if it's non-empty and not domain parts or protocol prefixes
-    if username and username not in ["github.com", "www.github.com", "www", "http:", "https:"]:
-        return username
-
-    return None
+    parsed = urlparse(github_url.strip())
+    if parsed.netloc.lower() not in {"github.com", "www.github.com", "api.github.com"}:
+        return None
+
+    path_segments = [segment for segment in parsed.path.split("/") if segment]
+    if not path_segments:
+        return None
+
+    username = path_segments[-1]
+    if username in {"apps", "users", "orgs"}:
+        return None
+
+    return username
πŸ“œ Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 07baeba and d14956d.

πŸ“’ Files selected for processing (2)
  • website/templates/leaderboard_global.html (4 hunks)
  • website/views/user.py (3 hunks)

@DonnieBLT DonnieBLT merged commit 945523b into OWASP-BLT:main Nov 9, 2025
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

Fix and enable tracking of pull request reviews for the TOP BLT PRs leaderboard

2 participants