diff --git a/src/main/java/com/iemr/common/controller/grievance/GrievanceController.java b/src/main/java/com/iemr/common/controller/grievance/GrievanceController.java index 8ac8a8d4..a4e3212c 100644 --- a/src/main/java/com/iemr/common/controller/grievance/GrievanceController.java +++ b/src/main/java/com/iemr/common/controller/grievance/GrievanceController.java @@ -130,13 +130,19 @@ public String moveToBin(@RequestBody String request) { @Operation(summary = "get grievance outbound worklist)") @PostMapping(value = "/getGrievanceOutboundWorklist", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization") - public ResponseEntity> getGrievanceOutboundWorklist(@Param(value = "{\"providerServiceMapId\":\" called service ID integer\", " + public ResponseEntity> getGrievanceOutboundWorklist(@Param(value = "{\"providerServiceMapId\":\" called service ID integer\", " + "\"userId\":\"Optional - Integer ID of user that is assigned to\"}") @RequestBody String request) { logger.info("Request received for grievance worklist"); List response = new ArrayList<>(); + Map responseMap = new HashMap<>(); + try { response = grievanceHandlingService.getFormattedGrievanceData(request); - + // Prepare the success response structure + responseMap.put("data", response); + responseMap.put("statusCode", HttpStatus.OK.value()); + responseMap.put("errorMessage", "Success"); + responseMap.put("status", "Success"); } catch (Exception e) { @@ -148,11 +154,15 @@ public ResponseEntity> getGrievanceOutboundWorklist(@ // Return error response with empty list and error message errorResponse.add(errorDTO); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse); + + responseMap.put("data", errorResponse); + responseMap.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + responseMap.put("errorMessage", e.getMessage()); + responseMap.put("status", "Error"); } - return ResponseEntity.ok(response); + return ResponseEntity.ok(responseMap); } diff --git a/src/main/java/com/iemr/common/dto/grivance/GrievanceTransactionDTO.java b/src/main/java/com/iemr/common/dto/grivance/GrievanceTransactionDTO.java index 6243e001..48d25b7e 100644 --- a/src/main/java/com/iemr/common/dto/grivance/GrievanceTransactionDTO.java +++ b/src/main/java/com/iemr/common/dto/grivance/GrievanceTransactionDTO.java @@ -9,7 +9,9 @@ @Data public class GrievanceTransactionDTO implements Serializable { private static final long serialVersionUID = 1L; - + + private String actionTakenBy; + private String status; private String fileName; private String fileType; private String redressed; @@ -20,9 +22,12 @@ public class GrievanceTransactionDTO implements Serializable { // Constructor, Getters, and Setters public GrievanceTransactionDTO( + String actionTakenBy, String status, String fileName, String fileType, String redressed, Timestamp createdAt, Timestamp updatedAt, String comment) { super(); + this.actionTakenBy = actionTakenBy; + this.status = status; this.fileName = fileName; this.fileType = fileType; this.redressed = redressed; diff --git a/src/main/java/com/iemr/common/dto/grivance/GrievanceWorklistDTO.java b/src/main/java/com/iemr/common/dto/grivance/GrievanceWorklistDTO.java index 6e4b1604..365c76a3 100644 --- a/src/main/java/com/iemr/common/dto/grivance/GrievanceWorklistDTO.java +++ b/src/main/java/com/iemr/common/dto/grivance/GrievanceWorklistDTO.java @@ -37,15 +37,14 @@ public class GrievanceWorklistDTO implements Serializable { private String age; private Boolean retryNeeded; private Integer callCounter; - // private String lastCall; // Add this field if you want - + private Timestamp lastCall; public GrievanceWorklistDTO(String complaintID, String subjectOfComplaint, String complaint, Long beneficiaryRegID, Integer providerServiceMapID, String firstName, String lastName, String primaryNumber, List transactions, String severety, String state, Integer userId, Boolean deleted, String createdBy, Timestamp createdDate, Timestamp lastModDate, Boolean isCompleted, String gender, String district, Long beneficiaryID, String age, - Boolean retryNeeded, Integer callCounter) { + Boolean retryNeeded, Integer callCounter, Timestamp lastCall) { super(); this.complaintID = complaintID; this.subjectOfComplaint = subjectOfComplaint; @@ -70,6 +69,7 @@ public GrievanceWorklistDTO(String complaintID, String subjectOfComplaint, Strin this.age = age; this.retryNeeded = retryNeeded; this.callCounter = callCounter; + this.lastCall = lastCall; } diff --git a/src/main/java/com/iemr/common/repository/grievance/GrievanceOutboundRepository.java b/src/main/java/com/iemr/common/repository/grievance/GrievanceOutboundRepository.java index 88c50d66..88c8dfa9 100644 --- a/src/main/java/com/iemr/common/repository/grievance/GrievanceOutboundRepository.java +++ b/src/main/java/com/iemr/common/repository/grievance/GrievanceOutboundRepository.java @@ -3,21 +3,20 @@ import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.query.Procedure; +import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.iemr.common.data.grievance.GrievanceDetails; -import jakarta.transaction.Transactional; @Repository public interface GrievanceOutboundRepository extends JpaRepository { - @Transactional - @Procedure(procedureName = "Pr_Grievanceworklist") - List getGrievanceWorklistData(@Param("providerServiceMapId") Integer providerServiceMapId, - @Param("userId") Integer userId); + + @Query(value =" call db_iemr.Pr_Grievanceworklist(:providerServiceMapID, :userId)", nativeQuery = true) + List getGrievanceWorklistData(@Param("providerServiceMapID") Integer providerServiceMapID, + @Param("userId") Integer userId); } diff --git a/src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java b/src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java index 6db4b497..7e95b792 100644 --- a/src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java +++ b/src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java @@ -61,13 +61,11 @@ public GrievanceHandlingServiceImpl(GrievanceDataRepo grievanceDataRepo, Grievan // retry logic private InputMapper inputMapper = new InputMapper(); // InputMapper used to map the JSON request - + @Override public String allocateGrievances(String request) throws Exception { - // Step 1: Parse the request string into the appropriate - // GrievanceAllocationRequest object - GrievanceAllocationRequest allocationRequest = InputMapper.gson().fromJson(request, - GrievanceAllocationRequest.class); + // Step 1: Parse the request string into the appropriate GrievanceAllocationRequest object + GrievanceAllocationRequest allocationRequest = InputMapper.gson().fromJson(request, GrievanceAllocationRequest.class); // Step 2: Fetch grievances based on the start date, end date range, and // language @@ -79,37 +77,45 @@ public String allocateGrievances(String request) throws Exception { throw new Exception("No grievances found in the given date range and language."); } - // Step 3: Sort grievances in ascending order based on creation date - grievances.sort(Comparator.comparing(GrievanceDetails::getCreatedDate)); - - // Step 4: Get the allocation parameters from the request - int totalAllocated = 0; - int userIndex = 0; - List userIds = allocationRequest.getTouserID(); - int allocateNo = allocationRequest.getAllocateNo(); // Number of grievances to allocate per user + // Step 3: Get the allocation parameters from the request + List userIds = allocationRequest.getTouserID(); + int allocateNo = allocationRequest.getAllocateNo(); // Number of grievances to allocate per user - for (int i = 0; i < grievances.size(); i++) { - Integer userId = userIds.get(userIndex); - GrievanceDetails grievance = grievances.get(i); - - int rowsAffected = grievanceDataRepo.allocateGrievance(grievance.getGrievanceId(), userId); - if (rowsAffected > 0) { - totalAllocated++; - logger.debug("Allocated grievance ID {} to user ID {}", grievance.getGrievanceId(), userId); - } else { - logger.error("Failed to allocate grievance ID {} to user ID {}", grievance.getGrievanceId(), userId); - } + // Step 4: Initialize counters + int totalAllocated = 0; + int grievanceIndex = 0; // Start from the first grievance + int totalUsers = userIds.size(); + int totalGrievances = grievances.size(); + + // Step 5: Allocate grievances to users, ensuring each user gets exactly 'allocateNo' grievances + for (Integer userId : userIds) { + int allocatedToCurrentUser = 0; + + // Allocate 'allocateNo' grievances to the current user + while (allocatedToCurrentUser < allocateNo && grievanceIndex < totalGrievances) { + GrievanceDetails grievance = grievances.get(grievanceIndex); + + // Allocate the grievance to the user + int rowsAffected = grievanceDataRepo.allocateGrievance(grievance.getGrievanceId(), userId); + if (rowsAffected > 0) { + totalAllocated++; + logger.debug("Allocated grievance ID {} to user ID {}", grievance.getGrievanceId(), userId); + } else { + logger.error("Failed to allocate grievance ID {} to user ID {}", grievance.getGrievanceId(), userId); + } + + grievanceIndex++; // Move to the next grievance + allocatedToCurrentUser++; // Increment the number of grievances allocated to the current user + } - // Move to the next user after allocateNo grievances - if ((i + 1) % allocateNo == 0) { - userIndex = (userIndex + 1) % userIds.size(); - } - } + // If we have allocated the specified number of grievances, move on to the next user + } - // Step 6: Return a message with the total number of grievances allocated - return "Successfully allocated " + totalAllocated + " grievances to users."; + // Step 6: Return a message with the total number of grievances allocated + return "Successfully allocated " + allocateNo + " grievance to each user."; } + @Override public String allocatedGrievanceRecordsCount(String request) throws IEMRException, JSONException { GrievanceDetails grievanceRequest = InputMapper.gson().fromJson(request, GrievanceDetails.class); @@ -146,57 +152,61 @@ public String allocatedGrievanceRecordsCount(String request) throws IEMRExceptio return resultArray.toString(); } + + @Override public String reallocateGrievances(String request) throws Exception { - // Step 1: Parse the request string into the appropriate - // GrievanceReallocationRequest object - GrievanceReallocationRequest reallocationRequest = InputMapper.gson().fromJson(request, - GrievanceReallocationRequest.class); + // Step 1: Parse the request string into the appropriate GrievanceReallocationRequest object + GrievanceReallocationRequest reallocationRequest = InputMapper.gson().fromJson(request, GrievanceReallocationRequest.class); - // Step 2: Fetch grievances that are allocated to the 'fromUserId' and match the - // criteria - List grievances = grievanceDataRepo.findAllocatedGrievancesByUserAndLanguage( - reallocationRequest.getFromUserId(), reallocationRequest.getLanguage()); + // Step 2: Fetch grievances that are allocated to the 'fromUserId' and match the criteria + List grievances = grievanceDataRepo.findAllocatedGrievancesByUserAndLanguage( + reallocationRequest.getFromUserId(), reallocationRequest.getLanguage()); - if (grievances.isEmpty()) { - throw new Exception("No grievances found for the given user and language."); - } + if (grievances.isEmpty()) { + throw new Exception("No grievances found for the given user and language."); + } - // Step 3: Sort grievances in ascending order based on creation date - grievances.sort(Comparator.comparing(GrievanceDetails::getCreatedDate)); + // Step 3: Sort grievances in ascending order based on creation date + grievances.sort(Comparator.comparing(GrievanceDetails::getCreatedDate)); - // Step 4: Get the allocation parameters from the request - int totalReallocated = 0; - int userIndex = 0; - List toUserIds = reallocationRequest.getTouserID(); - int allocateNo = reallocationRequest.getAllocateNo(); // Number of grievances to reallocate per user + // Step 4: Get the allocation parameters from the request + int totalReallocated = 0; + int grievanceIndex = 0; // Start from the first grievance + List toUserIds = reallocationRequest.getTouserID(); + int allocateNo = reallocationRequest.getAllocateNo(); // Number of grievances to reallocate per user - // Step 5: Reallocate grievances to users in a round-robin fashion - for (int i = 0; i < grievances.size(); i++) { - if (i % allocateNo == 0 && userIndex < toUserIds.size()) { - // Reallocate to the next user when reaching the allocateNo threshold - Integer toUserId = toUserIds.get(userIndex); - GrievanceDetails grievance = grievances.get(i); + // Step 5: Reallocate grievances to users + for (Integer toUserId : toUserIds) { + int allocatedToCurrentUser = 0; - // Call the repository method to reallocate the grievance to the new user - int rowsAffected = grievanceDataRepo.reallocateGrievance(grievance.getGrievanceId(), toUserId); + // Reallocate 'allocateNo' grievances to the current user + while (allocatedToCurrentUser < allocateNo && grievanceIndex < grievances.size()) { + GrievanceDetails grievance = grievances.get(grievanceIndex); - if (rowsAffected > 0) { - totalReallocated++; - logger.debug("Reallocated grievance ID " + grievance.getGrievanceId() + " to user ID " + toUserId); - } else { - logger.error("Failed to reallocate grievance ID " + grievance.getGrievanceId() + " to user ID " - + toUserId); - } + // Call the repository method to reallocate the grievance to the new user + int rowsAffected = grievanceDataRepo.reallocateGrievance(grievance.getGrievanceId(), toUserId); - userIndex = (userIndex + 1) % toUserIds.size(); - } - } + if (rowsAffected > 0) { + totalReallocated++; + logger.debug("Reallocated grievance ID {} to user ID {}", grievance.getGrievanceId(), toUserId); + } else { + logger.error("Failed to reallocate grievance ID {} to user ID {}", grievance.getGrievanceId(), toUserId); + } - // Step 6: Return a message with the total number of grievances reallocated - return "Successfully reallocated " + totalReallocated + " grievances to users."; + grievanceIndex++; // Move to the next grievance + allocatedToCurrentUser++; // Increment the number of grievances reallocated to the current user + } + + // If the current user is allocated the specified number of grievances, move to the next user + } + + // Step 6: Return a message with the total number of grievances reallocated + return "Successfully reallocated " + totalReallocated + " grievance to user."; } + + @Override public String moveToBin(String request) throws Exception { // Step 1: Parse the request string into the appropriate MoveToBinRequest object @@ -284,22 +294,30 @@ public List getFormattedGrievanceData(String request) thro // Loop through the worklist data and format the response for (Object[] row : worklistData) { - if (row == null || row.length < 28) + if (row == null || row.length < 30) { logger.warn("invalid row data received"); continue; } + + // Handle age conversion from Double to "x years" format + String ageFormatted = "N/A"; // Default value for age if it's not available + if (row[25] != null) { + Double age = (Double) row[25]; + ageFormatted = age.intValue() + " years"; // Convert the age to integer and append " years" + } + GrievanceWorklistDTO grievance = new GrievanceWorklistDTO( (String) row[0], // complaintID (String) row[1], // subjectOfComplaint (String) row[2], // complaint (Long) row[3], // beneficiaryRegID (Integer) row[4],// providerServiceMapID - (String) row[5], // primaryNumber (String) row[20], // firstName (String) row[21], // lastName - + (String) row[5], // primaryNumber + new ArrayList<>(),// transactions (initially empty, will be populated later) (String) row[12], // severety (String) row[13], // state @@ -312,14 +330,17 @@ public List getFormattedGrievanceData(String request) thro (String) row[22], // gender (String) row[23], // district (Long) row[24], // beneficiaryID - (String) row[25], // age + // (Double) row[25], // age + ageFormatted, (Boolean) row[26], // retryNeeded - (Integer) row[27] // callCounter + (Integer) row[27], // callCounter + (Timestamp) row[17] //lastCall yet to fill ); // Extract transactions from the current row and add them to the grievance object GrievanceTransactionDTO transaction = new GrievanceTransactionDTO( - + (String) row[28], //actionTakenBy yet to fill + (String) row[29], //status yet to fill (String) row[6], // fileName (String) row[7], // fileType (String) row[8], // redressed