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

General: Fix an issue with course deletion summary entries #9856

Merged
merged 12 commits into from
Jan 5, 2025

Conversation

ole-ve
Copy link
Contributor

@ole-ve ole-ve commented Nov 25, 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 documented the Java code using JavaDoc style.

Client

  • Important: I implemented the changes with a very good performance, prevented too many (unnecessary) REST calls and made sure the UI is responsive, even with large data (e.g. using paging).
  • I strictly followed the principle of data economy for all client-server REST calls.
  • I strictly followed the client coding and design guidelines.
  • Following the theming guidelines, I specified colors only in the theming variable files and checked that the changes look consistent in both the light and the dark theme.

Motivation and Context

Fixes #9722. On the course DTO, there are some fields that have no assigned values on the course management page.
These changes load the required values from the server.

Steps for Testing

Create a course with exercises for each type, lectures, and exams. Verify that all of these values are correct.

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

Summary by CodeRabbit

  • New Features

    • Enhanced course deletion summary with more detailed metrics
    • Added counts for various exercise types, exams, and lectures
    • Improved tracking of course-related content during deletion process
  • Technical Improvements

    • Updated data transfer objects and repositories to support more comprehensive course information
    • Added new query methods to retrieve detailed course statistics

The changes provide a more comprehensive overview of course content before deletion, giving users more insight into the course's components.

@ole-ve ole-ve self-assigned this Nov 25, 2024
@ole-ve ole-ve requested a review from a team as a code owner November 25, 2024 17:05
@github-actions github-actions bot added server Pull requests that update Java code. (Added Automatically!) client Pull requests that update TypeScript code. (Added Automatically!) core Pull requests that affect the corresponding module exam Pull requests that affect the corresponding module exercise Pull requests that affect the corresponding module lecture Pull requests that affect the corresponding module labels Nov 25, 2024
@ole-ve ole-ve changed the title Courses: Load course deletion summary entries from server that are not present in the client Usability: Load course deletion summary entries from server that are not present in the client Nov 25, 2024
Copy link

coderabbitai bot commented Nov 25, 2024

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/core/service/CourseService.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/exercise/dto/ExerciseTypeCountDTO.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/exercise/repository/ExerciseRepository.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.

  • 1 others

Walkthrough

This pull request enhances the course deletion summary functionality across multiple components of the Artemis application. The changes introduce more comprehensive metrics for course deletion, including detailed counts for lectures, exams, and various exercise types. The modifications span both backend (Java) and frontend (TypeScript) files, updating data transfer objects, repositories, services, and components to provide a more accurate representation of course components during the deletion process.

Changes

File Change Summary
src/main/java/de/tum/cit/aet/artemis/core/dto/CourseDeletionSummaryDTO.java Added 7 new fields for exercise types, exams, and lectures
src/main/java/de/tum/cit/aet/artemis/core/service/CourseService.java Updated getDeletionSummary method to include new metrics
src/main/webapp/app/entities/course-deletion-summary.model.ts Added corresponding new properties to TypeScript interface
src/main/webapp/app/course/manage/...component.ts Updated summary fetching and entry calculation logic
Repositories (ExamRepository, ExerciseRepository, LectureRepository) Added methods to count entities by course ID

Assessment against linked issues

Objective Addressed Explanation
Display correct numbers in course deletion confirmation
Match numbers of lectures, exercises, exams, and posts

Suggested labels

assessment

Suggested reviewers

  • az108
  • JohannesStoehr
  • SimonEntholzer
  • krusche
  • Hialus

Possibly related PRs


📜 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 1e8fd97 and 444cd80.

📒 Files selected for processing (4)
  • src/main/java/de/tum/cit/aet/artemis/core/service/CourseService.java (2 hunks)
  • src/main/java/de/tum/cit/aet/artemis/exercise/dto/ExerciseTypeCountDTO.java (1 hunks)
  • src/main/java/de/tum/cit/aet/artemis/exercise/repository/ExerciseRepository.java (2 hunks)
  • src/main/java/de/tum/cit/aet/artemis/exercise/service/ExerciseService.java (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/java/de/tum/cit/aet/artemis/exercise/repository/ExerciseRepository.java
  • src/main/java/de/tum/cit/aet/artemis/exercise/service/ExerciseService.java
  • src/main/java/de/tum/cit/aet/artemis/core/service/CourseService.java
🧰 Additional context used
📓 Path-based instructions (1)
src/main/java/de/tum/cit/aet/artemis/exercise/dto/ExerciseTypeCountDTO.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/exercise/dto/ExerciseTypeCountDTO.java (2)

8-9: Good use of Java Record for a concise DTO.

The record structure adheres to the coding guidelines (java_records, minimal data, single responsibility). Naming conventions also look consistent.


10-12: Validate that ExerciseType.getExerciseTypeFromClass never returns null.

Currently, the code doesn't handle a scenario where getExerciseTypeFromClass might return null. Confirm the method's behavior or add a guard clause to avoid a potential NPE.

✅ Verification successful

Let me check the implementation of getExerciseTypeFromClass to understand its behavior better.


Let me check the implementation in ExerciseType.java to see how it handles the return value.


getExerciseTypeFromClass is safe from null returns

Based on the implementation, the method ExerciseType.getExerciseTypeFromClass cannot return null because:

  1. It uses a switch expression that exhaustively handles all cases
  2. For known exercise types, it returns an enum constant (TEXT, PROGRAMMING, etc.)
  3. For unknown types, it throws an IllegalArgumentException

The current usage in ExerciseTypeCountDTO is safe from NPE.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `ExerciseType.getExerciseTypeFromClass` can never return null.

rg -A 5 "ExerciseType\.getExerciseTypeFromClass"

Length of output: 1752


Script:

#!/bin/bash
# Find the implementation of getExerciseTypeFromClass in ExerciseType
ast-grep --pattern 'getExerciseTypeFromClass'

Length of output: 1689


Script:

#!/bin/bash
# Get the implementation of getExerciseTypeFromClass method
rg -A 10 "getExerciseTypeFromClass.*\{" src/main/java/de/tum/cit/aet/artemis/exercise/domain/ExerciseType.java

Length of output: 677


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

🧹 Outside diff range and nitpick comments (11)
src/main/webapp/app/entities/course-deletion-summary.model.ts (1)

5-11: Consider adding JSDoc documentation for the new properties.

The new properties are well-named and correctly typed. However, adding JSDoc comments would improve maintainability by documenting the purpose and expected values of each property.

 export interface CourseDeletionSummaryDTO {
     numberOfBuilds: number;
     numberOfCommunicationPosts: number;
     numberOfAnswerPosts: number;
+    /** Number of programming exercises in the course */
     numberProgrammingExercises: number;
+    /** Number of text exercises in the course */
     numberTextExercises: number;
+    /** Number of file upload exercises in the course */
     numberFileUploadExercises: number;
+    /** Number of quiz exercises in the course */
     numberQuizExercises: number;
+    /** Number of modeling exercises in the course */
     numberModelingExercises: number;
+    /** Number of exams in the course */
     numberExams: number;
+    /** Number of lectures in the course */
     numberLectures: number;
 }
src/main/java/de/tum/cit/aet/artemis/core/dto/CourseDeletionSummaryDTO.java (1)

6-7: Consider improving organization and documentation

While the implementation is functionally correct, consider these improvements:

  1. Group related fields into nested records for better organization
  2. Add JavaDoc documentation explaining the purpose of each field

Example refactor:

-public record CourseDeletionSummaryDTO(long numberOfBuilds, long numberOfCommunicationPosts, long numberOfAnswerPosts, long numberProgrammingExercises, long numberTextExercises,
-        long numberFileUploadExercises, long numberModelingExercises, long numberQuizExercises, long numberExams, long numberLectures) {
+/**
+ * Data Transfer Object for course deletion summary information.
+ * Contains counts of various course components that will be affected by deletion.
+ */
+public record CourseDeletionSummaryDTO(
+    // Build and communication metrics
+    long numberOfBuilds,
+    long numberOfCommunicationPosts,
+    long numberOfAnswerPosts,
+    
+    // Exercise counts by type
+    ExerciseCountsDTO exerciseCounts,
+    
+    // Course structure counts
+    long numberExams,
+    long numberLectures
+) {
+    /**
+     * Nested record for exercise-related counts
+     */
+    public record ExerciseCountsDTO(
+        long numberProgrammingExercises,
+        long numberTextExercises,
+        long numberFileUploadExercises,
+        long numberModelingExercises,
+        long numberQuizExercises
+    ) {}
+}
src/main/java/de/tum/cit/aet/artemis/exercise/dto/ExerciseTypeCount.java (3)

8-12: Add JavaDoc documentation for better maintainability.

Consider adding JavaDoc documentation to describe:

  • The purpose and usage of this DTO class
  • The meaning of each field
  • Any constraints or invariants
+/**
+ * Data Transfer Object for representing the count of exercises grouped by their type.
+ * Used in course deletion summary to provide exercise statistics.
+ */
 public class ExerciseTypeCount {

+    /** The type of the exercise */
     private final ExerciseType exerciseType;

+    /** The number of exercises of this type */
     private final long count;

19-25: Add JavaDoc to getter methods.

While the getters are correctly implemented, adding documentation would improve code maintainability.

+/**
+ * @return the type of the exercise
+ */
 public ExerciseType getExerciseType() {
     return exerciseType;
 }

+/**
+ * @return the number of exercises of this type
+ */
 public long getCount() {
     return count;
 }

8-26: Consider converting to a Java Record.

Since this class is a simple DTO with immutable fields and basic getters, it's a perfect candidate for a Java Record. This would:

  • Reduce boilerplate code
  • Automatically provide equals(), hashCode(), and toString()
  • Better express the intent of the class as a data carrier
-public class ExerciseTypeCount {
-    private final ExerciseType exerciseType;
-    private final long count;
-
-    public ExerciseTypeCount(Class<?> exerciseType, Long count) {
-        this.exerciseType = ExerciseType.getExerciseTypeFromClass(exerciseType.asSubclass(Exercise.class));
-        this.count = Objects.requireNonNullElse(count, 0L);
-    }
-
-    public ExerciseType getExerciseType() {
-        return exerciseType;
-    }
-
-    public long getCount() {
-        return count;
-    }
-}
+/**
+ * Data Transfer Object for representing the count of exercises grouped by their type.
+ * Used in course deletion summary to provide exercise statistics.
+ *
+ * @param exerciseType the type of the exercise
+ * @param count the number of exercises of this type
+ */
+public record ExerciseTypeCount(ExerciseType exerciseType, long count) {
+    /**
+     * Creates a new ExerciseTypeCount instance.
+     *
+     * @param exerciseType the class of the exercise type, must be a subclass of Exercise
+     * @param count the number of exercises of this type, defaults to 0 if null
+     * @throws NullPointerException if exerciseType is null
+     * @throws ClassCastException if exerciseType is not a subclass of Exercise
+     */
+    public ExerciseTypeCount(Class<?> exerciseType, Long count) {
+        this(
+            Objects.requireNonNull(exerciseType, "exerciseType must not be null"),
+            ExerciseType.getExerciseTypeFromClass(exerciseType.asSubclass(Exercise.class)),
+            Objects.requireNonNullElse(count, 0L)
+        );
+    }
+}
src/main/java/de/tum/cit/aet/artemis/lecture/repository/LectureRepository.java (1)

199-200: LGTM with suggestions for improvement.

The method follows Spring Data JPA conventions and aligns with the repository's purpose. Consider these enhancements:

+    /**
+     * Counts the number of lectures associated with a specific course.
+     * Used in course deletion summary to track the number of lectures that will be removed.
+     *
+     * @param courseId the ID of the course
+     * @return the number of lectures in the course
+     */
+    @Cacheable(cacheNames = "lectureCounts", key = "#courseId")
     long countByCourse_Id(Long courseId);

The suggested improvements:

  1. Added JavaDoc documentation to align with the existing codebase style
  2. Added @Cacheable annotation to optimize performance for repeated calls, following the pattern used in getLectureTitle
src/main/webapp/app/course/manage/course-management-tab-bar/course-management-tab-bar.component.ts (1)

246-252: Add JSDoc comments for the new summary fields

To maintain consistency with the PR's documentation requirements, consider adding JSDoc comments explaining these new fields.

 fetchCourseDeletionSummary(): Observable<EntitySummary> {
+    /**
+     * Fetches a comprehensive summary of course elements for deletion confirmation.
+     * Includes counts of:
+     * - Exams and lectures
+     * - Different types of exercises (programming, text, modeling, etc.)
+     * - Related entities (builds, communication posts, etc.)
+     * @returns Observable<EntitySummary> containing all course element counts
+     */
src/main/java/de/tum/cit/aet/artemis/exam/repository/ExamRepository.java (1)

388-389: Consider using primitive long for parameter type and add documentation.

While the implementation follows Spring Data JPA conventions, consider these improvements:

  1. Use primitive long instead of Long to prevent null values and maintain consistency with other similar methods in the repository.
  2. Add JavaDoc documentation to describe the method's purpose and parameters.
+    /**
+     * Count the number of exams associated with a course.
+     *
+     * @param courseId the id of the course
+     * @return the number of exams in the course
+     */
-    long countByCourse_Id(Long courseId);
+    long countByCourse_Id(long courseId);

The overall implementation is correct and aligns well with the repository's purpose of providing exam-related data access.

src/main/java/de/tum/cit/aet/artemis/exercise/repository/ExerciseRepository.java (1)

632-639: Consider enhancing the method documentation.

While the current documentation is clear, it would be helpful to add:

  • @throws clause for potential exceptions
  • Example of the returned data structure
     /**
      * Returns a mapping from exercise type to count for a given course id. Note that there are way fewer courses
      * than exercise, so loading the course and joining the course is way faster than vice versa.
      *
      * @param courseId the courseId to get the exerciseType->count mapping for
      * @return a list of mappings from exercise type to count
+     * @throws IllegalArgumentException if courseId is invalid
+     * Example return value: [(MODELING, 5), (PROGRAMMING, 3), (QUIZ, 2)]
      */
src/main/java/de/tum/cit/aet/artemis/exercise/service/ExerciseService.java (1)

835-845: Good implementation, but could be enhanced with validation and optimization.

The implementation is clean and handles all exercise types correctly. However, consider these improvements:

  1. Add parameter validation for courseId
  2. Add @NotNull annotation for the parameter
  3. Optimize the stream operations

Here's a suggested improvement:

-    public Map<ExerciseType, Long> countByCourseIdGroupByType(Long courseId) {
+    public Map<ExerciseType, Long> countByCourseIdGroupByType(@NotNull Long courseId) {
+        if (courseId == null) {
+            throw new IllegalArgumentException("courseId must not be null");
+        }
+
         Map<ExerciseType, Long> exerciseTypeCountMap = exerciseRepository.countByCourseIdGroupedByType(courseId).stream()
                 .collect(Collectors.toMap(ExerciseTypeCount::getExerciseType, ExerciseTypeCount::getCount));
-
-        return Arrays.stream(ExerciseType.values()).collect(Collectors.toMap(type -> type, type -> exerciseTypeCountMap.getOrDefault(type, 0L)));
+        return Arrays.stream(ExerciseType.values())
+                .collect(Collectors.toMap(
+                    Function.identity(),
+                    type -> exerciseTypeCountMap.getOrDefault(type, 0L)
+                ));
     }
src/main/java/de/tum/cit/aet/artemis/core/service/CourseService.java (1)

479-480: Ensure consistent naming conventions in repository methods

The method names countByCourse_Id do not follow standard CamelCase naming conventions. Consider renaming them to adhere to Java conventions.

Apply this diff to rename the methods:

- long numberLectures = lectureRepository.countByCourse_Id(courseId);
- long numberExams = examRepository.countByCourse_Id(courseId);
+ long numberLectures = lectureRepository.countByCourseId(courseId);
+ long numberExams = examRepository.countByCourseId(courseId);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4dde77f and 1cef9d1.

📒 Files selected for processing (9)
  • src/main/java/de/tum/cit/aet/artemis/core/dto/CourseDeletionSummaryDTO.java (1 hunks)
  • src/main/java/de/tum/cit/aet/artemis/core/service/CourseService.java (2 hunks)
  • src/main/java/de/tum/cit/aet/artemis/exam/repository/ExamRepository.java (1 hunks)
  • src/main/java/de/tum/cit/aet/artemis/exercise/dto/ExerciseTypeCount.java (1 hunks)
  • src/main/java/de/tum/cit/aet/artemis/exercise/repository/ExerciseRepository.java (2 hunks)
  • src/main/java/de/tum/cit/aet/artemis/exercise/service/ExerciseService.java (3 hunks)
  • src/main/java/de/tum/cit/aet/artemis/lecture/repository/LectureRepository.java (1 hunks)
  • src/main/webapp/app/course/manage/course-management-tab-bar/course-management-tab-bar.component.ts (1 hunks)
  • src/main/webapp/app/entities/course-deletion-summary.model.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
src/main/java/de/tum/cit/aet/artemis/core/dto/CourseDeletionSummaryDTO.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/core/service/CourseService.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/exam/repository/ExamRepository.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/exercise/dto/ExerciseTypeCount.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/exercise/repository/ExerciseRepository.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/exercise/service/ExerciseService.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/repository/LectureRepository.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/webapp/app/course/manage/course-management-tab-bar/course-management-tab-bar.component.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

src/main/webapp/app/entities/course-deletion-summary.model.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

🔇 Additional comments (10)
src/main/webapp/app/entities/course-deletion-summary.model.ts (1)

5-11: Verify null handling in consuming components.

Since these properties are loaded from the server, ensure that components using this DTO properly handle cases where these values might be undefined or null.

src/main/java/de/tum/cit/aet/artemis/core/dto/CourseDeletionSummaryDTO.java (1)

6-7: Implementation follows DTO best practices

The record implementation correctly follows the coding guidelines by:

  • Using Java records for DTOs
  • Using primitive types
  • Following naming conventions
  • Maintaining single responsibility
src/main/java/de/tum/cit/aet/artemis/exercise/dto/ExerciseTypeCount.java (1)

1-7: LGTM! Clean and well-organized imports.

The package structure and imports follow best practices with specific imports and no wildcards.

src/main/java/de/tum/cit/aet/artemis/lecture/repository/LectureRepository.java (1)

199-200: Verify integration with related components.

Let's ensure consistent implementation across the codebase:

✅ Verification successful

Method naming and integration are consistent with related components

The verification shows:

  • The method countByCourse_Id follows a consistent naming pattern used in other repositories (ExamRepository)
  • It's properly integrated in CourseService where it's used alongside examRepository.countByCourse_Id for course deletion metrics
  • The implementation aligns with the PR's objective of enhancing course deletion summary
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for similar count methods in related repositories and CourseService usage

# Check for similar count methods in other repositories
echo "Checking for similar count methods in repositories..."
rg -l "countByCourse_Id|countByCourseId" --type java

# Check CourseService implementation
echo "Checking CourseService implementation..."
rg "countByCourse_Id|getDeletionSummary.*Lecture" --type java

# Check for other counting patterns in repositories
echo "Checking counting patterns in repositories..."
ast-grep --pattern 'interface $REPO extends $_ {
  $$$
  count$_($_) $_
  $$$
}'

Length of output: 1708

src/main/webapp/app/course/manage/course-management-tab-bar/course-management-tab-bar.component.ts (1)

246-252: Verify performance impact for large courses

The PR objectives mention testing with courses having over 2000 students. Let's ensure the server-side summary calculation performs well at scale.

✅ Verification successful

Let me gather more information about the implementation to verify the performance aspects.


Let me search for more specific information about the database queries and their optimization.


Let me try one final search to check the query implementations.


Based on the gathered information, I can now provide a final response:

Performance optimizations are already in place for large-scale course operations

The implementation is well-optimized for handling large courses:

  • Uses efficient count queries instead of loading full entities
  • Leverages Hibernate's batch processing (hibernate.jdbc.batch_size: 25)
  • Implements second-level caching with Hazelcast
  • Uses optimized query configurations:
    • hibernate.query.in_clause_parameter_padding: true
    • hibernate.order_inserts/updates: true
    • Proper fetch depth control (hibernate.max_fetch_depth: 2)

The deletion summary calculation uses:

  • Single database round-trips for counting entities
  • Efficient group-by operations for exercise types
  • Optimized collection handling with streaming operations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for performance-related configurations or optimizations in the backend
rg -g '*.java' -A 5 'CourseDeletionSummary|getDeletionSummary'

# Look for any existing performance tests
fd -e java -e ts test.*performance

Length of output: 6400


Script:

#!/bin/bash
# Check the implementation details of the deletion summary calculation
rg -g '*.java' -A 10 'buildJobRepository.countBuildJobsByExerciseIds|communicationPostRepository.countByCourseId|answerPostRepository.countByCourseId'

# Look for any database query optimizations or batch processing
ast-grep --pattern 'class BuildJobRepository {
  $$$
  countBuildJobsByExerciseIds($$$) {
    $$$
  }
  $$$
}'

# Check if there are any pagination or limit configurations
rg -g '*.java' -B 3 -A 3 '@Query.*countBy.*CourseId|@Query.*countBy.*ExerciseIds'

Length of output: 3483


Script:

#!/bin/bash
# Check repository interfaces for query implementations
rg -g '*.java' -B 2 -A 2 'interface.*Repository.*{|@Query.*count'

# Look for any batch processing or pagination in exercise service
ast-grep --pattern 'class ExerciseService {
  $$$
  countByCourseIdGroupByType($$$) {
    $$$
  }
  $$$
}'

# Check for any existing database indexes or performance configurations
fd -e java -e xml -e properties 'repository|database|jpa' --exec rg -l 'Index|@Index|hibernate.jdbc.batch|fetch'

Length of output: 3782


Script:

#!/bin/bash
# Check specific repository implementations
rg -g '*.java' -A 5 'countBuildJobsByExerciseIds|countAnswerPostsByPostIdIn|countByCourse_Id'

# Look for any JPA configurations
rg -g '*.properties' -g '*.yml' 'spring.jpa|hibernate'

# Check exercise service implementation
rg -g '*.java' -A 10 'countByCourseIdGroupByType.*\{'

Length of output: 10824

src/main/java/de/tum/cit/aet/artemis/exercise/repository/ExerciseRepository.java (1)

632-647: Well-implemented query with good performance considerations!

The implementation efficiently retrieves exercise counts by type through a direct join from the course side, which is optimal given that there are fewer courses than exercises. The explicit type filtering and use of a strongly-typed DTO also ensures type safety.

src/main/java/de/tum/cit/aet/artemis/exercise/service/ExerciseService.java (1)

9-9: LGTM: Import statements are appropriate.

The added imports are necessary for the new functionality and follow the coding guidelines.

Also applies to: 67-67, 71-71

src/main/java/de/tum/cit/aet/artemis/core/service/CourseService.java (3)

99-99: Import statement added for ExerciseType

The import of ExerciseType is necessary for the new code additions and is appropriately included.


471-472: Extracted courseId for clarity and reuse

Defining courseId as a local variable improves readability and avoids multiple calls to course.getId().


489-490: Verified CourseDeletionSummaryDTO constructor parameters

The updated constructor parameters match the added counts, ensuring the deletion summary includes all necessary information.

@github-actions github-actions bot added the deployment-error Added by deployment workflows if an error occured label Nov 25, 2024
@sachmii sachmii added deploy:artemis-test1 and removed deployment-error Added by deployment workflows if an error occured labels Nov 25, 2024
@github-actions github-actions bot added the deployment-error Added by deployment workflows if an error occured label Nov 25, 2024
@sachmii sachmii removed the deployment-error Added by deployment workflows if an error occured label Nov 25, 2024
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 (1)
src/main/java/de/tum/cit/aet/artemis/exercise/service/ExerciseService.java (1)

836-847: Consider adding parameter validation and @NotNull annotation.

The implementation is clean and efficient, making good use of streams to transform the data. It properly handles cases where some exercise types have no exercises by defaulting to 0.

Consider these improvements:

  1. Add @NotNull annotation for the courseId parameter
  2. Add parameter validation to handle null courseId gracefully
-    public Map<ExerciseType, Long> countByCourseIdGroupByType(Long courseId) {
+    public Map<ExerciseType, Long> countByCourseIdGroupByType(@NotNull Long courseId) {
+        if (courseId == null) {
+            throw new IllegalArgumentException("courseId must not be null");
+        }
         Map<ExerciseType, Long> exerciseTypeCountMap = exerciseRepository.countByCourseIdGroupedByType(courseId).stream()
                 .collect(Collectors.toMap(ExerciseTypeCount::getExerciseType, ExerciseTypeCount::getCount));

         return Arrays.stream(ExerciseType.values()).collect(Collectors.toMap(type -> type, type -> exerciseTypeCountMap.getOrDefault(type, 0L)));
     }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between eaa817d and 19cc64d.

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

9-9: LGTM: Import statements are appropriate and well-organized.

The added imports are necessary for the new functionality and follow the project's conventions.

Also applies to: 67-67, 71-71

Copy link

github-actions bot commented Dec 3, 2024

There hasn't been any activity on this pull request recently. Therefore, this pull request has been automatically marked as stale and will be closed if no further activity occurs within seven days. Thank you for your contributions.

@github-actions github-actions bot added the stale label Dec 3, 2024
SimonEntholzer
SimonEntholzer previously approved these changes Jan 2, 2025
Copy link
Contributor

@SimonEntholzer SimonEntholzer left a comment

Choose a reason for hiding this comment

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

Works on Ts3 👍

coolchock
coolchock previously approved these changes Jan 2, 2025
Copy link
Contributor

@coolchock coolchock left a comment

Choose a reason for hiding this comment

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

re-approve, tested during testing session on ts3

muradium
muradium previously approved these changes Jan 2, 2025
Copy link
Contributor

@muradium muradium 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 TS3, values show correctly now

Copy link
Contributor

@SimonEntholzer SimonEntholzer left a comment

Choose a reason for hiding this comment

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

reapprove after renaming DAO to DTO

Copy link
Contributor

@coolchock coolchock left a comment

Choose a reason for hiding this comment

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

re-approve after renaming DAO to DTO

@krusche krusche merged commit afc50e8 into develop Jan 5, 2025
50 of 54 checks passed
@krusche krusche deleted the bugfix/course-deletion-summary-missing-values branch January 5, 2025 20:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
client Pull requests that update TypeScript code. (Added Automatically!) communication Pull requests that affect the corresponding module core Pull requests that affect the corresponding module exam Pull requests that affect the corresponding module exercise Pull requests that affect the corresponding module lecture Pull requests that affect the corresponding module ready for review server Pull requests that update Java code. (Added Automatically!) tests
Projects
Status: Merged
Status: Done
Development

Successfully merging this pull request may close these issues.

General: Course confirm delete operation does not display the correct numbers
9 participants