Skip to content
This repository has been archived by the owner on Nov 26, 2024. It is now read-only.

Develop #965

Merged
merged 19 commits into from
Oct 1, 2024
Merged

Develop #965

merged 19 commits into from
Oct 1, 2024

Conversation

debasishchakraborty-egovt
Copy link
Collaborator

@debasishchakraborty-egovt debasishchakraborty-egovt commented Oct 1, 2024

Summary by CodeRabbit

  • New Features

    • Introduced configuration for generating reports in chronological order.
    • Enhanced search functionality for water connections with fuzzy search capabilities and improved filtering options.
  • Bug Fixes

    • Improved error handling for search queries when no matching records are found.
  • Refactor

    • Split payment processing methods for better handling of ledger reports based on configuration.
  • Chores

    • Updated application properties to support new report ordering feature.

Copy link

coderabbitai bot commented Oct 1, 2024

Walkthrough

The pull request introduces enhancements across several classes related to water connection services. Key modifications include the addition of a new configuration property for report ordering, improvements in SQL query construction for flexible searches, and refined payment processing logic in ledger reports. These changes collectively aim to enhance the functionality and configurability of the water connection service.

Changes

File Change Summary
.../WSConfiguration.java Added a boolean property isReportRequiredInChronnologicalOrder and updated application.properties.
.../WsQueryBuilder.java Updated SQL queries and methods to improve search capabilities and added fuzzy search functionality.
.../LedgerReportRowMapper.java Introduced a dependency on WSConfiguration, split payment handling into two methods, and updated tax calculation logic.

Possibly related PRs

Poem

In the land of water flows,
A change in order now bestows,
Reports in line, a sight to see,
Queries dance with glee,
Payments sorted, all in place,
A leap for progress, a joyful race! 🐇✨


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 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 and nitpick comments (8)
municipal-services/ws-services/src/main/java/org/egov/waterconnection/config/WSConfiguration.java (1)

315-317: Consider renaming the field for consistency and fixing a typo.

The addition of this configuration property is good, as it allows for flexible report ordering. However, there are a couple of points to consider:

  1. The field name isReportRequiredInChronnologicalOrder contains a typo. "Chronnological" should be "Chronological".
  2. The naming convention for boolean fields in this class typically starts with "is" (e.g., isLocalizationStateLevel), but the property name in the @Value annotation doesn't follow this pattern.

Consider applying the following changes:

-	@Value("${report.in.chronological.order}")
-	private boolean isReportRequiredInChronnologicalOrder;
+	@Value("${is.report.required.in.chronological.order}")
+	private boolean isReportRequiredInChronologicalOrder;

This change will:

  1. Fix the typo in the field name.
  2. Align the property name in the @Value annotation with the existing naming convention in the class.
municipal-services/ws-services/src/main/java/org/egov/waterconnection/repository/rowmapper/LedgerReportRowMapper.java (6)

7-7: Remove unused import statement

The import io.swagger.models.auth.In on line 4 appears to be unused. Removing unnecessary imports improves code cleanliness and reduces potential confusion.

Apply this diff to remove the unused import:

- import io.swagger.models.auth.In;

90-90: Remove unnecessary logging statement

The log statement on line 90 appears to be for debugging purposes and may not be needed in production code.

Apply this diff to remove the log statement:

- log.info("Arrers are "+ledgerReport.getDemand().getArrears()+" and monthandYear"+ ledgerReport.getDemand().getMonthAndYear());

160-163: Add braces for single-line conditional statements

For better readability and to avoid potential errors during future modifications, it's recommended to use braces {} even for single-line if-else statements.

Apply this diff:

 if(config.isReportRequiredInChronnologicalOrder())
-     addPaymentToLedgerChronlogicalOrder(monthlyRecordsList);
+ {
+     addPaymentToLedgerChronologicalOrder(monthlyRecordsList);
+ }
 else
-     addPaymentToLedger(monthlyRecordsList);
+ {
+     addPaymentToLedger(monthlyRecordsList);
+ }

252-263: Use lambda expressions for comparator

Java 8 and above supports lambda expressions, which can simplify the comparator code and improve readability.

Apply this diff to refactor the comparator using a lambda expression:

- monthlyRecordList.sort(new Comparator<Map<String, Object>>() {
-     @Override
-     public int compare(Map<String, Object> o1, Map<String, Object> o2) {
-         String monthAndYear1 = (String) o1.keySet().iterator().next();
-         String monthAndYear2 = (String) o2.keySet().iterator().next();
-         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy", Locale.ENGLISH);
-         YearMonth yearMonth1 = YearMonth.parse(monthAndYear1, formatter);
-         YearMonth yearMonth2 = YearMonth.parse(monthAndYear2, formatter);
-         return yearMonth1.compareTo(yearMonth2);
-     }
- });
+ monthlyRecordList.sort((o1, o2) -> {
+     String monthAndYear1 = o1.keySet().iterator().next();
+     String monthAndYear2 = o2.keySet().iterator().next();
+     DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy", Locale.ENGLISH);
+     YearMonth yearMonth1 = YearMonth.parse(monthAndYear1, formatter);
+     YearMonth yearMonth2 = YearMonth.parse(monthAndYear2, formatter);
+     return yearMonth1.compareTo(yearMonth2);
+ });

401-426: Add method documentation and adhere to JavaDoc standards

The comments for the getDemandGenerationDateOfNextMonth method are close to JavaDoc format but missing the @param and @return annotations. For consistency and better tooling support, consider updating the comments to follow JavaDoc standards.

Apply this diff:

 /**
-  * This method retrieves the demand generation date for the next month in the ledger report.
-  * If the next month is beyond the list size, it returns 0 to indicate no demand for a future month.
-  *
-  * @param monthlyRecordList The list of monthly ledger records.
-  * @param currentIndex The index of the current month.
-  * @return The demand generation date of the next month or 0 if there is no next month.
-  */
+  * Retrieves the demand generation date for the next month in the ledger report.
+  * If the next month is beyond the list size, it returns 0 to indicate no demand for a future month.
+  *
+  * @param monthlyRecordList The list of monthly ledger records
+  * @param currentIndex      The index of the current month
+  * @return The demand generation date of the next month or 0 if there is no next month
+  */

431-434: Use constants for tax head codes in queries

Hardcoding tax head codes like 'WS_ADVANCE_CARRYFORWARD' can lead to errors if the codes change. Consider defining constants or using an enum for tax head codes to improve maintainability.

Apply this diff:

+ private static final String TAX_HEAD_WS_ADVANCE_CARRYFORWARD = "WS_ADVANCE_CARRYFORWARD";

...

taxAmountQuery.append(" AND taxheadcode != '" + TAX_HEAD_WS_ADVANCE_CARRYFORWARD + "'");
municipal-services/ws-services/src/main/java/org/egov/waterconnection/repository/builder/WsQueryBuilder.java (1)

Line range hint 922-923: Prevent SQL Injection by using parameterized queries

In the methods getQueryForWCCountbyDemandDate and getQueryForWCCountForPreviousreadingdate, the tenantId is concatenated directly into the SQL query:

query.append("WHERE d.tenantid  = '" +criteria.getTenantId()+"' ");
// ...
query.append(" AND d.tenantid='"+criteria.getTenantId()+"') ");

Concatenating user input directly into SQL queries can lead to SQL injection vulnerabilities. To enhance security, use parameterized queries by replacing the concatenation with placeholders and adding the parameters to the preparedStatement list.

Apply this diff to fix the issue:

- query.append("WHERE d.tenantid  = '" + criteria.getTenantId() + "' ");
+ query.append("WHERE d.tenantid = ? ");
+ preparedStatement.add(criteria.getTenantId());

// ...

- " and d.tenantid='" + criteria.getTenantId() + "') ");
+ " and d.tenantid=?) ");
+ preparedStatement.add(criteria.getTenantId());

Ensure to update all occurrences where variables are concatenated into SQL strings within these methods and elsewhere in the code.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 861db5e and 0ac0432.

📒 Files selected for processing (4)
  • municipal-services/ws-services/src/main/java/org/egov/waterconnection/config/WSConfiguration.java (1 hunks)
  • municipal-services/ws-services/src/main/java/org/egov/waterconnection/repository/builder/WsQueryBuilder.java (1 hunks)
  • municipal-services/ws-services/src/main/java/org/egov/waterconnection/repository/rowmapper/LedgerReportRowMapper.java (7 hunks)
  • municipal-services/ws-services/src/main/resources/application.properties (1 hunks)
🔇 Additional comments (2)
municipal-services/ws-services/src/main/java/org/egov/waterconnection/repository/rowmapper/LedgerReportRowMapper.java (2)

58-59: Proper dependency injection of WSConfiguration

Injecting WSConfiguration using @Autowired is appropriate and follows best practices for managing configurations.


106-108: Ensure correct calculation of tax amounts with paymentExists flag

With the introduction of the paymentExists parameter in getMonthlyTaxAmount, verify that the method correctly calculates the tax amount based on whether payments have been made. This change alters the query behavior and could affect the accuracy of the tax calculations.

Comment on lines +209 to +211

#ledger-report-format
report.in.chronological.order=true
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Unutilized property report.in.chronological.order detected.

The property report.in.chronological.order=true is defined in application.properties and injected into WSConfiguration.java. However, it is not utilized anywhere within the codebase, which may indicate redundancy or an incomplete implementation.

Please consider the following actions:

  1. Remove the unused property if it is not required to avoid unnecessary configuration.
  2. Verify the intended use of this property to ensure that its implementation aligns with the project's objectives and to complete any pending functionality.
🔗 Analysis chain

Confirm the impact of enabling chronological ordering for ledger reports.

The addition of report.in.chronological.order=true is noted. This change appears to enable chronological ordering for ledger reports, which could affect how reports are generated and displayed in the application.

Please address the following points:

  1. Confirm that this change is intentional and aligns with the PR objectives.
  2. Verify the expected behavior of reports with this setting enabled.
  3. Update any relevant documentation or user guides to reflect this change in report ordering.
  4. Ensure thorough testing of affected reports to validate the impact of this change.

To help verify the impact of this change, you can run the following script to search for usage of this property in the codebase:

This will help identify where the property is being used and potentially affected areas of the code.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of the new property in the codebase
rg --type java --type kotlin "report\.in\.chronological\.order"

Length of output: 315


Script:

#!/bin/bash
# Search for all usages of the 'report.in.chronological.order' property in Java and Kotlin files
rg --type java --type kotlin "report\.in\.chronological\.order"

Length of output: 315


Script:

#!/bin/bash
# Find the variable name injected with 'report.in.chronological.order' in WSConfiguration.java
grep -E '@Value\("\${report\.in\.chronological\.order}"\)' municipal-services/ws-services/src/main/java/org/egov/waterconnection/config/WSConfiguration.java

# Assuming the variable name is 'reportInChronologicalOrder', search for its usages within the file
rg 'reportInChronologicalOrder' municipal-services/ws-services/src/main/java/org/egov/waterconnection/config/WSConfiguration.java

Length of output: 332

Comment on lines +248 to +426

ledgerReport.setTotalBalanceLeftInMonth(ledgerReport.getDemand().getTotal_due_amount().subtract(totalPaymentInMonth));
ledgerReport.setTotalPaymentInMonth(totalPaymentInMonth);
}
// Keep track of the last valid demand (non-zero demandGenerationDate)
if (ledgerReport.getDemand().getDemandGenerationDate() != 0) {
log.info("Last Valid Demand monnth:"+ledgerReport.getDemand());
lastValidDemandReport = ledgerReport;
}
if (!paymentMatched ) {
// Add a default PaymentLedgerReport if no payments matched
log.info("If not matched:"+ledgerReport.getDemand().getMonthAndYear());
PaymentLedgerReport defaultPaymentLedgerReport = new PaymentLedgerReport();
defaultPaymentLedgerReport.setCollectionDate(null);
defaultPaymentLedgerReport.setReceiptNo("N/A");
defaultPaymentLedgerReport.setPaid(BigDecimal.ZERO);
defaultPaymentLedgerReport.setBalanceLeft(ledgerReport.getDemand().getTotal_due_amount());

if (ledgerReport.getPayment() == null) {
ledgerReport.setPayment(new ArrayList<>());
}
ledgerReport.getPayment().add(defaultPaymentLedgerReport);
}


}

// Handle payments for months with no valid demands
if (lastValidDemandReport != null) {
log.info("Last month logic:"+lastValidDemandReport);
// Assign payments to the last valid demand if found
List<Payment> payments = addPaymentDetails(lastValidDemandReport.getDemand().getConnectionNo());
BigDecimal totalPaymentInMonthlastValidMonth = BigDecimal.ZERO;
BigDecimal totalBalanceLeftInMonthLatValidMonth=BigDecimal.ZERO;
lastValidDemandReport.getPayment().clear();
boolean ifLastDemandHavePayments= false;

if (payments != null && !payments.isEmpty()) {

for (Payment payment : payments) {
Long transactionDateLong = payment.getTransactionDate();
if (transactionDateLong >= lastValidDemandReport.getDemand().getDemandGenerationDate()) {
PaymentLedgerReport paymentLedgerReport = new PaymentLedgerReport();
paymentLedgerReport.setCollectionDate(transactionDateLong);
paymentLedgerReport.setReceiptNo(payment.getPaymentDetails().get(0).getReceiptNumber());
paymentLedgerReport.setPaid(payment.getTotalAmountPaid());
paymentLedgerReport.setBalanceLeft(payment.getTotalDue().subtract(paymentLedgerReport.getPaid()));

lastValidDemandReport.getPayment().add(paymentLedgerReport);
totalPaymentInMonthlastValidMonth = totalPaymentInMonthlastValidMonth.add(payment.getTotalAmountPaid());
totalBalanceLeftInMonthLatValidMonth = totalBalanceLeftInMonthLatValidMonth.add(payment.getTotalDue().subtract(payment.getTotalAmountPaid()));
ifLastDemandHavePayments=true;
}
}
lastValidDemandReport.setTotalBalanceLeftInMonth(lastValidDemandReport.getDemand().getTotal_due_amount().subtract(totalPaymentInMonthlastValidMonth));
lastValidDemandReport.setTotalPaymentInMonth(totalPaymentInMonthlastValidMonth);

}
if(!ifLastDemandHavePayments){
// Add a default PaymentLedgerReport if no payments matched
log.info("If not matched:"+lastValidDemandReport.getDemand().getMonthAndYear());
PaymentLedgerReport defaultPaymentLedgerReport = new PaymentLedgerReport();
defaultPaymentLedgerReport.setCollectionDate(null);
defaultPaymentLedgerReport.setReceiptNo("N/A");
defaultPaymentLedgerReport.setPaid(BigDecimal.ZERO);
defaultPaymentLedgerReport.setBalanceLeft(lastValidDemandReport.getDemand().getTotal_due_amount());

if (lastValidDemandReport.getPayment() == null) {
lastValidDemandReport.setPayment(new ArrayList<>());
}
lastValidDemandReport.getPayment().add(defaultPaymentLedgerReport);
}
}
}

/**
* This method retrieves the demand generation date for the next month in the ledger report.
* If the next month is beyond the list size, it returns 0 to indicate no demand for a future month.
*
* @param monthlyRecordList The list of monthly ledger records.
* @param currentIndex The index of the current month.
* @return The demand generation date of the next month or 0 if there is no next month.
*/
private Long getDemandGenerationDateOfNextMonth(List<Map<String, Object>> monthlyRecordList, int currentIndex) {
// Check if there is a next month in the list
if (currentIndex + 1 < monthlyRecordList.size()) {
// Get the next month's record
Map<String, Object> nextMonthRecord = monthlyRecordList.get(currentIndex + 1);

// Extract the LedgerReport object for the next month
LedgerReport nextMonthLedgerReport = (LedgerReport) nextMonthRecord.values().iterator().next();

// Return the demand generation date of the next month
if (nextMonthLedgerReport != null && nextMonthLedgerReport.getDemand() != null) {
return nextMonthLedgerReport.getDemand().getDemandGenerationDate();
}
}
// Return 0 if there is no next month or no valid demand for the next month
return 0L;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Refactor the addPaymentToLedgerChronologicalOrder method for maintainability

The addPaymentToLedgerChronologicalOrder method is lengthy and complex, which can make it difficult to understand and maintain. Consider refactoring it into smaller, well-named helper methods to enhance readability.

@@ -150,7 +157,11 @@ public List<Map<String, Object>> extractData(ResultSet resultSet) throws SQLExce
}
log.info("ledger report list" + monthlyRecordsList);
if (!monthlyRecordsList.isEmpty()) {
addPaymentToLedger(monthlyRecordsList);
if(config.isReportRequiredInChronnologicalOrder())
addPaymentToLedgerChronlogicalOrder(monthlyRecordsList);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Correct typo in method name addPaymentToLedgerChronlogicalOrder

There is a typo in the method name addPaymentToLedgerChronlogicalOrder. The correct spelling is addPaymentToLedgerChronologicalOrder. This typo occurs in both the method call and its definition.

Apply this diff to correct the method name:

- addPaymentToLedgerChronlogicalOrder(monthlyRecordsList);
+ addPaymentToLedgerChronologicalOrder(monthlyRecordsList);

Also, update the method definition accordingly:

- private void addPaymentToLedgerChronlogicalOrder(List<Map<String, Object>> monthlyRecordList) {
+ private void addPaymentToLedgerChronologicalOrder(List<Map<String, Object>> monthlyRecordList) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
addPaymentToLedgerChronlogicalOrder(monthlyRecordsList);
addPaymentToLedgerChronologicalOrder(monthlyRecordsList);

@@ -4,6 +4,7 @@
import io.swagger.models.auth.In;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.egov.waterconnection.config.WSConfiguration;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add missing import for Locale

The class uses Locale.ENGLISH in date formatting but does not import java.util.Locale. This could lead to a Compilation Error.

Apply this diff to add the necessary import:

+ import java.util.Locale;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import org.egov.waterconnection.config.WSConfiguration;
import org.egov.waterconnection.config.WSConfiguration;
import java.util.Locale;

@@ -199,7 +210,7 @@ private void addPaymentToLedger(List<Map<String, Object>> monthlyRecordList) {
Long transactionDateLong = payment.getTransactionDate();
LocalDate transactionDate = Instant.ofEpochMilli(transactionDateLong).atZone(ZoneId.systemDefault()).toLocalDate();
String transactionMonthAndYear = transactionDate.format(DateTimeFormatter.ofPattern("MMMM yyyy"));
if (ledgerReport.getDemand().getMonthAndYear().equals(transactionMonthAndYear)) {
if (ledgerReport.getDemand().getDemandGenerationDate().compareTo(transactionDateLong)<0 ) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Potential logic error in payment matching condition

The condition ledgerReport.getDemand().getDemandGenerationDate().compareTo(transactionDateLong) < 0 on line 213 may incorrectly filter payments. Typically, you may want to include payments made on the same day (<= 0) or ensure the logic aligns with business requirements.

Apply this diff if the intention is to include payments made on the same day:

- if (ledgerReport.getDemand().getDemandGenerationDate().compareTo(transactionDateLong) < 0 ) {
+ if (ledgerReport.getDemand().getDemandGenerationDate().compareTo(transactionDateLong) <= 0 ) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (ledgerReport.getDemand().getDemandGenerationDate().compareTo(transactionDateLong)<0 ) {
if (ledgerReport.getDemand().getDemandGenerationDate().compareTo(transactionDateLong) <= 0 ) {


LedgerReport ledgerReport = ledgerReports.get(monthAndYear);
ledgerReport.getDemand().setArrears(taxAmountResult.subtract(totalAmountPaidResult));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle potential NullPointerException when setting arrears

The method taxAmountResult.subtract(totalAmountPaidResult) could throw a NullPointerException if either taxAmountResult or totalAmountPaidResult is null. Ensure both variables are non-null before performing the subtraction.

Apply this diff to add null checks:

- ledgerReport.getDemand().setArrears(taxAmountResult.subtract(totalAmountPaidResult));
+ BigDecimal arrears = (taxAmountResult != null ? taxAmountResult : BigDecimal.ZERO)
+     .subtract(totalAmountPaidResult != null ? totalAmountPaidResult : BigDecimal.ZERO);
+ ledgerReport.getDemand().setArrears(arrears);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
ledgerReport.getDemand().setArrears(taxAmountResult.subtract(totalAmountPaidResult));
BigDecimal arrears = (taxAmountResult != null ? taxAmountResult : BigDecimal.ZERO)
.subtract(totalAmountPaidResult != null ? totalAmountPaidResult : BigDecimal.ZERO);
ledgerReport.getDemand().setArrears(arrears);

Comment on lines +301 to +305
Long nextMonthDemGenDateLong =getDemandGenerationDateOfNextMonth(monthlyRecordList, i);
log.info("nextMonthDemGenDateLong:"+nextMonthDemGenDateLong);
// Check if the payment date falls on or after the current demand's generation date
if (transactionDateLong >= currentDemandDate &&
(i + 1 == monthlyRecordList.size() || transactionDateLong < nextMonthDemGenDateLong )) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle potential division by zero or null values

In the payment date checks, ensure that nextMonthDemGenDateLong is not zero to prevent logical errors. If nextMonthDemGenDateLong can be zero, additional checks are needed to handle that scenario appropriately.

Apply this diff to add a check for zero values:

if (transactionDateLong >= currentDemandDate &&
-     (i + 1 == monthlyRecordList.size() || transactionDateLong < nextMonthDemGenDateLong)) {
+     (i + 1 == monthlyRecordList.size() || (nextMonthDemGenDateLong != 0 && transactionDateLong < nextMonthDemGenDateLong))) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Long nextMonthDemGenDateLong =getDemandGenerationDateOfNextMonth(monthlyRecordList, i);
log.info("nextMonthDemGenDateLong:"+nextMonthDemGenDateLong);
// Check if the payment date falls on or after the current demand's generation date
if (transactionDateLong >= currentDemandDate &&
(i + 1 == monthlyRecordList.size() || transactionDateLong < nextMonthDemGenDateLong )) {
Long nextMonthDemGenDateLong =getDemandGenerationDateOfNextMonth(monthlyRecordList, i);
log.info("nextMonthDemGenDateLong:"+nextMonthDemGenDateLong);
// Check if the payment date falls on or after the current demand's generation date
if (transactionDateLong >= currentDemandDate &&
(i + 1 == monthlyRecordList.size() || (nextMonthDemGenDateLong != 0 && transactionDateLong < nextMonthDemGenDateLong))) {

Comment on lines +385 to +398
if(!ifLastDemandHavePayments){
// Add a default PaymentLedgerReport if no payments matched
log.info("If not matched:"+lastValidDemandReport.getDemand().getMonthAndYear());
PaymentLedgerReport defaultPaymentLedgerReport = new PaymentLedgerReport();
defaultPaymentLedgerReport.setCollectionDate(null);
defaultPaymentLedgerReport.setReceiptNo("N/A");
defaultPaymentLedgerReport.setPaid(BigDecimal.ZERO);
defaultPaymentLedgerReport.setBalanceLeft(lastValidDemandReport.getDemand().getTotal_due_amount());

if (lastValidDemandReport.getPayment() == null) {
lastValidDemandReport.setPayment(new ArrayList<>());
}
lastValidDemandReport.getPayment().add(defaultPaymentLedgerReport);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Avoid code duplication when adding default payment ledger reports

The logic for adding a default PaymentLedgerReport when no payments are matched is repeated multiple times in the code. Consider extracting this logic into a separate method to adhere to the DRY (Don't Repeat Yourself) principle.

Apply this diff to create a helper method:

+ private void addDefaultPaymentLedgerReport(LedgerReport ledgerReport, BigDecimal totalDueAmount) {
+     PaymentLedgerReport defaultPaymentLedgerReport = new PaymentLedgerReport();
+     defaultPaymentLedgerReport.setCollectionDate(null);
+     defaultPaymentLedgerReport.setReceiptNo("N/A");
+     defaultPaymentLedgerReport.setPaid(BigDecimal.ZERO);
+     defaultPaymentLedgerReport.setBalanceLeft(totalDueAmount);
+     if (ledgerReport.getPayment() == null) {
+         ledgerReport.setPayment(new ArrayList<>());
+     }
+     ledgerReport.getPayment().add(defaultPaymentLedgerReport);
+ }

...

- // Existing code where default payment ledger report is added
- PaymentLedgerReport defaultPaymentLedgerReport = new PaymentLedgerReport();
- defaultPaymentLedgerReport.setCollectionDate(null);
- defaultPaymentLedgerReport.setReceiptNo("N/A");
- defaultPaymentLedgerReport.setPaid(BigDecimal.ZERO);
- defaultPaymentLedgerReport.setBalanceLeft(ledgerReport.getDemand().getTotal_due_amount());
- if (ledgerReport.getPayment() == null) {
-     ledgerReport.setPayment(new ArrayList<>());
- }
- ledgerReport.getPayment().add(defaultPaymentLedgerReport);
+ // Use the helper method
+ addDefaultPaymentLedgerReport(ledgerReport, ledgerReport.getDemand().getTotal_due_amount());

Committable suggestion was skipped due to low confidence.


// Return the demand generation date of the next month
if (nextMonthLedgerReport != null && nextMonthLedgerReport.getDemand() != null) {
return nextMonthLedgerReport.getDemand().getDemandGenerationDate();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle potential NullPointerException when accessing demand generation date

In the getDemandGenerationDateOfNextMonth method, ensure that getDemandGenerationDate() does not return null to prevent a NullPointerException.

Apply this diff to add a null check:

if (nextMonthLedgerReport != null && nextMonthLedgerReport.getDemand() != null) {
+     if (nextMonthLedgerReport.getDemand().getDemandGenerationDate() != null) {
          return nextMonthLedgerReport.getDemand().getDemandGenerationDate();
+     } else {
+         return 0L;
+     }
}

Committable suggestion was skipped due to low confidence.

@@ -208,7 +208,7 @@ public class WsQueryBuilder {
"ORDER BY startdate";

public static final String TAX_AMOUNT_QUERY="SELECT SUM(taxamount) FROM egbs_demanddetail_v1 WHERE " +
"demandid IN (SELECT id FROM egbs_demand_v1 WHERE consumercode = ? AND taxperiodto < ? AND status='ACTIVE') and taxheadcode!= 'WS_ADVANCE_CARRYFORWARD';";
"demandid IN (SELECT id FROM egbs_demand_v1 WHERE consumercode = ? AND taxperiodto < ? AND status='ACTIVE') ";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Ensure 'taxperiodto' parameter is added to the prepared statement

In the TAX_AMOUNT_QUERY, the subquery includes a placeholder for taxperiodto:

"demandid IN (SELECT id FROM egbs_demand_v1 WHERE consumercode = ? AND taxperiodto < ? AND status='ACTIVE') ";

Make sure that the taxperiodto parameter is properly added to the preparedStatement list when executing this query to prevent potential issues with parameter binding and to ensure the query executes correctly.

@pradeepkumarcm-egov pradeepkumarcm-egov merged commit 5f94c27 into master Oct 1, 2024
1 of 2 checks passed
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants