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

AMM-1140 | API for fetching unallocated grievance record count for allocation screen #152

Merged
merged 28 commits into from
Jan 22, 2025

Conversation

srishtigrp78
Copy link
Member

@srishtigrp78 srishtigrp78 commented Jan 19, 2025

πŸ“‹ Description

JIRA ID: AMM-1140
API for fetching unallocated grievance record count for allocation screen


βœ… 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

Summary by CodeRabbit

  • New Features

    • Added an endpoint to fetch the count of unallocated grievances.
    • Implemented new methods to retrieve unallocated grievance statistics.
  • Bug Fixes

    • Introduced error handling for grievance count retrieval process.
  • Chores

    • Enhanced grievance management functionality with new data access methods.
    • Updated configuration to include an additional package for JPA repository scanning.

Copy link
Contributor

coderabbitai bot commented Jan 19, 2025

Walkthrough

This pull request introduces a new feature for fetching the count of unallocated grievances through a RESTful API. A new GrievanceController class is created with an endpoint /unallocatedGrievanceCount that handles POST requests. It interacts with the GrievanceDataSync service, which in turn calls the GrievanceDataRepo to retrieve the count of unallocated grievances. The implementation includes error handling and JSON response generation, allowing clients to query the count effectively.

Changes

File Change Summary
src/main/java/com/iemr/common/controller/grievance/GrievanceController.java Added new REST controller with /unallocatedGrievanceCount endpoint to fetch unallocated grievance count.
src/main/java/com/iemr/common/repository/grievance/GrievanceDataRepo.java Added fetchUnallocatedGrievanceCount() method to query unallocated grievances.
src/main/java/com/iemr/common/service/grievance/GrievanceDataSync.java Added new method signature for fetching unallocated grievance count.
src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java Implemented fetchUnallocatedGrievanceCount() method with JSON response generation.
src/main/java/com/iemr/common/config/PrimaryDBConfig.java Modified @EnableJpaRepositories annotation to include the package com.iemr.common.data.grievance.

Possibly related PRs

  • AMM-1076 and AMM-1078Β #146: This PR introduces a new method fetchUnallocatedGrievanceCount in the GrievanceDataRepo interface, which is directly related to the fetchUnallocatedGrievanceCount method in the GrievanceController class of the main PR.
  • AMM-1139 | Scheduler for fetching L3 to L5 grievance detailsΒ #148: This PR includes the introduction of a new class ScheduleForGrievanceDataSync that utilizes the GrievanceDataSync service, which is autowired in the GrievanceController. The synchronization of grievance data is relevant to the functionality being implemented in the main PR.

Suggested reviewers

  • helenKaryamsetty
  • ravishanigarapu

Poem

🐰 Grievance Tracker Hop! 🐰
Unallocated counts now take flight,
A rabbit's code leaps with delight!
Through layers of Java, swift and clean,
Tracking troubles not yet seen.
Count them quick, with bunny might! πŸš€


πŸ“œ Recent review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between d3534d9 and 6b58965.

πŸ“’ Files selected for processing (1)
  • src/main/java/com/iemr/common/config/PrimaryDBConfig.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/iemr/common/config/PrimaryDBConfig.java
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Package-test
  • GitHub Check: Build
  • GitHub Check: Analyze (java)

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

🧹 Nitpick comments (4)
src/main/java/com/iemr/common/repository/grievance/GrievanceDataRepo.java (1)

18-20: Consider performance optimizations for the count query.

The implementation is correct, but for optimal performance on large datasets, consider:

  1. Adding an index on the isAllocated column if not already present
  2. Using countQuery attribute or native query with EXISTS clause for better performance
-	@Query("select count(request) "
-			+ "from GrievanceDetails request where request.isAllocated = false")
+	@Query(value = "select count(1) from grievance_details where is_allocated = false", 
+           nativeQuery = true)

Also, consider adding an index if not present:

