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

Development: Migrate tutorial groups service folder to new angular guidelines #9941

Merged
merged 2 commits into from
Dec 10, 2024

Conversation

az108
Copy link
Contributor

@az108 az108 commented Dec 4, 2024

Checklist

General

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

Keeping Code new and up to date should be high priority for projects, therefore we are moving to the new Angular Signals,Inject and Standalone.

Description

Migrated old Code to new Client Code guidelines

Review Progress

Code Review

  • Code Review 1
  • Code Review 2

Summary by CodeRabbit

  • New Features

    • Transitioned to a more modern dependency injection method using the inject function for various services, enhancing code readability and maintainability.
  • Bug Fixes

    • No specific bug fixes were mentioned, but the changes may improve overall service stability.
  • Refactor

    • Removed constructors from several service classes, simplifying their structure while maintaining existing functionalities.

@az108 az108 self-assigned this Dec 4, 2024
@az108 az108 requested a review from a team as a code owner December 4, 2024 14:13
@github-actions github-actions bot added the client Pull requests that update TypeScript code. (Added Automatically!) label Dec 4, 2024
@az108 az108 changed the title Tutorial Groups: Migrate tutorial groups service folder to new angular guidelines Tutorial groups: Migrate tutorial groups service folder to new angular guidelines Dec 4, 2024
Copy link

coderabbitai bot commented Dec 4, 2024

Walkthrough

The pull request introduces modifications to several service classes within the tutorial groups module, specifically transitioning from constructor-based dependency injection to using the inject function from Angular's core. This change affects the TutorialGroupFreePeriodService, TutorialGroupSessionService, TutorialGroupsConfigurationService, and TutorialGroupsService, simplifying their structure by removing constructors and directly initializing dependencies as private properties. The order of property declarations has been adjusted, but the overall functionality and method logic remain unchanged across all services.

Changes

File Change Summary
src/main/webapp/app/course/tutorial-groups/services/tutorial-group-free-period.service.ts - Replaced constructor-based injection of HttpClient with inject(HttpClient).
- Moved resourceURL declaration below httpClient.
src/main/webapp/app/course/tutorial-groups/services/tutorial-group-session.service.ts - Replaced constructor-based injection of HttpClient and TutorialGroupFreePeriodService with inject().
- Moved resourceURL declaration below injected properties.
src/main/webapp/app/course/tutorial-groups/services/tutorial-groups-configuration.service.ts - Removed constructor and replaced HttpClient injection with inject(HttpClient).
- Moved resourceURL declaration below httpClient.
src/main/webapp/app/course/tutorial-groups/services/tutorial-groups.service.ts - Removed constructor and replaced injection of HttpClient, TutorialGroupSessionService, and TutorialGroupsConfigurationService with inject().
- Moved resourceURL declaration below injected properties.

Possibly related PRs

  • Tutorial groups: Redesign overview page #9445: The changes in the TutorialGroupFreePeriodService class are related to the modifications in the TutorialGroupSessionService, which also transitioned to using the inject function for dependency injection, indicating a broader refactor of services in the tutorial groups context.
  • Development: Improve performance of programming exercise details view #9785: The improvements in the ProgrammingExerciseDetailComponent include a similar transition to using the inject function for dependency injection, aligning with the modernization efforts seen in the TutorialGroupFreePeriodService.

Suggested labels

tests, ready for review, component:TutorialGroups, lock:artemis-test1, refactoring

Suggested reviewers

  • HawKhiem
  • anian03
  • rabeatwork
  • magaupp

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (8)
src/main/webapp/app/course/tutorial-groups/services/tutorial-group-free-period.service.ts (2)

18-20: Consider reordering class members

According to Angular style guide, consider organizing class members in the following order:

  1. Public properties
  2. Private properties
  3. Constructor/lifecycle hooks
  4. Public methods
  5. Private methods
@Injectable({ providedIn: 'root' })
export class TutorialGroupFreePeriodService {
-    private httpClient = inject(HttpClient);
-
-    private resourceURL = 'api';
+    // Private properties
+    private readonly httpClient = inject(HttpClient);
+    private readonly resourceURL = 'api';

Line range hint 71-89: Consider simplifying date conversion methods

The date conversion methods could be simplified using optional chaining and nullish coalescing operators.

