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

Bugfix: fixed duplication of chats #3360

Merged

Conversation

Aad1tya27
Copy link
Contributor

@Aad1tya27 Aad1tya27 commented Jan 20, 2025

Fixes a Bug in the Chat section.

Issue Number:

Fixes #3301

Snapshots/Videos:
image

If relevant, did you update the documentation?
No

Does this PR introduce a breaking change?
No

Checklist

CodeRabbit AI Review

  • I have reviewed and addressed all critical issues flagged by CodeRabbit AI
  • I have implemented or provided justification for each non-critical suggestion
  • I have documented my reasoning in the PR comments where CodeRabbit AI suggestions were not implemented

Test Coverage

  • I have written tests for all new changes/features
  • I have verified that test coverage meets or exceeds 95%
  • I have run the test suite locally and all tests pass

Other information

Have you read the contributing guide?
Yes

Summary by CodeRabbit

  • Documentation

    • Added documentation for several mock variables related to Organization Tags.
    • Created documentation for Chat type alias.
    • Updated documentation for the CreateDirectChat component and related files.
    • Documented the handleCreateDirectChat function.
  • New Features

    • Enhanced chat creation logic to prevent duplicate chats.
    • Added check for existing chats before creating a new direct chat.
  • Refactor

    • Exported Chat type to make it accessible across the application.
    • Updated CreateDirectChat component to include chat list validation.

Copy link
Contributor

coderabbitai bot commented Jan 20, 2025

Walkthrough

This pull request introduces several documentation updates and code modifications related to the Chat feature, primarily focusing on preventing duplicate chat creation. The changes include updating documentation for various mock variables, introducing a new Chat type, and modifying the CreateDirectChat component to check for existing chats before creating a new one. The primary goal is to address the issue of creating multiple chat rooms with the same user.

Changes

File Change Summary
docs/docs/auto-docs/components/UserPortal/CreateDirectChat/... Updated function definition line number
docs/docs/auto-docs/screens/OrganizationTags/OrganizationTagsMocks/variables/ Added new documentation files for mock variables: MOCKS_EMPTY, MOCKS_ERROR, MOCKS_ERROR_ERROR_TAG, MOCKS_NO_MORE_PAGES, MOCKS_NULL_END_CURSOR, MOCKS_UNDEFINED_USER_TAGS
docs/docs/auto-docs/screens/UserPortal/Chat/Chat/type-aliases/Chat.md New documentation for Chat type alias
src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx Added chats prop to interface, imported Chat type, updated chat creation logic to prevent duplicates
src/screens/UserPortal/Chat/Chat.tsx Changed Chat type to exported type, added chats prop to CreateDirectChat component

Assessment against linked issues

Objective Addressed Explanation
Prevent creating duplicate chat rooms
Check for existing chat before creating new one

Possibly related PRs

Suggested labels

ignore-sensitive-files-pr

Suggested reviewers

  • palisadoes
  • disha1202

Poem

🐰 In the realm of chats, a rabbit's delight,
No duplicates shall see the light!
With logic sharp and wisdom keen,
One chat per user, clean and serene.
Hop, hop, hooray for code so bright! 🎉


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 621782c and 85d44e4.

📒 Files selected for processing (4)
  • docs/docs/auto-docs/components/UserPortal/CreateDirectChat/CreateDirectChat/functions/default.md (1 hunks)
  • docs/docs/auto-docs/components/UserPortal/CreateDirectChat/CreateDirectChat/functions/handleCreateDirectChat.md (1 hunks)
  • src/components/UserPortal/CreateDirectChat/CreateDirectChat.spec.tsx (5 hunks)
  • src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx (5 hunks)
✅ Files skipped from review due to trivial changes (1)
  • docs/docs/auto-docs/components/UserPortal/CreateDirectChat/CreateDirectChat/functions/handleCreateDirectChat.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/docs/auto-docs/components/UserPortal/CreateDirectChat/CreateDirectChat/functions/default.md
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test Application
  • GitHub Check: Analyse Code With CodeQL (javascript)
🔇 Additional comments (6)
src/components/UserPortal/CreateDirectChat/CreateDirectChat.spec.tsx (2)

16-17: LGTM! Clean import organization.

The imports are well-organized, separating type imports from component imports.

Also applies to: 31-32


4041-4196: Well-structured test coverage for chat creation scenarios!

