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: Submit building subscription #155

Merged
merged 1 commit into from
Feb 25, 2025
Merged

Conversation

GiaBaorr
Copy link
Collaborator

@GiaBaorr GiaBaorr commented Feb 25, 2025

Summary by CodeRabbit

  • New Features

    • Introduced subscription endpoints that enable enterprise owners to subscribe and view credit conversion ratios.
    • Enhanced subscription management with effective date ranges, device limits, and transaction tracking.
    • Enabled secure wallet fund withdrawals with balance validation.
  • Chores

    • Updated back-end logic, front-end models, and database schema to support new credit conversion and subscription functionalities.

Copy link

coderabbitai bot commented Feb 25, 2025

Walkthrough

This pull request introduces new DTOs, entities, enums, and service layers to support credit conversion ratios and subscription functionality. Changes include new records for data transfer, additional entity fields and relationships (including subscription and transaction enhancements), and new repository methods to support business queries. A REST controller and underlying service implementation handle subscription requests with validations, wallet operations, and error handling. Furthermore, the pull request adds SQL migration scripts for creating and updating database tables as well as front-end models and configuration enhancements for testing and logging.

Changes

File(s) Change Summary
sep490-enterprise/.../dtos/CreditConvertRatioDTO.java
sep490-enterprise/.../dtos/SubscribeRequestDTO.java
New DTO records for credit conversion ratios and subscription requests (with validation constraints).
sep490-enterprise/.../entities/CreditConvertRatioEntity.java
sep490-enterprise/.../entities/SubscriptionEntity.java
sep490-enterprise/.../entities/TransactionEntity.java
sep490-enterprise/.../entities/WalletEntity.java
New entity for credit conversion ratios; updated SubscriptionEntity with new date/device fields and methods; TransactionEntity now captures additional transaction details; WalletEntity adds a withdraw method.
sep490-enterprise/.../entities/CreditConvertType.java
sep490-enterprise/.../entities/TransactionType.java
New enumerations defining credit conversion types and transaction types.
sep490-enterprise/.../mappers/CreditConvertRatioMapper.java New MapStruct mapper interface to convert between entity and DTO objects.
sep490-enterprise/.../repositories/BuildingRepository.java
sep490-enterprise/.../repositories/CreditConvertRatioRepository.java
sep490-enterprise/.../repositories/SubscriptionRepository.java
BuildingRepository now includes a method for non-paginated queries; new repository for CreditConvertRatioEntity; SubscriptionRepository adds a method to fetch currently valid subscriptions.
sep490-enterprise/.../rest/SubscriptionController.java New REST controller exposing endpoints for retrieving credit conversion ratios and processing subscription requests.
sep490-enterprise/.../services/SubscriptionService.java
sep490-enterprise/.../services/impl/SubscriptionServiceImpl.java
New service interface and its implementation handling subscription logic, including validation, transaction processing, and wallet management.
sep490-enterprise/.../resources/db/migration/V0.0.1.9__CreditSubscription.sql
sep490-idp/.../data/temp-data.sql
New SQL migration script creating/updating tables and inserting initial credit conversion ratio data.
sep490-frontend/.../models/enterprise.dto.ts New front-end DTOs and enum for credit conversion and subscription request data structures.
sep490-enterprise/.../TestcontainersConfigs.java Updated test configuration to enable DEBUG logging for Flyway.

Sequence Diagram(s)

GET /api/subscription/convert-ratio Flow

sequenceDiagram
    participant C as Client
    participant SC as SubscriptionController
    participant SS as SubscriptionService
    participant M as CreditConvertRatioMapper
    participant DB as Database

    C->>SC: GET /api/subscription/convert-ratio
    SC->>SS: getCreditConvertRatios()
    SS->>DB: Query credit conversion ratios
    DB-->>SS: Return entity list
    SS->>M: Map entities to DTOs
    M-->>SS: Return DTO list
    SC-->>C: 200 OK with DTO list
Loading

POST /api/subscription Flow

sequenceDiagram
    participant C as Client
    participant SC as SubscriptionController
    participant SS as SubscriptionService

    C->>SC: POST /api/subscription (SubscribeRequestDTO)
    SC->>SS: subscribe(request)
    SS->>SS: Validate & process subscription (check dates, devices, wallet, etc.)
    SS-->>SC: Success or error outcome
    SC-->>C: 201 Created (or error response)
