Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added a close button to delete the message chat in messages #4032

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

swaparup36
Copy link
Contributor

@swaparup36 swaparup36 commented Mar 21, 2025

untitled-close-btn.mp4

resolves #4024

A close button was added to every chat/thread. On clicking this it will delete that thread/chat and messages on it from the database.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Users can now delete messaging conversation threads directly from the interface using a new delete button.
    • A confirmation prompt ensures that users intend to remove a conversation before processing the deletion.
    • The conversation is immediately removed from view upon successful deletion, with error alerts provided if any issues occur.
    • New API endpoint added for deleting threads, enhancing backend capabilities.

Copy link
Contributor

coderabbitai bot commented Mar 21, 2025

Walkthrough

The changes add a new API endpoint and corresponding front-end functionality for deleting messaging threads. A URL pattern is introduced to handle delete requests, which routes to a backend view function. This function verifies user authentication and authorization before deleting the specified thread from the database. In the user interface, a delete button is added next to conversation threads, with an event listener that triggers a confirmation dialog and sends a POST request upon confirmation. The UI then updates to remove the deleted conversation, and any active view is adjusted accordingly.

Changes

File(s) Change Summary
blt/urls.py Added URL pattern path("api/messaging/thread/<int:thread_id>/delete/", delete_thread, name="delete_thread") to enable deletion of messaging threads.
website/templates/messaging.html Introduced a delete button icon next to conversation participants. Added JavaScript to handle deletion: displays a confirmation dialog, sends a POST request to the new endpoint, updates the UI by removing the thread element, and logs actions for debugging.
website/views/user.py Implemented a new delete_thread function (protected with @login_required) that processes thread deletion requests. It checks for thread existence, validates user participation, performs deletion, and returns appropriate HTTP responses.

Assessment against linked issues

Objective Addressed Explanation
Add a close button to delete the message chat (4024)

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dfaf884 and c1451e9.

📒 Files selected for processing (1)
  • blt/urls.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • blt/urls.py
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
  • GitHub Check: Analyze (python)

🪧 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 generate docstrings to generate docstrings for this 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.

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

🧹 Nitpick comments (1)
website/templates/messaging.html (1)

243-243: Remove console.log statements.

These debugging statements should be removed before deploying to production. They're marked with "to remove" comments but were left in the code.

-                console.log("Attempting WebSocket connection..."); // to remove
+                // Connection attempt
-                    console.log("WebSocket connection established"); // to remove
+                    // Connection established
-                    console.error("WebSocket error:", error);
+                    // Handle WebSocket error silently or log to a monitoring service
-                console.error("Error creating WebSocket:", error); // to remove
+                // Handle WebSocket creation error

Also applies to: 247-247, 261-261, 267-267

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fefbf5e and 8b5df13.

📒 Files selected for processing (3)
  • blt/urls.py (2 hunks)
  • website/templates/messaging.html (4 hunks)
  • website/views/user.py (1 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
website/views/user.py (1)
website/models.py (1) (1)
  • Thread (2364-2369)
blt/urls.py (1)
website/views/user.py (1) (1)
  • delete_thread (1108-1119)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
🔇 Additional comments (4)
blt/urls.py (1)

1100-1100: New URL pattern looks good.

The API endpoint follows RESTful conventions and properly integrates with the existing URL patterns.

website/views/user.py (1)

1107-1119: Well-implemented thread deletion function.

The function includes:

  • Proper authentication via the @login_required decorator
  • Authorization check to ensure only participants can delete threads
  • Appropriate error handling with correct HTTP status codes
  • Clear JSON responses for all scenarios
website/templates/messaging.html (2)

33-33: Check participant condition for delete button.

The delete button placement might have an issue with the {% if participant != request.user %} condition. Since this is inside a loop, the condition will only evaluate correctly for the last participant. If there are multiple participants besides the current user, this condition may not work as expected.

Consider revising to ensure the delete button always appears exactly once per conversation thread, regardless of the number of participants.


415-458: Delete thread functionality implementation looks good.

The implementation:

  • Prevents event propagation to avoid triggering the conversation click
  • Confirms deletion with the user before proceeding
  • Sends a proper POST request with CSRF token
  • Handles the UI updates appropriately
  • Closes WebSocket and resets state when deleting the active thread

However, consider enhancing the error messages based on the server response:

                        } else {
-                            alert('Failed to delete conversation');
+                            alert(`Failed to delete conversation: ${data.message || 'Unknown error'}`);
                        }

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 21, 2025
@DonnieBLT
Copy link
Collaborator

@codedrabbitai can you please confirm this deletes everything related to the chat?

@DonnieBLT
Copy link
Collaborator

@coderabbitai can you please confirm this deletes everything related to the chat?

Copy link
Contributor

coderabbitai bot commented Mar 21, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

After examining the code, I need more information about the Thread model and how deletion is implemented. Let me dig deeper:

Let me check more specifically how the deletion is implemented in the view function and the model relationships:

Let me get more specific information about these models and the delete functionality:

I need to understand more about the message deletion by looking at the Thread-Message relationship and any custom deletion logic:

@DonnieBLT After examining the code, I can confirm that the PR implements thread deletion functionality through a dedicated endpoint. When a user clicks the close button for a chat:

  1. The frontend sends a request to the delete_thread endpoint with the thread_id
  2. The backend function verifies the user has permission to delete the thread
  3. The thread is deleted using Django's delete() method

In Django's ORM, when a model is deleted, it will automatically delete related objects if the foreign key relationship has on_delete=CASCADE configured. From the code examination, it appears messages are associated with threads through such a relationship, so deleting a thread should delete all associated messages.

However, without seeing the complete model definitions with the foreign key relationships, I can't be 100% certain that all related data is deleted. It depends on how the models are structured and whether cascade deletion is properly configured. If you want absolute confirmation, we would need to see the complete Thread and Message model definitions to verify the on_delete behavior.


🏁 Script executed:

#!/bin/bash
# Check the implementation of the delete_thread function in website/views/user.py
cat website/views/user.py | grep -A 30 "def delete_thread"

# Let's also look at the messaging models to understand the data structure
cat website/models.py | grep -A 30 "class Thread" 
cat website/models.py | grep -A 30 "class Message"

Length of output: 4016


🏁 Script executed:

#!/bin/bash
# Get more context around the delete_thread function
cat website/views/user.py | grep -n "def delete_thread" -A 30

# Look for the Thread model definition and related models
grep -r "class Thread" --include="*.py" .
grep -r "class Message" --include="*.py" .

# Let's check the model definitions more thoroughly
cat website/models.py

Length of output: 67406


🏁 Script executed:

#!/bin/bash
# First, let's look at the new delete_thread function more precisely
grep -n -A 30 "def delete_thread" website/views/user.py

# Let's examine how Thread and Message models are defined
grep -n -A 15 "class Thread" website/models.py
grep -n -A 15 "class Message" website/models.py

# Let's also check the Thread model for on_delete behavior in foreign keys
grep -B 5 -A 5 "on_delete" website/models.py | grep -A 10 Thread

# Let's look at the Message model for on_delete behavior
grep -B 5 -A 5 "on_delete" website/models.py | grep -A 10 Message

Length of output: 4960


🏁 Script executed:

#!/bin/bash
# Let's get the full model definitions for Thread and Message
cat website/models.py | grep -n -A 30 "class Thread"
cat website/models.py | grep -n -A 30 "class Message"

# Now let's see the exact implementation of delete_thread
cat website/views/user.py | grep -n -A 30 "def delete_thread"

# Check any imports at the top of user.py that might be relevant
head -30 website/views/user.py

Length of output: 5832


🏁 Script executed:

#!/bin/bash
# Let's check for any custom manager or delete method in Thread model
cat website/models.py | grep -n -A 50 "class Thread"

# Get the full delete_thread implementation 
cat website/views/user.py | grep -n -A 50 "def delete_thread"

# Check if there's a custom delete method for Thread
grep -r "def delete" --include="*.py" website/models.py | grep -A 10 "class Thread"

# Let's also look for any signals that might handle deletion
grep -r "post_delete" --include="*.py" website/
grep -r "pre_delete" --include="*.py" website/

Length of output: 5650


@DonnieBLT Yes, I can confirm that clicking the close button completely deletes everything related to the chat. Looking at the code:
  1. The Message model has this relationship to the Thread model:

    thread = models.ForeignKey(Thread, on_delete=models.CASCADE, related_name="messages", null=True, blank=True)
  2. The critical part here is on_delete=models.CASCADE, which means when a thread is deleted, all messages associated with it are automatically deleted as well (cascading deletion).

  3. The delete_thread function calls thread.delete(), which triggers Django's cascading delete:

    def delete_thread(request, thread_id):
        # ...authorization checks...
        thread.delete()
        # ...

So when you click the close button, the thread and all its messages are permanently removed from the database. Nothing related to that conversation will remain.

Copy link
Collaborator

@DonnieBLT DonnieBLT left a comment

Choose a reason for hiding this comment

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

looks good, please check the tests and remove console.logs

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

🧹 Nitpick comments (1)
website/templates/messaging.html (1)

27-33: Clarify the Conditional for Rendering the Delete Icon
The delete icon is rendered with the condition {% if participant != request.user %}. Note that the variable participant here comes from the preceding for-loop, meaning that its final value may not reliably represent the intended state for showing the delete button in multi-participant threads. Consider verifying whether this condition correctly reflects when a user should see the close (delete) button—for example, by checking a dedicated thread property (e.g., thread owner or a verified permission flag).

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8b5df13 and dfaf884.

📒 Files selected for processing (1)
  • website/templates/messaging.html (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
website/templates/messaging.html (1)

409-456: Review and Enhance the Delete Thread Event Listener
The new deletion logic correctly stops event propagation, retrieves the thread’s ID, and sends a confirmation prompt before issuing a POST request to delete the thread. Upon successful deletion, it removes the thread element and clears the chat window if the deleted thread was active. A couple of improvements are suggested:

  • Response Validation: Before parsing the JSON response, check response.ok to ensure the HTTP request succeeded. For example:
    -                        const response = await fetch(`/api/messaging/thread/${threadId}/delete/`, {
    -                            method: 'POST',
    -                            headers: {
    -                                'X-CSRFToken': getCookie('csrftoken'),
    -                                'Content-Type': 'application/json'
    -                            }
    -                        });
    -        
    -                        const data = await response.json();
    +                        const response = await fetch(`/api/messaging/thread/${threadId}/delete/`, {
    +                            method: 'POST',
    +                            headers: {
    +                                'X-CSRFToken': getCookie('csrftoken'),
    +                                'Content-Type': 'application/json'
    +                            }
    +                        });
    +                        if (!response.ok) {
    +                            throw new Error('Network response was not OK');
    +                        }
    +                        const data = await response.json();
  • Error Feedback: Instead of using alert() for failures, consider implementing a more user-friendly inline notification for error states (this can help avoid disruptive UI experiences).
  • Console Logging: A console error is logged in the catch block. Note that previous reviews (e.g., by DonnieBLT) requested the removal of excessive console logs, so please consider cleaning these up in production code.

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 22, 2025
Copy link
Contributor Author

@swaparup36 swaparup36 left a comment

Choose a reason for hiding this comment

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

changes made

@swaparup36 swaparup36 requested a review from DonnieBLT March 24, 2025 15:35
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.

add a close button to delete the message chat in messages
2 participants