The test suite comprehensively covers three key scenarios:

  1. Creating a new chat when no conversation exists
  2. Preventing duplicate chat creation
  3. Handling errors during chat creation

The test cases are well-organized and use clear mock implementations.

src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx (4)

4-11: LGTM! Well-organized type imports.

The type imports are properly organized and include all necessary types for Apollo operations and i18next translations.

Also applies to: 28-30


41-41: LGTM! Props interface update.

The InterfaceCreateDirectChatProps interface is correctly updated to include the chats prop.


70-134: Robust implementation of chat creation with proper error handling!

The handleCreateDirectChat function implementation:

  1. Efficiently checks for existing chats using find() and some()
  2. Provides user-friendly error messages
  3. Implements proper error handling with try-catch
  4. Follows proper TypeScript typing

257-266: LGTM! Updated function call with all required parameters.

The handleCreateDirectChat function is called with all necessary parameters in the correct order.


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

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 comments (1)
src/screens/UserPortal/Chat/Chat.tsx (1)

Missing test coverage for duplicate chat detection confirmed

The implementation includes proper duplicate chat detection and error handling, but there are no tests covering these scenarios. The original review comment is correct - test coverage is needed for:

  1. Attempting to create a duplicate chat
  2. Successfully creating a new chat
  3. Error handling when a duplicate is detected
🔗 Analysis chain

Line range hint 79-100: Add test coverage for duplicate chat detection.

Please add test cases to cover:

  1. Attempting to create a duplicate chat
  2. Successfully creating a new chat
  3. Error handling when a duplicate is detected

This will address the pipeline failure regarding code coverage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check current test coverage for CreateDirectChat
rg -A 5 "test.*CreateDirectChat" "src/**/*test*"

Length of output: 104


Script:

#!/bin/bash
# Find all test files
echo "=== Test files ==="
fd -e test.tsx -e test.ts -e spec.tsx -e spec.ts

# Find CreateDirectChat implementation
echo -e "\n=== CreateDirectChat implementation ==="
rg -g "*.{ts,tsx}" "CreateDirectChat"

# Search for chat-related test files
echo -e "\n=== Chat-related test files ==="
fd -e test.tsx -e test.ts -e spec.tsx -e spec.ts chat

Length of output: 14147


Script:

#!/bin/bash
# Check test content for duplicate chat scenarios
echo "=== CreateDirectChat test content ==="
cat src/components/UserPortal/CreateDirectChat/CreateDirectChat.spec.tsx

# Check implementation for error handling
echo -e "\n=== CreateDirectChat implementation details ==="
cat src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx

Length of output: 65857


Script:

#!/bin/bash
# Search for error handling in CreateDirectChat implementation
echo "=== CreateDirectChat error handling ==="
rg -A 5 -B 5 "catch|error|duplicate" "src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx"

# Get the handleCreateDirectChat function implementation
echo -e "\n=== handleCreateDirectChat implementation ==="
ast-grep --pattern 'handleCreateDirectChat = async ($$$) => { $$$ }' "src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx"

Length of output: 1204


Script:

#!/bin/bash
# Search for duplicate chat test cases
echo "=== Test cases for duplicate chat ==="
rg -B 10 -A 10 "duplicate|already exists|chatExists" "src/components/UserPortal/CreateDirectChat/CreateDirectChat.spec.tsx"

# Search for error handler test cases
echo -e "\n=== Error handler test cases ==="
rg -B 5 -A 5 "error|expect.*fail|expect.*throw" "src/components/UserPortal/CreateDirectChat/CreateDirectChat.spec.tsx"

Length of output: 408

🧹 Nitpick comments (1)
src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx (1)

80-84: Optimize the chat existence check using Array.some().

The current implementation using forEach can be simplified for better readability and efficiency.

-    let chatExists = false;
-    chats.forEach((chat) => {
-      if (chat.users[0]._id === id || chat.users[1]._id === id)
-        chatExists = true;
-    });
+    const chatExists = chats.some(
+      (chat) => chat.users[0]._id === id || chat.users[1]._id === id
+    );
🧰 Tools
🪛 GitHub Actions: PR Workflow

[error] Contains code coverage disable statement. Please remove it and add the appropriate tests.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 158414f and 67d099b.

