Repository navigation
[WEB-5153] chore: optimised the cycle transfer issues - #7969
Conversation
|
Linked to Plane Work Item(s) This comment was auto-generated by Plane |
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughDelegate cycle-issue transfer from endpoint handlers to a new utility function Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Client
participant API as TransferCycleIssueEndpoint
participant Util as transfer_cycle_issues
participant DB as DB/ORM
participant Act as ActivityLogger
Client->>API: POST /cycles/{id}/transfer { new_cycle_id }
API->>Util: transfer_cycle_issues(slug, project_id, cycle_id, new_cycle_id, request, user_id)
rect rgba(235,245,255,0.6)
Util->>DB: Fetch source & destination cycles (annotated counts)
alt destination completed
Util-->>API: { error: "destination cycle completed" } (400)
API-->>Client: 400 { error: ... }
else proceed
Util->>DB: Query issues, estimates, assignee/label distributions
Util->>DB: Bulk update incomplete CycleIssue -> new_cycle
Util->>DB: Persist progress_snapshot
Util->>Act: Log cycle.activity.created with updated/created items
Util-->>API: { message: "Success" }
API-->>Client: 200 { message: "Success" }
end
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Pull Request Overview
This PR refactors the cycle issue transfer functionality by extracting the complex logic into a dedicated utility function. The refactoring improves code maintainability and reusability while maintaining the same functionality.
- Extracted cycle issue transfer logic into a reusable utility function
- Updated two view files to use the new utility function instead of inline code
- Applied code formatting improvements across the affected files
Reviewed Changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| apps/api/plane/utils/cycle_transfer_issues.py | New utility function containing the extracted cycle issue transfer logic |
| apps/api/plane/app/views/cycle/base.py | Refactored to use the new utility function and applied code formatting |
| apps/api/plane/api/views/cycle.py | Refactored to use the new utility function and applied code formatting |
Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (2)
apps/api/plane/app/views/cycle/base.py (1)
100-102: Avoid deferred field hits in prefetch; include display_name (and avatar if used).Using only("avatar_asset", "first_name", "id") may trigger additional DB queries if serializers access display_name/avatar. Add display_name (and avatar if referenced) to the projection.
- queryset=User.objects.only( - "avatar_asset", "first_name", "id" - ).distinct(), + queryset=User.objects.only( + "id", "first_name", "display_name", "avatar_asset", "avatar" + ).distinct(),apps/api/plane/api/views/cycle.py (1)
198-200: Align “current cycle” time window with project timezone for consistency.Base app view uses project timezone→UTC conversion; this uses timezone.now(). Consider matching the project-tz approach to avoid mismatched lists across endpoints.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
apps/api/plane/api/views/cycle.py(19 hunks)apps/api/plane/app/views/cycle/base.py(20 hunks)apps/api/plane/utils/cycle_transfer_issues.py(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
apps/api/plane/utils/cycle_transfer_issues.py (5)
apps/api/plane/db/models/cycle.py (2)
Cycle(56-97)CycleIssue(100-123)apps/api/plane/db/models/issue.py (1)
Issue(104-250)apps/api/plane/db/models/project.py (1)
Project(65-159)apps/api/plane/bgtasks/issue_activities_task.py (1)
issue_activity(1500-1600)apps/api/plane/api/views/cycle.py (5)
get(186-281)get(468-482)get(758-770)get(877-928)get(1098-1113)
apps/api/plane/app/views/cycle/base.py (2)
apps/api/plane/utils/cycle_transfer_issues.py (1)
transfer_cycle_issues(31-480)apps/api/plane/db/models/cycle.py (2)
CycleIssue(100-123)Cycle(56-97)
apps/api/plane/api/views/cycle.py (1)
apps/api/plane/utils/cycle_transfer_issues.py (1)
transfer_cycle_issues(31-480)
⏰ 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). (2)
- GitHub Check: Lint API
- GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
apps/api/plane/api/views/cycle.py (1)
1218-1235: Good refactor: delegation to transfer utility.Endpoint is simpler and consistently handles success/error via the utility.
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
apps/api/plane/api/views/cycle.py (1)
534-536: Reuse the sanitized payload when validating completed cycles.Per earlier feedback, we build
request_datathat strips disallowed fields, but the serializer here still consumesrequest.data, letting forbidden updates slip through on completed cycles. Please passdata=request_datainstead.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
apps/api/plane/api/views/cycle.py(19 hunks)apps/api/plane/utils/cycle_transfer_issues.py(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
apps/api/plane/api/views/cycle.py (2)
apps/api/plane/utils/cycle_transfer_issues.py (1)
transfer_cycle_issues(31-488)apps/api/plane/db/models/cycle.py (2)
Cycle(56-97)CycleIssue(100-123)
apps/api/plane/utils/cycle_transfer_issues.py (4)
apps/api/plane/db/models/cycle.py (2)
Cycle(56-97)CycleIssue(100-123)apps/api/plane/db/models/issue.py (1)
Issue(104-250)apps/api/plane/db/models/project.py (1)
Project(65-159)apps/api/plane/bgtasks/issue_activities_task.py (1)
issue_activity(1500-1600)
⏰ 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). (2)
- GitHub Check: Analyze (javascript)
- GitHub Check: Build and lint web apps
|
@NarayanBavisetti Can you check the AI reviews? and resolve them |
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/api/plane/api/views/cycle.py (1)
788-796: None-safe archive guard.
cycle.end_datecan be None (draft cycle); comparing None with datetime raises TypeError.- if cycle.end_date >= timezone.now(): + if cycle.end_date is None or cycle.end_date >= timezone.now(): return Response( {"error": "Only completed cycles can be archived"}, status=status.HTTP_400_BAD_REQUEST, )
♻️ Duplicate comments (5)
apps/api/plane/utils/cycle_transfer_issues.py (3)
440-448: Exclude soft-deleted rows from transfer set.Include
deleted_atfilters on both bridge and issue to avoid resurrecting removed items.cycle_issues = CycleIssue.objects.filter( cycle_id=cycle_id, project_id=project_id, workspace__slug=slug, + deleted_at__isnull=True, + issue__deleted_at__isnull=True, issue__archived_at__isnull=True, issue__is_draft=False, issue__state__group__in=["backlog", "unstarted", "started"], )
53-63: Guardnew_cyclebefore dereferencing; fail fast on missing/archived/completed targets.Accessing
new_cycle.end_datewithout a None-check can 500; also block archived targets early.@@ - # Get the new cycle + # Get the new cycle new_cycle = Cycle.objects.filter( workspace__slug=slug, project_id=project_id, pk=new_cycle_id ).first() - # Check if new cycle is already completed - if new_cycle.end_date is not None and new_cycle.end_date < timezone.now(): + # Validate target cycle + if new_cycle is None: + return {"success": False, "error": "Target cycle not found"} + if new_cycle.archived_at is not None: + return {"success": False, "error": "Cannot transfer to an archived cycle"} + # Disallow transfer into a completed cycle + if new_cycle.end_date is not None and new_cycle.end_date < timezone.now(): return { "success": False, "error": "The cycle where the issues are transferred is already completed", } + + # No-op guard + if str(new_cycle.id) == str(cycle_id): + return {"success": False, "error": "Source and target cycles are the same"}
411-485: Make snapshot + transfer atomic; dispatch activity on commit.Without a transaction, snapshot may persist while transfer fails; also fire
issue_activityonly after commit.@@ -from django.db import models +from django.db import models +from django.db import transaction @@ - # Get the current cycle and save progress snapshot - current_cycle = Cycle.objects.filter( - workspace__slug=slug, project_id=project_id, pk=cycle_id - ).first() - - current_cycle.progress_snapshot = { + # Apply snapshot and transfer atomically + with transaction.atomic(): + # Get and update current (source) cycle snapshot + current_cycle = Cycle.objects.filter( + workspace__slug=slug, project_id=project_id, pk=cycle_id + ).select_for_update().first() + if current_cycle is None: + return {"success": False, "error": "Source cycle not found"} + + current_cycle.progress_snapshot = { @@ - } - current_cycle.save(update_fields=["progress_snapshot"]) + } + current_cycle.save(update_fields=["progress_snapshot"]) @@ - # Get issues to transfer (only incomplete issues) - cycle_issues = CycleIssue.objects.filter( + # Get issues to transfer (only incomplete issues) + cycle_issues = CycleIssue.objects.filter( cycle_id=cycle_id, project_id=project_id, workspace__slug=slug, + deleted_at__isnull=True, + issue__deleted_at__isnull=True, issue__archived_at__isnull=True, issue__is_draft=False, issue__state__group__in=["backlog", "unstarted", "started"], - ) + ) + + # Exclude issues already in target cycle to avoid unique-constraint conflicts + existing_in_target = CycleIssue.objects.filter( + cycle_id=new_cycle_id, + project_id=project_id, + workspace__slug=slug, + deleted_at__isnull=True, + ).values_list("issue_id", flat=True) + cycle_issues = cycle_issues.exclude(issue_id__in=existing_in_target) @@ - updated_cycles = [] - update_cycle_issue_activity = [] - for cycle_issue in cycle_issues: - cycle_issue.cycle_id = new_cycle_id - updated_cycles.append(cycle_issue) - update_cycle_issue_activity.append( - { - "old_cycle_id": str(cycle_id), - "new_cycle_id": str(new_cycle_id), - "issue_id": str(cycle_issue.issue_id), - } - ) + updated_cycles = [] + update_cycle_issue_activity = [] + for cycle_issue in cycle_issues: + cycle_issue.cycle_id = new_cycle_id + updated_cycles.append(cycle_issue) + update_cycle_issue_activity.append( + { + "old_cycle_id": str(cycle_id), + "new_cycle_id": str(new_cycle_id), + "issue_id": str(cycle_issue.issue_id), + } + ) @@ - # Bulk update cycle issues - cycle_issues = CycleIssue.objects.bulk_update( - updated_cycles, ["cycle_id"], batch_size=100 - ) + # Bulk update cycle issues + CycleIssue.objects.bulk_update(updated_cycles, ["cycle_id"], batch_size=100) - # Capture Issue Activity - issue_activity.delay( - type="cycle.activity.created", - requested_data=json.dumps({"cycles_list": []}), - actor_id=str(user_id), - issue_id=None, - project_id=str(project_id), - current_instance=json.dumps( - { - "updated_cycle_issues": update_cycle_issue_activity, - "created_cycle_issues": [], - } - ), - epoch=int(timezone.now().timestamp()), - notification=True, - origin=base_host(request=request, is_app=True), - ) + # Fire activity after successful commit + def _after_commit(): + issue_activity.delay( + type="cycle.activity.created", + requested_data=json.dumps({"cycles_list": []}), + actor_id=str(user_id), + issue_id=None, + project_id=str(project_id), + current_instance=json.dumps( + { + "updated_cycle_issues": update_cycle_issue_activity, + "created_cycle_issues": [], + } + ), + epoch=int(timezone.now().timestamp()), + notification=True, + origin=base_host(request=request, is_app=True), + ) + transaction.on_commit(_after_commit)apps/api/plane/api/views/cycle.py (2)
534-536: Use sanitizedrequest_datain update serializer.Otherwise prohibited fields can slip through for completed cycles.
- serializer = CycleUpdateSerializer( - cycle, data=request.data, partial=True, context={"request": request} - ) + serializer = CycleUpdateSerializer( + cycle, data=request_data, partial=True, context={"request": request} + )
1218-1228: Flip the completion guard: allow transfer only when source is completed.Condition is inverted; it currently blocks completed cycles and allows active ones.
Based on learnings- # transfer work items only when cycle is completed (passed the end data) - if old_cycle.end_date is not None and old_cycle.end_date < timezone.now(): + # Transfer only when the old cycle is completed + if old_cycle.end_date is None or old_cycle.end_date >= timezone.now(): return Response( - {"error": "The old cycle is not completed yet"}, + {"error": "The old cycle is not completed yet"}, status=status.HTTP_400_BAD_REQUEST, )
🧹 Nitpick comments (2)
apps/api/plane/utils/cycle_transfer_issues.py (1)
65-139: Optional: Validate source completion here too (defense-in-depth).Even though the view should guard this, add a check to ensure transfers only occur from completed cycles.
Based on learnings@@ - old_cycle = ( + old_cycle = ( Cycle.objects.filter(workspace__slug=slug, project_id=project_id, pk=cycle_id) @@ ) old_cycle = old_cycle.first() if old_cycle is None: return { "success": False, "error": "Source cycle not found", } + if old_cycle.end_date is None or old_cycle.end_date >= timezone.now(): + return {"success": False, "error": "The old cycle is not completed yet"}apps/api/plane/api/views/cycle.py (1)
1240-1247: Preserve error status from utility (optional).The utility returns only
success/error. Consider propagating distinct HTTP statuses (404 vs 400) for clearer API semantics.- else: - return Response( - {"error": result.get("error")}, - status=status.HTTP_400_BAD_REQUEST, - ) + else: + # Optionally, return 404 when source/target not found + return Response({"error": result.get("error")}, status=status.HTTP_400_BAD_REQUEST)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
apps/api/plane/api/views/cycle.py(19 hunks)apps/api/plane/utils/cycle_transfer_issues.py(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-17T10:46:13.800Z
Learnt from: NarayanBavisetti
PR: makeplane/plane#7969
File: apps/api/plane/api/views/cycle.py:1218-1228
Timestamp: 2025-10-17T10:46:13.800Z
Learning: In the cycle transfer functionality in apps/api/plane/api/views/cycle.py, transfers should only be allowed from completed cycles (end_date < timezone.now()), not from active or draft cycles. The guard should block when end_date is None or end_date >= timezone.now().
Applied to files:
apps/api/plane/api/views/cycle.pyapps/api/plane/utils/cycle_transfer_issues.py
🧬 Code graph analysis (2)
apps/api/plane/api/views/cycle.py (2)
apps/api/plane/utils/cycle_transfer_issues.py (1)
transfer_cycle_issues(31-486)apps/api/plane/db/models/cycle.py (2)
Cycle(56-97)CycleIssue(100-123)
apps/api/plane/utils/cycle_transfer_issues.py (5)
apps/api/plane/db/models/cycle.py (2)
Cycle(56-97)CycleIssue(100-123)apps/api/plane/db/models/issue.py (1)
Issue(104-250)apps/api/plane/db/models/project.py (1)
Project(65-159)apps/api/plane/bgtasks/issue_activities_task.py (1)
issue_activity(1500-1600)apps/api/plane/api/views/cycle.py (5)
get(186-281)get(468-482)get(758-770)get(877-928)get(1098-1113)
⏰ 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). (1)
- GitHub Check: Build and lint web apps
🔇 Additional comments (1)
apps/api/plane/utils/cycle_transfer_issues.py (1)
142-147: LGTM: defensive check for missing source cycle.
* chore: optimised the cycle transfer issues * chore: added more vlaidation in transfer * chore: improve the comments
Description
This pull request optimizes the transfer of issues from one cycle to another.
A utility function has been introduced to handle the logic for transferring issues between cycles.
Type of Change
Summary by CodeRabbit