    private convertTutorialGroupFreePeriodDatesFromClient(tutorialGroupFreePeriodDTO: TutorialGroupFreePeriodDTO): TutorialGroupFreePeriodDTO {
-        if (tutorialGroupFreePeriodDTO) {
-            return Object.assign({}, tutorialGroupFreePeriodDTO, {
-                startDate: toISO8601DateTimeString(tutorialGroupFreePeriodDTO.startDate),
-                endDate: toISO8601DateTimeString(tutorialGroupFreePeriodDTO.endDate),
-            });
-        } else {
-            return tutorialGroupFreePeriodDTO;
-        }
+        return tutorialGroupFreePeriodDTO && {
+            ...tutorialGroupFreePeriodDTO,
+            startDate: toISO8601DateTimeString(tutorialGroupFreePeriodDTO.startDate),
+            endDate: toISO8601DateTimeString(tutorialGroupFreePeriodDTO.endDate),
+        };
    }
src/main/webapp/app/course/tutorial-groups/services/tutorial-groups-configuration.service.ts (2)

12-14: Consider reordering class members and adding readonly modifier

For consistency with other services and immutability best practices.

@Injectable({ providedIn: 'root' })
export class TutorialGroupsConfigurationService {
-    private httpClient = inject(HttpClient);
-
-    private resourceURL = 'api';
+    // Private properties
+    private readonly httpClient = inject(HttpClient);
+    private readonly resourceURL = 'api';

Line range hint 47-61: Improve null safety in date conversion methods

The method uses excessive non-null assertions (!). Consider using optional chaining and type guards.

    private convertTutorialGroupsConfigurationResponseDatesFromServer(res: HttpResponse<TutorialGroupsConfiguration>): HttpResponse<TutorialGroupsConfiguration> {
-        if (res.body) {
-            res.body.tutorialPeriodStartInclusive = convertDateFromServer(res.body!.tutorialPeriodStartInclusive);
-            res.body!.tutorialPeriodEndInclusive = convertDateFromServer(res.body!.tutorialPeriodEndInclusive);
-            if (res.body!.tutorialGroupFreePeriods) {
-                res.body!.tutorialGroupFreePeriods.forEach((tutorialGroupFreePeriod) => {
-                    tutorialGroupFreePeriod.start = convertDateFromServer(tutorialGroupFreePeriod.start);
-                    tutorialGroupFreePeriod.end = convertDateFromServer(tutorialGroupFreePeriod.end);
-                });
-            }
-        }
+        const body = res.body;
+        if (body) {
+            body.tutorialPeriodStartInclusive = convertDateFromServer(body.tutorialPeriodStartInclusive);
+            body.tutorialPeriodEndInclusive = convertDateFromServer(body.tutorialPeriodEndInclusive);
+            body.tutorialGroupFreePeriods?.forEach((period) => {
+                period.start = convertDateFromServer(period.start);
+                period.end = convertDateFromServer(period.end);
+            });
+        }
        return res;
    }
src/main/webapp/app/course/tutorial-groups/services/tutorial-group-session.service.ts (3)

20-23: Consider reordering class members and adding readonly modifier

For consistency with other services and immutability best practices.

@Injectable({ providedIn: 'root' })
export class TutorialGroupSessionService {
-    private httpClient = inject(HttpClient);
-    private tutorialGroupFreePeriodService = inject(TutorialGroupFreePeriodService);
-
-    private resourceURL = 'api';
+    // Private properties
+    private readonly httpClient = inject(HttpClient);
+    private readonly tutorialGroupFreePeriodService = inject(TutorialGroupFreePeriodService);
+    private readonly resourceURL = 'api';

Line range hint 40-50: Simplify HTTP params construction

The current implementation has redundant null checks. Consider using nullish coalescing.

    updateAttendanceCount(courseId: number, tutorialGroupId: number, sessionId: number, attendanceCount: number | undefined): Observable<EntityResponseType> {
-        let params = new HttpParams();
-        if (attendanceCount !== undefined && attendanceCount !== null) {
-            params = params.append('attendanceCount', attendanceCount.toString());
-        }
+        const params = attendanceCount != null ? new HttpParams().append('attendanceCount', attendanceCount.toString()) : new HttpParams();
        return this.httpClient
            .patch<TutorialGroupSession>(`${this.resourceURL}/courses/${courseId}/tutorial-groups/${tutorialGroupId}/sessions/${sessionId}/attendance-count`, null, {
                observe: 'response',
                params,
            })
            .pipe(map((res: EntityResponseType) => this.convertTutorialGroupSessionResponseDatesFromServer(res)));
    }

Based on the search results, I can now provide a final response. The codebase shows consistent error handling patterns across various services using RxJS's catchError operator, often combined with AlertService for user notifications. However, the tutorial group session service lacks this pattern.

Add consistent error handling to align with codebase patterns

The service methods should include error handling using RxJS operators, following the established pattern in the codebase. Example implementation:

import { catchError } from 'rxjs/operators';
import { HttpErrorResponse } from '@angular/common/http';
import { AlertService } from 'app/core/util/alert.service';

// Add to constructor:
constructor(
    private alertService: AlertService,
    // ... other dependencies
) {}

// Modify each HTTP method to include:
.pipe(
    catchError((error: HttpErrorResponse) => {
        this.alertService.error('artemisApp.tutorialGroup.error.operation');
        return throwError(() => error);
    })
)
🔗 Analysis chain

Line range hint 26-91: Consider adding consistent error handling

The service methods handle HTTP responses differently. Consider adding consistent error handling across all methods.

Consider adding error handling to all HTTP methods:

import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

// Add to each HTTP method:
.pipe(
    catchError(error => {
        console.error('API Error:', error);
        return throwError(() => error);
    })
)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for error handling patterns in other services
rg -A 2 "catchError|throwError" src/main/webapp/app/course/tutorial-groups/services/

Length of output: 86


Script:

#!/bin/bash
# Let's broaden the search to check error handling patterns across the application
rg -A 2 "catchError|throwError" "src/main/webapp/app/"

# Also check for any HTTP error handling patterns that might use different approaches
rg -A 2 "error.*handle|handle.*error" "src/main/webapp/app/"

Length of output: 69016

src/main/webapp/app/course/tutorial-groups/services/tutorial-groups.service.ts (1)

18-22: Consider enhancing immutability

Consider the following improvements:

  1. Mark injected services as readonly since they are immutable dependencies
  2. Convert resourceURL to a readonly constant using uppercase naming
-    private httpClient = inject(HttpClient);
-    private tutorialGroupSessionService = inject(TutorialGroupSessionService);
-    private tutorialGroupsConfigurationService = inject(TutorialGroupsConfigurationService);
-
-    private resourceURL = 'api';
+    private readonly httpClient = inject(HttpClient);
+    private readonly tutorialGroupSessionService = inject(TutorialGroupSessionService);
+    private readonly tutorialGroupsConfigurationService = inject(TutorialGroupsConfigurationService);
+
+    private readonly RESOURCE_URL = 'api';

Remember to update all references of resourceURL to RESOURCE_URL throughout the file.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0f12a54 and 8266df5.

📒 Files selected for processing (4)
  • src/main/webapp/app/course/tutorial-groups/services/tutorial-group-free-period.service.ts (2 hunks)
  • src/main/webapp/app/course/tutorial-groups/services/tutorial-group-session.service.ts (2 hunks)
  • src/main/webapp/app/course/tutorial-groups/services/tutorial-groups-configuration.service.ts (2 hunks)
  • src/main/webapp/app/course/tutorial-groups/services/tutorial-groups.service.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
src/main/webapp/app/course/tutorial-groups/services/tutorial-groups.service.ts (1)

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

src/main/webapp/app/course/tutorial-groups/services/tutorial-groups-configuration.service.ts (1)

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

src/main/webapp/app/course/tutorial-groups/services/tutorial-group-free-period.service.ts (1)

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

src/main/webapp/app/course/tutorial-groups/services/tutorial-group-session.service.ts (1)

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

🔇 Additional comments (2)
src/main/webapp/app/course/tutorial-groups/services/tutorial-groups.service.ts (2)

2-2: LGTM: Import statement correctly updated

The inject import from @angular/core is properly added and grouped with other Angular core imports.


18-20: LGTM: Proper migration to new dependency injection pattern

The service correctly implements the new Angular dependency injection pattern using inject(). All dependencies are properly initialized and marked as private.

Copy link

github-actions bot commented Dec 5, 2024

⚠️ Unable to deploy to test servers ⚠️

Testserver "artemis-test1.artemis.cit.tum.de" is already in use by PR #9799.

@github-actions github-actions bot added the deployment-error Added by deployment workflows if an error occured label Dec 5, 2024
@sarpsahinalp sarpsahinalp added deploy:artemis-test1 and removed deployment-error Added by deployment workflows if an error occured labels Dec 5, 2024
@sarpsahinalp sarpsahinalp temporarily deployed to artemis-test1.artemis.cit.tum.de December 5, 2024 19:32 — with GitHub Actions Inactive
Copy link
Contributor

@raffifasaro raffifasaro left a comment

Choose a reason for hiding this comment

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

Code LGTM

Copy link
Contributor

@asliayk asliayk left a comment

Choose a reason for hiding this comment

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

code lgtm

@bassner bassner merged commit 82f04e6 into develop Dec 10, 2024
60 of 69 checks passed
@bassner bassner deleted the chore/migrate-tutorial-groups-to-signals branch December 10, 2024 16:56
@krusche krusche changed the title Tutorial groups: Migrate tutorial groups service folder to new angular guidelines Development: Migrate tutorial groups service folder to new angular guidelines Dec 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
client Pull requests that update TypeScript code. (Added Automatically!) ready to merge
Projects
Status: Merged
Development

Successfully merging this pull request may close these issues.

7 participants