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/credit-purchase #141

Merged
merged 3 commits into from
Feb 16, 2025
Merged

feature/credit-purchase #141

merged 3 commits into from
Feb 16, 2025

Conversation

GiaBaorr
Copy link
Collaborator

@GiaBaorr GiaBaorr commented Feb 16, 2025

Fetch list of credit packages

Summary by CodeRabbit

  • New Features

    • Introduced a refreshed plan interface that allows users to view and purchase credit packages with enhanced details and pricing display.
    • Enhanced payment processing with streamlined checkout links for credit purchases.
    • Added new functionality for retrieving credit package data from the backend API.
  • Refactor

    • Replaced legacy subscription views with the new plan experience.
    • Updated configuration settings to support the improved payment and credit package features.
  • Database

    • Modified the schema to support credit package functionalities with updated credit and pricing information.
  • Bug Fixes

    • Corrected display issues related to credit package information in the user interface.
  • Chores

    • Removed unused components and services to streamline the codebase.

Copy link

coderabbitai bot commented Feb 16, 2025

Walkthrough

The pull request implements a series of changes across multiple projects. In the enterprise backend, a new PayOS dependency is added, new DTOs, entities, mapper, repository, and service classes are introduced for credit packages, while the legacy BundleEntity and its repository are removed. The PaymentServiceImpl is enhanced with a new checkout link creation flow. The frontend sees import path updates and the renaming of SubscriptionComponent to PlanComponent with improved navigation. In contrast, the IDP project removes the PayOS dependency, payment service interfaces, implementations, and associated configurations.

Changes

File(s) Change Summary
sep490-enterprise/build.gradle
sep490-idp/build.gradle
Enterprise: Added dependency vn.payos:payos-java:1.0.3.
IDP: Removed the same dependency.
sep490-enterprise/src/main/resources/application.yml
sep490-enterprise/src/main/resources/db/migration/V0.0.1.6__CreditPackage.sql
sep490-idp/src/main/resources/application.yml
Enterprise: Added new payment properties (homepage, payos settings) and a migration script renaming the bundles table to credit_packages with added fields;
IDP: Removed the payment configuration section.
sep490-enterprise/src/main/java/enterprise/dtos/CreditPackageDTO.java
sep490-enterprise/src/main/java/enterprise/dtos/CreditPurchaseDTO.java
sep490-enterprise/src/main/java/enterprise/entities/CreditPackageEntity.java
sep490-enterprise/src/main/java/enterprise/mappers/CreditPackageMapper.java
sep490-enterprise/src/main/java/enterprise/repositories/CreditPackageRepository.java
sep490-enterprise/src/main/java/enterprise/rest/CreditPackageController.java
sep490-enterprise/src/main/java/enterprise/services/CreditPackageService.java
sep490-enterprise/src/main/java/enterprise/services/CreditPackageServiceImpl.java
Introduced new credit package domain: DTO records, a new entity, mapper interface, repository, REST controller exposing a GET endpoint, and service layer to manage credit packages.
sep490-enterprise/src/main/java/enterprise/entities/BundleEntity.java
sep490-enterprise/src/main/java/enterprise/entities/PaymentEntity.java
sep490-enterprise/src/main/java/enterprise/configs/PaymentConfig.java
sep490-enterprise/src/main/java/enterprise/services/impl/PaymentServiceImpl.java
Removed legacy BundleEntity and its repository; updated PaymentEntity by removing its bundle relationship; changed package declaration in PaymentConfig; enhanced PaymentServiceImpl with checkout link creation logic and supporting methods.
Frontend files:
sep490-frontend/src/app/modules/enterprise/components/building-details/building-details.component.ts
sep490-frontend/src/app/modules/enterprise/components/buildings/buildings.component.ts
sep490-frontend/src/app/modules/enterprise/components/payment/payment.component.html
sep490-frontend/src/app/modules/enterprise/components/payment/payment.component.ts
sep490-frontend/src/app/modules/enterprise/components/plan/plan.component.html
sep490-frontend/src/app/modules/enterprise/components/plan/plan.component.ts
sep490-frontend/src/app/modules/enterprise/enterprise-routing.module.ts
sep490-frontend/src/app/modules/enterprise/enterprise.module.ts
sep490-frontend/src/app/modules/enterprise/models/enterprise.dto.ts
sep490-frontend/src/app/modules/enterprise/services/credit-package.service.ts
sep490-frontend/src/app/services/building.service.ts
Updated import paths to a consolidated module; removed SubscriptionComponent and replaced it with a renamed PlanComponent including updated routing; added new navigation in PaymentComponent; introduced a new CreditPackageService in the frontend; and updated model interfaces in enterprise.dto.ts.
sep490-idp/src/main/java/green_buildings/idp/service/PaymentService.java
sep490-idp/src/main/java/green_buildings/idp/service/impl/PaymentServiceImpl.java
Removed the payment service interface and its implementation from the IDP project, eliminating PayOS-based payment processing.

