Skip to content

Conversation

@pablohashescobar
Copy link
Member

@pablohashescobar pablohashescobar commented Aug 12, 2025

Description

fix: LabelDetailAPIEndpoint from LabelListCreateAPIEndpoint or passing the get_queryset method to inherited class

Type of Change

  • Bug fix (non-breaking change which fixes an issue)

Test Scenarios

  • test label CRUD endpoints for v1 apis

References

WEB-4668

Summary by CodeRabbit

  • Bug Fixes

    • Corrected external ID conflict validation for project labels to check only against other labels, preventing false conflicts when updating an existing label and returning proper 409 errors for true duplicates.
  • Tests

    • Added comprehensive contract tests for label endpoints (list, create, detail, update, delete), covering success and error scenarios, including external ID handling and validation cases.

…or passing the get_queryset method to inherited class
…validation

- Introduced comprehensive tests for creating, retrieving, updating, and deleting labels.
- Enhanced validation logic to prevent duplicate external IDs in label creation.
- Updated the existing LabelDetailAPIEndpoint to exclude the current label when checking for duplicates.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 12, 2025

Walkthrough

Label detail endpoint now inherits from LabelListCreateAPIEndpoint, and its PATCH conflict check targets Label records excluding the current label. A new test suite validates list/create/detail/update/delete behavior for label endpoints, including external_id/external_source handling and duplicate constraint responses.

Changes

Cohort / File(s) Summary of Changes
Label API Endpoint Update
apps/api/plane/api/views/issue.py
Changed LabelDetailAPIEndpoint base class to LabelListCreateAPIEndpoint. Updated PATCH validation to check external_id/external_source conflicts against Label.objects and exclude the current label by id.
Contract Tests for Label API
apps/api/plane/tests/contract/api/test_labels.py
Added fixtures and tests covering list, create (incl. external_id/source), detail, patch, delete, and duplicate external_id conflict (409) for label endpoints.

Sequence Diagram(s)

sequenceDiagram
  participant C as Client
  participant API as Label API Endpoint
  participant DB as Label Store

  C->>API: POST /labels (name, color, [external_id, source])
  API->>DB: Check conflict by external_id+source
  alt Conflict
    API-->>C: 409 CONFLICT
  else No conflict
    API->>DB: Create Label
    API-->>C: 201 Created
  end
Loading
sequenceDiagram
  participant C as Client
  participant API as Label Detail Endpoint
  participant DB as Label Store

  C->>API: PATCH /labels/{id} (updates)
  API->>DB: Check conflict excluding {id}
  alt Conflict
    API-->>C: 409 CONFLICT
  else No conflict
    API->>DB: Update Label
    API-->>C: 200 OK
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Suggested labels

tests required

Suggested reviewers

  • dheeru0198
  • sriramveeraghanta

Poem

I thump my paws—new labels bloom,
With checks that dodge the conflict’s gloom.
Patch and post, we hop along,
IDs aligned, ears tall and strong.
In tests we burrow, sure and tight—
Carrots up! The suite’s alright. 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-label-detail

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
🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@makeplane
Copy link

makeplane bot commented Aug 12, 2025

Pull Request Linked with Plane Work Items

Comment Automatically Generated by Plane

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 (4)
apps/api/plane/api/views/issue.py (1)

950-957: Good inheritance change; consider removing redundant attribute re-declarations

Inheriting from LabelListCreateAPIEndpoint is the right move to reuse get_queryset and permissions. The explicit re-declarations of serializer_class, model, permission_classes, and use_read_replica here are redundant (they’re identical to the parent) and can be dropped to keep things DRY and prevent divergence in future edits.

Suggested diff:

 class LabelDetailAPIEndpoint(LabelListCreateAPIEndpoint):
     """Label Detail Endpoint"""

-    serializer_class = LabelSerializer
-    model = Label
-    permission_classes = [ProjectMemberPermission]
-    use_read_replica = True
+    # Inherit serializer_class, model, permission_classes, and use_read_replica
+    # from LabelListCreateAPIEndpoint to avoid duplication.
apps/api/plane/tests/contract/api/test_labels.py (3)

3-3: Remove unused import

IntegrityError is not used in this test module.

Apply this diff:

-from django.db import IntegrityError

176-186: Drop redundant local import of uuid4

uuid4 is already imported at the top. The local import is unnecessary.

Apply this diff:

-        from uuid import uuid4
-
         fake_id = uuid4()

188-204: Add PATCH external_id conflict and unchanged-value tests to cover edge cases

To validate the updated conflict logic (including exclude(pk=...) and guarding on provided external_id), add tests for:

  • 409 when PATCH attempts to set external_id to one already used by another label
  • 200 when PATCH keeps the same external_id on the same label (no conflict)

