Skip to content

[WEB-5153] chore: optimised the cycle transfer issues - #7969

Merged
sriramveeraghanta merged 3 commits into
previewfrom
chore-cycle-transfer-issues
Oct 22, 2025
Merged

sriramveeraghanta merged 3 commits into
previewfrom
chore-cycle-transfer-issues

Conversation

@NarayanBavisetti

@NarayanBavisetti NarayanBavisetti commented Oct 15, 2025 •

Copy link
Copy Markdown
Contributor

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

  • Code refactoring

Summary by CodeRabbit

  • Refactor
    • Centralized and simplified cycle-issue transfer to improve reliability.
    • Prevents transferring into already-completed cycles and returns clear errors.
    • Only incomplete issues are moved between cycles.
    • Generates and saves consistent progress snapshots and estimate charts for the destination cycle.
    • Standardized success/error responses and improved activity logging for transfers.

@makeplane

makeplane Bot commented Oct 15, 2025

Copy link
Copy Markdown

Linked to Plane Work Item(s)

This comment was auto-generated by Plane

@coderabbitai

coderabbitai Bot commented Oct 15, 2025 •

Copy link
Copy Markdown
Contributor

Note

Other AI code review bot(s) detected

CodeRabbit 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.

Walkthrough

Delegate cycle-issue transfer from endpoint handlers to a new utility function transfer_cycle_issues(...) which validates destination cycle, aggregates progress and estimate data, bulk-moves incomplete issues, persists snapshots, and logs activity; endpoints now call the utility and return its result.

Changes

Cohort / File(s) Summary
API endpoint delegation
apps/api/plane/api/views/cycle.py, apps/api/plane/app/views/cycle/base.py
Replace heavy in-method transfer logic with a single call to transfer_cycle_issues(...); simplify POST handlers to rely on utility response, update imports, and apply minor formatting/serializer argument adjustments.
Transfer utility module
apps/api/plane/utils/cycle_transfer_issues.py
New module adding transfer_cycle_issues(slug, project_id, cycle_id, new_cycle_id, request, user_id): validates destination, computes annotated counts and (if point-based) estimate distributions and burndown, builds assignee/label distributions, bulk-updates incomplete CycleIssue records, persists progress_snapshot, logs activity events, and returns structured success/error payloads.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

A rabbit hopped through cycles' rows,
Counting points where soft wind blows.
One helper hop, the issues flew—
Snapshots stitched and burndowns too.
Thump-thump—transfer finished, woo-hoo! 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The pull request description is incomplete compared to the required template. While the Description and Type of Change sections are present and appropriately filled out, the description lacks critical sections: Test Scenarios (which describes the tests performed to verify the refactoring) is entirely missing, References section is absent (though WEB-5153 is mentioned in the title), and the Description itself is minimal with only two sentences that don't explain the rationale, detailed changes, or impact of the refactoring. This incomplete coverage of the template requirements results in insufficient information for reviewers to understand how the changes were validated and what specific issues or context motivated this refactoring. The author should add the missing Test Scenarios section describing what tests were performed to verify the refactoring maintains existing functionality, include a References section linking to issue WEB-5153 for context, and expand the Description section to explain what specific changes were made, why the refactoring was necessary, and what benefits the new utility function provides (e.g., reduced code duplication, improved maintainability, performance gains).
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title "[WEB-5153] chore: optimised the cycle transfer issues" clearly and specifically describes the main change in the pull request: refactoring and optimizing the cycle issue transfer functionality by introducing a centralized utility function. The title is concise, uses appropriate terminology ("chore," "optimised"), and directly reflects the core refactoring work shown across the modified files. A teammate scanning the commit history would understand that this PR focuses on optimizing the cycle transfer process through code consolidation and refactoring.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore-cycle-transfer-issues

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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2b106cb and 67a667d.

📒 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.

Comment thread apps/api/plane/api/views/cycle.py Resolved
Comment thread apps/api/plane/app/views/cycle/base.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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_data that strips disallowed fields, but the serializer here still consumes request.data, letting forbidden updates slip through on completed cycles. Please pass data=request_data instead.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 67a667d and 4b85c69.

📒 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

Comment thread apps/api/plane/api/views/cycle.py Resolved
dheeru0198
dheeru0198 previously approved these changes Oct 16, 2025
@dheeru0198

Copy link
Copy Markdown
Member

@NarayanBavisetti Can you check the AI reviews? and resolve them

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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_date can 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_at filters 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: Guard new_cycle before dereferencing; fail fast on missing/archived/completed targets.

Accessing new_cycle.end_date without 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_activity only 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 sanitized request_data in 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4b85c69 and 8f5ff14.

📒 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.py
  • apps/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.

@sriramveeraghanta
sriramveeraghanta merged commit f94da68 into preview Oct 22, 2025
@sriramveeraghanta
sriramveeraghanta deleted the chore-cycle-transfer-issues branch October 22, 2025 18:59
TheJohnFogarty pushed a commit to TheJohnFogarty/plane that referenced this pull request Aug 7, 2026
* chore: optimised the cycle transfer issues

* chore: added more vlaidation in transfer

* chore: improve the comments
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.

5 participants