diff --git a/src/main/java/com/iemr/common/identity/controller/IdentityController.java b/src/main/java/com/iemr/common/identity/controller/IdentityController.java index d9ed288c..2482ac47 100644 --- a/src/main/java/com/iemr/common/identity/controller/IdentityController.java +++ b/src/main/java/com/iemr/common/identity/controller/IdentityController.java @@ -30,10 +30,13 @@ import java.util.List; import java.util.Objects; +import com.iemr.common.identity.data.rmnch.RMNCHBeneficiaryDetailsRmnch; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -315,6 +318,17 @@ public String searchBeneficiaryByVillageIdAndLastModDate( } return response; } + + + @PostMapping("/getRmnchDataByBenRedID") + public ResponseEntity getRmnchDataByBenID(@RequestBody BigInteger object) { + try { + RMNCHBeneficiaryDetailsRmnch data = svc.getRmnchDataByBenID(object); + return ResponseEntity.ok(data); + } catch (Exception e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); + } + } // search beneficiary by lastModDate and districtID @Operation(summary ="Get count of beneficiary by villageId and last modified date-time") @PostMapping(path = "/countBenByVillageIdAndLastModifiedDate") @@ -593,7 +607,6 @@ public String createIdentity(@Param(value = "{\r\n" + " \"eventTypeName\": \"St + " \"sexualOrientationType\": \"String\",\r\n" + " \"vanID\": \"Integer\",\r\n" + " \"createdDate\": \"Timestamp\"\r\n" + " \"faceEmbedding\": [\"Float\"]\r\n" + "}") @RequestBody String identityData) throws IEMRException { logger.info("IdentityController.createIdentity - start"); - System.out.println("[TRACE][Identity-API] /id/create raw request body : " + identityData); // Bare Gson matches Common-API's RegisterBenificiaryServiceImpl, which also // serializes the outgoing identity payload with a bare new Gson(). dob relies @@ -602,10 +615,8 @@ public String createIdentity(@Param(value = "{\r\n" + " \"eventTypeName\": \"St // works regardless of which Gson instance performs the parse. IdentityDTO identity = new Gson().fromJson(identityData, IdentityDTO.class); logger.info("identity hit: " + identity); - System.out.println("[TRACE][Identity-API] /id/create parsed IdentityDTO : " + identity); BeneficiaryCreateResp map; map = svc.createIdentity(identity); - System.out.println("[TRACE][Identity-API] /id/create svc.createIdentity result : " + InputMapper.getInstance().gson().toJson(map)); String data = InputMapper.getInstance().gson().toJson(map); String response = getSuccessResponseString(data, 200, "success", "createIdentityByAgent"); diff --git a/src/main/java/com/iemr/common/identity/controller/rmnch/RMNCHMobileAppController.java b/src/main/java/com/iemr/common/identity/controller/rmnch/RMNCHMobileAppController.java index df7487b8..deada381 100644 --- a/src/main/java/com/iemr/common/identity/controller/rmnch/RMNCHMobileAppController.java +++ b/src/main/java/com/iemr/common/identity/controller/rmnch/RMNCHMobileAppController.java @@ -23,10 +23,13 @@ import java.sql.Timestamp; +import com.google.gson.Gson; +import com.google.gson.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -56,14 +59,17 @@ public class RMNCHMobileAppController { @PostMapping(value = "/syncDataToAmrit", consumes = "application/json", produces = "application/json") @Operation(summary = "Sync data to AMRIT for already regestered beneficiary with AMRIT beneficiary id ") - public String syncDataToAmrit(@RequestBody String requestOBJ) { + public String syncDataToAmrit(@RequestBody String requestOBJ,@RequestHeader(value = "jwttoken") String authorization) { OutputResponse response = new OutputResponse(); try { if (requestOBJ != null) { - System.out.println("syncDataToAmrit request body : " + requestOBJ); - String s = rmnchDataSyncService.syncDataToAmrit(requestOBJ); - System.out.println("syncDataToAmrit response body : " + s); + + String s = rmnchDataSyncService.syncDataToAmrit(requestOBJ,authorization); + logger.info("syncDataToAmrit Response: {}", s); + response.setResponse(s); + + logger.info(" syncDataToAmrit Final API Response: {}", response.toString()); } else response.setError(5000, "Invalid/NULL request obj"); } catch (Exception e) { @@ -75,6 +81,46 @@ public String syncDataToAmrit(@RequestBody String requestOBJ) { } + @PostMapping(value = "/syncDataToAmritByHwc", consumes = "application/json", produces = "application/json") + @Operation(summary = "Sync data to AMRIT for already registered beneficiary with AMRIT beneficiary id") + public ResponseEntity syncDataToAmritHwc(@RequestBody String requestOBJ) { + + try { + if (requestOBJ == null || requestOBJ.isEmpty()) { + return ResponseEntity.badRequest().body("Invalid/NULL request obj"); + } + + JsonObject requestObj = new Gson().fromJson(requestOBJ, JsonObject.class); + + Long beneficiaryID = requestObj.has("benficieryid") && !requestObj.get("benficieryid").isJsonNull() + ? requestObj.get("benficieryid").getAsLong() + : null; + + Long beneficiaryRegID = requestObj.has("benRegId") && !requestObj.get("benRegId").isJsonNull() + ? requestObj.get("benRegId").getAsLong() + : null; + + if (beneficiaryID == null || beneficiaryRegID == null) { + return ResponseEntity.badRequest().body("beneficiaryID or beneficiaryRegID is missing"); + } + + String result = rmnchDataSyncService.saveBeneficiaryDetailsAfterRegistration( + beneficiaryID, + beneficiaryRegID, + requestOBJ + ); + + return ResponseEntity.ok(result); + + } catch (Exception e) { + logger.error("Error in RMNCH mobile data sync : {}", e.getMessage()); + return ResponseEntity.internalServerError() + .body("Error in RMNCH mobile data sync : " + e.getMessage()); + } + } + + + // @Deprecated @PostMapping(value = "/getBeneficiaryDataForVillage", consumes = "application/json", produces = "application/json") @Operation(summary = "Get beneficiary data for given village ") diff --git a/src/main/java/com/iemr/common/identity/data/rmnch/RMNCHBeneficiaryDetailsRmnch.java b/src/main/java/com/iemr/common/identity/data/rmnch/RMNCHBeneficiaryDetailsRmnch.java index e343087e..a6604f69 100644 --- a/src/main/java/com/iemr/common/identity/data/rmnch/RMNCHBeneficiaryDetailsRmnch.java +++ b/src/main/java/com/iemr/common/identity/data/rmnch/RMNCHBeneficiaryDetailsRmnch.java @@ -564,6 +564,29 @@ public class RMNCHBeneficiaryDetailsRmnch { @Expose private Boolean isDeactivate; + @Expose + @Transient + private String abhaId; + + @Expose + @Transient + private String familyId; + + // Anthropometry fields sent by Stop TB mobile app via beneficiaryDetails payload. + // i_beneficiarydetails_rmnch has no these columns — stored in i_beneficiarydetails.otherFields instead. + @Expose + @Transient + private Double height; + @Expose + @Transient + private Double weight; + @Expose + @Transient + private Double bmi; + @Expose + @Transient + private Double temperature; // stored as "temperatureValue" in otherFields to match getBeneficiaryData key + @Expose @Column(name = "gpsLatitude") private Double gpsLatitude; @@ -589,19 +612,4 @@ public class RMNCHBeneficiaryDetailsRmnch { @Column(name = "gpsUnavailableReason") private String gpsUnavailableReason; - // Anthropometry fields sent by Stop TB mobile app via beneficiaryDetails payload. - // i_beneficiarydetails_rmnch has no these columns — stored in i_beneficiarydetails.otherFields instead. - @Expose - @Transient - private Double height; - @Expose - @Transient - private Double weight; - @Expose - @Transient - private Double bmi; - @Expose - @Transient - private Double temperature; // stored as "temperatureValue" in otherFields to match getBeneficiaryData key - } diff --git a/src/main/java/com/iemr/common/identity/data/rmnch/RMNCHMBeneficiarydetail.java b/src/main/java/com/iemr/common/identity/data/rmnch/RMNCHMBeneficiarydetail.java index a3b71194..0e86127e 100644 --- a/src/main/java/com/iemr/common/identity/data/rmnch/RMNCHMBeneficiarydetail.java +++ b/src/main/java/com/iemr/common/identity/data/rmnch/RMNCHMBeneficiarydetail.java @@ -215,6 +215,14 @@ public class RMNCHMBeneficiarydetail { @Transient private Integer ProviderServiceMapID; + @Expose + @Transient + private String abhaId; + + @Expose + @Column(name = "familyid") + private String familyId; + @Expose private String placeOfCurrentLiving; diff --git a/src/main/java/com/iemr/common/identity/dto/BeneficiariesDTO.java b/src/main/java/com/iemr/common/identity/dto/BeneficiariesDTO.java index d48cd9b5..0ecfb6b2 100644 --- a/src/main/java/com/iemr/common/identity/dto/BeneficiariesDTO.java +++ b/src/main/java/com/iemr/common/identity/dto/BeneficiariesDTO.java @@ -89,6 +89,8 @@ public int compareTo(BeneficiariesDTO ben) { private BigInteger religionId; private String religion; private String monthlyFamilyIncome; + private String reproductiveStatus; + private Integer reproductiveStatusId; // End Outreach // Start 1097 diff --git a/src/main/java/com/iemr/common/identity/dto/IdentityDTO.java b/src/main/java/com/iemr/common/identity/dto/IdentityDTO.java index 322e57fc..f6c000cb 100644 --- a/src/main/java/com/iemr/common/identity/dto/IdentityDTO.java +++ b/src/main/java/com/iemr/common/identity/dto/IdentityDTO.java @@ -125,6 +125,8 @@ public class IdentityDTO { private Integer incomeStatusId; private String incomeStatus; private String monthlyFamilyIncome; + private String reproductiveStatus; + private Integer reproductiveStatusId; @Expose private Integer vanID; diff --git a/src/main/java/com/iemr/common/identity/repo/rmnch/RMNCHBenDetailsRepo.java b/src/main/java/com/iemr/common/identity/repo/rmnch/RMNCHBenDetailsRepo.java index 1bc948a3..27c7a445 100644 --- a/src/main/java/com/iemr/common/identity/repo/rmnch/RMNCHBenDetailsRepo.java +++ b/src/main/java/com/iemr/common/identity/repo/rmnch/RMNCHBenDetailsRepo.java @@ -24,6 +24,7 @@ import java.math.BigInteger; import java.util.List; +import io.swagger.v3.oas.annotations.info.License; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; @@ -36,8 +37,16 @@ public interface RMNCHBenDetailsRepo extends CrudRepository getByBenRegID(@Param("beneficiaryRegID") BigInteger beneficiaryRegID); + + @Query(""" + SELECT t + FROM RMNCHMBeneficiarydetail t + WHERE t.id IN ( + SELECT m.benDetailsId + FROM RMNCHMBeneficiarymapping m + WHERE m.benRegId = :beneficiaryRegID + ) + """) + List getByBenRegID( + @Param("beneficiaryRegID") BigInteger beneficiaryRegID); } diff --git a/src/main/java/com/iemr/common/identity/repo/rmnch/RMNCHCBACDetailsRepo.java b/src/main/java/com/iemr/common/identity/repo/rmnch/RMNCHCBACDetailsRepo.java index 49fb4697..95e452b4 100644 --- a/src/main/java/com/iemr/common/identity/repo/rmnch/RMNCHCBACDetailsRepo.java +++ b/src/main/java/com/iemr/common/identity/repo/rmnch/RMNCHCBACDetailsRepo.java @@ -37,7 +37,7 @@ public interface RMNCHCBACDetailsRepo extends CrudRepository getByRegID(@Param("benRegID") BigInteger benRegID); @Query(value = "select beneficiary_visit_code,visit_category from db_iemr.i_ben_flow_outreach where beneficiary_reg_id=:benRegID AND beneficiary_visit_code is not null AND visit_category is not null order by created_date desc limit 1", nativeQuery = true) public List getVisitDetailsbyRegID(@Param("benRegID") Long benRegID); diff --git a/src/main/java/com/iemr/common/identity/service/IdentityService.java b/src/main/java/com/iemr/common/identity/service/IdentityService.java index a70597dc..06a921b2 100644 --- a/src/main/java/com/iemr/common/identity/service/IdentityService.java +++ b/src/main/java/com/iemr/common/identity/service/IdentityService.java @@ -809,6 +809,16 @@ public List searchBeneficiaryByVillageIdAndLastModifyDate(List return beneficiaryList; } + + public RMNCHBeneficiaryDetailsRmnch getRmnchDataByBenID(BigInteger benID) { + RMNCHBeneficiaryDetailsRmnch rmnchBeneficiaryDetailsRmnch = new RMNCHBeneficiaryDetailsRmnch(); + + if(!rMNCHBeneficiaryDetailsRmnchRepo.getByRegID(benID).isEmpty()){ + rmnchBeneficiaryDetailsRmnch = rMNCHBeneficiaryDetailsRmnchRepo.getByRegID(benID).get(0); + } + return rmnchBeneficiaryDetailsRmnch; + } + public Long countBeneficiaryByVillageIdAndLastModifyDate(List villageIDs, Timestamp lastModifiedDate) { Long beneficiaryCount = 0L; try { @@ -1492,10 +1502,8 @@ public BeneficiaryCreateResp createIdentity(IdentityDTO identity) { Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase); mDetl.setCreatedDate(ts); } - System.out.println("[TRACE][Identity-API] before detailRepo.save mDetl.getDob()=" + mDetl.getDob()); mDetl = detailRepo.save(mDetl); logger.info("IdentityService.createIdentity - Details saved - id = " + mDetl.getBeneficiaryDetailsId()); - System.out.println("[TRACE][Identity-API] after detailRepo.save mDetl.getDob()=" + mDetl.getDob() + " id=" + mDetl.getBeneficiaryDetailsId()); // Update van serial no for data sync detailRepo.updateVanSerialNo(mDetl.getBeneficiaryDetailsId()); @@ -1689,7 +1697,6 @@ private MBeneficiarydetail convertIdentityDTOToMBeneficiarydetail(IdentityDTO dt } beneficiarydetail.setCommunity(dto.getCommunity()); beneficiarydetail.setCommunityId(dto.getCommunityId()); - System.out.println("[TRACE][Identity-API] convertIdentityDTOToMBeneficiarydetail dto.getDob()=" + dto.getDob()); beneficiarydetail.setDob(dto.getDob()); beneficiarydetail.setEducation(dto.getEducation()); beneficiarydetail.setEducationId(dto.getEducationId()); @@ -1999,6 +2006,7 @@ public List getBeneficiariesDeatilsByBenRegIdList(List { @@ -153,6 +161,8 @@ public HealthService( this.elasticsearchEnabled = elasticsearchEnabled; this.elasticsearchIndexingRequired = elasticsearchIndexingRequired; this.elasticsearchTargetIndex = (elasticsearchTargetIndex != null) ? elasticsearchTargetIndex : "amrit_data"; + this.elasticsearchUsername = elasticsearchUsername; + this.elasticsearchPassword = elasticsearchPassword; } @PostConstruct @@ -176,15 +186,30 @@ public void cleanup() { private void initializeElasticsearchClient() { try { - this.elasticsearchRestClient = RestClient.builder( + RestClientBuilder builder = RestClient.builder( new HttpHost(elasticsearchHost, elasticsearchPort, "http")) .setRequestConfigCallback(cb -> cb .setConnectTimeout(ELASTICSEARCH_CONNECT_TIMEOUT_MS) - .setSocketTimeout(ELASTICSEARCH_SOCKET_TIMEOUT_MS)) - .build(); + .setSocketTimeout(ELASTICSEARCH_SOCKET_TIMEOUT_MS)); + + // Attach Basic Auth when credentials are configured, so the health + // probes authenticate against a security-enabled cluster (matches + // ElasticsearchConfig). When username is blank (security disabled), + // the client stays unauthenticated. + if (elasticsearchUsername != null && !elasticsearchUsername.isEmpty()) { + BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials( + AuthScope.ANY, + new UsernamePasswordCredentials(elasticsearchUsername, elasticsearchPassword)); + builder.setHttpClientConfigCallback(httpClientBuilder -> + httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)); + } + + this.elasticsearchRestClient = builder.build(); this.elasticsearchClientReady = true; - logger.info("Elasticsearch client initialized (connect/socket timeout: {}ms)", - ELASTICSEARCH_CONNECT_TIMEOUT_MS); + logger.info("Elasticsearch client initialized (connect/socket timeout: {}ms, auth: {})", + ELASTICSEARCH_CONNECT_TIMEOUT_MS, + (elasticsearchUsername != null && !elasticsearchUsername.isEmpty()) ? "enabled" : "disabled"); } catch (Exception e) { logger.warn("Failed to initialize Elasticsearch client: {}", e.getMessage()); this.elasticsearchClientReady = false; diff --git a/src/main/java/com/iemr/common/identity/service/rmnch/RmnchDataSyncService.java b/src/main/java/com/iemr/common/identity/service/rmnch/RmnchDataSyncService.java index 1d343d4b..7bbcb316 100644 --- a/src/main/java/com/iemr/common/identity/service/rmnch/RmnchDataSyncService.java +++ b/src/main/java/com/iemr/common/identity/service/rmnch/RmnchDataSyncService.java @@ -22,7 +22,11 @@ package com.iemr.common.identity.service.rmnch; public interface RmnchDataSyncService { - public String syncDataToAmrit(String requestOBJ) throws Exception; + public String syncDataToAmrit(String requestOBJ, String authorization) throws Exception; + public String saveBeneficiaryDetailsAfterRegistration( + Long beneficiaryID, + Long beneficiaryRegID, + String comingRequest); public String getBenData(String requestOBJ, String authorisation) throws Exception; public String getBenDataByAsha(String requestOBJ, String authorisation) throws Exception; } diff --git a/src/main/java/com/iemr/common/identity/service/rmnch/RmnchDataSyncServiceImpl.java b/src/main/java/com/iemr/common/identity/service/rmnch/RmnchDataSyncServiceImpl.java index 302e1723..b0a78bff 100644 --- a/src/main/java/com/iemr/common/identity/service/rmnch/RmnchDataSyncServiceImpl.java +++ b/src/main/java/com/iemr/common/identity/service/rmnch/RmnchDataSyncServiceImpl.java @@ -24,6 +24,7 @@ import java.math.BigInteger; import java.sql.Date; import java.sql.Timestamp; +import java.text.SimpleDateFormat; import java.time.Period; import java.util.ArrayList; import java.util.Arrays; @@ -32,6 +33,7 @@ import java.util.List; import java.util.Map; import java.util.regex.Pattern; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -39,6 +41,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; +import org.springframework.http.*; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @@ -79,6 +82,8 @@ import com.iemr.common.identity.utils.exception.IEMRException; import com.iemr.common.identity.utils.http.HttpUtils; import com.iemr.common.identity.utils.mapper.InputMapper; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; @Service @Qualifier("rmnchServiceImpl") @@ -117,13 +122,17 @@ public class RmnchDataSyncServiceImpl implements RmnchDataSyncService { @Autowired private RedisStorage redisStorage; + @Value("${fhir-url}") + private String fhirUrl; + // When true, sync fails loudly if camp is not configured instead of silently // skipping vanID stamping @Value("${stoptb.enforce.vanid:false}") private boolean enforceVanID; @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override - public String syncDataToAmrit(String requestOBJ) throws Exception { + public String syncDataToAmrit(String requestOBJ, String authorization) throws Exception { + Map resultMap = new HashMap(); @@ -159,6 +168,8 @@ public String syncDataToAmrit(String requestOBJ) throws Exception { // other tables data saving // ben details RMNCH extra fields details + logger.info("Request object of syncDataToAmrit: "+jsnOBJ); + BigInteger benRegID = null; @@ -190,10 +201,6 @@ public String syncDataToAmrit(String requestOBJ) throws Exception { obj.setBenRegId(benRegID); // Extract GPS from i_bendemographics JsonObject demog = benGpsMap.get(obj.getBenficieryid()); - System.out.println("[TRACE][Identity-API] syncDataToAmrit benficieryid=" + obj.getBenficieryid() - + " i_bendemographics.pinCode=" + (demog != null && demog.has("pinCode") && !demog.get("pinCode").isJsonNull() - ? demog.get("pinCode") : "ABSENT") - + " entity.getPinCode()=" + obj.getPinCode()); if (demog != null) { if (demog.has("latitude") && !demog.get("latitude").isJsonNull()) obj.setGpsLatitude(demog.get("latitude").getAsDouble()); @@ -229,31 +236,41 @@ public String syncDataToAmrit(String requestOBJ) throws Exception { } obj.setRelatedBeneficiaryIdsDB(sb.toString()); } - if(!rMNCHBenDetailsRepo.getByBenRegID(obj.getBenRegId()).isEmpty()){ - RMNCHMBeneficiarydetail rmnchmBeneficiarydetail = - rMNCHBenDetailsRepo.getByBenRegID(obj.getBenRegId()).get(0); - if (obj.getVanID() == null && vanID != null) { - obj.setVanID(vanID); - obj.setParkingPlaceID(parkingPlaceID); - } - if (rmnchmBeneficiarydetail != null) { - rmnchmBeneficiarydetail.setFirstName(obj.getFirstName()); - rmnchmBeneficiarydetail.setLastName(obj.getLastName()); - rmnchmBeneficiarydetail.setFatherName(obj.getFatherName()); - rmnchmBeneficiarydetail.setMotherName(obj.getMotherName()); - rmnchmBeneficiarydetail.setDob(obj.getDob()); - rmnchmBeneficiarydetail.setSpousename(obj.getSpousename()); - rmnchmBeneficiarydetail.setGender(obj.getGender()); - rmnchmBeneficiarydetail.setGenderId(obj.getGenderId()); - rmnchmBeneficiarydetail.setMaritalstatus(obj.getMaritalstatus()); - rmnchmBeneficiarydetail.setMaritalstatusId(obj.getMaritalstatusId()); - rmnchmBeneficiarydetail.setPlaceOfCurrentLiving(obj.getPlaceOfCurrentLiving()); - rmnchmBeneficiarydetail.setOtherPlaceOfCurrentLiving(obj.getOtherPlaceOfCurrentLiving()); - rmnchmBeneficiarydetail.setInstitutionName(obj.getInstitutionName()); - benDetailsList.add(rmnchmBeneficiarydetail); - } + if (obj.getVanID() == null && vanID != null) { + obj.setVanID(vanID); + obj.setParkingPlaceID(parkingPlaceID); + } + if(!rMNCHBenDetailsRepo.getByBenRegID(obj.getBenRegId()).isEmpty()){ + RMNCHMBeneficiarydetail rmnchmBeneficiarydetail = + rMNCHBenDetailsRepo.getByBenRegID(obj.getBenRegId()).get(0); + if (rmnchmBeneficiarydetail != null) { + rmnchmBeneficiarydetail.setFirstName(obj.getFirstName()); + rmnchmBeneficiarydetail.setLastName(obj.getLastName()); + rmnchmBeneficiarydetail.setFatherName(obj.getFatherName()); + rmnchmBeneficiarydetail.setMotherName(obj.getMotherName()); + rmnchmBeneficiarydetail.setDob(obj.getDob()); + rmnchmBeneficiarydetail.setSpousename(obj.getSpousename()); + rmnchmBeneficiarydetail.setGender(obj.getGender()); + rmnchmBeneficiarydetail.setGenderId(obj.getGenderId()); + rmnchmBeneficiarydetail.setMaritalstatus(obj.getMaritalstatus()); + rmnchmBeneficiarydetail.setMaritalstatusId(obj.getMaritalstatusId()); + rmnchmBeneficiarydetail.setPlaceOfCurrentLiving(obj.getPlaceOfCurrentLiving()); + rmnchmBeneficiarydetail.setOtherPlaceOfCurrentLiving(obj.getOtherPlaceOfCurrentLiving()); + rmnchmBeneficiarydetail.setInstitutionName(obj.getInstitutionName()); + if(obj.getFamilyId()!=null && !obj.getFamilyId().isEmpty()){ + rmnchmBeneficiarydetail.setFamilyId(obj.getFamilyId()); + + } + benDetailsList.add(rmnchmBeneficiarydetail); + if (obj.getAbhaId()!=null && !obj.getAbhaId().isEmpty()) { + mapHealthIDToBeneficiary(authorization,obj.getBenRegId().longValue(),obj.getBenficieryid().longValue(),obj.getAbhaId(),obj.getCreatedBy(),obj.getFirstName(),obj.getLastName(),obj.getDob().toString(),obj.getProviderServiceMapID()); + + } + + } } + } // Keep original list before saveAll — @Transient fields (height/weight/bmi/temperature) @@ -294,12 +311,11 @@ public String syncDataToAmrit(String requestOBJ) throws Exception { RMNCHBornBirthDetails temp = rMNCHBornBirthDetailsRepo.getByRegID(benRegID).get(0); if (temp != null) obj.setBornBirthDeatilsId(temp.getBornBirthDeatilsId()); - if (obj.getVanID() == null && vanID != null) { - obj.setVanID(vanID); - obj.setParkingPlaceID(parkingPlaceID); - } } - + if (obj.getVanID() == null && vanID != null) { + obj.setVanID(vanID); + obj.setParkingPlaceID(parkingPlaceID); + } } bornBirthList = (ArrayList) rMNCHBornBirthDetailsRepo .saveAll(bornBirthList); @@ -320,9 +336,11 @@ public String syncDataToAmrit(String requestOBJ) throws Exception { obj.setConfirmed_tb("Not checked"); obj.setConfirmed_ncd_diseases("Not checked"); obj.setDiagnosis_status("pending"); - RMNCHCBACdetails temp = rMNCHCBACDetailsRepo.getByRegID(benRegID); - if (temp != null) - obj.setCBACDetailsid(temp.getCBACDetailsid()); + if(!rMNCHCBACDetailsRepo.getByRegID(benRegID).isEmpty()){ + RMNCHCBACdetails temp = rMNCHCBACDetailsRepo.getByRegID(benRegID).get(0); + if (temp != null) + obj.setCBACDetailsid(temp.getCBACDetailsid()); + } if (obj.getVanID() == null && vanID != null) { obj.setVanID(vanID); obj.setParkingPlaceID(parkingPlaceID); @@ -356,18 +374,18 @@ public String syncDataToAmrit(String requestOBJ) throws Exception { } for (RMNCHHouseHoldDetails obj : houseHoldList) { - if(!rMNCHHouseHoldDetailsRepo - .getByHouseHoldID(obj.getHouseoldId()).isEmpty()){ - RMNCHHouseHoldDetails temp = rMNCHHouseHoldDetailsRepo - .getByHouseHoldID(obj.getHouseoldId()).get(0); - if (temp != null) - obj.setHouseHoldDetailsId(temp.getHouseHoldDetailsId()); - if (obj.getVanID() == null && vanID != null) { - obj.setVanID(vanID); - obj.setParkingPlaceID(parkingPlaceID); - } - if (hhTimestampMap.containsKey(obj.getHouseoldId())) - obj.setGpsTimestamp(new Timestamp(hhTimestampMap.get(obj.getHouseoldId()))); + if(!rMNCHHouseHoldDetailsRepo + .getByHouseHoldID(obj.getHouseoldId()).isEmpty()){ + RMNCHHouseHoldDetails temp = rMNCHHouseHoldDetailsRepo + .getByHouseHoldID(obj.getHouseoldId()).get(0); + if (temp != null) + obj.setHouseHoldDetailsId(temp.getHouseHoldDetailsId()); + if (hhTimestampMap.containsKey(obj.getHouseoldId())) + obj.setGpsTimestamp(new Timestamp(hhTimestampMap.get(obj.getHouseoldId()))); + } + if (obj.getVanID() == null && vanID != null) { + obj.setVanID(vanID); + obj.setParkingPlaceID(parkingPlaceID); } } houseHoldList = (ArrayList) rMNCHHouseHoldDetailsRepo @@ -385,8 +403,11 @@ public String syncDataToAmrit(String requestOBJ) throws Exception { } catch ( Exception e) { + logger.error("Full Exception", e); + throw new Exception(e); // ✅ original exception wrap karo + } resultMap.put("beneficiaryDetails", beneficiaryDetailsIds); resultMap.put("bornBirthDeatils", bornBirthDeatilsIds); @@ -396,6 +417,243 @@ public String syncDataToAmrit(String requestOBJ) throws Exception { return new Gson().toJson(resultMap); } + /** + * Splits a list into sub-lists (batches) of the given size. + * Last batch may contain fewer elements. + */ + private List> partitionList(List list, int batchSize) { + List> batches = new ArrayList<>(); + if (list == null || list.isEmpty()) { + return batches; + } + for (int i = 0; i < list.size(); i += batchSize) { + batches.add(new ArrayList<>(list.subList(i, Math.min(i + batchSize, list.size())))); + } + return batches; + } + + public String mapHealthIDToBeneficiary(String authorization, + Long benRegID, + Long beneficiaryID, + String abhaId, + String createdBy,String firstName,String lastName,String dob,Integer providerServiceMapId) { + try { + RestTemplate restTemplate = new RestTemplate(); + String formattedDob = dob; + + try { + if (dob != null && dob.contains(" ")) { + Timestamp timestamp = Timestamp.valueOf(dob); + formattedDob = new SimpleDateFormat("dd-MM-yyyy") + .format(timestamp); + } + } catch (Exception ex) { + logger.warn("DOB format conversion failed, sending original DOB : {}", dob); + } + logger.info("Authorization Token : {}", authorization); + + Map requestMap = new HashMap<>(); + + requestMap.put("beneficiaryRegID", benRegID); + requestMap.put("beneficiaryID", beneficiaryID); + requestMap.put("healthIdNumber", abhaId); + + requestMap.put("createdBy", createdBy); + requestMap.put("providerServiceMapId", providerServiceMapId); + requestMap.put("isNew", false); + + // ABHA Profile + Map abhaProfile = new HashMap<>(); + abhaProfile.put("ABHANumber", abhaId); + + List phrAddress = new ArrayList<>(); + phrAddress.add(abhaId + "@abdm"); + + abhaProfile.put("phrAddress", phrAddress); + abhaProfile.put("firstName", firstName); + abhaProfile.put("middleName", ""); + abhaProfile.put("lastName", lastName); + abhaProfile.put("dob", formattedDob); + + + requestMap.put("ABHAProfile", abhaProfile); + + String requestBody = new Gson().toJson(requestMap); + + String url = fhirUrl + + ConfigProperties.getPropertyByName("mapHealthIDToBeneficiary"); + + logger.info("Calling URL : {}", url); + logger.info("Request Body : {}", requestBody); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + headers.set("Jwttoken", authorization); + + HttpEntity entity = + new HttpEntity<>(requestBody, headers); + + ResponseEntity response = restTemplate.exchange( + url, + HttpMethod.POST, + entity, + String.class + ); + + logger.info("ABHA Mapping Response : {}", response.getBody()); + + return response.getBody(); + + } catch (HttpClientErrorException e) { + + logger.error("HTTP Error Status : {}", e.getStatusCode()); + logger.error("HTTP Error Response : {}", e.getResponseBodyAsString(), e); + + return "HTTP Error : " + e.getStatusCode(); + + } catch (Exception e) { + + logger.error("Error while saving Health ID Mapping", e); + + return "Error Save Health Id : " + e.getMessage(); + } + + } + + + @Override + @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) + public String saveBeneficiaryDetailsAfterRegistration( + Long beneficiaryID, + Long beneficiaryRegID, + String comingRequest) { + + logger.info("Method started. beneficiaryID={}, beneficiaryRegID={}", + beneficiaryID, beneficiaryRegID); + + try { + + JsonObject requestObj = new Gson().fromJson(comingRequest, JsonObject.class); + logger.info("Request Parsed Successfully"); + + List list = + rMNCHBeneficiaryDetailsRmnchRepo.getByRegID( + BigInteger.valueOf(beneficiaryRegID)); + + logger.info("Records found for RegID {} : {}", beneficiaryRegID, list.size()); + + RMNCHBeneficiaryDetailsRmnch entity; + boolean isNew = list.isEmpty(); + + if (isNew) { + entity = new RMNCHBeneficiaryDetailsRmnch(); + logger.info("Creating new RMNCH record"); + } else { + entity = list.get(0); + logger.info("Updating existing RMNCH record. ID={}", + entity.getBeneficiaryDetails_RmnchId()); + } + + String createdBy = getString(requestObj, "createdBy", "system"); + + entity.setBenficieryid(BigInteger.valueOf(beneficiaryID)); + entity.setBenRegId(BigInteger.valueOf(beneficiaryRegID)); + + if (isNew) { + entity.setCreatedBy(createdBy); + entity.setCreatedDate(new Timestamp(System.currentTimeMillis())); + } else { + entity.setUpdatedBy(createdBy); + entity.setUpdatedDate(new Timestamp(System.currentTimeMillis())); + } + + entity.setVanID(getInt(requestObj, "vanID", null)); + entity.setParkingPlaceID(getInt(requestObj, "parkingPlaceID", null)); + entity.setProviderServiceMapID(getInt(requestObj, "providerServiceMapID", null)); + entity.setGenderId(getInt(requestObj, "genderID", null)); + + entity.setReproductiveStatusId( + getInt( + requestObj, + "reproductiveStatusId", + getInt(requestObj, "maritalStatusID", null) + ) + ); + + entity.setReproductiveStatus( + getString(requestObj, "reproductiveStatus", null) + ); + + entity.setFirstName(getString(requestObj, "firstName", null)); + entity.setLastName(getString(requestObj, "lastName", null)); + entity.setFatherName(getString(requestObj, "fatherName", null)); + entity.setSpousename(getString(requestObj, "spouseName", null)); + + entity.setMaritalstatusId( + getInt(requestObj, "maritalStatusID", null) + ); + + entity.setMaritalstatus( + getString(requestObj, "maritalStatusName", null) + ); + + // DOB + if (requestObj.has("dOB") + && !requestObj.get("dOB").isJsonNull() + && requestObj.get("dOB").getAsString().trim().length() > 0) { + + try { + entity.setDob( + Timestamp.valueOf( + requestObj.get("dOB") + .getAsString() + .replace("T", " ") + .replace("Z", "") + ) + ); + + logger.info("DOB set successfully"); + + } catch (Exception ex) { + logger.error("Invalid DOB format : {}", + requestObj.get("dOB").getAsString(), ex); + } + } + + logger.info("Before save"); + + RMNCHBeneficiaryDetailsRmnch saved = + rMNCHBeneficiaryDetailsRmnchRepo.save(entity); + + logger.info("After save. Saved ID={}", + saved.getBeneficiaryDetails_RmnchId()); + + logger.info("Saved RMNCH for benRegID={}", beneficiaryRegID); + + return "Saved RMNCH for beneficiaryID: " + beneficiaryID; + + } catch (Exception e) { + + logger.error( + "Exception occurred in saveBeneficiaryDetailsAfterRegistration", + e + ); + + return "Error save beneficiary in rmnch : " + e.getMessage(); + } + } + private String getString(JsonObject obj, String key, String defaultVal) { + return (obj.has(key) && !obj.get(key).isJsonNull()) + ? obj.get(key).getAsString() + : defaultVal; + } + + private Integer getInt(JsonObject obj, String key, Integer defaultVal) { + return (obj.has(key) && !obj.get(key).isJsonNull()) + ? obj.get(key).getAsInt() + : defaultVal; + } private boolean hasAnthropometryData(RMNCHBeneficiaryDetailsRmnch obj) { return obj.getHeight() != null || obj.getWeight() != null @@ -562,12 +820,15 @@ private String getMappingsForAddressIDs(List addressLi benDetailsRMNCHOBJ = rMNCHBeneficiaryDetailsRmnchRepo .getByRegID(m.getBenRegId()).get(0); } - if(!rMNCHBornBirthDetailsRepo.getByRegID(m.getBenRegId()).isEmpty()){ - benBotnBirthRMNCHROBJ = rMNCHBornBirthDetailsRepo.getByRegID(m.getBenRegId()).get(0); + if(!rMNCHBornBirthDetailsRepo.getByRegID(m.getBenRegId()).isEmpty()){ + benBotnBirthRMNCHROBJ = rMNCHBornBirthDetailsRepo.getByRegID(m.getBenRegId()).get(0); - } + } + if(! rMNCHCBACDetailsRepo.getByRegID(m.getBenRegId()).isEmpty()){ + benCABCRMNCHROBJ = rMNCHCBACDetailsRepo.getByRegID(m.getBenRegId()).get(0); + + } - benCABCRMNCHROBJ = rMNCHCBACDetailsRepo.getByRegID(m.getBenRegId()); // 20-09-2021,start NcdTbHrpData res = getHRP_NCD_TB_SuspectedStatus(m.getBenRegId().longValue(), authorisation, benDetailsOBJ); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 12be1b44..79ba181f 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -148,6 +148,7 @@ spring.jpa.properties.hibernate.show_sql=false door-to-door-page-size=2 get-HRP-Status=ANC/getHRPStatus getHealthID=healthID/getBenhealthID +mapHealthIDToBeneficiary=healthIDRecord/mapHealthIDToBeneficiary spring.main.allow-bean-definition-overriding=true spring.main.allow-circular-references=true