Skip to content

Align badge css classes and auto-sync badges during user update#3725

Open
Isha-upadhyay wants to merge 6 commits intoOWASP:mainfrom
Isha-upadhyay:feature/badge-sync-alignment
Open

Align badge css classes and auto-sync badges during user update#3725
Isha-upadhyay wants to merge 6 commits intoOWASP:mainfrom
Isha-upadhyay:feature/badge-sync-alignment

Conversation

@Isha-upadhyay
Copy link
Contributor

@Isha-upadhyay Isha-upadhyay commented Feb 1, 2026

Proposed change

Resolves #3419

This PR cleans up and stabilizes how badges are handled across backend and frontend.

What was happening

  • Backend was sending badge css_class values in a different format than what the frontend expects.
  • Frontend relied on implicit normalization (snake_case → camelCase + fallbacks), which was fragile.
  • Badge sync commands were only updating when run manually, so badges could become stale after data updates.
  • Staff and Project Leader were also sharing the same icon, making roles harder to distinguish.

What I changed

  • Aligned backend BadgeCssClass values directly with frontend icon keys (removed normalization dependency).
  • Updated badge management commands to use enum values instead of hardcoded strings.
  • Integrated badge updates into the regular github_update_users sync flow so badges refresh automatically.
  • Assigned different icons for Staff and Project Leader for better clarity.

Screenshots:
Screenshot 2026-02-01 142353

.

Result

  • No frontend normalization needed
  • Consistent icon mapping
  • Badges stay in sync automatically
  • Clear visual distinction between roles

Checklist

  • Required: I followed the contributing workflow
  • Required: I verified that my code works as intended and resolves the issue as described
  • Required: I ran make check-test locally: all warnings addressed, tests passed
  • I used AI for code, documentation, tests, or communication related to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 1, 2026

Summary by CodeRabbit

  • New Features

    • Badge synchronization now runs automatically after user data updates to keep staff and project leader badges current.
  • Style

    • Updated visual icons for Staff, Project Leader, and Bug Slash badges for improved consistency.
  • Refactor

    • Simplified frontend badge icon resolution logic for easier maintenance.
  • Documentation

    • Added comprehensive Badges documentation covering behavior and verification.
  • Chores

    • Data migration renames an internal badge identifier; tests updated accordingly.

Walkthrough

Adds post-sync badge synchronization calls to the GitHub user update flow, changes several badge CSS class values and an enum choice (with migration), refactors frontend badge icon resolution to use camelCase keys, updates tests to match, and adds comprehensive badge documentation.

Changes

Cohort / File(s) Summary
Badge Sync Integration
backend/apps/github/management/commands/github_update_users.py, backend/tests/apps/github/management/commands/github_update_users_test.py
After bulk-saving user contributions, invokes nest_update_staff_badges and nest_update_project_leader_badges via call_command with try/except logging; tests now patch/verify call_command and add a test asserting the commands are called.
Badge CSS Class Updates (commands & tests)
backend/apps/nest/management/commands/nest_update_staff_badges.py, backend/apps/nest/management/commands/nest_update_project_leader_badges.py, backend/tests/apps/nest/management/commands/nest_update_staff_badges_test.py, backend/tests/apps/nest/management/commands/nest_update_project_leader_badges_test.py
Updates Command.badge_css_class values: staff from fa-user-shieldribbon, project leader from fa-user-shieldstar; tests updated to assert new values.
Badge Enum, Migration & Model
backend/apps/nest/models/badge.py, backend/apps/nest/migrations/0009_rename_bug_slash_css_class.py
Renames BadgeCssClass choice value bug_slashbugSlash and adds a reversible data migration to rename existing Badge.css_class rows accordingly.
Frontend icon resolution & tests
frontend/src/components/Badges.tsx, frontend/__tests__/unit/components/Badges.test.tsx
Removes normalization step and adds resolveIcon to map CSS class keys directly (expects camelCase like bugSlash); tests updated to use camelCase keys and simplified assertions.
Documentation
backend/docs/Badges.md
Adds extensive documentation covering badge data model, backend/frontend coordination, sync flow, migration steps, testing and verification guidance.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • arkid15r
  • kasya
  • ahmedxgouda
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main changes: aligning badge CSS classes and integrating automatic badge synchronization into the user update workflow.
Description check ✅ Passed The description comprehensively explains the changes: what was happening, what changed, and the results. It directly addresses the backend-frontend coordination gaps and automation behavior outlined in the linked issue.
Linked Issues check ✅ Passed The PR successfully addresses all key coding requirements from issue #3419: integrates badge sync into github_update_users for automatic updates, aligns backend BadgeCssClass with frontend expectations, clarifies automation behavior, and improves badge distinction.
Out of Scope Changes check ✅ Passed All changes are directly scoped to issue #3419: badge CSS class alignment, enum usage in commands, automatic sync integration, distinct icons, and supporting documentation. No unrelated modifications detected.
Docstring Coverage ✅ Passed Docstring coverage is 86.67% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Important

Action Needed: IP Allowlist Update

If your organization protects your Git platform with IP whitelisting, please add the new CodeRabbit IP address to your allowlist:

  • 136.113.208.247/32 (new)
  • 34.170.211.100/32
  • 35.222.179.152/32

Reviews will stop working after February 8, 2026 if the new IP is not added to your allowlist.


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.

@Isha-upadhyay Isha-upadhyay marked this pull request as draft February 1, 2026 12:19
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

