Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,32 @@
5. To fix lint issues
```
ruff check --fix
```
```

## API Documentation

### Tasks

#### Add Label to Task
Comment on lines +98 to +102
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Fix markdown formatting issues.

The static analysis correctly identifies several markdown formatting issues that should be addressed for consistency and readability.

Apply these formatting fixes:

    ruff check --fix
    ```
+
+## API Documentation
+
+### Tasks
+
+#### Add Label to Task
+
+```http
-## API Documentation

-### Tasks

-#### Add Label to Task
-```
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

102-102: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)

🤖 Prompt for AI Agents
In README.md around lines 98 to 102, fix the markdown formatting by ensuring
proper spacing and heading structure. Add blank lines before and after the
headings "## API Documentation", "### Tasks", and "#### Add Label to Task" to
improve readability and consistency. Also, wrap the HTTP example or related
content in proper code block syntax using triple backticks to clearly separate
it from the headings.

```
POST /v1/tasks/{task_id}/labels

Add a label to an existing task.

Request Body:
{
"label_id": "string" // ID of the label to add
}

Responses:
200 OK - Label added successfully
400 Bad Request - Invalid input (e.g., invalid label ID format)
404 Not Found - Task or label not found
500 Internal Server Error - Unexpected server error

Example:
POST /v1/tasks/123/labels
{
"label_id": "456"
}
```
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Add missing trailing newline.

Files should end with a single newline character as indicated by the static analysis.

Add a trailing newline at the end of the file:

}


> Committable suggestion skipped: line range outside the PR's diff.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.17.2)</summary>

124-124: Files should end with a single newline character
null

(MD047, single-trailing-newline)

</details>

</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

In README.md at line 124, the file is missing a trailing newline character at
the end. Add a single newline character after the last line to ensure the file
ends properly as required by static analysis tools.


</details>

<!-- This is an auto-generated comment by CodeRabbit -->

12 changes: 12 additions & 0 deletions todo/serializers/add_label_serializer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from rest_framework import serializers
from todo.models.common.pyobjectid import PyObjectId


class AddLabelSerializer(serializers.Serializer):
label_id = serializers.CharField(required=True)

def validate_label_id(self, value):
try:
return PyObjectId(value)
except Exception:
raise serializers.ValidationError("Invalid label ID format")
Comment on lines +8 to +12
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve exception handling specificity.

The generic except Exception could mask unexpected errors. Based on the PyObjectId implementation in the relevant code snippets, it raises ValueError for invalid ObjectIds.

Use more specific exception handling:

    def validate_label_id(self, value):
        try:
            return PyObjectId(value)
-        except Exception:
+        except (ValueError, TypeError):
            raise serializers.ValidationError("Invalid label ID format")

This way, only expected validation errors are caught, and any unexpected exceptions will bubble up for proper debugging.

📝 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
def validate_label_id(self, value):
try:
return PyObjectId(value)
except Exception:
raise serializers.ValidationError("Invalid label ID format")
def validate_label_id(self, value):
try:
return PyObjectId(value)
except (ValueError, TypeError):
raise serializers.ValidationError("Invalid label ID format")
🤖 Prompt for AI Agents
In todo/serializers/add_label_serializer.py around lines 8 to 12, replace the
generic 'except Exception' with 'except ValueError' in the validate_label_id
method to catch only the expected validation errors from PyObjectId. This
ensures that only invalid ObjectId formats raise a ValidationError, while other
unexpected exceptions are not suppressed and can be properly debugged.

42 changes: 42 additions & 0 deletions todo/services/task_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,3 +221,45 @@ def create_task(cls, dto: CreateTaskDTO) -> CreateTaskResponse:
],
)
)

@staticmethod
def add_label_to_task(task_id: PyObjectId, label_id: PyObjectId) -> None:
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the missing import for PyObjectId.

The static analysis correctly identifies that PyObjectId is not imported. Add the import at the module level with the other imports.

Add this import at the top of the file with the other imports:

+from todo.models.common.pyobjectid import PyObjectId
📝 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
def add_label_to_task(task_id: PyObjectId, label_id: PyObjectId) -> None:
+from todo.models.common.pyobjectid import PyObjectId
🧰 Tools
🪛 Ruff (0.11.9)

226-226: Undefined name PyObjectId

(F821)


226-226: Undefined name PyObjectId

(F821)

🤖 Prompt for AI Agents
In todo/services/task_service.py at line 226, the function uses PyObjectId but
it is not imported. Add the import statement for PyObjectId at the top of the
file alongside the other imports to resolve the missing import error.

"""
Add a label to a task.

Args:
task_id: The ID of the task
label_id: The ID of the label to add

Raises:
ValueError: If the task or label doesn't exist
"""
from todo.repositories.task_repository import TaskRepository
from todo.repositories.label_repository import LabelRepository
Comment on lines +237 to +238
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Move imports to module level.

Imports inside functions are generally an anti-pattern and can hurt performance. These repositories are already imported at the module level.

Remove these local imports since TaskRepository and LabelRepository are already imported at lines 17-18:

-        from todo.repositories.task_repository import TaskRepository
-        from todo.repositories.label_repository import LabelRepository
-
📝 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
from todo.repositories.task_repository import TaskRepository
from todo.repositories.label_repository import LabelRepository
🤖 Prompt for AI Agents
In todo/services/task_service.py around lines 237 to 238, remove the local
imports of TaskRepository and LabelRepository inside the function since they are
already imported at the module level at lines 17-18. This will avoid redundant
imports and improve performance.


# Check if task exists
task = TaskRepository.get_by_id(task_id)
if not task:
raise ValueError(ApiErrorResponse(
statusCode=404,
message="Task not found",
errors=[{"detail": f"Task with ID {task_id} does not exist"}]
))
Comment on lines +243 to +247
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Maintain consistency with existing error response patterns.

The error response structure here doesn't match the pattern used elsewhere in this file. The existing pattern uses ApiErrorDetail objects with proper structure.

Update the error response to match the existing pattern:

-            raise ValueError(ApiErrorResponse(
-                statusCode=404,
-                message="Task not found",
-                errors=[{"detail": f"Task with ID {task_id} does not exist"}]
-            ))
+            raise ValueError(
+                ApiErrorResponse(
+                    statusCode=404,
+                    message="Task not found",
+                    errors=[
+                        ApiErrorDetail(
+                            source={ApiErrorSource.PARAMETER: "task_id"},
+                            title="Task not found",
+                            detail=f"Task with ID {task_id} does not exist",
+                        )
+                    ],
+                )
+            )
📝 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
raise ValueError(ApiErrorResponse(
statusCode=404,
message="Task not found",
errors=[{"detail": f"Task with ID {task_id} does not exist"}]
))
raise ValueError(
ApiErrorResponse(
statusCode=404,
message="Task not found",
errors=[
ApiErrorDetail(
source={ApiErrorSource.PARAMETER: "task_id"},
title="Task not found",
detail=f"Task with ID {task_id} does not exist",
)
],
)
)
🤖 Prompt for AI Agents
In todo/services/task_service.py around lines 243 to 247, the raised ValueError
uses an ApiErrorResponse with a list of dictionaries for errors, which is
inconsistent with the rest of the file that uses ApiErrorDetail objects. To fix
this, replace the dictionary in the errors list with an instance of
ApiErrorDetail, properly initialized with the error detail message, ensuring the
error response structure matches the existing pattern.


# Check if label exists
label = LabelRepository.get_by_id(label_id)
if not label:
raise ValueError(ApiErrorResponse(
statusCode=404,
message="Label not found",
errors=[{"detail": f"Label with ID {label_id} does not exist"}]
))
Comment on lines +252 to +256
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Maintain consistency with existing error response patterns.

Same issue as above - the error response structure should match the existing pattern.

Update the error response to match the existing pattern:

-            raise ValueError(ApiErrorResponse(
-                statusCode=404,
-                message="Label not found",
-                errors=[{"detail": f"Label with ID {label_id} does not exist"}]
-            ))
+            raise ValueError(
+                ApiErrorResponse(
+                    statusCode=404,
+                    message="Label not found",
+                    errors=[
+                        ApiErrorDetail(
+                            source={ApiErrorSource.PARAMETER: "label_id"},
+                            title="Label not found",
+                            detail=f"Label with ID {label_id} does not exist",
+                        )
+                    ],
+                )
+            )
📝 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
raise ValueError(ApiErrorResponse(
statusCode=404,
message="Label not found",
errors=[{"detail": f"Label with ID {label_id} does not exist"}]
))
raise ValueError(
ApiErrorResponse(
statusCode=404,
message="Label not found",
errors=[
ApiErrorDetail(
source={ApiErrorSource.PARAMETER: "label_id"},
title="Label not found",
detail=f"Label with ID {label_id} does not exist",
)
],
)
)
🤖 Prompt for AI Agents
In todo/services/task_service.py around lines 252 to 256, the raised
ValueError's ApiErrorResponse structure does not match the existing error
response pattern. Modify the ApiErrorResponse to follow the consistent format
used elsewhere in the codebase, ensuring the keys and structure align with the
standard error response pattern, such as using 'status_code' instead of
'statusCode' and adjusting the message and errors fields accordingly.


# Initialize labels list if None
if task.labels is None:
task.labels = []

# Add label if not already present
if label_id not in task.labels:
task.labels.append(label_id)
TaskRepository.update(task)
Comment on lines +263 to +265
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Convert PyObjectId to string before storing in labels list.

The task.labels list should contain string IDs, not PyObjectId objects. Looking at the existing code patterns in this file (e.g., line 158), label IDs are stored as strings.

Convert the label_id to string before adding:

-        if label_id not in task.labels:
-            task.labels.append(label_id)
+        label_id_str = str(label_id)
+        if label_id_str not in task.labels:
+            task.labels.append(label_id_str)
📝 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
if label_id not in task.labels:
task.labels.append(label_id)
TaskRepository.update(task)
label_id_str = str(label_id)
if label_id_str not in task.labels:
task.labels.append(label_id_str)
TaskRepository.update(task)
🤖 Prompt for AI Agents
In todo/services/task_service.py around lines 263 to 265, the code appends
label_id directly to task.labels, but task.labels should store string IDs, not
PyObjectId objects. Fix this by converting label_id to a string before appending
it to task.labels, ensuring consistency with existing code patterns in the file.

1 change: 1 addition & 0 deletions todo/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@

urlpatterns = [
path("tasks", TaskView.as_view(), name="tasks"),
path("tasks/<str:task_id>/labels", TaskView.as_view({"post": "post_label"}), name="task_labels"),
path("health", HealthView.as_view(), name="health"),
]
47 changes: 47 additions & 0 deletions todo/views/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@

from todo.serializers.get_tasks_serializer import GetTaskQueryParamsSerializer
from todo.serializers.create_task_serializer import CreateTaskSerializer
from todo.serializers.add_label_serializer import AddLabelSerializer
from todo.services.task_service import TaskService
from todo.dto.task_dto import CreateTaskDTO
from todo.dto.responses.error_response import ApiErrorResponse, ApiErrorDetail, ApiErrorSource
from todo.dto.responses.create_task_response import CreateTaskResponse
from todo.constants.messages import ApiErrors
from todo.models.common.pyobjectid import PyObjectId

class TaskView(APIView):
def get(self, request: Request):
Expand Down Expand Up @@ -59,6 +61,51 @@ def post(self, request: Request):
data=fallback_response.model_dump(mode="json"), status=status.HTTP_500_INTERNAL_SERVER_ERROR
)

