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

Bugfix/96 language management by parameter lang from idp to angular and vice versa #151

Conversation

nganntqe170236
Copy link
Collaborator

@nganntqe170236 nganntqe170236 commented Feb 23, 2025

Summary by CodeRabbit

  • New Features
    • Enhanced user settings now let you select your preferred language (Vietnamese, English, or Chinese) with changes applied instantly.
    • Enjoy theme customization with real-time support for dark, light, or system modes to match your visual preference.
    • Your language and theme selections are now seamlessly integrated into your profile for a more personalized experience.

nganntqe170236 and others added 2 commits February 23, 2025 19:03
Copy link

coderabbitai bot commented Feb 23, 2025

Walkthrough

This update integrates language and theme configuration across the system. On the backend, a new UserLocale enum and additional fields/methods in user context and entity classes support locale handling. In the IDP module, REST endpoints, service methods, and a DB migration have been added for managing user language and theme preferences. In the frontend, Angular components and services are updated to inject user configuration, replace old language interceptors, and use new enums and models for consistent user preferences management.

Changes

File(s) Change Summary
sep490-commons/.../UserLocale.java
sep490-commons/.../JwtAuthenticationConverter.java
sep490-commons/.../UserContextData.java
Added UserLocale enum with locale codes and a fromCode method; updated UserContextData by adding a new language field and marking permissions as transient; included a new parameter in JWT conversion.
sep490-idp/.../UserConfigs.java
sep490-idp/.../UserEntity.java
sep490-idp/.../UserResource.java
sep490-idp/.../MvcUserContextData.java
sep490-idp/.../UserService.java
sep490-idp/.../UserServiceImpl.java
sep490-idp/.../V0.0.1.8__UserConfigs.sql
Introduced user configuration support in the IDP layer: new record for user configs, added locale and theme fields in the entity, new REST endpoints for fetching and updating user preferences, enhanced context data via MvcUserContextData, and updated service interfaces/implementations with DB migration changes.
sep490-frontend/.../app.component.ts
sep490-frontend/.../app.module.ts
sep490-frontend/.../header/header.component.ts
sep490-frontend/.../authorization/authorization.module.ts
sep490-frontend/.../enterprise-user-details.component.ts
sep490-frontend/.../users.component.ts
sep490-frontend/.../enums/user-language.enum.ts
sep490-frontend/.../interceptor/language.interceptor.ts (removed)
sep490-frontend/.../models/user-configs.ts
sep490-frontend/.../services/user.service.ts
sep490-frontend/.../core/services/theme.service.ts
Updated Angular application to integrate user language and theme preferences. Changes include constructor updates to inject UserService, replacing UserService with EnterpriseUserService where appropriate, type improvements using the new UserLanguage enum, removal of the legacy LanguageInterceptor, and the addition of new models and services for managing user configurations and theme changes.
sep490-idp/.../LoginService.java
sep490-idp/.../UserInfoService.java
Minor refactoring and formatting updates, including the extraction of a dedicated userContextData variable in LoginService and improved code formatting in UserInfoService.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant H as HeaderComponent
    participant TS as TranslateService
    participant US as UserService
    participant UR as UserResource

    U->>H: Selects new language/theme
    H->>TS: Update UI language (translate.use)
    H->>US: Invoke changeLanguage/changeTheme
    US->>UR: HTTP PUT /api/user/{language|theme}/{value}
    UR-->>US: 204 No Content
    H->>U: UI reflects new settings
Loading

Possibly related PRs

Suggested labels

user story, improvement

Suggested reviewers

  • thongdanghoang
  • huynhlephcvinh

Poem

I'm a happy rabbit, leaping with delight,
New enums and configs shining bright.
Languages and themes now dance in code,
A playful hop down a clean new road.
Cheers and carrots for every line—so light!
🐇🌟

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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 (10)
sep490-frontend/src/app/modules/core/services/theme.service.ts (2)

76-94: Add error handling for localStorage operations.

