Skip to content

Resolve date alignment logic in project health metrics#3838

Closed
saichethana28 wants to merge 2 commits intoOWASP:mainfrom
saichethana28:fix/latest-metrics-months
Closed

Resolve date alignment logic in project health metrics#3838
saichethana28 wants to merge 2 commits intoOWASP:mainfrom
saichethana28:fix/latest-metrics-months

Conversation

@saichethana28
Copy link
Contributor

Proposed change

Resolves #3795

The project health metrics were previously miscalculating the time-series data for the "latest months," leading to inaccurate reporting of project activity over time. This PR updates the logic in the ProjectHealthMetrics model to correctly identify and aggregate data points for the most recent months.

Key changes:

  • Refactored date range logic in project_health_metrics.py to ensure consistent month-to-month alignment.
  • Added comprehensive unit tests to validate the calculation logic across various edge cases (e.g., year rollovers and empty data sets).
  • Verified that the fix scales correctly without impacting performance.

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 7, 2026

Summary by CodeRabbit

  • Bug Fixes

    • Improved monthly health metrics aggregation and formatting so monthly data are grouped and presented as readable month strings (e.g., "Jan 2024") in results.
  • Tests

    • Added tests for monthly grouping logic and empty-state handling to ensure correct monthly scores and month labels.

Walkthrough

Replaces ExtractMonth/TruncDate with TruncMonth for monthly aggregation, removes distinct() on monthly query, orders and formats month keys to "%b %Y" (strings). Adds tests for monthly grouping and empty-state behavior; one existing assertion removed.

Changes

Cohort / File(s) Summary
Monthly aggregation refactor
backend/apps/owasp/models/project_health_metrics.py
Switched monthly truncation to TruncMonth, removed distinct() on the monthly metrics query, ensured results are ordered by month, and convert month keys to formatted strings ("%b %Y").
Test coverage (monthly logic & empty state)
backend/tests/apps/owasp/models/project_health_metrics_test.py
Removed one post-update assertion and added two tests: test_get_stats_monthly_grouping_logic (mocks queryset chain and validates months ["Jan 2024","Jan 2025"] and scores [80.0,90.0]) and test_get_stats_empty_state (validates empty lists).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • arkid15r
  • kasya
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Resolve date alignment logic in project health metrics' clearly summarizes the main change—fixing date/time-series calculation logic in the ProjectHealthMetrics model.
Description check ✅ Passed The description is directly related to the changeset, explaining the date alignment bug fix, refactored logic, and added tests for ProjectHealthMetrics.
Linked Issues check ✅ Passed The PR addresses issue #3795 by fixing the date alignment logic in ProjectHealthMetrics to correctly display the most recent months instead of older ones, meeting the stated objective.
Out of Scope Changes check ✅ Passed All changes are focused on fixing the ProjectHealthMetrics date alignment issue; modifications to the model and corresponding test additions are directly related to the linked issue.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% 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 docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

No actionable comments were generated in the recent review. 🎉

🧹 Recent nitpick comments
backend/tests/apps/owasp/models/project_health_metrics_test.py (1)

123-124: Mock entries use naive datetimes — consider using aware datetimes or date objects to match TruncMonth output.

TruncMonth returns datetime.date (or aware datetime) objects, not naive datetime instances. While this doesn't affect the test outcome since the data is mocked, using the same types as the production code would make the test more representative.

Optional: use date objects to mirror TruncMonth output
-        mock_entry_1 = {"month": timezone.datetime(2024, 1, 1), "score": 80.0}
-        mock_entry_2 = {"month": timezone.datetime(2025, 1, 1), "score": 90.0}
+        from datetime import date
+        mock_entry_1 = {"month": date(2024, 1, 1), "score": 80.0}
+        mock_entry_2 = {"month": date(2025, 1, 1), "score": 90.0}

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.

cubic-dev-ai[bot]
cubic-dev-ai bot previously approved these changes Feb 7, 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 2 files

Confidence score: 5/5

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

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/tests/apps/owasp/models/project_health_metrics_test.py`:
- Around line 182-186: The mock_now fixture is defined but never used; either
remove the unused fixture named mock_now or make the tests use it by adding
mock_now as a parameter to the tests that rely on current time (e.g.,
test_get_stats_monthly_grouping_logic and test_get_stats_empty_state) so
Django's timezone.now is patched to the fixed value when those tests run; locate
the fixture mock_now and the tests test_get_stats_monthly_grouping_logic and
test_get_stats_empty_state and either delete mock_now or add it to the tests'
parameter lists to ensure the filter that calls timezone.now() sees the frozen
time.
🧹 Nitpick comments (2)
backend/tests/apps/owasp/models/project_health_metrics_test.py (2)

119-151: Test is tightly coupled to ORM chain shape but functionally correct.

The mock wiring mirrors the exact query-chain call order (.annotate().filter().values().annotate().order_by()). This is fragile — any reordering in get_stats will silently break the mock and return Mock objects instead of the expected data, potentially causing confusing test failures rather than clear assertion errors.

Consider adding a defensive assertion (e.g., verifying months entries are strings) or, if feasible, using an in-memory SQLite database with pytest-django marks for a more resilient integration-style test. That said, this is a common trade-off in Django unit tests, so it's fine to keep as-is if you prefer.


123-124: Mock month values are naive datetimes.

Production code's TruncMonth returns timezone-aware datetimes. Using timezone.datetime(2024, 1, 1) here produces naive datetimes. This works because strftime doesn't check awareness, but for consistency consider using timezone.make_aware(...) as done elsewhere in this file (e.g., FIXED_DATE on line 14).

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@sonarqubecloud
Copy link

sonarqubecloud bot commented Feb 7, 2026

@saichethana28 saichethana28 marked this pull request as ready for review February 7, 2026 18:49
Copy link
Collaborator

@arkid15r arkid15r left a comment

Choose a reason for hiding this comment

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

I verified that my code works as intended and resolves the issue as described

Could you attach a screenshot demonstrating fix is working?

@arkid15r
Copy link
Collaborator

arkid15r commented Feb 8, 2026

Closing in favor of #3842

@arkid15r arkid15r closed this Feb 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Project Health Dashboard latest date doesn't look right

2 participants