Skip to content

Comments

[WEB-2598] fix: show toast when existing issue is added to cycles#5771

Closed
sharma01ketan wants to merge 9 commits intopreviewfrom
fix/add-existing-issue-to-cycle-toast
Closed

[WEB-2598] fix: show toast when existing issue is added to cycles#5771
sharma01ketan wants to merge 9 commits intopreviewfrom
fix/add-existing-issue-to-cycle-toast

Conversation

@sharma01ketan
Copy link
Contributor

@sharma01ketan sharma01ketan commented Oct 8, 2024

[WEB-2598]

This PR aims to display a toast message on the loading, success and failure state, when an existing issue is added to a cycle in the calendar view at the project level.

Previous State:

  • No successful toast is displayed when the promise is resolved
Screen.Recording.2024-10-08.at.3.34.30.PM.mov

New State:

  • Toast appears for: Uploading, Successful and Failure state, the Success state.
Screen.Recording.2024-10-08.at.3.34.51.PM.mov

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced user feedback during issue addition with dynamic toast notifications for loading, success, and error states.
    • Introduced the ability for partial updates to project instances, simplifying access control for users with ADMIN roles.
  • Bug Fixes

    • Improved error handling with more informative messages based on the specific error encountered.
    • Updated URL validation to recognize a broader range of valid URL formats.

@sharma01ketan sharma01ketan added 🐛bug Something isn't working 🌐frontend labels Oct 8, 2024
@sharma01ketan sharma01ketan added this to the v0.23-dev milestone Oct 8, 2024
@sharma01ketan sharma01ketan self-assigned this Oct 8, 2024
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 8, 2024

Walkthrough

The changes involve updates to the CalendarQuickAddIssueActions component in the quick-add-issue-actions.tsx file, where the setToast function has been replaced with setPromiseToast to improve user feedback during asynchronous operations. The handleAddIssuesToView function now utilizes a promise for managing updates and notifications, providing dynamic messages for loading, success, and error states. Additionally, a new partial_update method has been introduced in the ProjectViewSet class in base.py to allow partial updates to project instances, simplifying permission checks. The URL validation logic in string.helper.ts has also been refined.

Changes

File Path Change Summary
web/core/components/issues/issue-layouts/calendar/quick-add-issue-actions.tsx Replaced setToast with setPromiseToast, updated handleAddIssuesToView for promise-based handling, improved error handling with dynamic messages. Removed setToast import and added setPromiseToast.
apiserver/plane/app/views/project/base.py Added partial_update method in ProjectViewSet for partial project updates with simplified permission checks.
web/helpers/string.helper.ts Updated regex pattern in checkURLValidity function to enhance URL validation accuracy.

Possibly related PRs

Suggested labels

🌟enhancement, 🧹chore

Suggested reviewers

  • sriramveeraghanta
  • SatishGandham
  • rahulramesha

Poem

🐰 In the garden where issues grow,
Quick adds now have a smoother flow.
With promise toast, we share the news,
Loading, success, no more blues!
A hop, a skip, a joyful cheer,
User feedback is now crystal clear! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

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

@sharma01ketan sharma01ketan marked this pull request as ready for review October 8, 2024 10:12
@sriramveeraghanta sriramveeraghanta modified the milestones: v0.23.0, v0.24.0 Oct 8, 2024
Copy link
Collaborator

@gakshita gakshita left a comment

Choose a reason for hiding this comment

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

Remove extra files

if (!workspaceSlug || !projectId) return;

