Skip to content

Conversation

Axxiar
Copy link
Contributor

@Axxiar Axxiar commented Oct 3, 2025

In ebios/workshop 3/activity 1, sorting by entity sorts by entity.id, not entity.name

Summary by CodeRabbit

  • New Features

    • Global customizable ordering mappings for list endpoints, enabling intuitive sorting by related fields.
    • Stakeholder listing now supports combined filtering, text search, and mapped ordering (e.g., sort by related entity name).
  • Bug Fixes / Behavior

    • User/group listing gains mapped sorting by folder/name with consistent ascending/descending behavior.
    • UI: displayed paths now always show full path (no truncation/ellipsis).

Copy link
Contributor

coderabbitai bot commented Oct 3, 2025

Walkthrough

Adds a reusable CustomOrderingFilter that requires an ordering_mapping and remaps ordering terms (preserving direction); applies it as UserGroupOrderingFilter and StakeholderOrderingFilter, and wires StakeholderOrderingFilter plus DjangoFilterBackend and SearchFilter into StakeholderViewSet. Also removes path-truncation logic from UserGroupNameDisplay.svelte to always render full path.

Changes

Cohort / File(s) Summary
Core ordering utilities & user-group mapping
backend/core/views.py
Added CustomOrderingFilter (subclass of DRF OrderingFilter) that enforces presence of ordering_mapping via __init_subclass__; get_ordering remaps ordering terms (preserving "-" direction) and returns Optional[list[str]]; added Optional import; UserGroupOrderingFilter now inherits and sets ordering_mapping = {"localization_dict": "folder__name"}.
EBIOS stakeholder view enhancements
backend/ebios_rm/views.py
Added StakeholderOrderingFilter(CustomOrderingFilter) with ordering_mapping = {"entity": "entity__name"}; updated StakeholderViewSet.filter_backends to include DjangoFilterBackend, filters.SearchFilter, and StakeholderOrderingFilter; added imports for rest_framework.filters and django_filters.rest_framework.DjangoFilterBackend.
Frontend display behavior
frontend/src/lib/components/ModelTable/UserGroupNameDisplay.svelte
Removed conditional truncation/ellipsis logic; always compute and render the full path by joining path segments with " / ", eliminating shortened-path branch.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant ViewSet as StakeholderViewSet
  participant DFB as DjangoFilterBackend
  participant SFB as SearchFilter
  participant OF as StakeholderOrderingFilter
  participant ORM as QuerySet/DB

  Client->>ViewSet: GET /stakeholders?search=...&ordering=entity
  ViewSet->>DFB: apply filters (query params)
  DFB-->>ViewSet: filtered queryset
  ViewSet->>SFB: apply search
  SFB-->>ViewSet: searched queryset
  ViewSet->>OF: get_ordering(request, queryset, view)
  note right of OF #D6EAF8: Map "entity" -> "entity__name"\nPreserve direction (e.g., -entity)
  OF-->>ViewSet: ordering=["entity__name"]
  ViewSet->>ORM: order_by(entity__name)
  ORM-->>ViewSet: ordered results
  ViewSet-->>Client: 200 OK (paginated list)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • eric-intuitem
  • ab-smith

Poem

I twitch my nose at tangled keys,
I hop through fields and map with ease.
From entity to folder's name,
I nudge the order, tame the game.
Paths unrolled — a joyful breeze 🐇

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly describes the primary change—correcting the invalid sort by entities in ebios workshop 3—and uses a clear “fix:” prefix that aligns with the PR’s intent to resolve that specific issue.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch CA-1207-invalid-entity-sort-workshop3

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9afed99 and 1a7fbc1.