📒 Files selected for processing (10)
  • docs/docs/auto-docs/components/UserPortal/CreateDirectChat/CreateDirectChat/functions/default.md (1 hunks)
  • docs/docs/auto-docs/screens/OrganizationTags/OrganizationTagsMocks/variables/MOCKS_EMPTY.md (1 hunks)
  • docs/docs/auto-docs/screens/OrganizationTags/OrganizationTagsMocks/variables/MOCKS_ERROR.md (2 hunks)
  • docs/docs/auto-docs/screens/OrganizationTags/OrganizationTagsMocks/variables/MOCKS_ERROR_ERROR_TAG.md (1 hunks)
  • docs/docs/auto-docs/screens/OrganizationTags/OrganizationTagsMocks/variables/MOCKS_NO_MORE_PAGES.md (1 hunks)
  • docs/docs/auto-docs/screens/OrganizationTags/OrganizationTagsMocks/variables/MOCKS_NULL_END_CURSOR.md (1 hunks)
  • docs/docs/auto-docs/screens/OrganizationTags/OrganizationTagsMocks/variables/MOCKS_UNDEFINED_USER_TAGS.md (1 hunks)
  • docs/docs/auto-docs/screens/UserPortal/Chat/Chat/type-aliases/Chat.md (1 hunks)
  • src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx (4 hunks)
  • src/screens/UserPortal/Chat/Chat.tsx (2 hunks)
✅ Files skipped from review due to trivial changes (6)
  • docs/docs/auto-docs/components/UserPortal/CreateDirectChat/CreateDirectChat/functions/default.md
  • docs/docs/auto-docs/screens/OrganizationTags/OrganizationTagsMocks/variables/MOCKS_NULL_END_CURSOR.md
  • docs/docs/auto-docs/screens/UserPortal/Chat/Chat/type-aliases/Chat.md
  • docs/docs/auto-docs/screens/OrganizationTags/OrganizationTagsMocks/variables/MOCKS_EMPTY.md
  • docs/docs/auto-docs/screens/OrganizationTags/OrganizationTagsMocks/variables/MOCKS_UNDEFINED_USER_TAGS.md
  • docs/docs/auto-docs/screens/OrganizationTags/OrganizationTagsMocks/variables/MOCKS_ERROR_ERROR_TAG.md
🧰 Additional context used
📓 Learnings (2)
docs/docs/auto-docs/screens/OrganizationTags/OrganizationTagsMocks/variables/MOCKS_ERROR.md (2)
Learnt from: arpit-chakraborty
PR: PalisadoesFoundation/talawa-admin#3158
File: src/screens/OrganizationTags/OrganizationTagsMocks.ts:384-524
Timestamp: 2025-01-15T05:39:30.480Z
Learning: In OrganizationTagsMocks.ts, MOCKS_NULL_END_CURSOR and MOCKS_NO_MORE_PAGES are designed to test UI handling of edge cases where pagination data is inconsistent (e.g., hasNextPage is true but endCursor is null, or next page returns undefined data).
Learnt from: meetulr
PR: PalisadoesFoundation/talawa-admin#2355
File: src/screens/ManageTag/ManageTagMocks.ts:187-269
Timestamp: 2024-11-12T10:40:58.654Z
Learning: In `src/screens/ManageTag/ManageTagMocks.ts`, when mocking data for `USER_TAGS_ASSIGNED_MEMBERS` and `USER_TAGS_MEMBERS_TO_ASSIGN_TO`, it's acceptable for user IDs to overlap because the queries serve different purposes and the overlapping IDs can represent realistic scenarios in tests.
docs/docs/auto-docs/screens/OrganizationTags/OrganizationTagsMocks/variables/MOCKS_NO_MORE_PAGES.md (1)
Learnt from: arpit-chakraborty
PR: PalisadoesFoundation/talawa-admin#3158
File: src/screens/OrganizationTags/OrganizationTagsMocks.ts:384-524
Timestamp: 2025-01-15T05:39:30.480Z
Learning: In OrganizationTagsMocks.ts, MOCKS_NULL_END_CURSOR and MOCKS_NO_MORE_PAGES are designed to test UI handling of edge cases where pagination data is inconsistent (e.g., hasNextPage is true but endCursor is null, or next page returns undefined data).
🪛 GitHub Actions: PR Workflow
src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx

[error] Contains code coverage disable statement. Please remove it and add the appropriate tests.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyse Code With CodeQL (javascript)
🔇 Additional comments (7)
docs/docs/auto-docs/screens/OrganizationTags/OrganizationTagsMocks/variables/MOCKS_NO_MORE_PAGES.md (1)

1-9: LGTM! Documentation is well-structured and comprehensive.

The documentation for MOCKS_NO_MORE_PAGES is clear and follows the standard format. The type definitions accurately represent the complex structure needed for testing pagination edge cases.

docs/docs/auto-docs/screens/OrganizationTags/OrganizationTagsMocks/variables/MOCKS_ERROR.md (1)

9-9: LGTM! Documentation updates are accurate.

The changes to the line number reference and the ID value from 'orgId' to 'orgIdError' are well documented. The distinction in ID values helps better identify error test cases.

Also applies to: 35-35

src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx (3)

21-22: LGTM! Necessary imports added.

The new imports support the chat duplication check functionality.

🧰 Tools
🪛 GitHub Actions: PR Workflow

[error] Contains code coverage disable statement. Please remove it and add the appropriate tests.


33-33: LGTM! Interface updated with chats property.

The addition of chats: Chat[] enables duplicate chat detection.

🧰 Tools
🪛 GitHub Actions: PR Workflow

[error] Contains code coverage disable statement. Please remove it and add the appropriate tests.


86-89: LGTM! Well-implemented error handling.

The error handling:

  • Uses the project's error handling utility
  • Supports internationalization
  • Provides clear user feedback
🧰 Tools
🪛 GitHub Actions: PR Workflow

[error] Contains code coverage disable statement. Please remove it and add the appropriate tests.

src/screens/UserPortal/Chat/Chat.tsx (2)

Line range hint 87-101: LGTM! Chat type properly exported.

The Chat type export enables proper type checking for duplicate chat detection.


335-335: LGTM! Chats prop correctly passed to CreateDirectChat.

The implementation properly passes the current chats state for duplicate detection.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 20, 2025
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: 2

🧹 Nitpick comments (1)
src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx (1)

Line range hint 137-207: Consider UX improvements for search and feedback.

The component implementation is solid, but could benefit from these UX enhancements:

  1. Add debouncing to the search to prevent excessive API calls
  2. Show loading state during chat creation
  3. Use a toast notification for errors instead of the error handler

Would you like me to provide the implementation for these improvements?

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 67d099b and 1a56523.

📒 Files selected for processing (1)
  • src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test Application
  • GitHub Check: Analyse Code With CodeQL (javascript)
🔇 Additional comments (1)
src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx (1)

21-22: LGTM! Well-structured type imports and interface updates.

The new imports and interface changes are well-organized and properly typed, supporting the duplicate chat prevention feature.

Also applies to: 33-33

Copy link

codecov bot commented Jan 20, 2025

Codecov Report

Attention: Patch coverage is 92.30769% with 1 line in your changes missing coverage. Please review.

Project coverage is 89.78%. Comparing base (158414f) to head (85d44e4).
Report is 12 commits behind head on develop-postgres.

Files with missing lines Patch % Lines
...s/UserPortal/CreateDirectChat/CreateDirectChat.tsx 92.30% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@                  Coverage Diff                  @@
##           develop-postgres    #3360       +/-   ##
=====================================================
+ Coverage              8.40%   89.78%   +81.37%     
=====================================================
  Files                   312      335       +23     
  Lines                  8105     8621      +516     
  Branches               1801     1922      +121     
=====================================================
+ Hits                    681     7740     +7059     
+ Misses                 7347      624     -6723     
- Partials                 77      257      +180     
Flag Coverage Δ
combined 89.78% <92.30%> (?)
jest 7.94% <0.00%> (?)
vitest 89.78% <92.30%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 20, 2025
@Aad1tya27
Copy link
Contributor Author

@palisadoes CodeRabbit approved my changes but the check failed. I think the PR can be merged.

Copy link
Contributor

@palisadoes palisadoes left a comment

Choose a reason for hiding this comment

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

Please make the code coverage of the file you edited get to 100%. We cannot afford to have this error be repeated.

image

@palisadoes palisadoes merged commit 5434bfc into PalisadoesFoundation:develop-postgres Jan 21, 2025
19 checks passed
yugal07 pushed a commit to yugal07/talawa-admin that referenced this pull request Jan 24, 2025
* fixed duplication of chats

* removed istanbul ignore text

* added error handling

* added tests for createdirectchat.tsx
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.

2 participants