const issueIds = data.map((i) => i.id);
const updatePromise = Promise.all(
Copy link
Collaborator

Choose a reason for hiding this comment

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

better naming here

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

🧹 Outside diff range and nitpick comments (9)
web/helpers/string.helper.ts (1)

273-273: Improved URL validation regex

The updated regex pattern for URL validation is more comprehensive and aligns well with the PR objectives. It now correctly handles optional protocols, various domain structures, and optional paths and query parameters.

Consider the following minor improvements:

  1. Pre-compile the regex pattern for better performance, especially if this function is called frequently:
const URL_PATTERN = /^(https?:\/\/)?([\da-z.-]+)\.([a-z]{2,6})(\/[\w.-]*)*\/?(\?[=&\w.-]*)?$/i;

export const checkURLValidity = (url: string): boolean => {
  if (!url) return false;
  return URL_PATTERN.test(url);
};
  1. Add examples to the JSDoc comment to illustrate valid and invalid URLs:
/**
 * @description
 * This function tests whether a URL is valid or not.
 * It accepts URLs with or without the protocol.
 * @param {string} url
 * @returns {boolean}
 * @example
 * checkURLValidity("https://example.com") => true
 * checkURLValidity("example.com") => true
 * checkURLValidity("example") => false
 * checkURLValidity("https://example.com/path?query=param") => true
 */

These changes will improve performance and provide better documentation for future developers.

apiserver/plane/app/views/project/base.py (8)

416-416: Consider expanding permission checks

The @allow_permission([ROLE.ADMIN]) decorator restricts this method to admin users only. Consider if project owners or other roles should also have partial update capabilities.

You might want to implement a more granular permission system that allows certain updates based on user roles and the specific fields being updated.


Line range hint 417-428: Improve error handling for non-existent projects

The error handling for non-existent projects is combined with workspace not found errors. Consider separating these for more precise error reporting.

Consider refactoring the error handling as follows:

try:
    workspace = Workspace.objects.get(slug=slug)
except Workspace.DoesNotExist:
    return Response(
        {"error": "Workspace does not exist"},
        status=status.HTTP_404_NOT_FOUND,
    )

try:
    project = Project.objects.get(pk=pk)
except Project.DoesNotExist:
    return Response(
        {"error": "Project does not exist"},
        status=status.HTTP_404_NOT_FOUND,
    )

Line range hint 429-443: Consider moving serializer logic to a separate method

The serializer validation and saving logic could be moved to a separate method for better readability and reusability.

Consider creating a helper method like _update_project to handle serializer logic:

def _update_project(self, project, data, workspace_id):
    serializer = ProjectSerializer(
        project,
        data=data,
        context={"workspace_id": workspace_id},
        partial=True,
    )
    if serializer.is_valid():
        serializer.save()
        return serializer
    return None

Line range hint 444-461: Ensure atomicity for inbox and triage state creation

The creation of the inbox and triage state is not atomic. If one operation fails, it could leave the system in an inconsistent state.

Consider wrapping these operations in a transaction to ensure atomicity:

from django.db import transaction

# ...

with transaction.atomic():
    if serializer.data["inbox_view"]:
        inbox = Inbox.objects.filter(
            project=project,
            is_default=True,
        ).first()
        if not inbox:
            Inbox.objects.create(
                name=f"{project.name} Inbox",
                project=project,
                is_default=True,
            )

        State.objects.get_or_create(
            name="Triage",
            group="triage",
            description="Default state for managing all Inbox Issues",
            project_id=pk,
            color="#ff7700",
            is_triage=True,
        )

Line range hint 462-475: Consider optimizing database queries

The method performs multiple database queries that could potentially be optimized.

Consider using select_related or prefetch_related to reduce the number of database queries:

project = (
    self.get_queryset()
    .select_related('workspace')
    .filter(pk=serializer.data["id"])
    .first()
)

Line range hint 476-486: Ensure proper error handling for model_activity task

The model_activity.delay() call is not wrapped in a try-except block. If this task fails, it could potentially cause the entire update operation to fail silently.

Consider adding error handling for the model_activity task:

try:
    model_activity.delay(
        model_name="project",
        model_id=str(project.id),
        requested_data=request.data,
        current_instance=current_instance,
        actor_id=request.user.id,
        slug=slug,
        origin=request.META.get("HTTP_ORIGIN"),
    )
except Exception as e:
    # Log the error, but don't fail the update operation
    logger.error(f"Failed to log model activity: {str(e)}")

Line range hint 487-506: Improve error handling and response messages

The error handling for IntegrityError and ValidationError could be improved to provide more specific error messages.

Consider refactoring the error handling as follows:

except IntegrityError as e:
    if "already exists" in str(e):
        return Response(
            {"error": "The project name is already taken"},
            status=status.HTTP_409_CONFLICT,
        )
    return Response(
        {"error": "An integrity error occurred"},
        status=status.HTTP_400_BAD_REQUEST,
    )
except serializers.ValidationError as e:
    return Response(
        {"error": "Validation error", "details": e.detail},
        status=status.HTTP_400_BAD_REQUEST,
    )

Line range hint 416-506: Overall assessment of the partial_update method

The partial_update method in the ProjectViewSet class is well-structured and covers important aspects of project updates. However, there are several areas for improvement:

  1. Permission checks could be more granular.
  2. Error handling can be more specific and informative.
  3. Database queries could be optimized to reduce the number of calls.
  4. The creation of inbox and triage states should be atomic.
  5. Error handling for the model_activity task should be added.

Addressing these points will improve the robustness and efficiency of the method.

Consider refactoring this method into smaller, more focused methods to improve readability and maintainability. Also, consider adding unit tests to cover various scenarios, especially around error handling and permission checks.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 323c414 and 25bd32c.

📒 Files selected for processing (2)
  • apiserver/plane/app/views/project/base.py (1 hunks)
  • web/helpers/string.helper.ts (1 hunks)
🧰 Additional context used

@sriramveeraghanta sriramveeraghanta deleted the fix/add-existing-issue-to-cycle-toast branch February 10, 2026 13:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐛bug Something isn't working 🌐frontend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants