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

Lectures: Correctly put and get competencies for attachment units #9684

Closed

Conversation

badkeyy
Copy link
Contributor

@badkeyy badkeyy commented Nov 6, 2024

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 added multiple integration tests (Spring) related to the features (with a high test coverage).
  • I added pre-authorization annotations according to the guidelines and checked the course groups for all new REST Calls (security).
  • I documented the Java code using JavaDoc style.

Motivation and Context

Fixes this issue: #9666

Description

  • Added the competencyLinks field to attachment-units GET-Request
  • Added the competencyLinks field to attachment-units PUT-Request (Updates the attachment unit)

Steps for Testing

Prerequisites:

  • 1 Instructor
  • 1 Demo Course with at least one lecture and competency
  1. Log in to Artemis
  2. Navigate to the demo lecture’s units
  3. Create a new attachment unit
  4. Try to edit the created attachment unit, add the test competency and press "Submit"
  5. After pressing edit again find the added competency in the attachment unit

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

Performance Review

  • I (as a reviewer) confirm that the client changes (in particular related to REST calls and UI responsiveness) are implemented with a very good performance even for very large courses with more than 2000 students.
  • I (as a reviewer) confirm that the server changes (in particular related to database calls) are implemented with a very good performance even for very large courses with more than 2000 students.

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Exam Mode Test

  • Test 1
  • Test 2

Performance Tests

  • Test 1
  • Test 2

Screenshots

video

Summary by CodeRabbit

  • New Features

    • Enhanced functionality for updating attachment units, including competency link updates and improved file handling.
    • Retrieval of attachment units now includes associated slides and competencies for better data visibility.
  • Bug Fixes

    • Improved error handling to ensure attachments are present during updates and to validate file types.
  • Documentation

    • Updated method signatures to reflect changes in functionality and parameters.

@badkeyy badkeyy requested a review from a team as a code owner November 6, 2024 14:55
@github-actions github-actions bot added server Pull requests that update Java code. (Added Automatically!) lecture Pull requests that affect the corresponding module labels Nov 6, 2024
Copy link

coderabbitai bot commented Nov 6, 2024

Walkthrough

The changes in this pull request focus on the AttachmentUnitService and AttachmentUnitResource classes, enhancing the functionality of the updateAttachmentUnit method by updating competency links, improving error handling, and refining file handling logic. The AttachmentUnitResource class has also been updated to retrieve attachment units along with their associated slides and competencies, ensuring that the necessary data is available during updates. Method signatures have been updated to reflect these changes, particularly in relation to the handling of competency links and file operations.

Changes

File Path Change Summary
src/main/java/de/tum/cit/aet/artemis/lecture/service/AttachmentUnitService.java - Modified updateAttachmentUnit to set competency links and enhance error handling.
- Refined file handling logic for updates.
src/main/java/de/tum/cit/aet/artemis/lecture/web/AttachmentUnitResource.java - Updated getAttachmentUnit and updateAttachmentUnit to use findOneWithSlidesAndCompetencies.
- Maintained existing logic in createAttachmentUnit, uploadSlidesForProcessing, and others with enhanced error handling.

Possibly related PRs

Suggested labels

tests, enhancement, bugfix, ready for review

Suggested reviewers

  • JohannesStoehr
  • MaximilianAnzinger
  • N0W0RK
  • florian-glombik
  • egekurt123

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

🧹 Outside diff range and nitpick comments (4)
src/main/java/de/tum/cit/aet/artemis/lecture/service/AttachmentUnitService.java (2)

120-120: Add validation and defensive copying for competency links.

While the competency links update works, consider these improvements for better robustness:

  1. Validate the incoming competency links before assignment
  2. Use defensive copying to prevent external modifications
-        existingAttachmentUnit.setCompetencyLinks(updateUnit.getCompetencyLinks());
+        Set<CompetencyLectureUnitLink> newLinks = updateUnit.getCompetencyLinks();
+        if (newLinks != null) {
+            existingAttachmentUnit.setCompetencyLinks(new HashSet<>(newLinks));
+        } else {
+            existingAttachmentUnit.setCompetencyLinks(new HashSet<>());
+        }

Line range hint 116-159: Consider refactoring for better separation of concerns.

The updateAttachmentUnit method handles multiple responsibilities (competency updates, file handling, attachment updates) making it complex and harder to maintain. Consider breaking it down into smaller, focused methods:

  1. Extract competency handling logic
  2. Extract file handling logic
  3. Extract attachment update logic

Example refactoring structure:

public AttachmentUnit updateAttachmentUnit(...) {
    // Main orchestration
    validatePreConditions(existingAttachmentUnit);
    AttachmentUnit savedUnit = updateBasicProperties(existingAttachmentUnit, updateUnit);
    updateCompetencies(savedUnit, updateUnit);
    updateAttachmentIfNeeded(savedUnit, updateAttachment);
    handleFileIfProvided(savedUnit, updateFile, keepFilename);
    return finalizeUpdate(savedUnit);
}

private void updateCompetencies(AttachmentUnit existingUnit, AttachmentUnit updateUnit) {
    Set<CompetencyLectureUnitLink> existingLinks = new HashSet<>(existingUnit.getCompetencyLinks());
    // Update logic...
    competencyProgressService.updateProgressForUpdatedLearningObjectAsync(...);
}

private void handleFileIfProvided(...) {
    if (updateFile == null) return;
    // File handling logic...
}

This refactoring would:

  • Improve code readability
  • Make the code easier to test
  • Make the code easier to maintain
  • Reduce cognitive complexity
src/main/java/de/tum/cit/aet/artemis/lecture/web/AttachmentUnitResource.java (2)

103-103: Update JavaDoc to reflect competency data in response.

The method now returns competency data along with the attachment unit, but this isn't documented in the JavaDoc. Consider updating the documentation to reflect this change.

-     * @return the ResponseEntity with status 200 (OK) and with body the attachment unit, or with status 404 (Not Found)
+     * @return the ResponseEntity with status 200 (OK) and with body the attachment unit including slides and competencies, or with status 404 (Not Found)

103-103: Consider lazy loading optimization if competencies aren't always needed.

The change from findByIdElseThrow to findOneWithSlidesAndCompetencies eagerly loads additional data. Consider implementing a separate endpoint or query parameter if this additional data isn't always required by clients.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fdc2501 and 881405e.

