diff --git a/src/main/java/com/iemr/common/config/quartz/QuartzConfig.java b/src/main/java/com/iemr/common/config/quartz/QuartzConfig.java index ac359f40..61e70fd0 100644 --- a/src/main/java/com/iemr/common/config/quartz/QuartzConfig.java +++ b/src/main/java/com/iemr/common/config/quartz/QuartzConfig.java @@ -24,8 +24,6 @@ import java.io.IOException; import java.util.Properties; - - import org.quartz.Trigger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -97,8 +95,7 @@ public SchedulerFactoryBean quartzScheduler() { Trigger[] triggers = { processMQTriggerForUnblock().getObject(), processMQTriggerForSMS().getObject(), processMQTriggerForEmail().getObject(), processMQTriggerForRegistration().getObject(), processMQTriggerForEverwellDataSync().getObject(), processMQTriggerForCtiDataSync().getObject(), - processMQTriggerForAvniRegistration().getObject(), - processMQTriggerForNHMDashboardData().getObject(), processMQTriggerForGrievanceDataSync().getObject() }; + processMQTriggerForAvniRegistration().getObject(), processMQTriggerForNHMDashboardData().getObject() }; quartzScheduler.setTriggers(triggers); @@ -227,33 +224,6 @@ public CronTriggerFactoryBean processMQTriggerForEverwellDataSync() { return cronTriggerFactoryBean; } - //-----------------Grievance Data Sync Scheduler---------------------------------------------- - - @Bean - public JobDetailFactoryBean processMQJobForGrievanceDataSync() { - JobDetailFactoryBean jobDetailFactory; - jobDetailFactory = new JobDetailFactoryBean(); - jobDetailFactory.setJobClass(ScheduleForGrievanceDataSync.class); - jobDetailFactory.setGroup(quartzJobGroup); - return jobDetailFactory; - } - - @Bean - public CronTriggerFactoryBean processMQTriggerForGrievanceDataSync() { - Boolean startJob = ConfigProperties.getBoolean("start-grievancedatasync-scheduler"); - CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean(); - String scheduleConfig = quartzJobDefaultSchedule; - if (startJob) { - scheduleConfig = ConfigProperties.getPropertyByName("cron-scheduler-grievancedatasync"); - } - cronTriggerFactoryBean.setJobDetail(processMQJobForGrievanceDataSync().getObject()); - cronTriggerFactoryBean.setCronExpression(scheduleConfig); - cronTriggerFactoryBean.setGroup(quartzJobGroup); - return cronTriggerFactoryBean; - } - - - // -------------------------------------------------------------------------------------------------------------- @Bean public JobDetailFactoryBean processMQJobForCtiDataSync() { diff --git a/src/main/java/com/iemr/common/config/quartz/ScheduleForGrievanceDataSync.java b/src/main/java/com/iemr/common/config/quartz/ScheduleForGrievanceDataSync.java index 8843738c..f016de3d 100644 --- a/src/main/java/com/iemr/common/config/quartz/ScheduleForGrievanceDataSync.java +++ b/src/main/java/com/iemr/common/config/quartz/ScheduleForGrievanceDataSync.java @@ -1,38 +1,39 @@ package com.iemr.common.config.quartz; -import org.quartz.Job; -import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + import com.iemr.common.service.grievance.GrievanceDataSync; -@Service -@Transactional -public class ScheduleForGrievanceDataSync implements Job { +@Component +public class ScheduleForGrievanceDataSync { + + @Value("${start-grievancedatasync-scheduler}") + private boolean grievanceFlag; private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - - + private final GrievanceDataSync grievanceDataSync; - + @Autowired public ScheduleForGrievanceDataSync(GrievanceDataSync grievanceDataSync) { this.grievanceDataSync = grievanceDataSync; } - - @Override - public void execute(JobExecutionContext arg0) throws JobExecutionException - { - logger.info("Started job for grievance data sync {}", arg0.getClass().getName()); - grievanceDataSync.dataSyncToGrievance(); - logger.info("Completed job for grievance data sync {}" , arg0.getClass().getName()); - } - + @Scheduled(cron = "${cron-scheduler-grievancedatasync}") + public void execute() { + if (grievanceFlag) { + logger.info("Started job for grievance data sync "); + grievanceDataSync.dataSyncToGrievance(); + logger.info("Completed job for grievance data sync "); + } + + } } 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 6126b8bd..df574a12 100644 --- a/src/main/java/com/iemr/common/controller/grievance/GrievanceController.java +++ b/src/main/java/com/iemr/common/controller/grievance/GrievanceController.java @@ -1,83 +1,121 @@ package com.iemr.common.controller.grievance; - -import com.iemr.common.service.grievance.GrievanceDataSync; -import com.iemr.common.service.grievance.GrievanceHandlingService; -import com.iemr.common.utils.exception.IEMRException; -import com.iemr.common.utils.response.OutputResponse; -import io.lettuce.core.dynamic.annotation.Param; -import io.swagger.v3.oas.annotations.Operation; import javax.ws.rs.core.MediaType; import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; +import com.iemr.common.data.grievance.UnallocationRequest; +import com.iemr.common.service.grievance.GrievanceDataSync; +import com.iemr.common.service.grievance.GrievanceHandlingService; +import com.iemr.common.utils.exception.IEMRException; +import com.iemr.common.utils.response.OutputResponse; + +import io.lettuce.core.dynamic.annotation.Param; +import io.swagger.v3.oas.annotations.Operation; + @RestController public class GrievanceController { final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - - private GrievanceDataSync grievanceDataSync; - - private final GrievanceHandlingService grievanceHandlingService; - - @Autowired - public GrievanceController(GrievanceHandlingService grievanceHandlingService, GrievanceDataSync grievanceDataSync) { - this.grievanceDataSync = grievanceDataSync; - this.grievanceHandlingService = grievanceHandlingService; - } - - - @CrossOrigin() - @Operation(summary = "/unallocatedGrievanceCount") - @PostMapping(value = "/unallocatedGrievanceCount", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization") - public String fetchUnallocatedGrievanceCount() { - OutputResponse responseData = new OutputResponse(); - try { - responseData.setResponse(grievanceDataSync.fetchUnallocatedGrievanceCount()); - } - catch (IEMRException e) { - logger.error("Business logic error in UnallocatedGrievanceCount" + e.getMessage(), e); - responseData.setError(e); - } - catch (JSONException e) { - logger.error("JSON processing error in UnallocatedGrievanceCount" + e.getMessage(), e); - responseData.setError(e); - } - catch (Exception e) { - logger.error("UnallocatedGrievanceCount failed with error" + e.getMessage(), e); - responseData.setError(e); - } - return responseData.toString(); - - } - - - - @Operation(summary = "Allocate grievances to users") - @PostMapping(value = "/allocateGrievances", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization") - public String allocateGrievances(@Param(value = "{\"startDate\":\"ISO-8601 format start date (e.g., 2022-12-01T07:49:00.000Z)\", " - + "\"endDate\":\"ISO-8601 format end date (e.g., 2025-01-16T07:49:30.561)\", " - + "\"userID\":\"Array list of User IDs (agents to be allocated grievances)\", " - + "\"allocateNo\":\"Integer - number of grievances to be allocated to each user\"," - + "\"language\":\"String - language to filter grievances by\"}") - - @RequestBody String request) { - OutputResponse response = new OutputResponse(); - try { - // Call the service to allocate grievances based on the incoming JSON request - response.setResponse(grievanceHandlingService.allocateGrievances(request)); - } catch (Exception e) { - logger.error("Grievance allocation failed with error: " + e.getMessage(), e); - response.setError(e); - } - return response.toString(); - } - + private GrievanceDataSync grievanceDataSync; + + private final GrievanceHandlingService grievanceHandlingService; + + @Autowired + public GrievanceController(GrievanceHandlingService grievanceHandlingService, GrievanceDataSync grievanceDataSync) { + this.grievanceDataSync = grievanceDataSync; + this.grievanceHandlingService = grievanceHandlingService; + } + + @Operation(summary = "/unallocatedGrievanceCount") + @PostMapping(value = "/unallocatedGrievanceCount", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization") + public String fetchUnallocatedGrievanceCount(@RequestBody UnallocationRequest request) { + OutputResponse responseData = new OutputResponse(); + try { + responseData.setResponse(grievanceDataSync.fetchUnallocatedGrievanceCount(request.getPreferredLanguageName())); + } catch (IEMRException e) { + logger.error("Business logic error in UnallocatedGrievanceCount" + e.getMessage(), e); + responseData.setError(e); + } catch (JSONException e) { + logger.error("JSON processing error in UnallocatedGrievanceCount" + e.getMessage(), e); + responseData.setError(e); + } catch (Exception e) { + logger.error("UnallocatedGrievanceCount failed with error" + e.getMessage(), e); + responseData.setError(e); + } + return responseData.toString(); + + } + + @Operation(summary = "Allocate grievances to users") + @PostMapping(value = "/allocateGrievances", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization") + public String allocateGrievances( + @Param(value = "{\"startDate\":\"ISO-8601 format start date (e.g., 2022-12-01T07:49:00.000Z)\", " + + "\"endDate\":\"ISO-8601 format end date (e.g., 2025-01-16T07:49:30.561)\", " + + "\"userID\":\"Array list of User IDs (agents to be allocated grievances)\", " + + "\"allocateNo\":\"Integer - number of grievances to be allocated to each user\"," + + "\"language\":\"String - language to filter grievances by\"}") + + @RequestBody String request) { + OutputResponse response = new OutputResponse(); + try { + // Call the service to allocate grievances based on the incoming JSON request + response.setResponse(grievanceHandlingService.allocateGrievances(request)); + } catch (Exception e) { + logger.error("Grievance allocation failed with error: " + e.getMessage(), e); + response.setError(e); + } + return response.toString(); + } + + @Operation(summary = "Allocated Grievance Records Count") + @PostMapping(value = "/allocatedGrievanceRecordsCount", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization") + public String allocatedGrievanceRecordsCount(@Param(value = "{\"providerServiceMapID\":\"Service ID integer\", " + + "\"assignedUserID\":\"Optional - Integer user ID to whom grievances are assigned\"}") @RequestBody String request) { + OutputResponse response = new OutputResponse(); + try { + response.setResponse(grievanceHandlingService.allocatedGrievanceRecordsCount(request)); + } catch (Exception e) { + logger.error("allocatedGrievanceRecordsCount failed with error " + e.getMessage(), e); + response.setError(e); + } + return response.toString(); + } + + @Operation(summary = "Reallocate grievances to other users") + @PostMapping(value = "/reallocateGrievances", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization") + public String reallocateGrievances(@RequestBody String request) { + OutputResponse response = new OutputResponse(); + try { + // Call the service to reallocate grievances based on the incoming JSON request + response.setResponse(grievanceHandlingService.reallocateGrievances(request)); + } catch (Exception e) { + logger.error("Grievance reallocation failed with error: " + e.getMessage(), e); + response.setError(e); + } + return response.toString(); + } + + @Operation(summary = "Move grievances to bin (unassign from agent)") + @PostMapping(value = "/moveToBin", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization") + public String moveToBin(@RequestBody String request) { + + OutputResponse response = new OutputResponse(); + try { + response.setResponse(grievanceHandlingService.moveToBin(request)); + } catch (Exception e) { + logger.error("Move to bin failed with error: " + e.getMessage(), e); + response.setError(e); + } + return response.toString(); + } + } diff --git a/src/main/java/com/iemr/common/data/grievance/GrievanceAllocationRequest.java b/src/main/java/com/iemr/common/data/grievance/GrievanceAllocationRequest.java index 7bf44e44..8dc30cc1 100644 --- a/src/main/java/com/iemr/common/data/grievance/GrievanceAllocationRequest.java +++ b/src/main/java/com/iemr/common/data/grievance/GrievanceAllocationRequest.java @@ -1,68 +1,23 @@ package com.iemr.common.data.grievance; +import java.sql.Timestamp; +import java.util.List; - import java.time.LocalDateTime; - import java.util.List; +import lombok.Data; - public class GrievanceAllocationRequest { +@Data +public class GrievanceAllocationRequest { - private LocalDateTime startDate; // Start date for filtering grievances - private LocalDateTime endDate; // End date for filtering grievances - private List userID; // List of user IDs (agents) to whom grievances will be allocated - private Integer allocateNo; // Number of grievances to be allocated to each user - private String language; - // Getters and Setters + private Timestamp startDate; // Start date for filtering grievances + private Timestamp endDate; // End date for filtering grievances + private List userID; // List of user IDs (agents) to whom grievances will be allocated + private Integer allocateNo; // Number of grievances to be allocated to each user + private String preferredLanguage; - public LocalDateTime getStartDate() { - return startDate; - } - - public void setStartDate(LocalDateTime startDate) { - this.startDate = startDate; - } - - public LocalDateTime getEndDate() { - return endDate; - } - - public void setEndDate(LocalDateTime endDate) { - this.endDate = endDate; - } - - public List getUserID() { - return userID; - } - - public void setUserID(List userID) { - this.userID = userID; - } - - public Integer getAllocateNo() { - return allocateNo; - } - - public void setAllocateNo(Integer allocateNo) { - this.allocateNo = allocateNo; - } - - public String getLanguage() { - return language; - } - - public void setLanguage(String language) { - this.language = language; - } - - @Override - public String toString() { - return "GrievanceAllocationRequest{" + - "startDate=" + startDate + - ", endDate=" + endDate + - ", userID=" + userID + - ", allocateNo=" + allocateNo + - ", language=" + language + - '}'; - } - + @Override + public String toString() { + return "GrievanceAllocationRequest{" + "startDate=" + startDate + ", endDate=" + endDate + ", userID=" + userID + + ", allocateNo=" + allocateNo + ", language=" + preferredLanguage + '}'; + } } diff --git a/src/main/java/com/iemr/common/data/grievance/GrievanceDetails.java b/src/main/java/com/iemr/common/data/grievance/GrievanceDetails.java index 52659c3b..1a39edf1 100644 --- a/src/main/java/com/iemr/common/data/grievance/GrievanceDetails.java +++ b/src/main/java/com/iemr/common/data/grievance/GrievanceDetails.java @@ -17,123 +17,124 @@ import jakarta.persistence.Table; import jakarta.validation.constraints.NotBlank; import lombok.Data; +import lombok.NoArgsConstructor; @Entity @Table(name = "t_grievanceworklist") @Data +@NoArgsConstructor public class GrievanceDetails { - + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Expose @Column(name = "GWID") private Long gwid; - + @Expose @Column(name = "Grievanceid") private Long grievanceId; - + @Expose @Column(name = "BeneficiaryRegID") private Long beneficiaryRegID; - + @Column(name = "BenCallid") @Expose private Long benCallID; - + @Column(name = "ProviderServiceMapID") @Expose private Integer providerServiceMapID; - + @Expose @Column(name = "ComplaintID") private String complaintID; - + @Expose @Column(name = "SubjectOfComplaint") private String subjectOfComplaint; - + @Expose @Column(name = "Complaint") private String complaint; - + @Expose @Column(name = "primaryNumber") private String primaryNumber; - + @Expose @Column(name = "Severety") @NotBlank(message = "Severety is required") private String severety; - + @Expose @Column(name = "Level") - private String level; + private String level; @Expose @Column(name = "State") private String state; - + @Expose @Column(name = "Agentid") - private String agentid; - + private String agentid; + @Expose @Column(name = "userid") - private String userid; - + private Integer assignedUserID; + @Expose @Column(name = "isAllocated") private Boolean isAllocated = false; - + @Expose - @Column(name = "retryNeeded") - private Boolean retryNeeded; - + @Column(name = "retryNeeded") + private Boolean retryNeeded; + @Expose @Column(name = "isRegistered") private Boolean isRegistered = false; - - @Expose - @Column(name = "callCounter") - private Integer callCounter; - - @Expose - @Column(name = "PreferredLanguageId") - private Integer preferredLanguageId; - - @Expose - @Column(name = "PreferredLanguage") - private String preferredLanguage; - + + @Expose + @Column(name = "callCounter") + private Integer callCounter; + + @Expose + @Column(name = "PreferredLanguageId") + private Integer preferredLanguageId; + + @Expose + @Column(name = "PreferredLanguage") + private String preferredLanguage; @Column(name = "Deleted", insertable = false, updatable = true) private Boolean deleted = false; - + @Expose @Column(name = "Processed") - private Character processed = 'N'; - + private Character processed = 'N'; + @Column(name = "CreatedBy") @Expose private String createdBy; - + @Expose @Column(name = "CreatedDate", insertable = false, updatable = false) private Timestamp createdDate; - + @Column(name = "ModifiedBy") private String modifiedBy; - + @Column(name = "LastModDate", insertable = false, updatable = false) private Timestamp lastModDate; - + @Expose @Column(name = "VanSerialNo") private Integer vanSerialNo; @Expose @Column(name = "VanID") private Integer vanID; - + @Expose @Column(name = "VehicalNo") private String vehicalNo; @@ -147,23 +148,22 @@ public class GrievanceDetails { @Expose @Column(name = "SyncedDate") private Timestamp syncedDate; - + @Expose @Column(name = "isCompleted") private Boolean isCompleted = false; - + @OneToMany(mappedBy = "grievanceDetails", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JsonManagedReference - private List grievanceTransactionDetails; - + private List grievanceTransactionDetails; public GrievanceDetails(Long gwid, Long grievanceId, Long beneficiaryRegID, Long benCallID, Integer providerServiceMapID, String complaintID, String subjectOfComplaint, String complaint, - String primaryNumber, String severety, String state, String agentID, String userid, Boolean isAllocated, - Boolean retryNeeded, Boolean isRegistered, Integer callCounter, Integer preferredLanguageId, String preferredLanguage, Boolean deleted, Character processed, - String createdBy, Timestamp createdDate, String modifiedBy, Timestamp lastModDate, Integer vanSerialNo, - Integer vanID, String vehicalNo, Integer parkingPlaceID, String syncedBy, Timestamp syncedDate, - Boolean isCompleted) { + String primaryNumber, String severety, String state, String agentID, Integer userid, Boolean isAllocated, + Boolean retryNeeded, Boolean isRegistered, Integer callCounter, Integer preferredLanguageId, + String preferredLanguage, Boolean deleted, Character processed, String createdBy, Timestamp createdDate, + String modifiedBy, Timestamp lastModDate, Integer vanSerialNo, Integer vanID, String vehicalNo, + Integer parkingPlaceID, String syncedBy, Timestamp syncedDate, Boolean isCompleted) { super(); this.gwid = gwid; this.grievanceId = grievanceId; @@ -177,7 +177,7 @@ public GrievanceDetails(Long gwid, Long grievanceId, Long beneficiaryRegID, Long this.severety = severety; this.state = state; this.agentid = agentID; - this.userid = userid; + this.assignedUserID = userid; this.isAllocated = isAllocated; this.retryNeeded = retryNeeded; this.isRegistered = isRegistered; @@ -198,279 +198,5 @@ public GrievanceDetails(Long gwid, Long grievanceId, Long beneficiaryRegID, Long this.syncedDate = syncedDate; this.isCompleted = isCompleted; } - - // Getters and Setters - public Long getGwid() { - return gwid; - } - - public void setGwid(Long gwid) { - this.gwid = gwid; - } - - public Long getGrievanceId() { - return grievanceId; - } - - public void setGrievanceId(Long grievanceId) { - this.grievanceId = grievanceId; - } - - public Long getBeneficiaryRegId() { - return beneficiaryRegID; - } - - public void setBeneficiaryRegId(Long beneficiaryRegId) { - this.beneficiaryRegID = beneficiaryRegId; - } - - public Long getBencallId() { - return benCallID; - } - - public void setBencallId(Long bencallId) { - this.benCallID = bencallId; - } - - public Integer getProviderServiceMapId() { - return providerServiceMapID; - } - - public void setProviderServiceMapId(Integer providerServiceMapId) { - this.providerServiceMapID = providerServiceMapId; - } - - public String getComplaintId() { - return complaintID; - } - - public void setComplaintId(String complaintId) { - this.complaintID = complaintId; - } - - public String getSubjectOfComplaint() { - return subjectOfComplaint; - } - - public void setSubjectOfComplaint(String subjectOfComplaint) { - this.subjectOfComplaint = subjectOfComplaint; - } - - public String getComplaint() { - return complaint; - } - - public void setComplaint(String complaint) { - this.complaint = complaint; - } - - public String getPrimaryNumber() { - return primaryNumber; - } - - public void setPrimaryNumber(String primaryNumber) { - this.primaryNumber = primaryNumber; - } - - public String getSeverety() { - return severety; - } - - public void setSeverity(String severety) { - this.severety = severety; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public String getAgentId() { - return agentid; - } - - public void setAgentId(String agentId) { - this.agentid = agentId; - } - - public Boolean getIsRegistered() { - return isRegistered; - } - - public void setIsRegistered(Boolean isRegistered) { - this.isRegistered = isRegistered; - } - - public String getUserId() { - return userid; - } - - public void setUserId(String userId) { - this.userid = userId; - } - - public Boolean getIsAllocated() { - return isAllocated; - } - - public void setIsAllocated(Boolean isAllocated) { - this.isAllocated = isAllocated; - } - - public Boolean getRetryNeeded() { - return retryNeeded; - } - - public void setRetryNeeded(Boolean retryNeeded) { - this.retryNeeded = retryNeeded; - } - - public Integer getCallCounter() { - return callCounter; - } - - public void setCallCounter(Integer callCounter) { - this.callCounter = callCounter; - } - - public Integer getPreferredLanguageId() { - return preferredLanguageId; - } - - public void setPreferredLanguageId(Integer preferredLanguageId) { - this.preferredLanguageId = preferredLanguageId; - } - - public String getPreferredLanguage() { - return preferredLanguage; - } - - public void setPreferredLanguage(String preferredLanguage) { - this.preferredLanguage = preferredLanguage; - } - - public Boolean getDeleted() { - return deleted; - } - - public void setDeleted(Boolean deleted) { - this.deleted = deleted; - } - - public Character getProcessed() { - return processed; - } - - public void setProcessed(Character processed) { - this.processed = processed; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public Timestamp getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Timestamp createdDate) { - this.createdDate = createdDate; - } - - public String getModifiedBy() { - return modifiedBy; - } - - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - public Timestamp getLastModDate() { - return lastModDate; - } - - public void setLastModDate(Timestamp lastModDate) { - this.lastModDate = lastModDate; - } - - public Integer getVanSerialNo() { - return vanSerialNo; - } - - public void setVanSerialNo(Integer vanSerialNo) { - this.vanSerialNo = vanSerialNo; - } - - public Integer getVanId() { - return vanID; - } - - public void setVanId(Integer vanId) { - this.vanID = vanId; - } - - public String getVehicleNo() { - return vehicalNo; - } - - public void setVehicleNo(String vehicleNo) { - this.vehicalNo = vehicleNo; - } - - public Integer getParkingPlaceId() { - return parkingPlaceID; - } - - public void setParkingPlaceId(Integer parkingPlaceId) { - this.parkingPlaceID = parkingPlaceId; - } - - public String getSyncedBy() { - return syncedBy; - } - - public void setSyncedBy(String syncedBy) { - this.syncedBy = syncedBy; - } - - public Timestamp getSyncedDate() { - return syncedDate; - } - - public void setSyncedDate(Timestamp syncedDate) { - this.syncedDate = syncedDate; - } - - public Boolean getIsCompleted() { - return isCompleted; - } - - public void setIsCompleted(Boolean isCompleted) { - this.isCompleted = isCompleted; - } - - - - // Getter for grievanceTransactionDetails - public List getGrievanceTransactionDetails() { - return grievanceTransactionDetails; - } - - // Setter for grievanceTransactionDetails - public void setGrievanceTransactionDetails(List grievanceTransactionDetails) { - this.grievanceTransactionDetails = grievanceTransactionDetails; - } - - - } - - \ No newline at end of file diff --git a/src/main/java/com/iemr/common/data/grievance/GrievanceReallocationRequest.java b/src/main/java/com/iemr/common/data/grievance/GrievanceReallocationRequest.java new file mode 100644 index 00000000..4cd202bd --- /dev/null +++ b/src/main/java/com/iemr/common/data/grievance/GrievanceReallocationRequest.java @@ -0,0 +1,18 @@ +package com.iemr.common.data.grievance; + +import java.util.List; + +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +public class GrievanceReallocationRequest { + + private Integer providerServiceMapId; + private String language; + private Integer fromUserId; + private List touserID; + private Integer allocateNo; + +} diff --git a/src/main/java/com/iemr/common/data/grievance/MoveToBinRequest.java b/src/main/java/com/iemr/common/data/grievance/MoveToBinRequest.java new file mode 100644 index 00000000..7c095ec1 --- /dev/null +++ b/src/main/java/com/iemr/common/data/grievance/MoveToBinRequest.java @@ -0,0 +1,14 @@ +package com.iemr.common.data.grievance; + +import lombok.Data; + +@Data +public class MoveToBinRequest { + + private Integer providerServiceMapID; + private Integer assignedUserID; + private String preferredLanguageName; + private Boolean is1097; + private Integer noOfCalls; + +} diff --git a/src/main/java/com/iemr/common/data/grievance/UnallocationRequest.java b/src/main/java/com/iemr/common/data/grievance/UnallocationRequest.java new file mode 100644 index 00000000..1f89ff2e --- /dev/null +++ b/src/main/java/com/iemr/common/data/grievance/UnallocationRequest.java @@ -0,0 +1,17 @@ +package com.iemr.common.data.grievance; + +import java.sql.Timestamp; + +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +public class UnallocationRequest { + + private Integer providerServiceMapID; + private String preferredLanguageName; + private Timestamp filterStartDate; + private Timestamp filterEndDate; + +} diff --git a/src/main/java/com/iemr/common/repository/grievance/GrievanceDataRepo.java b/src/main/java/com/iemr/common/repository/grievance/GrievanceDataRepo.java index b874dac4..151ab91d 100644 --- a/src/main/java/com/iemr/common/repository/grievance/GrievanceDataRepo.java +++ b/src/main/java/com/iemr/common/repository/grievance/GrievanceDataRepo.java @@ -1,9 +1,9 @@ package com.iemr.common.repository.grievance; - -import java.time.LocalDateTime; +import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; +import java.util.Set; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; @@ -15,30 +15,60 @@ import jakarta.transaction.Transactional; @Repository -public interface GrievanceDataRepo extends CrudRepository{ +public interface GrievanceDataRepo extends CrudRepository { @Query("SELECT COUNT(g) > 0 FROM GrievanceDetails g WHERE g.complaintID = :complaintId") - boolean existsByComplaintId(@Param("complaintId") String complaintId); - - @Query("select count(request) " - + "from GrievanceDetails request where request.isAllocated = false") - public Long fetchUnallocatedGrievanceCount(); + boolean existsByComplaintId(@Param("complaintId") String complaintId); - - @Query("SELECT g FROM GrievanceDetails g WHERE g.createdDate BETWEEN :startDate AND :endDate AND g.isAllocated = false AND g.preferredLanguage = :language") - List findGrievancesInDateRangeAndLanguage( - @Param("startDate") LocalDateTime startDate, - @Param("endDate") LocalDateTime endDate, - @Param("language") String language); + @Query("SELECT g FROM GrievanceDetails g WHERE g.createdDate BETWEEN :startDate AND :endDate AND g.isAllocated = false AND g.preferredLanguage = :language") + List findGrievancesInDateRangeAndLanguage(@Param("startDate") Timestamp startDate, + @Param("endDate") Timestamp endDate, @Param("language") String language); - @Modifying - @Query("UPDATE GrievanceDetails g SET g.isAllocated = true, g.userid = :userId WHERE g.grievanceId = :grievanceId") - @Transactional - public int allocateGrievance(@Param("grievanceId") Long grievanceId, @Param("userId") Integer userId); + @Modifying + @Query("UPDATE GrievanceDetails g SET g.isAllocated = true, g.assignedUserID = :assignedUserId WHERE g.grievanceId = :grievanceId") + @Transactional + public int allocateGrievance(@Param("grievanceId") Long grievanceId, + @Param("assignedUserId") Integer assignedUserId); @Query(nativeQuery = true, value = "SELECT PreferredLanguageId, PreferredLanguage, VanSerialNo, VanID, ParkingPlaceId, VehicalNo FROM db_identity.i_beneficiarydetails WHERE BeneficiaryRegID = :benRegId") public ArrayList getBeneficiaryGrievanceDetails(@Param("benRegId") Long benRegId); - + + @Query("select grievance.preferredLanguage, count(distinct grievance.grievanceId) " + + "from GrievanceDetails grievance " + "where grievance.providerServiceMapID = :providerServiceMapID " + + "and grievance.assignedUserID = :assignedUserID " + "and grievance.deleted = false " + + "group by grievance.preferredLanguage") + public Set fetchGrievanceRecordsCount(@Param("providerServiceMapID") Integer providerServiceMapID, + @Param("assignedUserID") Integer assignedUserID); + + @Query("SELECT g FROM GrievanceDetails g WHERE g.assignedUserID = :assignedUserID AND g.preferredLanguage = :language AND g.isAllocated = true") + List findAllocatedGrievancesByUserAndLanguage(@Param("assignedUserID") Integer assignedUserID, + @Param("language") String language); + + @Modifying + @Query("UPDATE GrievanceDetails g SET g.assignedUserID = :assignedUserID WHERE g.grievanceId = :grievanceId") + @Transactional + public int reallocateGrievance(@Param("grievanceId") Long grievanceId, + @Param("assignedUserID") Integer assignedUserID); + + @Query("SELECT g FROM GrievanceDetails g WHERE g.assignedUserID = :assignedUserID " + + "AND g.preferredLanguage = :preferredLanguageName") + List findGrievancesByUserAndLanguage(@Param("assignedUserID") Integer assignedUserID, + @Param("preferredLanguageName") String language); + + @Modifying + @Transactional + @Query("UPDATE GrievanceDetails g SET g.assignedUserID = NULL WHERE g.grievanceId = :grievanceId AND g.assignedUserID = :assignedUserID") + int unassignGrievance(@Param("grievanceId") Long grievanceId, @Param("assignedUserID") Integer assignedUserID); + + @Modifying + @Transactional + @Query("UPDATE GrievanceDetails g SET g.isAllocated = :isAllocated WHERE g.grievanceId = :grievanceId") + int updateGrievanceAllocationStatus(@Param("grievanceId") Long grievanceId, + @Param("isAllocated") Boolean isAllocated); + + @Query("Select grievance.preferredLanguage, count(grievance) from GrievanceDetails grievance where grievance.isAllocated=false group by grievance.preferredLanguage") + public Set fetchUnallocatedGrievanceCount(); + } diff --git a/src/main/java/com/iemr/common/service/grievance/GrievanceDataSync.java b/src/main/java/com/iemr/common/service/grievance/GrievanceDataSync.java index ec0992f7..b7546fea 100644 --- a/src/main/java/com/iemr/common/service/grievance/GrievanceDataSync.java +++ b/src/main/java/com/iemr/common/service/grievance/GrievanceDataSync.java @@ -10,6 +10,6 @@ public interface GrievanceDataSync { public List> dataSyncToGrievance(); - public String fetchUnallocatedGrievanceCount() throws IEMRException, JSONException; + public String fetchUnallocatedGrievanceCount(String preferredLanguage) throws IEMRException, JSONException; } diff --git a/src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java b/src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java index b5600c7a..b93c2721 100644 --- a/src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java +++ b/src/main/java/com/iemr/common/service/grievance/GrievanceDataSyncImpl.java @@ -6,9 +6,12 @@ import java.util.Calendar; import java.util.Date; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; +import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; @@ -52,6 +55,8 @@ public class GrievanceDataSyncImpl implements GrievanceDataSync { private static final String FILE_NAME = "fileName"; private static final String FILE_TYPE = "fileType"; + private static final String PREFERRED_LANGUAGE = "preferredLanguage"; + private static final String COUNT_OF_PREFERRED_LANGUAGE = "countOfPrefLanguage"; private final GrievanceDataRepo grievanceDataRepo; private final GrievanceTransactionRepo grievanceTransactionRepo; @@ -159,7 +164,7 @@ public List> dataSyncToGrievance() { + " already exists in the grievance worklist table."); } - grievance.setComplaintId(formattedComplaintId); + grievance.setComplaintID(formattedComplaintId); // Fetch related grievance transaction details List transactionDetailsList = fetchGrievanceTransactions( @@ -210,33 +215,32 @@ public List> dataSyncToGrievance() { for (Object[] objects : lists) { if (objects != null && objects.length <= 4) { - grievance.setComplaintId((String) objects[0]); - grievance.setBeneficiaryRegId((Long) objects[1]); - grievance.setBencallId((Long) objects[2]); - grievance.setProviderServiceMapId((Integer) objects[3]); + grievance.setComplaintID((String) objects[0]); + grievance.setBeneficiaryRegID((Long) objects[1]); + grievance.setBenCallID((Long) objects[2]); + grievance.setProviderServiceMapID((Integer) objects[3]); String state = locationStateRepository .findByStateIDForGrievance((Integer) objects[4]); grievance.setState(state); } } - //setting language related properties and other - ArrayList list1 = grievanceDataRepo.getBeneficiaryGrievanceDetails(grievance.getBeneficiaryRegId()); + // setting language related properties and other + ArrayList list1 = grievanceDataRepo + .getBeneficiaryGrievanceDetails(grievance.getBeneficiaryRegID()); for (Object[] objects : list1) { if (objects != null && objects.length >= 6) { grievance.setPreferredLanguageId((Integer) objects[0]); grievance.setPreferredLanguage((String) objects[1]); grievance.setVanSerialNo((Integer) objects[2]); - grievance.setVanId((Integer) objects[3]); - grievance.setParkingPlaceId((Integer) objects[4]); + grievance.setVanID((Integer) objects[3]); + grievance.setParkingPlaceID((Integer) objects[4]); grievance.setVehicalNo((String) objects[5]); - + } } - - - + // Setting remaining grievance properties (similar to the existing code) - grievance.setAgentId(grievance.getAgentId()); + grievance.setAgentid(grievance.getAgentid()); grievance.setDeleted(grievance.getDeleted()); grievance.setCreatedBy(registeringUser); grievance.setProcessed('N'); @@ -256,8 +260,8 @@ public List> dataSyncToGrievance() { combinedData.put("complaintID", grievance.getGrievanceId()); combinedData.put("subjectOfComplaint", grievance.getSubjectOfComplaint()); combinedData.put("complaint", grievance.getComplaint()); - combinedData.put("beneficiaryRegID", grievance.getBeneficiaryRegId()); - combinedData.put("providerServiceMapId", grievance.getProviderServiceMapId()); + combinedData.put("beneficiaryRegID", grievance.getBeneficiaryRegID()); + combinedData.put("providerServiceMapId", grievance.getProviderServiceMapID()); combinedData.put("primaryNumber", grievance.getPrimaryNumber()); @@ -279,7 +283,7 @@ public List> dataSyncToGrievance() { combinedData.put("transaction", transactions); combinedData.put("severity", grievance.getSeverety()); combinedData.put("state", grievance.getState()); - combinedData.put("agentId", grievance.getAgentId()); + combinedData.put("agentId", grievance.getAgentid()); combinedData.put("deleted", grievance.getDeleted()); combinedData.put("createdBy", grievance.getCreatedBy()); combinedData.put("createdDate", grievance.getCreatedDate()); @@ -398,18 +402,70 @@ private void generateGrievanceAuthToken() { } } - public String fetchUnallocatedGrievanceCount() throws IEMRException, JSONException { + public String fetchUnallocatedGrievanceCount(String preferredLanguage) throws IEMRException, JSONException { logger.debug("Request received for fetchUnallocatedGrievanceCount"); - Long unallocatedCount = grievanceDataRepo.fetchUnallocatedGrievanceCount(); + // Fetch all unallocated grievances count from the database + Set resultSet = grievanceDataRepo.fetchUnallocatedGrievanceCount(); - if (unallocatedCount == null) { - throw new IEMRException("Failed to fetch unallocated grievance count"); + // Initialize the result JSON object to hold counts + JSONObject result = new JSONObject(); + boolean preferredLanguageFound = false; + result.put("All", 0); // Initialize the "All" language count to 0 + + // Loop through the resultSet and populate the counts for each language + if (resultSet != null && !resultSet.isEmpty()) { + for (Object[] recordSet : resultSet) { + String language = ((String) recordSet[0]).trim(); + Long count = (Long) recordSet[1]; + + // Add the count to the result for the current language + result.put(language, count); + result.put("All", result.getLong("All") + count); // Add to the total "All" count + + // If the preferred language matches, mark it as found + if (preferredLanguage != null && preferredLanguage.equalsIgnoreCase(language)) { + preferredLanguageFound = true; + } + } } - JSONObject result = new JSONObject(); - result.put("count", unallocatedCount); - return result.toString(); - } + // If the preferred language is provided but not found in the results, add it + // with count 0 + if (preferredLanguage != null && !preferredLanguageFound) { + result.put(preferredLanguage, 0); + } + + // Create the final JSON response array + JSONArray resultArray = new JSONArray(); + + // Case 1: If preferredLanguage is provided, return only that language's count + if (preferredLanguage != null) { + JSONObject preferredLanguageEntry = new JSONObject(); + preferredLanguageEntry.put(PREFERRED_LANGUAGE, preferredLanguage); + preferredLanguageEntry.put(COUNT_OF_PREFERRED_LANGUAGE, result.getLong(preferredLanguage)); + resultArray.put(preferredLanguageEntry); + } else { + // Case 2: If no preferredLanguage is provided, return counts for all languages + // Add the "All" entry first + JSONObject allEntry = new JSONObject(); + allEntry.put(PREFERRED_LANGUAGE, "All"); + allEntry.put(COUNT_OF_PREFERRED_LANGUAGE, result.getLong("All")); + resultArray.put(allEntry); + + // Add counts for other languages + Iterator keys = result.keys(); + while (keys.hasNext()) { + String key = keys.next(); + if (!key.equals("All")) { + JSONObject temp = new JSONObject(); + temp.put(PREFERRED_LANGUAGE, key); + temp.put(COUNT_OF_PREFERRED_LANGUAGE, result.getLong(key)); + resultArray.put(temp); + } + } + } + return resultArray.toString(); + } } diff --git a/src/main/java/com/iemr/common/service/grievance/GrievanceHandlingService.java b/src/main/java/com/iemr/common/service/grievance/GrievanceHandlingService.java index 19a96723..49065db7 100644 --- a/src/main/java/com/iemr/common/service/grievance/GrievanceHandlingService.java +++ b/src/main/java/com/iemr/common/service/grievance/GrievanceHandlingService.java @@ -1,9 +1,18 @@ package com.iemr.common.service.grievance; +import org.json.JSONException; import org.springframework.stereotype.Service; +import com.iemr.common.utils.exception.IEMRException; + @Service public interface GrievanceHandlingService { public String allocateGrievances(String request) throws Exception; + public String allocatedGrievanceRecordsCount(String request) throws IEMRException, JSONException; + + public String reallocateGrievances(String request) throws Exception; + + public String moveToBin(String request) throws Exception; + } 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 6ade7fc7..c79dd3de 100644 --- a/src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java +++ b/src/main/java/com/iemr/common/service/grievance/GrievanceHandlingServiceImpl.java @@ -1,79 +1,237 @@ package com.iemr.common.service.grievance; +import java.util.ArrayList; import java.util.Comparator; +import java.util.Iterator; import java.util.List; +import java.util.Set; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Service; import com.iemr.common.data.grievance.GrievanceAllocationRequest; import com.iemr.common.data.grievance.GrievanceDetails; +import com.iemr.common.data.grievance.GrievanceReallocationRequest; +import com.iemr.common.data.grievance.MoveToBinRequest; import com.iemr.common.repository.grievance.GrievanceDataRepo; +import com.iemr.common.utils.exception.IEMRException; import com.iemr.common.utils.mapper.InputMapper; @Service public class GrievanceHandlingServiceImpl implements GrievanceHandlingService { + private Logger logger = LoggerFactory.getLogger(GrievanceHandlingServiceImpl.class); - private Logger logger = LoggerFactory.getLogger(GrievanceHandlingServiceImpl.class); - - private final GrievanceDataRepo grievanceDataRepo; - - @Autowired - public GrievanceHandlingServiceImpl(GrievanceDataRepo grievanceDataRepo) { - this.grievanceDataRepo = grievanceDataRepo; - } - - - @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 2: Fetch grievances based on the start date, end date range, and language - List grievances = grievanceDataRepo.findGrievancesInDateRangeAndLanguage( - allocationRequest.getStartDate(), allocationRequest.getEndDate(), allocationRequest.getLanguage()); - - if (grievances.isEmpty()) { - 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.getUserID(); - 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); - } - - // Move to the next user after allocateNo grievances - if ((i + 1) % allocateNo == 0) { - userIndex = (userIndex + 1) % userIds.size(); - } - } - - // Step 6: Return a message with the total number of grievances allocated - return "Successfully allocated " + totalAllocated + " grievances to users."; - } + @Autowired + public GrievanceHandlingServiceImpl(GrievanceDataRepo grievanceDataRepo) { + this.grievanceDataRepo = grievanceDataRepo; + } + + @Value("${grievanceAllocationRetryConfiguration}") + private Integer grievanceAllocationRetryConfiguration; // Value from application.properties, can be used to + // configure + // 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 2: Fetch grievances based on the start date, end date range, and + // language + List grievances = grievanceDataRepo.findGrievancesInDateRangeAndLanguage( + allocationRequest.getStartDate(), allocationRequest.getEndDate(), + allocationRequest.getPreferredLanguage()); + + if (grievances.isEmpty()) { + 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.getUserID(); + 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); + } + + // Move to the next user after allocateNo grievances + if ((i + 1) % allocateNo == 0) { + userIndex = (userIndex + 1) % userIds.size(); + } + } + + // Step 6: Return a message with the total number of grievances allocated + return "Successfully allocated " + totalAllocated + " grievances to users."; + } + + @Override + public String allocatedGrievanceRecordsCount(String request) throws IEMRException, JSONException { + GrievanceDetails grievanceRequest = InputMapper.gson().fromJson(request, GrievanceDetails.class); + + Integer providerServiceMapID = grievanceRequest.getProviderServiceMapID(); + Integer assignedUserID = grievanceRequest.getAssignedUserID(); + + Set resultSet = grievanceDataRepo.fetchGrievanceRecordsCount(providerServiceMapID, assignedUserID); + + JSONObject result = new JSONObject(); + result.put("All", 0); + + if (resultSet != null && !resultSet.isEmpty()) { + for (Object[] recordSet : resultSet) { + String language = ((String) recordSet[0]).trim(); + Long count = (Long) recordSet[1]; + result.put(language, count); + result.put("All", result.getLong("All") + count); + } + } + + JSONArray resultArray = new JSONArray(); + Iterator keys = result.keys(); + while (keys.hasNext()) { + String key = keys.next(); + if (!key.equals("All") || result.getLong(key) > 0) { // Skip "All" if it's empty + JSONObject temp = new JSONObject(); + temp.put("language", key); + temp.put("count", result.getLong(key)); + resultArray.put(temp); + } + } + + 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 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."); + } + + // 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 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); + + // Call the repository method to reallocate the grievance to the new user + int rowsAffected = grievanceDataRepo.reallocateGrievance(grievance.getGrievanceId(), toUserId); + + 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); + } + + userIndex = (userIndex + 1) % toUserIds.size(); + } + } + + // Step 6: Return a message with the total number of grievances reallocated + return "Successfully reallocated " + totalReallocated + " grievances to users."; + } + + @Override + public String moveToBin(String request) throws Exception { + // Step 1: Parse the request string into the appropriate MoveToBinRequest object + MoveToBinRequest moveToBinRequest = InputMapper.gson().fromJson(request, MoveToBinRequest.class); + + // Step 2: Fetch grievances based on assigned user, language + // condition + List grievances = grievanceDataRepo.findGrievancesByUserAndLanguage( + moveToBinRequest.getAssignedUserID(), moveToBinRequest.getPreferredLanguageName()); + + if (grievances.isEmpty()) { + throw new Exception("No grievances found for the given user, language, and condition."); + } + + // Step 3: Filter grievances to select only the required number of calls + List grievancesToMove = new ArrayList<>(); + int count = 0; + + for (GrievanceDetails grievance : grievances) { + if (count >= moveToBinRequest.getNoOfCalls()) { + break; // Stop once we've selected the required number of grievances + } + grievancesToMove.add(grievance); + count++; + } + + if (grievancesToMove.isEmpty()) { + throw new Exception("No grievances found to move to bin."); + } + + // Step 4: Unassign grievances from the user and "move them to bin" + int totalUnassigned = 0; + for (GrievanceDetails grievance : grievancesToMove) { + int rowsAffected = grievanceDataRepo.unassignGrievance(grievance.getGrievanceId(), + moveToBinRequest.getAssignedUserID()); + if (rowsAffected > 0) { + grievance.setIsAllocated(false); // Assuming there's a setter for this flag + int updateFlagResult = grievanceDataRepo.updateGrievanceAllocationStatus(grievance.getGrievanceId(), + false); + if (updateFlagResult > 0) { + totalUnassigned++; + logger.debug("Unassigned grievance ID {} from user ID {}", grievance.getGrievanceId(), + moveToBinRequest.getAssignedUserID()); + } else { + logger.error("Failed to unassign grievance ID {} from user ID {}", grievance.getGrievanceId(), + moveToBinRequest.getAssignedUserID()); + } + } else { + logger.error("Failed to unassign grievance ID {} from user ID {}", grievance.getGrievanceId(), + moveToBinRequest.getAssignedUserID()); + } + } + + // Step 5: Return the response as count of successfully unassigned grievances + return totalUnassigned + " grievances successfully moved to bin."; + } }