Loading

Suggested labels

user story, improvement

Suggested reviewers

  • thongdanghoang
  • huynhlephcvinh
  • nganntqe170236

Poem

Oh, I hop with joy in my code-filled glade,
New DTOs and entities in the tech parade.
Subscriptions and transactions dance in delight,
Mapping and migrations keep everything right.
With a twitch of my nose and a happy little bound,
I celebrate these changes with a joyful sound!
🐇✨ Happy coding from your rabbit friend!

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

🧹 Nitpick comments (16)
sep490-enterprise/src/main/java/enterprise/entities/CreditConvertRatioEntity.java (1)

20-21: Consider using BigDecimal instead of double for financial values

Using double for financial calculations can lead to precision issues. BigDecimal is generally recommended for monetary values.

    @Column(name = "ratio")
-   private double ratio;
+   private BigDecimal ratio;

Don't forget to add the import:

import java.math.BigDecimal;
sep490-enterprise/src/main/java/enterprise/repositories/CreditConvertRatioRepository.java (1)

9-11: Consider adding a findByConvertType query method

The repository currently only provides standard CRUD operations. Adding a specific finder method for convertType would improve usability since it's a common lookup scenario.

@Repository
public interface CreditConvertRatioRepository extends JpaRepository<CreditConvertRatioEntity, UUID> {
+    Optional<CreditConvertRatioEntity> findByConvertType(CreditConvertType convertType);
}

Don't forget to add the import:

import enterprise.entities.CreditConvertType;
import java.util.Optional;
sep490-enterprise/src/main/java/enterprise/services/SubscriptionService.java (1)

9-13: Consider returning DTOs instead of entities.

The getCreditConvertRatios() method returns entity objects directly, which could leak implementation details to the presentation layer. This approach tightly couples your service layer with your data layer and might expose sensitive or unnecessary information.

- List<CreditConvertRatioEntity> getCreditConvertRatios();
+ List<CreditConvertRatioDTO> getCreditConvertRatios();

Additionally, the subscribe() method returns void, which doesn't provide any feedback about the result. Consider returning a response object that indicates success or provides information about the created subscription.

sep490-enterprise/src/main/java/enterprise/repositories/SubscriptionRepository.java (1)

18-18: Consider pagination for potentially large result sets.

Similar to the BuildingRepository, this method returns all valid subscriptions without pagination, which could lead to performance issues if there are many subscriptions.

Consider adding pagination to improve performance, especially if this method will be used in user-facing interfaces:

- List<SubscriptionEntity> findAllValidSubscriptions(@Param("now") LocalDate now);
+ Page<SubscriptionEntity> findAllValidSubscriptions(@Param("now") LocalDate now, Pageable pageable);
sep490-enterprise/src/main/java/enterprise/dtos/SubscribeRequestDTO.java (1)

8-15: Add validation constraints for all fields.

While you've added validation for months and numberOfDevices, other fields lack validation. Consider adding:

public record SubscribeRequestDTO(
-       UUID buildingId,
+       @NotNull UUID buildingId,
        @Min(1) int months,
        @Min(100) int numberOfDevices,
-       double monthRatio,
-       double deviceRatio,
-       TransactionType type) {
+       @NotNull @DecimalMin("0.0") double monthRatio,
+       @NotNull @DecimalMin("0.0") double deviceRatio,
+       @NotNull TransactionType type) {
}

Also, consider adding validation documentation to explain the business rules behind these constraints (e.g., why 100 is the minimum number of devices).

sep490-enterprise/src/main/java/enterprise/services/impl/SubscriptionServiceImpl.java (3)

55-55: Fix typo in comment.

There's a spelling error in the comment.

-        // Handel wallet
+        // Handle wallet

62-62: Fix typo in comment.

There's a spelling error in the comment.

-        // Handel Subscription
+        // Handle Subscription

116-120: Improve variable naming for clarity.

The variable name noDevicesRatio is confusing as it's actually representing the cost per device, not the absence of devices.

-        CreditConvertRatioEntity noDevicesRatio = creditConvertRatios
+        CreditConvertRatioEntity deviceRatio = creditConvertRatios
                 .stream()
-                .filter(x -> x.getConvertType().equals(CreditConvertType.MONTH))
+                .filter(x -> x.getConvertType().equals(CreditConvertType.DEVICE))
                 .findFirst()
                 .orElseThrow();
sep490-enterprise/src/main/java/enterprise/rest/SubscriptionController.java (1)

31-35: Consider renaming method to align with endpoint path.

The method name getCreditConvertRatio doesn't match the endpoint path /convert-ratio (singular vs. plural). For better code readability and consistency, consider renaming the method to getCreditConvertRatios() to match the plural form returned by the service.

-public ResponseEntity<List<CreditConvertRatioDTO>> getCreditConvertRatio() {
+public ResponseEntity<List<CreditConvertRatioDTO>> getCreditConvertRatios() {
sep490-enterprise/src/main/resources/db/migration/V0.0.1.9__CreditSubscription.sql (1)

15-22: Reconsider foreign key constraint naming and column nullability.

Two items to consider:

  1. The foreign key constraint name pk_subscriptions is misleading as 'pk' typically indicates a primary key, but this is a foreign key.
  2. All new columns are marked as NOT NULL, but depending on your business logic, some fields like amount, months, and number_of_devices might not apply to all transaction types.
ALTER TABLE transactions
    ADD COLUMN transaction_type VARCHAR(255) NOT NULL,
    ADD COLUMN subscription_id UUID NOT NULL,
-   ADD COLUMN amount DOUBLE PRECISION,
-   ADD COLUMN months INTEGER,
-   ADD COLUMN number_of_devices INTEGER;
+   ADD COLUMN amount DOUBLE PRECISION NULL,
+   ADD COLUMN months INTEGER NULL,
+   ADD COLUMN number_of_devices INTEGER NULL;
ALTER TABLE transactions
-   ADD CONSTRAINT pk_subscriptions FOREIGN KEY (subscription_id) REFERENCES subscriptions (subscription_id);
+   ADD CONSTRAINT fk_transaction_subscription FOREIGN KEY (subscription_id) REFERENCES subscriptions (subscription_id);
sep490-enterprise/src/main/java/enterprise/entities/TransactionEntity.java (2)

42-44: Consider using BigDecimal for financial amounts.

Using double for financial calculations can lead to precision issues. Consider using BigDecimal instead for more accurate financial operations.

@Column(name = "amount")
-private double amount;
+private BigDecimal amount;

Don't forget to add the import:

import java.math.BigDecimal;

45-49: Add validation constraints for numeric fields.

Consider adding validation annotations to ensure months and numberOfDevices contain valid values (e.g., positive numbers).

@Column(name = "months")
+@Min(value = 1, message = "Months must be at least 1")
private int months;

@Column(name = "number_of_devices")
+@Min(value = 1, message = "Number of devices must be at least 1")
private int numberOfDevices;

Don't forget to add the import:

import jakarta.validation.constraints.Min;
sep490-enterprise/src/main/java/enterprise/entities/SubscriptionEntity.java (4)

33-40: Add validation for date range and device count.

Consider adding validation annotations to ensure:

  1. startDate is before or equal to endDate
  2. maxNumberOfDevices has a valid positive value
+@NotNull
@Column(name = "start_date")
private LocalDate startDate;

+@NotNull
@Column(name = "end_date")
private LocalDate endDate;

@Column(name = "max_number_of_devices")
+@Min(value = 1, message = "Maximum number of devices must be at least 1")
private int maxNumberOfDevices;

Don't forget to add the import:

import jakarta.validation.constraints.Min;

42-45: Rename collection field to use plural form.

For better code readability and to follow standard conventions, rename the collection field from transaction to transactions.

@OneToMany(fetch = FetchType.LAZY,
           cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH},
           mappedBy = "subscription")
-private List<TransactionEntity> transaction = new ArrayList<>();
+private List<TransactionEntity> transactions = new ArrayList<>();

Also update the addTransaction method:

public void addTransaction(TransactionEntity transaction) {
-    this.transaction.add(transaction);
+    this.transactions.add(transaction);
}

47-51: Make isValid() method more testable.

For better testability, consider refactoring the method to accept the current date as a parameter:

-public boolean isValid() {
-    LocalDate now = LocalDate.now();
+public boolean isValid() {
+    return isValid(LocalDate.now());
+}
+
+public boolean isValid(LocalDate now) {
     return !now.isBefore(startDate)
            && !now.isAfter(endDate);
}

53-55: Add null check in addTransaction method.

Add a null check to prevent NullPointerException.

public void addTransaction(TransactionEntity transaction) {
+    if (transaction == null) {
+        return;
+    }
     this.transaction.add(transaction);
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4ddb062 and 77b4fa0.

📒 Files selected for processing (18)
  • sep490-enterprise/src/main/java/enterprise/dtos/CreditConvertRatioDTO.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/dtos/SubscribeRequestDTO.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/CreditConvertRatioEntity.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/CreditConvertType.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/SubscriptionEntity.java (2 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/TransactionEntity.java (2 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/TransactionType.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/WalletEntity.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/mappers/CreditConvertRatioMapper.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/repositories/BuildingRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/repositories/CreditConvertRatioRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/repositories/SubscriptionRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/rest/SubscriptionController.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/SubscriptionService.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/impl/SubscriptionServiceImpl.java (1 hunks)
  • sep490-enterprise/src/main/resources/db/migration/V0.0.1.9__CreditSubscription.sql (1 hunks)
  • sep490-frontend/src/app/modules/enterprise/models/enterprise.dto.ts (1 hunks)
  • sep490-idp/src/main/resources/data/temp-data.sql (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • sep490-enterprise/src/main/java/enterprise/entities/CreditConvertType.java
  • sep490-enterprise/src/main/java/enterprise/entities/TransactionType.java
🔇 Additional comments (15)
sep490-enterprise/src/main/java/enterprise/dtos/CreditConvertRatioDTO.java (1)

7-8: LGTM - Well-structured DTO using Java records

The DTO is well-designed using Java records, which provides immutability and automatic generation of necessary methods.

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

23-25: LGTM - Proper enum handling with unique constraint

The use of EnumType.STRING provides better readability in the database, and the unique constraint on convert_type ensures data integrity.

sep490-enterprise/src/main/java/enterprise/repositories/BuildingRepository.java (1)

15-15:

❓ Verification inconclusive

Consider pagination for potentially large result sets.

The method findAllByEnterpriseId returns all buildings for an enterprise without pagination. This could lead to performance issues if an enterprise has a large number of buildings.

If the number of buildings per enterprise is expected to be large, consider either:

  1. Using the existing paginated method findByEnterpriseId
  2. Adding a limit to this method
  3. Adding a comment explaining why a non-paginated version is needed

🏁 Script executed:

#!/bin/bash
# Check if there are existing buildings and estimate potential scale
echo "Checking building table structure and potential scale:"
rg -A 10 "CREATE TABLE.*building" --glob="*.sql"

Length of output: 4311


Action: Evaluate pagination for building retrieval

The repository method findAllByEnterpriseId(UUID enterpriseId) currently returns all building records for an enterprise without any pagination. Given that the database migration (V0.0.1.0__EnterpriseEntityRelationships.sql) creates the buildings table—suggesting that enterprises might have many entries—this approach could lead to performance issues with large result sets.

Please consider one of the following options:

  • Use the existing paginated method (e.g., findByEnterpriseId) if it meets the requirements.
  • Add pagination (limit/offset) to this method.
  • Alternatively, if returning all records is intentional due to business constraints, add a clarifying comment in the code.

Please verify that the chosen approach aligns with the expected scale for enterprise building data and addresses potential performance concerns.

sep490-enterprise/src/main/java/enterprise/repositories/SubscriptionRepository.java (1)

13-18: Well-structured JPQL query.

The query is clear and follows good practices with multi-line formatting for readability.

sep490-enterprise/src/main/java/enterprise/mappers/CreditConvertRatioMapper.java (1)

1-15: Clean and well-structured mapper interface.

The mapper interface is correctly defined with the @Mapper annotation and properly configured with Spring's component model. The mapping methods are appropriately named and follow the standard pattern for bidirectional entity-DTO conversion.

sep490-frontend/src/app/modules/enterprise/models/enterprise.dto.ts (2)

26-34: Well-defined enum and interface for credit conversion.

The CreditConvertType enum and CreditConvertRatio interface are properly defined and align well with their backend counterparts. Using keyof typeof CreditConvertType for the convertType property ensures type safety when working with the enum values.


36-43: Comprehensive SubscribeRequest interface.

The SubscribeRequest interface correctly extends BaseDTO and includes all necessary properties for handling subscription requests. The typing is appropriate and consistent with the backend model.

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

28-43: Well-structured service implementation with proper annotations.

The service class is properly annotated with Spring's @Service, @Transactional, @RequiredArgsConstructor, and includes appropriate logging with @Slf4j. Dependencies are correctly injected via constructor injection.

sep490-idp/src/main/resources/data/temp-data.sql (1)

23-28: Well-structured initial data for credit conversion ratios.

The SQL insertion statements for the credit_convert_ratio table are properly formatted and include the correct data for both MONTH and DEVICE conversion types with appropriate ratio values. This provides a good foundation for testing the subscription functionality.

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

22-25: Good controller structure with proper annotations.

The controller is well-organized with appropriate annotations for REST functionality, request mapping, and constructor dependency injection.


37-42: Appropriate security constraint and response status for subscription endpoint.

Correctly restricting access to enterprise owners and returning HTTP 201 (Created) status for successful subscription.

sep490-enterprise/src/main/resources/db/migration/V0.0.1.9__CreditSubscription.sql (2)

1-13: Good table definition with unique constraint.

The credit_convert_ratio table is properly defined with audit fields, UUID primary key, and a unique constraint on convert_type to prevent duplicates.


24-27: Appropriate subscription table modifications.

The additions to the subscriptions table are properly defined with appropriate NOT NULL constraints for required fields.

sep490-enterprise/src/main/java/enterprise/entities/TransactionEntity.java (2)

34-36: Proper enum mapping for transaction type.

The TransactionType enum is correctly mapped with EnumType.STRING to store the enum names in the database.


38-40: Good relationship definition with subscription entity.

The many-to-one relationship with SubscriptionEntity is properly set up with appropriate fetch type and nullable constraints.

@GiaBaorr GiaBaorr force-pushed the feature/submit-subscription branch from 77b4fa0 to c899364 Compare February 25, 2025 16:03
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

🧹 Nitpick comments (5)
sep490-enterprise/src/main/java/enterprise/entities/WalletEntity.java (2)

40-45: Consider adding validation for negative withdrawal amounts

While the method correctly prevents withdrawing more than the available balance, it doesn't validate if the withdrawal amount is negative. A negative withdrawal would effectively become a deposit.

public void withdraw(long amount) {
+    if (amount < 0) {
+        throw new IllegalArgumentException("Withdrawal amount must be positive");
+    }
    if (amount > balance) {
        throw new IllegalArgumentException("Insufficient balance");
    }
    balance -= amount;
}

40-45: Add Javadoc to document the method's behavior

Consider adding Javadoc to document the method's purpose and the exceptions it might throw, which would improve code clarity and maintainability.

+/**
+ * Withdraws the specified amount from the wallet.
+ *
+ * @param amount the amount to withdraw
+ * @throws IllegalArgumentException if the amount is greater than the current balance
+ */
public void withdraw(long amount) {
    if (amount > balance) {
        throw new IllegalArgumentException("Insufficient balance");
    }
    balance -= amount;
}
sep490-idp/src/main/resources/data/temp-data.sql (1)

22-29: SQL Insert for Credit Conversion Ratios is Correctly Structured

The new SQL block properly inserts seed data into the credit_convert_ratio table. The use of NOW() for the timestamp fields and gen_random_uuid() for the ID is appropriate, and the two rows provide distinct values for the convert_type field—aligning with the unique constraint defined in the corresponding migration script.

Optional Improvement: If this script may be executed multiple times (e.g., in testing or development environments), consider making the insertion idempotent by adding an ON CONFLICT DO NOTHING clause or similar strategy to prevent duplicate key errors.

sep490-enterprise/src/main/java/enterprise/entities/SubscriptionEntity.java (2)

42-45: Consider renaming the collection field to plural form.

The field name transaction represents a collection of transactions, so it should follow Java naming conventions and be plural (transactions).

-    private List<TransactionEntity> transaction = new ArrayList<>();
+    private List<TransactionEntity> transactions = new ArrayList<>();

39-40: Consider adding validation for maxNumberOfDevices.

To ensure data integrity, consider adding validation to ensure maxNumberOfDevices is a positive number.

    @Column(name = "max_number_of_devices")
+   @jakarta.validation.constraints.Positive
    private int maxNumberOfDevices;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 77b4fa0 and c899364.

📒 Files selected for processing (19)
  • sep490-enterprise/src/main/java/enterprise/dtos/CreditConvertRatioDTO.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/dtos/SubscribeRequestDTO.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/CreditConvertRatioEntity.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/CreditConvertType.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/SubscriptionEntity.java (2 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/TransactionEntity.java (2 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/TransactionType.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/WalletEntity.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/mappers/CreditConvertRatioMapper.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/repositories/BuildingRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/repositories/CreditConvertRatioRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/repositories/SubscriptionRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/rest/SubscriptionController.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/SubscriptionService.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/impl/SubscriptionServiceImpl.java (1 hunks)
  • sep490-enterprise/src/main/resources/db/migration/V0.0.1.9__CreditSubscription.sql (1 hunks)
  • sep490-enterprise/src/test/java/enterprise/TestcontainersConfigs.java (1 hunks)
  • sep490-frontend/src/app/modules/enterprise/models/enterprise.dto.ts (1 hunks)
  • sep490-idp/src/main/resources/data/temp-data.sql (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (15)
  • sep490-enterprise/src/main/java/enterprise/entities/CreditConvertType.java
  • sep490-enterprise/src/main/java/enterprise/entities/TransactionType.java
  • sep490-enterprise/src/main/java/enterprise/dtos/CreditConvertRatioDTO.java
  • sep490-enterprise/src/main/java/enterprise/repositories/CreditConvertRatioRepository.java
  • sep490-enterprise/src/main/java/enterprise/services/SubscriptionService.java
  • sep490-enterprise/src/main/java/enterprise/entities/CreditConvertRatioEntity.java
  • sep490-enterprise/src/main/java/enterprise/repositories/BuildingRepository.java
  • sep490-enterprise/src/main/java/enterprise/mappers/CreditConvertRatioMapper.java
  • sep490-enterprise/src/main/java/enterprise/services/impl/SubscriptionServiceImpl.java
  • sep490-enterprise/src/main/java/enterprise/repositories/SubscriptionRepository.java
  • sep490-enterprise/src/main/java/enterprise/rest/SubscriptionController.java
  • sep490-frontend/src/app/modules/enterprise/models/enterprise.dto.ts
  • sep490-enterprise/src/main/java/enterprise/entities/TransactionEntity.java
  • sep490-enterprise/src/main/resources/db/migration/V0.0.1.9__CreditSubscription.sql
  • sep490-enterprise/src/main/java/enterprise/dtos/SubscribeRequestDTO.java
🔇 Additional comments (5)
sep490-enterprise/src/test/java/enterprise/TestcontainersConfigs.java (1)

63-63: Appropriate Flyway logging configuration added.

Setting Flyway's logging level to DEBUG will provide more detailed information about database migrations during tests, which is particularly useful for troubleshooting the new credit subscription schema changes introduced in this PR.

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

40-45: LGTM: Withdrawal method implements proper balance validation

The implementation correctly validates if there's sufficient balance before withdrawing, preventing negative balances as recommended in the previous review.

sep490-enterprise/src/main/java/enterprise/entities/SubscriptionEntity.java (3)

4-5: New imports look good.

The added imports appropriately support the new fields and relationships being introduced to the subscription entity.

Also applies to: 10-10, 17-19


33-40: Date fields and device limit are well-structured.

The new fields (startDate, endDate, and maxNumberOfDevices) are properly annotated with @column and mapped to appropriate database columns.


47-51: The validity check method is well-implemented.

The isValid() method effectively checks if the current date falls within the subscription period.

@GiaBaorr GiaBaorr force-pushed the feature/submit-subscription branch from 1b4cb5c to 5ea0875 Compare February 25, 2025 16:43
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-enterprise/src/main/java/enterprise/entities/SubscriptionEntity.java (3)

47-51: Consider renaming and improving the date validation method.

The isValid() method checks if the current date falls within the subscription period, but the name doesn't explicitly convey this temporal check. A more descriptive name like isActive() or isCurrentlyValid() would better communicate its purpose.

Additionally, the date validation logic could be simplified for better readability:

-    public boolean isValid() {
+    public boolean isCurrentlyValid() {
         LocalDate now = LocalDate.now();
-        return !now.isBefore(startDate)
-               && !now.isAfter(endDate);
+        return (now.isEqual(startDate) || now.isAfter(startDate))
+               && (now.isEqual(endDate) || now.isBefore(endDate));
     }

Or even more concisely using the Java Time API:

-    public boolean isValid() {
+    public boolean isCurrentlyValid() {
         LocalDate now = LocalDate.now();
-        return !now.isBefore(startDate)
-               && !now.isAfter(endDate);
+        return now.compareTo(startDate) >= 0 && now.compareTo(endDate) <= 0;
     }

33-40: Add validation constraints to enhance data integrity.

The subscription date fields and device limit would benefit from validation annotations to ensure data integrity before persistence.

     @Column(name = "start_date")
+    @NotNull
     private LocalDate startDate;
     
     @Column(name = "end_date")
+    @NotNull
     private LocalDate endDate;
     
     @Column(name = "max_number_of_devices")
+    @Min(value = 1, message = "Number of devices must be at least 1")
     private int maxNumberOfDevices;

This ensures that:

  1. Date fields cannot be null, preventing potential issues with the isValid() method
  2. The maximum number of devices is always a positive value

45-45: Consider renaming the field to match its plural nature.

The field transaction represents a collection of transactions, so renaming it to transactions would make the code more intuitive and follow common naming conventions for collections.

-    private List<TransactionEntity> transaction = new ArrayList<>();
+    private List<TransactionEntity> transactions = new ArrayList<>();

Remember to update all references to this field throughout the class, including the addTransaction method.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1b4cb5c and 5ea0875.

📒 Files selected for processing (19)
  • sep490-enterprise/src/main/java/enterprise/dtos/CreditConvertRatioDTO.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/dtos/SubscribeRequestDTO.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/CreditConvertRatioEntity.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/CreditConvertType.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/SubscriptionEntity.java (2 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/TransactionEntity.java (2 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/TransactionType.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/entities/WalletEntity.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/mappers/CreditConvertRatioMapper.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/repositories/BuildingRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/repositories/CreditConvertRatioRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/repositories/SubscriptionRepository.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/rest/SubscriptionController.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/SubscriptionService.java (1 hunks)
  • sep490-enterprise/src/main/java/enterprise/services/impl/SubscriptionServiceImpl.java (1 hunks)
  • sep490-enterprise/src/main/resources/db/migration/V0.0.1.9__CreditSubscription.sql (1 hunks)
  • sep490-enterprise/src/test/java/enterprise/TestcontainersConfigs.java (1 hunks)
  • sep490-frontend/src/app/modules/enterprise/models/enterprise.dto.ts (1 hunks)
  • sep490-idp/src/main/resources/data/temp-data.sql (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (18)
  • sep490-enterprise/src/main/java/enterprise/entities/TransactionType.java
  • sep490-enterprise/src/main/java/enterprise/entities/CreditConvertType.java
  • sep490-enterprise/src/main/java/enterprise/entities/CreditConvertRatioEntity.java
  • sep490-enterprise/src/main/java/enterprise/services/SubscriptionService.java
  • sep490-enterprise/src/main/java/enterprise/dtos/CreditConvertRatioDTO.java
  • sep490-enterprise/src/main/java/enterprise/entities/WalletEntity.java
  • sep490-enterprise/src/main/java/enterprise/repositories/CreditConvertRatioRepository.java
  • sep490-enterprise/src/main/java/enterprise/repositories/SubscriptionRepository.java
  • sep490-enterprise/src/test/java/enterprise/TestcontainersConfigs.java
  • sep490-enterprise/src/main/java/enterprise/repositories/BuildingRepository.java
  • sep490-enterprise/src/main/java/enterprise/mappers/CreditConvertRatioMapper.java
  • sep490-frontend/src/app/modules/enterprise/models/enterprise.dto.ts
  • sep490-enterprise/src/main/java/enterprise/services/impl/SubscriptionServiceImpl.java
  • sep490-enterprise/src/main/java/enterprise/rest/SubscriptionController.java
  • sep490-enterprise/src/main/java/enterprise/dtos/SubscribeRequestDTO.java
  • sep490-idp/src/main/resources/data/temp-data.sql
  • sep490-enterprise/src/main/resources/db/migration/V0.0.1.9__CreditSubscription.sql
  • sep490-enterprise/src/main/java/enterprise/entities/TransactionEntity.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/entities/SubscriptionEntity.java (1)

53-58: The addTransaction implementation includes necessary null check and bidirectional relationship.

The method now properly checks for null and maintains the bidirectional relationship between subscription and transaction as recommended in the previous review.

@GiaBaorr GiaBaorr merged commit 39fc6cf into main Feb 25, 2025
8 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