CREATE INDEX idx_grievance_is_allocated ON grievance_details(is_allocated);
src/main/java/com/iemr/common/controller/grievance/GrievanceController.java (2)

28-30: Consider adding API versioning.

To ensure backward compatibility and easier API evolution, consider adding version prefix to the endpoint (e.g., /v1/unallocatedGrievanceCount).

@CrossOrigin()
@Operation(summary = "/unallocatedGrievanceCount")
-@RequestMapping(value = "/unallocatedGrievanceCount", ...)
+@RequestMapping(value = "/v1/unallocatedGrievanceCount", ...)

28-30: Consider adding rate limiting.

Since this is a counting operation that could be resource-intensive on the database, consider adding rate limiting to prevent abuse.

@CrossOrigin()
+@RateLimiter(name = "grievanceCount", fallbackMethod = "grievanceCountFallback")
@Operation(summary = "/unallocatedGrievanceCount")
src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java (1)

378-378: Add debug level check before logging.

For better performance, wrap debug logs with level check.

-logger.debug("Request received for fetchUnallocatedGrievanceCount");
+if (logger.isDebugEnabled()) {
+    logger.debug("Request received for fetchUnallocatedGrievanceCount");
+}
πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between b7d3c80 and 7b3b990.

πŸ“’ Files selected for processing (4)
  • src/main/java/com/iemr/common/controller/grievance/GrievanceController.java (1 hunks)
  • src/main/java/com/iemr/common/repository/grievance/GrievanceDataRepo.java (1 hunks)
  • src/main/java/com/iemr/common/service/grievance/GrievanceDataSync.java (1 hunks)
  • src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: style-check / checkstyle
  • GitHub Check: Build
  • GitHub Check: Analyze (java)
  • GitHub Check: Package-test
πŸ”‡ Additional comments (1)
src/main/java/com/iemr/common/repository/grievance/GrievanceDataRepo.java (1)

18-20: LGTM! Basic implementation looks good.

The query is correctly implemented using JPQL with:

  • Proper entity reference
  • Clear condition for unallocated grievances
  • Appropriate return type (Long) for count operation


@CrossOrigin()
@Operation(summary = "/unallocatedGrievanceCount")
@RequestMapping(value = "/unallocatedGrievanceCount", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization")
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 19, 2025

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Use GET method instead of POST for read operations.

This endpoint retrieves data without making any modifications, so it should use HTTP GET to follow REST principles.

-@RequestMapping(value = "/unallocatedGrievanceCount", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization")
+@GetMapping(value = "/unallocatedGrievanceCount", produces = MediaType.APPLICATION_JSON, headers = "Authorization")
πŸ“ 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
@RequestMapping(value = "/unallocatedGrievanceCount", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization")
@GetMapping(value = "/unallocatedGrievanceCount", produces = MediaType.APPLICATION_JSON, headers = "Authorization")

Copy link
Member Author

Choose a reason for hiding this comment

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

resolved

Copy link
Contributor

Choose a reason for hiding this comment

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

@srishtigrp78 Thank you for implementing the change! This will make the API more RESTful.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Comment on lines 35 to 38
} catch (Exception e) {
logger.error("UnallocatedGrievanceCount failed with error" + e.getMessage(), e);
responseData.setError(e);
}
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 19, 2025

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Enhance error handling with specific error codes.

The current implementation catches all exceptions generically. Consider handling specific exceptions (IEMRException, JSONException) separately with appropriate error codes.

-} catch (Exception e) {
-    logger.error("UnallocatedGrievanceCount failed with error" + e.getMessage(), e);
-    responseData.setError(e);
-}
+} catch (IEMRException e) {
+    logger.error("Business logic error in UnallocatedGrievanceCount: " + e.getMessage(), e);
+    responseData.setError(e, "BUS_ERR_001");
+} catch (JSONException e) {
+    logger.error("JSON processing error in UnallocatedGrievanceCount: " + e.getMessage(), e);
+    responseData.setError(e, "JSON_ERR_001");
+} catch (Exception e) {
+    logger.error("Unexpected error in UnallocatedGrievanceCount: " + e.getMessage(), e);
+    responseData.setError(e, "SYS_ERR_001");
+}

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Member Author