📒 Files selected for processing (2)
  • src/main/java/de/tum/cit/aet/artemis/lecture/service/AttachmentUnitService.java (1 hunks)
  • src/main/java/de/tum/cit/aet/artemis/lecture/web/AttachmentUnitResource.java (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/main/java/de/tum/cit/aet/artemis/lecture/service/AttachmentUnitService.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/lecture/web/AttachmentUnitResource.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

🔇 Additional comments (1)
src/main/java/de/tum/cit/aet/artemis/lecture/web/AttachmentUnitResource.java (1)

103-106: LGTM! The implementation aligns with PR objectives.

The change correctly implements the requirement to include competency data when retrieving attachment units. The implementation:

  • Follows proper authorization checks
  • Maintains error handling
  • Uses appropriate repository method

Copy link

coderabbitai bot commented Nov 6, 2024

Walkthrough

The changes in this pull request focus on enhancing the AttachmentUnitService and AttachmentUnitResource classes. The updateAttachmentUnit method now includes logic to update competency links and improved error handling. The retrieval methods have been updated to fetch attachment units along with their associated slides and competencies. Additionally, error handling for file uploads has been strengthened, particularly for PDF files. Overall, these modifications aim to improve the management and processing of attachment units within the application.

Changes

File Change Summary
src/main/java/de/tum/cit/aet/artemis/lecture/service/AttachmentUnitService.java Updated updateAttachmentUnit to set competency links, enhanced error handling, and adjusted file processing logic.
src/main/java/de/tum/cit/aet/artemis/lecture/web/AttachmentUnitResource.java Modified methods for retrieving and updating attachment units to include slides and competencies, improved error handling for file uploads, and retained ID checks in the creation process.

Possibly related PRs

Suggested labels

enhancement, bugfix, server, tests, component:AdaptiveLearning

Suggested reviewers

  • JohannesStoehr
  • MaximilianAnzinger
  • N0W0RK
  • florian-glombik
  • egekurt123

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

🧹 Outside diff range and nitpick comments (2)
src/main/java/de/tum/cit/aet/artemis/lecture/service/AttachmentUnitService.java (2)

Line range hint 116-171: Consider breaking down the updateAttachmentUnit method.

The method handles multiple concerns (competency updates, file handling, progress tracking) making it harder to maintain and test. Consider extracting the file handling logic into a separate method.

Example refactor:

 public AttachmentUnit updateAttachmentUnit(...) {
     Set<CompetencyLectureUnitLink> existingCompetencyLinks = new HashSet<>(existingAttachmentUnit.getCompetencyLinks());
     
     // Update basic properties
     updateBasicProperties(existingAttachmentUnit, updateUnit);
     
     AttachmentUnit savedAttachmentUnit = lectureUnitService.saveWithCompetencyLinks(existingAttachmentUnit, attachmentUnitRepository::saveAndFlush);
     
     // Handle attachment updates
     updateAttachmentAndFile(savedAttachmentUnit, updateAttachment, updateFile, keepFilename);
     
     // Handle competency progress
     updateCompetencyProgress(existingAttachmentUnit, updateUnit, existingCompetencyLinks);
     
     return savedAttachmentUnit;
 }

+private void updateBasicProperties(AttachmentUnit existingUnit, AttachmentUnit updateUnit) {
+    existingUnit.setDescription(updateUnit.getDescription());
+    existingUnit.setName(updateUnit.getName());
+    existingUnit.setReleaseDate(updateUnit.getReleaseDate());
+    existingUnit.setCompetencyLinks(updateUnit.getCompetencyLinks());
+}

+private void updateAttachmentAndFile(AttachmentUnit unit, Attachment updateAttachment, MultipartFile file, boolean keepFilename) {
+    // Extract file handling logic here
+}

+private void updateCompetencyProgress(AttachmentUnit existingUnit, AttachmentUnit updateUnit, Set<CompetencyLectureUnitLink> originalLinks) {
+    existingUnit.setCompetencyLinks(originalLinks);
+    competencyProgressService.updateProgressForUpdatedLearningObjectAsync(existingUnit, Optional.of(updateUnit));
+}

Line range hint 116-171: Consider adding explicit transaction boundaries.

The method performs multiple database operations without explicit transaction boundaries. Consider adding @Transactional to ensure atomic updates.

+@Transactional
 public AttachmentUnit updateAttachmentUnit(AttachmentUnit existingAttachmentUnit, AttachmentUnit updateUnit, 
     Attachment updateAttachment, MultipartFile updateFile, boolean keepFilename) {
     // ... existing code ...
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fdc2501 and 881405e.

📒 Files selected for processing (2)
  • src/main/java/de/tum/cit/aet/artemis/lecture/service/AttachmentUnitService.java (1 hunks)
  • src/main/java/de/tum/cit/aet/artemis/lecture/web/AttachmentUnitResource.java (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/main/java/de/tum/cit/aet/artemis/lecture/service/AttachmentUnitService.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/lecture/web/AttachmentUnitResource.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

🔇 Additional comments (2)
src/main/java/de/tum/cit/aet/artemis/lecture/service/AttachmentUnitService.java (1)

120-120: LGTM: Competency links update implementation.

The implementation correctly updates the competency links while preserving the original links for progress tracking.

src/main/java/de/tum/cit/aet/artemis/lecture/web/AttachmentUnitResource.java (1)

103-103: Ensure efficient fetching of associated entities to prevent N+1 queries

By using findOneWithSlidesAndCompetencies, ensure that slides and competencies are fetched eagerly to avoid potential N+1 query problems and improve performance when accessing these associations.

Run the following script to verify the fetching strategy:

✅ Verification successful

Let me check the actual implementation of this method by looking for the query definition.


The query is already optimized with LEFT JOIN FETCH statements

The findOneWithSlidesAndCompetencies method is properly implemented with eager fetching using LEFT JOIN FETCH for slides, competency links, and competencies. This prevents N+1 query issues by fetching all related entities in a single query.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if 'findOneWithSlidesAndCompetencies' method fetches slides and competencies eagerly.

# Expected result: The method uses JOIN FETCH to eagerly load slides and competencies.

rg -A 5 'findOneWithSlidesAndCompetencies' src/main/java/de/tum/cit/aet/artemis/lecture/repository/AttachmentUnitRepository.java

Length of output: 233


Script:

#!/bin/bash
# Look for @Query annotation above the findOneWithSlidesAndCompetencies method
rg -B 5 "findOneWithSlidesAndCompetencies" src/main/java/de/tum/cit/aet/artemis/lecture/repository/AttachmentUnitRepository.java

# Also check if there's any named query definition in XML or properties files
fd -e xml -e properties | xargs rg "findOneWithSlidesAndCompetencies"

Length of output: 547

@Strohgelaender
Copy link
Contributor

Welcome to Artemis 👋
Thanks for the PR, the changes look good.

Can you also add some server tests to check for this behaviour?

Copy link
Member

@bassner bassner left a comment

Choose a reason for hiding this comment

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

@Strohgelaender is right - please add a small test for this so it doesn't happen again :)

@bassner bassner changed the title Lectures : Correctly put and get competencies for attachment units 'Lectures : Correctly put and get competencies for attachment units Nov 11, 2024
@bassner bassner changed the title 'Lectures : Correctly put and get competencies for attachment units 'Lectures`: Correctly put and get competencies for attachment units Nov 11, 2024
@bassner bassner changed the title 'Lectures`: Correctly put and get competencies for attachment units Lectures: Correctly put and get competencies for attachment units Nov 11, 2024
@bassner bassner added this to the 7.7.1 milestone Nov 11, 2024
@JohannesStoehr
Copy link
Contributor

Thank you for your help with fixing the issue. Since we want to fix the bug quickly, I adapted the tests in a new PR and incorporated your changes in this PR: #9739 Feel free to assign yourself as well in this PR.

As our readme states (https://github.com/ls1intum/Artemis#communication), we also use Slack for communication. If you want to contribute more in the future, feel free to sign up so we can better communicate and easier collaborate on PRs in the future.

@badkeyy
Copy link
Contributor Author

badkeyy commented Nov 11, 2024

Thank you for your help with fixing the issue. Since we want to fix the bug quickly, I adapted the tests in a new PR and incorporated your changes in this PR: #9739 Feel free to assign yourself as well in this PR.

As our readme states (https://github.com/ls1intum/Artemis#communication), we also use Slack for communication. If you want to contribute more in the future, feel free to sign up so we can better communicate and easier collaborate on PRs in the future.

Thanks for picking this up - as I have been very busy this past week I havn't had time to add the tests. I will definitely join the slack, thanks for the hint.

@badkeyy
Copy link
Contributor Author

badkeyy commented Nov 11, 2024

Closed in favor of #9739

@badkeyy badkeyy closed this Nov 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
lecture Pull requests that affect the corresponding module server Pull requests that update Java code. (Added Automatically!)
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

5 participants