📒 Files selected for processing (1)
  • frontend/src/lib/components/ModelTable/UserGroupNameDisplay.svelte (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/lib/components/ModelTable/UserGroupNameDisplay.svelte
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: build_enterprise_frontend
  • GitHub Check: build_community_frontend
  • GitHub Check: build (3.12)
  • GitHub Check: test (3.12)
  • GitHub Check: enterprise-startup-functional-test (3.12)
  • GitHub Check: enterprise-startup-docker-compose-test
  • GitHub Check: startup-docker-compose-test
  • GitHub Check: startup-functional-test (3.12)
  • GitHub Check: Analyze (python)

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.

@Axxiar Axxiar marked this pull request as ready for review October 6, 2025 15:36
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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 85672d6 and 44c7dba.

📒 Files selected for processing (2)
  • backend/core/views.py (2 hunks)
  • backend/ebios_rm/views.py (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
backend/ebios_rm/views.py (1)
backend/core/views.py (2)
  • GenericFilterSet (160-225)
  • CustomOrderingFilter (228-261)
🔇 Additional comments (3)
backend/ebios_rm/views.py (3)

3-7: LGTM!

The import of CustomOrderingFilter is correctly added and necessary for the new StakeholderOrderingFilter implementation.


27-28: LGTM!

The imports for filters and DjangoFilterBackend are correctly added and necessary for the filter backends configuration.


214-216: LGTM!

The StakeholderOrderingFilter correctly extends CustomOrderingFilter and defines the required ordering_mapping attribute. The mapping of "entity" to "entity__name" directly addresses the sorting issue described in the PR, ensuring entities are sorted by name rather than ID.

Comment on lines +223 to +227
filter_backends = [
DjangoFilterBackend,
filters.SearchFilter,
StakeholderOrderingFilter,
]
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Good fix for the entity sorting issue.

The filter_backends configuration correctly integrates the custom ordering filter to fix the entity sorting behavior.

Consider adding explicit configuration for better clarity:

     filter_backends = [
         DjangoFilterBackend,
         filters.SearchFilter,
         StakeholderOrderingFilter,
     ]
+    ordering_fields = ["entity", "created_at", "updated_at"]
+    search_fields = ["entity__name"]  # If search functionality is desired

Run the following script to verify the entity field relationship and test the fix:


🏁 Script executed:

#!/bin/bash
# Description: Verify Stakeholder model has entity FK with name field

# Find the Stakeholder model definition
ast-grep --pattern $'class Stakeholder($$$):
  $$$'

# Check for entity field usage in Stakeholder
rg -A 5 -B 2 "entity.*=" backend/ebios_rm/models.py

# Verify entity is used in related queries
rg "entity__name" backend/

Length of output: 9180


🏁 Script executed:

#!/bin/bash
echo "=== StakeholderViewSet Definition ==="
rg -nP 'class\s+StakeholderViewSet' -C5 backend/ebios_rm/views.py

echo
echo "=== search_fields in StakeholderViewSet ==="
rg -nC3 'search_fields' backend/ebios_rm/views.py

echo
echo "=== filterset_fields or filterset_class in StakeholderViewSet ==="
rg -nC3 'filterset_' backend/ebios_rm/views.py

echo
echo "=== ordering_fields in StakeholderViewSet ==="
rg -nC3 'ordering_fields' backend/ebios_rm/views.py

Length of output: 2797


Specify search_fields for SearchFilter and restrict ordering_fields

The filters.SearchFilter will error without search_fields, so add:

 class StakeholderViewSet(BaseModelViewSet):
     filter_backends = [
         DjangoFilterBackend,
         filters.SearchFilter,
         StakeholderOrderingFilter,
     ]
+    search_fields = ['entity__name']
+    ordering_fields = ['entity', 'created_at', 'updated_at']
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
filter_backends = [
DjangoFilterBackend,
filters.SearchFilter,
StakeholderOrderingFilter,
]
filter_backends = [
DjangoFilterBackend,
filters.SearchFilter,
StakeholderOrderingFilter,
]
search_fields = ['entity__name']
ordering_fields = ['entity', 'created_at', 'updated_at']
🤖 Prompt for AI Agents
In backend/ebios_rm/views.py around lines 223 to 227, the SearchFilter is
configured but no search_fields are provided (which will raise an error) and
ordering is unconstrained; add a search_fields attribute listing the text fields
you want searchable (e.g., ['name', 'description', 'email'] or the actual model
field names used here) and add an ordering_fields attribute that restricts
allowed ordering keys (e.g., ['id', 'name', 'created_at'] or the specific fields
on the view's queryset). Place both attributes on the view class alongside
filter_backends.

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)
backend/core/views.py (1)

228-263: Solid ordering remap; harden subclass check

Great reusable filter. Replace assert with a real exception and accept kwargs in init_subclass to be robust in all runtimes.

Apply this diff:

-    def __init_subclass__(cls):
-        assert hasattr(cls, "ordering_mapping"), (
-            f"Subclasses of {cls.__name__} must define the ordering_mapping attribute."
-        )
+    def __init_subclass__(cls, **kwargs):
+        super().__init_subclass__(**kwargs)
+        if not hasattr(cls, "ordering_mapping"):
+            raise TypeError(
+                f"{cls.__name__} must define class attribute 'ordering_mapping'"
+            )

Also consider extracting this class into a shared filters module for reuse across apps.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 44c7dba and afcccb0.

📒 Files selected for processing (1)
  • backend/core/views.py (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: test (3.12)
  • GitHub Check: build_community_frontend
  • GitHub Check: build_enterprise_frontend
  • GitHub Check: build (3.12)
  • GitHub Check: startup-docker-compose-test
  • GitHub Check: enterprise-startup-docker-compose-test
  • GitHub Check: enterprise-startup-functional-test (3.12)
  • GitHub Check: startup-functional-test (3.12)
🔇 Additional comments (2)
backend/core/views.py (2)

16-16: Add Optional import — OK

Type annotation update looks good.


3213-3214: UserGroupOrderingFilter mapping looks correct

Mapping localization_dict → folder__name matches the view’s ordering_fields and preserves direction. LGTM.

Copy link
Collaborator

@eric-intuitem eric-intuitem left a comment

Choose a reason for hiding this comment

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

This breaks the advance sorting for user groups (bug visible in pro version only).
This PR should not touch this part.

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)
backend/core/views.py (1)

228-263: Solid remapped ordering; replace assert in init_subclass with explicit error

Logic correctly preserves direction and falls back when unmapped. Prefer raising a concrete exception (and calling super) over assert, which can be disabled with -O.

Apply this diff:

-    def __init_subclass__(cls):
-        assert hasattr(cls, "ordering_mapping"), (
-            f"Subclasses of {cls.__name__} must define the ordering_mapping attribute."
-        )
+    def __init_subclass__(cls) -> None:
+        super().__init_subclass__()
+        if not hasattr(cls, "ordering_mapping"):
+            raise TypeError(
+                f"{cls.__name__} must define class attribute 'ordering_mapping'."
+            )

Optional: consider typing ordering_mapping as Mapping[str, str] for flexibility.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between afcccb0 and 4a02287.

📒 Files selected for processing (1)
  • backend/core/views.py (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: test (3.12)
  • GitHub Check: enterprise-startup-functional-test (3.12)
  • GitHub Check: enterprise-startup-docker-compose-test
  • GitHub Check: startup-functional-test (3.12)
  • GitHub Check: build (3.12)
  • GitHub Check: startup-docker-compose-test
  • GitHub Check: build_enterprise_frontend
  • GitHub Check: build_community_frontend
🔇 Additional comments (1)
backend/core/views.py (1)

16-16: Import update looks good

Optional is needed for the new get_ordering signature; no issues.

@Axxiar Axxiar requested a review from eric-intuitem October 7, 2025 09:59
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.

3 participants