Choose a reason for hiding this comment

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

resolved

Copy link
Contributor

Choose a reason for hiding this comment

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

@srishtigrp78 Thank you for implementing the enhanced error handling! This will make debugging and error tracking much more effective.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Comment on lines 380 to 387
Long unallocatedCount = grievanceDataRepo.fetchUnallocatedGrievanceCount();

// Create a response JSON object
JSONObject result = new JSONObject();
result.put("count", unallocatedCount); // Store the count of unallocated grievances

// Return the result as a string
return result.toString();
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 19, 2025

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Simplify method to return domain object and add null check.

The service layer should return domain objects and let the controller handle JSON serialization. Also, add null check for repository result.

-Long unallocatedCount = grievanceDataRepo.fetchUnallocatedGrievanceCount();
-
-// Create a response JSON object
-JSONObject result = new JSONObject();
-result.put("count", unallocatedCount);  // Store the count of unallocated grievances
-
-// Return the result as a string
-return result.toString();
+Long unallocatedCount = grievanceDataRepo.fetchUnallocatedGrievanceCount();
+if (unallocatedCount == null) {
+    throw new IEMRException("Failed to fetch unallocated grievance count");
+}
+return unallocatedCount;

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Member Author

Choose a reason for hiding this comment

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

resolved

Copy link
Contributor

Choose a reason for hiding this comment

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

@srishtigrp78 Thank you for implementing the suggested changes! This will make the code more robust by properly handling null cases.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

@drtechie
Copy link
Member

@srishtigrp78 saw the original ticket.
Wondering if this API really belongs to Common-API.
Also, can you look at the security hotspot?

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

πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 7b3b990 and d834aa9.

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

21-31: Well-structured dependency injection and logging setup!

Good practices observed:

  • Constructor injection for dependencies
  • Proper logger initialization

35-35: Use GET method for read operations.


1-20: Review placement of this API in Common-API.

Based on the PR objectives and previous comments, there are concerns about whether this API belongs in the Common-API repository. The placement under com.iemr.common suggests this is meant to be shared functionality, but the specific nature of "unallocated grievance counts" might indicate it belongs in a more specialized service.

Let's analyze the usage patterns to determine if this truly belongs in Common-API:

βœ… Verification successful

Placement in Common-API is appropriate

The grievance functionality, including the unallocated count feature, is correctly placed in Common-API as it's part of the core grievance data synchronization service. This is evidenced by:

  • Integration with the existing GrievanceDataSync interface
  • Shared usage through common repository and service layers
  • Consistent architectural pattern with other grievance-related operations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other grievance-related components to understand the context
rg -l "grievance" --type java

# Check if similar counting/allocation APIs exist in Common-API
ast-grep --pattern 'class $_ {
  $$$
  @$_Mapping($_)
  $_ fetch$_Count() {
    $$$
  }
  $$$
}'

Length of output: 1004


Script:

#!/bin/bash
# Check existing grievance endpoints and their purposes
rg -B 2 -A 2 "@(GetMapping|PostMapping|PutMapping|RequestMapping).+grievance" --type java

# Examine the GrievanceDataSync interface to understand shared functionality
cat src/main/java/com/iemr/common/service/grievance/GrievanceDataSync.java

# Look for references to grievance allocation in existing code
rg "grievance.*allocat" --type java

Length of output: 903


35-46: Verify security considerations for the endpoint.

The endpoint handles sensitive grievance data and requires proper security controls:

  1. Verify Authorization header processing
  2. Check for proper access control

Let's analyze the security implementation:

βœ… Verification successful

Security implementation verified for the endpoint