I can open a follow-up PR, but here are ready-to-use tests:

@pytest.mark.django_db
def test_update_label_duplicate_external_id_conflict(api_key_client, workspace, project):
    l1 = Label.objects.create(
        name="L1", project=project, workspace=workspace, color="#111111",
        external_id="dup-1", external_source="github"
    )
    l2 = Label.objects.create(
        name="L2", project=project, workspace=workspace, color="#222222",
        external_id="dup-2", external_source="github"
    )
    url = f"/api/v1/workspaces/{workspace.slug}/projects/{project.id}/labels/{l2.id}/"
    response = api_key_client.patch(url, {"external_id": "dup-1", "external_source": "github"}, format="json")
    assert response.status_code == status.HTTP_409_CONFLICT

@pytest.mark.django_db
def test_update_label_external_id_unchanged_no_conflict(api_key_client, workspace, project):
    lbl = Label.objects.create(
        name="L1", project=project, workspace=workspace, color="#111111",
        external_id="keep-1", external_source="github"
    )
    url = f"/api/v1/workspaces/{workspace.slug}/projects/{project.id}/labels/{lbl.id}/"
    response = api_key_client.patch(url, {"external_id": "keep-1"}, format="json")
    assert response.status_code == status.HTTP_200_OK
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d317755 and 9ebe64e.

📒 Files selected for processing (2)
  • apps/api/plane/api/views/issue.py (2 hunks)
  • apps/api/plane/tests/contract/api/test_labels.py (1 hunks)

Comment on lines 1013 to 1025
str(request.data.get("external_id"))
and (label.external_id != str(request.data.get("external_id")))
and Issue.objects.filter(
and Label.objects.filter(
project_id=project_id,
workspace__slug=slug,
external_source=request.data.get(
"external_source", label.external_source
),
external_id=request.data.get("external_id"),
).exists()
)
.exclude(id=pk)
.exists()
):
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

Bug: str(None) truthiness causes false 409 conflicts on PATCH

Using str(request.data.get("external_id")) in the guard means that when external_id is missing or null, it becomes the string "None" (truthy), which incorrectly triggers the duplicate check and can return 409 for valid requests. Also, exclude(pk=pk) is more idiomatic than exclude(id=pk).

Apply this diff:

-            if (
-                str(request.data.get("external_id"))
-                and (label.external_id != str(request.data.get("external_id")))
-                and Label.objects.filter(
-                    project_id=project_id,
-                    workspace__slug=slug,
-                    external_source=request.data.get(
-                        "external_source", label.external_source
-                    ),
-                    external_id=request.data.get("external_id"),
-                )
-                .exclude(id=pk)
-                .exists()
-            ):
+            if (
+                request.data.get("external_id")
+                and (label.external_id != str(request.data.get("external_id")))
+                and Label.objects.filter(
+                    project_id=project_id,
+                    workspace__slug=slug,
+                    external_source=request.data.get(
+                        "external_source", label.external_source
+                    ),
+                    external_id=request.data.get("external_id"),
+                )
+                .exclude(pk=pk)
+                .exists()
+            ):
📝 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
str(request.data.get("external_id"))
and (label.external_id != str(request.data.get("external_id")))
and Issue.objects.filter(
and Label.objects.filter(
project_id=project_id,
workspace__slug=slug,
external_source=request.data.get(
"external_source", label.external_source
),
external_id=request.data.get("external_id"),
).exists()
)
.exclude(id=pk)
.exists()
):
if (
request.data.get("external_id")
and (label.external_id != str(request.data.get("external_id")))
and Label.objects.filter(
project_id=project_id,
workspace__slug=slug,
external_source=request.data.get(
"external_source", label.external_source
),
external_id=request.data.get("external_id"),
)
.exclude(pk=pk)
.exists()
):
🤖 Prompt for AI Agents
In apps/api/plane/api/views/issue.py around lines 1013 to 1025, the guard is
using str(request.data.get("external_id")) which converts None to "None"
(truthy) and causes false 409 conflicts; change the logic to read the raw
external_id = request.data.get("external_id"), ensure you only run the duplicate
check when external_id is not None and not an empty string (e.g., if external_id
is not None and external_id != ""), use that raw value (or str() only after
confirming it's not None) in the filter, and replace .exclude(id=pk) with the
idiomatic .exclude(pk=pk).

@pushya22 pushya22 merged commit 545507f into preview Aug 12, 2025
5 of 7 checks passed
@pushya22 pushya22 deleted the fix-label-detail branch August 12, 2025 09:13
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.

4 participants