🤖 Fix all issues with AI agents
In `@backend/apps/nest/models/badge.py`:
- Line 15: Create a Django data migration to rename persisted css_class values
so existing Badge rows keep matching the updated TextChoices: add a migration
that uses apps.get_model('nest', 'Badge') and a forward function (e.g.,
update_bug_slash_css_class) to filter
Badge.objects.filter(css_class='bug_slash').update(css_class='bugSlash') and a
reverse function (e.g., reverse_bug_slash_css_class) to change 'bugSlash' back
to 'bug_slash'; add this migration to the nest app dependencies immediately
after the previous migration so the stored values align with the new BUG_SLASH
enum constant.
🧹 Nitpick comments (2)
backend/apps/github/management/commands/github_update_users.py (1)

61-66: Consider error handling for badge sync commands.

If either badge sync command fails, the entire github_update_users command will fail after user contributions have already been saved. This could leave the system in a partially updated state. Consider wrapping the calls in try/except to log errors without failing the entire update:

🛡️ Suggested error handling
         # Sync badges after user data refresh
         self.stdout.write("Syncing badges...")
 
-        call_command("nest_update_staff_badges")
-        call_command("nest_update_project_leader_badges")
+        try:
+            call_command("nest_update_staff_badges", stdout=self.stdout)
+            call_command("nest_update_project_leader_badges", stdout=self.stdout)
+        except Exception as e:
+            logger.exception("Badge sync failed")
+            self.stderr.write(self.style.ERROR(f"Badge sync failed: {e}"))

Note: Passing stdout=self.stdout also ensures the nested commands' output is captured consistently.

backend/tests/apps/github/management/commands/github_update_users_test.py (1)

240-262: Tighten badge-sync call assertions to prevent false positives.

assert_any_call passes even if extra commands are invoked or order changes unintentionally. Consider asserting exact calls + count for stronger regression protection.

✅ Suggested tightening
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, patch, call
-        mock_call_command.assert_any_call("nest_update_staff_badges")
-        mock_call_command.assert_any_call("nest_update_project_leader_badges")
+        mock_call_command.assert_has_calls(
+            [
+                call("nest_update_staff_badges"),
+                call("nest_update_project_leader_badges"),
+            ],
+            any_order=False,
+        )
+        assert mock_call_command.call_count == 2

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

🤖 Fix all issues with AI agents
In `@backend/apps/owasp/migrations/0073_rename_bug_slash_css_class.py`:
- Around line 16-19: The migration class (Migration) and its dependency tuple
referencing ("nest", "0072") are in the wrong app; move this data migration so
it belongs to the nest app (the migration that manipulates the Badge model) and
update the Migration.dependencies to point to the correct preceding nest
migration (i.e., the immediate prior nest migration name/number) so Django
registers it under the nest app migration history and preserves ordering and
model access to Badge.
🧹 Nitpick comments (1)
backend/apps/github/management/commands/github_update_users.py (1)

65-70: Consider isolating exception handling for each badge command.

Both badge commands are wrapped in a single try block. If nest_update_staff_badges fails, nest_update_project_leader_badges will be skipped entirely, even though they are independent operations. Separating them ensures both commands get a chance to run.

Also, the command will exit with success (exit code 0) even when badge sync fails since the exception is caught but not re-raised. If this is intentional (to prioritize user contribution updates), consider documenting that decision. Otherwise, you may want to track the failure and raise at the end.

♻️ Proposed refactor to isolate exception handling
         # Sync badges after user data refresh
         self.stdout.write("Syncing badges...")
 
+        badge_sync_failed = False
+
         try:
             call_command("nest_update_staff_badges", stdout=self.stdout)
+        except Exception as e:
+            logger.exception("Staff badge sync failed")
+            self.stderr.write(self.style.ERROR(f"Staff badge sync failed: {e}"))
+            badge_sync_failed = True
+
+        try:
             call_command("nest_update_project_leader_badges", stdout=self.stdout)
         except Exception as e:
-            logger.exception("Badge sync failed")
-            self.stderr.write(self.style.ERROR(f"Badge sync failed: {e}"))
+            logger.exception("Project leader badge sync failed")
+            self.stderr.write(self.style.ERROR(f"Project leader badge sync failed: {e}"))
+            badge_sync_failed = True
+
+        if badge_sync_failed:
+            self.stderr.write(self.style.WARNING("User update completed but badge sync had errors"))

Based on learnings: In Django management commands, use self.stdout.write() and self.stderr.write() for output (which this code correctly does).

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 2, 2026
@Isha-upadhyay Isha-upadhyay marked this pull request as ready for review February 2, 2026 14:15
@github-actions github-actions bot added the docs Improvements or additions to documentation label Feb 2, 2026
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

🤖 Fix all issues with AI agents
In `@backend/docs/Badges.md`:
- Line 200: The fenced code block that currently starts with ``` and contains
the lines "Syncing badges...", "Syncing OWASP Staff...", "Syncing Project
Leaders..." needs a language specifier for proper highlighting and linting;
change the opening fence to include a language (e.g., use ```text or ```bash) so
the block becomes ```text (or another appropriate language) followed by the
existing lines and the closing ```.

@sonarqubecloud
Copy link

sonarqubecloud bot commented Feb 4, 2026

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 11 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend backend-tests docs Improvements or additions to documentation frontend frontend-tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Improve Badge Utilization by Clarifying Backend Frontend Coordination and Automation

1 participant

Comments