Possibly related PRs

Suggested labels

improvement, task

Suggested reviewers

  • thongdanghoang
  • huynhlephcvinh
  • nganntqe170236

Poem

I’m a rabbit, hopping with delight,
Codes and configs making my day bright.
Bundles vanish and credits now bloom,
Payment paths guide with a joyful zoom.
With each new line, the system sings its tune!
🐇💻✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d3d712e and 839780e.

📒 Files selected for processing (4)
  • sep490-enterprise/src/main/java/enterprise/entities/CreditPackageEntity.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/rest/CreditPackageController.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/CreditPackageService.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/CreditPackageServiceImpl.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • sep490-enterprise/src/main/java/enterprise/services/CreditPackageService.java
  • sep490-enterprise/src/main/java/enterprise/entities/CreditPackageEntity.java
  • sep490-enterprise/src/main/java/enterprise/services/CreditPackageServiceImpl.java
  • sep490-enterprise/src/main/java/enterprise/rest/CreditPackageController.java
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build Java Modules (sep490-enterprise)

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

🔭 Outside diff range comments (1)
sep490-frontend/src/app/modules/enterprise/components/plan/plan.component.ts (1)

41-45: ⚠️ Potential issue

Implement the purchase logic in onBuyCredit.

The purchase logic is currently incomplete with just a comment placeholder.

Consider implementing:

  onBuyCredit(): void {
    if (this.selectedPackageId) {
-     // Handle purchase logic
+     this.registerSubscription(
+       this.creditPackageService.purchasePackage(this.selectedPackageId)
+         .subscribe({
+           next: (response) => {
+             // Handle successful purchase
+             this.getBalance(); // Refresh balance
+           },
+           error: (error) => {
+             console.error('Purchase failed:', error);
+             // Show error message to user
+           }
+         })
+     );
    }
  }
🧹 Nitpick comments (10)
sep490-frontend/src/app/modules/enterprise/components/buildings/buildings.component.ts (1)

117-183: Consider refactoring map-related code for better maintainability.

The map initialization and styling logic could be improved:

  1. Move map initialization to a dedicated service
  2. Extract magic numbers in map styles to constants
  3. Eliminate duplicate style objects in highlightFeature and resetFeature methods

Here's a suggested approach:

// Create a new file: map.service.ts
import {Injectable} from '@angular/core';
import * as L from 'leaflet';

@Injectable({
  providedIn: 'root'
})
export class MapService {
  private readonly DEFAULT_STYLE = {
    weight: 3,
    opacity: 0.5,
    color: '#008f68',
    fillOpacity: 0.8,
    fillColor: '#6DB65B'
  };

  private readonly HIGHLIGHT_STYLE = {
    weight: 10,
    opacity: 1.0,
    color: '#DFA612',
    fillOpacity: 1.0,
    fillColor: '#FAE042'
  };

  initMap(elementId: string, center: L.LatLngExpression, zoom: number): L.Map {
    const map = L.map(elementId, {center, zoom});
    
    const tiles = L.tileLayer(
      'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      {
        maxZoom: 18,
        minZoom: 3
      }
    );

    tiles.addTo(map);
    return map;
  }

  highlightFeature(e: L.LeafletMouseEvent): void {
    e.target.setStyle(this.HIGHLIGHT_STYLE);
  }

  resetFeature(e: L.LeafletMouseEvent): void {
    e.target.setStyle(this.DEFAULT_STYLE);
  }
}

Then update the component:

-  private initMap(): void {
-    if (document.getElementById('map')) {
-      this.map = L.map('map', {
-        center: [10.841394, 106.810052],
-        zoom: 20
-      });
-    } else {
-      throw new Error(
-        'Map element not found, should set id="map" to the map element'
-      );
-    }
-
-    const tiles = L.tileLayer(
-      'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
-      {
-        maxZoom: 18,
-        minZoom: 3
-      }
-    );
-
-    tiles.addTo(this.map);
-  }
+  constructor(
+    private readonly router: Router,
+    private readonly buildingService: BuildingService,
+    private readonly markerService: MarkerService,
+    private readonly shapeService: RegionService,
+    private readonly mapService: MapService
+  ) {
+    super();
+  }
+
+  private initMap(): void {
+    if (!document.getElementById('map')) {
+      throw new Error(
+        'Map element not found, should set id="map" to the map element'
+      );
+    }
+    this.map = this.mapService.initMap('map', [10.841394, 106.810052], 20);
+  }

-  private highlightFeature(e: L.LeafletMouseEvent): void {
-    const layer = e.target;
-
-    layer.setStyle({
-      weight: 10,
-      opacity: 1.0,
-      color: '#DFA612',
-      fillOpacity: 1.0,
-      fillColor: '#FAE042'
-    });
-  }
+  private highlightFeature = this.mapService.highlightFeature.bind(this.mapService);

-  private resetFeature(e: L.LeafletMouseEvent): void {
-    const layer = e.target;
-
-    layer.setStyle({
-      weight: 3,
-      opacity: 0.5,
-      color: '#008f68',
-      fillOpacity: 0.8,
-      fillColor: '#6DB65B'
-    });
-  }
+  private resetFeature = this.mapService.resetFeature.bind(this.mapService);
sep490-frontend/src/app/modules/enterprise/models/enterprise.dto.ts (1)

16-19: Consider using a more precise type for price handling.

The price field is typed as number which could lead to precision issues when handling currency values. Consider using a more appropriate type or adding documentation about the expected format (e.g., cents vs dollars).

 export interface CreditPackage extends BaseDTO {
   numberOfCredits: number;
-  price: number;
+  price: number; // Price in cents to avoid floating-point precision issues
 }
sep490-frontend/src/app/modules/enterprise/services/credit-package.service.ts (1)

7-8: Specify service registration scope.

Consider specifying the providedIn property in the @Injectable decorator to define the service's registration scope.

-@Injectable()
+@Injectable({
+  providedIn: 'root'
+})
sep490-enterprise/src/main/java/enterprise/services/CreditPackageServiceImpl.java (1)

19-21: Consider implementing pagination for large datasets.

The findAll() method returns all credit packages without pagination. This could lead to performance issues if the number of credit packages grows large.

-public List<CreditPackageEntity> findAll() {
-    return creditPackageRepository.findAll();
+public Page<CreditPackageEntity> findAll(Pageable pageable) {
+    return creditPackageRepository.findAll(pageable);
 }
sep490-enterprise/src/main/java/enterprise/entities/CreditPackageEntity.java (1)

25-28: Add documentation for price field.

The price field should have documentation specifying the unit of currency (e.g., cents vs dollars) to prevent confusion.

 @Column(name = "price", nullable = false)
 @Min(0)
 @NotNull
+// Price in cents to avoid floating-point precision issues
 private long price = 0;
sep490-enterprise/src/main/java/enterprise/rest/CreditPackageController.java (1)

23-25: Consider adding API documentation.

While the endpoint is well-implemented with proper role-based security, adding OpenAPI/Swagger annotations would improve API discoverability and documentation.

Add these annotations:

    @GetMapping
    @RolesAllowed({UserRole.RoleNameConstant.SYSTEM_ADMIN, UserRole.RoleNameConstant.ENTERPRISE_OWNER})
+   @Operation(summary = "Get all credit packages")
+   @ApiResponse(responseCode = "200", description = "Successfully retrieved credit packages")
    public List<CreditPackageDTO> findAll() {
sep490-frontend/src/app/modules/enterprise/components/plan/plan.component.ts (1)

55-61: Improve type safety in service subscription.

The service subscription lacks type information and error handling.

Add type safety and error handling:

  getCreditPackages(): void {
    this.registerSubscription(
-     this.creditPackageService.getAllCreditPackages().subscribe(rs => {
-       this.creditPackages = rs;
-     })
+     this.creditPackageService.getAllCreditPackages().subscribe({
+       next: (packages: CreditPackage[]) => {
+         this.creditPackages = packages;
+       },
+       error: (error) => {
+         console.error('Failed to fetch credit packages:', error);
+         // Show error message to user
+       }
+     })
    );
  }
sep490-frontend/src/app/modules/enterprise/components/payment/payment.component.ts (1)

103-109: Consider handling navigation promise.

The navigation method could handle the Promise returned by router.navigate to manage navigation failures.

-  navigateToSubscription(): void {
-    void this.router.navigate([
+  async navigateToSubscription(): Promise<void> {
+    try {
+      await this.router.navigate([
       '/',
       AppRoutingConstants.ENTERPRISE_PATH,
       AppRoutingConstants.PLAN_PATH
-    ]);
+      ]);
+    } catch (error) {
+      console.error('Navigation failed:', error);
+      // Handle navigation failure
+    }
   }
sep490-enterprise/src/main/java/enterprise/services/impl/PaymentServiceImpl.java (1)

48-57: Consider URL validation in setUrls method.

The setUrls method should validate the constructed URLs to ensure they are properly formatted.

 @PostConstruct
 public void setUrls() {
+    if (homepage == null || homepage.isEmpty()) {
+        throw new IllegalStateException("Homepage URL is not configured");
+    }
     returnUrl = UriComponentsBuilder.fromUriString(homepage)
                                   .path(returnPath)
                                   .build()
                                   .toUriString();
+    if (!returnUrl.startsWith("http")) {
+        throw new IllegalStateException("Invalid return URL: " + returnUrl);
+    }
     cancelUrl = UriComponentsBuilder.fromUriString(homepage)
                                   .path(cancelPath)
                                   .build()
                                   .toUriString();
+    if (!cancelUrl.startsWith("http")) {
+        throw new IllegalStateException("Invalid cancel URL: " + cancelUrl);
+    }
 }
sep490-enterprise/src/main/resources/application.yml (1)

69-69: Newline at End of File:

YAML lint recommends ending the file with a newline character. Please add a newline at the end of the file to conform with best practices.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 69-69: no new line character at the end of file

(new-line-at-end-of-file)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9a72163 and b8f8e1b.

📒 Files selected for processing (32)
  • sep490-enterprise/build.gradle (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/configs/PaymentConfig.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/dtos/CreditPackageDTO.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/dtos/CreditPurchaseDTO.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/BundleEntity.java (0 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/CreditPackageEntity.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/PaymentEntity.java (0 hunks)
  • sep490-enterprise/src/main/java/enterprise/mappers/CreditPackageMapper.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/repositories/BundleRepository.java (0 hunks)
  • sep490-enterprise/src/main/java/enterprise/repositories/CreditPackageRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/rest/CreditPackageController.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/CreditPackageService.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/CreditPackageServiceImpl.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/impl/PaymentServiceImpl.java (2 hunks)
  • sep490-enterprise/src/main/resources/application.yml (2 hunks)
  • sep490-enterprise/src/main/resources/db/migration/V0.0.1.6__CreditPackage.sql (1 hunks)
  • sep490-frontend/src/app/modules/enterprise/components/building-details/building-details.component.ts (1 hunks)
  • sep490-frontend/src/app/modules/enterprise/components/buildings/buildings.component.ts (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 (3 hunks)
  • sep490-frontend/src/app/modules/enterprise/components/plan/plan.component.html (2 hunks)
  • sep490-frontend/src/app/modules/enterprise/components/plan/plan.component.ts (2 hunks)
  • sep490-frontend/src/app/modules/enterprise/enterprise-routing.module.ts (2 hunks)
  • sep490-frontend/src/app/modules/enterprise/enterprise.module.ts (3 hunks)
  • sep490-frontend/src/app/modules/enterprise/models/building-details.dto.ts (0 hunks)
  • sep490-frontend/src/app/modules/enterprise/models/enterprise.dto.ts (1 hunks)
  • sep490-frontend/src/app/modules/enterprise/services/credit-package.service.ts (1 hunks)
  • sep490-frontend/src/app/services/building.service.ts (1 hunks)
  • sep490-idp/build.gradle (0 hunks)
  • sep490-idp/src/main/java/green_buildings/idp/service/PaymentService.java (0 hunks)
  • sep490-idp/src/main/java/green_buildings/idp/service/impl/PaymentServiceImpl.java (0 hunks)
  • sep490-idp/src/main/resources/application.yml (0 hunks)
💤 Files with no reviewable changes (8)
  • sep490-frontend/src/app/modules/enterprise/models/building-details.dto.ts
  • sep490-idp/src/main/java/green_buildings/idp/service/PaymentService.java
  • sep490-enterprise/src/main/java/enterprise/entities/PaymentEntity.java
  • sep490-idp/build.gradle
  • sep490-enterprise/src/main/java/enterprise/entities/BundleEntity.java
  • sep490-enterprise/src/main/java/enterprise/repositories/BundleRepository.java
  • sep490-idp/src/main/java/green_buildings/idp/service/impl/PaymentServiceImpl.java
  • sep490-idp/src/main/resources/application.yml
✅ Files skipped from review due to trivial changes (3)
  • sep490-enterprise/src/main/java/enterprise/configs/PaymentConfig.java
  • sep490-frontend/src/app/services/building.service.ts
  • sep490-enterprise/src/main/java/enterprise/dtos/CreditPackageDTO.java
🧰 Additional context used
🪛 YAMLlint (1.35.1)
sep490-enterprise/src/main/resources/application.yml

[error] 69-69: no new line character at the end of file

(new-line-at-end-of-file)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build Java Modules (sep490-idp)
🔇 Additional comments (14)
sep490-frontend/src/app/modules/enterprise/components/building-details/building-details.component.ts (1)

19-19: LGTM! Good job consolidating DTOs.

The import path change aligns with the consolidation of DTOs into enterprise.dto.ts, which improves code organization and maintainability.

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

11-11: LGTM! Consistent with DTO consolidation.

The import path change aligns with the consolidation of DTOs into enterprise.dto.ts, maintaining consistency with other components.

sep490-enterprise/src/main/java/enterprise/entities/CreditPackageEntity.java (1)

20-23: Consider adding a maximum value constraint.

The numberOfCredits field has a minimum value constraint but no maximum value constraint. Consider adding an upper limit if there should be one.

 @Column(name = "number_of_credits", nullable = false)
 @Min(0)
+@Max(value = 1000000, message = "Number of credits cannot exceed 1,000,000")
 @NotNull
 private int numberOfCredits = 0;
sep490-enterprise/src/main/java/enterprise/rest/CreditPackageController.java (1)

15-18: LGTM! Well-structured controller implementation.

The controller follows Spring best practices with proper annotations and dependency injection using @RequiredArgsConstructor.

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

7-7: LGTM! Clean routing configuration update.

The replacement of SubscriptionComponent with PlanComponent is properly implemented with correct path configuration.

Also applies to: 24-26

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

6-6: LGTM! Module configuration properly updated.

The module is well-structured with:

  • Correct component declaration updates
  • Proper service registration in providers

Also applies to: 9-9, 19-19, 30-31

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

2-3: LGTM! Clean import additions.

The imports for Router and routing constants are appropriately added.


48-49: LGTM! Proper dependency injection.

The Router is correctly injected as a private readonly dependency.

sep490-enterprise/build.gradle (1)

28-28:

❓ Verification inconclusive

Verify PayOS SDK version and security.

Please verify the latest version of the PayOS SDK and check for any known vulnerabilities.


🌐 Web query:

What is the latest version of the PayOS Java SDK? Are there any known vulnerabilities?

💡 Result:

The latest version of the PayOS Java SDK isn't explicitly stated in publicly available documentation from the provided sources[1][7]. However, integration instructions indicate developers should use <version>{VERSION}</version> in Maven/Gradle configurations[7], suggesting users must check repositories like Maven Central or GitHub for updates.

For vulnerabilities:

  • No direct vulnerabilities are reported for PayOS’s Java SDK in the search results.
  • General Java ecosystem risks apply:
    • SpringShell (CVE-2022-22965): Affects Spring Framework versions 5.3.0–5.3.17 if using JDK 9+ and Tomcat[6].
    • JNDI Exploits: Vulnerable in older Java versions (e.g., JDK 1.8 <u191) when unsecured ORB listeners exist[2][8].

For secure integration:

  1. Use Java 17+ (recommended by PayOS demo projects)[1].
  2. Ensure dependencies like Spring/Protobuf are patched (e.g., Protobuf-Java ≥3.25.5 for Temporal SDK users)[5].
  3. Follow Payara Server mitigation guidelines if applicable (e.g., disable public ORB listeners)[2][8].

Always verify SDK versions via official channels like GitHub or Maven Central and monitor security advisories for dependencies like Spring or Protobuf[6][5].

Citations:


Attention: Verify PayOS SDK Version and Security

In the file sep490-enterprise/build.gradle at line 28, the dependency is hardcoded as follows:

implementation 'vn.payos:payos-java:1.0.3'

Based on the latest web query:

  • The current public documentation doesn’t explicitly state the latest version of the PayOS Java SDK. Please verify on Maven Central or the SDK’s official GitHub repository to ensure that version 1.0.3 is still recommended.
  • There are no directly reported vulnerabilities for the PayOS SDK. However, remain vigilant by checking overall dependency security (e.g., related Java ecosystem issues).

Action Items:

  • Manually confirm the most recent version of PayOS Java SDK.
  • Consider adopting a version management strategy (such as version ranges) if applicable.
  • Monitor dependency security advisories and ensure ancillary libraries (like Spring/Protobuf) are up to date.
sep490-enterprise/src/main/resources/application.yml (2)

13-13: New Homepage Configuration:

A new homepage property with the URL http://localhost:4200 has been added under spring.application. Verify that this URL is correct for your deployment environment.


63-69: Payment Integration Properties Added:

A new payment section under the root has been introduced for PayOS integration, including properties for client_id, api_key, checksum_key, returnPath, and cancelPath. These use environment placeholders with default values to prevent null entries. Please confirm that the default values and the environment variable fallbacks are appropriate for your staging/production environments.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 69-69: no new line character at the end of file

(new-line-at-end-of-file)

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

25-25: New Navigation Event Binding:

The <p-button> element now includes an (onClick)="navigateToSubscription()" binding. Ensure that the navigateToSubscription() method is defined in the corresponding component TypeScript file and navigates to the intended subscription page.

sep490-frontend/src/app/modules/enterprise/components/plan/plan.component.html (2)

99-100: Updated Credit Package Display:

The template now references {{ package.numberOfCredits }} instead of the previous {{ package.credits }}. This aligns with the backend DTO changes. Please confirm that all related services and mappers have been updated to reflect this change.


108-108: Price Formatting Update:

The price is now rendered using the Angular number pipe (| number: "1.0-0") and appended with VND for better clarity and localization. Verify that the data type of package.price is consistent with this formatting.

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

♻️ Duplicate comments (1)
sep490-enterprise/src/main/java/enterprise/services/CreditPackageService.java (1)

9-14: 🛠️ Refactor suggestion

Enhance service interface with essential operations and use DTOs.

The previous review comment about enhancing the service interface remains valid and unaddressed.

  1. The service interface is too thin. Consider adding common operations:
    • create
    • update
    • delete
    • findByPriceRange
  2. Return DTOs instead of entities to prevent entity exposure
  3. Add pagination support for the findAll method
+import enterprise.dtos.CreditPackageDTO;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.Pageable;
+import java.math.BigDecimal;
+import java.util.Optional;
+import java.util.UUID;

 public interface CreditPackageService {
-    List<CreditPackageEntity> findAll();
-    Optional<CreditPackageEntity> findById(UUID id);
+    Page<CreditPackageDTO> findAll(Pageable pageable);
+    Optional<CreditPackageDTO> findById(UUID id);
+    CreditPackageDTO create(CreditPackageDTO dto);
+    CreditPackageDTO update(UUID id, CreditPackageDTO dto);
+    void delete(UUID id);
+    List<CreditPackageDTO> findByPriceRange(BigDecimal minPrice, BigDecimal maxPrice);
 }
🧹 Nitpick comments (5)
sep490-enterprise/src/main/java/enterprise/services/CreditPackageServiceImpl.java (3)

15-15: Refine transaction rollback configuration.

The current configuration @Transactional(rollbackOn = Throwable.class) is too broad. Consider specifying more targeted exceptions for rollback.

-@Transactional(rollbackOn = Throwable.class)
+@Transactional(rollbackOn = {DataAccessException.class, IllegalArgumentException.class})

20-23: Add validation and error handling for findAll operation.

The current implementation lacks validation and error handling. Consider:

  1. Adding logging
  2. Handling potential repository exceptions
  3. Adding validation for empty results
 @Override
 public List<CreditPackageEntity> findAll() {
+    log.debug("Fetching all credit packages");
+    try {
         return creditPackageRepository.findAll();
+    } catch (DataAccessException e) {
+        log.error("Error fetching credit packages", e);
+        throw new ServiceException("Failed to fetch credit packages", e);
+    }
 }

25-28: Add validation and error handling for findById operation.

The current implementation lacks input validation and error handling. Consider:

  1. Validating the input UUID
  2. Adding logging
  3. Handling potential repository exceptions
 @Override
 public Optional<CreditPackageEntity> findById(UUID id) {
+    if (id == null) {
+        throw new IllegalArgumentException("Credit package id cannot be null");
+    }
+    log.debug("Fetching credit package with id: {}", id);
+    try {
         return creditPackageRepository.findById(id);
+    } catch (DataAccessException e) {
+        log.error("Error fetching credit package with id: {}", id, e);
+        throw new ServiceException("Failed to fetch credit package", e);
+    }
 }
sep490-enterprise/src/main/java/enterprise/rest/CreditPackageController.java (2)

18-21: Add OpenAPI documentation.

Add OpenAPI annotations to document the API endpoints.

+@Tag(name = "Credit Package", description = "Credit package management APIs")
 @RestController
 @RequestMapping("/api/credit-package")
 @RequiredArgsConstructor
 public class CreditPackageController {

26-33: Add OpenAPI documentation and response status for findAll endpoint.

Add proper documentation and response status for the findAll endpoint.

+@Operation(summary = "Get all credit packages", description = "Returns a list of all credit packages")
+@ApiResponse(responseCode = "200", description = "Successfully retrieved credit packages")
 @GetMapping
 @RolesAllowed({UserRole.RoleNameConstant.SYSTEM_ADMIN, UserRole.RoleNameConstant.ENTERPRISE_OWNER})
+@ResponseStatus(HttpStatus.OK)
 public List<CreditPackageDTO> findAll() {
     return creditPackageService.findAll()
                                .stream()
                                .map(mapper::entityToDTO)
                                .toList();
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b8f8e1b and d3d712e.

📒 Files selected for processing (3)
  • sep490-enterprise/src/main/java/enterprise/rest/CreditPackageController.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/CreditPackageService.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/CreditPackageServiceImpl.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build Java Modules (sep490-enterprise)

@GiaBaorr GiaBaorr closed this Feb 16, 2025
@GiaBaorr GiaBaorr reopened this Feb 16, 2025
@GiaBaorr GiaBaorr force-pushed the feature/credit-purchase branch from d3d712e to 839780e Compare February 16, 2025 14:47
@GiaBaorr GiaBaorr merged commit 9cb00b4 into main Feb 16, 2025
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants