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

Adaptive learning: Add learner profile interface #10440

Open
wants to merge 4 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:

  • TS3
  • 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

Summary by CodeRabbit

  • New Features

    • Launched a new Learner Profile section in user settings, enabling users to view and adjust details for their courses.
    • Introduced interactive UI elements, including editable sliders for parameters like grade ambition, time investment, and repetition intensity.
    • Enhanced the system’s data integration to support real-time retrieval and updates of learner profiles.
    • Expanded localization support with new English and German translations.
    • Added new components for managing course learner profiles and their associated data.
    • Introduced a new RESTful resource for managing learner profiles, including endpoints for retrieving and updating profiles.
  • Tests

    • Added comprehensive tests to validate the functionality of the new profile and slider features.

@N0W0RK N0W0RK requested a review from a team as a code owner March 4, 2025 16:39
@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 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 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
Copy link

coderabbitai bot commented Mar 4, 2025

Walkthrough

This pull request introduces a set of new backend and frontend features for managing course learner profiles. On the backend, a new constant, DTO record, repository method, and REST controller endpoints are added. On the frontend, several Angular components, services, and models support an interactive learner profile interface that includes editable sliders, localization updates, and a new user settings route. Test suites for these new UI components have also been added to ensure correct behavior.

Changes

File(s) Change Summary
.../atlas/domain/profile/CourseLearnerProfile.java Added a new constant (ENTITY_NAME).
.../atlas/dto/CourseLearnerProfileDTO.java Introduced a new DTO record with an of() method.
.../atlas/repository/CourseLearnerProfileRepository.java Added a repository method (findAllByLogin) for retrieving profiles by user login.
.../atlas/web/LearnerProfileResource.java Added a REST controller with GET and PUT endpoints for managing course learner profiles.
.../app/entities/learner-profile.model.ts Introduced a TypeScript model for CourseLearnerProfileDTO.
.../app/learner-profile/service/learner-profile-api.service.ts Added an API service providing asynchronous GET and PUT methods to interact with the new REST endpoints.
.../app/shared/editable-slider/double-slider.component.*
.../app/shared/editable-slider/edit-process.component.*
.../app/shared/editable-slider/editable-slider.component.*
.../app/shared/user-settings/learner-profile/*
Added several Angular components and their templates/styles for double sliders, edit process handling, and overall learner profile UI.
.../app/shared/user-settings/user-settings-container/user-settings-container.component.html
.../app/shared/user-settings/user-settings.route.ts
Introduced a new route and a navigation link for learner profiles in user settings.
.../app/i18n/en/learnerProfile.json
.../app/i18n/de/learnerProfile.json
.../app/i18n/en/userSettings.json
.../app/i18n/de/userSettings.json
Provided new localization files and entries for the learner profile feature and associated user settings in both English and German.
.../spec/component/learner-profile/component/course-learner-profile.component.spec.ts
.../spec/component/learner-profile/component/double-slider.component.spec.ts
.../spec/component/learner-profile/component/edit-process.component.spec.ts
Introduced new test suites to verify the functionality of the course learner profile component, double slider interactions, and edit process transitions.

Possibly related PRs

Suggested labels

feature, ready for review, small, user interface

Suggested reviewers

  • JohannesStoehr
  • N0W0RK
  • HawKhiem
  • florian-glombik
  • dmytropolityka
  • krusche
  • sachmii
✨ Finishing Touches
  • 📝 Generate Docstrings

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

@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

@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
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.

Looks good overall, just a few small comments

@RequestMapping("api/atlas/")
public class LearnerProfileResource {

private static final int MIN_PROFILE_VALUE = 1;
Copy link
Contributor

Choose a reason for hiding this comment

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

what are min and max profile values? Can they be named in a more descriptive way?

}

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

@tobias-lippert tobias-lippert Mar 4, 2025

Choose a reason for hiding this comment

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

no await here, then you can also remove the async

pointer-events: all;
cursor: pointer;
}
input[type='range']#currentSlider::-webkit-slider-thumb {
Copy link
Contributor

Choose a reason for hiding this comment

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

codacy


loadCourses() {
this.courses = [];
//iterat eover each course ID in courseLearnerProfiles map to retrieve course title
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
//iterat eover each course ID in courseLearnerProfiles map to retrieve course title
//iterate over each course ID in courseLearnerProfiles map to retrieve course title

@helios-aet helios-aet bot temporarily deployed to artemis-test7.artemis.cit.tum.de March 4, 2025 20:56 Inactive
@helios-aet helios-aet bot temporarily deployed to artemis-test7.artemis.cit.tum.de March 4, 2025 21:42 Inactive
Copy link

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 Mar 12, 2025
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: 2

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

108-109: Avoid redundant whenStable() calls.

There are two consecutive calls to await fixture.whenStable() which is unnecessary. One call is sufficient to wait for all async operations to complete.

        fixture.detectChanges();
        await fixture.whenStable();
-       await fixture.whenStable();
        fixture.detectChanges();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b584591 and 30a1605.

📒 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
🪛 GitHub Actions: Test
src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts

[error] 125-125: Test failed: expect(component.courses).toStrictEqual(courses) - Expected array with courses but received an empty array.


[error] 134-134: Test failed: expect(component.activeCourse).toBe(course) - Expected: 1, Received: undefined.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (4)
src/test/javascript/spec/component/learner-profile/component/course-learner-profile.component.spec.ts (4)

76-77: Remove duplicate AlertService provider.

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

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

138-141: Avoid mutating shared test data.

The current implementation is modifying the shared profiles object directly, which could lead to side effects in other tests. Create a deep copy of the profile object before modifying it.

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

147-153: Update API endpoint path to match service import and improve assertions.

The API endpoint path includes /atlas/ but the import doesn't reflect this structure. Also, adjust spy assertions according to coding guidelines.

function validateUpdate(course: number, profile: CourseLearnerProfileDTO) {
-   const req = httpTesting.expectOne(`api/atlas/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(profile);
-   expect(putUpdatedCourseLearnerProfileSpy).toHaveBeenCalled();
+   expect(putUpdatedCourseLearnerProfileSpy).toHaveBeenCalledOnce();
-   expect(putUpdatedCourseLearnerProfileSpy.mock.calls[0][0]).toEqual(profile);
+   expect(putUpdatedCourseLearnerProfileSpy).toHaveBeenCalledWith(profile);
    expect(component.courseLearnerProfiles[course]).toEqual(profile);
}

155-165: Update error validation path and verify AlertService is called.

Fix the API endpoint path and add validation for AlertService calls according to the coding guidelines.

function validateError(course: number, profile: CourseLearnerProfileDTO) {
-   const req = httpTesting.expectOne(`api/atlas/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);
}

Comment on lines +124 to +126
expect(component).toBeTruthy();
expect(component.courses).toStrictEqual(courses);
expect(component.courseLearnerProfiles).toEqual(profiles);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix failing test - component.courses is empty.

The test is failing because component.courses is empty. The pipeline shows: "Expected array with courses but received an empty array." Ensure the component correctly initializes courses from the mocked service.

Verify how the component initializes the courses property. You might need to check the component implementation to ensure it properly loads courses from the courseManagerService during initialization.

🧰 Tools
🪛 GitHub Actions: Test

[error] 125-125: Test failed: expect(component.courses).toStrictEqual(courses) - Expected array with courses but received an empty array.

Comment on lines +130 to +135
let course = 1;
selectCourse(course);
let changeEvent = new Event('change', { bubbles: true, cancelable: false });
selector.dispatchEvent(changeEvent);
expect(component.activeCourse).toBe(course);
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix failing test - activeCourse is undefined.

The test is failing because component.activeCourse remains undefined after selection. The pipeline shows: "Expected: 1, Received: undefined."

Check how the component handles the select change event. Make sure the component's method for handling course selection is being called and correctly updates the activeCourse property.

🧰 Tools
🪛 GitHub Actions: Test

[error] 134-134: Test failed: expect(component.activeCourse).toBe(course) - Expected: 1, Received: undefined.

@github-actions github-actions bot removed the stale label Mar 13, 2025
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!) 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.

2 participants