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

crud-credit-package-ui #149

Merged
merged 3 commits into from
Feb 22, 2025
Merged

crud-credit-package-ui #149

merged 3 commits into from
Feb 22, 2025

Conversation

huynhlephcvinh
Copy link
Collaborator

@huynhlephcvinh huynhlephcvinh commented Feb 22, 2025

Summary by CodeRabbit

  • New Features

    • Added an administrative credit package search endpoint.
    • Introduced a new form component and routing for creating/updating credit packages.
    • Enhanced the package credit management UI with a structured table view and interactive elements.
  • Refactor

    • Enhanced routing and role-based access control with dedicated admin guards.
  • Chores

    • Updated translation strings for confirmation messages and package credit management.

These improvements empower administrators with robust tools for managing credit packages through an enriched UI and backend enhancements.

Copy link

coderabbitai bot commented Feb 22, 2025

Walkthrough

This pull request introduces new functionalities across both backend and frontend code. In the backend, new imports and search methods are added to support pagination and credit package searches. In the frontend, role-based routing guards are enhanced, and new components, services, and internationalization resources are added to manage the creation, updating, and display of credit packages. The changes include modifications to controller endpoints, service interfaces/implementations, routing constants, Angular components, and translation files.

Changes

File(s) Change Summary
sep490-enterprise/.../CreditPackageRepository.java Added new import statements for PaymentEntity, Page, Pageable, and UUID.
sep490-enterprise/.../CreditPackageController.java
sep490-enterprise/.../CreditPackageService.java
sep490-enterprise/.../CreditPackageServiceImpl.java
Introduced search functionality: new endpoint in the controller, new search(Pageable) method in the service interface, and its implementation using repository calls for paginated credit package search.
sep490-frontend/.../app-routing.constant.ts
sep490-frontend/.../app-routing.module.ts
Added new constant PACKAGE_CREDIT_DETAILS_PATH and updated guard logic by modifying authGuard and introducing AdminGuard for role-based route protection.
sep490-frontend/.../admin-routing.module.ts
sep490-frontend/.../admin.module.ts
Introduced new routing configurations and added the CreateUpdatePackageCreditComponent to the admin module declarations.
sep490-frontend/.../components/create-update-package-credit/*
sep490-frontend/.../components/package-credit/*
Added new Angular component CreateUpdatePackageCreditComponent with its HTML template and TypeScript logic, and overhauled PackageCreditComponent with enhanced table templates, interactions, and extended functionalities for editing, deleting, and displaying credit packages.
sep490-frontend/.../services/package-credit.service.ts Created PackageCreditService with methods to search, retrieve, create/update, and delete credit packages.
sep490-frontend/.../assets/i18n/en.json
sep490-frontend/.../assets/i18n/vi.json
sep490-frontend/.../assets/i18n/zh.json
Updated default confirmation messages and added new "admin": { "packageCredit": { ... } } sections for translations related to package credit management.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Controller as CreditPackageController
    participant Service as CreditPackageServiceImpl
    participant Repository as CreditPackageRepository

    Client->>+Controller: POST /search with SearchCriteriaDTO
    Controller->>+Service: Call search(pageable)
    Service->>+Repository: Execute paginated search
    Repository-->>-Service: Return Page<CreditPackageEntity>
    Service-->>-Controller: Return search results
    Controller->>Client: ResponseEntity<SearchResultDTO<CreditPackageDTO>>
Loading
sequenceDiagram
    participant Route
    participant Guard as AdminGuard
    participant AuthSvc as AuthService
    participant Router

    Route->>Guard: Evaluate access for SYSTEM_ADMIN
    Guard->>AuthSvc: Check authentication & user role
    AuthSvc-->>Guard: Return user role info
    alt Authorized (SYSTEM_ADMIN)
        Guard-->>Route: Return true (Access Granted)
    else Unauthorized
        Guard->>Router: Navigate to forbidden route
        Guard-->>Route: Return false (Access Denied)
    end
Loading

Possibly related PRs

  • Feat/manager credit package with role admin #143: The changes in the main PR are related to the retrieved PR as both involve modifications to the CreditPackageController class, specifically with the addition of methods for handling credit packages, including search and management functionalities.

Suggested labels

user story

Suggested reviewers

  • GiaBaorr
  • nganntqe170236
  • thongdanghoang

Poem

I'm a little bunny with a hop in my code,
Leaping through new endpoints on my digital road.
With search functions and guards, my world feels light,
Credit packages dancing in the moonlit night.
I nibble on bugs and sip sweet success tea,
Celebrating these changes as happy as can be! 🐰💻


📜 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 db0c2c0 and d4b3cc1.

📒 Files selected for processing (1)
  • sep490-enterprise/src/main/java/enterprise/rest/CreditPackageController.java (3 hunks)
🔇 Additional comments (3)
sep490-enterprise/src/main/java/enterprise/rest/CreditPackageController.java (3)

3-3: LGTM! Imports are correctly added for search functionality.

The new imports support pagination and search result handling.

Also applies to: 10-11


49-49: LGTM! Role-based access control is properly implemented.

Restricting create and delete operations to SYSTEM_ADMIN is appropriate for maintaining data integrity and security.

Also applies to: 78-78


84-93: Enhance error handling and input validation for the search endpoint.

While the endpoint is secured with role-based access, it could benefit from:

  • Input validation for page size and sort parameters
  • Proper error handling for invalid search criteria
  • Response documentation
@PostMapping("/search")
@RolesAllowed({UserRole.RoleNameConstant.SYSTEM_ADMIN})
+ @ApiOperation(value = "Search credit packages", response = SearchResultDTO.class)
+ @ApiResponses(value = {
+     @ApiResponse(code = 200, message = "Successfully retrieved credit packages"),
+     @ApiResponse(code = 400, message = "Invalid search criteria"),
+     @ApiResponse(code = 403, message = "Access denied")
+ })
public ResponseEntity<SearchResultDTO<CreditPackageDTO>> search(
+     @Valid
      @RequestBody SearchCriteriaDTO<Void> searchCriteria ) {
+     if (searchCriteria.page().size() > 100) {
+         throw new InvalidRequestException("Page size cannot exceed 100");
+     }
      var pageable = CommonMapper.toPageable(searchCriteria.page(), searchCriteria.sort());
      var searchResults = creditPackageService.search(pageable);
      return ResponseEntity.ok(
              CommonMapper.toSearchResultDTO(
                      searchResults,
                      mapper::entityToDTO));
}
✨ 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: 5

🧹 Nitpick comments (10)
sep490-frontend/src/app/app-routing.module.ts (1)

17-50: Consider extracting reusable role-check logic.
The authGuard code block is repeated in AdminGuard with minor modifications for role-based checks. This duplication can be extracted into a helper function that accepts the required role, reducing repetition and enhancing maintainability.

sep490-frontend/src/app/modules/admin/components/package-credit/package-credit.component.ts (1)

100-100: Correct the comment to reflect packages.
The inline comment references "the selected user's ID," but we’re retrieving the package’s ID.

-    const pkgId = this.selected[0].id; // Retrieve the selected user's ID.
+    const pkgId = this.selected[0].id; // Retrieve the selected package's ID.
sep490-frontend/src/app/modules/admin/admin-routing.module.ts (1)

19-24: Remove unnecessary template literals.

The template literals (${...}) are not needed for static strings without interpolation.

-        path: `${AppRoutingConstants.PACKAGE_CREDIT_DETAILS_PATH}`,
+        path: AppRoutingConstants.PACKAGE_CREDIT_DETAILS_PATH,
-        path: `${AppRoutingConstants.PACKAGE_CREDIT_DETAILS_PATH}/:id`,
+        path: AppRoutingConstants.PACKAGE_CREDIT_DETAILS_PATH + '/:id',
sep490-frontend/src/app/modules/admin/services/package-credit.service.ts (1)

11-11: Consider moving the endpoint to routing constants.

The endpoint string could be moved to AppRoutingConstants to maintain consistency with other API endpoints.

sep490-enterprise/src/main/java/enterprise/services/impl/CreditPackageServiceImpl.java (2)

3-14: Consider organizing imports by category.

The imports could be better organized into categories (e.g., core Java, Spring, domain, etc.) for better readability.

// Core Java imports
import java.util.*;

// Spring Framework imports
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

// Domain imports
import enterprise.entities.CreditPackageEntity;
import enterprise.entities.PaymentEntity;
import enterprise.repositories.CreditPackageRepository;
import enterprise.services.CreditPackageService;

// DTO imports
import enterprise.dtos.PaymentCriteriaDTO;
import green_buildings.commons.api.dto.SearchCriteriaDTO;

// Utility imports
import commons.springfw.impl.utils.SecurityUtils;

52-55: Consider enhancing the search method with filtering capabilities.

The current implementation returns all records without any filtering. Consider adding support for search criteria to filter results based on price range, number of credits, etc.

@Override
public Page<CreditPackageEntity> search(Pageable pageable) {
-   return creditPackageRepository.findAll(pageable);
+   // Example implementation with filtering
+   return creditPackageRepository.findByPriceBetweenAndNumberOfCreditsBetween(
+       searchCriteria.getMinPrice(),
+       searchCriteria.getMaxPrice(),
+       searchCriteria.getMinCredits(),
+       searchCriteria.getMaxCredits(),
+       pageable
+   );
}
sep490-frontend/src/app/modules/admin/components/create-update-package-credit/create-update-package-credit.component.ts (1)

28-33: Consider enhancing form validation rules.

While basic validation is in place, consider adding:

  • Maximum value validators for both fields
  • Pattern validator for price to ensure proper currency format
  • Custom validator to ensure price is proportional to credits
numberOfCredits: new FormControl(null, [
  Validators.required,
  Validators.min(1),
+ Validators.max(10000),
+ this.validateCreditsAndPrice
]),
price: new FormControl(null, [
  Validators.required,
  Validators.min(1),
+ Validators.max(1000000000),
+ Validators.pattern(/^\d+$/),
+ this.validateCreditsAndPrice
])
sep490-frontend/src/app/modules/admin/components/package-credit/package-credit.component.html (1)

35-52: Enhance accessibility for action buttons.

The action buttons lack proper ARIA labels and keyboard navigation support.

<p-button
    icon="pi pi-pencil"
    [rounded]="true"
    [text]="true"
    severity="info"
+   [attr.aria-label]="'Edit ' + rowData.numberOfCredits + ' credits package'"
+   [tabindex]="0"
    (onClick)="onEdit(rowData)"
/>
<p-button
    icon="pi pi-trash"
    [rounded]="true"
    [text]="true"
    severity="danger"
+   [attr.aria-label]="'Delete ' + rowData.numberOfCredits + ' credits package'"
+   [tabindex]="0"
    (onClick)="onDelete(rowData)"
/>
sep490-frontend/src/app/modules/admin/components/create-update-package-credit/create-update-package-credit.component.html (1)

56-56: CSS Class Naming Check

The class attribute on the button container includes *:min-w-24. This notation is unusual for Tailwind CSS or standard CSS classes. Verify whether this is intentional or a typo that needs correction.

sep490-frontend/src/assets/i18n/en.json (1)

212-235: New Translation Section for Package Credit

The new "packageCredit" object under "admin" includes properties for the title, table headers, input prompts, and messages for success and error outcomes. One point to note: the error message "Package Credit deleted unsuccessfully" is somewhat awkward. Consider revising it to "Failed to delete Package Credit" for better clarity.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4d7f23c and db0c2c0.

📒 Files selected for processing (16)
  • sep490-enterprise/src/main/java/enterprise/repositories/CreditPackageRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/rest/CreditPackageController.java (2 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/CreditPackageService.java (2 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/impl/CreditPackageServiceImpl.java (2 hunks)
  • sep490-frontend/src/app/app-routing.constant.ts (1 hunks)
  • sep490-frontend/src/app/app-routing.module.ts (3 hunks)
  • sep490-frontend/src/app/modules/admin/admin-routing.module.ts (2 hunks)
  • sep490-frontend/src/app/modules/admin/admin.module.ts (1 hunks)
  • sep490-frontend/src/app/modules/admin/components/create-update-package-credit/create-update-package-credit.component.html (1 hunks)
  • sep490-frontend/src/app/modules/admin/components/create-update-package-credit/create-update-package-credit.component.ts (1 hunks)
  • sep490-frontend/src/app/modules/admin/components/package-credit/package-credit.component.html (1 hunks)
  • sep490-frontend/src/app/modules/admin/components/package-credit/package-credit.component.ts (1 hunks)
  • sep490-frontend/src/app/modules/admin/services/package-credit.service.ts (1 hunks)
  • sep490-frontend/src/assets/i18n/en.json (2 hunks)
  • sep490-frontend/src/assets/i18n/vi.json (2 hunks)
  • sep490-frontend/src/assets/i18n/zh.json (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • sep490-enterprise/src/main/java/enterprise/repositories/CreditPackageRepository.java
🧰 Additional context used
🪛 Biome (1.9.4)
sep490-frontend/src/app/modules/admin/components/create-update-package-credit/create-update-package-credit.component.ts

[error] 51-51: The function should not return a value because its return type is void.

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.

(lint/correctness/noVoidTypeReturn)

⏰ 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 (15)
sep490-frontend/src/app/app-routing.module.ts (3)

2-2: No issues with the updated imports and references.
Everything looks appropriate for the new authentication logic.

Also applies to: 7-7, 15-15, 20-20


52-85: Verify handling of non-existent roles.
If a user doesn’t contain UserRole.SYSTEM_ADMIN, the guard navigates to FORBIDDEN. Confirm that any upstream logic consistently assigns roles properly, so valid admins aren't inadvertently blocked, nor unprivileged users allowed.


110-110: Route-guard usage looks good.
Switching to the AdminGuard for the admin route properly enforces system administrator access.

sep490-frontend/src/app/modules/admin/components/package-credit/package-credit.component.ts (2)

128-157: Well-structured delete logic and user feedback.
Clearing the selected array after deletion and triggering a table refresh is a clean approach for UI consistency, with success/error messages providing immediate feedback.


71-88:

✅ Verification successful

Verify defined translation keys.
The column headers use i18n keys like 'admin.packageCredit.table.numberCredit' and 'admin.packageCredit.table.price'. Ensure these keys exist in your translation files, so columns are properly labeled.


🏁 Script executed:

#!/bin/bash
rg -A 2 "admin\.packageCredit\.table\.numberCredit"
rg -A 2 "admin\.packageCredit\.table\.price"

Length of output: 1846


Translation Keys Verified and Consistent

The verification confirms that both translation keys (admin.packageCredit.table.numberCredit and admin.packageCredit.table.price) are used consistently across components (in both the package-credit and create-update-package-credit components). No further changes are required.

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

3-7: New imports look consistent.
These additions align well with the introduction of paginated searches.

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

8-14: LGTM! Component properly integrated into the module.

The CreateUpdatePackageCreditComponent is correctly imported and declared in the AdminModule.

sep490-frontend/src/app/app-routing.constant.ts (1)

26-26: LGTM! Routing constant properly defined.

The constant follows the established naming pattern and is properly grouped under the Admin Module section.

sep490-frontend/src/app/modules/admin/components/create-update-package-credit/create-update-package-credit.component.html (2)

2-10: Conditional Rendering Syntax Verification

The template uses @if (isEdit) to conditionally render the header. In standard Angular templates the preferred approach is to use structural directives (e.g. *ngIf). Please confirm if you are using a preprocessor or a custom templating engine that supports the @if syntax.


58-72: Button Event Binding Verification

The <p-button> components use (onClick)="submit()" and (onClick)="reset()" for event handling. Typically, Angular components listen on the (click) event unless the button component explicitly defines onClick as an output. Please verify that the event bindings are correctly named for your custom component library.

sep490-frontend/src/assets/i18n/zh.json (2)

6-6: Confirmation Message Update

The defaultConfirmMessage has been updated to "是否删除此行?" to reflect a row deletion context instead of user deletion. This update appears appropriate—please confirm that it aligns with the intended UX wording.


213-235: New Translation Section for Package Credit

A new "packageCredit" section under "admin" has been added with keys for title, table headers, input placeholders, and messages for success and error states. The messages currently indicate deletion outcomes (e.g. "信用包已删除"). Please confirm that these messages are meant for deletion actions and that their semantic context fits all intended credit package operations.

sep490-frontend/src/assets/i18n/en.json (1)

6-6: Confirmation Message Update

The defaultConfirmMessage is now "Do you want to delete this row?" which correctly reflects the new context for deletion confirmation.

sep490-frontend/src/assets/i18n/vi.json (2)

4-4: Confirmation Message Update

The defaultConfirmMessage has been updated to "Bạn có muốn xóa hàng này không?" to match the new deletion context. This change looks good—please ensure it is consistent with other language translations.


212-236: New Translation Section for Package Credit

A new "packageCredit" block under "admin" has been added with keys for the title, table headers, input placeholders, and messages for success and error scenarios. The messages, which indicate deletion outcomes, should be reviewed to ensure they match the intended operations in your UI.

@huynhlephcvinh huynhlephcvinh merged commit fd873a4 into main Feb 22, 2025
5 checks passed
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