Skip to content

Conversation

ravishanigarapu
Copy link
Member

@ravishanigarapu ravishanigarapu commented Mar 25, 2025

πŸ“‹ Description

JIRA ID: AMM-1305, AMM-1333,AMM-1303

Even after 3 attempts, record is displaying in the grievance worklist


βœ… Type of Change

  • 🐞 Bug fix (non-breaking change which resolves an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • πŸ”₯ Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • πŸ›  Refactor (change that is neither a fix nor a new feature)
  • βš™οΈ Config change (configuration file or build script updates)
  • πŸ“š Documentation (updates to docs or readme)
  • πŸ§ͺ Tests (adding new or updating existing tests)
  • 🎨 UI/UX (changes that affect the user interface)
  • πŸš€ Performance (improves performance)
  • 🧹 Chore (miscellaneous changes that don't modify src or test files)

ℹ️ Additional Information

Please describe how the changes were tested, and include any relevant screenshots, logs, or other information that provides additional context.

Summary by CodeRabbit

  • New Features

    • Enhanced grievance worklist details now include an additional identification field.
    • Improved retrieval of transaction data for more accurate grievance updates.
  • Bug Fixes

    • Adjusted query conditions to ensure only relevant grievances are fetched and updated.
  • Refactor

    • Reorganized data structure and constructor parameters for consistency.
    • Updated internal annotation usage to ensure clearer, more precise data mapping.
    • Streamlined grievance data synchronization logic for better clarity and error handling.
    • Updated method for retrieving grievance transactions to enhance data accuracy.
    • Modified response handling in the grievance controller for improved JSON serialization.
    • Simplified query parameters in grievance data repository methods for better maintainability.

Copy link
Contributor

coderabbitai bot commented Mar 25, 2025

Walkthrough

This pull request refines the handling of grievance transactions by replacing a wildcard import with explicit Jakarta Persistence annotation imports in the transaction entity. Additionally, it introduces a new field in the grievance worklist DTO with corresponding constructor changes. A new repository method is added to fetch transaction data using native SQL, and the service implementation is updated to inject this repository and adjust data extraction logic accordingly. Furthermore, several query methods in the grievance data repository are modified to enhance specificity and reduce parameters.

Changes

File(s) Change Summary
src/.../data/grievance/GrievanceTransaction.java Replaced wildcard import with explicit imports for Jakarta Persistence annotations; removed the NotBlank import and repositioned the Date import.
src/.../dto/grivance/GrievanceWorklistDTO.java Added a new Long grievanceId field; updated and reordered constructor parameters, removing the transactions list initialization parameter.
src/.../repository/grievance/GrievanceTransactionRepo.java Introduced a new repository method getGrievanceTransaction with a native SQL query to fetch specific fields based on grievanceId.
src/.../service/grievance/GrievanceHandlingServiceImpl.java Updated constructor to inject GrievanceTransactionRepo; modified getFormattedGrievanceData and transaction handling logic.
src/.../controller/grievance/GrievanceController.java Changed return type of getGrievanceOutboundWorklist from ResponseEntity<Map<String, Object>> to String and updated internal logic for JSON serialization using Gson.
src/.../repository/grievance/GrievanceDataRepo.java Modified several query conditions in methods to enhance specificity and reduce parameters, including fetchGrievanceRecordsCount, updateComplaintResolution, and others.
src/.../service/grievance/GrievanceDataSyncImpl.java Restructured dataSyncToGrievance method for clarity and error handling; modified fetchUnallocatedGrievanceCount and completeGrievanceCall for improved logic.
src/.../repository/callhandling/BeneficiaryCallRepository.java Updated fetchBenCallRemarks method to change the parameter from beneficiaryRegID to benCallID reflecting a shift in the criteria used to fetch remarks.

Possibly related PRs

Suggested reviewers

  • helenKaryamsetty

Poem

Hopping through code with nimble feet,
I trimmed wild imports to make our code neat.
New fields and queries now shine so bright,
As transactions dance in the soft moonlight.
With carrots of wisdom πŸ₯• I celebrate this feat,
A CodeRabbit's joy in every line we complete!

✨ Finishing Touches
  • πŸ“ Generate Docstrings

πŸͺ§ 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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
Contributor

@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 (3)
src/main/java/com/iemr/common/repository/grievance/GrievanceTransactionRepo.java (1)

3-15: Consider returning a strongly typed projection or DTO instead of List<Object[]>.

While returning a raw List<Object[]> from a native query is functional, using an interface-based projection or a custom DTO reduces casting overhead and increases maintainability.

src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (1)

334-348: Refactor raw Object[] usage for readability.

Fetching transactions via grievanceTransactionRepo.getGrievanceTransaction works, but consider typed queries or projections to minimize indexing errors and improve code clarity.

src/main/java/com/iemr/common/dto/grivance/GrievanceWorklistDTO.java (1)

13-77: Consider additional improvements to the DTO design

While the current changes are valid, several improvements could enhance code quality and maintainability:

  1. Add JavaDoc comments to explain the purpose of fields, especially clarifying the difference between complaintID and grievanceId
  2. Standardize field naming conventions for consistency (some fields use camelCase while others don't)
  3. Consider using enums instead of strings for fields like severety (also appears misspelled - should be "severity")
  4. Group related fields together for better readability
πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 482f441 and 1993622.

πŸ“’ Files selected for processing (4)
  • src/main/java/com/iemr/common/data/grievance/GrievanceTransaction.java (1 hunks)
  • src/main/java/com/iemr/common/dto/grivance/GrievanceWorklistDTO.java (3 hunks)
  • src/main/java/com/iemr/common/repository/grievance/GrievanceTransactionRepo.java (1 hunks)
  • src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (3 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
src/main/java/com/iemr/common/data/grievance/GrievanceTransaction.java (1)
src/main/java/com/iemr/common/data/grievance/GrievanceDetails.java (1)
  • Entity (23-210)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: style-check / checkstyle
  • GitHub Check: Build
  • GitHub Check: Package-test
  • GitHub Check: Analyze (java)
πŸ”‡ Additional comments (8)
src/main/java/com/iemr/common/data/grievance/GrievanceTransaction.java (1)

4-16: Use of explicit imports is a best practice.

Replacing wildcard imports with explicit named imports fosters clarity and maintainability.

src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (3)

34-34: Constructor-based injection of GrievanceTransactionRepo looks good.

Injecting the new repository in the constructor is consistent with Spring best practices and keeps dependencies explicit. No issues here.

Also applies to: 48-48, 52-52, 56-56


300-301: Verify the type used for age casting.

Casting row[20] directly to Long could cause a ClassCastException if the underlying DB column is mapped to a different type. Confirm that the result maps correctly to Long.


307-320: Possible confusion in column indexing.

Line 330 reuses row[13] for lastCall while line 319 uses the same index for lastModDate. Verify that both fields indeed reference the same column. If not, update the indexes accordingly.

Also, ensure the field mapping aligns with the underlying query structure to avoid subtle data mismatch.

Also applies to: 328-330

src/main/java/com/iemr/common/dto/grivance/GrievanceWorklistDTO.java (4)

17-17: New field added for grievance identification

Adding the grievanceId field of type Long is a good addition that likely provides a more robust identifier for grievances compared to the String-based complaintID. This change appears to support the enhanced grievance transaction handling mentioned in the PR summary.


49-49: Correctly initializing the new field

The new grievanceId field is properly initialized in the constructor.


63-64: Parameter reordering reflected in assignments

The assignments for firstName and lastName have been correctly moved to reflect their new positions in the parameter list.


42-45:

βœ… Verification successful

Constructor signature changes need careful consideration

The constructor has been modified to include the new grievanceId parameter and reorder several parameters. While the implementation is correct, this change requires updating all places where this constructor is called to match the new signature.


🏁 Script executed:

#!/bin/bash
# Find all instances where GrievanceWorklistDTO constructor is called
# to verify they've been updated with the new parameter order

echo "Searching for GrievanceWorklistDTO constructor usage..."
rg "new GrievanceWorklistDTO\(" --type java -A 10 -B 2

Length of output: 3581


Constructor Signature Verification – All Constructor Calls Match the New Order

  • Verified that the parameterized constructor in GrievanceWorklistDTO (now including grievanceId as the second parameter) is correctly invoked in src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java.
  • Noted that the call in src/main/java/com/iemr/common/controller/grievance/GrievanceController.java uses the no-argument constructor. Assuming that retaining a default constructor is intentional for error handling or similar cases, no changes appear necessary there.
  • Please ensure documentation clearly distinguishes the intended use between the parameterized and the default constructors.

// Loop through the worklist data and format the response
for (Object[] row : worklistData) {
if (row == null || row.length < 30)
if (row == null || row.length < 22)
Copy link
Contributor

@coderabbitai coderabbitai bot Mar 25, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential off-by-one error in array length check.

Subsequent code references row[22] despite only ensuring row.length >= 22. For an array of length 22, row[22] would be out of range.

Consider changing the condition to if (row == null || row.length < 23) or remove references to row[22] if unintended.

Copy link
Member Author

@ravishanigarapu ravishanigarapu Apr 1, 2025

Choose a reason for hiding this comment

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

@coderabbitai the query returns only 22 columns. it should not be more than 22 columns.

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Contributor

@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

πŸ”­ Outside diff range comments (1)
src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java (1)

258-305: πŸ’‘ Verification agent

🧩 Analysis chain

Validate presence of the "transaction" key.
When fetching JsonArray arr = transactionDetailsJson.get("transaction").getAsJsonArray();, no null-check is performed. If the key is missing or incorrectly named, a runtime exception may occur.


🏁 Script executed:

#!/bin/bash
# Search for usage of "transaction" field to confirm we never store null or absent keys.

rg -A 2 'get\("transaction"\)'

Length of output: 414


Action Required: Add Null-Check for "transaction" Key

The current implementation in src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java (lines 258-305) retrieves the "transaction" key without checking if it exists. This may lead to a runtime exception if the key is absent. Please add a null/absent check before calling getAsJsonArray() to ensure the code handles missing or incorrectly named keys gracefully.

  • File: src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java
  • Location: Lines 258-305
♻️ Duplicate comments (1)
src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (1)

292-296: ⚠️ Potential issue

Off-by-one error when referencing row[22].
You skip rows if row.length < 22, but you later access row[22]. This can lead to an ArrayIndexOutOfBoundsException.

- if (row == null || row.length < 22)
+ if (row == null || row.length < 23)
🧹 Nitpick comments (5)
src/main/java/com/iemr/common/controller/grievance/GrievanceController.java (2)

147-148: Consider returning an HTTP-aware ResponseEntity.
Changing from ResponseEntity<Map<String, Object>> to String restricts the ability to provide custom HTTP statuses, headers, and typed responses. If feasible, consider returning ResponseEntity<String> instead, so that clients can handle status codes appropriately.


152-152: Remove or utilize the unused ObjectMapper instance.
ObjectMapper objectMapper = new ObjectMapper(); is never used in this method. Minimizing unused variables can reduce confusion.

- ObjectMapper objectMapper = new ObjectMapper();
src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java (2)

125-131: Refactor the token check for clarity.
Having an empty if block is less readable. Using an early-return or inverting to if (token is expired) generate token; can be clearer:

 if (GRIEVANCE_AUTH_TOKEN != null && GRIEVANCE_TOKEN_EXP != null
     && GRIEVANCE_TOKEN_EXP > System.currentTimeMillis()) {
-    // do nothing
} else {
    generateGrievanceAuthToken();
}

138-145: Setting Content-Length manually may be unnecessary.
In many cases, RestTemplate handles the Content-Length header automatically. Manually overriding it can cause issues if the request changes after setting the header.

- headers.add("Content-Length", String.valueOf(contentLength));
src/main/java/com/iemr/common/repository/grievance/GrievanceDataRepo.java (1)

47-135: Consistent architectural approach to query conditions

All the changes in this file follow a consistent pattern of removing providerServiceMapID from query conditions, suggesting a deliberate architectural decision. This simplifies the queries and makes the code more maintainable, assuming that complaintID, beneficiaryRegID, and userID together form a sufficient unique key.

When making such a significant change to query conditions across multiple methods, consider adding a comment or documentation update explaining the rationale behind removing providerServiceMapID from query conditions. This would help future developers understand why this decision was made.

πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 1993622 and 0563e98.

πŸ“’ Files selected for processing (5)
  • src/main/java/com/iemr/common/controller/grievance/GrievanceController.java (4 hunks)
  • src/main/java/com/iemr/common/dto/grivance/GrievanceWorklistDTO.java (4 hunks)
  • src/main/java/com/iemr/common/repository/grievance/GrievanceDataRepo.java (3 hunks)
  • src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java (6 hunks)
  • src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/iemr/common/dto/grivance/GrievanceWorklistDTO.java
πŸ”‡ Additional comments (16)
src/main/java/com/iemr/common/controller/grievance/GrievanceController.java (3)

3-8: Imports look fine.
These imported classes support JSON serialization (java.lang.reflect.Type, java.text.SimpleDateFormat, etc.) without obvious issues.


27-35: Jackson and Gson library imports are valid.
No issues flagged with the newly introduced Jackson and Gson dependencies.


178-188: Gson serialization with custom date format looks good.
The custom date serializer ensures dates are returned in "yyyy-MM-dd HH:mm:ss" format. If privacy regulations require masking of sensitive data (e.g., phone numbers), consider applying it within this serialization step. Otherwise, this implementation is acceptable.

src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java (2)

133-136: Creation of HTTP headers is standard.
The headers (Content-Type, User-Agent, AUTHORIZATION) are well-defined and align with typical REST usage.


488-493: Defensive checks for null recordSet elements are commendable.
These null-safe checks prevent unintended NullPointerExceptions. This is a good practice.

src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (4)

34-34: Repo injection looks correct.
The addition of GrievanceTransactionRepo and its injection in the constructor appear consistent with the existing design. No immediate concerns.

Also applies to: 48-48, 52-52, 56-56


298-303: Long-based age handling is acceptable.
Switching from a floating type to a long integer for age appears more consistent. This avoids floating point issues and clarifies the usage of age as an integer-based measure.


334-349: Transaction retrieval and mapping are structured well.
Fetching transactions via grievanceTransactionRepo.getGrievanceTransaction and mapping to GrievanceTransactionDTO is clear and maintainable.


476-486: Remarks fetching logic is sound.
The code gracefully falls back to alternative sources if remarks are null. No immediate issues found here.

src/main/java/com/iemr/common/repository/grievance/GrievanceDataRepo.java (7)

47-48: Filtered out completed grievances from the count query

The addition of grievance.isCompleted=false to the query ensures that only active (not completed) grievances are counted, which aligns with the purpose of workload tracking and management.


102-103: Removed providerServiceMapID from overloaded resolution method

Similar to the previous change, the providerServiceMapID condition has been removed from this overloaded method as well, maintaining consistency between both versions of updateComplaintResolution.


112-112: Added complaintResolution to getCallCounter result set

The query now returns additional information (complaint resolution status) along with call counter and retry status, which provides more context in a single database call.


117-118: Removed providerServiceMapID from completed status update

The query has been simplified to only use complaintID, userID, and beneficiaryRegID as conditions for updating the completed status. This follows the pattern of other method changes in this file.


123-123: Removed providerServiceMapID parameter from method signature

The parameter has been removed in line with the changes to the query condition, maintaining consistency between the method signature and implementation.


88-89:

❓ Verification inconclusive

Removed providerServiceMapID condition from complaint resolution update

The query has been simplified by removing the providerServiceMapID condition. This potentially broadens the scope of which records can be updated.


🏁 Script executed:

#!/bin/bash
# Verify if providerServiceMapID is used elsewhere to uniquely identify grievances
# or if the combination of complaintID, beneficiaryRegID, and userID is sufficient

# Check if there are any instances where two grievances share the same complaintID, beneficiaryRegID, and userID but have different providerServiceMapID
rg -A 5 "complaintID.+beneficiaryRegID.+userID.+providerServiceMapID" --type java

Length of output: 81


Action Required: Confirm Uniqueness Conditions in Grievance Update Query
The removal of the providerServiceMapID condition simplifies the query to use only complaintID, beneficiaryRegID, and userID for matching records. Although the initial automated search did not reveal any instances where duplicate grievances (differing by providerServiceMapID) occur, the evidence remains inconclusive. Please manually verify that these three fields together uniquely identify a grievance to ensure the change won’t inadvertently broaden the update scope.

  • Confirm that no grievances exist with the same complaintID, beneficiaryRegID, and userID but different providerServiceMapID values.
  • Ensure the simplified query does not affect additional records unexpectedly.

128-129:

βœ… Verification successful

Removed providerServiceMapID from call counter update

This change is consistent with the pattern of simplifying queries throughout this file by relying on the combination of complaintID, beneficiaryRegID, and userID to uniquely identify grievance records.


🏁 Script executed:

#!/bin/bash
# Check for any potential issues with concurrent updates after removing providerServiceMapID

# Look for other places where these fields are used in combination
rg -A 5 "complaintID.+beneficiaryRegID.+userID" --type java

# Check if there are any service methods that might expect providerServiceMapID to be part of the update condition
rg -A 10 "updateCallCounter|updateCompletedStatusInCall|updateComplaintResolution" --type java

Length of output: 18904


Verified: Simplified update query aligns with codebase patterns

The removal of providerServiceMapID from the call counter update in GrievanceDataRepo.java has been confirmed. Our searches indicate that all related update methods across the repository and service implementations rely on the combination of complaintID, beneficiaryRegID, and userID to uniquely identify grievance records. This consistent approach minimizes redundancy and potential concurrency issues.

  • The query now solely uses complaintID, beneficiaryRegID, and userID for record matching.
  • Similar patterns in GrievanceDataSyncImpl.java, GrievanceHandlingServiceImpl.java, and Everwell service classes further reinforce this change.

Comment on lines 150 to 178
if (response != null && response.hasBody()) {
JSONObject obj = new JSONObject(response.getBody());
if (obj != null && obj.has("data") && obj.has("status") && obj.getInt("status") == 200) {
logger.info("Grievance data details response received successfully ");

String responseStr = response.getBody();
JsonObject jsnOBJ = new JsonObject();
JsonParser jsnParser = new JsonParser();
JsonElement jsnElmnt = jsnParser.parse(responseStr);
jsnOBJ = jsnElmnt.getAsJsonObject();
int total = jsnOBJ.get("total").getAsInt();
String GrievanceUrl = updateGrievanceDetails.replace("PageNumber", String.valueOf(total));
ResponseEntity<String> grievienceResponse = restTemplate.exchange(GrievanceUrl, HttpMethod.POST,
request, String.class);
String respStr = grievienceResponse.getBody();

JsonElement jsnElmntResp = jsnParser.parse(respStr);
jsnOBJ = jsnElmntResp.getAsJsonObject();
JsonArray grievanceJsonDataArray = jsnOBJ.getAsJsonArray("data");
if (Integer.parseInt(jsnOBJ.get("total").toString()) > 0) {
for (JsonElement grievanceElement : grievanceJsonDataArray) {
String formattedComplaintId = null;
try {
JsonObject grievanceJsonData = grievanceElement.getAsJsonObject();
GrievanceDetails grievance = new GrievanceDetails();
String complaintId = grievanceJsonData.get("complainId").getAsString();
formattedComplaintId = complaintId.replace("\\/", "/");
boolean complaintExists = grievanceDataRepo.existsByComplaintId(formattedComplaintId);
if (complaintExists) {
Copy link
Contributor

Choose a reason for hiding this comment

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

πŸ’‘ Verification agent

🧩 Analysis chain

Verify total and data fields exist in every response.
The code assumes "status" == 200 and that "total" / "data" fields exist. Unexpected or empty responses could cause exceptions at runtime.


🏁 Script executed:

#!/bin/bash
# Checking usage of fields "total" and "data" in the grievance responses
# to ensure robust error handling.

rg -A 5 'obj\.has\("total"\)' 
rg -A 5 'obj\.has\("data"\)'

Length of output: 2133


Attention: Add explicit validation for the total field in the grievance response.

While the code correctly checks for the presence of "data" and "status" (with "status" == 200), it directly uses the "total" field without verifying its existence. This could lead to runtime exceptions if "total" is missing or malformed in the response. I recommend adding a conditional check to ensure that "total" exists before attempting to use its value. For instance:

  • In src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java (lines 150-178), verify that jsnOBJ.has("total") (or its equivalent) is true before calling get("total") and proceeding with subsequent operations.
  • Ensure similar validations are applied consistently across related response handling utilities (e.g., compare with the check in src/main/java/com/iemr/common/utils/response/OutputResponse.java).

Implementing this check will prevent exceptions on unexpected or empty responses.

Copy link
Contributor

@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 (2)
src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (2)

478-487: Clarify resolution-based remarks retrieval logic.
Right now, the code only checks if complaintResolution is null or not. If the business needs a distinctly different flow for β€œresolved” vs. β€œunresolved,” consider an explicit comparison for better clarity.


522-522: Consider returning an empty string instead of β€œNo remarks found.”
A literal message might confuse consumers if they parse remarks programmatically. An empty string could be clearer.

-    return "No remarks found";
+    return "";
πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between c16bf0c and 2bde1cf.

πŸ“’ Files selected for processing (1)
  • src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (java)
  • GitHub Check: Build
  • GitHub Check: Package-test
πŸ”‡ Additional comments (9)
src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (9)

34-34: No concerns for the import statement.


48-48: New dependency injection looks good.
No issues noted with adding a final field for the GrievanceTransactionRepo.


292-292: Possible off-by-one error in the row length check.
This comment matches a past review. You’re ensuring row.length >= 22, but the code references row[22] in nearby lines, which would be out of range if the array length is exactly 22.


306-333: Check repeated use of row[13].
You’re assigning row[13] to both lastModDate and lastCall. If this is unintentional, consider adding a separate column index for lastCall.


336-349: Verify potential null return from getGrievanceTransaction.
If the repository method can return null, a NullPointerException could occur. Otherwise, returning an empty list is safe. Please confirm expected behavior.


406-411: Complaint resolution update logic looks solid.
The checks on updateCount are appropriate, and both variants handle remarks or no remarks consistently.


517-518: Index check is well-handled.
You guard against emptiness before accessing benCallResults.get(0). No issues found here.


301-302:

❓ Verification inconclusive

Validate the type of row[20].
Casting row[20] to a Long could raise a ClassCastException if the stored procedure doesn’t always return a numeric type for that index.

Consider verifying the stored procedure schema:


🏁 Script executed:

#!/bin/bash
# Searches for the definition/usage of getGrievanceWorklistData to confirm the type at index 20
rg -A 5 "getGrievanceWorklistData"
fd -e sql -x cat {}

Length of output: 1201


Action: Verify and Safeguard Row Index 20 Type Conversion

The verification confirms that the method retrieving worklist data from the database returns a raw List<Object[]>. However, there isn’t conclusive evidence from the stored procedure's schema about the type at index 20. To avoid a potential ClassCastException, please ensure that:

  • The stored procedure indeed returns a numeric type (preferably a Long) at index 20.
  • If the returned type might vary (e.g., could be an Integer, BigDecimal, or even null), add an instanceof check or safely convert to a Long (for example, by converting a Number using .longValue()).
  • Consider updating the code at src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java to handle cases where row[20] may not be a Long.

52-56:

βœ… Verification successful

Verify external constructor references.
Ensure that any existing code instantiating GrievanceHandlingServiceImpl is updated to pass the newly required GrievanceTransactionRepo.

You can run this script to locate all constructor invocations:


🏁 Script executed:

#!/bin/bash
# Searches for all calls to the GrievanceHandlingServiceImpl constructor
rg "GrievanceHandlingServiceImpl\s*\("

Length of output: 248


Constructor Parameter Update Verified

We ran the search and confirmed that the only instance of a GrievanceHandlingServiceImpl constructor call is the definition within the class itself (in src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java). There are no direct external instantiation calls (e.g., via new GrievanceHandlingServiceImpl(...)) in the codebase. If this class is being injected via a dependency injection framework (such as Spring), please double-check that the DI configuration has been updated to supply the new GrievanceTransactionRepo parameter.

Copy link

sonarqubecloud bot commented Apr 1, 2025

Copy link
Contributor

@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

♻️ Duplicate comments (1)
src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (1)

299-337: ⚠️ Potential issue

Potential out-of-bounds access for row[22].

Since the code references row[22] (line 336) but only checks for row.length < 22 (line 299), arrays of exactly length 22 will cause an out-of-bounds error. Increase the check to < 23 if you truly need to access row[22], or remove any references to the 23rd column if the query only returns 22 columns.

-if (row == null || row.length < 22)
+if (row == null || row.length < 23)
 {
   logger.warn("invalid row data received");
   continue;
 }
🧹 Nitpick comments (5)
src/main/java/com/iemr/common/repository/callhandling/BeneficiaryCallRepository.java (1)

194-195: Prefer returning a list of strings.

Since only the remarks column is being selected here, consider returning List<String> rather than List<Object[]>. This will make the usage in the calling code more straightforward and eliminate the need to handle object arrays for a single string value.

-@Query("SELECT b.remarks FROM BeneficiaryCall b WHERE b.benCallID = :benCallID")
-List<Object[]> fetchBenCallRemarks(@Param("benCallID") Long benCallID);
+@Query("SELECT b.remarks FROM BeneficiaryCall b WHERE b.benCallID = :benCallID")
+List<String> fetchBenCallRemarks(@Param("benCallID") Long benCallID);
src/main/java/com/iemr/common/controller/grievance/GrievanceController.java (2)

140-141: Consider returning a typed response.

Returning raw JSON strings can make status code handling and client-side error interpretation more cumbersome. If possible, consider returning ResponseEntity<?> to leverage HTTP status codes more effectively, or ensure the client is prepared for a raw string response.


145-146: Remove or utilize the unused ObjectMapper.

An ObjectMapper is instantiated but never used. If GSON is the preferred serializer, you may remove this redundant code to avoid confusion.

-ObjectMapper objectMapper = new ObjectMapper();
src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (2)

14-14: Consider using org.apache.commons.lang3.StringUtils.

Using org.apache.commons.lang.StringUtils is generally fine, but org.apache.commons.lang3.StringUtils is the more modern library with additional improvements and ongoing support.


483-486: Use isBlank() if whitespace-only values should be treated as empty.

Using StringUtils.isEmpty() is fine if you only want to check for null or zero-length strings. If you also want to treat whitespace as empty, consider isBlank() or trimming the input first.

πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 2bde1cf and 0b7922e.

πŸ“’ Files selected for processing (4)
  • src/main/java/com/iemr/common/controller/grievance/GrievanceController.java (4 hunks)
  • src/main/java/com/iemr/common/repository/callhandling/BeneficiaryCallRepository.java (1 hunks)
  • src/main/java/com/iemr/common/repository/grievance/GrievanceDataRepo.java (3 hunks)
  • src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/iemr/common/repository/grievance/GrievanceDataRepo.java
πŸ”‡ Additional comments (5)
src/main/java/com/iemr/common/controller/grievance/GrievanceController.java (1)

171-181: JSON date serialization looks good.

Registering a custom JsonSerializer<Date> with GSON provides flexible control over date formatting. This approach is clear and consistent.

src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (4)

41-41: Injection of GrievanceTransactionRepo is correct.

Introducing GrievanceTransactionRepo in the service constructor and storing it as a final field is a clean approach, ensuring proper dependency injection.

Also applies to: 55-55, 59-59, 63-63


341-355: Adding transaction data looks good.

Retrieving the transaction records from GrievanceTransactionRepo and populating them into the DTO is logically sound, ensuring the main grievance object includes all pertinent transaction details.


411-411: Check parameter ordering for complaint resolution update.

These calls to updateComplaintResolution appear correct but rely on a carefully ordered parameter list. Make sure the target repository method signature expects the same argument ordering to avoid subtle misalignment.

Also applies to: 416-416


524-532: Fetching remarks from BeneficiaryCall is well-handled.

Verifying the query results and returning "No remarks found" in the absence of data is a clean approach. The null checks prevent potential NullPointerExceptions.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (2)

342-356: Consider minimizing repeated queries.
Calling grievanceTransactionRepo.getGrievanceTransaction(...) inside the loop may cause extra DB calls for each row, potentially impacting performance at scale. A single batched query or an IN clause could be more efficient.


484-487: Consider isBlank() if whitespace-only remarks matter.
StringUtils.isEmpty() ignores only null/empty strings, but not whitespace-only content. If whitespace is significant, consider isBlank().

πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 0b7922e and 1e4eea6.

πŸ“’ Files selected for processing (1)
  • src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (8 hunks)
πŸ”‡ Additional comments (4)
src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java (4)

3-14: Imports appear consistent.
These newly added imports for java.lang.reflect.Type and org.apache.commons.lang.StringUtils align with the usage of custom Gson serialization and string checks, respectively. No conflicts or issues observed.


41-63: Repository integration looks good.
Introducing and injecting GrievanceTransactionRepo in the constructor follows recommended constructor injection practices. The code is clear and consistent.


299-299: Potential off-by-one error (duplicate).
You are referencing row[22] below but the condition only checks row.length < 22. An array with length 22 has valid indices 0..21, making row[22] out of bounds.


305-308: Verify the type of row[20].
Casting row[20] to Long may cause ClassCastException if this column is returned as a different numeric type (e.g., Integer) from the query.

Would you like to confirm the actual database type of this column and ensure correct casting? You can run a script to inspect the data type or ask the DB administrator for clarification.

Comment on lines +314 to +338
(Long) row[1], //grievanceId
(String) row[2], // subjectOfComplaint
(String) row[3], // complaint
(Long) row[4], // beneficiaryRegID
(Integer) row[5],// providerServiceMapID
(String) row[6], // primaryNumber
(String) row[7], // severety
(String) row[8], // state
(Integer) row[9],// userId
(Boolean) row[10],// deleted
(String) row[11],// createdBy
(Timestamp) row[12], // createdDate
(Timestamp) row[13], // lastModDate
(Boolean) row[14], // isCompleted

(String) row[15], // firstName
(String) row[16], // lastName
(String) row[17], // gender
(String) row[18], // district
(Long) row[19], // beneficiaryID
ageFormatted,
(Boolean) row[26], // retryNeeded
(Integer) row[27], // callCounter
(Timestamp) row[18] //lastCall yet to fill
(Boolean) row[21], // retryNeeded
(Integer) row[22], // callCounter
(Timestamp) row[13] //lastCall

Copy link
Contributor

Choose a reason for hiding this comment

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

πŸ’‘ Verification agent

🧩 Analysis chain

Check repeated usage of row[13].
You're setting both lastModDate and lastCall from row[13]. If these columns differ in the DB, referencing the same index may be incorrect. Verify that the intended column for "lastCall" is also at index 13.


🏁 Script executed:

#!/bin/bash
# Validate whether the 'lastCall' DB column is indeed located at index 13.
# We'll look for references in the codebase where 'row[13]' is assigned for two different fields.

rg -A 4 'row\[13\]'

Length of output: 1231


Attention: Potential Incorrect Database Column Mapping

In src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java, the code assigns (Timestamp) row[13] to both the lastModDate and lastCall fields. Since the database schema likely distinguishes between these two values, please verify whether lastCall should reference a different column index. If the intended DB column for lastCall differs from lastModDate, the mapping should be updated accordingly.

  • Action Required:
    • Check the DB schema to confirm the correct column index for the lastCall field.
    • Update the index for lastCall if it is intended to come from a column other than what is currently referenced by row[13].

Comment on lines +523 to +533
Long benCallID = grievance.getBenCallID();
// Query t_bencall to fetch remarks based on benRegId
List<Object[]> benCallResults = beneficiaryCallRepo.fetchBenCallRemarks(beneficiaryRegID);
List<Object[]> benCallResults = beneficiaryCallRepo.fetchBenCallRemarks(benCallID);

if (benCallResults != null && !benCallResults.isEmpty()) {
return (String) benCallResults.get(0)[0]; // Fetch the remarks
if(null != benCallResults.get(0) && null != benCallResults.get(0)[0])
return (String) benCallResults.get(0)[0]; // Fetch the remarks
}
}

return "No remarks found in t_bencall";
return "No remarks found";
Copy link
Contributor

Choose a reason for hiding this comment

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

πŸ’‘ Verification agent

🧩 Analysis chain

Verify benCallID usage to avoid null scenarios.
Here, fetchBenCallRemarks(benCallID) is invoked without ensuring benCallID is non-null. A null or missing benCallID could cause a query issue or unexpected results.


🏁 Script executed:

#!/bin/bash
# Verify if benCallID can be null or unset, potentially leading to problems in fetchBenCallRemarks.

rg -A 3 'benCallID' 

Length of output: 65151


Action: Introduce an explicit null-check for benCallID before querying remarks
In the code within GrievanceHandlingServiceImpl.java at lines 523–533, benCallID is retrieved via grievance.getBenCallID() and immediately passed to beneficiaryCallRepo.fetchBenCallRemarks(benCallID) without verifying its non-nullity. Although many parts of the codebase assume a non-null benCallID, if for any reason grievance.getBenCallID() can return null, this may result in a query error or produce unexpected results. Consider adding a defensive null-checkβ€”such as returning a default message like "No remarks found" when benCallID is nullβ€”to ensure robust handling.

@devikasuresh20 devikasuresh20 merged commit 0698e6b into PSMRI:develop Apr 1, 2025
7 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jul 4, 2025
1 task
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