diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index af5c31d0..238d5f92 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -43,3 +43,10 @@ abha.client.id=@env.ABHA_CLIENT_ID@ abha.client.secret=@env.ABHA_CLIENT_SECRET@ abha.token.url=@env.ABHA_TOKEN_URL@ abha.xcmid=@env.ABHA_XCM_ID@ + +# GovThealth API Config +govthealth.user.details.url=@env.GOVTHEALTH_USER_DETAILS_URL@ +govthealth.user.id=@env.GOVTHEALTH_USER_ID@ +govthealth.password=@env.GOVTHEALTH_PASSWORD@ + + diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index cce60f89..07309133 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -43,5 +43,10 @@ abha.client.secret=${ABHA_CLIENT_SECRET} abha.token.url=${ABHA_TOKEN_URL} abha.xcmid=${ABHA_XCM_ID} +# GovThealth API Config +govthealth.user.details.url=${GOVTHEALTH_USER_DETAILS_URL} +govthealth.user.id=${GOVTHEALTH_USER_ID} +govthealth.password=${GOVTHEALTH_PASSWORD} + diff --git a/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java b/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java new file mode 100644 index 00000000..8025de55 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java @@ -0,0 +1,54 @@ +package com.iemr.flw.controller; + +import com.iemr.flw.domain.iemr.AdolescentHealth; +import com.iemr.flw.dto.abhaBeneficiary.AbhaBeneficiaryDTO; +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.AbhaRequestDTO; +import com.iemr.flw.service.AbhaBeneficiaryService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/UserRegistration") +public class AbhaBeneficiaryController { + @Autowired + private AbhaBeneficiaryService abhaBeneficiaryService; + + private final org.slf4j.Logger logger = LoggerFactory.getLogger(AbhaBeneficiaryController.class); + + + + @RequestMapping(value = "/GetUserDetailsByAyushmanCardNo",method = RequestMethod.POST) + public ResponseEntity> getAllAdolescentHealth(@RequestBody AbhaRequestDTO request ) { + Map response = new HashMap<>(); + try { + if(request.getCardNo()!=null){ + Object abhaBeneficiaryDTOList = abhaBeneficiaryService.getBeneficiaryByAbha(request); + + if (abhaBeneficiaryDTOList != null ) { + response.put("statusCode",200); + response.put("data", abhaBeneficiaryDTOList); + } else { + response.put("statusCode", 5000); + response.put("error", "Invalid/NULL request obj"); + } + } + + } catch (Exception e) { + logger.error("Error in get data : " + e); + response.put("statusCode",5000); + response.put("error","Error in get data : " + e); + + } + return ResponseEntity.ok(response); + } +} diff --git a/src/main/java/com/iemr/flw/controller/BeneficiaryController.java b/src/main/java/com/iemr/flw/controller/BeneficiaryController.java index ee573095..d439fbf5 100644 --- a/src/main/java/com/iemr/flw/controller/BeneficiaryController.java +++ b/src/main/java/com/iemr/flw/controller/BeneficiaryController.java @@ -97,7 +97,7 @@ public ResponseEntity saveEyeSurgery(@RequestBody List logger.error("Error saving eye checkup visit:", e); response.put("statusCode", 5000); response.put("errorMessage", e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + return ResponseEntity.ok(response); } } @@ -117,14 +117,14 @@ public ResponseEntity getAllEyeSurgery(@RequestBody GetBenRequestHandler requ } else { response.put("statusCode", 5000); response.put("message", "No records found"); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + return ResponseEntity.ok(response); } } catch (Exception e) { logger.error("Error fetching eye checkup visit:", e); response.put("statusCode", 5000); response.put("errorMessage", e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + return ResponseEntity.ok(response); } } @@ -185,9 +185,8 @@ public ResponseEntity saveIfaFormData( response.put("statusCode", 5000); response.put("errorMessage", e.getMessage()); - return ResponseEntity - .status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(response); + return ResponseEntity.ok(response); + } } diff --git a/src/main/java/com/iemr/flw/controller/ChildCareController.java b/src/main/java/com/iemr/flw/controller/ChildCareController.java index 0e45b36a..bbc9cba2 100644 --- a/src/main/java/com/iemr/flw/controller/ChildCareController.java +++ b/src/main/java/com/iemr/flw/controller/ChildCareController.java @@ -7,9 +7,12 @@ import com.iemr.flw.domain.iemr.HbncVisit; import com.iemr.flw.domain.iemr.IfaDistribution; import com.iemr.flw.domain.iemr.SamVisitResponseDTO; +import com.iemr.flw.domain.iemr.UserServiceRole; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.repo.iemr.UserServiceRoleRepo; import com.iemr.flw.service.ChildCareService; +import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.response.OutputResponse; @@ -39,9 +42,14 @@ public class ChildCareController { @Autowired private ChildCareService childCareService; + @Autowired + private UserService userService; + @Autowired private JwtUtil jwtUtil; + @Autowired + private UserServiceRoleRepo userServiceRoleRepo; @Operation(summary = "save HBYC details") @RequestMapping(value = {"/hbycVisit/saveAll"}, method = {RequestMethod.POST}) public String saveHbycRecords(@RequestBody List hbycDTOs, @@ -117,7 +125,7 @@ public String saveHBNCVisit(@RequestBody List hbncRequestDTOs, } } catch (Exception e) { logger.error("Error saving HBNC visit: ", e); - response.setError(500, "Server error: " + e.getMessage()); + response.setError(5000, "Server error: " + e.getMessage()); } return response.toString(); } @@ -153,7 +161,7 @@ public ResponseEntity>> getHBNCVisit } catch (Exception e) { logger.error("Exception in fetching HBNC visits", e); - response.setStatusCode(500); + response.setStatusCode(5000); response.setStatus("Failed"); response.setErrorMessage("Internal Server Error: " + e.getMessage()); response.setData(null); @@ -249,7 +257,7 @@ public ResponseEntity saveSevereAcuteMalnutrition(@RequestBody List s if(token!=null){ Integer userId = jwtUtil.extractUserId(token); - String userName = jwtUtil.extractUsername(token); + String userName = userService.getUserDetail(userId).getUserName(); String responseObject = childCareService.saveSamDetails(samRequest,userId,userName); if (responseObject != null) { @@ -270,7 +278,7 @@ public ResponseEntity saveSevereAcuteMalnutrition(@RequestBody List s } catch (Exception e) { logger.error("Error saving SAM details:", e); - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode",5000); response.put("errorMessage", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } @@ -295,7 +303,7 @@ public ResponseEntity getAllSevereAcuteMalnutrition(@RequestBody GetBenReques } catch (Exception e) { logger.error("Error fetching SAM records:", e); - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode", 5000); response.put("errorMessage", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } @@ -313,9 +321,8 @@ public ResponseEntity saveOrsDistribution(@RequestBody List saveOrsDistribution(@RequestBody List getAllOrDistribution(@RequestBody GetBenRequestHandler response.put("data", responseObject); return ResponseEntity.ok(response); } else { - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode", 5000); response.put("message", "No ORS records found"); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } } catch (Exception e) { logger.error("Error fetching ORS records:", e); - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode", 5000); response.put("errorMessage", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } @@ -402,7 +409,7 @@ public ResponseEntity saveIfDistribution(@RequestBody List getIfaDistribution(@RequestBody GetBenRequestHandler re } catch (Exception e) { logger.error("Error fetching IFA records:", e); - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode", 5000); response.put("errorMessage", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } diff --git a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java index 816fb244..764ebeaf 100644 --- a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java +++ b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java @@ -210,6 +210,8 @@ public ResponseEntity> getAllLeprosy( response.put("statusCode", 5000); } } catch (Exception e) { + logger.info("Fail leprosy: "+e.getMessage()); + logger.info("Fail leprosy full error: "+e); response.put("status", "Error: " + e.getMessage()); response.put("statusCode", 5000); } @@ -240,6 +242,8 @@ public ResponseEntity> getAllLeprosyFollowUp( response.put("statusCode", 5000); } } catch (Exception e) { + logger.info("Fail leprosy followUp: "+e.getMessage()); + logger.info("Fail leprosy full error: "+e); response.put("status", "Error: " + e.getMessage()); response.put("statusCode", 5000); } @@ -256,6 +260,8 @@ public ResponseEntity> getAllData( response.put("data", diseaseControlService.getAllScreeningData(getDiseaseRequestHandler)); } catch (Exception e) { + logger.info("getAllDisease "+e.getMessage()); + logger.info("Fail getAllDisease full error: "+e); response.put("status", "Error" + e.getMessage()); response.put("statusCode", 5000); } diff --git a/src/main/java/com/iemr/flw/controller/IRSRoundController.java b/src/main/java/com/iemr/flw/controller/IRSRoundController.java index 13193e05..77047f89 100644 --- a/src/main/java/com/iemr/flw/controller/IRSRoundController.java +++ b/src/main/java/com/iemr/flw/controller/IRSRoundController.java @@ -5,6 +5,7 @@ import com.iemr.flw.dto.iemr.IRSRoundListDTO; import com.iemr.flw.repo.iemr.UserServiceRoleRepo; import com.iemr.flw.service.IRSRoundService; +import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.response.OutputResponse; import org.springframework.beans.factory.annotation.Autowired; @@ -30,7 +31,7 @@ public class IRSRoundController { private JwtUtil jwtUtil; @Autowired - private UserServiceRoleRepo userServiceRoleRepo; + private UserService userService; @PostMapping(value = "/add") public ResponseEntity> addRound(@RequestBody IRSRoundListDTO dto,@RequestHeader("jwtToken") String token) { @@ -42,7 +43,7 @@ public ResponseEntity> addRound(@RequestBody IRSRoundListDTO return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response) ; } Integer userId = jwtUtil.extractUserId(token); - List s = irsRoundService.addRounds(dto.getRounds(), userId, userServiceRoleRepo.getUserNamedByUserId(userId)); + List s = irsRoundService.addRounds(dto.getRounds(), userId, userService.getUserDetail(userId).getUserName()); if (s.size() != 0) { Map data = new HashMap<>(); data.put("entries", s); diff --git a/src/main/java/com/iemr/flw/controller/IncentiveController.java b/src/main/java/com/iemr/flw/controller/IncentiveController.java index 0d317f9d..fe1d93ac 100644 --- a/src/main/java/com/iemr/flw/controller/IncentiveController.java +++ b/src/main/java/com/iemr/flw/controller/IncentiveController.java @@ -67,7 +67,7 @@ public String saveIncentiveMasterData(@RequestBody IncentiveRequestDTO incentive // add logic for different state or district if (incentiveRequestDTO != null) { String s = incentiveService.getIncentiveMaster(incentiveRequestDTO); - logger.info("All incentives" + s); + // logger.info("All incentives" + s); if (s != null) response.setResponse(s); @@ -94,7 +94,7 @@ public String getAllIncentivesByUserId(@RequestBody GetBenRequestHandler request logger.info("request object with timestamp : " + new Timestamp(System.currentTimeMillis()) + " " + requestDTO); String s = incentiveService.getAllIncentivesByUserId(requestDTO); - logger.info("User Incentive:" + s); + //logger.info("User Incentive:" + s); if (s != null) response.setResponse(s); else diff --git a/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java b/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java index c2b421d6..29204ab6 100644 --- a/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java +++ b/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java @@ -29,6 +29,8 @@ import com.iemr.flw.dto.iemr.MalariaFollowUpDTO; import com.iemr.flw.service.MalariaFollowUpService; import com.iemr.flw.utils.JwtUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -40,6 +42,7 @@ @RestController @RequestMapping(value = "/follow-up", headers = "Authorization") public class MalariaFollowUpController { + private final Logger logger = LoggerFactory.getLogger(MalariaFollowUpController.class); @Autowired private JwtUtil jwtUtil; @@ -88,6 +91,8 @@ public ResponseEntity> getFollowUpsByUserId(@RequestBody Get } } catch (Exception e) { + logger.info("Fail Malaria followUp: "+e.getMessage()); + logger.info("Fail Malaria full error: "+e); response.put("status", "Error: " + e.getMessage()); response.put("statusCode", 5000); } diff --git a/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiarydetail.java b/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiarydetail.java index 72e994f5..779a09da 100644 --- a/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiarydetail.java +++ b/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiarydetail.java @@ -186,4 +186,8 @@ public class RMNCHMBeneficiarydetail { @Transient private Integer ProviderServiceMapID; + @Expose + @Column(name = "familyid") + private String familyId; + } diff --git a/src/main/java/com/iemr/flw/domain/iemr/AbhaApiResponse.java b/src/main/java/com/iemr/flw/domain/iemr/AbhaApiResponse.java new file mode 100644 index 00000000..db38d11a --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/AbhaApiResponse.java @@ -0,0 +1,21 @@ +package com.iemr.flw.domain.iemr; + +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.iemr.flw.dto.abhaBeneficiary.AbhaBeneficiaryDTO; +import lombok.Data; + +import java.util.List; + +@Data +public class AbhaApiResponse { + + @JsonProperty("status_code") + private String statusCode; + + private String message; + + @JsonProperty("data") + @JsonAlias("object_data") + private List data; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/abhaBeneficiary/AbhaBeneficiaryDTO.java b/src/main/java/com/iemr/flw/dto/abhaBeneficiary/AbhaBeneficiaryDTO.java new file mode 100644 index 00000000..dab9dec3 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/abhaBeneficiary/AbhaBeneficiaryDTO.java @@ -0,0 +1,65 @@ +package com.iemr.flw.dto.abhaBeneficiary; + +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +@Data +public class AbhaBeneficiaryDTO { + @JsonProperty("personName") + private String personName; + + private String firstName; + + private String lastName; + + @JsonProperty("age") + private String age; + + @JsonProperty("address") + private String address; + + @JsonProperty("district") + private String district; + + @JsonProperty("mobileNo") + private String mobileNo; + + @JsonProperty("block") + private String block; + + @JsonProperty("cardNo") + private String cardNo; + + @JsonProperty("villagename") + private String villagename; + + @JsonProperty("gender") + private String gender; + + @JsonProperty("district_Code") + private String districtCode; + + @JsonProperty("block_Code") + private String blockCode; + + @JsonProperty("village_Code") + private String villageCode; + + @JsonProperty("rural_Urban") + private String ruralUrban; + + @JsonProperty("abhaId") + private String abhaId; + + @JsonProperty("vvs") + private String vvs; + + @JsonProperty("familyid") + private String familyid; + + @JsonProperty("dob") + @JsonAlias("dob_secc") + private String dob; + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/AbhaRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AbhaRequestDTO.java new file mode 100644 index 00000000..9ec31c6f --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/AbhaRequestDTO.java @@ -0,0 +1,10 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class AbhaRequestDTO { + private String cardNo; + private Long houseHoldId; + +} diff --git a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java index 864c31a8..b3988c3e 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -25,6 +25,9 @@ public interface BeneficiaryRepo extends JpaRepository findById(Long benID); + List findByHouseoldId(Long houseHoldId); + Optional findByBenficieryid(Long benID); + @Query(value = "SELECT beneficiaryRegID FROM db_identity.i_beneficiarydetails_rmnch WHERE BeneficiaryId = :benId", nativeQuery = true) Long getBenRegIdFromBenId(@Param("benId") Long benId); @@ -45,7 +48,7 @@ Page getBenDataWithinDates( Page getBenDataByUser(@Param("userName") String userName, Pageable pageable); @Query(value = " SELECT t FROM RMNCHMBeneficiarymapping t WHERE t.benAddressId = :addressID") - RMNCHMBeneficiarymapping getByAddressID(@Param("addressID") BigInteger addressID); + List getByAddressID(@Param("addressID") BigInteger addressID); @Query(value = " SELECT t FROM RMNCHMBeneficiarymapping t WHERE t.benRegId = :BenRegId") RMNCHMBeneficiarymapping getById(@Param("BenRegId") BigInteger BenRegId); @@ -69,7 +72,7 @@ Page getBenDataWithinDates( BigInteger getBenIdFromRegID(@Param("benRegID") Long benRegID); @Query(value = " SELECT t FROM RMNCHBeneficiaryDetailsRmnch t WHERE t.BenRegId =:benRegID ") - RMNCHBeneficiaryDetailsRmnch getDetailsByRegID(@Param("benRegID") Long benRegID); + List getDetailsByRegID(@Param("benRegID") Long benRegID); @Query(value = " SELECT t FROM RMNCHBornBirthDetails t WHERE t.BenRegId =:benRegID ") RMNCHBornBirthDetails getBornBirthByRegID(@Param("benRegID") Long benRegID); @@ -80,6 +83,9 @@ Page getBenDataWithinDates( @Query(nativeQuery = true, value = " SELECT HealthIdNumber,HealthID FROM db_iemr.m_benhealthidmapping WHERE BeneficiaryRegID = :benRegId ") Object[] getBenHealthIdNumber(@Param("benRegId") BigInteger benRegId); + + @Query(nativeQuery = true, value = " SELECT HealthIdNumber,HealthID FROM db_iemr.m_benhealthidmapping WHERE HealthIdNumber = :HealthIdNumber ") + Object[] getHealthIdNumber(@Param("HealthIdNumber") String HealthIdNumber); @Query(nativeQuery = true, value = " SELECT HealthID,HealthIdNumber,isNewAbha FROM db_iemr.t_healthid WHERE HealthIdNumber = :healthIdNumber ") ArrayList getBenHealthDetails(@Param("healthIdNumber") String healthIdNumber); diff --git a/src/main/java/com/iemr/flw/repo/identity/HouseHoldRepo.java b/src/main/java/com/iemr/flw/repo/identity/HouseHoldRepo.java index 514eeb6b..a5ee8f25 100644 --- a/src/main/java/com/iemr/flw/repo/identity/HouseHoldRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/HouseHoldRepo.java @@ -5,8 +5,10 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import java.util.List; + public interface HouseHoldRepo extends JpaRepository { @Query(" SELECT t FROM RMNCHHouseHoldDetails t WHERE t.houseoldId =:houseoldId ") - RMNCHHouseHoldDetails getByHouseHoldID(@Param("houseoldId") long houseoldId); + List getByHouseHoldID(@Param("houseoldId") long houseoldId); } diff --git a/src/main/java/com/iemr/flw/repo/iemr/ANCVisitRepo.java b/src/main/java/com/iemr/flw/repo/iemr/ANCVisitRepo.java index 067e6acc..6d22f752 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/ANCVisitRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/ANCVisitRepo.java @@ -19,6 +19,8 @@ List getANCForPW(@Param("userId") String userId, @Query - ANCVisit findANCVisitByBenIdAndAncVisitAndIsActive(Long benId, Integer ancVisit, boolean b); + List findANCVisitByBenIdAndAncVisitAndIsActive(Long benId, Integer ancVisit, boolean b); + + List findByBenId(Long benId); } diff --git a/src/main/java/com/iemr/flw/repo/iemr/ChildRegisterRepo.java b/src/main/java/com/iemr/flw/repo/iemr/ChildRegisterRepo.java index 499d7a5c..f456428b 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/ChildRegisterRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/ChildRegisterRepo.java @@ -21,5 +21,5 @@ List getChildDetailsForUser(@Param("userId") String userId, Long countByBenId(Long benId); - List findByBenIdOrderByCreatedDateAsc(Long benId); + List findByBenId(Long benId); } diff --git a/src/main/java/com/iemr/flw/repo/iemr/EligibleCoupleRegisterRepo.java b/src/main/java/com/iemr/flw/repo/iemr/EligibleCoupleRegisterRepo.java index 2eae0b05..218c5b2b 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/EligibleCoupleRegisterRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/EligibleCoupleRegisterRepo.java @@ -14,7 +14,12 @@ public interface EligibleCoupleRegisterRepo extends JpaRepository findByCreatedBy(String userName); + @Query(" SELECT ecr FROM EligibleCoupleRegister ecr WHERE ecr.createdBy = :userId and ecr.createdDate >= :fromDate and ecr.createdDate <= :toDate") List getECRegRecords(@Param("userId") String userId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); + + @Query(" SELECT ecr FROM EligibleCoupleRegister ecr WHERE ecr.createdBy = :userId") + List getECRegRecords(@Param("userId") String userId); } diff --git a/src/main/java/com/iemr/flw/repo/iemr/IFAFormSubmissionRepository.java b/src/main/java/com/iemr/flw/repo/iemr/IFAFormSubmissionRepository.java index 40cbd60b..0b1b5ff7 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IFAFormSubmissionRepository.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IFAFormSubmissionRepository.java @@ -2,6 +2,8 @@ import com.iemr.flw.domain.iemr.IFAFormSubmissionData; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; @@ -9,4 +11,10 @@ public interface IFAFormSubmissionRepository extends JpaRepository { List findByUserId(Integer userName); + @Query("SELECT i FROM IFAFormSubmissionData i " + + "WHERE i.userId = :userId " + + "AND i.visitDate = :visitDate") + List findTodayData( + @Param("userId") Integer userId, + @Param("visitDate") String visitDate); } diff --git a/src/main/java/com/iemr/flw/repo/iemr/PNCVisitRepo.java b/src/main/java/com/iemr/flw/repo/iemr/PNCVisitRepo.java index 28675daa..39da97da 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/PNCVisitRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/PNCVisitRepo.java @@ -16,4 +16,6 @@ public interface PNCVisitRepo extends JpaRepository { List getPNCForPW(@Param("userId") String userId); PNCVisit findPNCVisitByBenIdAndPncPeriodAndIsActive(Long benId, Integer pncVisit, Boolean isActive); + + List findByBenId(Long benId); } diff --git a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java index ef6cc048..a5658777 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java @@ -36,6 +36,21 @@ public interface SupervisorDashboardRepo extends JpaRepository getAshasWithFacilityInfo(@Param("supervisorUserID") Integer supervisorUserID); + // Unclaimed incentive count per ASHA + @Query(value = "SELECT iar.asha_id, " + + "COUNT(*) AS unclaimedCount " + + "FROM incentive_activity_record iar " + + "WHERE iar.asha_id IN (:ashaIds) " + + "AND iar.created_date >= :startDate " + + "AND iar.created_date < :endDate " + + "AND (iar.is_claimed = false OR iar.is_claimed IS NULL) " + + "GROUP BY iar.asha_id", + nativeQuery = true) + List getUnclaimedCountByAshaIds( + @Param("ashaIds") List ashaIds, + @Param("startDate") Timestamp startDate, + @Param("endDate") Timestamp endDate); + // Get facility details with geo names @Query(value = "SELECT DISTINCT f.FacilityID, f.FacilityName, " + "COALESCE(s.StateName,'') AS stateName, " diff --git a/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java b/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java index 899a7ffd..2b78b68f 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java @@ -18,10 +18,22 @@ public interface UserServiceRoleRepo extends JpaRepository getUserRole(@Param("userId") Integer userId); - @Query("select u.userId from UserServiceRole u where u.userName = :userName and u.userServciceRoleDeleted = false") + @Query(value = """ + SELECT UserID + FROM db_iemr.v_userservicerolemapping + WHERE UserName = :userName + AND UserServciceRoleDeleted = 0 + LIMIT 1 + """, nativeQuery = true) Integer getUserIdByName(@Param("userName") String userName); - @Query("select u.userName from UserServiceRole u where u.userId = :userId and u.userServciceRoleDeleted = false") - String getUserNamedByUserId(@Param("userId") Integer userId); + @Query(value = """ + SELECT UserName + FROM db_iemr.v_userservicerolemapping + WHERE UserID = :userId + AND UserServciceRoleDeleted = 0 + LIMIT 1 + """, nativeQuery = true) + String getUserNamedByUserId(@Param("userId") Integer userId); } diff --git a/src/main/java/com/iemr/flw/service/AbhaBeneficiaryService.java b/src/main/java/com/iemr/flw/service/AbhaBeneficiaryService.java new file mode 100644 index 00000000..02a1281b --- /dev/null +++ b/src/main/java/com/iemr/flw/service/AbhaBeneficiaryService.java @@ -0,0 +1,12 @@ +package com.iemr.flw.service; + +import com.iemr.flw.dto.abhaBeneficiary.AbhaBeneficiaryDTO; +import com.iemr.flw.dto.iemr.AbhaRequestDTO; +import org.springframework.stereotype.Service; + +import java.util.List; + +public interface AbhaBeneficiaryService { + + Object getBeneficiaryByAbha(AbhaRequestDTO request); +} diff --git a/src/main/java/com/iemr/flw/service/ChildCareService.java b/src/main/java/com/iemr/flw/service/ChildCareService.java index c272fd2f..c78de3fd 100644 --- a/src/main/java/com/iemr/flw/service/ChildCareService.java +++ b/src/main/java/com/iemr/flw/service/ChildCareService.java @@ -27,7 +27,7 @@ public interface ChildCareService { List getSamVisitsByBeneficiary(GetBenRequestHandler dto); - String saveOrsDistributionDetails(List orsDistributionDTOS,Integer userId); + String saveOrsDistributionDetails(List orsDistributionDTOS); List getOrdDistrubtion(GetBenRequestHandler request); diff --git a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java index 71c9229e..8becce19 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java @@ -20,7 +20,8 @@ public interface IncentiveLogicService { IncentiveActivityRecord incentiveForSecondChildGap(Long benId, Timestamp secondChildDob, Timestamp secondChildDob1, Integer userId); - IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); + IncentiveActivityRecord incentiveForEyeSurgeyReferGovtHospital(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); + IncentiveActivityRecord incentiveForEyeSurgeyReferPrivateHospital(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); IncentiveActivityRecord incentiveForMalariaFollowUp(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); @@ -29,4 +30,6 @@ public interface IncentiveLogicService { IncentiveActivityRecord incentiveForTbFollowUpIsDrTb(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); IncentiveActivityRecord incentiveForGiveingIFA(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); + + IncentiveActivityRecord incentiveForTbSuspected(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); } diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java new file mode 100644 index 00000000..15ca0e7c --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java @@ -0,0 +1,198 @@ +package com.iemr.flw.service.impl; + +import com.google.gson.Gson; +import com.iemr.flw.controller.AbhaBeneficiaryController; +import com.iemr.flw.domain.iemr.AbhaApiResponse; +import com.iemr.flw.dto.abhaBeneficiary.AbhaBeneficiaryDTO; +import com.iemr.flw.dto.iemr.AbhaRequestDTO; +import com.iemr.flw.repo.identity.BeneficiaryRepo; +import com.iemr.flw.repo.identity.HouseHoldRepo; +import com.iemr.flw.service.AbhaBeneficiaryService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Service +public class AbhaBeneficiaryServiceImpl implements AbhaBeneficiaryService { + + private final org.slf4j.Logger logger = LoggerFactory.getLogger(AbhaBeneficiaryService.class); + + + @Autowired + private BeneficiaryRepo beneficiaryRepo; + + + + @Value("${govthealth.user.details.url}") + private String getUserDetailsUrl; + + @Value("${govthealth.user.id}") + private String govthealthUserId; + + @Value("${govthealth.password}") + private String govthealthPassword; + + @Autowired + private HouseHoldRepo houseHoldRepo; + + @Override + public Object getBeneficiaryByAbha(AbhaRequestDTO request) { + + try { + Long benRedId = null; + BigInteger benDetailsdId = null; + String familyId =null; + if(request.getHouseHoldId()!=null){ + benRedId = beneficiaryRepo.findByHouseoldId(request.getHouseHoldId()).get(0).getBenRegId(); + if(benRedId!=null){ + benDetailsdId = beneficiaryRepo.findByBenRegIdFromMapping(BigInteger.valueOf(benRedId)).getBenDetailsId(); + + } + if(benDetailsdId!=null){ + familyId = beneficiaryRepo.findByBeneficiaryDetailsId(benDetailsdId).getFamilyId(); + + } + } + + Object[] benHealthIdNumber = beneficiaryRepo.getHealthIdNumber(request.getCardNo()); + if (benHealthIdNumber != null && benHealthIdNumber.length > 0) { + Object[] healthData = (Object[]) benHealthIdNumber[0]; + String healthIdNumber = healthData[0] != null ? healthData[0].toString() : null; + String healthId = healthData[1] != null ? healthData[1].toString() : null; + logger.info("healthIdNumber:"+healthIdNumber); + logger.info("healthId:"+healthId); + if (request.getCardNo().equals(healthIdNumber)) { + + Map response = new HashMap<>(); + response.put("statusCode", 5000); + response.put("message", + "This ABHA No already exists"); + + return response; + } + } + + AbhaApiResponse abhaApiResponse = + getAbhaResponse(request.getCardNo()).getBody(); + + if (abhaApiResponse == null || abhaApiResponse.getData() == null) { + + Map response = new HashMap<>(); + response.put("statusCode", 5001); + response.put("message", "No data found"); + + return response; + } + + + for (AbhaBeneficiaryDTO dto : abhaApiResponse.getData()) { + + // Check if ABHA already exists in system + benHealthIdNumber = beneficiaryRepo.getHealthIdNumber(dto.getAbhaId()); + if (benHealthIdNumber != null && benHealthIdNumber.length > 0) { + Object[] healthData = (Object[]) benHealthIdNumber[0]; + String healthIdNumber = healthData[0] != null ? healthData[0].toString() : null; + String healthId = healthData[1] != null ? healthData[1].toString() : null; + logger.info("healthIdNumber:"+healthIdNumber); + logger.info("healthId:"+healthId); + if (dto.getAbhaId().equals(healthIdNumber)) { + + Map response = new HashMap<>(); + response.put("statusCode", 5000); + response.put("message", + "Beneficiary is already exists"); + + return response; + } + } + if(familyId!=null){ + if(!dto.getFamilyid().toString().equals(familyId)){ + Map response = new HashMap<>(); + response.put("statusCode", 5000); + response.put("message", + "Beneficiary is not associated with this family."); + + return response; + } + } + + + + + // Split name into firstName and lastName + String personName = dto.getPersonName(); + + if (personName != null + && !personName.trim().isEmpty()) { + + String[] names = + personName.trim().split("\\s+", 2); + + dto.setFirstName(names[0]); + + if (names.length > 1) { + dto.setLastName(names[1]); + } else { + dto.setLastName(""); + } + } + } + + + logger.info("ABHA Response Status : {}", + abhaApiResponse.getStatusCode()); + + logger.info("ABHA Response : {}", + new Gson().toJson(abhaApiResponse)); + + return abhaApiResponse; + + } catch (Exception e) { + + logger.error("Error while fetching beneficiary by ABHA", e); + + Map response = new HashMap<>(); + response.put("statusCode", 5000); + response.put("message", "Internal Server Error"); + + return response; + } + } + + public ResponseEntity getAbhaResponse(String requestId) { + RestTemplate restTemplate = new RestTemplate(); + + Map body = new HashMap<>(); + body.put("userId",govthealthUserId); + body.put("password", govthealthPassword); + body.put("cardNo", requestId); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + HttpEntity request = new HttpEntity<>(body, headers); + + ResponseEntity response = restTemplate.exchange( + getUserDetailsUrl, + HttpMethod.POST, + request, + AbhaApiResponse.class + ); + + System.out.println("Status = " + response.getStatusCode()); + System.out.println("Body = " + response.getBody()); + + return response; + } + +} diff --git a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java index 5c4e1a71..23c4bd60 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -23,6 +23,7 @@ import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.IncentiveLogicService; +import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -95,7 +96,7 @@ public class BeneficiaryServiceImpl implements BeneficiaryService { private JwtUtil jwtUtil; @Autowired - private UserServiceRoleRepo userRepo; + private UserService userService; @Autowired private IncentiveLogicService incentiveLogicService; @@ -103,7 +104,6 @@ public class BeneficiaryServiceImpl implements BeneficiaryService { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - @Override public String getBenData(GetBenRequestHandler request, String authorisation) throws Exception { @@ -177,274 +177,291 @@ private String getMappingsForAddressIDs(List addressLi for (RMNCHMBeneficiaryaddress a : addressList) { // exception by-passing try { - RMNCHMBeneficiarymapping m = beneficiaryRepo.getByAddressID(a.getId()); - if (m != null) { - benHouseHoldRMNCH_ROBJ = new RMNCHHouseHoldDetails(); - benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); - benBotnBirthRMNCH_ROBJ = new RMNCHBornBirthDetails(); - - benDetailsOBJ = new RMNCHMBeneficiarydetail(); - benAccountOBJ = new RMNCHMBeneficiaryAccount(); - benImageOBJ = new RMNCHMBeneficiaryImage(); - benAddressOBJ = new RMNCHMBeneficiaryaddress(); - benContactOBJ = new RMNCHMBeneficiarycontact(); - Map healthDetails = getBenHealthDetails(m.getBenRegId()); - if (m.getBenDetailsId() != null) { - benDetailsOBJ = beneficiaryRepo.getDetailsById(m.getBenDetailsId()); - } - if (m.getBenAccountID() != null) { - benAccountOBJ = beneficiaryRepo.getAccountById(m.getBenAccountID()); - } - if (m.getBenImageId() != null) { - benImageOBJ = beneficiaryRepo.getImageById(m.getBenImageId().longValue()); - } - if (m.getBenAddressId() != null) { - benAddressOBJ = beneficiaryRepo.getAddressById(m.getBenAddressId()); - } - if (m.getBenContactsId() != null) { - benContactOBJ = beneficiaryRepo.getContactById(m.getBenContactsId()); - } + if(!beneficiaryRepo.getByAddressID(a.getId()).isEmpty()){ + RMNCHMBeneficiarymapping m = beneficiaryRepo.getByAddressID(a.getId()).get(0); + if (m != null) { + benHouseHoldRMNCH_ROBJ = new RMNCHHouseHoldDetails(); + benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); + benBotnBirthRMNCH_ROBJ = new RMNCHBornBirthDetails(); + + benDetailsOBJ = new RMNCHMBeneficiarydetail(); + benAccountOBJ = new RMNCHMBeneficiaryAccount(); + benImageOBJ = new RMNCHMBeneficiaryImage(); + benAddressOBJ = new RMNCHMBeneficiaryaddress(); + benContactOBJ = new RMNCHMBeneficiarycontact(); + Map healthDetails = getBenHealthDetails(m.getBenRegId()); + if (m.getBenDetailsId() != null) { + benDetailsOBJ = beneficiaryRepo.getDetailsById(m.getBenDetailsId()); + } + if (m.getBenAccountID() != null) { + benAccountOBJ = beneficiaryRepo.getAccountById(m.getBenAccountID()); + } + if (m.getBenImageId() != null) { + benImageOBJ = beneficiaryRepo.getImageById(m.getBenImageId().longValue()); + } + if (m.getBenAddressId() != null) { + benAddressOBJ = beneficiaryRepo.getAddressById(m.getBenAddressId()); + } + if (m.getBenContactsId() != null) { + benContactOBJ = beneficiaryRepo.getContactById(m.getBenContactsId()); + } - BigInteger benID = null; - if (m.getBenRegId() != null) - benID = beneficiaryRepo.getBenIdFromRegID(m.getBenRegId().longValue()); + BigInteger benID = null; + if (m.getBenRegId() != null) + benID = beneficiaryRepo.getBenIdFromRegID(m.getBenRegId().longValue()); - if (m.getBenRegId() != null) { - benDetailsRMNCH_OBJ = beneficiaryRepo - .getDetailsByRegID((m.getBenRegId()).longValue()); - benBotnBirthRMNCH_ROBJ = beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()); + if (m.getBenRegId() != null) { + if(!beneficiaryRepo + .getDetailsByRegID((m.getBenRegId()).longValue()).isEmpty()){ + benDetailsRMNCH_OBJ = beneficiaryRepo + .getDetailsByRegID((m.getBenRegId()).longValue()).get(0); - if (benDetailsRMNCH_OBJ != null && benDetailsRMNCH_OBJ.getHouseoldId() != null) - benHouseHoldRMNCH_ROBJ = houseHoldRepo - .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()); + } + benBotnBirthRMNCH_ROBJ = beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()); - } - if (benDetailsRMNCH_OBJ == null) - benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); - // new mapping 30-06-2021 - if (benDetailsOBJ.getMotherName() != null) - benDetailsRMNCH_OBJ.setMotherName(benDetailsOBJ.getMotherName()); - if (benDetailsOBJ.getLiteracyStatus() != null) - benDetailsRMNCH_OBJ.setLiteracyStatus(benDetailsOBJ.getLiteracyStatus()); - - // bank - if (benAccountOBJ.getNameOfBank() != null) - benDetailsRMNCH_OBJ.setNameOfBank(benAccountOBJ.getNameOfBank()); - if (benAccountOBJ.getBranchName() != null) - benDetailsRMNCH_OBJ.setBranchName(benAccountOBJ.getBranchName()); - if (benAccountOBJ.getIfscCode() != null) - benDetailsRMNCH_OBJ.setIfscCode(benAccountOBJ.getIfscCode()); - if (benAccountOBJ.getBankAccount() != null) - benDetailsRMNCH_OBJ.setBankAccount(benAccountOBJ.getBankAccount()); - - // location - if (benAddressOBJ.getCountyid() != null) - benDetailsRMNCH_OBJ.setCountryId(benAddressOBJ.getCountyid()); - if (benAddressOBJ.getPermCountry() != null) - benDetailsRMNCH_OBJ.setCountryName(benAddressOBJ.getPermCountry()); - - if (benAddressOBJ.getStatePerm() != null) - benDetailsRMNCH_OBJ.setStateId(benAddressOBJ.getStatePerm()); - if (benAddressOBJ.getPermState() != null) - benDetailsRMNCH_OBJ.setStateName(benAddressOBJ.getPermState()); - - if (benAddressOBJ.getDistrictidPerm() != null) { - benDetailsRMNCH_OBJ.setDistrictid(benAddressOBJ.getDistrictidPerm()); + if (benDetailsRMNCH_OBJ != null && benDetailsRMNCH_OBJ.getHouseoldId() != null) + if(!houseHoldRepo + .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()).isEmpty()){ + benHouseHoldRMNCH_ROBJ = houseHoldRepo + .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()).get(0); + } - } - if (benAddressOBJ.getDistrictnamePerm() != null) { - benDetailsRMNCH_OBJ.setDistrictname(benAddressOBJ.getDistrictnamePerm()); - } + } + if (benDetailsRMNCH_OBJ == null) + benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); + + // new mapping 30-06-2021 + if (benDetailsOBJ.getMotherName() != null) + benDetailsRMNCH_OBJ.setMotherName(benDetailsOBJ.getMotherName()); + if (benDetailsOBJ.getLiteracyStatus() != null) + benDetailsRMNCH_OBJ.setLiteracyStatus(benDetailsOBJ.getLiteracyStatus()); + + // bank + if (benAccountOBJ.getNameOfBank() != null) + benDetailsRMNCH_OBJ.setNameOfBank(benAccountOBJ.getNameOfBank()); + if (benAccountOBJ.getBranchName() != null) + benDetailsRMNCH_OBJ.setBranchName(benAccountOBJ.getBranchName()); + if (benAccountOBJ.getIfscCode() != null) + benDetailsRMNCH_OBJ.setIfscCode(benAccountOBJ.getIfscCode()); + if (benAccountOBJ.getBankAccount() != null) + benDetailsRMNCH_OBJ.setBankAccount(benAccountOBJ.getBankAccount()); + + // location + if (benAddressOBJ.getCountyid() != null) + benDetailsRMNCH_OBJ.setCountryId(benAddressOBJ.getCountyid()); + if (benAddressOBJ.getPermCountry() != null) + benDetailsRMNCH_OBJ.setCountryName(benAddressOBJ.getPermCountry()); + + if (benAddressOBJ.getStatePerm() != null) + benDetailsRMNCH_OBJ.setStateId(benAddressOBJ.getStatePerm()); + if (benAddressOBJ.getPermState() != null) + benDetailsRMNCH_OBJ.setStateName(benAddressOBJ.getPermState()); + + if (benAddressOBJ.getDistrictidPerm() != null) { + benDetailsRMNCH_OBJ.setDistrictid(benAddressOBJ.getDistrictidPerm()); - if (benAddressOBJ.getPermSubDistrictId() != null) - benDetailsRMNCH_OBJ.setBlockId(benAddressOBJ.getPermSubDistrictId()); - if (benAddressOBJ.getPermSubDistrict() != null) - benDetailsRMNCH_OBJ.setBlockName(benAddressOBJ.getPermSubDistrict()); - - if (benAddressOBJ.getVillageidPerm() != null) - benDetailsRMNCH_OBJ.setVillageId(benAddressOBJ.getVillageidPerm()); - if (benAddressOBJ.getVillagenamePerm() != null) - benDetailsRMNCH_OBJ.setVillageName(benAddressOBJ.getVillagenamePerm()); - - if (benAddressOBJ.getPermServicePointId() != null) - benDetailsRMNCH_OBJ.setServicePointID(benAddressOBJ.getPermServicePointId()); - if (benAddressOBJ.getPermServicePoint() != null) - benDetailsRMNCH_OBJ.setServicePointName(benAddressOBJ.getPermServicePoint()); - - if (benAddressOBJ.getPermZoneID() != null) - benDetailsRMNCH_OBJ.setZoneID(benAddressOBJ.getPermZoneID()); - if (benAddressOBJ.getPermZone() != null) - benDetailsRMNCH_OBJ.setZoneName(benAddressOBJ.getPermZone()); - - if (benAddressOBJ.getPermAddrLine1() != null) - benDetailsRMNCH_OBJ.setAddressLine1(benAddressOBJ.getPermAddrLine1()); - if (benAddressOBJ.getPermAddrLine2() != null) - benDetailsRMNCH_OBJ.setAddressLine2(benAddressOBJ.getPermAddrLine2()); - if (benAddressOBJ.getPermAddrLine3() != null) - benDetailsRMNCH_OBJ.setAddressLine3(benAddressOBJ.getPermAddrLine3()); - - // ----------------------------------------------------------------------------- - - // related benids - if (benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB() != null) { - - String[] relatedBenIDsString = benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB().split(","); - Long[] relatedBenIDs = new Long[relatedBenIDsString.length]; - int pointer = 0; - for (String s : relatedBenIDsString) { - relatedBenIDs[pointer] = Long.valueOf(s); - pointer++; } + if (benAddressOBJ.getDistrictnamePerm() != null) { + benDetailsRMNCH_OBJ.setDistrictname(benAddressOBJ.getDistrictnamePerm()); - benDetailsRMNCH_OBJ.setRelatedBeneficiaryIds(relatedBenIDs); - } - // ------------------------------------------------------------------------------ - - if (benDetailsOBJ.getCommunity() != null) - benDetailsRMNCH_OBJ.setCommunity(benDetailsOBJ.getCommunity()); - if (benDetailsOBJ.getCommunityId() != null) - benDetailsRMNCH_OBJ.setCommunityId(benDetailsOBJ.getCommunityId()); - if (benContactOBJ.getPreferredPhoneNum() != null) - benDetailsRMNCH_OBJ.setContact_number(benContactOBJ.getPreferredPhoneNum()); - - if (benDetailsOBJ.getDob() != null) - benDetailsRMNCH_OBJ.setDob(benDetailsOBJ.getDob()); - if (benDetailsOBJ.getFatherName() != null) - benDetailsRMNCH_OBJ.setFatherName(benDetailsOBJ.getFatherName()); - if (benDetailsOBJ.getFirstName() != null) - benDetailsRMNCH_OBJ.setFirstName(benDetailsOBJ.getFirstName()); - if (benDetailsOBJ.getGender() != null) - benDetailsRMNCH_OBJ.setGender(benDetailsOBJ.getGender()); - if (benDetailsOBJ.getGenderId() != null) - benDetailsRMNCH_OBJ.setGenderId(benDetailsOBJ.getGenderId()); - - if (benDetailsOBJ.getMaritalstatus() != null) - benDetailsRMNCH_OBJ.setMaritalstatus(benDetailsOBJ.getMaritalstatus()); - if (benDetailsOBJ.getMaritalstatusId() != null) - benDetailsRMNCH_OBJ.setMaritalstatusId(benDetailsOBJ.getMaritalstatusId()); - if (benDetailsOBJ.getMarriageDate() != null) - benDetailsRMNCH_OBJ.setMarriageDate(benDetailsOBJ.getMarriageDate()); - - if (benDetailsOBJ.getReligion() != null) - benDetailsRMNCH_OBJ.setReligion(benDetailsOBJ.getReligion()); - if (benDetailsOBJ.getReligionID() != null) - benDetailsRMNCH_OBJ.setReligionID(benDetailsOBJ.getReligionID()); - if (benDetailsOBJ.getSpousename() != null) - benDetailsRMNCH_OBJ.setSpousename(benDetailsOBJ.getSpousename()); - - if (benImageOBJ != null && benImageOBJ.getUser_image() != null) - benDetailsRMNCH_OBJ.setUser_image(benImageOBJ.getUser_image()); - - // new fields + } + + if (benAddressOBJ.getPermSubDistrictId() != null) + benDetailsRMNCH_OBJ.setBlockId(benAddressOBJ.getPermSubDistrictId()); + if (benAddressOBJ.getPermSubDistrict() != null) + benDetailsRMNCH_OBJ.setBlockName(benAddressOBJ.getPermSubDistrict()); + + if (benAddressOBJ.getVillageidPerm() != null) + benDetailsRMNCH_OBJ.setVillageId(benAddressOBJ.getVillageidPerm()); + if (benAddressOBJ.getVillagenamePerm() != null) + benDetailsRMNCH_OBJ.setVillageName(benAddressOBJ.getVillagenamePerm()); + + if (benAddressOBJ.getPermServicePointId() != null) + benDetailsRMNCH_OBJ.setServicePointID(benAddressOBJ.getPermServicePointId()); + if (benAddressOBJ.getPermServicePoint() != null) + benDetailsRMNCH_OBJ.setServicePointName(benAddressOBJ.getPermServicePoint()); + + if (benAddressOBJ.getPermZoneID() != null) + benDetailsRMNCH_OBJ.setZoneID(benAddressOBJ.getPermZoneID()); + if (benAddressOBJ.getPermZone() != null) + benDetailsRMNCH_OBJ.setZoneName(benAddressOBJ.getPermZone()); + + if (benAddressOBJ.getPermAddrLine1() != null) + benDetailsRMNCH_OBJ.setAddressLine1(benAddressOBJ.getPermAddrLine1()); + if (benAddressOBJ.getPermAddrLine2() != null) + benDetailsRMNCH_OBJ.setAddressLine2(benAddressOBJ.getPermAddrLine2()); + if (benAddressOBJ.getPermAddrLine3() != null) + benDetailsRMNCH_OBJ.setAddressLine3(benAddressOBJ.getPermAddrLine3()); + + // ----------------------------------------------------------------------------- + + // related benids + if (benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB() != null) { + + String[] relatedBenIDsString = benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB().split(","); + Long[] relatedBenIDs = new Long[relatedBenIDsString.length]; + int pointer = 0; + for (String s : relatedBenIDsString) { + relatedBenIDs[pointer] = Long.valueOf(s); + pointer++; + } + + benDetailsRMNCH_OBJ.setRelatedBeneficiaryIds(relatedBenIDs); + } + // ------------------------------------------------------------------------------ + + if (benDetailsOBJ.getCommunity() != null) + benDetailsRMNCH_OBJ.setCommunity(benDetailsOBJ.getCommunity()); + if (benDetailsOBJ.getCommunityId() != null) + benDetailsRMNCH_OBJ.setCommunityId(benDetailsOBJ.getCommunityId()); + if (benContactOBJ.getPreferredPhoneNum() != null) + benDetailsRMNCH_OBJ.setContact_number(benContactOBJ.getPreferredPhoneNum()); + + if (benDetailsOBJ.getDob() != null) + benDetailsRMNCH_OBJ.setDob(benDetailsOBJ.getDob()); + if (benDetailsOBJ.getFatherName() != null) + benDetailsRMNCH_OBJ.setFatherName(benDetailsOBJ.getFatherName()); + if (benDetailsOBJ.getFirstName() != null) + benDetailsRMNCH_OBJ.setFirstName(benDetailsOBJ.getFirstName()); + if (benDetailsOBJ.getGender() != null) + benDetailsRMNCH_OBJ.setGender(benDetailsOBJ.getGender()); + if (benDetailsOBJ.getGenderId() != null) + benDetailsRMNCH_OBJ.setGenderId(benDetailsOBJ.getGenderId()); + + if (benDetailsOBJ.getMaritalstatus() != null) + benDetailsRMNCH_OBJ.setMaritalstatus(benDetailsOBJ.getMaritalstatus()); + if (benDetailsOBJ.getMaritalstatusId() != null) + benDetailsRMNCH_OBJ.setMaritalstatusId(benDetailsOBJ.getMaritalstatusId()); + if (benDetailsOBJ.getMarriageDate() != null) + benDetailsRMNCH_OBJ.setMarriageDate(benDetailsOBJ.getMarriageDate()); + + if (benDetailsOBJ.getReligion() != null) + benDetailsRMNCH_OBJ.setReligion(benDetailsOBJ.getReligion()); + if (benDetailsOBJ.getReligionID() != null) + benDetailsRMNCH_OBJ.setReligionID(benDetailsOBJ.getReligionID()); + if (benDetailsOBJ.getSpousename() != null) + benDetailsRMNCH_OBJ.setSpousename(benDetailsOBJ.getSpousename()); + + if (benImageOBJ != null && benImageOBJ.getUser_image() != null) + benDetailsRMNCH_OBJ.setUser_image(benImageOBJ.getUser_image()); + + // new fields // benDetailsRMNCH_OBJ.setRegistrationDate(benDetailsOBJ.getCreatedDate()); - if (benID != null) - benDetailsRMNCH_OBJ.setBenficieryid(benID.longValue()); - - if (benDetailsOBJ.getLastName() != null) - benDetailsRMNCH_OBJ.setLastName(benDetailsOBJ.getLastName()); - - if (benDetailsRMNCH_OBJ.getCreatedBy() == null) - if (benDetailsOBJ.getCreatedBy() != null) - benDetailsRMNCH_OBJ.setCreatedBy(benDetailsOBJ.getCreatedBy()); - - // age calculation - String ageDetails = ""; - int age_val = 0; - String ageUnit = null; - if (benDetailsOBJ.getDob() != null) { - - Date date = new Date(benDetailsOBJ.getDob().getTime()); - Calendar cal = Calendar.getInstance(); - - cal.setTime(date); - - int year = cal.get(Calendar.YEAR); - int month = cal.get(Calendar.MONTH) + 1; - int day = cal.get(Calendar.DAY_OF_MONTH); - - java.time.LocalDate todayDate = java.time.LocalDate.now(); - java.time.LocalDate birthdate = java.time.LocalDate.of(year, month, day); - Period p = Period.between(birthdate, todayDate); - - int d = p.getDays(); - int mo = p.getMonths(); - int y = p.getYears(); - - if (y > 0) { - ageDetails = y + " years - " + mo + " months"; - age_val = y; - ageUnit = (age_val > 1) ? "Years" : "Year"; - } else { - if (mo > 0) { - ageDetails = mo + " months - " + d + " days"; - age_val = mo; - ageUnit = (age_val > 1) ? "Months" : "Month"; + if (benID != null) + benDetailsRMNCH_OBJ.setBenficieryid(benID.longValue()); + + if (benDetailsOBJ.getLastName() != null) + benDetailsRMNCH_OBJ.setLastName(benDetailsOBJ.getLastName()); + + if (benDetailsRMNCH_OBJ.getCreatedBy() == null) + if (benDetailsOBJ.getCreatedBy() != null) + benDetailsRMNCH_OBJ.setCreatedBy(benDetailsOBJ.getCreatedBy()); + + // age calculation + String ageDetails = ""; + int age_val = 0; + String ageUnit = null; + if (benDetailsOBJ.getDob() != null) { + + Date date = new Date(benDetailsOBJ.getDob().getTime()); + Calendar cal = Calendar.getInstance(); + + cal.setTime(date); + + int year = cal.get(Calendar.YEAR); + int month = cal.get(Calendar.MONTH) + 1; + int day = cal.get(Calendar.DAY_OF_MONTH); + + java.time.LocalDate todayDate = java.time.LocalDate.now(); + java.time.LocalDate birthdate = java.time.LocalDate.of(year, month, day); + Period p = Period.between(birthdate, todayDate); + + int d = p.getDays(); + int mo = p.getMonths(); + int y = p.getYears(); + + if (y > 0) { + ageDetails = y + " years - " + mo + " months"; + age_val = y; + ageUnit = (age_val > 1) ? "Years" : "Year"; } else { - ageDetails = d + " days"; - age_val = d; - ageUnit = (age_val > 1) ? "Days" : "Day"; + if (mo > 0) { + ageDetails = mo + " months - " + d + " days"; + age_val = mo; + ageUnit = (age_val > 1) ? "Months" : "Month"; + } else { + ageDetails = d + " days"; + age_val = d; + ageUnit = (age_val > 1) ? "Days" : "Day"; + } } - } - } + } - benDetailsRMNCH_OBJ.setAgeFull(ageDetails); - benDetailsRMNCH_OBJ.setAge(age_val); - if (ageUnit != null) - benDetailsRMNCH_OBJ.setAge_unit(ageUnit); - - resultMap = new HashMap<>(); - if (benHouseHoldRMNCH_ROBJ != null) - resultMap.put("householdDetails", benHouseHoldRMNCH_ROBJ); - else - resultMap.put("householdDetails", new HashMap()); - - if (benBotnBirthRMNCH_ROBJ != null) - resultMap.put("bornbirthDeatils", benBotnBirthRMNCH_ROBJ); - else - resultMap.put("bornbirthDeatils", new HashMap()); - - resultMap.put("beneficiaryDetails", benDetailsRMNCH_OBJ); - resultMap.put("abhaHealthDetails", healthDetails); - resultMap.put("houseoldId", benDetailsRMNCH_OBJ.getHouseoldId()); - resultMap.put("benficieryid", benDetailsRMNCH_OBJ.getBenficieryid()); - resultMap.put("isDeath", benDetailsRMNCH_OBJ.getIsDeath()); - resultMap.put("isDeathValue", benDetailsRMNCH_OBJ.getIsDeathValue()); - resultMap.put("dateOfDeath",benDetailsRMNCH_OBJ.getDateOfDeath()); - resultMap.put("timeOfDeath", benDetailsRMNCH_OBJ.getTimeOfDeath()); - resultMap.put("reasonOfDeath", benDetailsRMNCH_OBJ.getReasonOfDeath()); - resultMap.put("reasonOfDeathId", benDetailsRMNCH_OBJ.getReasonOfDeathId()); - resultMap.put("placeOfDeath", benDetailsRMNCH_OBJ.getPlaceOfDeath()); - resultMap.put("placeOfDeathId", benDetailsRMNCH_OBJ.getPlaceOfDeathId()); - resultMap.put("isSpouseAdded", benDetailsRMNCH_OBJ.getIsSpouseAdded()); - resultMap.put("isChildrenAdded", benDetailsRMNCH_OBJ.getIsChildrenAdded()); - resultMap.put("noOfchildren", benDetailsRMNCH_OBJ.getNoOfchildren()); - resultMap.put("isMarried", benDetailsRMNCH_OBJ.getIsMarried()); - resultMap.put("doYouHavechildren", benDetailsRMNCH_OBJ.getDoYouHavechildren()); - resultMap.put("noofAlivechildren",benDetailsRMNCH_OBJ.getNoofAlivechildren()); - resultMap.put("isDeactivate",benDetailsRMNCH_OBJ.getIsDeactivate()); - resultMap.put("BenRegId", m.getBenRegId()); - - // adding asha id / created by - user id - if (benAddressOBJ.getCreatedBy() != null) { - Integer userID = beneficiaryRepo.getUserIDByUserName(benAddressOBJ.getCreatedBy()); - if (userID != null && userID > 0) - resultMap.put("ashaId", userID); - } - // get HealthID of ben - if (m.getBenRegId() != null) { - fetchHealthIdByBenRegID(m.getBenRegId().longValue(), authorisation, resultMap); - } + benDetailsRMNCH_OBJ.setAgeFull(ageDetails); + benDetailsRMNCH_OBJ.setAge(age_val); + if (ageUnit != null) + benDetailsRMNCH_OBJ.setAge_unit(ageUnit); + + resultMap = new HashMap<>(); + if (benHouseHoldRMNCH_ROBJ != null) + resultMap.put("householdDetails", benHouseHoldRMNCH_ROBJ); + else + resultMap.put("householdDetails", new HashMap()); + + if (benBotnBirthRMNCH_ROBJ != null) + resultMap.put("bornbirthDeatils", benBotnBirthRMNCH_ROBJ); + else + resultMap.put("bornbirthDeatils", new HashMap()); + + resultMap.put("beneficiaryDetails", benDetailsRMNCH_OBJ); + resultMap.put("abhaHealthDetails", healthDetails); + resultMap.put("houseoldId", benDetailsRMNCH_OBJ.getHouseoldId()); + resultMap.put("benficieryid", benDetailsRMNCH_OBJ.getBenficieryid()); + resultMap.put("isDeath", benDetailsRMNCH_OBJ.getIsDeath()); + resultMap.put("isDeathValue", benDetailsRMNCH_OBJ.getIsDeathValue()); + resultMap.put("dateOfDeath",benDetailsRMNCH_OBJ.getDateOfDeath()); + resultMap.put("timeOfDeath", benDetailsRMNCH_OBJ.getTimeOfDeath()); + resultMap.put("reasonOfDeath", benDetailsRMNCH_OBJ.getReasonOfDeath()); + resultMap.put("reasonOfDeathId", benDetailsRMNCH_OBJ.getReasonOfDeathId()); + resultMap.put("placeOfDeath", benDetailsRMNCH_OBJ.getPlaceOfDeath()); + resultMap.put("placeOfDeathId", benDetailsRMNCH_OBJ.getPlaceOfDeathId()); + resultMap.put("isSpouseAdded", benDetailsRMNCH_OBJ.getIsSpouseAdded()); + resultMap.put("isChildrenAdded", benDetailsRMNCH_OBJ.getIsChildrenAdded()); + resultMap.put("noOfchildren", benDetailsRMNCH_OBJ.getNoOfchildren()); + resultMap.put("isMarried", benDetailsRMNCH_OBJ.getIsMarried()); + resultMap.put("doYouHavechildren", benDetailsRMNCH_OBJ.getDoYouHavechildren()); + resultMap.put("noofAlivechildren",benDetailsRMNCH_OBJ.getNoofAlivechildren()); + resultMap.put("isDeactivate", benDetailsRMNCH_OBJ.getIsDeactivate() != null + ? benDetailsRMNCH_OBJ.getIsDeactivate() + : false + ); + resultMap.put("BenRegId", m.getBenRegId()); + + // adding asha id / created by - user id + if (benAddressOBJ.getCreatedBy() != null) { + Integer userID = beneficiaryRepo.getUserIDByUserName(benAddressOBJ.getCreatedBy()); + if (userID != null && userID > 0) + resultMap.put("ashaId", userID); + } + // get HealthID of ben + if (m.getBenRegId() != null) { + fetchHealthIdByBenRegID(m.getBenRegId().longValue(), authorisation, resultMap); + } - resultList.add(resultMap); + resultList.add(resultMap); - } else { - // mapping not available + } else { + // mapping not available + } } + } catch (Exception e) { - logger.error("error for addressID :"+e.getMessage() + a.getId() + " and vanID : " + a.getVanID()); + logger.info("Error for ben :"+e.getMessage()); + logger.info("Error for ben :"+e); + logger.error("error for addressID :" + e.getMessage() + a.getId() + " and vanID : " + a.getVanID()); } } @@ -570,12 +587,22 @@ public String saveEyeCheckupVsit(List eyeCheckupRequestDTO visit.setFollowUpStatus(f.getFollow_up_status()); eyeCheckUpVisitRepo.save(visit); - if(visit.getReferredTo().equals("Govt Public Facility")){ - LocalDate localDate = visit.getVisitDate(); + if (visit.getReferredTo() != null) { + if (visit.getReferredTo().equals("Govt Public Facility")) { + LocalDate localDate = visit.getVisitDate(); - Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); - incentiveLogicService.incentiveForEyeSurgeyRefer(visit.getBeneficiaryId(),visitDate,visitDate,visit.getUserId()); + Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); + incentiveLogicService.incentiveForEyeSurgeyReferGovtHospital(visit.getBeneficiaryId(), visitDate, visitDate, visit.getUserId()); + } + + if (visit.getReferredTo().equals("Private Facility")) { + LocalDate localDate = visit.getVisitDate(); + + Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); + incentiveLogicService.incentiveForEyeSurgeyReferPrivateHospital(visit.getBeneficiaryId(), visitDate, visitDate, visit.getUserId()); + } } + } return "Eye checkup data saved successfully."; @@ -594,7 +621,7 @@ public String saveEyeCheckupVsit(List eyeCheckupRequestDTO public List getEyeCheckUpVisit(GetBenRequestHandler request,String token) { String createdBy = null; try { - createdBy = userRepo.getUserNamedByUserId(jwtUtil.extractUserId(token)); + createdBy = userService.getUserDetail(jwtUtil.extractUserId(token)).getUserName(); } catch (Exception e) { logger.error("Error extracting userId from token: " + e.getMessage()); } @@ -620,6 +647,22 @@ public List getEyeCheckUpVisit(GetBenRequestHandler reques dto.setFields(fields); + if (v.getReferredTo() != null) { + if (v.getReferredTo().equals("Govt Public Facility")) { + LocalDate localDate = v.getVisitDate(); + + Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); + incentiveLogicService.incentiveForEyeSurgeyReferGovtHospital(v.getBeneficiaryId(), visitDate, visitDate, v.getUserId()); + } + + if (v.getReferredTo().equals("Private Facility")) { + LocalDate localDate = v.getVisitDate(); + + Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); + incentiveLogicService.incentiveForEyeSurgeyReferPrivateHospital(v.getBeneficiaryId(), visitDate, visitDate, v.getUserId()); + } + } + return dto; }).collect(Collectors.toList()); } diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 60306e0b..1d1988d4 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -190,18 +190,18 @@ public List savePolioCampaign(List polioCa if (!campaignPolioRequest.isEmpty()) { List savedCampaigns = pulsePolioCampaignRepo.saveAll(campaignPolioRequest); - savedCampaigns.forEach(pulsePolioCampaign -> { - checkMonthlyPulsePolioIncentive(pulsePolioCampaign.getUserId(),pulsePolioCampaign.getStartDate(),pulsePolioCampaign.getEndDate()); + savedCampaigns.forEach(this::checkIncentiveForPulsePolio); - });{ - - } return savedCampaigns; } throw new IEMRException("No valid campaign data to save"); } + private void checkIncentiveForPulsePolio(PulsePolioCampaign pulsePolioCampaign){ + checkMonthlyPulsePolioIncentive(pulsePolioCampaign.getUserId(),pulsePolioCampaign.getStartDate(),pulsePolioCampaign.getEndDate()); + + } @Override @Transactional @@ -307,6 +307,7 @@ public List getPolioCampaign(String token) throws IEMR for (PulsePolioCampaign campaignOrs : campaignPolioPage.getContent()) { PolioCampaignResponseDTO dto = convertPolioToDTO(campaignOrs); polioCampaignDTOSResponse.add(dto); + } page++; } while (campaignPolioPage.hasNext()); diff --git a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java index 9479191a..aa45f30d 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; import com.iemr.flw.domain.iemr.*; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; @@ -88,12 +89,18 @@ public class ChildCareServiceImpl implements ChildCareService { @Autowired private IncentiveLogicService incentiveLogicService; + @Autowired + private ANCVisitRepo ancVisitRepo; + @Autowired + private PNCVisitRepo pncVisitRepo; + @Override public String registerHBYC(List hbycDTOs) { try { List hbycList = new ArrayList<>(); + hbycDTOs.forEach(it -> { HbycDTO hbycDTO = it.getFields(); hbycDTO.setVisit_date(it.getVisitDate()); @@ -102,14 +109,11 @@ public String registerHBYC(List hbycDTOs) { if (hbyc != null) { Long id = hbyc.getId(); - modelMapper.map(it, hbycDTO); hbyc.setId(id); hbyc.setUserId(userRepo.getUserIdByName(it.getUserName())); hbyc.setCreated_by(it.getUserName()); } else { hbyc = new HbycChildVisit(); - modelMapper.map(it, hbycDTO); - hbyc.setId(null); hbyc.setUserId(userRepo.getUserIdByName(it.getUserName())); hbyc.setCreated_by(it.getUserName()); hbyc.setBeneficiaryId(it.getBeneficiaryId()); @@ -146,14 +150,17 @@ public String registerHBYC(List hbycDTOs) { hbyc.setMcp_card_images(hbycDTO.getMcp_card_images()); } + hbycList.add(hbyc); }); hbycRepo.saveAll(hbycList); + logger.info("Total records to save : {}", hbycList.size()); checkAndAddHbyncIncentives(hbycList); return "no of hbyc details saved: " + hbycDTOs.size(); } catch (Exception e) { - logger.info("error while saving hbyc details: " + e.getMessage()); + logger.error("error while saving hbyc details", e); + } return null; } @@ -261,7 +268,10 @@ public List getHBNCDetails(GetBenRequestHandler dto) { responseDTO.setFields(fields); result.add(responseDTO); + } + checkAndAddHbncIncentives(hbncVisits, dto.getAshaId()); + } catch (Exception e) { logger.error("Error in getHBNCDetails: ", e); @@ -283,8 +293,8 @@ private String convert(Boolean value) { } private Boolean convertBollen(String value) { - if (value.equals("Yes")) { - return true; + if (value != null && !value.isEmpty()) { + return value.equalsIgnoreCase("Yes"); } else { return false; } @@ -353,11 +363,13 @@ public List getChildVaccinationDetails(GetBenRequestHandler List result = new ArrayList<>(); vaccinationDetails.forEach(childVaccination -> { ChildVaccinationDTO vaccinationDTO = mapper.convertValue(childVaccination, ChildVaccinationDTO.class); - BigInteger benId = beneficiaryRepo.getBenIdFromRegID(childVaccination.getBeneficiaryRegId()); - vaccinationDTO.setBeneficiaryId(benId.longValue()); + if(childVaccination.getBeneficiaryRegId()!=null){ + BigInteger benId = beneficiaryRepo.getBenIdFromRegID(childVaccination.getBeneficiaryRegId()); + vaccinationDTO.setBeneficiaryId(benId.longValue()); + + } result.add(vaccinationDTO); - checkAndAddIncentives(vaccinationDetails); }); return result; } catch (Exception e) { @@ -448,7 +460,7 @@ public List getAllChildVaccines(String category) { } @Override - public String saveSamDetails(List samRequest,Integer userId,String userName) { + public String saveSamDetails(List samRequest, Integer userId, String userName) { try { List vaccinationList = new ArrayList<>(); @@ -501,7 +513,7 @@ public String saveSamDetails(List samRequest,Integer userId,String userN samVisitRepository.saveAll(vaccinationList); // ✅ Handle incentive logic - checkAndAddSamVisitNRCReferalIncentive(vaccinationList,userId); + checkAndAddSamVisitNRCReferalIncentive(vaccinationList, userId); return "Saved/Updated " + samRequest.size() + " SAM visit records successfully"; } catch (Exception e) { @@ -541,8 +553,10 @@ public List getSamVisitsByBeneficiary(GetBenRequestHandler reque // ✅ Final Visit Label dto.setVisitLabel("Visit-" + visitNo); - - dto.setMuac(Double.parseDouble(entity.getMuac())); + String muacVal = entity.getMuac(); + dto.setMuac((muacVal != null && !muacVal.trim().isEmpty()) + ? Double.parseDouble(muacVal.trim()) + : 0.0); dto.setWeightForHeightStatus(entity.getWeightForHeightStatus()); dto.setIsChildReferredNrc(entity.getIsChildReferredNrc()); dto.setIsChildAdmittedNrc(entity.getIsChildAdmittedNrc()); @@ -574,8 +588,9 @@ public List getSamVisitsByBeneficiary(GetBenRequestHandler reque } @Override - public String saveOrsDistributionDetails(List orsDistributionDTOS,Integer userId) { + public String saveOrsDistributionDetails(List orsDistributionDTOS) { try { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); List orsDistributionList = new ArrayList<>(); orsDistributionDTOS.forEach(orsDistributionDTO -> { @@ -588,7 +603,7 @@ public String saveOrsDistributionDetails(List orsDistributio } orsDistribution.setHouseholdId(orsDistributionDTO.getHouseHoldId()); - orsDistribution.setUserId(userId); + orsDistribution.setUserId(userRepo.getUserIdByName(orsDistributionDTO.getUserName())); orsDistribution.setVisitDate(LocalDate.parse(orsDistributionDTO.getFields().getVisit_date(), formatter)); orsDistributionList.add(orsDistribution); @@ -659,9 +674,9 @@ private LocalDate parseDate(String dateStr) { } @Override - public List saveAllIfa(List dtoList,Integer userId) { + public List saveAllIfa(List dtoList, Integer userId) { List savedList = dtoList.stream() - .map(dto ->mapToEntity(dto,userId)) + .map(dto -> mapToEntity(dto, userId)) .map(ifaDistributionRepository::save) .toList(); @@ -669,12 +684,15 @@ public List saveAllIfa(List dtoList,Integer savedList.forEach(data -> { Timestamp visitTimestamp = Timestamp.valueOf(data.getIfaProvisionDate().atStartOfDay()); - incentiveLogicService.incentiveForGiveingIFA( - data.getBeneficiaryId(), - visitTimestamp, - visitTimestamp, - data.getUserId() - ); + if(data.getIfaBottleCount().equals("10.0")){ + incentiveLogicService.incentiveForGiveingIFA( + data.getBeneficiaryId(), + visitTimestamp, + visitTimestamp, + data.getUserId() + ); + } + }); return savedList; @@ -683,8 +701,34 @@ public List saveAllIfa(List dtoList,Integer @Override public List getByBeneficiaryId(GetBenRequestHandler requestHandler) { - return ifaDistributionRepository.findByUserId(requestHandler.getAshaId()).stream() - .map(this::mapToDTO) + + return ifaDistributionRepository.findByUserId(requestHandler.getAshaId()) + .stream() + .map(data -> { + + try { + if ("10.0".equals(data.getIfaBottleCount())) { + + Timestamp visitTimestamp = + Timestamp.valueOf(data.getIfaProvisionDate().atStartOfDay()); + + incentiveLogicService.incentiveForGiveingIFA( + data.getBeneficiaryId(), + visitTimestamp, + visitTimestamp, + data.getUserId() + ); + } + } catch (Exception e) { + logger.error( + "Error while processing IFA incentive for beneficiaryId: {}", + data.getBeneficiaryId(), + e + ); + } + + return mapToDTO(data); + }) .toList(); } @@ -712,7 +756,7 @@ private IfaDistributionDTO mapToDTO(IfaDistribution entity) { } // 🔄 Helper method to convert DTO → Entity - private IfaDistribution mapToEntity(IfaDistributionDTO dto,Integer userId) { + private IfaDistribution mapToEntity(IfaDistributionDTO dto, Integer userId) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); IfaDistribution entity = new IfaDistribution(); @@ -741,12 +785,12 @@ private IfaDistribution mapToEntity(IfaDistributionDTO dto,Integer userId) { return entity; } - private void checkAndAddSamVisitNRCReferalIncentive(List samVisits,Integer userId) { + private void checkAndAddSamVisitNRCReferalIncentive(List samVisits, Integer userId) { samVisits.forEach(samVisit -> { IncentiveActivity samreferralnrcActivityAm = incentivesRepo.findIncentiveMasterByNameAndGroup("SAM_REFERRAL_NRC", GroupName.CHILD_HEALTH.getDisplayName()); IncentiveActivity samreferralnrcActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("SAM_REFERRAL_NRC", GroupName.ACTIVITY.getDisplayName()); - if(userService.getUserDetail(userId).getStateId().equals(StateCode.AM.getStateCode())) { + if (userService.getUserDetail(userId).getStateId().equals(StateCode.AM.getStateCode())) { if (samreferralnrcActivityAm != null) { if (samVisit.getIsChildReferredNrc().equals("Yes")) { @@ -755,7 +799,7 @@ private void checkAndAddSamVisitNRCReferalIncentive(List samVisits,Int } } - if(userService.getUserDetail(userId).getStateId().equals(StateCode.CG.getStateCode())){ + if (userService.getUserDetail(userId).getStateId().equals(StateCode.CG.getStateCode())) { if (samreferralnrcActivityCH != null) { if (samVisit.getIsChildReferredNrc().equals("Yes")) { createIncentiveRecordforSamReferalToNrc(samVisit, samVisit.getBeneficiaryId(), samreferralnrcActivityCH, samVisit.getCreatedBy()); @@ -764,9 +808,6 @@ private void checkAndAddSamVisitNRCReferalIncentive(List samVisits,Int } - - - }); } @@ -831,14 +872,32 @@ private void checkAndAddHbyncIncentives(List hbycList) { private void checkAndAddHbncIncentives(List hbncVisits, Integer userId) { Integer stateCode = userService.getUserDetail(userId).getStateId(); hbncVisits.forEach(hbncVisit -> { - GroupName.setIsCh(false); Long benId = hbncVisit.getBeneficiaryId(); - if (stateCode.equals(StateCode.AM)) { + if (stateCode.equals(StateCode.AM.getStateCode())) { if (hbncVisit.getVisit_day().equals("42nd Day")) { IncentiveActivity visitActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("HBNC_0_42_DAYS", GroupName.CHILD_HEALTH.getDisplayName()); createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityAM, "HBNC_0_42_DAYS"); + } + if (hbncVisit.getVisit_day().equals("42th Day")) { + if (!ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()) { + if (ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getIsHrpConfirmed()) { + IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); + + createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_HEALTH_CHECK"); + + } + } + if (!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()) { + if (!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getMotherDangerSign().isEmpty()) { + IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); + + createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_CARE"); + + } + } + } logger.info("getDischarged_from_sncu" + hbncVisit.getDischarged_from_sncu()); @@ -859,10 +918,25 @@ private void checkAndAddHbncIncentives(List hbncVisits, Integer userI } if (stateCode.equals(StateCode.CG.getStateCode())) { - if (hbncVisit.getVisit_day().equals("7th Day")) { - IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); + if (hbncVisit.getVisit_day().equals("42th Day")) { + if (!ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()) { + if (ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getIsHrpConfirmed() && pncVisitRepo.findByBenId(hbncVisit + .getBeneficiaryId()).get(0).getPncPeriod().toString().equals("42")) { + IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); - createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_CARE"); + createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_HEALTH_CHECK"); + + } + } + if (!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()) { + if (!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getMotherDangerSign().isEmpty() && pncVisitRepo.findByBenId(hbncVisit + .getBeneficiaryId()).get(0).getPncPeriod().toString().equals("42")) { + IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); + + createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_CARE"); + + } + } } } @@ -878,50 +952,59 @@ private void checkAndAddIncentives(List vaccinationList) { vaccinationList.forEach(vaccination -> { - Long benId = beneficiaryRepo.getBenIdFromRegID(vaccination.getBeneficiaryRegId()).longValue(); - Integer userId = userRepo.getUserIdByName(vaccination.getCreatedBy()); - Integer immunizationServiceId = getImmunizationServiceIdForVaccine(vaccination.getVaccineId().shortValue()); - if (immunizationServiceId < 6) { - IncentiveActivity immunizationActivityAM = - incentivesRepo.findIncentiveMasterByNameAndGroup("FULL_IMMUNIZATION_0_1", GroupName.IMMUNIZATION.getDisplayName()); - IncentiveActivity immunizationActivityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("FULL_IMMUNIZATION_0_1", GroupName.ACTIVITY.getDisplayName()); - - - if (immunizationActivityAM != null && childVaccinationRepo.getFirstYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) - .equals(childVaccinationRepo.getFirstYearVaccineCount())) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivityAM); + Long benId= null; + if(vaccination.getBeneficiaryRegId()!=null){ + BigInteger benIdObj = beneficiaryRepo.getBenIdFromRegID(vaccination.getBeneficiaryRegId()); + if (benIdObj != null) { + benId = benIdObj.longValue(); } - if (immunizationActivityCH != null && childVaccinationRepo.getFirstYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) - .equals(childVaccinationRepo.getFirstYearVaccineCount())) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivityCH); + Integer userId = userRepo.getUserIdByName(vaccination.getCreatedBy()); + Integer immunizationServiceId = getImmunizationServiceIdForVaccine(vaccination.getVaccineId().shortValue()); + if (immunizationServiceId < 6) { + IncentiveActivity immunizationActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FULL_IMMUNIZATION_0_1", GroupName.IMMUNIZATION.getDisplayName()); + IncentiveActivity immunizationActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FULL_IMMUNIZATION_0_1", GroupName.ACTIVITY.getDisplayName()); + + + if (immunizationActivityAM != null && childVaccinationRepo.getFirstYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) + .equals(childVaccinationRepo.getFirstYearVaccineCount())) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivityAM); + } + + if (immunizationActivityCH != null && childVaccinationRepo.getFirstYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) + .equals(childVaccinationRepo.getFirstYearVaccineCount())) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivityCH); + } + } else if (immunizationServiceId == 7) { + IncentiveActivity immunizationActivity2AM = + incentivesRepo.findIncentiveMasterByNameAndGroup("COMPLETE_IMMUNIZATION_1_2", GroupName.IMMUNIZATION.getDisplayName()); + IncentiveActivity immunizationActivity2CH = + incentivesRepo.findIncentiveMasterByNameAndGroup("COMPLETE_IMMUNIZATION_1_2", GroupName.ACTIVITY.getDisplayName()); + if (immunizationActivity2AM != null && childVaccinationRepo.getSecondYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) + .equals(childVaccinationRepo.getSecondYearVaccineCount())) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivity2AM); + } + if (immunizationActivity2CH != null && childVaccinationRepo.getSecondYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) + .equals(childVaccinationRepo.getSecondYearVaccineCount())) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivity2CH); + } } - } else if (immunizationServiceId == 7) { - IncentiveActivity immunizationActivity2AM = - incentivesRepo.findIncentiveMasterByNameAndGroup("COMPLETE_IMMUNIZATION_1_2", GroupName.IMMUNIZATION.getDisplayName()); - IncentiveActivity immunizationActivity2CH = - incentivesRepo.findIncentiveMasterByNameAndGroup("COMPLETE_IMMUNIZATION_1_2", GroupName.ACTIVITY.getDisplayName()); - if (immunizationActivity2AM != null && childVaccinationRepo.getSecondYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) - .equals(childVaccinationRepo.getSecondYearVaccineCount())) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivity2AM); + IncentiveActivity immunizationActivity5AM = + incentivesRepo.findIncentiveMasterByNameAndGroup("DPT_IMMUNIZATION_5_YEARS", GroupName.IMMUNIZATION.getDisplayName()); + if (immunizationActivity5AM != null && childVaccinationRepo.checkDptVaccinatedUser(vaccination.getBeneficiaryRegId()) == 1) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivity5AM); } - if (immunizationActivity2CH != null && childVaccinationRepo.getSecondYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) - .equals(childVaccinationRepo.getSecondYearVaccineCount())) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivity2CH); + + IncentiveActivity immunizationActivity5CH = + incentivesRepo.findIncentiveMasterByNameAndGroup("DPT_IMMUNIZATION_5_YEARS", GroupName.ACTIVITY.getDisplayName()); + if (immunizationActivity5CH != null && childVaccinationRepo.checkDptVaccinatedUser(vaccination.getBeneficiaryRegId()) == 1) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivity5CH); } - } - IncentiveActivity immunizationActivity5AM = - incentivesRepo.findIncentiveMasterByNameAndGroup("DPT_IMMUNIZATION_5_YEARS", GroupName.IMMUNIZATION.getDisplayName()); - if (immunizationActivity5AM != null && childVaccinationRepo.checkDptVaccinatedUser(vaccination.getBeneficiaryRegId()) == 1) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivity5AM); - } - IncentiveActivity immunizationActivity5CH = - incentivesRepo.findIncentiveMasterByNameAndGroup("DPT_IMMUNIZATION_5_YEARS", GroupName.ACTIVITY.getDisplayName()); - if (immunizationActivity5CH != null && childVaccinationRepo.checkDptVaccinatedUser(vaccination.getBeneficiaryRegId()) == 1) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivity5CH); } + }); } diff --git a/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java index eeea8405..32c6d76a 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java @@ -50,6 +50,7 @@ public String getByUserId(GetBenRequestHandler dto) { // ChildRegisterDTO childDTO = modelMapper.map(childRegister, ChildRegisterDTO.class); // result.add(childDTO); // }); + List result = childRegisterList.stream() .map(childRegister -> modelMapper.map(childRegister, ChildRegisterDTO.class)) .collect(Collectors.toList()); @@ -90,45 +91,31 @@ public String save(List childRegisterDTOs) throws Exception { } public void processFirstChildIncentive(ChildRegister childRegister) { - Long benId = childRegister.getBenId(); - - RMNCHBeneficiaryDetailsRmnch beneficiary = - beneficiaryRepo.findById(benId).orElse(null); - - if (beneficiary == null || beneficiary.getDateMarriage() == null) { - return; - } + logger.info("Child register {}"+childRegister.getBenId()); // First child validation - Long childCount = childRepo.countByBenId(benId); + List childCount = childRepo.findByBenId(benId); - if (childCount != 1) { - return; - } - - Timestamp marriageDate = beneficiary.getDateMarriage(); - // Temporary: using createdDate as child DOB - Timestamp childBirthDate = childRegister.getCreatedDate(); + if(!childCount.isEmpty()){ + logger.info("Child register {}"+childCount.size()); - long diffMillis = childBirthDate.getTime() - marriageDate.getTime(); + if(childCount.size()==1){ + Integer userId = + userServiceRoleRepo.getUserIdByName(childRegister.getCreatedBy()); - long days = diffMillis / (1000 * 60 * 60 * 24); + incentiveLogicService.incentiveForChildBirthGap( + benId, + childRegister.getCreatedDate(), + childRegister.getCreatedDate(), + userId + ); + } + } - // >= 2 years - if (days >= 730) { - Integer userId = - userServiceRoleRepo.getUserIdByName(childRegister.getCreatedBy()); - incentiveLogicService.incentiveForChildBirthGap( - benId, - childBirthDate, - childBirthDate, - userId - ); - } } private void processSecondChildGapIncentive(ChildRegister currentChild) { @@ -136,48 +123,26 @@ private void processSecondChildGapIncentive(ChildRegister currentChild) { Long benId = currentChild.getBenId(); // Total children count - Long childCount = childRepo.countByBenId(benId); + List childCount = childRepo.findByBenId(benId); // Applicable only for second child - if (childCount != 2) { - return; - } - List children = - childRepo.findByBenIdOrderByCreatedDateAsc(benId); + if(!childCount.isEmpty()){ + if(childCount.size()==2){ + Integer userId = + userServiceRoleRepo.getUserIdByName( + currentChild.getCreatedBy()); - if (children.size() < 2) { - return; - } - - // First child - ChildRegister firstChild = children.get(0); - - // Second child - ChildRegister secondChild = children.get(1); - - Timestamp firstChildDob = firstChild.getCreatedDate(); + incentiveLogicService.incentiveForSecondChildGap( + benId, + currentChild.getCreatedDate(), + currentChild.getCreatedDate(), + userId + ); + } + } - Timestamp secondChildDob = secondChild.getCreatedDate(); - long diffMillis = - secondChildDob.getTime() - firstChildDob.getTime(); - long days = diffMillis / (1000 * 60 * 60 * 24); - - // >= 3 years - if (days >= 1095) { - - Integer userId = - userServiceRoleRepo.getUserIdByName( - currentChild.getCreatedBy()); - - incentiveLogicService.incentiveForSecondChildGap( - benId, - secondChildDob, - secondChildDob, - userId - ); - } } } diff --git a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java index 95b0557b..4fb218b9 100644 --- a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java @@ -188,6 +188,7 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) } } + ecrList.add(existingECR); }); eligibleCoupleRegisterRepo.saveAll(ecrList); @@ -409,6 +410,7 @@ public String getEligibleCoupleRegRecords(GetBenRequestHandler dto) { Gson gson = new GsonBuilder() .serializeNulls() .setDateFormat("MMM dd, yyyy h:mm:ss a").create(); + return gson.toJson(list); } catch (Exception e) { logger.error(e.getMessage()); @@ -418,6 +420,7 @@ public String getEligibleCoupleRegRecords(GetBenRequestHandler dto) { @Override public List getEligibleCoupleTracking(GetBenRequestHandler dto) { + List recordList = new ArrayList<>(); try { String user = beneficiaryRepo.getUserName(dto.getAshaId()); @@ -425,9 +428,12 @@ public List getEligibleCoupleTracking(GetBenRequestHa List eligibleCoupleTrackingList = eligibleCoupleTrackingRepo.getECTrackRecords(user, dto.getFromDate(), dto.getToDate()); + recordRepo.saveAll(recordList); + return eligibleCoupleTrackingList.stream() .map(ect -> mapper.convertValue(ect, EligibleCoupleTrackingDTO.class)) .collect(Collectors.toList()); + } catch (Exception e) { logger.error(e.getMessage()); } diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index addc43b1..feb02d9e 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -25,12 +25,14 @@ package com.iemr.flw.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.flw.domain.identity.RMNCHBeneficiaryDetailsRmnch; import com.iemr.flw.domain.iemr.*; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; import com.iemr.flw.masterEnum.DiseaseType; import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.masterEnum.StateCode; +import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.DiseaseControlService; import com.iemr.flw.service.IncentiveLogicService; @@ -97,6 +99,9 @@ public class DiseaseControlServiceImpl implements DiseaseControlService { @Autowired private UserService userService; + @Autowired + private BeneficiaryRepo beneficiaryRepo; + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); @@ -312,39 +317,42 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO) { } } if (screeningLeprosy.getIsConfirmed()) { - if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), - diseaseControlDTO.getUserId()); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); - } + if(screeningLeprosy.getTypeOfLeprosy()!=null){ + if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + diseaseControlDTO.getUserId()); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } - } - if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), - diseaseControlDTO.getUserId()); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); } + if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + diseaseControlDTO.getUserId()); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } + } } + } return "Data add successfully"; @@ -457,39 +465,43 @@ private void checkAndIncentive(ScreeningLeprosy screeningLeprosy,Integer userId) } } if (screeningLeprosy.getIsConfirmed()) { - if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), - userId); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); - } + if(screeningLeprosy.getTypeOfLeprosy()!=null){ + if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + userId); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } - } - if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), - userId); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); } + if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + userId); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } + } } + + } } @@ -523,39 +535,92 @@ public Object getAllMalaria(GetDiseaseRequestHandler getDiseaseRequestHandler) { // Map to DTOs List dtoList = filteredList.stream().map(disease -> { + DiseaseMalariaDTO dto = new DiseaseMalariaDTO(); - // Map fields from DiseaseMalaria to DTO - dto.setId(disease.getId()); - dto.setBenId(disease.getBenId()); - dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); - dto.setScreeningDate(disease.getScreeningDate()); - dto.setBeneficiaryStatus(disease.getBeneficiaryStatus()); - dto.setDateOfDeath(disease.getDateOfDeath()); - dto.setPlaceOfDeath(disease.getPlaceOfDeath()); - dto.setOtherPlaceOfDeath(disease.getOtherPlaceOfDeath()); - dto.setReasonForDeath(disease.getReasonForDeath()); - dto.setOtherReasonForDeath(disease.getOtherReasonForDeath()); - dto.setCaseStatus(disease.getCaseStatus()); - dto.setRapidDiagnosticTest(disease.getRapidDiagnosticTest()); - dto.setDateOfRdt(disease.getDateOfRdt()); - dto.setSlideTestPf(disease.getSlideTestPf()); - dto.setSlideTestPv(disease.getSlideTestPv()); - dto.setDateOfSlideTest(disease.getDateOfSlideTest()); - dto.setSlideNo(disease.getSlideNo()); - dto.setReferredTo(disease.getReferredTo()); - dto.setOtherReferredFacility(disease.getOtherReferredFacility()); - dto.setRemarks(disease.getRemarks()); - dto.setMalariaSlideTestType(disease.getMalariaSlideTestType()); - dto.setMalariaTestType(disease.getMalariaTestType()); - dto.setDateOfVisitBySupervisor(disease.getDateOfVisitBySupervisor()); - dto.setUserId(disease.getUserId()); - dto.setDiseaseTypeId(disease.getDiseaseTypeId()); - - // Parse symptoms (if present) + if (disease.getId() != null) + dto.setId(disease.getId()); + + if (disease.getBenId() != null) + dto.setBenId(disease.getBenId()); + + if (disease.getHouseHoldDetailsId() != null) + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + + if (disease.getScreeningDate() != null) + dto.setScreeningDate(disease.getScreeningDate()); + + if (disease.getBeneficiaryStatus() != null && !disease.getBeneficiaryStatus().trim().isEmpty()) + dto.setBeneficiaryStatus(disease.getBeneficiaryStatus()); + + if (disease.getDateOfDeath() != null) + dto.setDateOfDeath(disease.getDateOfDeath()); + + if (disease.getPlaceOfDeath() != null && !disease.getPlaceOfDeath().trim().isEmpty()) + dto.setPlaceOfDeath(disease.getPlaceOfDeath()); + + if (disease.getOtherPlaceOfDeath() != null && !disease.getOtherPlaceOfDeath().trim().isEmpty()) + dto.setOtherPlaceOfDeath(disease.getOtherPlaceOfDeath()); + + if (disease.getReasonForDeath() != null && !disease.getReasonForDeath().trim().isEmpty()) + dto.setReasonForDeath(disease.getReasonForDeath()); + + if (disease.getOtherReasonForDeath() != null && !disease.getOtherReasonForDeath().trim().isEmpty()) + dto.setOtherReasonForDeath(disease.getOtherReasonForDeath()); + + if (disease.getCaseStatus() != null && !disease.getCaseStatus().trim().isEmpty()) + dto.setCaseStatus(disease.getCaseStatus()); + + if (disease.getRapidDiagnosticTest() != null) + dto.setRapidDiagnosticTest(disease.getRapidDiagnosticTest()); + + if (disease.getDateOfRdt() != null) + dto.setDateOfRdt(disease.getDateOfRdt()); + + if (disease.getSlideTestPf() != null) + dto.setSlideTestPf(disease.getSlideTestPf()); + + if (disease.getSlideTestPv() != null) + dto.setSlideTestPv(disease.getSlideTestPv()); + + if (disease.getDateOfSlideTest() != null) + dto.setDateOfSlideTest(disease.getDateOfSlideTest()); + + if (disease.getSlideNo() != null && !disease.getSlideNo().trim().isEmpty()) + dto.setSlideNo(disease.getSlideNo()); + + if (disease.getReferredTo() != null) + dto.setReferredTo(disease.getReferredTo()); + + if (disease.getOtherReferredFacility() != null && !disease.getOtherReferredFacility().trim().isEmpty()) + dto.setOtherReferredFacility(disease.getOtherReferredFacility()); + + if (disease.getRemarks() != null && !disease.getRemarks().trim().isEmpty()) + dto.setRemarks(disease.getRemarks()); + + if (disease.getMalariaSlideTestType() != null && !disease.getMalariaSlideTestType().trim().isEmpty()) + dto.setMalariaSlideTestType(disease.getMalariaSlideTestType()); + + if (disease.getMalariaTestType() != null && !disease.getMalariaTestType().trim().isEmpty()) + dto.setMalariaTestType(disease.getMalariaTestType()); + + if (disease.getDateOfVisitBySupervisor() != null) + dto.setDateOfVisitBySupervisor(disease.getDateOfVisitBySupervisor()); + + if (disease.getUserId() != null) + dto.setUserId(disease.getUserId()); + + if (disease.getDiseaseTypeId() != null) + dto.setDiseaseTypeId(disease.getDiseaseTypeId()); + + // Symptoms JSON try { - if (disease.getSymptoms() != null && !disease.getSymptoms().isEmpty()) { - MalariaSymptomsDTO symptomsDTO = objectMapper.readValue(disease.getSymptoms(), MalariaSymptomsDTO.class); + if (disease.getSymptoms() != null && + !disease.getSymptoms().trim().isEmpty()) { + + MalariaSymptomsDTO symptomsDTO = + objectMapper.readValue(disease.getSymptoms(), MalariaSymptomsDTO.class); + dto.setFeverMoreThanTwoWeeks(symptomsDTO.isFeverMoreThanTwoWeeks()); dto.setFluLikeIllness(symptomsDTO.isFluLikeIllness()); dto.setShakingChills(symptomsDTO.isShakingChills()); @@ -567,7 +632,8 @@ public Object getAllMalaria(GetDiseaseRequestHandler getDiseaseRequestHandler) { dto.setDiarrhea(symptomsDTO.isDiarrhea()); } } catch (Exception e) { - throw new RuntimeException("Error parsing symptoms JSON for Malaria Disease ID: " + disease.getId(), e); + logger.error("Error parsing symptoms for diseaseId={}", + disease.getId(), e); } return dto; @@ -613,30 +679,77 @@ public Object getAllKalaAzar(GetDiseaseRequestHandler getDiseaseRequestHandler) // Map to DTOs List dtoList = filteredList.stream().map(disease -> { + DiseaseKalaAzarDTO dto = new DiseaseKalaAzarDTO(); - dto.setId(disease.getId()); - dto.setBenId(disease.getBenId()); - dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); - dto.setVisitDate(disease.getVisitDate()); - dto.setBeneficiaryStatus(disease.getBeneficiaryStatus()); - dto.setDateOfDeath(disease.getDateOfDeath()); - dto.setPlaceOfDeath(disease.getPlaceOfDeath()); - dto.setOtherPlaceOfDeath(disease.getOtherPlaceOfDeath()); - dto.setReasonForDeath(disease.getReasonForDeath()); - dto.setOtherReasonForDeath(disease.getOtherReasonForDeath()); - dto.setKalaAzarCaseStatus(disease.getKalaAzarCaseStatus()); - dto.setKalaAzarCaseCount(disease.getKalaAzarCaseCount()); - dto.setRapidDiagnosticTest(disease.getRapidDiagnosticTest()); - dto.setDateOfRdt(disease.getDateOfRdt()); - dto.setFollowUpPoint(disease.getFollowUpPoint()); - dto.setReferredTo(disease.getReferredTo()); - dto.setOtherReferredFacility(disease.getOtherReferredFacility()); - dto.setCreatedDate(disease.getCreatedDate()); - dto.setCreatedBy(disease.getCreatedBy()); - dto.setBeneficiaryStatusId(disease.getBeneficiaryStatusId()); - dto.setReferToName(disease.getReferToName()); - dto.setUserId(disease.getUserId()); - dto.setDiseaseTypeId(disease.getDiseaseTypeId()); + + if (disease.getId() != null) + dto.setId(disease.getId()); + + if (disease.getBenId() != null) + dto.setBenId(disease.getBenId()); + + if (disease.getHouseHoldDetailsId() != null) + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + + if (disease.getVisitDate() != null) + dto.setVisitDate(disease.getVisitDate()); + + if (disease.getBeneficiaryStatus() != null && !disease.getBeneficiaryStatus().trim().isEmpty()) + dto.setBeneficiaryStatus(disease.getBeneficiaryStatus()); + + if (disease.getDateOfDeath() != null) + dto.setDateOfDeath(disease.getDateOfDeath()); + + if (disease.getPlaceOfDeath() != null && !disease.getPlaceOfDeath().trim().isEmpty()) + dto.setPlaceOfDeath(disease.getPlaceOfDeath()); + + if (disease.getOtherPlaceOfDeath() != null && !disease.getOtherPlaceOfDeath().trim().isEmpty()) + dto.setOtherPlaceOfDeath(disease.getOtherPlaceOfDeath()); + + if (disease.getReasonForDeath() != null && !disease.getReasonForDeath().trim().isEmpty()) + dto.setReasonForDeath(disease.getReasonForDeath()); + + if (disease.getOtherReasonForDeath() != null && !disease.getOtherReasonForDeath().trim().isEmpty()) + dto.setOtherReasonForDeath(disease.getOtherReasonForDeath()); + + if (disease.getKalaAzarCaseStatus() != null && !disease.getKalaAzarCaseStatus().trim().isEmpty()) + dto.setKalaAzarCaseStatus(disease.getKalaAzarCaseStatus()); + + if (disease.getKalaAzarCaseCount() != null) + dto.setKalaAzarCaseCount(disease.getKalaAzarCaseCount()); + + if (disease.getRapidDiagnosticTest() != null) + dto.setRapidDiagnosticTest(disease.getRapidDiagnosticTest()); + + if (disease.getDateOfRdt() != null) + dto.setDateOfRdt(disease.getDateOfRdt()); + + if (disease.getFollowUpPoint() != null) + dto.setFollowUpPoint(disease.getFollowUpPoint()); + + if (disease.getReferredTo() != null && !disease.getReferredTo().trim().isEmpty()) + dto.setReferredTo(disease.getReferredTo()); + + if (disease.getOtherReferredFacility() != null && !disease.getOtherReferredFacility().trim().isEmpty()) + dto.setOtherReferredFacility(disease.getOtherReferredFacility()); + + if (disease.getCreatedDate() != null) + dto.setCreatedDate(disease.getCreatedDate()); + + if (disease.getCreatedBy() != null && !disease.getCreatedBy().trim().isEmpty()) + dto.setCreatedBy(disease.getCreatedBy()); + + if (disease.getBeneficiaryStatusId() != null) + dto.setBeneficiaryStatusId(disease.getBeneficiaryStatusId()); + + if (disease.getReferToName() != null && !disease.getReferToName().trim().isEmpty()) + dto.setReferToName(disease.getReferToName()); + + if (disease.getUserId() != null) + dto.setUserId(disease.getUserId()); + + if (disease.getDiseaseTypeId() != null) + dto.setDiseaseTypeId(disease.getDiseaseTypeId()); return dto; }).collect(Collectors.toList()); @@ -666,23 +779,58 @@ public Object getAllFilaria(GetDiseaseRequestHandler getDiseaseRequestHandler) { // Map to DTOs List dtoList = filteredList.stream().map(disease -> { + DiseaseFilariasisDTO dto = new DiseaseFilariasisDTO(); - dto.setId(disease.getId()); - dto.setBenId(disease.getBenId()); - dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); - dto.setSufferingFromFilariasis(disease.getSufferingFromFilariasis()); - dto.setAffectedBodyPart(disease.getAffectedBodyPart()); - dto.setMdaHomeVisitDate(disease.getMdaHomeVisitDate()); - dto.setDoseStatus(disease.getDoseStatus()); - dto.setFilariasisCaseCount(disease.getFilariasisCaseCount()); - dto.setOtherDoseStatusDetails(disease.getOtherDoseStatusDetails()); - dto.setMedicineSideEffect(disease.getMedicineSideEffect()); - dto.setOtherSideEffectDetails(disease.getOtherSideEffectDetails()); - dto.setCreatedDate(disease.getCreatedDate()); - dto.setCreatedBy(disease.getCreatedBy()); - dto.setUserId(disease.getUserId()); + + if (disease.getId() != null) + dto.setId(disease.getId()); + + if (disease.getBenId() != null) + dto.setBenId(disease.getBenId()); + + if (disease.getHouseHoldDetailsId() != null) + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + + if (disease.getSufferingFromFilariasis() != null) + dto.setSufferingFromFilariasis(disease.getSufferingFromFilariasis()); + + if (disease.getAffectedBodyPart() != null && + !disease.getAffectedBodyPart().trim().isEmpty()) + dto.setAffectedBodyPart(disease.getAffectedBodyPart()); + + if (disease.getMdaHomeVisitDate() != null) + dto.setMdaHomeVisitDate(disease.getMdaHomeVisitDate()); + + if (disease.getDoseStatus() != null && + !disease.getDoseStatus().trim().isEmpty()) + dto.setDoseStatus(disease.getDoseStatus()); + + if (disease.getFilariasisCaseCount() != null) + dto.setFilariasisCaseCount(disease.getFilariasisCaseCount()); + + if (disease.getOtherDoseStatusDetails() != null && + !disease.getOtherDoseStatusDetails().trim().isEmpty()) + dto.setOtherDoseStatusDetails(disease.getOtherDoseStatusDetails()); + + if (disease.getMedicineSideEffect() != null) + dto.setMedicineSideEffect(disease.getMedicineSideEffect()); + + if (disease.getOtherSideEffectDetails() != null && + !disease.getOtherSideEffectDetails().trim().isEmpty()) + dto.setOtherSideEffectDetails(disease.getOtherSideEffectDetails()); + + if (disease.getCreatedDate() != null) + dto.setCreatedDate(disease.getCreatedDate()); + + if (disease.getCreatedBy() != null && + !disease.getCreatedBy().trim().isEmpty()) + dto.setCreatedBy(disease.getCreatedBy()); + + if (disease.getUserId() != null) + dto.setUserId(disease.getUserId()); return dto; + }).collect(Collectors.toList()); return dtoList; @@ -704,19 +852,44 @@ public Object getAllLeprosy(GetDiseaseRequestHandler getDiseaseRequestHandler) { // Map to DTOs List dtoList = filteredList.stream().map(disease -> { DiseaseLeprosyDTO dto = new DiseaseLeprosyDTO(); - dto.setId(disease.getId()); - dto.setBenId(disease.getBenId()); - dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); - dto.setHomeVisitDate(disease.getHomeVisitDate()); - dto.setLeprosyStatus(disease.getLeprosyStatus()); - dto.setReferredTo(disease.getReferredTo()); - dto.setOtherReferredTo(disease.getOtherReferredTo()); - dto.setLeprosyStatusDate(disease.getLeprosyStatusDate()); - dto.setTypeOfLeprosy(disease.getTypeOfLeprosy()); - dto.setFollowUpDate(disease.getFollowUpDate()); - dto.setBeneficiaryStatus(disease.getLeprosyStatus()); - dto.setRemark(disease.getRemark()); - dto.setUserId(disease.getUserId()); + if (disease.getId() != null) + dto.setId(disease.getId()); + + if (disease.getBenId() != null) + dto.setBenId(disease.getBenId()); + + if (disease.getHouseHoldDetailsId() != null) + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + + if (disease.getHomeVisitDate() != null) + dto.setHomeVisitDate(disease.getHomeVisitDate()); + + if (disease.getLeprosyStatus() != null && !disease.getLeprosyStatus().trim().isEmpty()) + dto.setLeprosyStatus(disease.getLeprosyStatus()); + + if (disease.getReferredTo() != null && !disease.getReferredTo().trim().isEmpty()) + dto.setReferredTo(disease.getReferredTo()); + + if (disease.getOtherReferredTo() != null && !disease.getOtherReferredTo().trim().isEmpty()) + dto.setOtherReferredTo(disease.getOtherReferredTo()); + + if (disease.getLeprosyStatusDate() != null) + dto.setLeprosyStatusDate(disease.getLeprosyStatusDate()); + + if (disease.getTypeOfLeprosy() != null && !disease.getTypeOfLeprosy().trim().isEmpty()) + dto.setTypeOfLeprosy(disease.getTypeOfLeprosy()); + + if (disease.getFollowUpDate() != null) + dto.setFollowUpDate(disease.getFollowUpDate()); + + if (disease.getLeprosyStatus() != null && !disease.getLeprosyStatus().trim().isEmpty()) + dto.setBeneficiaryStatus(disease.getLeprosyStatus()); + + if (disease.getRemark() != null && !disease.getRemark().trim().isEmpty()) + dto.setRemark(disease.getRemark()); + + if (disease.getUserId() != null) + dto.setUserId(disease.getUserId()); return dto; @@ -812,7 +985,10 @@ private ScreeningLeprosy saveLeprosyData(DiseaseLeprosyDTO diseaseControlData) { diseaseLeprosy.setDiseaseTypeId(diseaseControlData.getDiseaseTypeId()); diseaseLeprosy.setOtherReferredTo(diseaseControlData.getOtherReferredTo()); diseaseLeprosy.setLeprosyStatusDate(diseaseControlData.getLeprosyStatusDate()); - diseaseLeprosy.setTypeOfLeprosy(diseaseControlData.getTypeOfLeprosy()); + if(diseaseControlData.getTypeOfLeprosy()!=null){ + diseaseLeprosy.setTypeOfLeprosy(diseaseControlData.getTypeOfLeprosy()); + + } diseaseLeprosy.setFollowUpDate(diseaseControlData.getFollowUpDate()); diseaseLeprosy.setBeneficiaryStatus(diseaseControlData.getBeneficiaryStatus()); diseaseLeprosy.setBeneficiaryStatusId(diseaseControlData.getBeneficiaryStatusId()); @@ -1044,8 +1220,10 @@ public List saveMosquitoMobilizationNet(List mos List entityList = mosquitoNetDTOList.stream().map(dto -> { MosquitoNetEntity entity = new MosquitoNetEntity(); + if(!beneficiaryRepo.findByHouseoldId(dto.getHouseHoldId()).isEmpty()){ + entity.setBeneficiaryId(beneficiaryRepo.findByHouseoldId(dto.getHouseHoldId()).get(0).getBenficieryid()); - entity.setBeneficiaryId(dto.getBeneficiaryId()); + } entity.setHouseHoldId(dto.getHouseHoldId()); // ✅ String → LocalDate conversion @@ -1122,7 +1300,6 @@ public List getAllMosquitoMobilizationNet(Integer userId) { mosquitoNetListDTO.setVisit_date(entity.getVisitDate().format(formatter)); dto.setFields(mosquitoNetListDTO); - checkAndAddIncentives(entity); return dto; @@ -1142,17 +1319,28 @@ private void checkAndAddIncentives(MosquitoNetEntity mosquitoNetEntity) { private void checkAndAddIncentives(ScreeningMalaria diseaseScreening) { Integer stateId = userService.getUserDetail(diseaseScreening.getUserId()).getStateId(); IncentiveActivity diseaseScreeningActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("NVBDCP_MALARIA_TREATMENT", GroupName.UMBRELLA_PROGRAMMES.getDisplayName()); + IncentiveActivity diseaseScreeningActivityCG = incentivesRepo.findIncentiveMasterByNameAndGroup("NVBDCP_MALARIA_TREATMENT", GroupName.ACTIVITY.getDisplayName()); IncentiveActivity incentiveActivityForCollectSlideAM = incentivesRepo.findIncentiveMasterByNameAndGroup("NVBDCP_SLIDE_COLLECTION", GroupName.UMBRELLA_PROGRAMMES.getDisplayName()); IncentiveActivity incentiveActivityForCollectSlideCG = incentivesRepo.findIncentiveMasterByNameAndGroup("NVBDCP_SLIDE_COLLECTION", GroupName.ACTIVITY.getDisplayName()); if (diseaseScreeningActivity != null) { - if (Objects.equals(diseaseScreening.getCaseStatus(), "Confirmed")) { - addIncentive(diseaseScreeningActivity, diseaseScreening); + if(stateId.equals(StateCode.AM.getStateCode())){ + if (Objects.equals(diseaseScreening.getCaseStatus(), "Confirmed")) { + addIncentive(diseaseScreeningActivity, diseaseScreening); + } + } + if(stateId.equals(StateCode.CG.getStateCode())){ + if (Objects.equals(diseaseScreening.getCaseStatus(), "Confirmed")) { + addIncentive(diseaseScreeningActivityCG, diseaseScreening); + + } } + } + if (diseaseScreening.getCaseStatus().equals("Suspected")) { - if (diseaseScreening.getMalariaSlideTestType().equals("Slide Test") || diseaseScreening.getMalariaSlideTestType().equals("2")) { + if (!diseaseScreening.getMalariaTestType().isEmpty()) { if (stateId.equals(StateCode.AM.getStateCode())) { if (incentiveActivityForCollectSlideAM != null) { addIncentive(incentiveActivityForCollectSlideAM, diseaseScreening); @@ -1176,12 +1364,11 @@ private void addIncentive(IncentiveActivity diseaseScreeningActivity, MosquitoNe Timestamp visitTimestamp = Timestamp.valueOf(diseaseScreening.getVisitDate().atStartOfDay()); - IncentiveActivityRecord record = recordRepo .findRecordByActivityIdCreatedDateBenId( diseaseScreeningActivity.getId(), visitTimestamp, - diseaseScreening.getBeneficiaryId().longValue()); + diseaseScreening.getBeneficiaryId()); if (record == null) { @@ -1201,35 +1388,45 @@ record = new IncentiveActivityRecord(); recordRepo.save(record); } + } private void addIncentive(IncentiveActivity diseaseScreeningActivity, ScreeningMalaria diseaseScreening) { - IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(diseaseScreeningActivity.getId(), Timestamp.valueOf(diseaseScreening.getCreatedDate().toString()), diseaseScreening.getBenId().longValue()); - if (record == null) { - record = new IncentiveActivityRecord(); - record.setActivityId(diseaseScreeningActivity.getId()); - record.setCreatedDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); - record.setCreatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); - record.setStartDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); - record.setEndDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); - record.setUpdatedDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); - record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); - record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); - record.setBenId(diseaseScreening.getBenId().longValue()); - record.setAshaId(diseaseScreening.getUserId()); - record.setAmount(Long.valueOf(diseaseScreeningActivity.getRate())); - record.setIsEligible(true); - recordRepo.save(record); + try { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(diseaseScreeningActivity.getId(), Timestamp.valueOf(diseaseScreening.getCreatedDate().toString()), diseaseScreening.getBenId().longValue()); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(diseaseScreeningActivity.getId()); + record.setCreatedDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setCreatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); + record.setStartDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setEndDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setUpdatedDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); + record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); + record.setBenId(diseaseScreening.getBenId().longValue()); + record.setAshaId(diseaseScreening.getUserId()); + record.setAmount(Long.valueOf(diseaseScreeningActivity.getRate())); + record.setIsEligible(true); + recordRepo.save(record); + logger.info("Incentive for {}"+diseaseScreeningActivity.getDescription()); + + } + }catch (Exception e){ + logger.info("Fail to generate Incentive for {}"+diseaseScreeningActivity.getDescription()+ "Exception"+e.getMessage()); } + } @Override public List saveChronicDiseaseVisit( List requestList, String token) throws IEMRException { + Integer userId = jwtUtil.extractUserId(token); + String userName= userRepo.getUserNamedByUserId(userId); List responseList = new ArrayList<>(); @@ -1249,9 +1446,9 @@ public List saveChronicDiseaseVisit( } entity.setDiagnosisCodes(dto.getDiagnosisCodes()); entity.setFormDataJson(dto.getFormDataJson()); - entity.setUserID(jwtUtil.extractUserId(token)); - entity.setCreatedBy(userRepo.getUserNamedByUserId(jwtUtil.extractUserId(token))); - entity.setUpdatedBy(jwtUtil.extractUserId(token)); + entity.setUserID(userId); + entity.setCreatedBy(userName); + entity.setUpdatedBy(userId); if (dto.getTreatmentStartDate() != null) { @@ -1275,7 +1472,9 @@ public List saveChronicDiseaseVisit( private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity, Integer ashaId) { String userName = userRepo.getUserNamedByUserId(ashaId); + Integer stateId = userService.getUserDetail(ashaId).getStateId(); IncentiveActivity incentiveActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("NCD_FOLLOWUP_TREATMENT", GroupName.NCD.getDisplayName()); + IncentiveActivity incentiveActivityCG = incentivesRepo.findIncentiveMasterByNameAndGroup("NCD_FOLLOWUP_TREATMENT", GroupName.ACTIVITY.getDisplayName()); logger.info("incentiveActivity:" + incentiveActivity.getId()); if (incentiveActivity != null) { if (chronicDiseaseVisitEntity.getFollowUpNo() != null @@ -1297,17 +1496,28 @@ private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity, .anyMatch(targetDiseases::contains); if (matchFound && Integer.valueOf(6).equals(chronicDiseaseVisitEntity.getFollowUpNo())) { - LocalDateTime localDateTime = chronicDiseaseVisitEntity.getCreatedDate(); + LocalDateTime localDateTime = chronicDiseaseVisitEntity.getFollowUpDate().atStartOfDay(); Timestamp followUpTimestamp = Timestamp.valueOf(localDateTime); + if(stateId.equals(StateCode.AM.getStateCode())){ + addNCDFolloupIncentiveRecord( + incentiveActivity, + ashaId, + chronicDiseaseVisitEntity.getBenId(), + followUpTimestamp, + userName + ); + } + if(stateId.equals(StateCode.CG.getStateCode())){ + addNCDFolloupIncentiveRecord( + incentiveActivityCG, + ashaId, + chronicDiseaseVisitEntity.getBenId(), + followUpTimestamp, + userName + ); + } - addNCDFolloupIncentiveRecord( - incentiveActivity, - ashaId, - chronicDiseaseVisitEntity.getBenId(), - followUpTimestamp, - userName - ); } } } diff --git a/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java index 380ed511..76e8dc58 100644 --- a/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java @@ -1,6 +1,8 @@ package com.iemr.flw.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.flw.controller.DeathReportsController; +import com.iemr.flw.domain.iemr.EligibleCoupleRegister; import com.iemr.flw.domain.iemr.IFAFormSubmissionData; import com.iemr.flw.domain.iemr.IncentiveActivity; import com.iemr.flw.domain.iemr.IncentiveActivityRecord; @@ -10,15 +12,14 @@ import com.iemr.flw.dto.iemr.IFAFormSubmissionResponse; import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.masterEnum.StateCode; -import com.iemr.flw.repo.iemr.IFAFormSubmissionRepository; -import com.iemr.flw.repo.iemr.IncentiveRecordRepo; -import com.iemr.flw.repo.iemr.IncentivesRepo; -import com.iemr.flw.repo.iemr.UserServiceRoleRepo; +import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.IFAFormSubmissionService; import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; import jakarta.persistence.criteria.CriteriaBuilder; import lombok.RequiredArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -34,6 +35,9 @@ public class IFAFormSubmissionServiceImpl implements IFAFormSubmissionService { private final IFAFormSubmissionRepository repository; private final ObjectMapper mapper = new ObjectMapper(); + private final Logger logger = LoggerFactory.getLogger(IFAFormSubmissionServiceImpl.class); + + @Autowired private JwtUtil jwtUtil; @@ -48,6 +52,9 @@ public class IFAFormSubmissionServiceImpl implements IFAFormSubmissionService { @Autowired private UserService userService; + @Autowired + private EligibleCoupleRegisterRepo eligibleCoupleRegisterRepo; + @Override public String saveFormData(List requests, Integer userId) { try { @@ -75,30 +82,35 @@ public String saveFormData(List requests, Integer user } private void checkIFAIncentive(List entities,Integer userId) { - Integer stateCode = userService.getUserDetail(userId).getStateId(); - if(stateCode.equals(StateCode.AM.getStateCode())){ - IncentiveActivity incentiveActivityAM= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.CHILD_HEALTH.getDisplayName()); - - if(incentiveActivityAM!=null){ - entities.forEach(ifaFormSubmissionData -> { - addIFAIncentive(ifaFormSubmissionData,incentiveActivityAM); - - }); + try { + List records = repository.findByUserId(userId); + List eligibleCoupleRegisters = eligibleCoupleRegisterRepo.getECRegRecords(userService.getUserDetail(userId).getUserName()); + int totalEligibleCouples = eligibleCoupleRegisters.size(); + int totalIFASubmissions = records.size(); + if(totalEligibleCouples>0){ + double percentage = + (totalIFASubmissions * 100.0) / totalEligibleCouples; + if(percentage>=70){ + Integer stateCode = userService.getUserDetail(userId).getStateId(); + if(stateCode.equals(StateCode.CG.getStateCode())){ + IncentiveActivity incentiveActivityCG= incentivesRepo.findIncentiveMasterByNameAndGroup("NATIONAL_IRON_PLUS", GroupName.ACTIVITY.getDisplayName()); + + if(incentiveActivityCG!=null){ + entities.forEach(ifaFormSubmissionData -> { + addIFAIncentive(ifaFormSubmissionData,incentiveActivityCG); + + }); + } + + } + } } + }catch (Exception e){ + logger.error("Error while processing IFA incentive", e); } - if(stateCode.equals(StateCode.CG.getStateCode())){ - IncentiveActivity incentiveActivityCG= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.ACTIVITY.getDisplayName()); - - if(incentiveActivityCG!=null){ - entities.forEach(ifaFormSubmissionData -> { - addIFAIncentive(ifaFormSubmissionData,incentiveActivityCG); - }); - } - - } } @@ -112,7 +124,7 @@ private void addIFAIncentive(IFAFormSubmissionData ifaFormSubmissionData, Incent IncentiveActivityRecord incentiveActivityRecord = incentiveRecordRepo.findRecordByActivityIdCreatedDateBenId(incentiveActivityAM.getId(),ifaVisitDateTimestamp,ifaFormSubmissionData.getBeneficiaryId()); if(incentiveActivityRecord==null){ incentiveActivityRecord = new IncentiveActivityRecord(); - incentiveActivityRecord.setActivityId(ifaFormSubmissionData.getId()); + incentiveActivityRecord.setActivityId(incentiveActivityAM.getId()); incentiveActivityRecord.setCreatedDate(ifaVisitDateTimestamp); incentiveActivityRecord.setStartDate(ifaVisitDateTimestamp); incentiveActivityRecord.setEndDate(ifaVisitDateTimestamp); @@ -122,6 +134,7 @@ private void addIFAIncentive(IFAFormSubmissionData ifaFormSubmissionData, Incent incentiveActivityRecord.setBenId(ifaFormSubmissionData.getBeneficiaryId()); incentiveActivityRecord.setAshaId(userServiceRoleRepo.getUserIdByName(ifaFormSubmissionData.getUserName())); incentiveActivityRecord.setAmount(Long.valueOf(incentiveActivityAM.getRate())); + incentiveActivityRecord.setIsEligible(true); incentiveRecordRepo.save(incentiveActivityRecord); } } diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index 87cb83f9..2802fa92 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -85,6 +85,37 @@ public IncentiveActivityRecord incentiveForLeprosyPaucibacillaryConfirmed( } } + @Override + public IncentiveActivityRecord incentiveForTbSuspected(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId) { + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "INFORMANT_INCENTIVE"; + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + + } catch (Exception e) { + logger.error("Check Tb Suspected Incentive Exception: ", e); + return null; + } + } @Override public IncentiveActivityRecord incentiveForLeprosyMultibacillaryConfirmed( @@ -262,7 +293,7 @@ public IncentiveActivityRecord incentiveForChildBirthGap(Long benId, Date treatm } @Override - public IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp secondChildDob, Timestamp secondChildDob1, Integer userId) { + public IncentiveActivityRecord incentiveForEyeSurgeyReferGovtHospital(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId) { try { Integer stateCode = userService.getUserDetail(userId).getStateId(); @@ -278,8 +309,8 @@ public IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp activityName, GroupName.ACTIVITY.getDisplayName(), benId, - secondChildDob, - secondChildDob1, + treatmentStartDate, + treatmentEndDate, userId); } @@ -288,8 +319,8 @@ public IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp activityName, GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), benId, - secondChildDob, - secondChildDob1, + treatmentStartDate, + treatmentEndDate, userId); } @@ -301,9 +332,52 @@ public IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp logger.error("Check Eye surgery Incentive Exception: ", e); return null; } + } + + @Override + public IncentiveActivityRecord incentiveForEyeSurgeyReferPrivateHospital(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId) { + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "NPCB_PRIVATE_CATARACT"; + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + if (stateCode.equals(StateCode.AM.getStateCode())) { + return processIncentive( + activityName, + GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + } catch (Exception e) { + logger.error("Check Eye surgery Incentive Exception: ", e); + return null; + } } + + @Override public IncentiveActivityRecord incentiveForGiveingIFA(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId) { try { @@ -314,7 +388,7 @@ public IncentiveActivityRecord incentiveForGiveingIFA(Long benId, Timestamp trea return null; } - String activityName = "LACTATING_MOTHERS_HOME_VISIT"; + String activityName = "NIPI_CHILDREN"; if (stateCode.equals(StateCode.CG.getStateCode())) { return processIncentive( @@ -329,7 +403,7 @@ public IncentiveActivityRecord incentiveForGiveingIFA(Long benId, Timestamp trea if (stateCode.equals(StateCode.AM.getStateCode())) { return processIncentive( activityName, - GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), + GroupName.CHILD_HEALTH.getDisplayName(), benId, treatmentStartDate, treatmentEndDate, @@ -439,7 +513,7 @@ public IncentiveActivityRecord incentiveForMalariaFollowUp(Long benId, Timestamp return null; } - String activityName = "NPCB_GOVT_CATARACT"; + String activityName = "NVBDCP_MALARIA_TREATMENT"; if (stateCode.equals(StateCode.CG.getStateCode())) { return processIncentive( @@ -493,6 +567,16 @@ public IncentiveActivityRecord incentiveForSecondChildGap(Long benId, Timestamp userId); } + if (stateCode.equals(StateCode.AM.getStateCode())) { + return processIncentive( + activityName, + GroupName.FAMILY_PLANNING.getDisplayName(), + benId, + secondChildDob, + secondChildDob1, + userId); + } + // state not supported logger.info("No incentive mapping for stateCode: {}", stateCode); return null; @@ -574,6 +658,7 @@ private IncentiveActivityRecord saveIncentive( Integer userId) { try { + String userName = userServiceRoleRepo.getUserNamedByUserId(userId); if (activity == null || benId == null || startDate == null || endDate == null) { logger.warn("Invalid input for saving incentive"); @@ -602,8 +687,8 @@ private IncentiveActivityRecord saveIncentive( record.setUpdatedDate(startTimestamp); record.setStartDate(startTimestamp); record.setEndDate(endTimestamp); - record.setCreatedBy(userServiceRoleRepo.getUserNamedByUserId(userId)); - record.setUpdatedBy(userServiceRoleRepo.getUserNamedByUserId(userId)); + record.setCreatedBy(userName); + record.setUpdatedBy(userName); record.setBenId(benId); record.setAshaId(userId); record.setAmount(Long.valueOf(activity.getRate())); diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java index a6584705..55e04af9 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -25,10 +25,12 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; + import java.math.BigInteger; import java.sql.Timestamp; import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.Function; @@ -39,12 +41,18 @@ public class IncentiveServiceImpl implements IncentiveService { private final Logger logger = LoggerFactory.getLogger(IncentiveServiceImpl.class); - @Autowired private BeneficiaryRepo beneficiaryRepo; - @Autowired private IncentiveActivityLangMappingRepo incentiveActivityLangMappingRepo; - @Autowired private IncentivesRepo incentivesRepo; - @Autowired private IncentiveRecordRepo recordRepo; - @Autowired private IncentivePendingActivityRepository incentivePendingActivityRepository; - @Autowired private UserServiceRoleRepo userRepo; + @Autowired + private BeneficiaryRepo beneficiaryRepo; + @Autowired + private IncentiveActivityLangMappingRepo incentiveActivityLangMappingRepo; + @Autowired + private IncentivesRepo incentivesRepo; + @Autowired + private IncentiveRecordRepo recordRepo; + @Autowired + private IncentivePendingActivityRepository incentivePendingActivityRepository; + @Autowired + private UserServiceRoleRepo userRepo; ; ModelMapper modelMapper = new ModelMapper(); @@ -52,7 +60,6 @@ public class IncentiveServiceImpl implements IncentiveService { private JwtUtil jwtUtil; - @Autowired private MaaMeetingService maaMeetingService; @@ -65,6 +72,12 @@ public class IncentiveServiceImpl implements IncentiveService { @Autowired private UserService userService; + @Autowired + private EligibleCoupleRegisterRepo eligibleCoupleRegisterRepo; + + @Autowired + private IFAFormSubmissionRepository ifaFormSubmissionRepository; + // ================= MASTER SAVE ================= @Override @@ -151,10 +164,10 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { } } else { - if(isCG){ + if (isCG) { dto.setGroupName(""); - }else { + } else { dto.setGroupName(inc.getGroup()); } @@ -174,13 +187,15 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { @Override public String getAllIncentivesByUserId(GetBenRequestHandler request) { + Integer stateCode = userService.getUserDetail(request.getAshaId()).getStateId(); + String userName = userService.getUserDetail(request.getAshaId()).getUserName(); try { if (stateCode.equals(StateCode.AM.getStateCode())) { checkMonthlyAshaIncentive(request.getAshaId()); } - if(stateCode.equals(StateCode.CG.getStateCode())){ + if (stateCode.equals(StateCode.CG.getStateCode())) { checkMonthlyAshaIncentiveForCg(request.getAshaId()); } @@ -190,7 +205,7 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { } try { - + addIncentiveForIronTablets(request.getAshaId()); incentiveOfNcdReferal(request.getAshaId(), request.getVillageID()); } catch (Exception e) { @@ -253,18 +268,18 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { } else { entry.setName(""); } - if(entry.getVerifiedByUserId()!=null){ + if (entry.getVerifiedByUserId() != null) { entry.setSupervisorRole(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getRoleName()); entry.setVerifiedByUserName(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getName()); } - if(entry.getAshaId()!=null){ + if (entry.getAshaId() != null) { if (entry.getCreatedBy() == null) { - entry.setCreatedBy(userRepo.getUserNamedByUserId(entry.getAshaId())); + entry.setCreatedBy(userName); } if (entry.getUpdatedBy() == null) { - entry.setUpdatedBy(userRepo.getUserNamedByUserId(entry.getAshaId())); + entry.setUpdatedBy(userName); } if (entry.getIsEligible() == null) { @@ -429,6 +444,7 @@ public String getAllIncentivesGroupedActivity(GetBenRequestHandler request) { return null; } } + @Override public String updateIncentive(PendingActivityDTO pendingActivityDTO) { try { @@ -504,7 +520,6 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { } - // ================= UPDATE CLAIM ================= @Transactional public String updateClaimStatus(Integer ashaId, Integer month, Integer year, Boolean isClaimed, String token) { @@ -538,7 +553,7 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { List.of("NCD_POP_ENUMERATION", "NCD_FOLLOWUP_TREATMENT"), groupName ).stream().collect(Collectors.toMap(IncentiveActivity::getName, Function.identity())); - IncentiveActivity ncdPopEnumeration = activityMap.get("NCD_POP_ENUMERATION"); + IncentiveActivity ncdPopEnumeration = activityMap.get("NCD_POP_ENUMERATION"); CompletableFuture> benReferFuture = CompletableFuture.supplyAsync(() -> benReferDetailsRepo.findByCreatedBy(userName)); @@ -550,7 +565,6 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { List recordsToSave = new ArrayList<>(); - if (ncdPopEnumeration != null && !cbacDetailsImer.isEmpty()) { List cbacBenIds = cbacDetailsImer.stream() .filter(c -> c != null && c.getBeneficiaryRegId() != null) @@ -620,15 +634,15 @@ private void checkMonthlyAshaIncentive(Integer ashaId) { IncentiveActivity ADDITIONAL_ASHA_INCENTIVE = incentivesRepo.findIncentiveMasterByNameAndGroup("ADDITIONAL_ASHA_INCENTIVE", GroupName.ADDITIONAL_INCENTIVE.getDisplayName()); IncentiveActivity ASHA_MONTHLY_ROUTINE = incentivesRepo.findIncentiveMasterByNameAndGroup("ASHA_MONTHLY_ROUTINE", GroupName.ASHA_MONTHLY_ROUTINE.getDisplayName()); if (MOBILEBILLREIMB_ACTIVITY != null) { - addMonthlyAshaIncentiveRecord(MOBILEBILLREIMB_ACTIVITY, ashaId,userName); + addMonthlyAshaIncentiveRecord(MOBILEBILLREIMB_ACTIVITY, ashaId, userName); } if (ADDITIONAL_ASHA_INCENTIVE != null) { - addMonthlyAshaIncentiveRecord(ADDITIONAL_ASHA_INCENTIVE, ashaId,userName); + addMonthlyAshaIncentiveRecord(ADDITIONAL_ASHA_INCENTIVE, ashaId, userName); } if (ASHA_MONTHLY_ROUTINE != null) { - addMonthlyAshaIncentiveRecord(ASHA_MONTHLY_ROUTINE, ashaId,userName); + addMonthlyAshaIncentiveRecord(ASHA_MONTHLY_ROUTINE, ashaId, userName); } } catch (Exception e) { @@ -646,15 +660,15 @@ private void checkMonthlyAshaIncentiveForCg(Integer ashaId) { IncentiveActivity MITANIN_REGISTER_5_INFO_FILL = incentivesRepo.findIncentiveMasterByNameAndGroup("MITANIN_REGISTER_5_INFO_FILL", GroupName.ACTIVITY.getDisplayName()); IncentiveActivity MITANIN_REGISTER = incentivesRepo.findIncentiveMasterByNameAndGroup("MITANIN_REGISTER", GroupName.ACTIVITY.getDisplayName()); if (MONTHLY_HONORARIUM != null) { - addMonthlyAshaIncentiveRecord(MONTHLY_HONORARIUM, ashaId,userName); + addMonthlyAshaIncentiveRecord(MONTHLY_HONORARIUM, ashaId, userName); } if (MITANIN_REGISTER_5_INFO_FILL != null) { - addMonthlyAshaIncentiveRecord(MITANIN_REGISTER_5_INFO_FILL, ashaId,userName); + addMonthlyAshaIncentiveRecord(MITANIN_REGISTER_5_INFO_FILL, ashaId, userName); } if (MITANIN_REGISTER != null) { - addMonthlyAshaIncentiveRecord(MITANIN_REGISTER, ashaId,userName); + addMonthlyAshaIncentiveRecord(MITANIN_REGISTER, ashaId, userName); } } catch (Exception e) { @@ -664,7 +678,7 @@ private void checkMonthlyAshaIncentiveForCg(Integer ashaId) { } - private void addMonthlyAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId,String userName) { + private void addMonthlyAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId, String userName) { try { Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now()); @@ -702,4 +716,83 @@ record = new IncentiveActivityRecord(); } } + + private void addIncentiveForIronTablets(Integer userId) { + IncentiveActivity incentiveActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("NATIONAL_IRON_PLUS", GroupName.CHILD_HEALTH.getDisplayName()); + IncentiveActivity incentiveActivityCG = incentivesRepo.findIncentiveMasterByNameAndGroup("NATIONAL_IRON_PLUS", GroupName.ACTIVITY.getDisplayName()); + + String userName = userService.getUserDetail(userId).getUserName(); + Integer stateId = userService.getUserDetail(userId).getStateId(); + if (userName != null) { + List eligibleCoupleRegisters = eligibleCoupleRegisterRepo.findByCreatedBy(userName); + List ifaFormSubmissionData = ifaFormSubmissionRepository.findByUserId(userId); + logger.info("eligibleCoupleRegisters :" + eligibleCoupleRegisters.size()); + logger.info("ifaFormSubmissionData :" + ifaFormSubmissionData.size()); + + if (!eligibleCoupleRegisters.isEmpty() && !ifaFormSubmissionData.isEmpty()) { + + int percentage = (int) (((double) ifaFormSubmissionData.size() + / eligibleCoupleRegisters.size()) * 100); + + logger.info("IFA Count : {}", ifaFormSubmissionData.size()); + logger.info("Eligible Couple Count : {}", eligibleCoupleRegisters.size()); + logger.info("Percentage : {}", percentage); + + if (percentage >= 50) { + + if (stateId.equals(StateCode.AM.getStateCode())) { + addIFAIncentive( + ifaFormSubmissionData.get(ifaFormSubmissionData.size() - 1), + incentiveActivityAM, + userId, + userName); + } + + if (stateId.equals(StateCode.CG.getStateCode())) { + addIFAIncentive( + ifaFormSubmissionData.get(ifaFormSubmissionData.size() - 1), + incentiveActivityCG, + userId, + userName); + } + } + } + + } + + + } + + private void addIFAIncentive(IFAFormSubmissionData ifaFormSubmissionData, IncentiveActivity incentiveActivityAM, Integer userId, String userName) { + Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now()); + + Timestamp startOfMonth = Timestamp.valueOf(LocalDate.now().withDayOfMonth(1).atStartOfDay()); + Timestamp endOfMonth = Timestamp.valueOf(LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).atTime(23, 59, 59)); + + logger.info("IFA incentive"); + IncentiveActivityRecord incentiveActivityRecord = recordRepo.findRecordByActivityIdCreatedDateBenId( + incentiveActivityAM.getId(), + startOfMonth, + endOfMonth, + 0L, + userId + ); + if (incentiveActivityRecord == null) { + incentiveActivityRecord = new IncentiveActivityRecord(); + incentiveActivityRecord.setActivityId(incentiveActivityAM.getId()); + incentiveActivityRecord.setCreatedDate(timestamp); + incentiveActivityRecord.setStartDate(timestamp); + incentiveActivityRecord.setEndDate(timestamp); + incentiveActivityRecord.setUpdatedDate(timestamp); + incentiveActivityRecord.setUpdatedBy(ifaFormSubmissionData.getUserName()); + incentiveActivityRecord.setCreatedBy(ifaFormSubmissionData.getUserName()); + incentiveActivityRecord.setBenId(0L); + incentiveActivityRecord.setAshaId(userId); + incentiveActivityRecord.setAmount(Long.valueOf(incentiveActivityAM.getRate())); + recordRepo.save(incentiveActivityRecord); + logger.info("saved IFA incentive"); + + } + } + } diff --git a/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java index 7932e134..f5ef4a09 100644 --- a/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java @@ -47,11 +47,6 @@ public Boolean saveFollowUp(MalariaFollowUpDTO malariaFollowUpDTO,String token) return false; } - if (dto.getReferralDate() != null && - dto.getReferralDate().before(dto.getTreatmentStartDate())) { - return false; - } - dto.setUserId(jwtUtil.extractUserId(token)); MalariaFollowUp entity = new MalariaFollowUp(); @@ -63,7 +58,8 @@ public Boolean saveFollowUp(MalariaFollowUpDTO malariaFollowUpDTO,String token) new Timestamp(entity.getTreatmentStartDate().getTime()), new Timestamp(entity.getTreatmentCompletionDate().getTime()), entity.getUserId() - ); } + ); + } return true; } diff --git a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java index ce7bc1d1..3813df54 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -5,6 +5,7 @@ import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; import com.iemr.flw.masterEnum.GroupName; +import com.iemr.flw.masterEnum.StateCode; import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.IncentiveLogicService; @@ -145,7 +146,7 @@ public List getANCVisits(GetBenRequestHandler dto) { .map(anc -> mapper.convertValue(anc, ANCVisitDTO.class)) .collect(Collectors.toList()); } catch (Exception e) { - logger.error(e.getMessage()); + logger.error("ANC VISIT :---------------------"+e.getMessage()); } return null; } @@ -162,10 +163,14 @@ public String saveANCVisit(List ancVisitDTOs, Integer userId) { ancVisitDTOs.forEach(it -> { logger.info("Processing Beneficiary Id: {} ANC Visit: {}", it.getBenId(), it.getAncVisit()); + logger.info("Processing Beneficiary Id: {} ANC Visit: {}", it.getBenId(), it.getIsPaiucdId()); - ANCVisit ancVisit = + List ancVisitList = ancVisitRepo.findANCVisitByBenIdAndAncVisitAndIsActive(it.getBenId(), it.getAncVisit(), true); - + ANCVisit ancVisit = new ANCVisit(); + if(!ancVisitList.isEmpty()){ + ancVisit = ancVisitList.get(0); + } logger.info("ANC visit fetch completed"); if (ancVisit != null) { @@ -307,6 +312,7 @@ public String savePmsmaRecords(List pmsmaDTOs) { }); pmsmaRepo.saveAll(pmsmaList); logger.info("PMSMA details saved"); + checkAndAddHighRisk(pmsmaList); return "No. of PMSMA records saved: " + pmsmaList.size(); @@ -435,6 +441,8 @@ public String savePNCVisit(List pncVisitDTOs) { @Override @Transactional public String saveANCVisitQuestions(List dtos, String authorization) throws IEMRException { + Integer userId = jwtUtil.extractUserId(authorization); + String userName = userRepo.getUserNamedByUserId(userId); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); List entities = new ArrayList<>(); @@ -495,9 +503,9 @@ public String saveANCVisitQuestions(List dtos, String aut entity.setProlongedLabor(yesNoToBoolean(fields.getProlongedLabor())); entity.setMalpresentation(yesNoToBoolean(fields.getMalpresentation())); - entity.setUserId(jwtUtil.extractUserId(authorization)); - entity.setCreatedBy(userRepo.getUserNamedByUserId(jwtUtil.extractUserId(authorization))); - entity.setUpdatedBy(userRepo.getUserNamedByUserId(jwtUtil.extractUserId(authorization))); + entity.setUserId(userId); + entity.setCreatedBy(userName); + entity.setUpdatedBy(userName); entities.add(entity); } @@ -576,96 +584,118 @@ private Boolean yesNoToBoolean(String value) { private void checkAndAddAntaraIncentive(List recordList, PNCVisit ect) { Integer userId = userRepo.getUserIdByName(ect.getCreatedBy()); + Integer stateId = userRepo.getUserRole(userId).get(0).getStateId(); logger.info("ContraceptionMethod:" + ect.getContraceptionMethod()); - if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("MALE STERILIZATION")) { + // logic for assam + if(stateId.equals(StateCode.AM.getStateCode())){ + if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("MALE STERILIZATION")) { - IncentiveActivity maleSterilizationActivityAM = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MALE_STER", GroupName.FAMILY_PLANNING.getDisplayName()); + IncentiveActivity maleSterilizationActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MALE_STER", GroupName.FAMILY_PLANNING.getDisplayName()); - IncentiveActivity maleSterilizationActivityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MALE_STER", GroupName.ACTIVITY.getDisplayName()); - if (maleSterilizationActivityAM != null) { - addIncenticeRecord(recordList, ect, userId, maleSterilizationActivityAM); - } - if (maleSterilizationActivityCH != null) { - addIncenticeRecord(recordList, ect, userId, maleSterilizationActivityCH); - } + if (maleSterilizationActivityAM != null) { + addIncenticeRecord(ect, userId, maleSterilizationActivityAM); + } - } else if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("FEMALE STERILIZATION")) { - IncentiveActivity femaleSterilizationActivityAM = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.FAMILY_PLANNING.getDisplayName()); + } + if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("FEMALE STERILIZATION")) { + + IncentiveActivity femaleSterilizationActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.FAMILY_PLANNING.getDisplayName()); + if (femaleSterilizationActivityAM != null) { + addIncenticeRecord(ect, userId, femaleSterilizationActivityAM); + } - IncentiveActivity femaleSterilizationActivityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.ACTIVITY.getDisplayName()); - if (femaleSterilizationActivityAM != null) { - addIncenticeRecord(recordList, ect, userId, femaleSterilizationActivityAM); } + if (ect.getContraceptionMethod() != null && (ect.getContraceptionMethod().equals("MiniLap") || ect.getContraceptionMethod().equals("POST PARTUM STERILIZATION (PPS)"))) { - if (femaleSterilizationActivityCH != null) { - addIncenticeRecord(recordList, ect, userId, femaleSterilizationActivityCH); + IncentiveActivity miniLapActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPS", GroupName.FAMILY_PLANNING.getDisplayName()); + if (miniLapActivity != null) { + addIncenticeRecord(ect, userId, miniLapActivity); + } } - } else if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("MiniLap")) { + if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("Condom")) { - IncentiveActivity miniLapActivity = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MINILAP", GroupName.FAMILY_PLANNING.getDisplayName()); - if (miniLapActivity != null) { - addIncenticeRecord(recordList, ect, userId, miniLapActivity); + IncentiveActivity comdomActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_CONDOM", GroupName.FAMILY_PLANNING.getDisplayName()); + if (comdomActivity != null) { + addIncenticeRecord(ect, userId, comdomActivity); + } } - } else if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("Condom")) { + if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("POST PARTUM IUCD (PPIUCD) WITHIN 48 HRS OF DELIVERY")) { + + IncentiveActivity PPIUCDActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPIUCD", GroupName.FAMILY_PLANNING.getDisplayName()); + + if (PPIUCDActivityAM != null) { + addIncenticeRecord(ect, userId, PPIUCDActivityAM); + } - IncentiveActivity comdomActivity = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_CONDOM", GroupName.FAMILY_PLANNING.getDisplayName()); - if (comdomActivity != null) { - addIncenticeRecord(recordList, ect, userId, comdomActivity); } - } else if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("POST PARTUM IUCD (PPIUCD) WITHIN 48 HRS OF DELIVERY")) { - IncentiveActivity PPIUCDActivityAM = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPIUCD", GroupName.FAMILY_PLANNING.getDisplayName()); + } + // logic for cg + if(stateId.equals(StateCode.CG.getStateCode())){ IncentiveActivity PPIUCDActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPIUCD", GroupName.ACTIVITY.getDisplayName()); - if (PPIUCDActivityAM != null) { - addIncenticeRecord(recordList, ect, userId, PPIUCDActivityAM); - } + if (PPIUCDActivityCH != null) { - addIncenticeRecord(recordList, ect, userId, PPIUCDActivityCH); + addIncenticeRecord(ect, userId, PPIUCDActivityCH); } - } else if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("POST PARTUM STERILIZATION (PPS)")) { - IncentiveActivity ppsActivityAM = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPS", GroupName.FAMILY_PLANNING.getDisplayName()); + IncentiveActivity femaleSterilizationActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.ACTIVITY.getDisplayName()); - IncentiveActivity ppsActivityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPS", GroupName.ACTIVITY.getDisplayName()); - if (ppsActivityAM != null) { - addIncenticeRecord(recordList, ect, userId, ppsActivityAM); + + if (femaleSterilizationActivityCH != null) { + addIncenticeRecord(ect, userId, femaleSterilizationActivityCH); } - if (ppsActivityCH != null) { - addIncenticeRecord(recordList, ect, userId, ppsActivityCH); + IncentiveActivity maleSterilizationActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MALE_STER", GroupName.ACTIVITY.getDisplayName()); + + if (maleSterilizationActivityCH != null) { + addIncenticeRecord(ect, userId, maleSterilizationActivityCH); } - } - if (ect.getMotherDangerSign() != null - && !ect.getMotherDangerSign().isEmpty() - && ect.getPncPeriod() == 7) { - IncentiveActivity highRiskPostpartumCareActivityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); - if (highRiskPostpartumCareActivityCH != null) { - addIncenticeRecord(recordList, ect, userId, highRiskPostpartumCareActivityCH); + if (ect.getMotherDangerSign() != null + && !ect.getMotherDangerSign().isEmpty() + && ect.getPncPeriod() == 7) { + + IncentiveActivity highRiskPostpartumCareActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); + if (highRiskPostpartumCareActivityCH != null) { + addIncenticeRecord(ect, userId, highRiskPostpartumCareActivityCH); + + } } + if (ect.getPncPeriod() == 1 || ect.getPncPeriod() == 3 || ect.getPncPeriod() == 7) { + if ((ect.getContraceptionMethod().equals("POST PARTUM STERILIZATION (PPS)") + || ect.getContraceptionMethod().equals("MiniLap")) + && ect.getSterilisationDate() != null) { + IncentiveActivity ppsActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPS", GroupName.ACTIVITY.getDisplayName()); + if (ppsActivityCH != null) { + + addIncenticeRecord(ect, userId, ppsActivityCH); + + } + } + } } + } - private void addIncenticeRecord(List recordList, PNCVisit ect, Integer userId, IncentiveActivity antaraActivity) { + private void addIncenticeRecord(PNCVisit ect, Integer userId, IncentiveActivity antaraActivity) { IncentiveActivityRecord record = recordRepo .findRecordByActivityIdCreatedDateBenId(antaraActivity.getId(), ect.getCreatedDate(), ect.getBenId()); // get bene details @@ -691,100 +721,98 @@ private void checkAndAddIncentives(List ancList, Integer userId) { Integer stateId = userRepo.getUserRole(userId).get(0).getStateId(); - IncentiveActivity anc1Activity = null; - IncentiveActivity ancFullActivityAM = null; - IncentiveActivity identifiedHrpActivityAM = null; - IncentiveActivity comprehensiveAbortionActivityAM = null; - IncentiveActivity paiucdActivityAM = null; - - IncentiveActivity ancFullActivityCH = null; - IncentiveActivity comprehensiveAbortionActivityCH = null; - IncentiveActivity identifiedHrpActivityCH = null; - IncentiveActivity paiucdActivityCH = null; // ✅ State 5 — Assam if (stateId.equals(5)) { - anc1Activity = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity anc1Activity = incentivesRepo.findIncentiveMasterByNameAndGroup( "ANC_REGISTRATION_1ST_TRIM", GroupName.MATERNAL_HEALTH.getDisplayName()); - ancFullActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity ancFullActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( "FULL_ANC", GroupName.MATERNAL_HEALTH.getDisplayName()); - identifiedHrpActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( - "EPMSMA_HRP_IDENTIFIED", GroupName.MATERNAL_HEALTH.getDisplayName()); - comprehensiveAbortionActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity identifiedHrpActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("EPMSMA_HRP_IDENTIFIED", GroupName.MATERNAL_HEALTH.getDisplayName()); + IncentiveActivity comprehensiveAbortionActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( "COMPREHENSIVE_ABORTION_CARE", GroupName.MATERNAL_HEALTH.getDisplayName()); - paiucdActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity paiucdActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( "FP_PAIUCD", GroupName.FAMILY_PLANNING.getDisplayName()); + + ancList.forEach(ancVisit -> { + + if (paiucdActivityAM != null && ancVisit.getIsPaiucdId() != null + && ancVisit.getIsPaiucdId().toString().equals("1")) { + recordAncRelatedIncentive(paiucdActivityAM, ancVisit); + } + + + + if (anc1Activity != null && ancVisit.getAncVisit() != null + && ancVisit.getAncVisit() == 1) { + recordAncFirstTRIMIncentive(anc1Activity, ancVisit); + } + + if (ancFullActivityAM != null && ancVisit.getAncVisit() != null + && ancVisit.getAncVisit() == 4) { + recordFullAncIncentive(ancFullActivityAM, ancVisit); + } + + + if (comprehensiveAbortionActivityAM != null && ancVisit.getIsAborted() != null + && ancVisit.getIsAborted()) { + recordAncRelatedIncentive(comprehensiveAbortionActivityAM, ancVisit); + } + + + if (identifiedHrpActivityAM != null && ancVisit.getIsHrpConfirmed() != null + && ancVisit.getIsHrpConfirmed()) { + recordAncRelatedIncentive(identifiedHrpActivityAM, ancVisit); + } + + + }); } // ✅ State 8 if (stateId.equals(8)) { - ancFullActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( + + IncentiveActivity ancFullActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( "ANC_FOUR_CHECKUPS_SUPPORT", GroupName.ACTIVITY.getDisplayName()); - comprehensiveAbortionActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity comprehensiveAbortionActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( "COMPREHENSIVE_ABORTION_CARE", GroupName.ACTIVITY.getDisplayName()); - identifiedHrpActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity identifiedHrpActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( "EPMSMA_HRP_IDENTIFIED", GroupName.ACTIVITY.getDisplayName()); - paiucdActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity paiucdActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( "FP_PAIUCD", GroupName.ACTIVITY.getDisplayName()); - } - final IncentiveActivity finalAnc1Activity = anc1Activity; - final IncentiveActivity finalAncFullActivityAM = ancFullActivityAM; - final IncentiveActivity finalIdentifiedHrpActivityAM = identifiedHrpActivityAM; - final IncentiveActivity finalComprehensiveAbortionActivityAM = comprehensiveAbortionActivityAM; - final IncentiveActivity finalPaiucdActivityAM = paiucdActivityAM; - final IncentiveActivity finalAncFullActivityCH = ancFullActivityCH; - final IncentiveActivity finalComprehensiveAbortionActivityCH = comprehensiveAbortionActivityCH; - final IncentiveActivity finalIdentifiedHrpActivityCH = identifiedHrpActivityCH; - final IncentiveActivity finalPaiucdActivityCH = paiucdActivityCH; - - ancList.forEach(ancVisit -> { - - if (finalPaiucdActivityAM != null && ancVisit.getIsPaiucd() != null - && ancVisit.getIsPaiucd().equals("Yes")) { - recordAncRelatedIncentive(finalPaiucdActivityAM, ancVisit); - } + ancList.forEach(ancVisit -> { - if (finalPaiucdActivityCH != null && ancVisit.getIsPaiucd() != null - && ancVisit.getIsPaiucd().equals("Yes")) { - recordAncRelatedIncentive(finalPaiucdActivityCH, ancVisit); - } - if (finalAnc1Activity != null && ancVisit.getAncVisit() != null - && ancVisit.getAncVisit() == 1) { - recordAncFirstTRIMIncentive(finalAnc1Activity, ancVisit); - } + if (paiucdActivityCH != null && ancVisit.getIsPaiucdId() != null + && ancVisit.getIsPaiucdId().toString().equals("1")) { + recordAncRelatedIncentive(paiucdActivityCH, ancVisit); + } - if (finalAncFullActivityAM != null && ancVisit.getAncVisit() != null - && ancVisit.getAncVisit() == 4) { - recordFullAncIncentive(finalAncFullActivityAM, ancVisit); - } - if (finalAncFullActivityCH != null && ancVisit.getAncVisit() != null - && ancVisit.getAncVisit() == 4) { - recordAncRelatedIncentive(finalAncFullActivityCH, ancVisit); - } - if (finalComprehensiveAbortionActivityAM != null && ancVisit.getIsAborted() != null - && ancVisit.getIsAborted()) { - recordAncRelatedIncentive(finalComprehensiveAbortionActivityAM, ancVisit); - } + if (ancFullActivityCH != null && ancVisit.getAncVisit() != null + && ancVisit.getAncVisit() == 4) { + recordAncRelatedIncentive(ancFullActivityCH, ancVisit); + } + + + + if (comprehensiveAbortionActivityCH != null && ancVisit.getIsAborted() != null + && ancVisit.getIsAborted()) { + recordAncRelatedIncentive(comprehensiveAbortionActivityCH, ancVisit); + } + + + if (identifiedHrpActivityCH != null && ancVisit.getIsHrpConfirmed() != null + && ancVisit.getIsHrpConfirmed()) { + recordAncRelatedIncentive(identifiedHrpActivityCH, ancVisit); + } + }); + } - if (finalComprehensiveAbortionActivityCH != null && ancVisit.getIsAborted() != null - && ancVisit.getIsAborted()) { - recordAncRelatedIncentive(finalComprehensiveAbortionActivityCH, ancVisit); - } - if (finalIdentifiedHrpActivityAM != null && ancVisit.getIsHrpConfirmed() != null - && ancVisit.getIsHrpConfirmed()) { - recordAncRelatedIncentive(finalIdentifiedHrpActivityAM, ancVisit); - } - if (finalIdentifiedHrpActivityCH != null && ancVisit.getIsHrpConfirmed() != null - && ancVisit.getIsHrpConfirmed()) { - recordAncRelatedIncentive(finalIdentifiedHrpActivityCH, ancVisit); - } - }); } private void recordAncRelatedIncentive(IncentiveActivity incentiveActivity, ANCVisit ancVisit) { diff --git a/src/main/java/com/iemr/flw/service/impl/SammelanServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SammelanServiceImpl.java index b9d035a7..e0460fe8 100644 --- a/src/main/java/com/iemr/flw/service/impl/SammelanServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SammelanServiceImpl.java @@ -121,17 +121,18 @@ private void checkIncentive(SammelanRecord record) { } private void addSammelanIncentive(IncentiveActivity incentiveActivity, SammelanRecord record) { + String userName = userRepo.getUserNamedByUserId(record.getAshaId()); IncentiveActivityRecord incentiveActivityRecord = incentiveRecordRepo.findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), record.getMeetingDate(), 0L, record.getAshaId()); try { if (incentiveActivityRecord == null) { incentiveActivityRecord = new IncentiveActivityRecord(); incentiveActivityRecord.setActivityId(incentiveActivity.getId()); incentiveActivityRecord.setCreatedDate(record.getMeetingDate()); - incentiveActivityRecord.setCreatedBy(userRepo.getUserNamedByUserId(record.getAshaId())); + incentiveActivityRecord.setCreatedBy(userName); incentiveActivityRecord.setStartDate(record.getMeetingDate()); incentiveActivityRecord.setEndDate(record.getMeetingDate()); incentiveActivityRecord.setUpdatedDate(record.getMeetingDate()); - incentiveActivityRecord.setUpdatedBy(userRepo.getUserNamedByUserId(record.getAshaId())); + incentiveActivityRecord.setUpdatedBy(userName); incentiveActivityRecord.setBenId(0L); incentiveActivityRecord.setAshaId(record.getAshaId()); incentiveActivityRecord.setAmount(Long.valueOf(incentiveActivity.getRate())); diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index c1850f38..771810e2 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -15,6 +15,7 @@ import com.iemr.flw.dto.iemr.UserServiceRoleDTO; import com.iemr.flw.masterEnum.IncentiveApprovalStatus; import com.iemr.flw.repo.iemr.*; +import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; import org.json.JSONArray; import org.json.JSONObject; @@ -47,7 +48,7 @@ public class SupervisorDashboardServiceImpl implements SupervisorDashboardServic private JwtUtil jwtUtil; @Autowired - private UserServiceRoleRepo userServiceRoleRepo; + private UserService userService; @Override public String getSupervisorDashboard(Integer supervisorUserID, Integer month, Integer year) { @@ -116,6 +117,8 @@ public String getSupervisorDashboard(Integer supervisorUserID, Integer month, In // 5. Get incentive status per ASHA (verified, rejected, pending, totalAmount) long overallVerified = 0, overallRejected = 0, overallPending = 0; + long overallUnclaimed = 0; + try { logger.info("Month: {}", month); logger.info("Year: {}", year); @@ -142,16 +145,26 @@ public String getSupervisorDashboard(Integer supervisorUserID, Integer month, In if (pending > 0) overallPending += 1; } } + List unclaimedRows = dashboardRepo.getUnclaimedCountByAshaIds(ashaIDs, startDate, endDate); + if (unclaimedRows != null) { + for (Object[] uRow : unclaimedRows) { + long count = ((Number) uRow[1]).longValue(); + if (count > 0) overallUnclaimed += 1; + } + } } catch (Exception e) { logger.error("Error fetching incentive status: " + e.getMessage(), e); } + + // Overall incentive summary across all ASHAs JSONObject overallSummary = new JSONObject(); overallSummary.put("verified", overallVerified); overallSummary.put("rejected", overallRejected); overallSummary.put("pending", overallPending); overallSummary.put("overDue", 0); + overallSummary.put("unclaimed", overallUnclaimed); result.put("incentiveSummary", overallSummary); // 7. Build facilities array with nested ASHAs @@ -249,8 +262,8 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci List countList = incentiveRecordRepo.getStatusCountByAshaId(ashaId, startDate, endDate); Long totalAmount = null; - if (userServiceRoleRepo.getUserNamedByUserId(ashaId) != null) { - Integer stateCode = userServiceRoleRepo.getUserRole(ashaId).get(0).getStateId(); + if (userService.getUserDetail(ashaId) != null) { + Integer stateCode = userService.getUserDetail(ashaId).getStateId(); totalAmount = incentiveRecordRepo.getTotalAmountByAsha( ashaId, startDate, endDate, approvalStatusID, stateCode); @@ -271,15 +284,15 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci activity.put("approvalDate", record.getApprovalDate()); activity.put("approvalStatus", record.getApprovalStatus()); if(record.getVerifiedByUserId()!=null){ - activity.put("verifiedByUserName", userServiceRoleRepo.getUserRole(record.getVerifiedByUserId()).get(0).getName()); + activity.put("verifiedByUserName", userService.getUserDetail(record.getVerifiedByUserId()).getName()); } activity.put("verifiedByUserId", record.getVerifiedByUserId()); activity.put("isClaimed", record.getIsClaimed()); activity.put("claimedDate", record.getCalimedDate()); - List roles = userServiceRoleRepo.getUserRole(record.getVerifiedByUserId()); - activity.put("role", (roles != null && !roles.isEmpty()) ? roles.get(0).getRoleName() : null); + UserServiceRoleDTO roles = userService.getUserDetail(record.getVerifiedByUserId()); + activity.put("role", (roles != null ) ? roles.getRoleName() : null); activityList.add(activity); } @@ -370,7 +383,8 @@ public int updateApprovalStatus(Integer ashaId, Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); Integer ashaSupervisorUserId = jwtUtil.extractUserId(token); - String ashaSupervisorUsername = userServiceRoleRepo.getUserNamedByUserId(ashaSupervisorUserId); + logger.info("Asha Supervisor User Id : {}", ashaSupervisorUserId); + String ashaSupervisorUsername = userService.getUserDetail(ashaSupervisorUserId).getUserName(); if (approvalStatus.equals(IncentiveApprovalStatus.REJECTED.getCode())) { int totalUpdated = 0; diff --git a/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java index 1b972be6..2a8c0eeb 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java @@ -7,6 +7,7 @@ import com.iemr.flw.dto.iemr.TBSuspectedDTO; import com.iemr.flw.dto.iemr.TBSuspectedRequestDTO; import com.iemr.flw.repo.iemr.TBSuspectedRepo; +import com.iemr.flw.service.IncentiveLogicService; import com.iemr.flw.service.TBSuspectedService; import org.modelmapper.ModelMapper; import org.slf4j.Logger; @@ -25,6 +26,9 @@ public class TBSuspectedServiceImpl implements TBSuspectedService { @Autowired private TBSuspectedRepo tbSuspectedRepo; + @Autowired + private IncentiveLogicService incentiveLogicService; + @Override public String getByBenId(Long benId, String authorisation) throws Exception { return null; @@ -49,6 +53,14 @@ public String save(TBSuspectedRequestDTO requestDTO) throws Exception { tbSuspected.setUserId(requestDTO.getUserId()); tbSuspectedRepo.save(tbSuspected); + if(tbSuspected!=null){ + if(tbSuspected.getIsConfirmed()){ + incentiveLogicService.incentiveForTbSuspected(tbSuspected.getBenId(),tbSuspected.getVisitDate(),tbSuspected.getVisitDate(),tbSuspected.getUserId()); + + } + + } + }); return "no of tb suspected items saved:" + requestDTO.getTbSuspectedList().size(); } @@ -57,7 +69,18 @@ public String save(TBSuspectedRequestDTO requestDTO) throws Exception { public String getByUserId(GetBenRequestHandler request) { List dtos = new ArrayList<>(); List tbSuspectedList = tbSuspectedRepo.getByUserId(request.getAshaId(), request.getFromDate(), request.getToDate()); - tbSuspectedList.forEach(tbSuspected -> dtos.add(modelMapper.map(tbSuspected, TBSuspectedDTO.class))); + tbSuspectedList.forEach(tbSuspected -> { + dtos.add(modelMapper.map(tbSuspected, TBSuspectedDTO.class)); + + if (tbSuspected != null && Boolean.TRUE.equals(tbSuspected.getIsConfirmed())) { + incentiveLogicService.incentiveForTbSuspected( + tbSuspected.getBenId(), + tbSuspected.getVisitDate(), + tbSuspected.getVisitDate(), + tbSuspected.getUserId() + ); + } + }); TBSuspectedRequestDTO tbSuspectedRequestDTO = new TBSuspectedRequestDTO(); tbSuspectedRequestDTO.setTbSuspectedList(dtos); tbSuspectedRequestDTO.setUserId(request.getAshaId()); diff --git a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java index eadfa4ee..d91d0c6f 100644 --- a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java @@ -107,6 +107,7 @@ public UwinSessionResponseDTO saveSession(UwinSessionRequestDTO req) throws Exce dto.setParticipants(session.getParticipants()); dto.setAttachments(Collections.singletonList(session.getAttachmentsJson())); + return dto; } @Override @@ -137,8 +138,6 @@ public UwinSession updateSession(UwinSessionRequestDTO req, Long recordId, Long String imagesJson = objectMapper.writeValueAsString(base64Images); session.setAttachmentsJson(imagesJson); - // Trigger incentive update if attachments exist - updateIncentivePendindDocService.updateIncentive(activityId); } repo.save(session); // ✅ Save updated session diff --git a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java index 579b84c9..4519bc62 100644 --- a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java @@ -226,20 +226,64 @@ private Boolean saveVhndFormData(VHNDFormDTO vhndFormDTO, Integer userID) { VHNDForm vhndForm = new VHNDForm(); vhndForm.setUserId(userID); vhndForm.setVhndDate(vhndFormDTO.getVhndDate()); - vhndForm.setImage2(vhndFormDTO.getImage2()); - vhndForm.setImage1(vhndFormDTO.getImage1()); - vhndForm.setPlace(vhndFormDTO.getPlace()); - vhndForm.setNoOfBeneficiariesAttended(vhndFormDTO.getNoOfBeneficiariesAttended()); - vhndForm.setPregnantWomenAnc(vhndFormDTO.getPregnantWomenAnc()); - vhndForm.setLactatingMothersPnc(vhndFormDTO.getLactatingMothersPnc()); - vhndForm.setChildrenImmunization(vhndFormDTO.getChildrenImmunization()); - vhndForm.setSelectAllEducation(vhndFormDTO.getSelectAllEducation()); - vhndForm.setKnowledgeBalancedDiet(vhndFormDTO.getKnowledgeBalancedDiet()); - vhndForm.setCareDuringPregnancy(vhndFormDTO.getCareDuringPregnancy()); - vhndForm.setImportanceBreastfeeding(vhndFormDTO.getImportanceBreastfeeding()); - vhndForm.setComplementaryFeeding(vhndFormDTO.getComplementaryFeeding()); - vhndForm.setHygieneSanitation(vhndFormDTO.getHygieneSanitation()); - vhndForm.setFamilyPlanningHealthcare(vhndFormDTO.getFamilyPlanningHealthcare()); + vhndForm.setImage2(vhndFormDTO.getImage2() != null ? vhndFormDTO.getImage2() : ""); + vhndForm.setImage1(vhndFormDTO.getImage1() != null ? vhndFormDTO.getImage1() : ""); + vhndForm.setPlace(vhndFormDTO.getPlace() != null ? vhndFormDTO.getPlace() : ""); + + vhndForm.setNoOfBeneficiariesAttended( + vhndFormDTO.getNoOfBeneficiariesAttended() != null + ? vhndFormDTO.getNoOfBeneficiariesAttended() + : 0); + + vhndForm.setPregnantWomenAnc( + vhndFormDTO.getPregnantWomenAnc() != null + ? vhndFormDTO.getPregnantWomenAnc() + : null); + + vhndForm.setLactatingMothersPnc( + vhndFormDTO.getLactatingMothersPnc() != null + ? vhndFormDTO.getLactatingMothersPnc() + : null); + + vhndForm.setChildrenImmunization( + vhndFormDTO.getChildrenImmunization() != null + ? vhndFormDTO.getChildrenImmunization() + : null); + + vhndForm.setSelectAllEducation( + vhndFormDTO.getSelectAllEducation() != null + ? vhndFormDTO.getSelectAllEducation() + : false); + + vhndForm.setKnowledgeBalancedDiet( + vhndFormDTO.getKnowledgeBalancedDiet() != null + ? vhndFormDTO.getKnowledgeBalancedDiet() + : null); + + vhndForm.setCareDuringPregnancy( + vhndFormDTO.getCareDuringPregnancy() != null + ? vhndFormDTO.getCareDuringPregnancy() + : null); + + vhndForm.setImportanceBreastfeeding( + vhndFormDTO.getImportanceBreastfeeding() != null + ? vhndFormDTO.getImportanceBreastfeeding() + : null); + + vhndForm.setComplementaryFeeding( + vhndFormDTO.getComplementaryFeeding() != null + ? vhndFormDTO.getComplementaryFeeding() + : null); + + vhndForm.setHygieneSanitation( + vhndFormDTO.getHygieneSanitation() != null + ? vhndFormDTO.getHygieneSanitation() + : null); + + vhndForm.setFamilyPlanningHealthcare( + vhndFormDTO.getFamilyPlanningHealthcare() != null + ? vhndFormDTO.getFamilyPlanningHealthcare() + : null); vhndForm.setFormType("VHND"); vhndRepo.save(vhndForm); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); @@ -248,6 +292,7 @@ private Boolean saveVhndFormData(VHNDFormDTO vhndFormDTO, Integer userID) { Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); incentiveLogicService.incentiveForVhndMeeting(0L,date,date,vhndForm.getUserId()); + return true; @@ -288,6 +333,8 @@ public List getAll(GetVillageLevelRequestHandler getVillageLev private void checkAndAddIncentives(String date, Integer userID, String formType, String createdBY) { + String userName = userRepo.getUserNamedByUserId(userID); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); // Parse to LocalDate @@ -309,11 +356,11 @@ private void checkAndAddIncentives(String date, Integer userID, String formType, record = new IncentiveActivityRecord(); record.setActivityId(villageFormEntryActivityAM.getId()); record.setCreatedDate(timestamp); - record.setCreatedBy(userRepo.getUserNamedByUserId(userID)); + record.setCreatedBy(userName); record.setStartDate(timestamp); record.setEndDate(timestamp); record.setUpdatedDate(timestamp); - record.setUpdatedBy(userRepo.getUserNamedByUserId(userID)); + record.setUpdatedBy(userName); record.setAshaId(userID); record.setBenId(0L); record.setAmount(Long.valueOf(villageFormEntryActivityAM.getRate())); @@ -321,7 +368,6 @@ record = new IncentiveActivityRecord(); } } - if (villageFormEntryActivityCH != null) { IncentiveActivityRecord record = recordRepo .findRecordByActivityIdCreatedDateBenId(villageFormEntryActivityCH.getId(), timestamp, 0L,userID); @@ -329,12 +375,12 @@ record = new IncentiveActivityRecord(); record = new IncentiveActivityRecord(); record.setActivityId(villageFormEntryActivityCH.getId()); record.setCreatedDate(timestamp); - record.setCreatedBy(userRepo.getUserNamedByUserId(userID)); + record.setCreatedBy(userName); record.setStartDate(timestamp); record.setEndDate(timestamp); record.setBenId(0L); record.setUpdatedDate(timestamp); - record.setUpdatedBy(userRepo.getUserNamedByUserId(userID)); + record.setUpdatedBy(userName); record.setAshaId(userID); record.setAmount(Long.valueOf(villageFormEntryActivityCH.getRate())); recordRepo.save(record);