While the Theme enum usage improves type safety, the localStorage operations should be wrapped in try-catch blocks to handle potential errors (e.g., when localStorage is disabled or full).

  initTheme(): void {
    if (this.isThemeConfigured()) {
      this.config.theme.set(this.userPreferredColorTheme);
-      if (localStorage.getItem(this.LOCAL_STORAGE_KEY) === Theme[Theme.DARK]) {
-        document.querySelector('html')?.classList.add(this.TOKEN);
+      try {
+        if (localStorage.getItem(this.LOCAL_STORAGE_KEY) === Theme[Theme.DARK]) {
+          document.querySelector('html')?.classList.add(this.TOKEN);
+        }
+      } catch (error) {
+        console.warn('Failed to access localStorage:', error);
+        // Fallback to system theme
+        this.config.theme.set(this.systemPreferredColorTheme);
+      }
      return;
    }
    // ... rest of the code
  }

  isDarkMode(): Observable<boolean> {
    if (this.isThemeConfigured()) {
-      return of(
-        localStorage.getItem(this.LOCAL_STORAGE_KEY) === Theme[Theme.DARK]
-      );
+      try {
+        return of(
+          localStorage.getItem(this.LOCAL_STORAGE_KEY) === Theme[Theme.DARK]
+        );
+      } catch (error) {
+        console.warn('Failed to access localStorage:', error);
+        return this.systemPreferredColorThemeChanged;
+      }
    }
    return this.systemPreferredColorThemeChanged;
  }

99-109: Improve error handling and simplify theme toggle logic.

The theme persistence is correctly implemented, but there are opportunities for improvement:

  1. Add error handling for UserService operations
  2. Simplify the theme toggle logic by extracting the new theme determination
  toggleLightDark(): void {
    this.config.theme.set(this.userPreferredColorTheme);
-    if (document.querySelector('html')?.classList.contains(this.TOKEN)) {
-      localStorage.setItem(this.LOCAL_STORAGE_KEY, Theme[Theme.LIGHT]);
-      this.userService.changeTheme(Theme[Theme.LIGHT]).subscribe();
-    } else {
-      localStorage.setItem(this.LOCAL_STORAGE_KEY, Theme[Theme.DARK]);
-      this.userService.changeTheme(Theme[Theme.DARK]).subscribe();
-    }
-    document.querySelector('html')?.classList.toggle(this.TOKEN);
+    const isDark = document.querySelector('html')?.classList.contains(this.TOKEN);
+    const newTheme = isDark ? Theme[Theme.LIGHT] : Theme[Theme.DARK];
+    
+    try {
+      localStorage.setItem(this.LOCAL_STORAGE_KEY, newTheme);
+      this.userService.changeTheme(newTheme).subscribe({
+        error: (error) => {
+          console.error('Failed to update theme preference:', error);
+          // Optionally revert the local change
+          localStorage.setItem(this.LOCAL_STORAGE_KEY, isDark ? Theme[Theme.DARK] : Theme[Theme.LIGHT]);
+        }
+      });
+      document.querySelector('html')?.classList.toggle(this.TOKEN);
+    } catch (error) {
+      console.warn('Failed to access localStorage:', error);
+    }
  }
sep490-commons/api/src/main/java/green_buildings/commons/api/enums/UserLocale.java (1)

19-24: Improve error handling in fromCode method.

The fromCode method throws NoSuchElementException without a clear error message when an invalid code is provided. Consider adding a descriptive message to help with debugging.

Apply this diff to improve error handling:

 public static UserLocale fromCode(String code) {
     return Arrays.stream(values())
                  .filter(userLanguage -> userLanguage.getCode().equals(code))
                  .findFirst()
-                  .orElseThrow();
+                  .orElseThrow(() -> 
+                      new NoSuchElementException("Invalid locale code: " + code));
 }
sep490-frontend/src/app/services/user.service.ts (1)

20-32: Optimize PUT requests by removing empty body objects.

The empty object bodies in PUT requests are unnecessary and can be omitted.

  changeLanguage(language: UserLanguage): Observable<void> {
-    return this.httpClient.put<void>(
-      `${AppRoutingConstants.IDP_API_URL}/user/language/${language}`,
-      {}
-    );
+    return this.httpClient.put<void>(
+      `${AppRoutingConstants.IDP_API_URL}/user/language/${language}`,
+      null
+    );
  }

  changeTheme(theme: string): Observable<void> {
-    return this.httpClient.put<void>(
-      `${AppRoutingConstants.IDP_API_URL}/user/theme/${theme}`,
-      {}
-    );
+    return this.httpClient.put<void>(
+      `${AppRoutingConstants.IDP_API_URL}/user/theme/${theme}`,
+      null
+    );
  }
sep490-frontend/src/app/components/header/header.component.ts (1)

46-55: Simplify language change subscription.

The subscription logic can be simplified using RxJS operators.

Consider this optimization:

-    this.translate.onLangChange
-      .pipe(
-        takeUntil(this.destroy$),
-        map(event => event.lang)
-      )
-      .subscribe(lang => {
-        this.selectedLanguage = this.languages?.find(
-          language => language.key.split('-')[0] === lang
-        );
-      });
+    this.translate.onLangChange.pipe(
+      takeUntil(this.destroy$),
+      map(event => this.languages?.find(
+        language => language.key.split('-')[0] === event.lang
+      ))
+    ).subscribe(language => {
+      this.selectedLanguage = language;
+    });
sep490-idp/src/main/java/green_buildings/idp/rest/UserResource.java (1)

53-69: Extract common user update logic.

The theme and language update endpoints share similar patterns.

Consider extracting the common logic:

+    private ResponseEntity<Void> updateUserPreference(
+        UserContextData userContextData,
+        Consumer<UserEntity> updateFunction
+    ) {
+        var userEntity = userService.findByEmail(userContextData.getUsername())
+            .orElseThrow(() -> new UserNotFoundException("User not found: " + userContextData.getUsername()));
+        updateFunction.accept(userEntity);
+        userService.update(userEntity);
+        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
+    }
+
     @PutMapping("/language/{language}")
     public ResponseEntity<Void> changeLanguage(@PathVariable("language") String locale,
                                                @AuthenticationPrincipal UserContextData userContextData) {
         if (Arrays.stream(UserLocale.values())
                   .map(UserLocale::getCode)
                   .noneMatch(code -> code.equals(locale))) {
             return ResponseEntity.badRequest().build();
         }
-        var userEntity = userService.findByEmail(userContextData.getUsername()).orElseThrow();
-        userEntity.setLocale(locale);
-        userService.update(userEntity);
-        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
+        return updateUserPreference(userContextData, user -> user.setLocale(locale));
     }
sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/JwtAuthenticationConverter.java (1)

71-72: Consider using a default language value instead of empty string.

Using StringUtils.EMPTY for language initialization might lead to undefined behavior. Consider using a default language value (e.g., 'en' or system default) to ensure consistent language handling.

-        StringUtils.EMPTY, // can't initialize language from JWT
+        UserLocale.VI.name(), // Default to Vietnamese as per database migration
sep490-frontend/src/app/modules/authorization/components/users/users.component.ts (1)

152-162: Enhance error handling in deleteUsers method.

The error handler could provide more specific error information to help users understand and resolve issues.

-      error: () => {
+      error: (error) => {
+        const errorDetail = error?.error?.message || 
+          this.translate.instant('enterprise.Users.message.error.detail');
         this.messageService.add({
           severity: 'error',
           summary: this.translate.instant(
             'enterprise.Users.message.error.summary'
           ),
-          detail: this.translate.instant(
-            'enterprise.Users.message.error.detail'
-          )
+          detail: errorDetail
         });
       }
sep490-frontend/src/app/modules/authorization/components/create-user/enterprise-user-details.component.ts (1)

109-109: Address the TODO comment.

There's a pending TODO comment about enterprise use case integration. This might be related to the mock buildings data being used.

Would you like me to help create a new issue to track the enterprise use case integration task?

sep490-idp/src/main/resources/db/migration/V0.0.1.8__UserConfigs.sql (1)

1-3: Verify the locale format and theme values.

The migration script looks good, but please ensure:

  1. The default locale 'vi-VN' matches the supported locales in the UserLocale enum.
  2. The default theme 'system' is a valid value in the frontend's Theme enum.

Also, consider adding a CHECK constraint to validate the locale format and theme values.

Here's a suggested enhancement:

 ALTER TABLE users
     ADD COLUMN locale VARCHAR(5) NOT NULL DEFAULT 'vi-VN',
-    ADD COLUMN theme VARCHAR(16) NOT NULL DEFAULT 'system';
+    ADD COLUMN theme VARCHAR(16) NOT NULL DEFAULT 'system',
+    ADD CONSTRAINT chk_locale CHECK (locale IN ('vi-VN', 'en-US', 'zh-CN')),
+    ADD CONSTRAINT chk_theme CHECK (theme IN ('system', 'light', 'dark'));
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 86afe41 and eb244c1.

📒 Files selected for processing (24)
  • sep490-commons/api/src/main/java/green_buildings/commons/api/enums/UserLocale.java (1 hunks)
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/JwtAuthenticationConverter.java (1 hunks)
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/UserContextData.java (1 hunks)
  • sep490-frontend/src/app/app.component.ts (2 hunks)
  • sep490-frontend/src/app/app.module.ts (0 hunks)
  • sep490-frontend/src/app/components/header/header.component.ts (3 hunks)
  • sep490-frontend/src/app/modules/authorization/authorization.module.ts (2 hunks)
  • sep490-frontend/src/app/modules/authorization/components/create-user/enterprise-user-details.component.ts (2 hunks)
  • sep490-frontend/src/app/modules/authorization/components/users/users.component.ts (2 hunks)
  • sep490-frontend/src/app/modules/authorization/services/enterprise-user.service.ts (1 hunks)
  • sep490-frontend/src/app/modules/core/services/theme.service.ts (5 hunks)
  • sep490-frontend/src/app/modules/shared/enums/user-language.enum.ts (1 hunks)
  • sep490-frontend/src/app/modules/shared/interceptor/language.interceptor.ts (0 hunks)
  • sep490-frontend/src/app/modules/shared/models/user-configs.ts (1 hunks)
  • sep490-frontend/src/app/services/user.service.ts (1 hunks)
  • sep490-idp/src/main/java/green_buildings/idp/dto/UserConfigs.java (1 hunks)
  • sep490-idp/src/main/java/green_buildings/idp/entity/UserEntity.java (1 hunks)
  • sep490-idp/src/main/java/green_buildings/idp/rest/UserResource.java (1 hunks)
  • sep490-idp/src/main/java/green_buildings/idp/security/MvcUserContextData.java (1 hunks)
  • sep490-idp/src/main/java/green_buildings/idp/service/UserService.java (2 hunks)
  • sep490-idp/src/main/java/green_buildings/idp/service/impl/LoginService.java (1 hunks)
  • sep490-idp/src/main/java/green_buildings/idp/service/impl/UserInfoService.java (2 hunks)
  • sep490-idp/src/main/java/green_buildings/idp/service/impl/UserServiceImpl.java (2 hunks)
  • sep490-idp/src/main/resources/db/migration/V0.0.1.8__UserConfigs.sql (1 hunks)
💤 Files with no reviewable changes (2)
  • sep490-frontend/src/app/modules/shared/interceptor/language.interceptor.ts
  • sep490-frontend/src/app/app.module.ts
✅ Files skipped from review due to trivial changes (3)
  • sep490-frontend/src/app/modules/shared/enums/user-language.enum.ts
  • sep490-frontend/src/app/modules/authorization/services/enterprise-user.service.ts
  • sep490-idp/src/main/java/green_buildings/idp/service/impl/UserInfoService.java
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build Java Modules (sep490-enterprise)
🔇 Additional comments (12)
sep490-frontend/src/app/modules/core/services/theme.service.ts (2)

6-7: LGTM! Imports are correctly added.

The new imports for UserService and Theme model are properly added and necessary for the enhanced theme management functionality.


51-54: LGTM! Constructor injection follows best practices.

The UserService is properly injected following Angular's dependency injection pattern, and the readonly modifier is correctly used.

sep490-frontend/src/app/modules/authorization/authorization.module.ts (1)

8-8: LGTM! Service replacement is properly configured.

The module correctly imports and provides the new EnterpriseUserService as a replacement for UserService.

Also applies to: 17-17

sep490-idp/src/main/java/green_buildings/idp/security/MvcUserContextData.java (1)

22-22: LGTM! Locale support properly integrated.

The locale from UserEntity is correctly passed to the superclass constructor, enabling language management support.

sep490-frontend/src/app/services/user.service.ts (1)

1-19: LGTM! Well-structured service implementation.

The service is properly decorated, injected, and implements user configuration management with proper typing and observables.

sep490-idp/src/main/java/green_buildings/idp/service/UserService.java (1)

31-33: LGTM! Well-defined service methods.

The new methods are properly typed and follow Java conventions:

  • findByEmail appropriately uses Optional for nullable results
  • update method signature is clear and concise
sep490-idp/src/main/java/green_buildings/idp/service/impl/LoginService.java (1)

29-30: LGTM! Code readability improvement.

Extracting MvcUserContextData creation to a separate variable improves code readability and maintainability.

sep490-frontend/src/app/app.component.ts (2)

23-32: Verify language code handling.

While the subscription logic is well-implemented with proper lifecycle management, the language code splitting might need validation to handle malformed language codes.

Consider adding a fallback:

-        this.translate.use(userConfigs.language.split('-')[0]);
+        const langCode = userConfigs.language?.split('-')?.[0] || 'en';
+        this.translate.use(langCode);

43-45: LGTM! Proper cleanup implementation.

The component correctly cleans up subscriptions using the destroy$ subject.

sep490-frontend/src/app/components/header/header.component.ts (1)

10-14: LGTM! Type safety improvement.

Using the UserLanguage enum instead of string type improves type safety and maintainability.

sep490-frontend/src/app/modules/authorization/components/create-user/enterprise-user-details.component.ts (2)

28-28: LGTM! Service import updated for better separation of concerns.

The change from UserService to EnterpriseUserService aligns with the component's enterprise-specific functionality.


128-128: LGTM! Constructor dependency updated to match the service change.

The constructor parameter type has been correctly updated to match the imported service.

@nganntqe170236 nganntqe170236 merged commit 8f89909 into main Feb 23, 2025
8 checks passed
@thongdanghoang thongdanghoang deleted the bugfix/96-language-management-by-parameter-lang-from-idp-to-angular-and-vice-versa branch February 26, 2025 06:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants