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

feature: Refine wallet, payment component #129

Merged
merged 3 commits into from
Feb 16, 2025

Conversation

GiaBaorr
Copy link
Collaborator

@GiaBaorr GiaBaorr commented Feb 15, 2025

Summary by CodeRabbit

  • New Features

    • Introduced dynamic wallet balance retrieval, ensuring that payment and plan views display current balances.
    • Enforced role-based access on payment search and wallet balance endpoints for enterprise owners.
    • Integrated a dedicated wallet service to streamline balance management.
  • Refactor

    • Updated payment search logic to utilize enterprise-specific criteria for more accurate results.
  • Style

    • Adjusted UI spacing on payment views for a more balanced layout.
  • UI Text

    • Revised labels to display "Credits" consistently.

Copy link

coderabbitai bot commented Feb 15, 2025

Walkthrough

This update modifies the payment and wallet functionalities across backend and frontend modules. In the backend, payment queries now use an enterprise ID instead of a name, and wallet operations have been refactored to return a numerical balance. Role-based access restrictions have been added to both payment and wallet endpoints. On the frontend, components now extend a subscription-aware base class and retrieve wallet balance dynamically using a new WalletService, and subtle UI text and style updates have been applied.

Changes

File(s) Change Summary
sep490-enterprise/.../PaymentRepository.java,
sep490-enterprise/.../PaymentServiceImpl.java,
sep490-enterprise/.../PaymentController.java
Changed payment search from name-based to enterprise ID-based, with repository method signature and service logic updated; added @RolesAllowed restriction on search endpoint.
sep490-enterprise/.../WalletRepository.java,
sep490-enterprise/.../WalletController.java,
sep490-enterprise/.../WalletService.java,
sep490-enterprise/.../WalletServiceImpl.java
Introduced a new wallet query method based on enterprise ID; updated getBalance logic to return a Long instead of an entity; applied role-based access control on balance retrieval.
sep490-frontend/.../payment.component.ts,
sep490-frontend/.../payment.component.html,
sep490-frontend/.../plan/plan.component.ts,
sep490-frontend/.../enterprise.module.ts,
sep490-frontend/.../services/wallet.service.ts
Updated Payment and Plan components to extend SubscriptionAwareComponent and use WalletService for dynamic balance fetching; modified CSS padding and added WalletService to module providers; new WalletService added to call API.
sep490-frontend/.../assets/i18n/en.json Updated credit terminology from singular "Credit" to plural "Credits" in button label and title.

Possibly related PRs

Suggested labels

user story

Suggested reviewers

  • thongdanghoang
  • huynhlephcvinh
  • nganntqe170236

Poem

In a meadow of code, amidst fields so bright,
I’ve hopped through the changes, with bytes taking flight.
A tweak here, a patch there, ensuring all is alright,
Enterprise IDs lead the way, guiding with might.
With roles and balances dancing in the digital light 🐰✨.
Cheers to fresh hops in our updated code night!

✨ 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: 2

🧹 Nitpick comments (7)
sep490-enterprise/src/main/java/enterprise/repositories/PaymentRepository.java (1)

12-19: Good architectural choice using UUID for enterprise identification.

The shift from name-based to UUID-based enterprise identification is a robust architectural decision that:

  • Ensures better uniqueness guarantees
  • Aligns with best practices for entity identification
  • Improves security by not exposing potentially sensitive name information
sep490-enterprise/src/main/java/enterprise/services/impl/PaymentServiceImpl.java (1)

27-28: Add error handling and logging.

Consider adding:

  1. Specific exception handling for the orElseThrow()
  2. Logging for audit and debugging purposes

Example implementation:

 @Override
 public Page<PaymentEntity> search(SearchCriteriaDTO<PaymentCriteriaDTO> searchCriteria, Pageable pageable) {
-    UUID enterpriseId = SecurityUtils.getCurrentUserEnterpriseId().orElseThrow();
-    return payRepo.findByEnterpriseId(enterpriseId, pageable);
+    UUID enterpriseId = SecurityUtils.getCurrentUserEnterpriseId()
+        .orElseThrow(() -> new SecurityException("Enterprise ID not found in security context"));
+    log.debug("Searching payments for enterprise ID: {}", enterpriseId);
+    Page<PaymentEntity> results = payRepo.findByEnterpriseId(enterpriseId, pageable);
+    log.debug("Found {} payments", results.getTotalElements());
+    return results;
 }
sep490-frontend/src/app/modules/enterprise/services/wallet.service.ts (2)

1-5: Imports are well-structured for typical Angular development.

Using HttpClient, Observable, and application routing constants is standard practice. Consider storing external URLs in environment-based configs for clarity across different environments.


10-15: Consider adding error handling.

While this method is fine for simple usage, you might want to handle potential errors or failed requests (e.g., using catchError) to provide a more robust user experience.

sep490-enterprise/src/main/java/enterprise/services/impl/WalletServiceImpl.java (1)

22-28: LGTM! The return type change improves data encapsulation.

The change from returning WalletEntity to Long is a good improvement as it reduces unnecessary data exposure by returning only the balance.

However, consider improving error handling by providing a custom exception with a clear error message.

-                .orElseThrow();
+                .orElseThrow(() -> new WalletNotFoundException("Wallet not found for enterprise ID: " + enterpriseId));
sep490-frontend/src/app/modules/enterprise/components/plan/plan.component.ts (1)

50-54: Add error handling to the wallet balance subscription.

Consider handling potential errors in the subscription to provide better user feedback.

     this.registerSubscription(
       this.walletService.getWalletBalance().subscribe(result => {
         this.balance = result;
-      })
+      },
+      error => {
+        console.error('Failed to fetch wallet balance:', error);
+        this.applicationService.showErrorMessage('Failed to fetch wallet balance');
+      })
     );
sep490-frontend/src/app/modules/enterprise/components/payment/payment.component.ts (1)

87-91: Add error handling and consider extracting shared wallet balance logic.

  1. Add error handling to provide better user feedback.
  2. Consider extracting the wallet balance retrieval logic to a base class since it's shared with PlanComponent.
     this.registerSubscription(
       this.walletService.getWalletBalance().subscribe(result => {
         this.balance = result;
-      })
+      },
+      error => {
+        console.error('Failed to fetch wallet balance:', error);
+        this.applicationService.showErrorMessage('Failed to fetch wallet balance');
+      })
     );

Consider creating a base class:

export abstract class WalletAwareComponent extends SubscriptionAwareComponent {
  protected balance: number = 0;

  constructor(protected readonly walletService: WalletService,
              protected readonly applicationService: ApplicationService) {
    super();
  }

  protected getBalance(): void {
    this.registerSubscription(
      this.walletService.getWalletBalance().subscribe(
        result => {
          this.balance = result;
        },
        error => {
          console.error('Failed to fetch wallet balance:', error);
          this.applicationService.showErrorMessage('Failed to fetch wallet balance');
        }
      )
    );
  }
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8e3e609 and 922d111.

📒 Files selected for processing (13)
  • sep490-enterprise/src/main/java/enterprise/repositories/PaymentRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/repositories/WalletRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/rest/PaymentController.java (2 hunks)
  • sep490-enterprise/src/main/java/enterprise/rest/WalletController.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/WalletService.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/impl/PaymentServiceImpl.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/impl/WalletServiceImpl.java (1 hunks)
  • sep490-frontend/src/app/modules/enterprise/components/payment/payment.component.html (1 hunks)
  • sep490-frontend/src/app/modules/enterprise/components/payment/payment.component.ts (5 hunks)
  • sep490-frontend/src/app/modules/enterprise/components/plan/plan.component.ts (4 hunks)
  • sep490-frontend/src/app/modules/enterprise/enterprise.module.ts (2 hunks)
  • sep490-frontend/src/app/modules/enterprise/services/wallet.service.ts (1 hunks)
  • sep490-frontend/src/assets/i18n/en.json (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • sep490-frontend/src/assets/i18n/en.json
  • sep490-frontend/src/app/modules/enterprise/components/payment/payment.component.html
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build Java Modules (sep490-enterprise)
  • GitHub Check: Build Java Modules (sep490-idp)
🔇 Additional comments (14)
sep490-enterprise/src/main/java/enterprise/repositories/WalletRepository.java (2)

6-8: LGTM!

The new imports are correctly added and necessary for the new functionality.


9-11: Well-designed method signature!

The new findByEnterpriseId method follows best practices:

  • Returns Optional for null-safety
  • Uses UUID for reliable entity identification
  • Follows Spring Data JPA naming conventions for automatic query generation

This change aligns well with the shift from name-based to ID-based queries.

sep490-enterprise/src/main/java/enterprise/services/impl/PaymentServiceImpl.java (1)

27-28: LGTM! Good security improvement.

The change to use enterprise ID from the security context enforces proper access control at the enterprise level.

sep490-enterprise/src/main/java/enterprise/rest/PaymentController.java (2)

10-11: LGTM! Clean security imports added.

The new imports correctly support the role-based access control implementation.


29-30:

❓ Verification inconclusive

Good security enhancement with role-based access control!

The @RolesAllowed annotation appropriately restricts payment search functionality to enterprise owners, following the principle of least privilege.

Let's verify if other payment-related endpoints are consistently protected:


🏁 Script executed:

#!/bin/bash
# Search for other payment-related endpoints in the codebase
ast-grep --pattern 'class $_ {
  $$$
  @$_Mapping($_)
  $$$
  public $_ $_Payment($$$) {
    $$$
  }
  $$$
}'

Length of output: 111


Security enhancement approved—further manual validation required!

The application of the @RolesAllowed annotation on the searchPayment endpoint in PaymentController correctly restricts access to enterprise owners. However, the initial automated search for additional payment-related endpoints produced no output, so we cannot conclusively confirm that all payment endpoints are consistently protected. Please manually verify that any other endpoints handling payment data include appropriate access controls.

  • PaymentController (lines 29-30): @RolesAllowed applied correctly to the searchPayment endpoint.
  • Action Needed: Manually audit related payment endpoints to ensure consistent protection.
sep490-enterprise/src/main/java/enterprise/rest/WalletController.java (3)

4-6: New imports align with role-based access needs and wallet operations.

These imports for WalletService, UserRole, and RolesAllowed support the newly introduced role-based restriction and delegated wallet logic.


21-22: Constructor-based injection is properly used.

Using private final fields with @RequiredArgsConstructor is a recommended practice, ensuring immutability and a clean dependency injection pattern.


24-26: Verify that the correct enterprise context is used in walletService.getBalance().

Currently, userContextData is not passed into the service. Confirm that the service is deriving the correct enterprise ID or user context internally. Otherwise, consider updating the method signature to ensure correctness.

sep490-enterprise/src/main/java/enterprise/services/WalletService.java (1)

5-5: Returning a numeric balance matches the new approach.

Switching from returning an entity to a simple Long for the balance is consistent with the updated controller logic and improves clarity.

sep490-frontend/src/app/modules/enterprise/services/wallet.service.ts (2)

6-7: Angular service initialization is correct.

Decorating the class with @Injectable() and exporting it is the conventional approach for DI in Angular.


8-9: Constructor injection of HttpClient is standard.

No concerns here. This is a best practice to keep your service testable and maintainable.

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

12-12: LGTM! The WalletService is properly configured.

The service is correctly imported and added to the providers array, making it available for dependency injection throughout the module.

Also applies to: 22-28

sep490-frontend/src/app/modules/enterprise/components/plan/plan.component.ts (1)

15-18: LGTM! The component properly extends SubscriptionAwareComponent.

The inheritance is correctly implemented with proper constructor initialization.

Also applies to: 34-36

sep490-frontend/src/app/modules/enterprise/components/payment/payment.component.ts (1)

24-27: LGTM! The component properly extends SubscriptionAwareComponent.

The inheritance is correctly implemented with proper constructor initialization.

Also applies to: 41-47

@GiaBaorr GiaBaorr force-pushed the feature/i-dont-know-what-is-this branch from 922d111 to 2a05631 Compare February 15, 2025 08:49
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

🧹 Nitpick comments (3)
sep490-frontend/src/app/modules/enterprise/components/payment/payment.component.ts (1)

86-92: Add error handling to the wallet balance subscription.

While the subscription is properly managed, consider adding error handling to gracefully handle potential API failures:

  getBalance(): void {
    this.registerSubscription(
      this.walletService.getWalletBalance().subscribe(
-       result => {
-         this.balance = result;
-       }
+       {
+         next: (result) => {
+           this.balance = result;
+         },
+         error: (error) => {
+           console.error('Failed to fetch wallet balance:', error);
+           // Consider showing a user-friendly error message
+           this.balance = 0; // or any other fallback value
+         }
+       }
      )
    );
  }
sep490-enterprise/src/main/java/enterprise/services/impl/WalletServiceImpl.java (1)

22-28: Enhance error handling with custom exceptions.

While the implementation is clean and functional, consider improving error handling by:

  1. Using custom exceptions with meaningful messages
  2. Handling specific failure cases separately

Here's a suggested improvement:

    public Long getBalance(){
-        UUID enterpriseId = SecurityUtils.getCurrentUserEnterpriseId().orElseThrow();
+        UUID enterpriseId = SecurityUtils.getCurrentUserEnterpriseId()
+                .orElseThrow(() -> new UnauthorizedException("User not associated with an enterprise"));
         return walRepo
                 .findByEnterpriseId(enterpriseId)
                 .map(WalletEntity::getBalance)
-                .orElseThrow();
+                .orElseThrow(() -> new ResourceNotFoundException("Wallet not found for enterprise: " + enterpriseId));
    }
sep490-enterprise/src/main/java/enterprise/rest/WalletController.java (1)

23-27: Add API documentation and consider specific response status.

Consider the following improvements:

  1. Add OpenAPI/Swagger documentation
  2. Use specific HTTP status codes for different scenarios

Here's a suggested improvement:

     @GetMapping("/balance")
     @RolesAllowed(UserRole.RoleNameConstant.ENTERPRISE_OWNER)
+    @Operation(summary = "Get enterprise wallet balance",
+              description = "Retrieves the current balance for the authenticated enterprise owner's wallet")
+    @ApiResponse(responseCode = "200", description = "Balance retrieved successfully")
+    @ApiResponse(responseCode = "404", description = "Wallet not found")
+    @ApiResponse(responseCode = "403", description = "User not authorized")
     public ResponseEntity<Long> getBalance(@AuthenticationPrincipal UserContextData userContextData) {
-        return ResponseEntity.ok().body(walletService.getBalance());
+        return ResponseEntity.status(HttpStatus.OK).body(walletService.getBalance());
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 922d111 and 2a05631.

📒 Files selected for processing (13)
  • sep490-enterprise/src/main/java/enterprise/repositories/PaymentRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/repositories/WalletRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/rest/PaymentController.java (2 hunks)
  • sep490-enterprise/src/main/java/enterprise/rest/WalletController.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/WalletService.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/impl/PaymentServiceImpl.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/impl/WalletServiceImpl.java (1 hunks)
  • sep490-frontend/src/app/modules/enterprise/components/payment/payment.component.html (1 hunks)
  • sep490-frontend/src/app/modules/enterprise/components/payment/payment.component.ts (5 hunks)
  • sep490-frontend/src/app/modules/enterprise/components/plan/plan.component.ts (4 hunks)
  • sep490-frontend/src/app/modules/enterprise/enterprise.module.ts (2 hunks)
  • sep490-frontend/src/app/modules/enterprise/services/wallet.service.ts (1 hunks)
  • sep490-frontend/src/assets/i18n/en.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (8)
  • sep490-frontend/src/assets/i18n/en.json
  • sep490-frontend/src/app/modules/enterprise/components/payment/payment.component.html
  • sep490-frontend/src/app/modules/enterprise/enterprise.module.ts
  • sep490-frontend/src/app/modules/enterprise/services/wallet.service.ts
  • sep490-frontend/src/app/modules/enterprise/components/plan/plan.component.ts
  • sep490-enterprise/src/main/java/enterprise/repositories/WalletRepository.java
  • sep490-enterprise/src/main/java/enterprise/rest/PaymentController.java
  • sep490-enterprise/src/main/java/enterprise/services/WalletService.java
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build Java Modules (sep490-enterprise)
🔇 Additional comments (8)
sep490-enterprise/src/main/java/enterprise/repositories/PaymentRepository.java (1)

13-13: Well-designed repository method!

The new findByEnterpriseId method follows Spring Data JPA conventions and improves the codebase by:

  • Using UUID instead of name for more reliable identification
  • Supporting pagination for better performance with large datasets
  • Implementing enterprise-scoped queries for proper multi-tenant data isolation
sep490-enterprise/src/main/java/enterprise/services/impl/PaymentServiceImpl.java (2)

27-28: LGTM! Secure enterprise ID retrieval and proper transaction handling.

The implementation correctly retrieves the enterprise ID from SecurityUtils and uses proper transaction management.


26-29: Consider handling the unused search criteria parameter.

The searchCriteria parameter is still unused in the implementation.

Previous suggestions remain valid:

  1. Remove it if search filtering is no longer needed, or
  2. Incorporate it into the query to maintain filtering capability while still scoping by enterprise ID.
sep490-frontend/src/app/modules/enterprise/components/payment/payment.component.ts (3)

2-2: LGTM!

The new imports are correctly added and follow Angular's module organization best practices.

Also applies to: 12-12


24-27: LGTM! Good improvement in subscription management.

The component now properly extends SubscriptionAwareComponent for better subscription handling and explicitly implements OnInit. This change:

  • Improves memory management by properly handling subscription cleanup.
  • Makes the interface implementation more explicit, enhancing code clarity.

41-47: LGTM! Constructor properly initialized.

The constructor changes are well-implemented:

  • Correctly injects the WalletService for wallet balance functionality.
  • Properly calls super() as required when extending SubscriptionAwareComponent.
sep490-enterprise/src/main/java/enterprise/services/impl/WalletServiceImpl.java (1)

20-20: LGTM!

Good use of spacing for improved readability.

sep490-enterprise/src/main/java/enterprise/rest/WalletController.java (1)

21-22: LGTM!

Good use of constructor injection via @requiredargsconstructor for the WalletService dependency.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2a05631 and 88a65f6.

📒 Files selected for processing (3)
  • sep490-enterprise/src/main/java/enterprise/repositories/WalletRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/WalletService.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/impl/WalletServiceImpl.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • sep490-enterprise/src/main/java/enterprise/repositories/WalletRepository.java
  • sep490-enterprise/src/main/java/enterprise/services/WalletService.java
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build Java Modules (sep490-enterprise)
🔇 Additional comments (1)
sep490-enterprise/src/main/java/enterprise/services/impl/WalletServiceImpl.java (1)

20-20: LGTM!

@GiaBaorr GiaBaorr merged commit 7097cfc into main Feb 16, 2025
5 checks passed
@GiaBaorr GiaBaorr deleted the feature/i-dont-know-what-is-this branch February 16, 2025 04:54
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.

3 participants