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

Communication: Prevent multiple group chats with same users #10138

Merged

Conversation

asliayk
Copy link
Contributor

@asliayk asliayk commented Jan 13, 2025

Checklist

General

Server

  • Important: I implemented the changes with a very good performance and prevented too many (unnecessary) and too complex database calls.
  • I strictly followed the principle of data economy for all database calls.
  • I strictly followed the server coding and design guidelines.
  • I documented the Java code using JavaDoc style.

Motivation and Context

Currently, it is possible to create multiple group chats with the same set of participants, leading to redundancy and confusion. (Closes #9985)

Description

Validation was added to ensure group chats are unique based on their participants. Existing chats with the same users are now reused instead of creating duplicates, aligning with one-to-one chat behavior.

Steps for Testing

Prerequisites:

  • 1 User
  • 1 Course with Communication enabled
  1. Log in to Artemis.
  2. Navigate to the Communication section of a course.
  3. Click the "Create Group Chat" button, which appears after clicking the plus button.
  4. Create a group chat with a random set of users.
  5. Attempt to create another group chat with the exact same set of users.
  6. Observe that it navigates to the pre-existing group chat instead of creating a duplicate.

Testserver States

Note

These badges show the state of the test servers.
Green = Currently available, Red = Currently locked
Click on the badges to get to the test servers.







Review Progress

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Test Coverage

Server

Class/File Line Coverage Confirmation (assert/expect)
GroupChatService.java 87%

Summary by CodeRabbit

  • New Features

    • Enhanced group chat functionality to prevent duplicate chats
    • Added ability to retrieve group chats with exact participants
  • Tests

    • Added integration test to verify group chat creation behavior
  • Bug Fixes

    • Improved group chat creation logic to handle existing chats more efficiently

@asliayk asliayk self-assigned this Jan 13, 2025
@github-actions github-actions bot added tests server Pull requests that update Java code. (Added Automatically!) communication Pull requests that affect the corresponding module labels Jan 13, 2025
@asliayk asliayk temporarily deployed to artemis-test5.artemis.cit.tum.de January 14, 2025 01:57 — with GitHub Actions Inactive
@asliayk asliayk marked this pull request as ready for review January 14, 2025 02:04
@asliayk asliayk requested a review from a team as a code owner January 14, 2025 02:04
@asliayk asliayk added the bugfix label Jan 14, 2025
Copy link

coderabbitai bot commented Jan 14, 2025

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 pmd (7.8.0)
src/main/java/de/tum/cit/aet/artemis/communication/repository/conversation/GroupChatRepository.java

The following rules are missing or misspelled in your ruleset file category/vm/bestpractices.xml: BooleanInstantiation, DontImportJavaLang, DuplicateImports, EmptyFinallyBlock, EmptyIfStmt, EmptyInitializer, EmptyStatementBlock, EmptyStatementNotInLoop, EmptySwitchStatements, EmptySynchronizedBlock, EmptyTryBlock, EmptyWhileStmt, ExcessiveClassLength, ExcessiveMethodLength, ImportFromSamePackage, MissingBreakInSwitch, SimplifyBooleanAssertion. Please check your ruleset configuration.

src/main/java/de/tum/cit/aet/artemis/communication/service/conversation/GroupChatService.java

The following rules are missing or misspelled in your ruleset file category/vm/bestpractices.xml: BooleanInstantiation, DontImportJavaLang, DuplicateImports, EmptyFinallyBlock, EmptyIfStmt, EmptyInitializer, EmptyStatementBlock, EmptyStatementNotInLoop, EmptySwitchStatements, EmptySynchronizedBlock, EmptyTryBlock, EmptyWhileStmt, ExcessiveClassLength, ExcessiveMethodLength, ImportFromSamePackage, MissingBreakInSwitch, SimplifyBooleanAssertion. Please check your ruleset configuration.

src/test/java/de/tum/cit/aet/artemis/communication/GroupChatIntegrationTest.java

The following rules are missing or misspelled in your ruleset file category/vm/bestpractices.xml: BooleanInstantiation, DontImportJavaLang, DuplicateImports, EmptyFinallyBlock, EmptyIfStmt, EmptyInitializer, EmptyStatementBlock, EmptyStatementNotInLoop, EmptySwitchStatements, EmptySynchronizedBlock, EmptyTryBlock, EmptyWhileStmt, ExcessiveClassLength, ExcessiveMethodLength, ImportFromSamePackage, MissingBreakInSwitch, SimplifyBooleanAssertion. Please check your ruleset configuration.

Walkthrough

This pull request addresses the issue of duplicate group chat creation by introducing a new method in the GroupChatRepository to find group chats with exact participants. The GroupChatService has been updated to check for existing group chats before creating a new one. A corresponding integration test has been added to verify the new behavior, ensuring that when a group chat is created with the same participants, the existing chat is returned instead of creating a duplicate.

Changes

File Change Summary
.../GroupChatRepository.java Added findGroupChatWithExactParticipants() method to query group chats with specific participants
.../GroupChatService.java Modified startGroupChat() to check for existing group chats and handle creator reassignment
.../GroupChatIntegrationTest.java Added test method to verify existing group chat retrieval

Assessment against linked issues

Objective Addressed Explanation
Prevent duplicate group chats
Return existing group chat when same users are used

Possibly related PRs

Suggested labels

small, bugfix, component:Communication

Suggested reviewers

  • sachmii
  • HawKhiem
  • cremertim
  • krusche
  • eceeeren

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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 or @coderabbitai title 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

@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: 1

🧹 Nitpick comments (2)
src/main/java/de/tum/cit/aet/artemis/communication/repository/conversation/GroupChatRepository.java (1)

61-74: Consider optimizing the query performance.

The current implementation uses two subqueries which might impact performance for large datasets. Consider this alternative approach using a HAVING clause:

    @Query("""
            SELECT gc
            FROM GroupChat gc
            JOIN gc.conversationParticipants cp
            WHERE gc.course.id = :courseId
            GROUP BY gc
            HAVING COUNT(CASE WHEN cp.user.id IN :participantIds THEN 1 END) = :participantCount
            AND COUNT(cp) = :participantCount
            """)

This version:

  • Reduces the number of subqueries
  • Maintains the same logic but with potentially better performance
  • Uses a single GROUP BY with conditional counting
src/test/java/de/tum/cit/aet/artemis/communication/GroupChatIntegrationTest.java (1)

326-342: Enhance test coverage with additional scenarios.

While the test verifies basic functionality, consider adding these scenarios:

  1. Creator reassignment when chat has no messages
  2. Different participant order (e.g., student3, student2 vs student2, student3)
  3. Edge cases:
    • Maximum participant limit
    • Participants from different courses

Example test for different participant order:

@Test
@WithMockUser(username = TEST_PREFIX + "student1", roles = "USER")
void shouldReturnSameGroupChatWithDifferentParticipantOrder() throws Exception {
    var chat1 = request.postWithResponseBody("/api/courses/" + exampleCourseId + "/group-chats", 
        List.of(testPrefix + "student2", testPrefix + "student3"), GroupChatDTO.class,
        HttpStatus.CREATED);

    var chat2 = request.postWithResponseBody("/api/courses/" + exampleCourseId + "/group-chats", 
        List.of(testPrefix + "student3", testPrefix + "student2"), GroupChatDTO.class,
        HttpStatus.CREATED);

    assertThat(chat1.getId()).isEqualTo(chat2.getId());
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e0cda16 and d7e8724.

📒 Files selected for processing (3)
  • src/main/java/de/tum/cit/aet/artemis/communication/repository/conversation/GroupChatRepository.java (2 hunks)
  • src/main/java/de/tum/cit/aet/artemis/communication/service/conversation/GroupChatService.java (1 hunks)
  • src/test/java/de/tum/cit/aet/artemis/communication/GroupChatIntegrationTest.java (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
src/test/java/de/tum/cit/aet/artemis/communication/GroupChatIntegrationTest.java (1)

Pattern src/test/java/**/*.java: test_naming: descriptive; test_size: small_specific; fixed_data: true; junit5_features: true; assert_use: assertThat; assert_specificity: true; archunit_use: enforce_package_rules; db_query_count_tests: track_performance; util_service_factory_pattern: true; avoid_db_access: true; mock_strategy: static_mocks; context_restart_minimize: true

src/main/java/de/tum/cit/aet/artemis/communication/repository/conversation/GroupChatRepository.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

src/main/java/de/tum/cit/aet/artemis/communication/service/conversation/GroupChatService.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (1)
src/main/java/de/tum/cit/aet/artemis/communication/service/conversation/GroupChatService.java (1)

59-62: Validate creator reassignment logic.

The current implementation allows creator reassignment when the chat has no messages. Consider adding additional validation:

  1. Check if the new creator is a course instructor
  2. Verify the new creator's permissions

Copy link

@ItsaaaMeMario ItsaaaMeMario left a comment

Choose a reason for hiding this comment

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

Tested on TS2, everything works as described. It navigates to the alreaddy existing group chat and does not create a duplicate group.

Copy link

@vinceclifford vinceclifford left a comment

Choose a reason for hiding this comment

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

Tested on TS2, works as expected

@HawKhiem HawKhiem temporarily deployed to artemis-test2.artemis.cit.tum.de January 14, 2025 20:16 — with GitHub Actions Inactive
Copy link
Contributor

@PaRangger PaRangger left a comment

Choose a reason for hiding this comment

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

Tested on TS5. Works as described.

Copy link

@Feras797 Feras797 left a comment

Choose a reason for hiding this comment

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

Tested on TS2, everything works as described. When creating a group chat twice with the same members, it automatically uses the already existing group chat.

Copy link

@sachmii sachmii left a comment

Choose a reason for hiding this comment

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

Tested on TS2, works as expected. Cannot create two group chats with the same users.

Copy link

@SindiBuklaji SindiBuklaji left a comment

Choose a reason for hiding this comment

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

Tested on TS4 and it works as described,

Copy link

@Cathy0123456789 Cathy0123456789 left a comment

Choose a reason for hiding this comment

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

Tested on TS4. Works as expected

@krusche krusche added this to the 7.9.0 milestone Jan 19, 2025
@krusche krusche changed the title Communication: Prevent multiple group chats with same user set Communication: Prevent multiple group chats with same users Jan 19, 2025
@krusche krusche merged commit 8ab4fea into develop Jan 19, 2025
146 of 149 checks passed
@krusche krusche deleted the feature/communication/prevent-group-chat-with-same-users branch January 19, 2025 21:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bugfix communication Pull requests that affect the corresponding module ready to merge server Pull requests that update Java code. (Added Automatically!) tests
Projects
Status: Merged
Development

Successfully merging this pull request may close these issues.

Communication: Duplicate group chat creation with same users
10 participants