Skip to content

Adaptive learning: Add learner profile interface #10440

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

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

Conversation

N0W0RK
Copy link
Contributor

@N0W0RK N0W0RK commented Mar 4, 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 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.

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.
  • I added multiple integration tests (Jest) related to the features (with a high test coverage), while following the test guidelines.
  • I added authorities to all new routes and checked the course groups for displaying navigation elements (links, buttons).
  • I documented the TypeScript code using JSDoc style.
  • I added multiple screenshots/screencasts of my UI changes.
  • I translated all newly inserted strings into English and German.

Motivation and Context

#9673 added learner profiles and course specific learner profiles to Artemis. As they will impact the way Artemis interacts with the user, the user should have the ability to review and correct the profile.

Description

This PR adds a new menu entry in the user settings page. The user is presented with the values stored in his learner profile.

A new component, editable slider, was created that is able to show an initial and current state. It is further more able to enter an edit mode to set a new initial value if the user feels, the current state is incorrect.

The user is now able to select a course, review the lerner profile and adjust it according to their preferences.

Steps for Testing

Prerequisites:

  • TS5
  • Test Course Konrad Gößmann
  1. Log in to Artemis
  2. Navigate to settings
  3. Select menu entry Learner Profile
  4. Check that no changes can be made when no course is selected.
  5. Check that changes that are saved are also stored in the database and still visible client side even after changing course
  6. Check that aborted edits do not persist in any way.

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

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

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Performance Tests

  • Test 1

Test Coverage

Client

Class/File Line Coverage Confirmation (assert/expect)
learner-profile-api.service.ts 80%
double-slider.component.ts 75%
edit-process.component.ts 71.42%
editable-slider.component.ts 100%
course-learner-profile.component.ts 95.77%

Server

Class/File Line Coverage Confirmation (assert/expect)
CourseLearnerProfile.java 28%
CourseLearnerProfileDTO.java 0%
LearnerProfileResource.java 7%

Screenshots

grafik
An example course learner profile.
video
Editing the profile.

Summary by CodeRabbit

  • New Features
    • Introduced a new Learner Profile section accessible from user settings to view and update course-related profile settings.
    • Added an intuitive interface with course selection and interactive sliders for key profile parameters.
    • Added API endpoints to securely fetch and update course learner profiles for authenticated users.
    • Enhanced localization with new text labels and descriptions for learner profiles in English and German.

@N0W0RK N0W0RK requested a review from a team as a code owner March 4, 2025 16:39
@github-project-automation github-project-automation bot moved this to Work In Progress in Artemis Development Mar 4, 2025
@N0W0RK N0W0RK moved this from Work In Progress to Ready For Review in Artemis Development Mar 4, 2025
@github-actions github-actions bot added tests server Pull requests that update Java code. (Added Automatically!) client Pull requests that update TypeScript code. (Added Automatically!) atlas Pull requests that affect the corresponding module labels Mar 4, 2025
@N0W0RK N0W0RK added ready for review and removed tests server Pull requests that update Java code. (Added Automatically!) client Pull requests that update TypeScript code. (Added Automatically!) atlas Pull requests that affect the corresponding module labels Mar 4, 2025
@N0W0RK N0W0RK added this to Atlas Mar 4, 2025
@N0W0RK N0W0RK moved this to In review in Atlas Mar 4, 2025
@N0W0RK N0W0RK added tests server Pull requests that update Java code. (Added Automatically!) client Pull requests that update TypeScript code. (Added Automatically!) atlas Pull requests that affect the corresponding module labels Mar 4, 2025
Copy link
Contributor

coderabbitai bot commented Mar 4, 2025

Walkthrough

This pull request introduces new functionality for managing course learner profiles. On the backend side, it adds a constant to the domain model, a new DTO record with a helper method, an additional repository method using a custom query, and a REST controller exposing GET and PUT endpoints with validation. On the frontend, several new Angular components, services, and unit tests are added including a double-slider component, along with updated localization JSON files and routing adjustments to integrate learner profile management into the user settings.

Changes

File(s) Change Summary
src/main/java/de/tum/cit/aet/artemis/atlas/domain/profile/CourseLearnerProfile.java
src/main/java/de/tum/cit/aet/artemis/atlas/dto/CourseLearnerProfileDTO.java
Added a new constant (ENTITY_NAME) to the domain class and introduced the CourseLearnerProfileDTO record with five primitive fields and a static of() method for DTO creation.
src/main/java/de/tum/cit/aet/artemis/atlas/repository/CourseLearnerProfileRepository.java Added the findAllByLogin method with a custom query and updated annotations from @Profile to @Conditional(AtlasEnabled.class), including necessary import adjustments.
src/main/java/de/tum/cit/aet/artemis/atlas/web/LearnerProfileResource.java Added a new REST controller featuring GET and PUT endpoints for retrieving and updating course learner profiles with input validations and logging.
src/main/webapp/app/learner-profile/service/learner-profile-api.service.ts Introduced the LearnerProfileApiService class extending BaseApiHttpService, with asynchronous methods to get learner profiles for the current user and update a specified profile via HTTP GET and PUT requests.
src/main/webapp/i18n/{de,en}/learnerProfile.json
src/main/webapp/i18n/{de,en}/userSettings.json
Added new localization files for the learner profile feature in both German and English, and added the learnerProfile key to existing user settings files.
src/main/webapp/app/core/user/settings/learner-profile/{course-learner-profile.component.html, course-learner-profile.component.scss, course-learner-profile.component.ts, course-learner-profile.component.spec.ts}
src/main/webapp/app/core/user/settings/learner-profile/{learner-profile.component.html, learner-profile.component.ts}
src/main/webapp/app/core/user/settings/user-settings.route.ts
Added new Angular components and associated files for managing learner profiles, including a dedicated course learner profile component (with HTML, styles, and tests), a parent learner profile component, and a new route for accessing these features through user settings.
src/main/webapp/app/shared/double-slider/double-slider.component.{html, scss} Introduced a new double-slider component with HTML template and SCSS styles, enabling user input for profile parameters via dual range sliders.

Sequence Diagram(s)

GET Learner Profiles Sequence

sequenceDiagram
    participant U as User
    participant A as LearnerProfileApiService
    participant R as LearnerProfileResource
    participant Repo as CourseLearnerProfileRepository
    U->>A: getCourseLearnerProfilesForCurrentUser()
    A->>R: GET /atlas/course-learner-profiles
    R->>Repo: findAllByLogin(user.login)
    Repo-->>R: Set<CourseLearnerProfile>
    R->>R: Map entities to DTOs using CourseLearnerProfileDTO.of()
    R-->>A: Return Map of DTOs
    A-->>U: Promise with learner profiles
Loading

Update Learner Profile Sequence

sequenceDiagram
    participant U as User
    participant A as LearnerProfileApiService
    participant R as LearnerProfileResource
    participant Repo as CourseLearnerProfileRepository
    U->>A: putUpdatedCourseLearnerProfile(updatedProfileDTO)
    A->>R: PUT /atlas/course-learner-profiles/{id} with payload
    R->>R: Validate profile ID and field bounds
    R->>Repo: Update and save CourseLearnerProfile
    Repo-->>R: Persisted profile data
    R->>R: Map updated entity to DTO
    R-->>A: Return updated DTO
    A-->>U: Promise with updated learner profile
Loading

Suggested labels

feature, communication

Suggested reviewers

  • N0W0RK
  • krusche

📜 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 8e665f6 and 13f4a36.