def post_label(self, request: Request, task_id: str):
"""
Add a label to a task.

Args:
request: HTTP request containing label data
task_id: ID of the task to add the label to

Returns:
Response: HTTP response with success or error details
"""
try:
task_id = PyObjectId(task_id)
except Exception:
return Response(
data=ApiErrorResponse(
statusCode=400,
message="Invalid task ID format",
errors=[{"detail": "The provided task ID is not valid"}]
).model_dump(mode="json"),
status=status.HTTP_400_BAD_REQUEST
)
Comment on lines +75 to +85
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Use more specific exception handling for ObjectId conversion.

The broad except Exception: clause catches all exceptions, which may mask other potential issues. Consider catching more specific exceptions related to ObjectId conversion.

         try:
             task_id = PyObjectId(task_id)
-        except Exception:
+        except (ValueError, TypeError, InvalidId):
             return Response(

Note: You may need to import InvalidId from bson.errors if PyObjectId uses BSON ObjectId internally.

Let me verify what specific exceptions PyObjectId raises:


🏁 Script executed:

#!/bin/bash
# Description: Check PyObjectId implementation to understand what exceptions it raises
# Expected: Find the specific exceptions that PyObjectId constructor can raise

ast-grep --pattern $'class PyObjectId {
  $$$
  def __init__($$$) {
    $$$
  }
  $$$
}'

# Also search for any exception handling patterns in existing PyObjectId usage
rg -A 5 -B 5 "PyObjectId\("

Length of output: 1738


🏁 Script executed:

#!/bin/bash
# Display the implementation of PyObjectId to determine which exceptions it raises
cat todo/models/common/pyobjectid.py

Length of output: 430


Use specific exception classes for ObjectId conversion

To avoid masking other errors, catch only the exceptions raised by the ObjectId constructor:

• File: todo/views/task.py

  • Add at the top:
    from bson.errors import InvalidId
  • Change the except block around PyObjectId(task_id) from a broad catch-all to only the known error types:
         try:
             task_id = PyObjectId(task_id)
  •    except Exception:
    
  •    except (InvalidId, TypeError):
           return Response(
               data=ApiErrorResponse(
                   statusCode=400,
                   message="Invalid task ID format",
                   errors=[{"detail": "The provided task ID is not valid"}]
               ).model_dump(mode="json"),
               status=status.HTTP_400_BAD_REQUEST
           )
    
    
    
🤖 Prompt for AI Agents
In todo/views/task.py around lines 75 to 85, replace the broad except Exception
clause catching all exceptions during PyObjectId conversion with a more specific
exception handler. Import InvalidId from bson.errors at the top of the file,
then change the except block to catch only InvalidId and any other specific
exceptions PyObjectId might raise. This prevents masking unrelated errors and
improves error handling clarity.


serializer = AddLabelSerializer(data=request.data)
if not serializer.is_valid():
return self._handle_validation_errors(serializer.errors)

try:
TaskService.add_label_to_task(task_id, serializer.validated_data["label_id"])
return Response(status=status.HTTP_200_OK)

except ValueError as e:
if isinstance(e.args[0], ApiErrorResponse):
error_response = e.args[0]
return Response(data=error_response.model_dump(mode="json"), status=error_response.statusCode)

fallback_response = ApiErrorResponse(
statusCode=500,
message=ApiErrors.UNEXPECTED_ERROR_OCCURRED,
errors=[{"detail": str(e) if settings.DEBUG else ApiErrors.INTERNAL_SERVER_ERROR}],
)
return Response(
data=fallback_response.model_dump(mode="json"), status=status.HTTP_500_INTERNAL_SERVER_ERROR
)

def _handle_validation_errors(self, errors):
formatted_errors = []
for field, messages in errors.items():
Expand Down