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: Fix issue that allows saving same post multiple times #10388

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from

Conversation

PaRangger
Copy link
Contributor

@PaRangger PaRangger commented Feb 22, 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

In certain edge cases, the same post can be saved multiple times, resulting in duplicate entries in the saved posts list. This usually happens when clicking the bookmark button rapidly multiple times. Additionally, marking any of these duplicates as "completed" or "archived" can trigger a 500 error.

Addresses #10226

Description

I updated the server-side logic to group saved posts by user ID, post ID, and post type, ensuring that duplicate posts are not displayed. When updating or deleting, all occurrences of a saved post for a given user ID, post ID, and post type combination will be modified accordingly. This approach helps prevent error 500s and enhances clarity in the user interface.

Steps for Testing

Prerequisites:

  • 1 Studen
  1. Log in to Artemis
  2. Navigate to course
  3. Navigate to the communication tab
  4. Navigate to any channel
  5. If none exist, create some posts
  6. Bookmark posts by hovering them and clicking the bookmark icon
  7. Verify that they appear in the "saved posts" section in the channel list
  8. Mark some posts as "completed" by hovering them in the saved posts list
  9. Everything should work as it did before

Testserver States

You can manage test servers using Helios. Check environment statuses in the environment list. To deploy to a test server, go to the CI/CD page, find your PR or branch, and trigger the deployment.

Review Progress

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Screenshots

Bildschirmfoto 2025-02-22 um 23 39 08

Summary by CodeRabbit

  • New Features
    • Enhanced the saved posts functionality to support managing multiple saved items, offering users more flexible and comprehensive bookmarking.
  • Refactor
    • Streamlined the processes for adding, removing, and updating saved posts to ensure improved accuracy and a consistent user experience.

@PaRangger PaRangger added small bugfix communication Pull requests that affect the corresponding module labels Feb 22, 2025
@PaRangger PaRangger self-assigned this Feb 22, 2025
@github-actions github-actions bot added the server Pull requests that update Java code. (Added Automatically!) label Feb 22, 2025
@helios-aet helios-aet bot temporarily deployed to artemis-test5.artemis.cit.tum.de February 22, 2025 22:53 Inactive
@PaRangger PaRangger marked this pull request as ready for review February 22, 2025 23:02
@PaRangger PaRangger requested a review from a team as a code owner February 22, 2025 23:02
@github-actions github-actions bot added the tests label Feb 22, 2025
Copy link

coderabbitai bot commented Feb 22, 2025

Walkthrough

The pull request updates how saved posts are managed across the repository, service, and test layers. A new repository method is introduced to retrieve multiple saved posts based on user ID, post ID, and posting type, and existing methods now include parameter annotations. The service layer has been revised to handle lists of saved posts instead of a single instance, with corresponding updates in save, remove, and update operations. Test cases have been aligned with these changes to ensure consistency in returned values.

Changes

File(s) Change Summary
src/main/java/de/tum/.../SavedPostRepository.java - Added new method: findSavedPostsByUserIdAndPostIdAndPostType returning a list of SavedPost.
- Updated findSavedPostsByUserIdAndStatusOrderByCompletedAtDescIdDesc with @Param annotations.
src/main/java/de/tum/.../SavedPostService.java - Modified method signatures and internal logic to handle a list of SavedPost instead of a single instance.
- Updated saving, removal, and status update operations to iterate over lists.
src/test/java/de/tum/.../SavedPostServiceTest.java - Revised tests to use findSavedPostsByUserIdAndPostIdAndPostType.
- Adjusted expected outputs to work with lists (empty or with contents) instead of null or a single entity.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant S as SavedPostService
    participant R as SavedPostRepository
    participant DB as Database

    U->>S: Initiate saved post action (save/remove/update)
    S->>R: Call findSavedPostsByUserIdAndPostIdAndPostType()
    R->>S: Return list of SavedPost(s)
    alt List is empty (save operation)
        S->>R: Save new post
        R->>DB: Persist new saved post
        DB-->>R: Acknowledgement
        R-->>S: Confirmation
    else List is non-empty (remove/update)
        loop For each SavedPost
            S->>R: Update/Delete SavedPost
            R->>DB: Persist changes
            DB-->>R: Acknowledgement
        end
        R-->>S: Confirmation
    end
    S->>U: Return operation result
Loading

Suggested reviewers

  • HawKhiem
  • FelberMartin
  • krusche
  • asliayk
  • SimonEntholzer
✨ 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 (6)
src/main/java/de/tum/cit/aet/artemis/communication/repository/SavedPostRepository.java (1)

96-99: Consider adding an index to optimize the grouped query.

The query effectively prevents duplicates by grouping saved posts. However, for optimal performance, consider adding a composite index on (user_id, status, completed_at).

CREATE INDEX idx_saved_post_user_status_completed 
ON saved_post (user_id, status, completed_at DESC);
src/main/java/de/tum/cit/aet/artemis/communication/service/SavedPostService.java (5)

42-44: Rename variable to reflect multiple saved posts
The variable existingSavedPost is a List<SavedPost> and should be pluralized (e.g., existingSavedPosts) for clarity.

-        var existingSavedPost = this.getSavedPostForCurrentUser(post);
-        if (!existingSavedPost.isEmpty()) {
+        var existingSavedPosts = this.getSavedPostForCurrentUser(post);
+        if (!existingSavedPosts.isEmpty()) {
             return;
         }

59-63: Consider transactional or concurrency safeguards
While this logic is correct, concurrently calling this operation could lead to partial deletes or race conditions. You might want to ensure this method is annotated with a transactional boundary or otherwise handled to avoid concurrency pitfalls.


65-68: Consider bulk delete to simplify removal logic
Deleting posts one by one is valid but may be less efficient in certain database contexts. Implementing a bulk delete method in the repository could streamline the query and reduce overhead.


86-91: Unify repeated update logic for improved maintainability
Repeatedly updating each SavedPost is correct but consider centralizing this logic (e.g., in a helper) or using a bulk operation if you anticipate large lists. This can improve performance and clarity while still ensuring cache invalidation, if applicable.


124-128: Rename method to clearly indicate list return type
The method name getSavedPostForCurrentUser returns a list. Renaming it to getSavedPostsForCurrentUser could make the intent clearer.

-    private List<SavedPost> getSavedPostForCurrentUser(Posting post) {
+    private List<SavedPost> getSavedPostsForCurrentUser(Posting post) {
         ...
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8b3c4ed and 89bd6dc.

📒 Files selected for processing (2)
  • src/main/java/de/tum/cit/aet/artemis/communication/repository/SavedPostRepository.java (3 hunks)
  • src/main/java/de/tum/cit/aet/artemis/communication/service/SavedPostService.java (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`src/main/java/**/*.java`: naming:CamelCase; principles:{sin...

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/repository/SavedPostRepository.java
  • src/main/java/de/tum/cit/aet/artemis/communication/service/SavedPostService.java
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (3)
src/main/java/de/tum/cit/aet/artemis/communication/repository/SavedPostRepository.java (2)

40-41: LGTM! Documentation improvement helps prevent misuse.

The updated documentation clearly warns about potential multiple entries and guides developers to use this method only when a single entry is expected.


51-60: LGTM! New method effectively addresses duplicate posts issue.

The method is well-documented and properly designed to handle multiple saved posts for the same user/post/type combination, directly addressing the PR's objective.

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

118-119: Documentation accurately reflects multiple rows
The updated doc comment clarifies that multiple saved posts may exist for the same posting. This improvement is helpful for maintainability.

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 (1)
src/main/java/de/tum/cit/aet/artemis/communication/repository/SavedPostRepository.java (1)

83-84: Consider adding indexes to optimize the grouped query.

The GROUP BY clause effectively prevents duplicates, but consider adding indexes on (user_id, post_id, post_type) to optimize query performance.

CREATE INDEX idx_saved_post_group ON saved_post (user_id, post_id, post_type);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 89bd6dc and 8f9dd8e.

📒 Files selected for processing (2)
  • src/main/java/de/tum/cit/aet/artemis/communication/repository/SavedPostRepository.java (2 hunks)
  • src/test/java/de/tum/cit/aet/artemis/communication/test_repository/SavedPostTestRepository.java (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`src/test/java/**/*.java`: test_naming: descriptive; test_si...

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/test/java/de/tum/cit/aet/artemis/communication/test_repository/SavedPostTestRepository.java
`src/main/java/**/*.java`: naming:CamelCase; principles:{sin...

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/repository/SavedPostRepository.java
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Call Build Workflow / Build and Push Docker Image
  • GitHub Check: Call Build Workflow / Build .war artifact
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: server-tests
  • GitHub Check: server-style
  • GitHub Check: client-tests
  • GitHub Check: client-style
  • GitHub Check: Analyse
🔇 Additional comments (4)
src/main/java/de/tum/cit/aet/artemis/communication/repository/SavedPostRepository.java (2)

38-47: LGTM! Well-documented method for handling duplicate posts.

The new method effectively supports the PR's objective of managing duplicate saved posts by allowing retrieval of all saved posts for a specific user, post, and type combination.


86-86: LGTM! Clear parameter annotations.

The @param annotations improve code clarity and follow SQL parameter annotation guidelines.

src/test/java/de/tum/cit/aet/artemis/communication/test_repository/SavedPostTestRepository.java (2)

6-7: LGTM!

The added imports are necessary and properly organized.


10-12: LGTM!

The interface is properly annotated and follows the test repository pattern.

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: 0

🧹 Nitpick comments (2)
src/main/java/de/tum/cit/aet/artemis/communication/service/SavedPostService.java (2)

58-71: LGTM! Consider using batch delete for better performance.

The method now correctly handles multiple saved posts. The comment about cache keys explains why posts are deleted one by one. However, if cache invalidation is not critical, consider using a batch delete operation for better performance.


79-92: LGTM! Consider using batch update for better performance.

The method now correctly handles multiple saved posts and properly manages the completion time. The comment about cache keys explains why posts are updated one by one. However, if cache invalidation is not critical, consider using a batch update operation for better performance.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f9dd8e and 1633ec9.

📒 Files selected for processing (2)
  • src/main/java/de/tum/cit/aet/artemis/communication/service/SavedPostService.java (4 hunks)
  • src/test/java/de/tum/cit/aet/artemis/communication/service/SavedPostServiceTest.java (6 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`src/main/java/**/*.java`: naming:CamelCase; principles:{sin...

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/SavedPostService.java
`src/test/java/**/*.java`: test_naming: descriptive; test_si...

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/test/java/de/tum/cit/aet/artemis/communication/service/SavedPostServiceTest.java
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: server-tests
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (3)
src/main/java/de/tum/cit/aet/artemis/communication/service/SavedPostService.java (2)

39-50: LGTM! The changes correctly prevent duplicate saved posts.

The method now properly handles the case of duplicate posts by checking if any saved posts already exist for the current user and post combination.


117-129: LGTM! Clear documentation of edge cases.

The method signature and documentation have been updated to clearly indicate that multiple saved posts may exist for the same posting in edge cases.

src/test/java/de/tum/cit/aet/artemis/communication/service/SavedPostServiceTest.java (1)

58-143: LGTM! Tests thoroughly cover the new functionality.

The test methods have been properly updated to:

  1. Use the new repository method that returns lists
  2. Cover both empty and non-empty result cases
  3. Maintain existing assertions

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 for review server Pull requests that update Java code. (Added Automatically!) small tests
Projects
Status: Ready For Review
Status: Todo
Development

Successfully merging this pull request may close these issues.

1 participant