📒 Files selected for processing (2)
  • src/main/webapp/i18n/de/userSettings.json (1 hunks)
  • src/main/webapp/i18n/en/userSettings.json (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/main/webapp/i18n/en/userSettings.json
  • src/main/webapp/i18n/de/userSettings.json
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Build .war artifact
  • GitHub Check: Build and Push Docker Image / Build Docker Image for ls1intum/artemis
  • GitHub Check: client-tests
  • GitHub Check: Build and Push Docker Image / Build Docker Image for ls1intum/artemis
  • GitHub Check: server-tests
  • GitHub Check: Analyse
  • GitHub Check: client-style
  • GitHub Check: client-tests-selected
  • GitHub Check: server-style
  • GitHub Check: Mend Security Check

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 8

🧹 Nitpick comments (25)
src/main/webapp/app/entities/learner-profile.model.ts (2)

1-7: Add JSDoc documentation to improve code clarity.

The CourseLearnerProfileDTO class lacks documentation explaining its purpose and the meaning of each property. Adding JSDoc comments would enhance code readability and maintainability.

+/**
+ * Data Transfer Object for Course Learner Profile.
+ * Represents a user's learning profile settings for a specific course.
+ */
 export class CourseLearnerProfileDTO {
+    /** Unique identifier for the learner profile */
     public id: number;
+    /** The associated course identifier */
     public courseId: number;
+    /** Indicates the user's goal for grade or bonus in the course (value range: typically 0-100) */
     public aimForGradeOrBonus: number;
+    /** Represents the user's planned time investment for the course (value range: typically 0-100) */
     public timeInvestment: number;
+    /** Indicates how intensely the user plans to review course materials (value range: typically 0-100) */
     public repetitionIntensity: number;
 }

1-7: Consider adding a constructor to initialize properties.

Adding a constructor would help ensure proper initialization of the DTO and provide a cleaner way to create new instances.

 export class CourseLearnerProfileDTO {
     public id: number;
     public courseId: number;
     public aimForGradeOrBonus: number;
     public timeInvestment: number;
     public repetitionIntensity: number;
+
+    constructor(
+        id?: number,
+        courseId?: number,
+        aimForGradeOrBonus?: number,
+        timeInvestment?: number,
+        repetitionIntensity?: number
+    ) {
+        this.id = id ?? 0;
+        this.courseId = courseId ?? 0;
+        this.aimForGradeOrBonus = aimForGradeOrBonus ?? 0;
+        this.timeInvestment = timeInvestment ?? 0;
+        this.repetitionIntensity = repetitionIntensity ?? 0;
+    }
 }
src/main/webapp/app/shared/user-settings/user-settings-container/user-settings-container.component.html (1)

22-49: Consider using @for instead of manually repeating navigation items.

Per the provided coding guidelines, @for (which replaces *ngFor) should be used instead of manually repeating similar elements. This would make the navigation bar more maintainable.

You could refactor this section to use an array of navigation items in the component class and iterate through them in the template:

 <section id="navigation-bar" class="list-group d-block pt-2">
     <span class="list-group-item disabled fw-bold" jhiTranslate="artemisApp.userSettings.userSettings"></span>
-    <a class="list-group-item btn btn-outline-primary" routerLink="account" routerLinkActive="active" jhiTranslate="artemisApp.userSettings.accountInformation"></a>
-    <a class="list-group-item btn btn-outline-primary" routerLink="profile" routerLinkActive="active" jhiTranslate="artemisApp.userSettings.learnerProfile"></a>
-    <a
-        class="list-group-item btn btn-outline-primary"
-        routerLink="notifications"
-        routerLinkActive="active"
-        jhiTranslate="artemisApp.userSettings.notificationSettings"
-    ></a>
-    <a class="list-group-item btn btn-outline-primary" routerLink="science" routerLinkActive="active" jhiTranslate="artemisApp.userSettings.scienceSettings"></a>
+    @for (navItem of basicNavItems; track navItem.route) {
+        <a 
+            class="list-group-item btn btn-outline-primary" 
+            [routerLink]="navItem.route" 
+            routerLinkActive="active" 
+            [jhiTranslate]="navItem.translationKey">
+        </a>
+    }
     @if (localVCEnabled) {
         <a class="list-group-item btn btn-outline-primary" routerLink="ssh" routerLinkActive="active" jhiTranslate="artemisApp.userSettings.sshSettings"></a>
         @if (isAtLeastTutor) {

In the component:

basicNavItems = [
    { route: 'account', translationKey: 'artemisApp.userSettings.accountInformation' },
    { route: 'profile', translationKey: 'artemisApp.userSettings.learnerProfile' },
    { route: 'notifications', translationKey: 'artemisApp.userSettings.notificationSettings' },
    { route: 'science', translationKey: 'artemisApp.userSettings.scienceSettings' },
];
src/main/webapp/i18n/de/userSettings.json (1)

11-11: Consider using "Lernerprofil" instead of "Lerner Profil".

In German, compound nouns are typically written as one word. The current translation "Lerner Profil" should be changed to "Lernerprofil" for better adherence to German language conventions.

-            "learnerProfile": "Lerner Profil",
+            "learnerProfile": "Lernerprofil",
src/main/webapp/app/shared/user-settings/learner-profile/learner-profile.component.ts (1)

8-8: Make standalone: true for better modularity.

Consider adding standalone: true to the component decorator to follow modern Angular practices and improve modularity.

    selector: 'jhi-learner-profile',
    templateUrl: './learner-profile.component.html',
    styleUrls: ['../user-settings.scss'],
-   imports: [CourseLearnerProfileComponent],
+   standalone: true,
+   imports: [CourseLearnerProfileComponent],
src/main/webapp/app/shared/editable-slider/edit-process.component.html (2)

3-3: Consider adding aria-labels for accessibility.

The icons used for saving and aborting actions should have aria-labels to improve accessibility for screen readers.

-        <span><fa-icon class="text-success mx-2" [icon]="faCheck" (click)="onSave()" /><fa-icon class="text-danger mx-2" [icon]="faXmark" (click)="onAbort()" /></span>
+        <span><fa-icon class="text-success mx-2" [icon]="faCheck" (click)="onSave()" aria-label="Save changes" /><fa-icon class="text-danger mx-2" [icon]="faXmark" (click)="onAbort()" aria-label="Cancel changes" /></span>

6-6: Add aria-label to edit icon for accessibility.

The pencil icon should have an aria-label for better accessibility.

-        <fa-icon class="mx-2" [icon]="faPencil" (click)="onEdit()" />
+        <fa-icon class="mx-2" [icon]="faPencil" (click)="onEdit()" aria-label="Edit" />
src/main/webapp/app/shared/editable-slider/editable-slider.component.html (1)

1-9: Appropriate implementation of reusable slider component.

The component has a clean structure with responsive layout using Bootstrap grid system. I appreciate the separation of concerns with dedicated components for edit process and double slider functionality.

One consideration: The line lengths in the double slider element (line 8) are quite long. Consider splitting the attributes across multiple lines for improved readability.

-    <jhi-double-slider [editStateTransition]="editStateTransition()" [currentValue]="currentValue()" [(initialValue)]="initialValue" [min]="min()" [max]="max()" />
+    <jhi-double-slider 
+        [editStateTransition]="editStateTransition()"
+        [currentValue]="currentValue()" 
+        [(initialValue)]="initialValue" 
+        [min]="min()" 
+        [max]="max()" 
+    />
src/main/webapp/app/shared/user-settings/learner-profile/course-learner-profile.component.html (2)

19-56: Component structure has a potential layout issue.

The slider components are wrapped in a grid with row-cols-2 but there are three slider components. This may cause unexpected layout behavior where the third slider might not align properly.

Either adjust the grid structure to accommodate three items per row:

-    <div class="row row-cols-2 gx-5 align-items-end">
+    <div class="row row-cols-3 gx-5 align-items-end">

Or if you intended to have two components per row with the third on the next row, no changes are needed, but consider adding a comment explaining this intention.


44-44: Inconsistent use of alignment classes.

Line 44 includes an align-items-end class on a column div, while other column divs don't have this class. This creates inconsistency in the layout. The align-items-end class should be applied to the row element if it needs to apply to all columns.

-        <div class="col align-items-end">
+        <div class="col">
src/main/webapp/app/shared/editable-slider/edit-process.component.ts (1)

31-44: Simplify the switch statement to improve readability.

The current implementation has redundant case clauses that could be simplified according to the static analysis. Since both TrySave and Abort transitions lead to the same behavior (setting editing = false), these cases can be combined.

ngOnChanges(changes: SimpleChanges): void {
    if (changes.editStateTransition) {
        switch (changes.editStateTransition.currentValue) {
            case EditStateTransition.Edit:
                this.editing = true;
                break;
-           case EditStateTransition.TrySave:
-           case EditStateTransition.Abort:
            default:
                this.editing = false;
                break;
        }
    }
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 37-37: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)


[error] 38-38: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)

src/main/webapp/app/learner-profile/service/learner-profile-api.service.ts (2)

11-13: Add await keyword for consistency in async method.

The putUpdatedCourseLearnerProfile method is declared as async but doesn't use await when calling the base put method, which is inconsistent with the getCourseLearnerProfilesForCurrentUser method. While it will still work, it's better to be consistent.

async putUpdatedCourseLearnerProfile(courseLearnerProfile: CourseLearnerProfileDTO): Promise<CourseLearnerProfileDTO> {
-   return this.put<CourseLearnerProfileDTO>(`atlas/course-learner-profiles/${courseLearnerProfile.id}`, courseLearnerProfile);
+   return await this.put<CourseLearnerProfileDTO>(`atlas/course-learner-profiles/${courseLearnerProfile.id}`, courseLearnerProfile);
}

1-14: Consider adding error handling for API calls.

The service methods don't include error handling. In a production environment, it's important to handle potential API errors gracefully.

async getCourseLearnerProfilesForCurrentUser(): Promise<Record<number, CourseLearnerProfileDTO>> {
-   return await this.get<Record<number, CourseLearnerProfileDTO>>('atlas/course-learner-profiles');
+   try {
+       return await this.get<Record<number, CourseLearnerProfileDTO>>('atlas/course-learner-profiles');
+   } catch (error) {
+       console.error('Failed to fetch learner profiles:', error);
+       throw error;
+   }
}

async putUpdatedCourseLearnerProfile(courseLearnerProfile: CourseLearnerProfileDTO): Promise<CourseLearnerProfileDTO> {
-   return this.put<CourseLearnerProfileDTO>(`atlas/course-learner-profiles/${courseLearnerProfile.id}`, courseLearnerProfile);
+   try {
+       return await this.put<CourseLearnerProfileDTO>(`atlas/course-learner-profiles/${courseLearnerProfile.id}`, courseLearnerProfile);
+   } catch (error) {
+       console.error('Failed to update learner profile:', error);
+       throw error;
+   }
}
src/test/javascript/spec/component/learner-profile/component/double-slider.component.spec.ts (2)

42-45: Use toBeTrue instead of toBeFalse for boolean assertions.

According to the coding guidelines, boolean assertions should use toBeTrue/toBeFalse instead of toBeTruthy/toBeFalsy.

it('should enable slider when editing', () => {
    component.onEdit();
-   expect(component.currentSlider().nativeElement.disabled).toBeFalse();
+   expect(component.currentSlider().nativeElement.disabled).toBeFalse();
});

Note: The code is already using toBeFalse() which aligns with the coding guidelines, so this is actually compliant. I initially thought it might be using toBeFalsy() which would have needed correction.


6-82: Consider adding accessibility tests.

The component involves UI interactions that should be accessible to all users. Consider adding tests that verify keyboard accessibility and ARIA attributes.

You could add tests like:

it('should be keyboard accessible', () => {
  // Setup component in edit mode
  component.onEdit();
  
  // Simulate keyboard interaction
  const event = new KeyboardEvent('keydown', { key: 'ArrowRight' });
  component.currentSlider().nativeElement.dispatchEvent(event);
  
  // Check if slider value changes appropriately
  // This would depend on your slider implementation
});

it('should have appropriate ARIA attributes', () => {
  // Check for aria-valuenow, aria-valuemin, aria-valuemax
  expect(component.currentSlider().nativeElement.getAttribute('aria-valuenow')).toBe(component.currentValue().toString());
  expect(component.currentSlider().nativeElement.getAttribute('aria-valuemin')).toBe(component.min().toString());
  expect(component.currentSlider().nativeElement.getAttribute('aria-valuemax')).toBe(component.max().toString());
});
src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts (5)

106-111: Remove duplicate await fixture.whenStable().

There's a duplicate call to await fixture.whenStable() which is unnecessary and may cause delays in test execution.

        fixture.detectChanges();
        await fixture.whenStable();
-       await fixture.whenStable();
        fixture.detectChanges();

117-121: Consider adding a return type to the selectCourse function.

Adding a return type to the utility function would improve code clarity and maintainability.

-    function selectCourse(id: number) {
+    function selectCourse(id: number): void {
        Array.from(selector.options).forEach((opt) => {
            opt.selected = opt.value == String(id);
        });
    }

137-145: Add type annotations to improve helper function readability.

The setupUpdateTest function could benefit from explicit type annotations for better clarity, especially since it returns a complex type.

-    function setupUpdateTest(course: number, updateFn: (value: number) => void, attribute: keyof CourseLearnerProfileDTO): CourseLearnerProfileDTO {
+    function setupUpdateTest(
+        course: number, 
+        updateFn: (value: number) => void, 
+        attribute: keyof CourseLearnerProfileDTO
+    ): CourseLearnerProfileDTO {
        let newVal = (profiles[course][attribute] + 1) % 5;
        let newProfile = profiles[course];
        newProfile[attribute] = newVal;
        component.activeCourse = course;

        updateFn(newVal);
        return newProfile;
    }

147-153: Add return type to helper function for consistency.

For consistency with other helper functions, consider adding a return type to validateUpdate.

-    function validateUpdate(course: number, profile: CourseLearnerProfileDTO) {
+    function validateUpdate(course: number, profile: CourseLearnerProfileDTO): void {
        const req = httpTesting.expectOne(`api/learner-profiles/course-learner-profiles/${course}`, 'Request to put new Profile');
        req.flush(profile);
        expect(putUpdatedCourseLearnerProfileSpy).toHaveBeenCalled();
        expect(putUpdatedCourseLearnerProfileSpy.mock.calls[0][0]).toEqual(profile);
        expect(component.courseLearnerProfiles[course]).toEqual(profile);
    }

155-165: Add return type to validateError function for consistency.

Similar to validateUpdate, add a return type to validateError for consistency.

-    function validateError(course: number, profile: CourseLearnerProfileDTO) {
+    function validateError(course: number, profile: CourseLearnerProfileDTO): void {
        const req = httpTesting.expectOne(`api/learner-profiles/course-learner-profiles/${course}`, 'Request to put new Profile');
        req.flush(errorBody, {
            headers: errorHeaders,
            status: 400,
            statusText: 'Bad Request',
        });
        expect(putUpdatedCourseLearnerProfileSpy).toHaveBeenCalled();
        expect(putUpdatedCourseLearnerProfileSpy.mock.calls[0][0]).toEqual(profile);
        expect(component.courseLearnerProfiles[course]).toEqual(profiles[course]);
    }
src/main/webapp/app/shared/user-settings/learner-profile/course-learner-profile.component.ts (1)

97-135: Consider refactoring repetitive update methods.

The three update methods (updateAimForGradeOrBonus, updateTimeInvestment, updateRepetitionIntensity) have very similar logic. Consider refactoring them into a single generic method to reduce code duplication.

+    private updateProfileAttribute(
+        value: number,
+        attribute: keyof CourseLearnerProfileDTO,
+        stateSignal: WritableSignal<EditStateTransition>
+    ): void {
+        // Return if value is changed without user trying to save
+        if (!this.courseLearnerProfiles || stateSignal() != EditStateTransition.TrySave) {
+            return;
+        }
+
+        // Try to update profile
+        const courseLearnerProfile = this.courseLearnerProfiles[this.activeCourse];
+        courseLearnerProfile[attribute] = value;
+        
+        this.learnerProfileAPIService.putUpdatedCourseLearnerProfile(courseLearnerProfile).then(
+            (updatedProfile) => {
+                // Update profile with response from server
+                this.courseLearnerProfiles[this.activeCourse] = updatedProfile;
+                stateSignal.set(EditStateTransition.Saved);
+            },
+            // Notify user of failure to update
+            (res: HttpErrorResponse) => this.onCourseLearnerProfileUpdateError(res, stateSignal)
+        );
+    }
+
+    updateAimForGradeOrBonus(value: number): void {
+        this.updateProfileAttribute(value, 'aimForGradeOrBonus', this.aimForGradeOrBonusState);
+    }
+
+    updateTimeInvestment(value: number): void {
+        this.updateProfileAttribute(value, 'timeInvestment', this.timeInvestmentState);
+    }
+
+    updateRepetitionIntensity(value: number): void {
+        this.updateProfileAttribute(value, 'repetitionIntensity', this.repetitionIntensityState);
+    }
src/main/java/de/tum/cit/aet/artemis/atlas/web/LearnerProfileResource.java (4)

53-53: Typographical fix: "which" instead of "wich"
The doc comment at line 53 has a minor typographical error in the word "wich." It should be "which" for clarity and correctness.

- * @return The ResponseEntity with status 200 (OK) and with body containing a map of DTOs, wich contain per course profile data.
+ * @return The ResponseEntity with status 200 (OK) and with body containing a map of DTOs, which contain per course profile data.

91-94: Typographical fix in error message key and text
"courseLEarnerProfileId" is misspelled (capital "L" rather than lowercase). To maintain consistency and clarity in your error messages, correct the spelling to "courseLearnerProfileId."

- throw new BadRequestAlertException("Provided courseLEarnerProfileId does not match CourseLearnerProfile.", 
+ throw new BadRequestAlertException("Provided courseLearnerProfileId does not match CourseLearnerProfile.", 

60-62: Potential performance consideration for large datasets
When querying many CourseLearnerProfiles, loading all records at once (via findAllByLogin) could be inefficient for users with many courses. If performance or memory usage becomes a concern, consider paginating or filtering based on active courses.


84-115: Concurrency caution for updates
When multiple clients update the same learner profile concurrently, the last writer wins. If you want to prevent race conditions or stale updates, consider an optimistic locking approach or a version field.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 93eba08 and aeb7c34.

📒 Files selected for processing (28)
  • src/main/java/de/tum/cit/aet/artemis/atlas/domain/profile/CourseLearnerProfile.java (1 hunks)
  • src/main/java/de/tum/cit/aet/artemis/atlas/dto/CourseLearnerProfileDTO.java (1 hunks)
  • src/main/java/de/tum/cit/aet/artemis/atlas/repository/CourseLearnerProfileRepository.java (2 hunks)
  • src/main/java/de/tum/cit/aet/artemis/atlas/web/LearnerProfileResource.java (1 hunks)
  • src/main/webapp/app/entities/learner-profile.model.ts (1 hunks)
  • src/main/webapp/app/learner-profile/service/learner-profile-api.service.ts (1 hunks)
  • src/main/webapp/app/shared/editable-slider/double-slider.component.html (1 hunks)
  • src/main/webapp/app/shared/editable-slider/double-slider.component.scss (1 hunks)
  • src/main/webapp/app/shared/editable-slider/double-slider.component.ts (1 hunks)
  • src/main/webapp/app/shared/editable-slider/edit-process.component.html (1 hunks)
  • src/main/webapp/app/shared/editable-slider/edit-process.component.scss (1 hunks)
  • src/main/webapp/app/shared/editable-slider/edit-process.component.ts (1 hunks)
  • src/main/webapp/app/shared/editable-slider/editable-slider.component.html (1 hunks)
  • src/main/webapp/app/shared/editable-slider/editable-slider.component.ts (1 hunks)
  • src/main/webapp/app/shared/user-settings/learner-profile/course-learner-profile.component.html (1 hunks)
  • src/main/webapp/app/shared/user-settings/learner-profile/course-learner-profile.component.scss (1 hunks)
  • src/main/webapp/app/shared/user-settings/learner-profile/course-learner-profile.component.ts (1 hunks)
  • src/main/webapp/app/shared/user-settings/learner-profile/learner-profile.component.html (1 hunks)
  • src/main/webapp/app/shared/user-settings/learner-profile/learner-profile.component.ts (1 hunks)
  • src/main/webapp/app/shared/user-settings/user-settings-container/user-settings-container.component.html (1 hunks)
  • src/main/webapp/app/shared/user-settings/user-settings.route.ts (1 hunks)
  • src/main/webapp/i18n/de/learnerProfile.json (1 hunks)
  • src/main/webapp/i18n/de/userSettings.json (1 hunks)
  • src/main/webapp/i18n/en/learnerProfile.json (1 hunks)
  • src/main/webapp/i18n/en/userSettings.json (1 hunks)
  • src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts (1 hunks)
  • src/test/javascript/spec/component/learner-profile/component/double-slider.component.spec.ts (1 hunks)
  • src/test/javascript/spec/component/learner-profile/component/edit-process.component.spec.ts (1 hunks)
✅ Files skipped from review due to trivial changes (7)
  • src/main/webapp/app/shared/user-settings/learner-profile/learner-profile.component.html
  • src/main/java/de/tum/cit/aet/artemis/atlas/domain/profile/CourseLearnerProfile.java
  • src/main/webapp/app/shared/editable-slider/double-slider.component.html
  • src/main/webapp/i18n/de/learnerProfile.json
  • src/main/webapp/app/shared/editable-slider/edit-process.component.scss
  • src/main/webapp/i18n/en/learnerProfile.json
  • src/main/webapp/app/shared/user-settings/learner-profile/course-learner-profile.component.scss
🧰 Additional context used
📓 Path-based instructions (5)
`src/main/webapp/**/*.ts`: angular_style:https://angular.io/...

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/learner-profile.model.ts
  • src/main/webapp/app/shared/user-settings/learner-profile/learner-profile.component.ts
  • src/main/webapp/app/shared/user-settings/user-settings.route.ts
  • src/main/webapp/app/shared/editable-slider/editable-slider.component.ts
  • src/main/webapp/app/shared/editable-slider/double-slider.component.ts
  • src/main/webapp/app/learner-profile/service/learner-profile-api.service.ts
  • src/main/webapp/app/shared/editable-slider/edit-process.component.ts
  • src/main/webapp/app/shared/user-settings/learner-profile/course-learner-profile.component.ts
`src/main/webapp/i18n/de/**/*.json`: German language transla...

src/main/webapp/i18n/de/**/*.json: German language translations should be informal (dutzen) and should never be formal (sietzen). So the user should always be addressed with "du/dein" and never with "sie/ihr".

  • src/main/webapp/i18n/de/userSettings.json
`src/main/webapp/**/*.html`: @if and @for are new and valid ...

src/main/webapp/**/*.html: @if and @for are new and valid Angular syntax replacing *ngIf and *ngFor. They should always be used over the old style.

  • src/main/webapp/app/shared/user-settings/user-settings-container/user-settings-container.component.html
  • src/main/webapp/app/shared/editable-slider/edit-process.component.html
  • src/main/webapp/app/shared/editable-slider/editable-slider.component.html
  • src/main/webapp/app/shared/user-settings/learner-profile/course-learner-profile.component.html
`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/atlas/dto/CourseLearnerProfileDTO.java
  • src/main/java/de/tum/cit/aet/artemis/atlas/repository/CourseLearnerProfileRepository.java
  • src/main/java/de/tum/cit/aet/artemis/atlas/web/LearnerProfileResource.java
`src/test/javascript/spec/**/*.ts`: jest: true; mock: NgMock...

src/test/javascript/spec/**/*.ts: jest: true; mock: NgMocks; bad_practices: avoid_full_module_import; perf_improvements: mock_irrelevant_deps; service_testing: mock_http_for_logic; no_schema: avoid_NO_ERRORS_SCHEMA; expectation_specificity: true; solutions: {boolean: toBeTrue/False, reference: toBe, existence: toBeNull/NotNull, undefined: toBeUndefined, class_obj: toContainEntries/toEqual, spy_calls: {not_called: not.toHaveBeenCalled, once: toHaveBeenCalledOnce, with_value: toHaveBeenCalledWith|toHaveBeenCalledExactlyOnceWith}}

  • src/test/javascript/spec/component/learner-profile/component/double-slider.component.spec.ts
  • src/test/javascript/spec/component/learner-profile/component/edit-process.component.spec.ts
  • src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts
🪛 Biome (1.9.4)
src/main/webapp/app/shared/editable-slider/edit-process.component.ts

[error] 37-37: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)


[error] 38-38: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)

🪛 GitHub Check: client-tests-selected
src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts

[failure] 4-4:
Cannot find module 'app/atlas/service/learner-profile-api.service' or its corresponding type declarations.

🪛 GitHub Check: client-tests
src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts

[failure] 4-4:
Cannot find module 'app/atlas/service/learner-profile-api.service' or its corresponding type declarations.

⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Call Build Workflow / Build .war artifact
  • GitHub Check: Call Build Workflow / Build and Push Docker Image
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: client-style
  • GitHub Check: server-style
  • GitHub Check: server-tests
  • GitHub Check: Analyse
🔇 Additional comments (45)
src/main/webapp/i18n/en/userSettings.json (1)

11-11: LGTM! Appropriate translation key added for the learner profile.

The addition of the "learnerProfile" key is consistent with the established pattern in the localization file and properly aligns with the new Learner Profile feature being added to the user settings.

src/main/webapp/app/shared/user-settings/user-settings.route.ts (1)

28-34: LGTM! The route configuration follows Angular best practices.

The implementation correctly uses lazy loading for the LearnerProfileComponent, which aligns with the coding guidelines. The route definition is properly structured with the appropriate path and page title.

src/main/webapp/app/shared/user-settings/user-settings-container/user-settings-container.component.html (1)

25-25: LGTM! The navigation link follows consistent UI patterns.

The new learner profile navigation link correctly implements the same styling and structure as other navigation links in the settings menu. It properly uses the Angular router directive and the translation pipe for localization.

src/main/webapp/app/shared/user-settings/learner-profile/learner-profile.component.ts (1)

1-10: Component implementation looks good.

The component is correctly defined as a shell that hosts the CourseLearnerProfileComponent. The implementation follows Angular's best practices with proper component metadata configuration.

src/main/webapp/app/shared/editable-slider/editable-slider.component.ts (1)

1-19: Well-structured component with correct use of input() and model() APIs.

The component is cleanly implemented using Angular's modern input() and model() APIs. All inputs are properly typed, and the component is correctly defined as standalone with its dependencies imported.

src/main/webapp/app/shared/editable-slider/edit-process.component.html (1)

1-8: Properly implemented HTML template with conditional styling.

The template uses ngClass appropriately for conditional styling and maintains good structure for showing different icons based on the editing state.

src/main/java/de/tum/cit/aet/artemis/atlas/repository/CourseLearnerProfileRepository.java (1)

34-40: Well-structured query for retrieving learner profiles by login.

The JPQL query is well-formed, respects SQL standards with uppercase keywords, and uses the proper @Param annotation for parameters. The method returns a Set which is an appropriate choice when duplicates aren't expected and uniqueness matters.

src/main/java/de/tum/cit/aet/artemis/atlas/dto/CourseLearnerProfileDTO.java (1)

7-8: Good use of Java record for DTO with clear fields.

The record definition follows the guidelines for DTOs with appropriate use of primitive types and meaningful field names in CamelCase.

src/main/webapp/app/shared/user-settings/learner-profile/course-learner-profile.component.html (2)

3-8: Correctly implemented course selection with modern Angular syntax.

The select element properly uses the new @for directive rather than the older *ngFor as required by the coding guidelines. The track expression is correctly set to course.id for optimal rendering performance.


12-17: Good use of legend for explaining slider states.

The legend clearly explains the meaning of the different colored dots, enhancing user experience through proper visual feedback.

src/main/webapp/app/shared/editable-slider/edit-process.component.ts (3)

7-12: Good enum definition with clear state transitions.

The EditStateTransition enum has well-defined states that reflect a complete editing workflow: initiating an edit, attempting to save, confirming a save, and aborting the operation.


21-24: Good use of Angular's modern signal-based APIs.

The component properly uses the new signal-based APIs (model and input) for reactive data binding, which is in line with current Angular best practices.


46-62: Good implementation of action methods with proper disabled state checks.

The onEdit, onSave, and onAbort methods correctly check if the component is disabled before performing any action, which prevents unexpected state changes when the component should be inactive.

src/main/webapp/app/learner-profile/service/learner-profile-api.service.ts (1)

7-9: Good implementation of profile retrieval method.

The method correctly uses the get method from the base service with proper typing to fetch course learner profiles.

src/main/webapp/app/shared/editable-slider/double-slider.component.ts (2)

23-29: Good implementation of edit mode with proper class manipulation.

The onEdit method correctly enables the slider, adds the editing class to the parent container, and updates the current and initial values from their respective signals.


48-65: Well-structured state management in ngOnChanges.

The ngOnChanges method correctly handles all possible state transitions by routing them to the appropriate handler methods. This is a clean approach to responding to external state changes.

src/test/javascript/spec/component/learner-profile/component/double-slider.component.spec.ts (3)

16-27: Good test setup with proper component initialization.

The test correctly configures the component with all required inputs using the TestBed and ComponentFixture APIs.


33-40: Well-structured initialization test with appropriate assertions.

The test properly verifies that all component inputs are set correctly after initialization.


72-81: Comprehensive test for the full edit-save workflow.

This test effectively verifies the complete edit-save workflow, ensuring that changes persist correctly after a successful save operation. The assertions are clear and cover both the model update and the UI state.

src/test/javascript/spec/component/learner-profile/component/edit-process.component.spec.ts (7)

1-10: Appropriate imports and setup for the EditProcessComponent test.

The imports are correctly structured, including Angular's testing utilities and the component under test with its associated type.


11-18: Well-structured test environment setup.

The beforeEach block correctly configures the TestBed and initializes the component with the necessary input.


20-22: Good test cleanup practice.

Using jest.restoreAllMocks() in afterEach ensures that all mocks are restored after each test, preventing test pollution.


24-28: Complete initialization test.

The test properly verifies component creation, initial state of editStateTransition, and the disabled state.


30-35: Well-structured async test for edit state transition.

The test correctly verifies the state transition to Edit mode, including proper use of autoDetectChanges and awaiting stability.


37-42: Appropriate test for abort state transition.

The test correctly verifies the state transition to Abort mode, following the same pattern as the previous test.


44-50: Consistent testing approach for save state transition.

This test maintains the same pattern as the other state transition tests, ensuring consistency in test structure.

src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts (4)

167-179: Well-structured test setup for PUT requests.

The test setup correctly modifies the edit state for all edit process components and ensures cleanup after tests.


180-190: Thorough testing of aimForGradeOrBonus updates.

The tests cover both success and error cases for updating the aimForGradeOrBonus attribute.


192-202: Complete tests for timeInvestment updates.

The tests appropriately validate both successful and failed updates to the timeInvestment attribute.


204-214: Comprehensive tests for repetitionIntensity updates.

The tests thoroughly verify the behavior for both successful and failed updates to the repetitionIntensity attribute.

src/main/webapp/app/shared/editable-slider/double-slider.component.scss (7)

1-4: Appropriate base styling for slider control.

The .sliders_control class provides a good foundational styling with proper positioning and spacing.


6-19: Cross-browser compatible styling for slider thumbs.

The styles properly handle different browser-specific pseudo-elements for range inputs, ensuring consistent behavior across browsers.


20-28: Consistent primary color for current slider thumb.

Using var(--primary) ensures the component adheres to the application's theme and remains consistent with design guidelines.


30-35: Improved usability for number inputs.

Making the spin buttons fully visible improves the user experience by providing clear visual cues for incrementing/decrementing values.


37-44: Appropriate positioning and interaction handling for range inputs.

The absolute positioning of range inputs and z-index management ensures proper layering of the UI elements.


46-48: Good visual separation for non-editing mode.

Making the track background transparent when not in editing mode helps users distinguish between editable and non-editable states.


50-52: Clean UI by hiding unnecessary elements during editing.

Hiding the initial slider during editing maintains a clean interface and prevents user confusion.

src/main/webapp/app/shared/user-settings/learner-profile/course-learner-profile.component.ts (7)

1-12: Appropriate imports and dependencies.

The component correctly imports the necessary Angular and application-specific modules needed for its functionality.


13-19: Well-structured component definition with proper imports.

The component is correctly defined with appropriate selector, template, styles, and imported components.


20-24: Good use of dependency injection.

Using Angular's inject function for dependency injection follows modern Angular practices.


38-42: Asynchronous initialization is properly implemented.

The ngOnInit method correctly uses async/await syntax for loading profiles before loading courses.


64-75: Proper error handling implementation.

The error handling method correctly extracts error information and displays appropriate alerts to the user.


77-95: Well-implemented update method with error handling.

The updateAimForGradeOrBonus method includes proper state checking, updates the profile, and handles both success and error cases.


137-139: Efficient profile loading implementation.

The loadProfiles method correctly uses async/await to retrieve all profiles in a single API call.

src/main/java/de/tum/cit/aet/artemis/atlas/web/LearnerProfileResource.java (1)

71-75: Good practice: Field boundary checks
The validateProfileField method is a clean way to ensure that fields remain within defined bounds. This helps guard against invalid data and keeps the logic DRY.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (8)
src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts (8)

42-45: Use const for immutable variables.

The errorHeaders variable is declared with let but is never reassigned. Use const for immutable variables to prevent accidental reassignment.

-    let errorHeaders = {
+    const errorHeaders = {
        'x-artemisapp-error': 'error.courseLearnerProfileNotFound',
        'x-artemisapp-params': 'courseLearnerProfile',
    };

108-109: Eliminate redundant whenStable() calls.

There are two consecutive calls to fixture.whenStable() which is redundant. A single call is sufficient to wait for all async operations to complete.

        fixture.detectChanges();
        await fixture.whenStable();
-        await fixture.whenStable();
        fixture.detectChanges();

125-126: Use consistent assertion methods.

The test uses both toStrictEqual and toEqual for object comparisons. It's better to consistently use toStrictEqual for more precise equality checks (including property types and object structure).

        expect(component).toBeTruthy();
        expect(component.courses).toStrictEqual(courses);
-        expect(component.courseLearnerProfiles).toEqual(profiles);
+        expect(component.courseLearnerProfiles).toStrictEqual(profiles);

131-134: Use TypeScript's strong typing for event objects.

The event object is created as a generic Event, but it would be more type-safe to use specific event types when available.

        selectCourse(course);
-        let changeEvent = new Event('change', { bubbles: true, cancelable: false });
+        const changeEvent = new Event('change', { bubbles: true, cancelable: false }) as Event;
        selector.dispatchEvent(changeEvent);
        expect(component.activeCourse).toBe(course);

137-141: Improve type safety in helper function.

The setupUpdateTest function lacks type annotations for its return value and some parameters. Adding these improves code readability and catches type errors early.

-    function setupUpdateTest(course: number, updateFn: (value: number) => void, attribute: keyof CourseLearnerProfileDTO): CourseLearnerProfileDTO {
-        let newVal = (profiles[course][attribute] + 1) % 5;
-        let newProfile = profiles[course];
+    function setupUpdateTest(course: number, updateFn: (value: number) => void, attribute: keyof CourseLearnerProfileDTO): CourseLearnerProfileDTO {
+        const newVal = (profiles[course][attribute] + 1) % 5;
+        const newProfile: CourseLearnerProfileDTO = { ...profiles[course] };
         newProfile[attribute] = newVal;
         component.activeCourse = course;

150-151: Use more specific spy assertions.

The test checks if the spy was called but doesn't verify it was called exactly once. Using toHaveBeenCalledTimes(1) or toHaveBeenCalledExactlyOnceWith provides stronger assertions.

        req.flush(profile);
-        expect(putUpdatedCourseLearnerProfileSpy).toHaveBeenCalled();
-        expect(putUpdatedCourseLearnerProfileSpy.mock.calls[0][0]).toEqual(profile);
+        expect(putUpdatedCourseLearnerProfileSpy).toHaveBeenCalledTimes(1);
+        expect(putUpdatedCourseLearnerProfileSpy).toHaveBeenCalledWith(profile);
        expect(component.courseLearnerProfiles[course]).toEqual(profile);

162-164: Use more specific spy assertions in error validation.

Similar to the success case, use more specific assertions for spy calls in error validation.

        });
-        expect(putUpdatedCourseLearnerProfileSpy).toHaveBeenCalled();
-        expect(putUpdatedCourseLearnerProfileSpy.mock.calls[0][0]).toEqual(profile);
+        expect(putUpdatedCourseLearnerProfileSpy).toHaveBeenCalledTimes(1);
+        expect(putUpdatedCourseLearnerProfileSpy).toHaveBeenCalledWith(profile);
        expect(component.courseLearnerProfiles[course]).toEqual(profiles[course]);

180-184: Test cases use hardcoded course IDs.

The test cases use a hardcoded course ID (1) while there are multiple courses defined. Consider using a more robust approach by iterating through available courses or using test.each for parameterized tests.

Instead of hardcoding course ID 1, you could use a more robust approach:

-        it('should update aimForGradeOrBonus on successful request', () => {
-            let course = 1;
-            let newProfile = setupUpdateTest(course, component.updateAimForGradeOrBonus.bind(component), 'aimForGradeOrBonus');
-            validateUpdate(course, newProfile);
-        });
+        it.each([1, 2])('should update aimForGradeOrBonus on successful request for course %i', (courseId) => {
+            const newProfile = setupUpdateTest(courseId, component.updateAimForGradeOrBonus.bind(component), 'aimForGradeOrBonus');
+            validateUpdate(courseId, newProfile);
+        });

This pattern can be applied to all similar test cases for more comprehensive coverage.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between aeb7c34 and 3b83402.

📒 Files selected for processing (1)
  • src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`src/test/javascript/spec/**/*.ts`: jest: true; mock: NgMock...

src/test/javascript/spec/**/*.ts: jest: true; mock: NgMocks; bad_practices: avoid_full_module_import; perf_improvements: mock_irrelevant_deps; service_testing: mock_http_for_logic; no_schema: avoid_NO_ERRORS_SCHEMA; expectation_specificity: true; solutions: {boolean: toBeTrue/False, reference: toBe, existence: toBeNull/NotNull, undefined: toBeUndefined, class_obj: toContainEntries/toEqual, spy_calls: {not_called: not.toHaveBeenCalled, once: toHaveBeenCalledOnce, with_value: toHaveBeenCalledWith|toHaveBeenCalledExactlyOnceWith}}

  • src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Call Build Workflow / Build .war artifact
  • GitHub Check: Call Build Workflow / Build and Push Docker Image
  • GitHub Check: client-tests
  • GitHub Check: server-tests
  • GitHub Check: Analyse
🔇 Additional comments (1)
src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts (1)

76-77: Remove duplicate AlertService provider.

There are two different providers for AlertService which is redundant and may cause unexpected behavior.

            providers: [
                { provide: SessionStorageService, useClass: MockSyncStorage },
-               MockProvider(AlertService),
                { provide: AlertService, useClass: MockAlertService },
                { provide: TranslateService, useClass: MockTranslateService },
                provideHttpClient(),
                provideHttpClientTesting(),
            ],

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (2)
src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts (2)

75-77: ⚠️ Potential issue

Remove duplicate AlertService provider.

There are two providers for AlertService which can cause unexpected behavior. One should be removed.

providers: [
    { provide: SessionStorageService, useClass: MockSyncStorage },
-   MockProvider(AlertService),
    { provide: AlertService, useClass: MockAlertService },
    { provide: TranslateService, useClass: MockTranslateService },
    provideHttpClient(),
    provideHttpClientTesting(),
],

155-165: 🛠️ Refactor suggestion

Update API endpoint path and verify AlertService error handling.

The API endpoint path should be consistent, and the error handling verification should check that AlertService is called with the error message.

function validateError(course: number, profile: CourseLearnerProfileDTO) {
-   const req = httpTesting.expectOne(`api/atlas/learner-profiles/course-learner-profiles/${course}`, 'Request to put new Profile');
+   const req = httpTesting.expectOne(`api/learner-profiles/course-learner-profiles/${course}`, 'Request to put new Profile');
    req.flush(errorBody, {
        headers: errorHeaders,
        status: 400,
        statusText: 'Bad Request',
    });
-   expect(putUpdatedCourseLearnerProfileSpy).toHaveBeenCalled();
+   expect(putUpdatedCourseLearnerProfileSpy).toHaveBeenCalledOnce();
-   expect(putUpdatedCourseLearnerProfileSpy.mock.calls[0][0]).toEqual(profile);
+   expect(putUpdatedCourseLearnerProfileSpy).toHaveBeenCalledWith(profile);
    expect(component.courseLearnerProfiles[course]).toEqual(profiles[course]);
+   const alertService = TestBed.inject(AlertService);
+   expect(alertService.error).toHaveBeenCalledWith(errorBody.message, errorBody.params);
}
🧹 Nitpick comments (5)
src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts (5)

108-110: Remove redundant await fixture.whenStable() call.

Two consecutive calls to fixture.whenStable() are unnecessary as this method returns a promise that resolves when all pending asynchronous activities are complete.

await fixture.whenStable();
-await fixture.whenStable();
fixture.detectChanges();

123-125: Use toBeTrue() instead of toBeTruthy() for boolean assertions.

According to coding guidelines, boolean assertions should use toBeTrue() or toBeFalse() instead of toBeTruthy() for more specific and clearer expectations.

it('should initialize', () => {
-   expect(component).toBeTruthy();
+   expect(component).toBeTrue();
    expect(component.courses).toStrictEqual(courses);
    expect(component.courseLearnerProfiles).toEqual(profiles);
});

129-135: Use const instead of let for constants and improve boolean comparison.

Variables that aren't reassigned should use const instead of let. Also, the comparison in the selectCourse function should use === for strict equality.

it('should select active course', () => {
-   let course = 1;
+   const course = 1;
    selectCourse(course);
-   let changeEvent = new Event('change', { bubbles: true, cancelable: false });
+   const changeEvent = new Event('change', { bubbles: true, cancelable: false });
    selector.dispatchEvent(changeEvent);
    expect(component.activeCourse).toBe(course);
});

function selectCourse(id: number) {
    Array.from(selector.options).forEach((opt) => {
-       opt.selected = opt.value == String(id);
+       opt.selected = opt.value === String(id);
    });
}

167-215: Add test for edit mode cancellation.

The test suite initializes edit mode and tests the update functionality, but there's no test to verify that cancelling an edit correctly reverts the values without making a PUT request.

Consider adding a test that:

  1. Enters edit mode
  2. Changes a value
  3. Triggers a cancel action
  4. Verifies that no PUT request is made
  5. Confirms the value is reverted to the original
it('should not update values when edit is cancelled', () => {
    const course = 1;
    component.activeCourse = course;
    const originalValue = profiles[course].aimForGradeOrBonus;
    const newValue = (originalValue + 1) % 5;
    
    // Enter edit mode
    editProcessComponents[0].editStateTransition.set(EditStateTransition.EnterEdit);
    fixture.detectChanges();
    
    // Change value
    component.updateAimForGradeOrBonus(newValue);
    
    // Cancel edit
    editProcessComponents[0].editStateTransition.set(EditStateTransition.Abort);
    fixture.detectChanges();
    
    // Verify no request made
    httpTesting.expectNone(`api/learner-profiles/course-learner-profiles/${course}`);
    expect(putUpdatedCourseLearnerProfileSpy).not.toHaveBeenCalled();
    
    // Verify value reverted
    expect(component.courseLearnerProfiles[course].aimForGradeOrBonus).toBe(originalValue);
});

180-184: Use const instead of let for constants in test cases.

Variables that aren't reassigned should use const instead of let in all test cases.

it('should update aimForGradeOrBonus on successful request', () => {
-   let course = 1;
-   let newProfile = setupUpdateTest(course, component.updateAimForGradeOrBonus.bind(component), 'aimForGradeOrBonus');
+   const course = 1;
+   const newProfile = setupUpdateTest(course, component.updateAimForGradeOrBonus.bind(component), 'aimForGradeOrBonus');
    validateUpdate(course, newProfile);
});

Make similar changes in all other test cases.

Also applies to: 192-196, 204-208

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3b83402 and b584591.

📒 Files selected for processing (1)
  • src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`src/test/javascript/spec/**/*.ts`: jest: true; mock: NgMock...

src/test/javascript/spec/**/*.ts: jest: true; mock: NgMocks; bad_practices: avoid_full_module_import; perf_improvements: mock_irrelevant_deps; service_testing: mock_http_for_logic; no_schema: avoid_NO_ERRORS_SCHEMA; expectation_specificity: true; solutions: {boolean: toBeTrue/False, reference: toBe, existence: toBeNull/NotNull, undefined: toBeUndefined, class_obj: toContainEntries/toEqual, spy_calls: {not_called: not.toHaveBeenCalled, once: toHaveBeenCalledOnce, with_value: toHaveBeenCalledWith|toHaveBeenCalledExactlyOnceWith}}

  • src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Call Build Workflow / Build .war artifact
  • GitHub Check: Call Build Workflow / Build and Push Docker Image
  • GitHub Check: client-tests
  • GitHub Check: server-tests
  • GitHub Check: Analyse

@helios-aet helios-aet bot temporarily deployed to artemis-test1.artemis.cit.tum.de March 4, 2025 17:25 Inactive
Copy link

End-to-End (E2E) Test Results Summary

TestsPassed ☑️Skipped ⚠️Failed ❌️Time ⏱
End-to-End (E2E) Test Report201 ran197 passed3 skipped1 failed50m 8s 924ms
TestResultTime ⏱
End-to-End (E2E) Test Report
e2e/exercise/programming/ProgrammingExerciseStaticCodeAnalysis.spec.ts
ts.Static code analysis tests › Configures SCA grading and makes a successful submission with SCA errors❌ failure1m 53s 157ms

@helios-aet helios-aet bot temporarily deployed to artemis-test3.artemis.cit.tum.de April 15, 2025 11:16 Inactive
@helios-aet helios-aet bot temporarily deployed to artemis-test5.artemis.cit.tum.de April 15, 2025 18:28 Inactive
@helios-aet helios-aet bot temporarily deployed to artemis-test5.artemis.cit.tum.de April 16, 2025 07:40 Inactive
ahmetsenturk
ahmetsenturk previously approved these changes Apr 16, 2025
Copy link
Contributor

@ahmetsenturk ahmetsenturk 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 - functionality works as described, pretty cool addition 😊

tobias-lippert
tobias-lippert previously approved these changes Apr 17, 2025
Copy link
Contributor

@tobias-lippert tobias-lippert left a comment

Choose a reason for hiding this comment

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

code

…-interface

# Conflicts:
#	src/main/webapp/app/core/user/settings/user-settings-container/user-settings-container.component.html
#	src/main/webapp/app/core/user/settings/user-settings.route.ts
@N0W0RK N0W0RK dismissed stale reviews from tobias-lippert and ahmetsenturk via 2ee85e6 April 18, 2025 17:10
ahmetsenturk
ahmetsenturk previously approved these changes Apr 18, 2025
Copy link
Contributor

@ahmetsenturk ahmetsenturk 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 merge commit

Copy link

End-to-End (E2E) Test Results Summary

TestsPassed ☑️Skipped ⚠️Failed ❌️Time ⏱
End-to-End (E2E) Test Report201 ran197 passed3 skipped1 failed49m 4s 670ms
TestResultTime ⏱
End-to-End (E2E) Test Report
e2e/course/CourseMessages.spec.ts
ts.Course messages › Channel messages › Write/edit/delete message in channel › Student should be able to edit message in channel❌ failure28s 580ms

Copy link

End-to-End (E2E) Test Results Summary

TestsPassed ☑️Skipped ⚠️Failed ❌️Time ⏱
End-to-End (E2E) Test Report201 ran196 passed3 skipped2 failed53m 11s 100ms
TestResultTime ⏱
End-to-End (E2E) Test Report
e2e/course/CourseMessages.spec.ts
ts.Course messages › Channel messages › Write/edit/delete message in channel › Student should be able to edit message in channel❌ failure2m 3s 370ms
e2e/exercise/programming/ProgrammingExerciseStaticCodeAnalysis.spec.ts
ts.Static code analysis tests › Configures SCA grading and makes a successful submission with SCA errors❌ failure1m 48s 483ms

Copy link

End-to-End (E2E) Test Results Summary

TestsPassed ☑️Skipped ⚠️Failed ❌️Time ⏱
End-to-End (E2E) Test Report201 ran195 passed3 skipped3 failed51m 10s 123ms
TestResultTime ⏱
End-to-End (E2E) Test Report
e2e/course/CourseMessages.spec.ts
ts.Course messages › Channel messages › Write/edit/delete message in channel › Student should be able to edit message in channel❌ failure2m 2s 782ms
e2e/exam/ExamParticipation.spec.ts
ts.Exam participation › Early hand-in with continue and reload page › Participates in the exam, hand-in early, but instead continues❌ failure51s 193ms
e2e/exercise/programming/ProgrammingExerciseStaticCodeAnalysis.spec.ts
ts.Static code analysis tests › Configures SCA grading and makes a successful submission with SCA errors❌ failure1m 44s 268ms

Copy link
Contributor

@florian-glombik florian-glombik left a comment

Choose a reason for hiding this comment

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

I think there are some smaller issues and inaccuracies that should be addressed, in general the code looks good and no major changes required 👍

Also note that the files of course-learner-profile.component should be grouped within a folder in /learner-profile

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/main/java/de/tum/cit/aet/artemis/atlas/web/LearnerProfileResource.java (1)

36-41: Rename constants to be more domain-specific

The current constants MIN_PROFILE_VALUE and MAX_PROFILE_VALUE lack clarity about what domain concept they represent. Since these represent bounds on a Likert scale as indicated in your JavaDoc, consider renaming them to be more descriptive.

-    private static final int MIN_PROFILE_VALUE = 1;
+    private static final int MIN_LIKERT_SCALE_VALUE = 1;

     /**
      * Maximum value allowed for profile fields representing values on a Likert scale.
      */
-    private static final int MAX_PROFILE_VALUE = 5;
+    private static final int MAX_LIKERT_SCALE_VALUE = 5;

Remember to update the references to these constants in the validateProfileField method as well.

🧹 Nitpick comments (5)
src/main/java/de/tum/cit/aet/artemis/atlas/web/LearnerProfileResource.java (5)

65-67: Consider performance optimization for large datasets

The current implementation loads all profiles for a user and then streams them into a map. This approach works fine for small datasets but might cause performance issues if a user has many course profiles.

Consider modifying the repository method to directly return the data in the required format to avoid loading all profiles into memory first.


77-79: Update constant references after renaming

If you rename the min and max constants as suggested earlier, remember to update references here.

-        if (value < MIN_PROFILE_VALUE || value > MAX_PROFILE_VALUE) {
+        if (value < MIN_LIKERT_SCALE_VALUE || value > MAX_LIKERT_SCALE_VALUE) {

89-120: Consider extracting business logic to a service layer

The controller is currently handling business logic directly. According to REST best practices and the single responsibility principle, controllers should delegate business logic to service classes.

Extract the validation and update logic to a LearnerProfileService class to improve separation of concerns and maintainability.


97-98: Fix typo in error message

There's a small typo in the error message parameter.

-            throw new BadRequestAlertException("Provided courseLEarnerProfileId does not match CourseLearnerProfile.", CourseLearnerProfile.ENTITY_NAME, "objectDoesNotMatchId",
+            throw new BadRequestAlertException("Provided courseLearnerProfileId does not match CourseLearnerProfile.", CourseLearnerProfile.ENTITY_NAME, "objectDoesNotMatchId",

54-68: Improve JavaDoc to better describe method purpose

The current JavaDoc states this is a GET endpoint but doesn't clearly describe its purpose. Consider enhancing the documentation to better explain what this endpoint achieves for the user.

     /**
-     * GET /learner-profiles/course-learner-profiles : get a Map of a {@link de.tum.cit.aet.artemis.core.domain.Course} id
-     * to the corresponding {@link CourseLearnerProfile} of the logged-in user.
+     * Retrieves all learner profiles for the currently authenticated user across all courses.
+     * 
+     * GET /course-learner-profiles : Returns a mapping from course IDs to the corresponding 
+     * {@link CourseLearnerProfile} for the authenticated user.
      *
      * @return The ResponseEntity with status 200 (OK) and with the body containing a map of DTOs, which contains per course profile data.
      */
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c882591 and 8e665f6.

📒 Files selected for processing (1)
  • src/main/java/de/tum/cit/aet/artemis/atlas/web/LearnerProfileResource.java (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`src/main/java/**/*.java`: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,de...

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/atlas/web/LearnerProfileResource.java
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Build and Push Docker Image / Build Docker Image for ls1intum/artemis
  • GitHub Check: Build and Push Docker Image / Build Docker Image for ls1intum/artemis
  • GitHub Check: Build .war artifact
  • GitHub Check: server-tests
  • GitHub Check: client-tests
  • GitHub Check: Analyse

Copy link

End-to-End (E2E) Test Results Summary

TestsPassed ☑️Skipped ⚠️Failed ❌️Time ⏱
End-to-End (E2E) Test Report201 ran197 passed3 skipped1 failed46m 53s 850ms
TestResultTime ⏱
End-to-End (E2E) Test Report
e2e/course/CourseMessages.spec.ts
ts.Course messages › Channel messages › Write/edit/delete message in channel › Student should be able to edit message in channel❌ failure2m 3s 132ms

Copy link
Contributor

@florian-glombik florian-glombik left a comment

Choose a reason for hiding this comment

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

Code

In a follow up learner-profile.component should be removed or extended. Right now this is just a wrapper for an existing component that does nothing 😅

Copy link

End-to-End (E2E) Test Results Summary

TestsPassed ☑️Skipped ⚠️Failed ❌️Time ⏱
End-to-End (E2E) Test Report201 ran197 passed3 skipped1 failed45m 28s 9ms
TestResultTime ⏱
End-to-End (E2E) Test Report
e2e/course/CourseMessages.spec.ts
ts.Course messages › Channel messages › Write/edit/delete message in channel › Student should be able to edit message in channel❌ failure2m 3s 7ms

Copy link
Contributor

@ahmetsenturk ahmetsenturk 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 stale review

Copy link

End-to-End (E2E) Test Results Summary

TestsPassed ☑️Skipped ⚠️Failed ❌️Time ⏱
End-to-End (E2E) Test Report201 ran196 passed3 skipped2 failed46m 26s 201ms
TestResultTime ⏱
End-to-End (E2E) Test Report
e2e/course/CourseMessages.spec.ts
ts.Course messages › Channel messages › Write/edit/delete message in channel › Student should be able to edit message in channel❌ failure2m 3s 458ms
e2e/exercise/quiz-exercise/QuizExerciseManagement.spec.ts
ts.Quiz Exercise Management › Quiz Exercise Creation › Creates a Quiz with Drag and Drop❌ failure2m 2s 184ms

@helios-aet helios-aet bot temporarily deployed to artemis-test5.artemis.cit.tum.de April 28, 2025 09:27 Inactive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
atlas Pull requests that affect the corresponding module client Pull requests that update TypeScript code. (Added Automatically!) core Pull requests that affect the corresponding module server Pull requests that update Java code. (Added Automatically!) tests
Projects
Status: Ready For Review
Status: In review
Development

Successfully merging this pull request may close these issues.

6 participants