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: Fix import all competencies with relations #9713

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

MaximilianAnzinger
Copy link
Contributor

@MaximilianAnzinger MaximilianAnzinger commented Nov 8, 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.
  • I documented the TypeScript code using JSDoc style.

Motivation and Context

This resolves a bug related to the bulk import of competencies from another course caused by a wrong endpoint call from the UI. Additionally it improves the propagation of updates to other components, to avoid that users have to refresh the page.

Steps for Testing

Prerequisites:

  • 1 Instructor
  • 2 Students
  • 1 Programming Exercise with Complaints enabled
  1. Log in to Artemis
  2. Navigate to Course Administration of the course without competencies
  3. Navigate to Competency Management
  4. Scroll to competencies
  5. Click 'Import Competencies'
  6. Select 'Import all competencies of a course'
  7. Select the other course with the competencies
  8. Import them with relations
  9. They should now appear in the table
  10. Click on Edit relations and make sure you see all competencies and relations in the graph

Testserver States

Note

These badges show the state of the test servers.
Green = Currently available, Red = Currently locked
Click on the badges to get to the test servers.







Review Progress

Performance Review

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

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Test Coverage

unchanged

Summary by CodeRabbit

  • New Features

    • Introduced a new input property allCompetencies to the Competency Management Table, allowing for better management of competency data.
    • Enhanced the competency management component to utilize the allCompetencies property for improved data handling.
  • Improvements

    • Simplified the URL structure in the import functionality of the Competency Service, streamlining the import process.

@github-actions github-actions bot added the client Pull requests that update TypeScript code. (Added Automatically!) label Nov 8, 2024
Copy link
Contributor

@JohannesStoehr JohannesStoehr left a comment

Choose a reason for hiding this comment

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

Code

@MaximilianAnzinger MaximilianAnzinger marked this pull request as ready for review November 8, 2024 19:58
@MaximilianAnzinger MaximilianAnzinger requested a review from a team as a code owner November 8, 2024 19:58
Copy link

coderabbitai bot commented Nov 8, 2024

Walkthrough

The changes in this pull request introduce a new input property allCompetencies to the CompetencyManagementTableComponent, allowing it to manage a broader collection of competencies. The importAll method in CompetencyService is updated to modify the endpoint for importing competencies, simplifying the URL structure. Additionally, the competency-management.component.html file is updated to bind the new property to instances of the competency management table component. Overall, these changes enhance the management and handling of competencies within the application.

Changes

File Path Change Summary
src/main/webapp/app/course/competencies/competency-management/competency-management-table.component.ts Added new input property @Input() allCompetencies: CourseCompetency[] and modified updateDataAfterImportAll method to handle imported competencies.
src/main/webapp/app/course/competencies/competency-management/competency-management.component.html Added [allCompetencies] binding to two instances of jhi-competency-management-table.
src/main/webapp/app/course/competencies/competency.service.ts Updated importAll method to change the URL endpoint, simplifying it while keeping the request body unchanged.

Possibly related PRs

Suggested labels

tests, server, bugfix, ready to merge, component:AdaptiveLearning

Suggested reviewers

  • JohannesStoehr
  • florian-glombik
  • SimonEntholzer
  • pzdr7
  • az108

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

🧹 Outside diff range and nitpick comments (4)
src/main/webapp/app/course/competencies/competency-management/competency-management.component.html (1)

46-46: Consider using a filtered competency set for prerequisites.

The prerequisites table uses the same courseCompetencies for allCompetencies. This might not be optimal if prerequisites should be selected from a different or filtered set of competencies.

Consider introducing a separate property like availablePrerequisites that filters out circular dependencies or inappropriate competencies for prerequisites.

src/main/webapp/app/course/competencies/competency.service.ts (1)

Line range hint 74-84: Add error handling and proper TypeScript documentation.

Consider these improvements:

  1. Add error handling for failed imports
  2. Add JSDoc documentation for the method
+    /**
+     * Imports all competencies from a source course to a target course.
+     * @param courseId - The ID of the target course
+     * @param sourceCourseId - The ID of the source course to import from
+     * @param importRelations - Whether to import competency relations
+     * @returns Observable of imported competencies with their relations
+     * @throws HttpErrorResponse if the import fails
+     */
     importAll(courseId: number, sourceCourseId: number, importRelations: boolean) {
+        // Handle potential errors from the server
+        return this.httpClient.post<Array<CompetencyWithTailRelationDTO>>(
             `${this.resourceURL}/courses/${courseId}/competencies/import-all`,
             {
                 importExercises: false,
                 importRelations: importRelations,
                 sourceCourseId: sourceCourseId,
                 importLectures: false,
             } as CourseCompetencyImportOptionsDTO,
             {
                 observe: 'response',
-            },
-        );
+            }
+        ).pipe(
+            tap({
+                error: (error) => {
+                    console.error('Failed to import competencies:', error);
+                    // Optional: Add your error handling logic here
+                }
+            })
+        );
     }
src/main/webapp/app/course/competencies/competency-management/competency-management-table.component.ts (2)

25-25: Add JSDoc documentation and consider type safety.

The new input property should be documented to explain its purpose and relationship with courseCompetencies. Also consider making it required or providing a default value to prevent undefined errors.

+    /** All available competencies across the course, including imported ones */
     @Input() allCompetencies: CourseCompetency[];

Line range hint 23-115: Consider architectural improvements for better maintainability.

The component handles its responsibilities well, but consider these architectural improvements:

  1. Extract the competency update logic into a dedicated service method
  2. Add state management for better data consistency across components
  3. Consider using RxJS behavior subjects for reactive updates

Example service method:

// competency.service.ts
updateCompetencies(importedCompetencies: CourseCompetency[], 
                  existingCompetencies: CourseCompetency[]): CourseCompetency[] {
    return existingCompetencies.concat(
        importedCompetencies.filter(
            comp => !existingCompetencies.some(
                existing => existing.id === comp.id
            )
        )
    );
}

This would centralize the update logic and make it reusable across components.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7a18571 and 748fbb0.

📒 Files selected for processing (3)
  • src/main/webapp/app/course/competencies/competency-management/competency-management-table.component.ts (2 hunks)
  • src/main/webapp/app/course/competencies/competency-management/competency-management.component.html (1 hunks)
  • src/main/webapp/app/course/competencies/competency.service.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
src/main/webapp/app/course/competencies/competency-management/competency-management-table.component.ts (1)

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

src/main/webapp/app/course/competencies/competency-management/competency-management.component.html (1)

Pattern 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/course/competencies/competency.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 (5)
src/main/webapp/app/course/competencies/competency-management/competency-management.component.html (2)

Line range hint 18-24: LGTM: Proper usage of new Angular syntax.

The template correctly uses the new @if syntax instead of the deprecated *ngIf, following the latest Angular guidelines.

Also applies to: 31-35


38-38: Verify the competency data binding.

The allCompetencies is bound to courseCompetencies while the table's main competencies are bound to competencies. Please verify if this is intentional, as it might lead to duplicate or inconsistent data if competencies and courseCompetencies represent different sets.

✅ Verification successful

Based on the shell script results, I can now generate the final response as the code shows clear evidence of the relationship between competencies and courseCompetencies:

The competency data binding is correct and intentional.

The component's implementation shows that:

  • courseCompetencies contains all competencies (both regular and prerequisites)
  • competencies is filtered from courseCompetencies to contain only regular competencies
  • The binding pattern is consistent with the component's data management where:
    this.courseCompetencies = await this.courseCompetencyApiService.getCourseCompetenciesByCourseId(this.courseId);
    this.competencies = this.courseCompetencies.filter((competency) => competency.type === CourseCompetencyType.COMPETENCY);
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the relationship between competencies and courseCompetencies
# Look for property declarations and assignments

# Search for competencies property
echo "Searching for competencies property..."
ast-grep --pattern 'competencies: $_'

# Search for courseCompetencies property
echo "Searching for courseCompetencies property..."
ast-grep --pattern 'courseCompetencies: $_'

# Search for assignments to these properties
echo "Searching for assignments..."
rg -A 5 'this\.(competencies|courseCompetencies)\s*='

Length of output: 9105

src/main/webapp/app/course/competencies/competency.service.ts (2)

Line range hint 74-84: LGTM! The endpoint simplification looks good.

The change to move sourceCourseId from the URL path to the request body aligns with REST best practices and should fix the bulk import issue.


Line range hint 74-84: Verify consistency with other import methods.

The implementation differs slightly from importBulk. Let's verify if this is intentional.

✅ Verification successful

Let me analyze the implementation differences between import methods by generating more targeted scripts.


Let me try a different approach using ripgrep to find the implementation details.


Implementation differences between importAll and importBulk are intentional and correct

The differences between importAll and importBulk methods are intentional:

  • importBulk includes competencyIds in the request body and passes importRelations as both a query parameter and body field, as it needs to specify which competencies to import
  • importAll only includes importRelations in the body since it imports all competencies from the source course
  • Both methods consistently set importExercises and importLectures to false
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Compare implementation differences between import methods

# Test 1: Check if other import methods use similar URL patterns
rg -A 10 "import.*competencies" src/main/webapp/app/course/competencies/

# Test 2: Check if other methods handle params differently
rg "new HttpParams\(\)" src/main/webapp/app/course/competencies/

Length of output: 89420


Script:

#!/bin/bash
# Check implementation details of import methods in competency service

# Look for importBulk implementation
ast-grep --pattern 'importBulk($$$) {
  $$$
}'

# Look for other import methods in competency service
ast-grep --pattern 'import.*\($$$\) {
  $$$
}'

Length of output: 221


Script:

#!/bin/bash
# Search for import method implementations in competency service

# Look for importBulk and other import methods
rg -A 15 "import.*\(" src/main/webapp/app/course/competencies/competency.service.ts

# Look for import-related HTTP calls
rg -A 10 "this\.http" src/main/webapp/app/course/competencies/competency.service.ts

Length of output: 6233

src/main/webapp/app/course/competencies/competency-management/competency-management-table.component.ts (1)

Line range hint 23-115: Verify template bindings and error handling.

Let's ensure the new property is properly bound in templates and error handling is consistent across related components.

✅ Verification successful

Let me gather more information about error handling patterns with the correct file type flag.


Error handling and template bindings are properly implemented.

The verification shows:

  1. Error handling is consistent across components using the global onError utility
  2. The allCompetencies binding in the parent component correctly passes courseCompetencies to the table component
  3. The table component safely handles the array operations with proper type checking
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify template bindings and related component usage

# Check template bindings for the new allCompetencies property
echo "Checking template bindings..."
rg -t html "allCompetencies" src/main/webapp/app/course/competencies/

# Check error handling in related components
echo "Checking error handling patterns..."
rg -t typescript "HttpErrorResponse|onError" src/main/webapp/app/course/competencies/

# Check for potential undefined access
echo "Checking for potential undefined access..."
ast-grep --pattern 'allCompetencies.$$$' src/main/webapp/app/course/competencies/

Length of output: 813


Script:

#!/bin/bash
# Check error handling with correct typescript file extension
echo "Checking error handling in TypeScript files..."
rg -t ts "HttpErrorResponse|onError" src/main/webapp/app/course/competencies/

# Check usage of allCompetencies in component
echo "Checking allCompetencies usage..."
rg -t ts "allCompetencies" src/main/webapp/app/course/competencies/

# Check parent component implementation
echo "Checking parent component..."
cat src/main/webapp/app/course/competencies/competency-management/competency-management.component.ts

Length of output: 18498

Comment on lines 98 to 100
this.courseCompetencies.push(...importedCompetencies);
this.allCompetencies.push(...importedCompetencies);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add safety checks and consider deduplication.

The current implementation has potential issues:

  1. No null/undefined checks before pushing to arrays
  2. No deduplication logic to prevent duplicate entries
  3. Potential memory concerns with unbounded array growth

Consider this safer implementation:

     updateDataAfterImportAll(res: Array<CompetencyWithTailRelationDTO>) {
         const importedCompetencies = res.map((dto) => dto.competency).filter((element): element is CourseCompetency => !!element);
-        this.courseCompetencies.push(...importedCompetencies);
-        this.allCompetencies.push(...importedCompetencies);
+        if (this.courseCompetencies && importedCompetencies.length) {
+            // Deduplicate based on competency ID
+            const newCompetencies = importedCompetencies.filter(
+                comp => !this.courseCompetencies.some(existing => existing.id === comp.id)
+            );
+            this.courseCompetencies.push(...newCompetencies);
+        }
+        if (this.allCompetencies && importedCompetencies.length) {
+            const newCompetencies = importedCompetencies.filter(
+                comp => !this.allCompetencies.some(existing => existing.id === comp.id)
+            );
+            this.allCompetencies.push(...newCompetencies);
+        }
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
this.courseCompetencies.push(...importedCompetencies);
this.allCompetencies.push(...importedCompetencies);
}
updateDataAfterImportAll(res: Array<CompetencyWithTailRelationDTO>) {
const importedCompetencies = res.map((dto) => dto.competency).filter((element): element is CourseCompetency => !!element);
if (this.courseCompetencies && importedCompetencies.length) {
// Deduplicate based on competency ID
const newCompetencies = importedCompetencies.filter(
comp => !this.courseCompetencies.some(existing => existing.id === comp.id)
);
this.courseCompetencies.push(...newCompetencies);
}
if (this.allCompetencies && importedCompetencies.length) {
const newCompetencies = importedCompetencies.filter(
comp => !this.allCompetencies.some(existing => existing.id === comp.id)
);
this.allCompetencies.push(...newCompetencies);
}
}

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!) lock:artemis-test3 ready for review
Projects
Status: Ready For Review
Status: In review
Development

Successfully merging this pull request may close these issues.

3 participants