The endpoint has proper security controls implemented through:

  • Mandatory Authorization header validation
  • Token-based authentication via HTTPRequestInterceptor
  • Redis-backed session management with proper expiry
  • Request validation and IP checking capabilities
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for security filters and interceptors
rg -A 5 "Authorization" --type java

# Look for access control annotations
ast-grep --pattern '@PreAuthorize($$$)'

# Check for security configuration
fd -e java -e xml -e properties -e yml | rg -l "security"

Length of output: 81857


Script:

#!/bin/bash
# Check for security filter chain config
rg -A 10 "SecurityFilterChain|WebSecurityConfigurerAdapter|SecurityConfiguration" --type java

# Look for role/authority checks
rg -A 5 "hasRole|hasAuthority|@Secured|@RolesAllowed" --type java

# Check security context usage
rg -A 5 "SecurityContextHolder|Authentication|UserDetails" --type java

Length of output: 6499


Script:

#!/bin/bash
# Check for custom filter implementations
rg -A 10 "implements Filter|extends OncePerRequestFilter" --type java

# Look for token validation logic
rg -A 10 "validateToken|verifyToken|checkToken" --type java

# Check session validation
rg -A 10 "SessionObject|RedisSession|validateSession" --type java

Length of output: 72574

Comment on lines +33 to +35
@CrossOrigin()
@Operation(summary = "/unallocatedGrievanceCount")
@PostMapping(value = "/unallocatedGrievanceCount", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization")
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Restrict CORS and add rate limiting.

The unrestricted @CrossOrigin() annotation could pose a security risk. Consider:

  1. Explicitly specify allowed origins
  2. Add rate limiting for this endpoint to prevent abuse

Apply this diff:

-@CrossOrigin()
+@CrossOrigin(origins = "${app.allowed-origins}")
+@RateLimiter(name = "grievanceCount")

Add to application.properties:

app.allowed-origins=https://example.com,https://admin.example.com

Comment on lines 37 to 44
OutputResponse responseData = new OutputResponse();
try {
responseData.setResponse(grievanceDataSync.fetchUnallocatedGrievanceCount());
} catch (Exception e) {
logger.error("UnallocatedGrievanceCount failed with error" + e.getMessage(), e);
responseData.setError(e);
}
return responseData.toString();
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 20, 2025

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Enhance response handling and security.

  1. Validate response before toString() to prevent potential null pointer exceptions
  2. Consider sanitizing error messages to avoid exposing sensitive information

Apply this diff:

 OutputResponse responseData = new OutputResponse();
 try {
-    responseData.setResponse(grievanceDataSync.fetchUnallocatedGrievanceCount());
+    Object count = grievanceDataSync.fetchUnallocatedGrievanceCount();
+    if (count != null) {
+        responseData.setResponse(count);
+    } else {
+        responseData.setError(new Exception("No data available"));
+    }
 } catch (Exception e) {
     logger.error("UnallocatedGrievanceCount failed with error" + e.getMessage(), e);
-    responseData.setError(e);
+    // Sanitize error message for production
+    responseData.setError(new Exception("An internal error occurred"));
 }
-return responseData.toString();
+return responseData != null ? responseData.toString() : "";
πŸ“ 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
OutputResponse responseData = new OutputResponse();
try {
responseData.setResponse(grievanceDataSync.fetchUnallocatedGrievanceCount());
} catch (Exception e) {
logger.error("UnallocatedGrievanceCount failed with error" + e.getMessage(), e);
responseData.setError(e);
}
return responseData.toString();
OutputResponse responseData = new OutputResponse();
try {
Object count = grievanceDataSync.fetchUnallocatedGrievanceCount();
if (count != null) {
responseData.setResponse(count);
} else {
responseData.setError(new Exception("No data available"));
}
} catch (Exception e) {
logger.error("UnallocatedGrievanceCount failed with error" + e.getMessage(), e);
// Sanitize error message for production
responseData.setError(new Exception("An internal error occurred"));
}
return responseData != null ? responseData.toString() : "";

Copy link
Member Author

Choose a reason for hiding this comment

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

resolved

Copy link
Contributor

Choose a reason for hiding this comment

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

@srishtigrp78 Thank you for implementing the suggested changes to improve the response handling and security! πŸŽ‰

 /\___/\
(  o o  )
(  =^=  ) 
 (______)

If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

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

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

377-389: πŸ› οΈ Refactor suggestion

Return domain object instead of JSON string.

The service layer should return domain objects and let the controller handle JSON serialization. This maintains better separation of concerns.

-public String fetchUnallocatedGrievanceCount() throws IEMRException, JSONException {
+public Long fetchUnallocatedGrievanceCount() throws IEMRException {
     logger.debug("Request received for fetchUnallocatedGrievanceCount");
 
     Long unallocatedCount = grievanceDataRepo.fetchUnallocatedGrievanceCount();
     
     if (unallocatedCount == null) {
         throw new IEMRException("Failed to fetch unallocated grievance count");
     }
     
-    JSONObject result = new JSONObject();
-    result.put("count", unallocatedCount);        
-    return result.toString();
+    return unallocatedCount;
 }
🧹 Nitpick comments (2)
src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java (2)

377-389: Enhance logging for better observability.

Add error logging and include more context in debug logs for better traceability.

 public String fetchUnallocatedGrievanceCount() throws IEMRException, JSONException {
-    logger.debug("Request received for fetchUnallocatedGrievanceCount");
+    logger.debug("Fetching unallocated grievance count");
 
     Long unallocatedCount = grievanceDataRepo.fetchUnallocatedGrievanceCount();
     
     if (unallocatedCount == null) {
+        logger.error("Failed to retrieve unallocated grievance count from repository");
         throw new IEMRException("Failed to fetch unallocated grievance count");
     }
     
+    logger.debug("Successfully retrieved unallocated grievance count: {}", unallocatedCount);
     JSONObject result = new JSONObject();
     result.put("count", unallocatedCount);        
     return result.toString();
 }

377-389: Wrap repository exceptions.

Catch and wrap repository exceptions to provide more meaningful error messages.

 public String fetchUnallocatedGrievanceCount() throws IEMRException, JSONException {
     logger.debug("Request received for fetchUnallocatedGrievanceCount");
 
-    Long unallocatedCount = grievanceDataRepo.fetchUnallocatedGrievanceCount();
+    Long unallocatedCount;
+    try {
+        unallocatedCount = grievanceDataRepo.fetchUnallocatedGrievanceCount();
+    } catch (Exception e) {
+        logger.error("Error while fetching unallocated grievance count", e);
+        throw new IEMRException("Database error while fetching unallocated grievance count", e);
+    }
     
     if (unallocatedCount == null) {
         throw new IEMRException("Failed to fetch unallocated grievance count");
     }
πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between d834aa9 and 734551a.

πŸ“’ Files selected for processing (2)
  • src/main/java/com/iemr/common/controller/grievance/GrievanceController.java (1 hunks)
  • src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/iemr/common/controller/grievance/GrievanceController.java
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)
πŸ”‡ Additional comments (1)
src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java (1)

14-15: LGTM!

The new imports are properly organized and all are being used in the implementation.

Also applies to: 41-42

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

πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 734551a and 47ceb56.

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

50-50: Review architectural decision: Grievance functionality in Common-API.

Based on the PR objectives and comments, there are concerns about placing grievance-related functionality in the Common-API. This warrants a deeper architectural discussion:

  1. Common-API should typically contain shared functionality used across multiple services
  2. If grievance management is specific to one domain, it might be better placed in a dedicated service

Consider:

  • Is this functionality used by multiple services?
  • Could this create unwanted dependencies?
  • Would this make the Common-API too domain-specific?
βœ… Verification successful

Architectural placement of grievance functionality in Common-API is appropriate

The grievance system exhibits characteristics of a shared service with cross-cutting concerns:

  • Integrates with common services (SMS, feedback)
  • Implements centralized data synchronization
  • Maintains independent data persistence
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for existing grievance-related code to understand the scope
rg -g '!target/' -g '!*.class' -l 'grievance' .

# Check for potential service dependencies
rg -g '!target/' -g '!*.class' -l '@Autowired.*Grievance|@Inject.*Grievance' .

Length of output: 1088


50-50: Verify the existence of the grievance package structure.

Let's ensure that the newly added package com.iemr.common.data.grievance exists and contains the necessary repository classes.

βœ… Verification successful

Package structure verification successful

The com.iemr.common.data.grievance package exists and contains the necessary entity classes (GrievanceDetails, GrievanceTransaction) that are properly referenced by their corresponding repository classes in the com.iemr.common.repository.grievance package. The component scanning configuration is correct.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the package directory exists and contains repository classes
fd -t d "grievance$" src/main/java
fd -t f ".*Repository\.java$|.*Repo\.java$" -p src/main/java/com/iemr/common/data/grievance

Length of output: 329


Script:

#!/bin/bash
# Check contents of data and repository packages
echo "=== Data Package Contents ==="
fd -t f ".*\.java$" src/main/java/com/iemr/common/data/grievance

echo -e "\n=== Repository Package Contents ==="
fd -t f ".*\.java$" src/main/java/com/iemr/common/repository/grievance

echo -e "\n=== Checking Repository References ==="
rg -l "com\.iemr\.common\.data\.grievance" src/main/java/com/iemr/common/repository/grievance

Length of output: 1017

@@ -47,7 +47,7 @@
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory", basePackages = { "com.iemr.common.repository",
"com.iemr.common.repo", "com.iemr.common.notification.agent", "com.iemr.common.covidVaccination", "com.iemr.common.repository.everwell.*", " com.iemr.common.repository.users" })
"com.iemr.common.repo", "com.iemr.common.notification.agent", "com.iemr.common.covidVaccination", "com.iemr.common.repository.everwell.*", "com.iemr.common.data.grievance"," com.iemr.common.repository.users" })
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 21, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix syntax error in basePackages list.

There's a syntax error in the repository packages list that could cause runtime issues:

  • Extra comma and space after "com.iemr.common.data.grievance"
  • Incorrect string concatenation

Apply this diff to fix the syntax:

-		"com.iemr.common.repo", "com.iemr.common.notification.agent", "com.iemr.common.covidVaccination", "com.iemr.common.repository.everwell.*", "com.iemr.common.data.grievance"," com.iemr.common.repository.users" })
+		"com.iemr.common.repo", "com.iemr.common.notification.agent", "com.iemr.common.covidVaccination", "com.iemr.common.repository.everwell.*", "com.iemr.common.data.grievance", "com.iemr.common.repository.users" })
πŸ“ 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
"com.iemr.common.repo", "com.iemr.common.notification.agent", "com.iemr.common.covidVaccination", "com.iemr.common.repository.everwell.*", "com.iemr.common.data.grievance"," com.iemr.common.repository.users" })
"com.iemr.common.repo", "com.iemr.common.notification.agent", "com.iemr.common.covidVaccination", "com.iemr.common.repository.everwell.*", "com.iemr.common.data.grievance", "com.iemr.common.repository.users" })

Copy link
Member Author

Choose a reason for hiding this comment

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

resolved

Copy link
Contributor

Choose a reason for hiding this comment

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

@srishtigrp78 Thank you for fixing the syntax error! πŸŽ‰

⟦⟨(β€’α΄₯β€’)⟩⟧
Happy!


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
1 Security Hotspot

See analysis details on SonarQube Cloud

Copy link
Member

@ravishanigarapu ravishanigarapu left a comment

Choose a reason for hiding this comment

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

looks fine

@ravishanigarapu ravishanigarapu merged commit 27a71ab into PSMRI:develop Jan 22, 2025
6 of 7 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.

3 participants