From 3814860768b0e07f19e807b7b3e7a432491bb741 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Thu, 19 Sep 2024 18:49:27 +0530 Subject: [PATCH 01/30] Abdm Facility fetch services changes --- src/main/environment/common_ci.properties | 4 + src/main/environment/common_dev.properties | 4 + .../environment/common_example.properties | 4 + src/main/environment/common_test.properties | 4 + .../facility/FacilityController.java | 56 ++++++++++++++ .../service/facility/FacilityService.java | 9 +++ .../service/facility/FacilityServiceImpl.java | 77 +++++++++++++++++++ 7 files changed, 158 insertions(+) create mode 100644 src/main/java/com/wipro/fhir/controller/facility/FacilityController.java create mode 100644 src/main/java/com/wipro/fhir/service/facility/FacilityService.java create mode 100644 src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index c21241d..816b47f 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -77,6 +77,10 @@ abdmGenerateMobileOTP=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/registration/aadhaar/ abdmConfirmAadhaarBio=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/confirmWithAadhaarBio abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile +##ABDM Facility services +getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices + + abhaMode=sbx #logging.pattern.level=DEBUG diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index 6eeea6c..798efa1 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -77,6 +77,10 @@ abdmGenerateMobileOTP=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/registration/aadhaar/ abdmConfirmAadhaarBio=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/confirmWithAadhaarBio abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile +##ABDM Facility services +getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices + + abhaMode=sbx #logging.pattern.level=DEBUG diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index eb1f02c..a3d7d7d 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -77,6 +77,10 @@ abdmGenerateMobileOTP=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/registration/aadhaar/ abdmConfirmAadhaarBio=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/confirmWithAadhaarBio abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile +##ABDM Facility services +getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices + + abhaMode=sbx #logging.pattern.level=DEBUG diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties index 6eeea6c..798efa1 100644 --- a/src/main/environment/common_test.properties +++ b/src/main/environment/common_test.properties @@ -77,6 +77,10 @@ abdmGenerateMobileOTP=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/registration/aadhaar/ abdmConfirmAadhaarBio=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/confirmWithAadhaarBio abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile +##ABDM Facility services +getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices + + abhaMode=sbx #logging.pattern.level=DEBUG diff --git a/src/main/java/com/wipro/fhir/controller/facility/FacilityController.java b/src/main/java/com/wipro/fhir/controller/facility/FacilityController.java new file mode 100644 index 0000000..15e489a --- /dev/null +++ b/src/main/java/com/wipro/fhir/controller/facility/FacilityController.java @@ -0,0 +1,56 @@ +package com.wipro.fhir.controller.facility; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.service.facility.FacilityService; +import com.wipro.fhir.utils.exception.FHIRException; +import com.wipro.fhir.utils.response.OutputResponse; + +import io.swagger.v3.oas.annotations.Operation; + + +@CrossOrigin +@RestController +@RequestMapping(value = "/facility", headers = "Authorization") +public class FacilityController { + + + @Autowired + private FacilityService facilityService; + + Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @CrossOrigin + @Operation(summary = "Get ABDM Registered Facilities") + @GetMapping(value = { "/getAbdmRegisteredFacilities" }) + public String getStoreStockDetails(@RequestHeader(value = "Authorization") String Authorization) { + + OutputResponse response = new OutputResponse(); + + try { + + String resp = facilityService.fetchRegisteredFacilities(); + + response.setResponse(resp); + + } catch (FHIRException e) { + + response.setError(5000, e.getMessage()); + logger.error(e.getMessage()); + } + logger.info("Get ABDM Registered facilities API response" + response.toString()); + return response.toString(); + } + + +} diff --git a/src/main/java/com/wipro/fhir/service/facility/FacilityService.java b/src/main/java/com/wipro/fhir/service/facility/FacilityService.java new file mode 100644 index 0000000..d1235c8 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/facility/FacilityService.java @@ -0,0 +1,9 @@ +package com.wipro.fhir.service.facility; + +import com.wipro.fhir.utils.exception.FHIRException; + +public interface FacilityService { + + String fetchRegisteredFacilities() throws FHIRException; + +} diff --git a/src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java b/src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java new file mode 100644 index 0000000..859d97b --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java @@ -0,0 +1,77 @@ +package com.wipro.fhir.service.facility; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.wipro.fhir.service.ndhm.Common_NDHMService; +import com.wipro.fhir.service.ndhm.GenerateSession_NDHMService; +import com.wipro.fhir.utils.exception.FHIRException; +import com.wipro.fhir.utils.http.HttpUtils; +@Service +public class FacilityServiceImpl implements FacilityService{ + + @Value("${getAbdmFacilityServicies}") + private String getAbdmServicies; + + @Autowired + private HttpUtils httpUtils; + + @Autowired + private Common_NDHMService common_NDHMService; + + @Autowired + private GenerateSession_NDHMService generateSession_NDHM; + + @Override + public String fetchRegisteredFacilities() throws FHIRException { + String res = null; + List> list = new ArrayList<>(); + HashMap map = new HashMap<>(); + try { + String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + HttpHeaders headers = common_NDHMService.getHeaders(ndhmAuthToken); + ResponseEntity responseEntity = httpUtils.getWithResponseEntity(getAbdmServicies, headers); + String responseStrLogin = common_NDHMService.getBody(responseEntity); + if (responseStrLogin != null) { + JsonObject jsnOBJ = new JsonObject(); + JsonParser jsnParser = new JsonParser(); + JsonElement jsnElmnt = jsnParser.parse(responseStrLogin); + jsnOBJ = jsnElmnt.getAsJsonObject(); + JsonElement jsonElement = jsnOBJ.get("services"); + JsonArray asJsonArray = jsonElement.getAsJsonArray(); + for (JsonElement jsonElement2 : asJsonArray) { + JsonObject asJsonObject = jsonElement2.getAsJsonObject(); + String types = asJsonObject.get("types").toString(); + if(null != types && types.contains("HIP")) { + map = new HashMap<>(); + map.put("id", asJsonObject.get("id")); + map.put("name", asJsonObject.get("name")); + list.add(map); + } + } + res = new Gson().toJson(list); + } else + res = "NDHM_FHIR Error while getting facilities"; + } + + catch (Exception e) { + throw new FHIRException("NDHM_FHIR Error while accessing ABDM API" + e.getMessage()); + } + return res; + } + +} + \ No newline at end of file From a2224b4c48c1b7811cc88d59d4b1a0d6afe233af Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Thu, 26 Sep 2024 17:24:38 +0530 Subject: [PATCH 02/30] facility save after carecontext and patientcarecontextx update --- src/main/environment/common_ci.properties | 12 ++++++--- src/main/environment/common_dev.properties | 12 ++++++--- .../environment/common_example.properties | 12 ++++++--- src/main/environment/common_test.properties | 12 ++++++--- .../carecontext/CareContextController.java | 5 ++-- .../data/mongo/care_context/CareContexts.java | 22 ++++++++++++++++ .../GenerateOTPForCareContextAndValidate.java | 14 +++++++++++ .../repo/healthID/BenHealthIDMappingRepo.java | 16 +++++++----- .../care_context/CareContextServiceImpl.java | 17 ++++++++++--- .../service/common/CommonServiceImpl.java | 25 +++++++++++++++++-- .../ndhm/LinkCareContext_NDHMServiceImpl.java | 10 +++++--- 11 files changed, 125 insertions(+), 32 deletions(-) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index 816b47f..50051d4 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -36,7 +36,11 @@ eAushadhiDummy=yes ##NDHM ABHA API clientID=@env.NDHM_ABHA_CLIENT_ID@ clientSecret=@env.NDHM_ABHA_CLIENT_SECRET_KEY@ -ndhmuserAuthenticate=@env.ABDM_BASE_URL@/gateway/v1/sessions + +##Default ABDM Facility ID +abdmFacilityId= @env.ABDM_FACILITY_ID@ + +ndhmuserAuthenticate=@env.ABDM_BASE_URL@/gateway/v0.5/sessions ndhmGenerateOTP=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/registration/mobile/generateOtp ndhmVerifyOTP=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/registration/mobile/verifyOtp ndhmCreateHealthID=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/registration/mobile/createHealthId @@ -53,9 +57,9 @@ abdmcreateHealthIdWithPreVerified= @env.ABDM_HEALTH_ID_BASE_URL@/api/v1/registra ##CareContext Creation API -generateOTPForCareContext=@env.ABDM_BASE_URL@/gateway/v1/users/auth/init -addCareContext = @env.ABDM_BASE_URL@/gateway/v1/links/link/add-contexts -validateOTPForCareContext=@env.ABDM_BASE_URL@/gateway/v1/users/auth/confirm +generateOTPForCareContext=@env.ABDM_BASE_URL@/gateway/v0.5/users/auth/init +addCareContext = @env.ABDM_BASE_URL@/gateway/v0.5/links/link/add-contexts +validateOTPForCareContext=@env.ABDM_BASE_URL@/gateway/v0.5/users/auth/confirm ##ABHA Card API ## Auth init - aadhar / mobile diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index 798efa1..f7484b6 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -36,7 +36,11 @@ eAushadhiDummy=yes ##NDHM ABHA API clientID= clientSecret= -ndhmuserAuthenticate=https://dev.abdm.gov.in/gateway/v1/sessions + +##Default ABDM Facility ID +abdmFacilityId= + +ndhmuserAuthenticate=https://dev.abdm.gov.in/gateway/v0.5/sessions ndhmGenerateOTP=https://healthidsbx.abdm.gov.in/api/v1/registration/mobile/generateOtp ndhmVerifyOTP=https://healthidsbx.abdm.gov.in/api/v1/registration/mobile/verifyOtp ndhmCreateHealthID=https://healthidsbx.abdm.gov.in/api/v1/registration/mobile/createHealthId @@ -53,9 +57,9 @@ abdmcreateHealthIdWithPreVerified= https://healthidsbx.abdm.gov.in/api/v1/regist ##CareContext Creation API -generateOTPForCareContext=https://dev.abdm.gov.in/gateway/v1/users/auth/init -addCareContext = https://dev.abdm.gov.in/gateway/v1/links/link/add-contexts -validateOTPForCareContext=https://dev.abdm.gov.in/gateway/v1/users/auth/confirm +generateOTPForCareContext=https://dev.abdm.gov.in/gateway/v0.5/users/auth/init +addCareContext = https://dev.abdm.gov.in/gateway/v0.5/links/link/add-contexts +validateOTPForCareContext=https://dev.abdm.gov.in/gateway/v0.5/users/auth/confirm ##ABHA Card API ## Auth init - aadhar / mobile diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index a3d7d7d..dee5c20 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -36,7 +36,11 @@ eAushadhiDummy=yes ##NDHM ABHA API clientID= clientSecret= -ndhmuserAuthenticate=https://dev.abdm.gov.in/gateway/v1/sessions + +##Default ABDM Facility ID +abdmFacilityId= + +ndhmuserAuthenticate=https://dev.abdm.gov.in/gateway/v0.5/sessions ndhmGenerateOTP=https://healthidsbx.abdm.gov.in/api/v1/registration/mobile/generateOtp ndhmVerifyOTP=https://healthidsbx.abdm.gov.in/api/v1/registration/mobile/verifyOtp ndhmCreateHealthID=https://healthidsbx.abdm.gov.in/api/v1/registration/mobile/createHealthId @@ -53,9 +57,9 @@ abdmcreateHealthIdWithPreVerified= https://healthidsbx.abdm.gov.in/api/v1/regist ##CareContext Creation API -generateOTPForCareContext=https://dev.abdm.gov.in/gateway/v1/users/auth/init -addCareContext = https://dev.abdm.gov.in/gateway/v1/links/link/add-contexts -validateOTPForCareContext=https://dev.abdm.gov.in/gateway/v1/users/auth/confirm +generateOTPForCareContext=https://dev.abdm.gov.in/gateway/v0.5/users/auth/init +addCareContext = https://dev.abdm.gov.in/gateway/v0.5/links/link/add-contexts +validateOTPForCareContext=https://dev.abdm.gov.in/gateway/v0.5/users/auth/confirm ##ABHA Card API ## Auth init - aadhar / mobile diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties index 798efa1..f7484b6 100644 --- a/src/main/environment/common_test.properties +++ b/src/main/environment/common_test.properties @@ -36,7 +36,11 @@ eAushadhiDummy=yes ##NDHM ABHA API clientID= clientSecret= -ndhmuserAuthenticate=https://dev.abdm.gov.in/gateway/v1/sessions + +##Default ABDM Facility ID +abdmFacilityId= + +ndhmuserAuthenticate=https://dev.abdm.gov.in/gateway/v0.5/sessions ndhmGenerateOTP=https://healthidsbx.abdm.gov.in/api/v1/registration/mobile/generateOtp ndhmVerifyOTP=https://healthidsbx.abdm.gov.in/api/v1/registration/mobile/verifyOtp ndhmCreateHealthID=https://healthidsbx.abdm.gov.in/api/v1/registration/mobile/createHealthId @@ -53,9 +57,9 @@ abdmcreateHealthIdWithPreVerified= https://healthidsbx.abdm.gov.in/api/v1/regist ##CareContext Creation API -generateOTPForCareContext=https://dev.abdm.gov.in/gateway/v1/users/auth/init -addCareContext = https://dev.abdm.gov.in/gateway/v1/links/link/add-contexts -validateOTPForCareContext=https://dev.abdm.gov.in/gateway/v1/users/auth/confirm +generateOTPForCareContext=https://dev.abdm.gov.in/gateway/v0.5/users/auth/init +addCareContext = https://dev.abdm.gov.in/gateway/v0.5/links/link/add-contexts +validateOTPForCareContext=https://dev.abdm.gov.in/gateway/v0.5/users/auth/confirm ##ABHA Card API ## Auth init - aadhar / mobile diff --git a/src/main/java/com/wipro/fhir/controller/carecontext/CareContextController.java b/src/main/java/com/wipro/fhir/controller/carecontext/CareContextController.java index 91d95c0..52f1cd3 100644 --- a/src/main/java/com/wipro/fhir/controller/carecontext/CareContextController.java +++ b/src/main/java/com/wipro/fhir/controller/carecontext/CareContextController.java @@ -50,7 +50,7 @@ public class CareContextController { @Operation(summary = "Generate OTP for care context linking") @PostMapping(value = { "/generateOTPForCareContext" }) public String generateOTP( - @Param(value = "{\"healthID\":\"String\",\"authenticationMode\":\"String\",\"healthIdNumber\":\"String\"}") @RequestBody String request, + @Param(value = "{\"healthID\":\"String\",\"authenticationMode\":\"String\",\"healthIdNumber\":\"String\", \"abdmFacilityId\":\"String\", \"abdmFacilityName\":\"String\" }") @RequestBody String request, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -75,7 +75,8 @@ public String generateOTP( public String validateOTPAndCreateCareContext( @Param(value = "{\"healthID\":\"String\",\"visitCode\\\":\\\"String\\\",\"beneficiaryID\\\":\\\"String\\\"" + ",\"beneficiaryRegID\\\":\\\"String\\\",\"otp\\\":\\\"String\\\"" - + ",\\\"txnId\\\":\\\"String\\\",\\\"visitcategory\\\":\\\"String\\\",\"healthIdNumber\":\"String\"}") @RequestBody String request, + + ",\\\"txnId\\\":\\\"String\\\",\\\"visitcategory\\\":\\\"String\\\",\"healthIdNumber\":\"String\", " + + "\\\"abdmFacilityId\\\":\\\"String\\\", \\\"abdmFacilityName\\\":\\\"String\\\"}") @RequestBody String request, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); diff --git a/src/main/java/com/wipro/fhir/data/mongo/care_context/CareContexts.java b/src/main/java/com/wipro/fhir/data/mongo/care_context/CareContexts.java index 66fb371..dc5d14a 100644 --- a/src/main/java/com/wipro/fhir/data/mongo/care_context/CareContexts.java +++ b/src/main/java/com/wipro/fhir/data/mongo/care_context/CareContexts.java @@ -30,6 +30,12 @@ public class CareContexts { @Expose private String Display; + + @Expose + private String careContextLinkedDate; + + @Expose + private String abdmFacilityId; public String getReferenceNumber() { return ReferenceNumber; @@ -47,4 +53,20 @@ public void setDisplay(String display) { Display = display; } + public String getCareContextLinkedDate() { + return careContextLinkedDate; + } + + public void setCareContextLinkedDate(String careContextLinkedDate) { + this.careContextLinkedDate = careContextLinkedDate; + } + + public String getAbdmFacilityId() { + return abdmFacilityId; + } + + public void setAbdmFacilityId(String abdmFacilityId) { + this.abdmFacilityId = abdmFacilityId; + } + } diff --git a/src/main/java/com/wipro/fhir/data/mongo/care_context/GenerateOTPForCareContextAndValidate.java b/src/main/java/com/wipro/fhir/data/mongo/care_context/GenerateOTPForCareContextAndValidate.java index 84231a5..77491f6 100644 --- a/src/main/java/com/wipro/fhir/data/mongo/care_context/GenerateOTPForCareContextAndValidate.java +++ b/src/main/java/com/wipro/fhir/data/mongo/care_context/GenerateOTPForCareContextAndValidate.java @@ -26,6 +26,8 @@ public class GenerateOTPForCareContextAndValidate {//give common name String authenticationMode; String healthID; String healthIdNumber; + String abdmFacilityName; + String abdmFacilityId; public String getAuthenticationMode() { return authenticationMode; } @@ -44,5 +46,17 @@ public String getHealthIdNumber() { public void setHealthIdNumber(String healthIdNumber) { this.healthIdNumber = healthIdNumber; } + public String getAbdmFacilityName() { + return abdmFacilityName; + } + public void setAbdmFacilityName(String abdmFacilityName) { + this.abdmFacilityName = abdmFacilityName; + } + public String getAbdmFacilityId() { + return abdmFacilityId; + } + public void setAbdmFacilityId(String abdmFacilityId) { + this.abdmFacilityId = abdmFacilityId; + } } diff --git a/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java b/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java index 0989777..d9e80be 100644 --- a/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java +++ b/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java @@ -46,19 +46,19 @@ public interface BenHealthIDMappingRepo extends CrudRepository getLinkedHealthIDForVisit(@Param("visitCode") Long visitCode); @@ -66,4 +66,8 @@ public interface BenHealthIDMappingRepo extends CrudRepository ccList = new ArrayList<>(); @@ -318,7 +329,17 @@ public int addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRes cc.setReferenceNumber(pVisit.getVisitCode() != null ? pVisit.getVisitCode().toString() : null); cc.setDisplay(pVisit.getVisitCategory() != null ? pVisit.getVisitCategory().toString() : null); - + + if (jsnOBJ.has("AbdmFacilityID") && jsnOBJ.get("AbdmFacilityID").isJsonNull() && + jsnOBJ.get("AbdmFacilityID").getAsString().isEmpty()) { + cc.setAbdmFacilityId(jsnOBJ.get("AbdmFacilityID").toString()); + } + if (jsnOBJ.has("CarecontextLinkDate") && jsnOBJ.get("CarecontextLinkDate").isJsonNull() && + jsnOBJ.get("CarecontextLinkDate").getAsString().isEmpty()) { + cc.setCareContextLinkedDate(jsnOBJ.get("CarecontextLinkDate").toString()); + } + + PatientCareContexts pcc; if (pDemo.getBeneficiaryID() != null) { diff --git a/src/main/java/com/wipro/fhir/service/ndhm/LinkCareContext_NDHMServiceImpl.java b/src/main/java/com/wipro/fhir/service/ndhm/LinkCareContext_NDHMServiceImpl.java index 2c4ecf6..86ceeec 100644 --- a/src/main/java/com/wipro/fhir/service/ndhm/LinkCareContext_NDHMServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/ndhm/LinkCareContext_NDHMServiceImpl.java @@ -55,8 +55,8 @@ @Service public class LinkCareContext_NDHMServiceImpl implements LinkCareContext_NDHMService { private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - @Value("${clientID}") - private String clientID; + @Value("${abdmFacilityId}") + private String abdmFacilityId; @Value("${abhaMode}") private String abhaMode; @Value("${clientSecret}") @@ -85,7 +85,11 @@ public String generateOTPForCareContext(String request) throws FHIRException { NDHMRequest obj = common_NDHMService.getRequestIDAndTimeStamp(); Requester requester = new Requester(); - requester.setId(clientID); + if(null != genOTP.getAbdmFacilityId() && null != genOTP.getAbdmFacilityName()) { + requester.setId(genOTP.getAbdmFacilityId()); + } else { + requester.setId(abdmFacilityId); + } requester.setType("HIP"); JsonParser jsnParser = new JsonParser(); Query query = new Query(); From 1a28c2bce4b9cc3082f84a5b32f6c5833464a165 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Tue, 8 Oct 2024 12:44:24 +0530 Subject: [PATCH 03/30] FacilityId save in mongo db and Variable declaration correction --- .../config/BlockingHttpMethodInterceptor.java | 33 --- .../carecontext/CareContextController.java | 3 +- .../facility/FacilityController.java | 24 +- .../fhir/data/e_aushdhi/T_PatientIssue.java | 209 +----------------- .../amrit_resource/AMRIT_ResourceMongo.java | 74 +------ .../mongo/amrit_resource/TempCollection.java | 64 +----- .../care_context/PatientCareContexts.java | 108 +-------- .../care_context/SaveFacilityIdForVisit.java | 13 ++ .../fhir/data/patient/PatientDemographic.java | 8 +- .../TRG_PatientResourceData.java | 79 +------ .../PatientEligibleForResourceCreation.java | 83 +------ .../ResourceRequestHandler.java | 115 +--------- .../AllergyIntoleranceDataModel.java | 12 +- .../resource_model/AppointmentDataModel.java | 12 +- .../ConditionDiagnosisDataModel.java | 12 +- .../DiagnosticReportDataModel.java | 12 +- .../resource_model/EncounterDataModel.java | 12 +- .../FamilyMemberHistoryDataModel.java | 12 +- .../LabTestAndComponentModel.java | 12 +- .../MedicationRequestDataModel.java | 12 +- .../VitalsAnthropometryModel.java | 8 +- ...atientEligibleForResourceCreationRepo.java | 45 ++-- .../repo/healthID/BenHealthIDMappingRepo.java | 22 +- .../amrit_resource/TempCollectionRepo.java | 3 +- .../TRG_PatientResourceData_Repo.java | 3 +- .../service/api_channel/APIChannelImpl.java | 3 +- .../care_context/CareContextServiceImpl.java | 12 +- .../service/common/CommonServiceImpl.java | 118 +++++----- .../service/facility/FacilityService.java | 2 + .../service/facility/FacilityServiceImpl.java | 30 +++ .../AllergyIntoleranceResource.java | 3 +- .../resource_model/AppointmentResource.java | 1 + .../resource_model/ConditionResource.java | 1 + .../DiagnosticReportResource.java | 1 + .../resource_model/EncounterResource.java | 1 + .../FamilyMemberHistoryResource.java | 1 + .../MedicationRequestResource.java | 1 + .../resource_model/ObservationResource.java | 1 + .../resource_model/PatientResource.java | 1 + .../utils/http/HTTPRequestInterceptor.java | 12 +- 40 files changed, 295 insertions(+), 883 deletions(-) delete mode 100644 src/main/java/com/wipro/fhir/config/BlockingHttpMethodInterceptor.java create mode 100644 src/main/java/com/wipro/fhir/data/mongo/care_context/SaveFacilityIdForVisit.java diff --git a/src/main/java/com/wipro/fhir/config/BlockingHttpMethodInterceptor.java b/src/main/java/com/wipro/fhir/config/BlockingHttpMethodInterceptor.java deleted file mode 100644 index 135ecbf..0000000 --- a/src/main/java/com/wipro/fhir/config/BlockingHttpMethodInterceptor.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.wipro.fhir.config; - -import org.springframework.web.servlet.HandlerInterceptor; -import org.springframework.web.servlet.ModelAndView; - -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -public class BlockingHttpMethodInterceptor implements HandlerInterceptor { - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - String method = request.getMethod(); - if (!("GET".equals(method) || "POST".equals(method))) { - response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return false; - } - return true; -} - - @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, - ModelAndView modelAndView) throws Exception { - // TODO Auto-generated method stub - - } - - @Override - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) - throws Exception { - // TODO Auto-generated method stub - - } -} diff --git a/src/main/java/com/wipro/fhir/controller/carecontext/CareContextController.java b/src/main/java/com/wipro/fhir/controller/carecontext/CareContextController.java index 52f1cd3..2c119a2 100644 --- a/src/main/java/com/wipro/fhir/controller/carecontext/CareContextController.java +++ b/src/main/java/com/wipro/fhir/controller/carecontext/CareContextController.java @@ -75,8 +75,7 @@ public String generateOTP( public String validateOTPAndCreateCareContext( @Param(value = "{\"healthID\":\"String\",\"visitCode\\\":\\\"String\\\",\"beneficiaryID\\\":\\\"String\\\"" + ",\"beneficiaryRegID\\\":\\\"String\\\",\"otp\\\":\\\"String\\\"" - + ",\\\"txnId\\\":\\\"String\\\",\\\"visitcategory\\\":\\\"String\\\",\"healthIdNumber\":\"String\", " - + "\\\"abdmFacilityId\\\":\\\"String\\\", \\\"abdmFacilityName\\\":\\\"String\\\"}") @RequestBody String request, + + ",\\\"txnId\\\":\\\"String\\\",\\\"visitcategory\\\":\\\"String\\\",\"healthIdNumber\":\"String\"}") @RequestBody String request, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); diff --git a/src/main/java/com/wipro/fhir/controller/facility/FacilityController.java b/src/main/java/com/wipro/fhir/controller/facility/FacilityController.java index 15e489a..3efafba 100644 --- a/src/main/java/com/wipro/fhir/controller/facility/FacilityController.java +++ b/src/main/java/com/wipro/fhir/controller/facility/FacilityController.java @@ -9,6 +9,7 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.wipro.fhir.data.request_handler.ResourceRequestHandler; @@ -33,7 +34,7 @@ public class FacilityController { @CrossOrigin @Operation(summary = "Get ABDM Registered Facilities") @GetMapping(value = { "/getAbdmRegisteredFacilities" }) - public String getStoreStockDetails(@RequestHeader(value = "Authorization") String Authorization) { + public String getAbdmRegisteredFacilities(@RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -51,6 +52,27 @@ public String getStoreStockDetails(@RequestHeader(value = "Authorization") Strin logger.info("Get ABDM Registered facilities API response" + response.toString()); return response.toString(); } + + + @CrossOrigin + @Operation(summary = "Get ABDM Registered Facilities") + @PostMapping(value = { "/saveAbdmFacilityId" }) + public String saveAbdmFacilityForVisit(@RequestHeader(value = "Authorization") String Authorization, @RequestBody() String reqObj) { + + OutputResponse response = new OutputResponse(); + + try { + + String resp = facilityService.saveAbdmFacilityId(reqObj); + response.setResponse(resp); + } catch (FHIRException e) { + + response.setError(5000, e.getMessage()); + logger.error(e.getMessage()); + } + logger.info("ABDM save Facility ID response" + response.toString()); + return response.toString(); + } } diff --git a/src/main/java/com/wipro/fhir/data/e_aushdhi/T_PatientIssue.java b/src/main/java/com/wipro/fhir/data/e_aushdhi/T_PatientIssue.java index d2362a4..7729fc7 100644 --- a/src/main/java/com/wipro/fhir/data/e_aushdhi/T_PatientIssue.java +++ b/src/main/java/com/wipro/fhir/data/e_aushdhi/T_PatientIssue.java @@ -22,6 +22,7 @@ package com.wipro.fhir.data.e_aushdhi; +import java.math.BigInteger; import java.util.Date; @@ -32,6 +33,7 @@ import jakarta.persistence.Id; import jakarta.persistence.Table; import jakarta.persistence.Transient; +import lombok.Data; import com.google.gson.annotations.Expose; @@ -39,7 +41,7 @@ @Entity @Table(name = "t_patientissue") - +@Data public class T_PatientIssue { @Id @@ -54,7 +56,7 @@ public class T_PatientIssue { @Expose @Column(name = "BeneficiaryRegID") - private Long benRegID; + private BigInteger benRegID; @Expose @Column(name = "FacilityID") @@ -144,208 +146,5 @@ public class T_PatientIssue { @Transient private Long beneficiaryID; - - - public Long getPatientIssueID() { - return patientIssueID; - } - - public void setPatientIssueID(Long patientIssueID) { - this.patientIssueID = patientIssueID; - } - - public Long getVanSerialNo() { - return vanSerialNo; - } - - public void setVanSerialNo(Long vanSerialNo) { - this.vanSerialNo = vanSerialNo; - } - - public Long getBenRegID() { - return benRegID; - } - - public void setBenRegID(Long benRegID) { - this.benRegID = benRegID; - } - - public Integer getFacilityID() { - return facilityID; - } - - public void setFacilityID(Integer facilityID) { - this.facilityID = facilityID; - } - - public Integer getSyncFacilityID() { - return syncFacilityID; - } - - public void setSyncFacilityID(Integer syncFacilityID) { - this.syncFacilityID = syncFacilityID; - } - - public Integer getVisitID() { - return visitID; - } - - public void setVisitID(Integer visitID) { - this.visitID = visitID; - } - - public String getPatientName() { - return patientName; - } - - public void setPatientName(String patientName) { - this.patientName = patientName; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - - public String getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - - public String getDoctorName() { - return doctorName; - } - - public void setDoctorName(String doctorName) { - this.doctorName = doctorName; - } - - public Integer getPrescriptionID() { - return prescriptionID; - } - - public void setPrescriptionID(Integer prescriptionID) { - this.prescriptionID = prescriptionID; - } - - public String getReference() { - return reference; - } - - public void setReference(String reference) { - this.reference = reference; - } - - public String getIssueType() { - return issueType; - } - - public void setIssueType(String issueType) { - this.issueType = issueType; - } - - public String getIssuedBy() { - return issuedBy; - } - - public void setIssuedBy(String issuedBy) { - this.issuedBy = issuedBy; - } - - public Integer getProviderServiceMapID() { - return providerServiceMapID; - } - - public void setProviderServiceMapID(Integer providerServiceMapID) { - this.providerServiceMapID = providerServiceMapID; - } - - public Boolean getDeleted() { - return deleted; - } - - public void setDeleted(Boolean deleted) { - this.deleted = deleted; - } - - public Character getProcessed() { - return processed; - } - - public void setProcessed(Character processed) { - this.processed = processed; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public Date getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public String getModifiedBy() { - return modifiedBy; - } - - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - public Date getLastModDate() { - return lastModDate; - } - - public void setLastModDate(Date lastModDate) { - this.lastModDate = lastModDate; - } - - public Long getVisitCode() { - return visitCode; - } - - public void setVisitCode(Long visitCode) { - this.visitCode = visitCode; - } - - public Long getVanID() { - return vanID; - } - - public void setVanID(Long vanID) { - this.vanID = vanID; - } - - public Long getParkingPlaceID() { - return parkingPlaceID; - } - - public void setParkingPlaceID(Long parkingPlaceID) { - this.parkingPlaceID = parkingPlaceID; - } - - public Long getBeneficiaryID() { - return beneficiaryID; - } - - public void setBeneficiaryID(Long beneficiaryID) { - this.beneficiaryID = beneficiaryID; - } - - } diff --git a/src/main/java/com/wipro/fhir/data/mongo/amrit_resource/AMRIT_ResourceMongo.java b/src/main/java/com/wipro/fhir/data/mongo/amrit_resource/AMRIT_ResourceMongo.java index 2a410a6..c1e9e1d 100644 --- a/src/main/java/com/wipro/fhir/data/mongo/amrit_resource/AMRIT_ResourceMongo.java +++ b/src/main/java/com/wipro/fhir/data/mongo/amrit_resource/AMRIT_ResourceMongo.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.data.mongo.amrit_resource; +import java.math.BigInteger; import java.sql.Timestamp; import org.springframework.data.annotation.Id; @@ -29,7 +30,10 @@ import com.google.gson.annotations.Expose; +import lombok.Data; + @Document(collection = "AMRIT_Resource") +@Data public class AMRIT_ResourceMongo { @Id @@ -39,11 +43,11 @@ public class AMRIT_ResourceMongo { @Expose @Field(value = "BeneficiaryRegID") - private Long beneficiaryRegID; + private BigInteger beneficiaryRegID; @Expose @Field(value = "BeneficiaryID") - private Long beneficiaryID; + private BigInteger beneficiaryID; @Expose @Field(value = "NationalHealthID") @@ -51,7 +55,7 @@ public class AMRIT_ResourceMongo { @Expose @Field(value = "VisitCode") - private Long visitCode; + private BigInteger visitCode; @Expose @Field(value = "ResourceType") @@ -65,68 +69,4 @@ public class AMRIT_ResourceMongo { @Field(value = "CreateDate") private Timestamp createDate = new Timestamp(System.currentTimeMillis()); - public Long getBeneficiaryRegID() { - return beneficiaryRegID; - } - - public void setBeneficiaryRegID(Long beneficiaryRegID) { - this.beneficiaryRegID = beneficiaryRegID; - } - - public String getNationalHealthID() { - return nationalHealthID; - } - - public void setNationalHealthID(String nationalHealthID) { - this.nationalHealthID = nationalHealthID; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public Long getBeneficiaryID() { - return beneficiaryID; - } - - public void setBeneficiaryID(Long beneficiaryID) { - this.beneficiaryID = beneficiaryID; - } - - public Long getVisitCode() { - return visitCode; - } - - public void setVisitCode(Long visitCode) { - this.visitCode = visitCode; - } - - public String getResourceType() { - return resourceType; - } - - public void setResourceType(String resourceType) { - this.resourceType = resourceType; - } - - public String getResourceJson() { - return resourceJson; - } - - public void setResourceJson(String resourceJson) { - this.resourceJson = resourceJson; - } - - public Timestamp getCreateDate() { - return createDate; - } - - public void setCreateDate(Timestamp createDate) { - this.createDate = createDate; - } - } diff --git a/src/main/java/com/wipro/fhir/data/mongo/amrit_resource/TempCollection.java b/src/main/java/com/wipro/fhir/data/mongo/amrit_resource/TempCollection.java index 45804e1..f19956c 100644 --- a/src/main/java/com/wipro/fhir/data/mongo/amrit_resource/TempCollection.java +++ b/src/main/java/com/wipro/fhir/data/mongo/amrit_resource/TempCollection.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.data.mongo.amrit_resource; +import java.math.BigInteger; import java.util.Date; import java.util.List; import java.util.Map; @@ -31,7 +32,10 @@ import com.google.gson.annotations.Expose; +import lombok.Data; + @Document(collection = "AMRIT_TempStorage") +@Data public class TempCollection { @Id @@ -41,11 +45,11 @@ public class TempCollection { @Expose @Field(value = "BeneficiaryRegID") - private Long beneficiaryRegID; + private BigInteger beneficiaryRegID; @Expose @Field(value = "VisitCode") - private Long visitCode; + private BigInteger visitCode; @Expose @Field(value = "DataType") @@ -63,60 +67,4 @@ public class TempCollection { @Field(value = "CreateBy") private String createBy; - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public Long getBeneficiaryRegID() { - return beneficiaryRegID; - } - - public void setBeneficiaryRegID(Long beneficiaryRegID) { - this.beneficiaryRegID = beneficiaryRegID; - } - - public Long getVisitCode() { - return visitCode; - } - - public void setVisitCode(Long visitCode) { - this.visitCode = visitCode; - } - - public String getDataType() { - return dataType; - } - - public void setDataType(String dataType) { - this.dataType = dataType; - } - - public Map> getDataJson() { - return dataJson; - } - - public void setDataJson(Map> dataJson) { - this.dataJson = dataJson; - } - - public Date getCreateDate() { - return createDate; - } - - public void setCreateDate(Date createDate) { - this.createDate = createDate; - } - - public String getCreateBy() { - return createBy; - } - - public void setCreateBy(String createBy) { - this.createBy = createBy; - } - } diff --git a/src/main/java/com/wipro/fhir/data/mongo/care_context/PatientCareContexts.java b/src/main/java/com/wipro/fhir/data/mongo/care_context/PatientCareContexts.java index bff86d0..efe0597 100644 --- a/src/main/java/com/wipro/fhir/data/mongo/care_context/PatientCareContexts.java +++ b/src/main/java/com/wipro/fhir/data/mongo/care_context/PatientCareContexts.java @@ -29,7 +29,10 @@ import com.google.gson.annotations.Expose; +import lombok.Data; + @Document(collection = "PatientCareContexts") +@Data public class PatientCareContexts { @Id @@ -73,108 +76,13 @@ public class PatientCareContexts { @Field(value = "HealthId") private String HealthId; - @Expose - @Field(value = "careContexts") - private String careContextsList; +// @Expose +// @Field(value = "careContexts") +// private String careContextsList; @Expose - @Field(value = "careContextsListTemp") - private ArrayList careContextsListTemp; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getPhoneNumber() { - return phoneNumber; - } - - public void setPhoneNumber(String phoneNumber) { - this.phoneNumber = phoneNumber; - } - - public String getIdentifier() { - return identifier; - } - - public void setIdentifier(String identifier) { - this.identifier = identifier; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getCaseReferenceNumber() { - return caseReferenceNumber; - } - - public void setCaseReferenceNumber(String caseReferenceNumber) { - this.caseReferenceNumber = caseReferenceNumber; - } - - public String getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - - public String getYearOfBirth() { - return yearOfBirth; - } - - public void setYearOfBirth(String yearOfBirth) { - this.yearOfBirth = yearOfBirth; - } - - public String getHealthNumber() { - return HealthNumber; - } - - public void setHealthNumber(String healthNumber) { - HealthNumber = healthNumber; - } - - public String getHealthId() { - return HealthId; - } - - public void setHealthId(String healthId) { - HealthId = healthId; - } - - public String getCareContextsList() { - return careContextsList; - } - - public void setCareContextsList(String careContextsList) { - this.careContextsList = careContextsList; - } - - public ArrayList getCareContextsListTemp() { - return careContextsListTemp; - } + @Field(value = "careContextsList") + private ArrayList careContextsList; - public void setCareContextsListTemp(ArrayList careContextsListTemp) { - this.careContextsListTemp = careContextsListTemp; - } } diff --git a/src/main/java/com/wipro/fhir/data/mongo/care_context/SaveFacilityIdForVisit.java b/src/main/java/com/wipro/fhir/data/mongo/care_context/SaveFacilityIdForVisit.java new file mode 100644 index 0000000..0a3c9f3 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/mongo/care_context/SaveFacilityIdForVisit.java @@ -0,0 +1,13 @@ +package com.wipro.fhir.data.mongo.care_context; + +import java.math.BigInteger; + +import lombok.Data; + +@Data +public class SaveFacilityIdForVisit { + + String facilityId; + BigInteger visitCode; + +} diff --git a/src/main/java/com/wipro/fhir/data/patient/PatientDemographic.java b/src/main/java/com/wipro/fhir/data/patient/PatientDemographic.java index 7303ad1..2b1f9d8 100644 --- a/src/main/java/com/wipro/fhir/data/patient/PatientDemographic.java +++ b/src/main/java/com/wipro/fhir/data/patient/PatientDemographic.java @@ -34,8 +34,8 @@ public class PatientDemographic { private String healthID; private String healthIdNo; - private Long beneficiaryRegID; - private Long beneficiaryID; + private BigInteger beneficiaryRegID; + private BigInteger beneficiaryID; private String firstName; private String middleName; @@ -62,7 +62,7 @@ public class PatientDemographic { private Integer actualAge; private String ageUnits; - public PatientDemographic(String healthID, String healthIdNo, Long beneficiaryRegID, Long beneficiaryID, + public PatientDemographic(String healthID, String healthIdNo, BigInteger beneficiaryRegID, BigInteger beneficiaryID, String name, Integer genderID, String gender, Integer maritalStatusID, String maritalStatus, Timestamp dOB, String preferredPhoneNo, String country, String state, String district) { super(); @@ -95,7 +95,7 @@ public PatientDemographic getPatientDemographic(List objList) { if (objList != null && objList.size() > 0) { Object[] objArr = objList.get(objList.size() - 1); PatientDemographic obj = new PatientDemographic((String) objArr[0], (String) objArr[1], - ((BigInteger) objArr[2]).longValue(), ((BigInteger) objArr[3]).longValue(), (String) objArr[4], + (BigInteger.valueOf((long) objArr[2])), BigInteger.valueOf((long) objArr[3]), (String) objArr[4], (Integer) objArr[5], (String) objArr[6], (Integer) objArr[7], (String) objArr[8], (Timestamp) objArr[9], (String) objArr[10], (String) objArr[11], (String) objArr[12], (String) objArr[13]); diff --git a/src/main/java/com/wipro/fhir/data/patient_data_handler/TRG_PatientResourceData.java b/src/main/java/com/wipro/fhir/data/patient_data_handler/TRG_PatientResourceData.java index 78a0172..f67f9f4 100644 --- a/src/main/java/com/wipro/fhir/data/patient_data_handler/TRG_PatientResourceData.java +++ b/src/main/java/com/wipro/fhir/data/patient_data_handler/TRG_PatientResourceData.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.data.patient_data_handler; +import java.math.BigInteger; import java.sql.Timestamp; import jakarta.persistence.Column; @@ -29,12 +30,14 @@ import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; +import lombok.Data; import com.fasterxml.jackson.annotation.JsonFormat; import com.google.gson.annotations.Expose; @Entity @Table(name = "db_identity.trg_patientresourcedata") +@Data public class TRG_PatientResourceData { @Id @@ -45,11 +48,11 @@ public class TRG_PatientResourceData { @Expose @Column(name = "BenRegId") - private Long benRegId; + private BigInteger benRegId; @Expose @Column(name = "BeneficiaryID") - private Long beneficiaryID; + private BigInteger beneficiaryID; @Expose @Column(name = "CreatedBy") @@ -76,76 +79,4 @@ public class TRG_PatientResourceData { @Column(name = "Processed") private Boolean processed; - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getBenRegId() { - return benRegId; - } - - public void setBenRegId(Long benRegId) { - this.benRegId = benRegId; - } - - public Long getBeneficiaryID() { - return beneficiaryID; - } - - public void setBeneficiaryID(Long beneficiaryID) { - this.beneficiaryID = beneficiaryID; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public Timestamp getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Timestamp createdDate) { - this.createdDate = createdDate; - } - - public String getModifiedBy() { - return modifiedBy; - } - - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - public Timestamp getLastModDate() { - return lastModDate; - } - - public void setLastModDate(Timestamp lastModDate) { - this.lastModDate = lastModDate; - } - - public String getTrgStatus() { - return trgStatus; - } - - public void setTrgStatus(String trgStatus) { - this.trgStatus = trgStatus; - } - - public Boolean getProcessed() { - return processed; - } - - public void setProcessed(Boolean processed) { - this.processed = processed; - } - } diff --git a/src/main/java/com/wipro/fhir/data/request_handler/PatientEligibleForResourceCreation.java b/src/main/java/com/wipro/fhir/data/request_handler/PatientEligibleForResourceCreation.java index 43d0804..3d8656d 100644 --- a/src/main/java/com/wipro/fhir/data/request_handler/PatientEligibleForResourceCreation.java +++ b/src/main/java/com/wipro/fhir/data/request_handler/PatientEligibleForResourceCreation.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.data.request_handler; +import java.math.BigInteger; import java.sql.Timestamp; import jakarta.persistence.Column; @@ -29,24 +30,26 @@ import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; +import lombok.Data; import com.google.gson.annotations.Expose; @Entity @Table(name = "ndhm_trg_visitdata") +@Data public class PatientEligibleForResourceCreation { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Expose @Column(name = "id") - private Long id; + private BigInteger id; @Expose @Column(name = "BeneficiaryRegID") - private Long beneficiaryRegID; + private BigInteger beneficiaryRegID; @Expose @Column(name = "beneficiary_id") - private Long beneficiaryId; + private BigInteger beneficiaryId; @Expose @Column(name = "visit_reason") private String visitReason; @@ -55,7 +58,7 @@ public class PatientEligibleForResourceCreation { private String visitCategory; @Expose @Column(name = "VisitCode") - private Long visitCode; + private BigInteger visitCode; @Expose @Column(name = "visitdate") private Timestamp visitDate; @@ -66,76 +69,4 @@ public class PatientEligibleForResourceCreation { @Column(name = "Processed_Flag") private Boolean processed; - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getBeneficiaryRegID() { - return beneficiaryRegID; - } - - public void setBeneficiaryRegID(Long beneficiaryRegID) { - this.beneficiaryRegID = beneficiaryRegID; - } - - public Long getBeneficiaryId() { - return beneficiaryId; - } - - public void setBeneficiaryId(Long beneficiaryId) { - this.beneficiaryId = beneficiaryId; - } - - public String getVisitReason() { - return visitReason; - } - - public void setVisitReason(String visitReason) { - this.visitReason = visitReason; - } - - public String getVisitCategory() { - return visitCategory; - } - - public void setVisitCategory(String visitCategory) { - this.visitCategory = visitCategory; - } - - public Long getVisitCode() { - return visitCode; - } - - public void setVisitCode(Long visitCode) { - this.visitCode = visitCode; - } - - public Timestamp getVisitDate() { - return visitDate; - } - - public void setVisitDate(Timestamp visitDate) { - this.visitDate = visitDate; - } - - public Timestamp getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Timestamp createdDate) { - this.createdDate = createdDate; - } - - public Boolean getProcessed() { - return processed; - } - - public void setProcessed(Boolean processed) { - this.processed = processed; - } - } diff --git a/src/main/java/com/wipro/fhir/data/request_handler/ResourceRequestHandler.java b/src/main/java/com/wipro/fhir/data/request_handler/ResourceRequestHandler.java index a754dd4..13e4d2a 100644 --- a/src/main/java/com/wipro/fhir/data/request_handler/ResourceRequestHandler.java +++ b/src/main/java/com/wipro/fhir/data/request_handler/ResourceRequestHandler.java @@ -21,10 +21,14 @@ */ package com.wipro.fhir.data.request_handler; +import java.math.BigInteger; + import org.springframework.stereotype.Component; import com.google.gson.annotations.Expose; +import lombok.Data; + /*** * * @author NE298657 @@ -33,12 +37,13 @@ @Component +@Data public class ResourceRequestHandler { // patient || - private Long beneficiaryID; + private BigInteger beneficiaryID; // Encounter/ care-context - private Long visitCode; - private Long beneficiaryRegID; + private BigInteger visitCode; + private BigInteger beneficiaryRegID; private Long benFlowID; // 27-10-2021 @@ -61,108 +66,4 @@ public class ResourceRequestHandler { @Expose private String village; - public String getHealthId() { - return healthId; - } - - public void setHealthId(String healthId) { - this.healthId = healthId; - } - - public String getHealthIdNumber() { - return healthIdNumber; - } - - public void setHealthIdNumber(String healthIdNumber) { - this.healthIdNumber = healthIdNumber; - } - - public String getAmritId() { - return amritId; - } - - public void setAmritId(String amritId) { - this.amritId = amritId; - } - - public String getExternalId() { - return externalId; - } - - public void setExternalId(String externalId) { - this.externalId = externalId; - } - - public Long getBeneficiaryRegID() { - return beneficiaryRegID; - } - - public void setBeneficiaryRegID(Long beneficiaryRegID) { - this.beneficiaryRegID = beneficiaryRegID; - } - - public Long getBenFlowID() { - return benFlowID; - } - - public void setBenFlowID(Long benFlowID) { - this.benFlowID = benFlowID; - } - - public Long getVisitCode() { - return visitCode; - } - - public void setVisitCode(Long visitCode) { - this.visitCode = visitCode; - } - - public Long getBeneficiaryID() { - return beneficiaryID; - } - - public Integer getPageNo() { - return pageNo; - } - - public void setPageNo(Integer pageNo) { - this.pageNo = pageNo; - } - - public void setBeneficiaryID(Long beneficiaryID) { - this.beneficiaryID = beneficiaryID; - } - - public String getPhoneNo() { - return phoneNo; - } - - public void setPhoneNo(String phoneNo) { - this.phoneNo = phoneNo; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public String getDistrict() { - return district; - } - - public void setDistrict(String district) { - this.district = district; - } - - public String getVillage() { - return village; - } - - public void setVillage(String village) { - this.village = village; - } - } diff --git a/src/main/java/com/wipro/fhir/data/resource_model/AllergyIntoleranceDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/AllergyIntoleranceDataModel.java index a49311d..bc520ff 100644 --- a/src/main/java/com/wipro/fhir/data/resource_model/AllergyIntoleranceDataModel.java +++ b/src/main/java/com/wipro/fhir/data/resource_model/AllergyIntoleranceDataModel.java @@ -44,9 +44,9 @@ public class AllergyIntoleranceDataModel implements Serializable { // @Id // @GeneratedValue - private Long id; - private Long beneficiaryRegID; - private Long visitCode; + private BigInteger id; + private BigInteger beneficiaryRegID; + private BigInteger visitCode; private Integer providerServiceMapID; private Integer vanID; private String allergyStatus; @@ -61,9 +61,9 @@ public AllergyIntoleranceDataModel() { } public AllergyIntoleranceDataModel(Object[] objArr) { - this.id = ((BigInteger) objArr[0]).longValue(); - this.beneficiaryRegID = ((BigInteger) objArr[1]).longValue(); - this.visitCode = ((BigInteger) objArr[2]).longValue(); + this.id = BigInteger.valueOf((long) objArr[0]); + this.beneficiaryRegID = BigInteger.valueOf((long) objArr[1]); + this.visitCode = BigInteger.valueOf((long) objArr[2]); this.providerServiceMapID = (Integer) objArr[3]; this.vanID = (Integer) objArr[4]; this.allergyStatus = (String) objArr[5]; diff --git a/src/main/java/com/wipro/fhir/data/resource_model/AppointmentDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/AppointmentDataModel.java index fb6c7f9..45ebabf 100644 --- a/src/main/java/com/wipro/fhir/data/resource_model/AppointmentDataModel.java +++ b/src/main/java/com/wipro/fhir/data/resource_model/AppointmentDataModel.java @@ -42,9 +42,9 @@ public class AppointmentDataModel implements Serializable { // @Id // @GeneratedValue - private Long id; - private Long beneficiaryRegID; - private Long visitCode; + private BigInteger id; + private BigInteger beneficiaryRegID; + private BigInteger visitCode; private Integer providerServiceMapID; private Integer vanID; private String status; @@ -60,9 +60,9 @@ public AppointmentDataModel() { } public AppointmentDataModel(Object[] objArr) { - this.id = ((BigInteger) objArr[0]).longValue(); - this.beneficiaryRegID = ((BigInteger) objArr[1]).longValue(); - this.visitCode = ((BigInteger) objArr[2]).longValue(); + this.id = BigInteger.valueOf((long) objArr[0]); + this.beneficiaryRegID = BigInteger.valueOf((long) objArr[1]); + this.visitCode = BigInteger.valueOf((long) objArr[2]); this.providerServiceMapID = (Integer) objArr[3]; this.vanID = (Integer) objArr[4]; diff --git a/src/main/java/com/wipro/fhir/data/resource_model/ConditionDiagnosisDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/ConditionDiagnosisDataModel.java index 55f68e5..74c6c3b 100644 --- a/src/main/java/com/wipro/fhir/data/resource_model/ConditionDiagnosisDataModel.java +++ b/src/main/java/com/wipro/fhir/data/resource_model/ConditionDiagnosisDataModel.java @@ -42,9 +42,9 @@ public class ConditionDiagnosisDataModel implements Serializable { // @Id // @GeneratedValue - private Long id; - private Long beneficiaryRegID; - private Long visitCode; + private BigInteger id; + private BigInteger beneficiaryRegID; + private BigInteger visitCode; private Integer providerServiceMapID; private Integer vanID; private String sctcode; @@ -56,9 +56,9 @@ public ConditionDiagnosisDataModel() { } public ConditionDiagnosisDataModel(Object[] objArr) { - this.id = ((BigInteger) objArr[0]).longValue(); - this.beneficiaryRegID = ((BigInteger) objArr[1]).longValue(); - this.visitCode = ((BigInteger) objArr[2]).longValue(); + this.id = BigInteger.valueOf((long) objArr[0]); + this.beneficiaryRegID = BigInteger.valueOf((long) objArr[1]); + this.visitCode = BigInteger.valueOf((long) objArr[2]); this.providerServiceMapID = (Integer) objArr[3]; this.vanID = (Integer) objArr[4]; this.sctTerm = (String) objArr[5]; diff --git a/src/main/java/com/wipro/fhir/data/resource_model/DiagnosticReportDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/DiagnosticReportDataModel.java index 263af1c..9acae30 100644 --- a/src/main/java/com/wipro/fhir/data/resource_model/DiagnosticReportDataModel.java +++ b/src/main/java/com/wipro/fhir/data/resource_model/DiagnosticReportDataModel.java @@ -42,9 +42,9 @@ public class DiagnosticReportDataModel { // @Id // @GeneratedValue - private Long id; - private Long beneficiaryRegID; - private Long visitCode; + private BigInteger id; + private BigInteger beneficiaryRegID; + private BigInteger visitCode; private Integer providerServiceMapID; private Integer vanID; private Integer procedureID; @@ -67,9 +67,9 @@ public DiagnosticReportDataModel() { } public DiagnosticReportDataModel(Object[] objArr) { - this.id = ((BigInteger) objArr[0]).longValue(); - this.beneficiaryRegID = ((BigInteger) objArr[1]).longValue(); - this.visitCode = ((BigInteger) objArr[2]).longValue(); + this.id = BigInteger.valueOf((long) objArr[0]); + this.beneficiaryRegID = BigInteger.valueOf((long) objArr[1]); + this.visitCode = BigInteger.valueOf((long) objArr[2]); this.providerServiceMapID = (Integer) objArr[3]; this.vanID = (Integer) objArr[4]; this.procedureID = (Integer) objArr[5]; diff --git a/src/main/java/com/wipro/fhir/data/resource_model/EncounterDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/EncounterDataModel.java index 1e8b522..cc2385b 100644 --- a/src/main/java/com/wipro/fhir/data/resource_model/EncounterDataModel.java +++ b/src/main/java/com/wipro/fhir/data/resource_model/EncounterDataModel.java @@ -40,9 +40,9 @@ public class EncounterDataModel implements Serializable { */ private static final long serialVersionUID = 1L; - private Long id; - private Long beneficiaryRegID; - private Long visitCode; + private BigInteger id; + private BigInteger beneficiaryRegID; + private BigInteger visitCode; private Integer providerServiceMapID; private Integer vanID; private Integer nurseFlag; @@ -55,9 +55,9 @@ public EncounterDataModel() { } public EncounterDataModel(Object[] objArr) { - this.id = ((BigInteger) objArr[0]).longValue(); - this.beneficiaryRegID = ((BigInteger) objArr[1]).longValue(); - this.visitCode = ((BigInteger) objArr[2]).longValue(); + this.id = BigInteger.valueOf((long) objArr[0]); + this.beneficiaryRegID = BigInteger.valueOf((long) objArr[1]); + this.visitCode = BigInteger.valueOf((long) objArr[2]); this.providerServiceMapID = (Integer) objArr[3]; this.vanID = (Integer) objArr[4]; diff --git a/src/main/java/com/wipro/fhir/data/resource_model/FamilyMemberHistoryDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/FamilyMemberHistoryDataModel.java index 47679a7..4c74e3b 100644 --- a/src/main/java/com/wipro/fhir/data/resource_model/FamilyMemberHistoryDataModel.java +++ b/src/main/java/com/wipro/fhir/data/resource_model/FamilyMemberHistoryDataModel.java @@ -42,9 +42,9 @@ public class FamilyMemberHistoryDataModel implements Serializable { // @Id // @GeneratedValue - private Long id; - private Long beneficiaryRegID; - private Long visitCode; + private BigInteger id; + private BigInteger beneficiaryRegID; + private BigInteger visitCode; private Integer providerServiceMapID; private Integer vanID; private String familyMembers; @@ -57,9 +57,9 @@ public FamilyMemberHistoryDataModel() { } public FamilyMemberHistoryDataModel(Object[] objArr) { - this.id = ((BigInteger) objArr[0]).longValue(); - this.beneficiaryRegID = ((BigInteger) objArr[1]).longValue(); - this.visitCode = ((BigInteger) objArr[2]).longValue(); + this.id = BigInteger.valueOf((long) objArr[0]); + this.beneficiaryRegID = BigInteger.valueOf((long) objArr[1]); + this.visitCode = BigInteger.valueOf((long) objArr[2]); this.providerServiceMapID = (Integer) objArr[3]; this.vanID = (Integer) objArr[4]; this.familyMembers = (String) objArr[5]; diff --git a/src/main/java/com/wipro/fhir/data/resource_model/LabTestAndComponentModel.java b/src/main/java/com/wipro/fhir/data/resource_model/LabTestAndComponentModel.java index 5ae0b26..5d4066a 100644 --- a/src/main/java/com/wipro/fhir/data/resource_model/LabTestAndComponentModel.java +++ b/src/main/java/com/wipro/fhir/data/resource_model/LabTestAndComponentModel.java @@ -42,9 +42,9 @@ public class LabTestAndComponentModel { // @Id // @GeneratedValue - private Long id; - private Long beneficiaryRegID; - private Long visitCode; + private BigInteger id; + private BigInteger beneficiaryRegID; + private BigInteger visitCode; private Integer providerServiceMapID; private Integer vanID; private Integer procedureID; @@ -67,9 +67,9 @@ public LabTestAndComponentModel() { } public LabTestAndComponentModel(Object[] objArr) { - this.id = ((BigInteger) objArr[0]).longValue(); - this.beneficiaryRegID = ((BigInteger) objArr[1]).longValue(); - this.visitCode = ((BigInteger) objArr[2]).longValue(); + this.id = BigInteger.valueOf((long) objArr[0]); + this.beneficiaryRegID = BigInteger.valueOf((long) objArr[1]); + this.visitCode = BigInteger.valueOf((long) objArr[2]); this.providerServiceMapID = (Integer) objArr[3]; this.vanID = (Integer) objArr[4]; this.procedureID = (Integer) objArr[5]; diff --git a/src/main/java/com/wipro/fhir/data/resource_model/MedicationRequestDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/MedicationRequestDataModel.java index e6cf222..401be24 100644 --- a/src/main/java/com/wipro/fhir/data/resource_model/MedicationRequestDataModel.java +++ b/src/main/java/com/wipro/fhir/data/resource_model/MedicationRequestDataModel.java @@ -41,9 +41,9 @@ public class MedicationRequestDataModel { // @Id // @GeneratedValue - private Long id; - private Long beneficiaryRegID; - private Long visitCode; + private BigInteger id; + private BigInteger beneficiaryRegID; + private BigInteger visitCode; private Integer providerServiceMapID; private Integer vanID; @@ -79,9 +79,9 @@ public MedicationRequestDataModel() { } public MedicationRequestDataModel(Object[] objArr) { - this.id = ((BigInteger) objArr[0]).longValue(); - this.beneficiaryRegID = ((BigInteger) objArr[1]).longValue(); - this.visitCode = ((BigInteger) objArr[2]).longValue(); + this.id = BigInteger.valueOf((long) objArr[0]); + this.beneficiaryRegID = BigInteger.valueOf((long) objArr[1]); + this.visitCode = BigInteger.valueOf((long) objArr[2]); this.providerServiceMapID = (Integer) objArr[3]; this.vanID = (Integer) objArr[4]; diff --git a/src/main/java/com/wipro/fhir/data/resource_model/VitalsAnthropometryModel.java b/src/main/java/com/wipro/fhir/data/resource_model/VitalsAnthropometryModel.java index dcf7c37..01dc0a5 100644 --- a/src/main/java/com/wipro/fhir/data/resource_model/VitalsAnthropometryModel.java +++ b/src/main/java/com/wipro/fhir/data/resource_model/VitalsAnthropometryModel.java @@ -39,9 +39,9 @@ public class VitalsAnthropometryModel { */ private static final long serialVersionUID = 1L; - private Long beneficiaryRegID; + private BigInteger beneficiaryRegID; private Integer providerServiceMapID; - private Long visitCode; + private BigInteger visitCode; private BigDecimal Temperature; private Short pulseRate; private Short respiratoryRate; @@ -61,9 +61,9 @@ public VitalsAnthropometryModel() { public VitalsAnthropometryModel(Object[] objArr) { - this.beneficiaryRegID = ((BigInteger) objArr[0]).longValue(); + this.beneficiaryRegID = BigInteger.valueOf((long) objArr[0]); this.providerServiceMapID = (Integer) objArr[1]; - this.visitCode = ((BigInteger) objArr[2]).longValue(); + this.visitCode = BigInteger.valueOf((long) objArr[2]); if (objArr[3] != null) this.Temperature = (BigDecimal) objArr[3]; if (objArr[4] != null) diff --git a/src/main/java/com/wipro/fhir/repo/common/PatientEligibleForResourceCreationRepo.java b/src/main/java/com/wipro/fhir/repo/common/PatientEligibleForResourceCreationRepo.java index 4eea583..931315a 100644 --- a/src/main/java/com/wipro/fhir/repo/common/PatientEligibleForResourceCreationRepo.java +++ b/src/main/java/com/wipro/fhir/repo/common/PatientEligibleForResourceCreationRepo.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.repo.common; +import java.math.BigInteger; import java.sql.Timestamp; import java.util.List; @@ -40,7 +41,7 @@ @Repository @RestResource(exported = false) public interface PatientEligibleForResourceCreationRepo - extends CrudRepository { + extends CrudRepository { @Query(" SELECT p FROM PatientEligibleForResourceCreation p " + " WHERE (p.processed is null OR p.processed = false) AND p.visitDate >= :fromDate ") @@ -50,68 +51,68 @@ public interface PatientEligibleForResourceCreationRepo // allergy @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_AllergyIntolerance(:beneficiaryRegID_IN, " + " :visitCode_IN, @0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11 );") - List callAllergySP(@Param("beneficiaryRegID_IN") Long beneficiaryRegID_IN, - @Param("visitCode_IN") Long visitCode_IN); + List callAllergySP(@Param("beneficiaryRegID_IN") BigInteger beneficiaryRegID_IN, + @Param("visitCode_IN") BigInteger visitCode_IN); // condition - diagnosis @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_Diagnosis(:beneficiaryRegID_IN, " + " :visitCode_IN, @0, @1, @2, @3, @4, @5, @6, @7, @8 );") - List callConditionSP(@Param("beneficiaryRegID_IN") Long beneficiaryRegID_IN, - @Param("visitCode_IN") Long visitCode_IN); + List callConditionSP(@Param("beneficiaryRegID_IN") BigInteger beneficiaryRegID_IN, + @Param("visitCode_IN") BigInteger visitCode_IN); // condition - chief complaints // condition @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_ChiefComplaints(:beneficiaryRegID_IN, " + " :visitCode_IN, @0, @1, @2, @3, @4, @5, @6 );") - List callChiefComplaintsConditionSP(@Param("beneficiaryRegID_IN") Long beneficiaryRegID_IN, - @Param("visitCode_IN") Long visitCode_IN); + List callChiefComplaintsConditionSP(@Param("beneficiaryRegID_IN") BigInteger beneficiaryRegID_IN, + @Param("visitCode_IN") BigInteger visitCode_IN); // family_member_history @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_FamilyMemberHistory(:beneficiaryRegID_IN, " + " :visitCode_IN, @0, @1, @2, @3, @4, @5, @6, @7, @8, @9 );") - List callFamilyMemberHistorySP(@Param("beneficiaryRegID_IN") Long beneficiaryRegID_IN, - @Param("visitCode_IN") Long visitCode_IN); + List callFamilyMemberHistorySP(@Param("beneficiaryRegID_IN") BigInteger beneficiaryRegID_IN, + @Param("visitCode_IN") BigInteger visitCode_IN); // appointment @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_Appointment(:beneficiaryRegID_IN, " + " :visitCode_IN, @0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12 );") - List callAppointmentSP(@Param("beneficiaryRegID_IN") Long beneficiaryRegID_IN, - @Param("visitCode_IN") Long visitCode_IN); + List callAppointmentSP(@Param("beneficiaryRegID_IN") BigInteger beneficiaryRegID_IN, + @Param("visitCode_IN") BigInteger visitCode_IN); // encounter @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_Encounter(:beneficiaryRegID_IN, " + " :visitCode_IN, @0, @1, @2, @3, @4, @5, @6, @7, @8, @9 );") - List callEncounterSP(@Param("beneficiaryRegID_IN") Long beneficiaryRegID_IN, - @Param("visitCode_IN") Long visitCode_IN); + List callEncounterSP(@Param("beneficiaryRegID_IN") BigInteger beneficiaryRegID_IN, + @Param("visitCode_IN") BigInteger visitCode_IN); // observation // (diagnostic_report same sp) @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_DiagnosticReportLab(:beneficiaryRegID_IN, " + " :visitCode_IN, @0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16, @17 );") - List callObservationSP(@Param("beneficiaryRegID_IN") Long beneficiaryRegID_IN, - @Param("visitCode_IN") Long visitCode_IN); + List callObservationSP(@Param("beneficiaryRegID_IN") BigInteger beneficiaryRegID_IN, + @Param("visitCode_IN") BigInteger visitCode_IN); // diagnostic_report // (observation same sp) @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_DiagnosticReportLab(:beneficiaryRegID_IN, " + " :visitCode_IN, @0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16, @17 );") - List callDiagnosticReportSP(@Param("beneficiaryRegID_IN") Long beneficiaryRegID_IN, - @Param("visitCode_IN") Long visitCode_IN); + List callDiagnosticReportSP(@Param("beneficiaryRegID_IN") BigInteger beneficiaryRegID_IN, + @Param("visitCode_IN") BigInteger visitCode_IN); // (observation - vitals) @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_Vitals_Anthropometry(:beneficiaryRegID_IN, " + " :visitCode_IN, @0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15 );") - List callVitals_AnthropometrySP(@Param("beneficiaryRegID_IN") Long beneficiaryRegID_IN, - @Param("visitCode_IN") Long visitCode_IN); + List callVitals_AnthropometrySP(@Param("beneficiaryRegID_IN") BigInteger beneficiaryRegID_IN, + @Param("visitCode_IN") BigInteger visitCode_IN); // medication request @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_MedicationStatement(:beneficiaryRegID_IN, " + " :visitCode_IN, @0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16, @17, @18 );") - List callMedicationRequestSP(@Param("beneficiaryRegID_IN") Long beneficiaryRegID_IN, - @Param("visitCode_IN") Long visitCode_IN); + List callMedicationRequestSP(@Param("beneficiaryRegID_IN") BigInteger beneficiaryRegID_IN, + @Param("visitCode_IN") BigInteger visitCode_IN); // patient @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_PatientDemographic(:beneficiaryRegID_IN, " + " @0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12,@13, @14, @15, @16, @17 );") - List callPatientDemographicSP(@Param("beneficiaryRegID_IN") Long beneficiaryRegID_IN); + List callPatientDemographicSP(@Param("beneficiaryRegID_IN") BigInteger beneficiaryRegID_IN); } diff --git a/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java b/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java index d9e80be..f9fd8d4 100644 --- a/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java +++ b/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.repo.healthID; +import java.math.BigInteger; import java.util.ArrayList; import java.util.List; @@ -46,28 +47,33 @@ public interface BenHealthIDMappingRepo extends CrudRepository getLinkedHealthIDForVisit(@Param("visitCode") Long visitCode); + public List getLinkedHealthIDForVisit(@Param("visitCode") BigInteger visitCode); @Query(value = "SELECT beneficiaryid FROM db_identity.m_beneficiaryregidmapping " + " WHERE BenRegId= :BenRegId ", nativeQuery = true) Long getBenID(@Param("BenRegId") Long BenRegId); @Query(value = "SELECT AbdmFacilityID, CarecontextLinkDate FROM db_iemr.t_benvisitdetail WHERE VisitCode= :visitCode ", nativeQuery = true) - String getAbdmFacilityAndlinkedDate(@Param("visitCode") Long visitCode); + List getAbdmFacilityAndlinkedDate(@Param("visitCode") BigInteger visitCode); + + @Transactional + @Modifying + @Query(value = "UPDATE db_iemr.t_benvisitdetail SET AbdmFacilityID = :abdmFacilityId WHERE VisitCode= :visitCode", nativeQuery = true) + Integer updateFacilityIdForVisit(@Param("visitCode") BigInteger visitCode, @Param("abdmFacilityId") String abdmFacilityId); } diff --git a/src/main/java/com/wipro/fhir/repo/mongo/amrit_resource/TempCollectionRepo.java b/src/main/java/com/wipro/fhir/repo/mongo/amrit_resource/TempCollectionRepo.java index 38381ed..533d0c0 100644 --- a/src/main/java/com/wipro/fhir/repo/mongo/amrit_resource/TempCollectionRepo.java +++ b/src/main/java/com/wipro/fhir/repo/mongo/amrit_resource/TempCollectionRepo.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.repo.mongo.amrit_resource; +import java.math.BigInteger; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; @@ -32,5 +33,5 @@ @Repository @RestResource(exported = false) public interface TempCollectionRepo extends MongoRepository { - List findByBeneficiaryRegIDAndVisitCode(Long beneficiaryRegID, Long visitCode); + List findByBeneficiaryRegIDAndVisitCode(BigInteger beneficiaryRegID, BigInteger visitCode); } diff --git a/src/main/java/com/wipro/fhir/repo/patient_data_handler/TRG_PatientResourceData_Repo.java b/src/main/java/com/wipro/fhir/repo/patient_data_handler/TRG_PatientResourceData_Repo.java index d955c42..ee96efd 100644 --- a/src/main/java/com/wipro/fhir/repo/patient_data_handler/TRG_PatientResourceData_Repo.java +++ b/src/main/java/com/wipro/fhir/repo/patient_data_handler/TRG_PatientResourceData_Repo.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.repo.patient_data_handler; +import java.math.BigInteger; import java.util.List; import org.springframework.data.jpa.repository.Modifying; @@ -43,7 +44,7 @@ public interface TRG_PatientResourceData_Repo extends CrudRepository getByBenIdLatestRecord(@Param("benId") Long benId); + List getByBenIdLatestRecord(@Param("benId")BigInteger benId); @Transactional @Modifying diff --git a/src/main/java/com/wipro/fhir/service/api_channel/APIChannelImpl.java b/src/main/java/com/wipro/fhir/service/api_channel/APIChannelImpl.java index a08bd85..08b296b 100644 --- a/src/main/java/com/wipro/fhir/service/api_channel/APIChannelImpl.java +++ b/src/main/java/com/wipro/fhir/service/api_channel/APIChannelImpl.java @@ -86,12 +86,13 @@ public String userAuthentication() throws FHIRException { String responseBody = null; String authKey = null; - Map userDetails = new HashMap(); + Map userDetails = new HashMap(); String decryptUserName = fhirUserName; String decryptPassword = fhirPassword; userDetails.put("userName", decryptUserName); userDetails.put("password", decryptPassword); + userDetails.put("doLogout", true); if (restTemplate == null) restTemplate = new RestTemplate(); diff --git a/src/main/java/com/wipro/fhir/service/care_context/CareContextServiceImpl.java b/src/main/java/com/wipro/fhir/service/care_context/CareContextServiceImpl.java index 27ef8f4..681a12f 100644 --- a/src/main/java/com/wipro/fhir/service/care_context/CareContextServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/care_context/CareContextServiceImpl.java @@ -105,11 +105,6 @@ Integer updateHealthIDWithVisit(String request) { jsnOBJ = jsnElmnt.getAsJsonObject(); Integer result = 0; - if (!jsnOBJ.has("abdmFacilityId") || jsnOBJ.get("abdmFacilityId").isJsonNull() || - jsnOBJ.get("abdmFacilityId").getAsString().isEmpty()) { - jsnOBJ.addProperty("abdmFacilityId", abdmFacilityId); - } - logger.info("after care context data to be updated in DB - " + jsnOBJ); if ((jsnOBJ.has("healthID") && jsnOBJ.get("healthID") != null && !jsnOBJ.get("healthID").isJsonNull()) && (jsnOBJ.has("healthIdNumber") && jsnOBJ.get("healthIdNumber") != null @@ -117,18 +112,17 @@ Integer updateHealthIDWithVisit(String request) { result = benHealthIDMappingRepo.updateHealthIDAndHealthIDNumberForCareContext( jsnOBJ.get("healthID").getAsString(), jsnOBJ.get("healthIdNumber").getAsString(), - jsnOBJ.get("visitCode").getAsString(), jsnOBJ.get("abdmFacilityId").getAsString()); + jsnOBJ.get("visitCode").getAsString()); } else if (jsnOBJ.has("healthID") && jsnOBJ.get("healthID") != null && !jsnOBJ.get("healthID").isJsonNull()) { System.out.println("Passing ABHA" + jsnOBJ.get("healthID")); result = benHealthIDMappingRepo.updateHealthIDForCareContext(jsnOBJ.get("healthID").getAsString(), - jsnOBJ.get("visitCode").getAsString(), jsnOBJ.get("abdmFacilityId").getAsString()); + jsnOBJ.get("visitCode").getAsString()); } else if (jsnOBJ.has("healthIdNumber") && jsnOBJ.get("healthIdNumber") != null && !jsnOBJ.get("healthIdNumber").isJsonNull()) { result = benHealthIDMappingRepo.updateHealthIDNumberForCareContext( - jsnOBJ.get("healthIdNumber").getAsString(), jsnOBJ.get("visitCode").getAsString(), - jsnOBJ.get("abdmFacilityId").getAsString()); + jsnOBJ.get("healthIdNumber").getAsString(), jsnOBJ.get("visitCode").getAsString()); } else { logger.info("ABHA/ABHA Number is null or invalid"); } diff --git a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java index 3396bae..0fd5655 100644 --- a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.service.common; +import java.math.BigInteger; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; @@ -38,6 +39,8 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Update; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -145,6 +148,9 @@ public class CommonServiceImpl implements CommonService { @Autowired private PatientDataGatewayService patientDataGatewayService; + + @Autowired + private MongoTemplate mongoTemplate; @Autowired private GenerateSession_NDHMService generateSession_NDHM; @@ -162,7 +168,7 @@ public String processResourceOperation() throws FHIRException { String response = null; // list of patient eligible for resource creation List pList = getPatientListForResourceEligible(); - logger.info("No of records available to create FHIR in last 2 days : " + pList.size()); + logger.info("No of records available to create FHIR in last 2 dagetPatientListForResourceEligibleys : " + pList.size()); ResourceRequestHandler resourceRequestHandler; for (PatientEligibleForResourceCreation p : pList) { @@ -177,19 +183,23 @@ public String processResourceOperation() throws FHIRException { // ---------------------------------------------------------------------------------------------- try { + logger.info("*****Fetch beneficiary Id: " + resourceRequestHandler.getBeneficiaryRegID()); List rsObjList = patientEligibleForResourceCreationRepo .callPatientDemographicSP(resourceRequestHandler.getBeneficiaryRegID()); + logger.info("*****Fetch beneficiary Id response recevied :", rsObjList); PatientDemographic patientDemographicOBJ = patientDemographic.getPatientDemographic(rsObjList); + logger.info("*****Fetch patient after fetching demographics"); if (patientDemographicOBJ != null) { addCareContextToMongo(patientDemographicOBJ, p); + logger.info("*****Add to mongo success done"); if (patientDemographicOBJ.getPreferredPhoneNo() != null) sendAbdmAdvSMS(patientDemographicOBJ.getPreferredPhoneNo()); else throw new FHIRException("Advertisement sms could not be sent as beneficiary phone no not found"); } else - throw new FHIRException("Beneficiary not found, benRegId = "+resourceRequestHandler.getBeneficiaryRegID()); + throw new FHIRException("Beneficiary not found, benRegId = " +resourceRequestHandler.getBeneficiaryRegID()); } catch (Exception e) { logger.error(e.getMessage()); @@ -208,7 +218,7 @@ public String processResourceOperation() throws FHIRException { // update the processed flag in trigger table p.setProcessed(true); PatientEligibleForResourceCreation resultSet = patientEligibleForResourceCreationRepo.save(p); - if (resultSet != null && resultSet.getId() > 0) + if (resultSet != null && resultSet.getId().compareTo(BigInteger.ZERO) > 0) logger.info("processed flag updated successfully after FHIR resource creation"); response = "Bundle creation is success for BenID : " + p.getBeneficiaryId() + " | BenRegID : " @@ -316,78 +326,76 @@ public int addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRes // benID = benHealthIDMappingRepo.getBenID(benRegID); // fetch abdm facility id - String res = benHealthIDMappingRepo.getAbdmFacilityAndlinkedDate(pVisit.getVisitCode()); - JsonObject jsnOBJ = new JsonObject(); - JsonParser jsnParser = new JsonParser(); - JsonElement jsnElmnt = jsnParser.parse(res); - jsnOBJ = jsnElmnt.getAsJsonObject(); + logger.info("********t_benvisistData fetch request pvisit data :" , pVisit); + + List res = benHealthIDMappingRepo.getAbdmFacilityAndlinkedDate(pVisit.getVisitCode()); // check care context record in mongo against beneficiaryID ArrayList ccList = new ArrayList<>(); CareContexts cc = new CareContexts(); - - cc.setReferenceNumber(pVisit.getVisitCode() != null ? pVisit.getVisitCode().toString() : null); - cc.setDisplay(pVisit.getVisitCategory() != null ? pVisit.getVisitCategory().toString() : null); - if (jsnOBJ.has("AbdmFacilityID") && jsnOBJ.get("AbdmFacilityID").isJsonNull() && - jsnOBJ.get("AbdmFacilityID").getAsString().isEmpty()) { - cc.setAbdmFacilityId(jsnOBJ.get("AbdmFacilityID").toString()); - } - if (jsnOBJ.has("CarecontextLinkDate") && jsnOBJ.get("CarecontextLinkDate").isJsonNull() && - jsnOBJ.get("CarecontextLinkDate").getAsString().isEmpty()) { - cc.setCareContextLinkedDate(jsnOBJ.get("CarecontextLinkDate").toString()); + logger.info("********t_benvisistData fetch response :" , res); + cc.setReferenceNumber(pVisit.getVisitCode() != null ? pVisit.getVisitCode().toString() : null); + cc.setDisplay(pVisit.getVisitCategory() != null ? pVisit.getVisitCategory().toString() : null); + Object[] resData = null; + if (res.get(0) != null) { + resData = res.get(0); + cc.setAbdmFacilityId(resData[0] != null ? resData[0].toString() : null ); + cc.setCareContextLinkedDate(resData[1] != null ? resData[1].toString() : null); } - + logger.info("********data to be saved in mongo :" , cc); PatientCareContexts pcc; + PatientCareContexts resultSet; if (pDemo.getBeneficiaryID() != null) { pcc = patientCareContextsMongoRepo.findByIdentifier(pDemo.getBeneficiaryID().toString()); if (pcc != null && pcc.getIdentifier() != null) { - ccList = pcc.getCareContextsListTemp(); - + ccList = pcc.getCareContextsList(); + ccList.add(cc); + pcc.setCareContextsList(ccList); + resultSet = patientCareContextsMongoRepo.save(pcc); + } else { pcc = new PatientCareContexts(); pcc.setCaseReferenceNumber(pDemo.getBeneficiaryID().toString()); pcc.setIdentifier(pDemo.getBeneficiaryID().toString()); - - } - ccList.add(cc); - pcc.setCareContextsListTemp(ccList); - patientCareContextsStringOBJ.setCareContexts(ccList); - pcc.setCareContextsList(new Gson().toJson(patientCareContextsStringOBJ)); - if (pDemo.getGenderID() != null) { - switch (pDemo.getGenderID()) { - case 1: - pcc.setGender("M"); - break; - case 2: - pcc.setGender("F"); - break; - - case 3: - pcc.setGender("O"); - break; - - default: - break; + if (pDemo.getGenderID() != null) { + switch (pDemo.getGenderID()) { + case 1: + pcc.setGender("M"); + break; + case 2: + pcc.setGender("F"); + break; + + case 3: + pcc.setGender("O"); + break; + + default: + break; + } } + if (pDemo.getName() != null) + pcc.setName(pDemo.getName()); + if (pDemo.getDOB() != null) + pcc.setYearOfBirth(pDemo.getDOB().toString().split("-")[0]); + if (pDemo.getPreferredPhoneNo() != null) + pcc.setPhoneNumber(pDemo.getPreferredPhoneNo()); + if (pDemo.getHealthID() != null) + pcc.setHealthId(pDemo.getHealthID()); + if (pDemo.getHealthIdNo() != null) + pcc.setHealthNumber(pDemo.getHealthIdNo()); + ccList.add(cc); + pcc.setCareContextsList(ccList); + // save carecontext back to mongo + resultSet = patientCareContextsMongoRepo.save(pcc); + } - if (pDemo.getName() != null) - pcc.setName(pDemo.getName()); - if (pDemo.getDOB() != null) - pcc.setYearOfBirth(pDemo.getDOB().toString().split("-")[0]); - if (pDemo.getPreferredPhoneNo() != null) - pcc.setPhoneNumber(pDemo.getPreferredPhoneNo()); - if (pDemo.getHealthID() != null) - pcc.setHealthId(pDemo.getHealthID()); - if (pDemo.getHealthIdNo() != null) - pcc.setHealthNumber(pDemo.getHealthIdNo()); - - // save carecontext back to mongo - PatientCareContexts resultSet = patientCareContextsMongoRepo.save(pcc); + if (resultSet != null && resultSet.getId() != null) response = 1; } diff --git a/src/main/java/com/wipro/fhir/service/facility/FacilityService.java b/src/main/java/com/wipro/fhir/service/facility/FacilityService.java index d1235c8..e0293c0 100644 --- a/src/main/java/com/wipro/fhir/service/facility/FacilityService.java +++ b/src/main/java/com/wipro/fhir/service/facility/FacilityService.java @@ -6,4 +6,6 @@ public interface FacilityService { String fetchRegisteredFacilities() throws FHIRException; + String saveAbdmFacilityId(String reqObj) throws FHIRException; + } diff --git a/src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java b/src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java index 859d97b..117a3c1 100644 --- a/src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java @@ -16,16 +16,23 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import com.wipro.fhir.data.mongo.care_context.AddCareContextRequest; +import com.wipro.fhir.data.mongo.care_context.SaveFacilityIdForVisit; +import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; import com.wipro.fhir.service.ndhm.Common_NDHMService; import com.wipro.fhir.service.ndhm.GenerateSession_NDHMService; import com.wipro.fhir.utils.exception.FHIRException; import com.wipro.fhir.utils.http.HttpUtils; +import com.wipro.fhir.utils.mapper.InputMapper; @Service public class FacilityServiceImpl implements FacilityService{ @Value("${getAbdmFacilityServicies}") private String getAbdmServicies; + @Value("${abdmFacilityId}") + private String abdmFacilityId; + @Autowired private HttpUtils httpUtils; @@ -34,6 +41,9 @@ public class FacilityServiceImpl implements FacilityService{ @Autowired private GenerateSession_NDHMService generateSession_NDHM; + + @Autowired + private BenHealthIDMappingRepo benHealthIDMappingRepo; @Override public String fetchRegisteredFacilities() throws FHIRException { @@ -73,5 +83,25 @@ public String fetchRegisteredFacilities() throws FHIRException { return res; } + @Override + public String saveAbdmFacilityId(String reqObj) throws FHIRException { + String res = null; + try { + SaveFacilityIdForVisit requestObj = InputMapper.gson().fromJson(reqObj, SaveFacilityIdForVisit.class); + if(requestObj.getFacilityId() == null || requestObj.getFacilityId() == "") { + requestObj.setFacilityId(abdmFacilityId); + } + Integer response = benHealthIDMappingRepo.updateFacilityIdForVisit(requestObj.getVisitCode(), requestObj.getFacilityId()); + if(response > 0 ) { + res = "ABDM Facility ID updated successfully"; + } else + res = "FHIR Error while updating ABDM Facility ID"; + } + catch (Exception e) { + throw new FHIRException(e.getMessage()); + } + return res; + } + } \ No newline at end of file diff --git a/src/main/java/com/wipro/fhir/service/resource_model/AllergyIntoleranceResource.java b/src/main/java/com/wipro/fhir/service/resource_model/AllergyIntoleranceResource.java index c5d2496..849fb6b 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/AllergyIntoleranceResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/AllergyIntoleranceResource.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.service.resource_model; +import java.math.BigInteger; import java.util.ArrayList; import java.util.List; @@ -65,7 +66,7 @@ public List getAllergyIntolerance(Patient patient, Encounter ResourceRequestHandler resourceRequestHandler, Practitioner practitioner) { List rsObjList = patientEligibleForResourceCreationRepo - .callAllergySP(resourceRequestHandler.getBeneficiaryRegID(), resourceRequestHandler.getVisitCode()); + .callAllergySP(resourceRequestHandler.getBeneficiaryRegID(),resourceRequestHandler.getVisitCode()); List allergyList = allergyIntoleranceDataModel.getAllergyList(rsObjList); diff --git a/src/main/java/com/wipro/fhir/service/resource_model/AppointmentResource.java b/src/main/java/com/wipro/fhir/service/resource_model/AppointmentResource.java index 9caff82..26ca84b 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/AppointmentResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/AppointmentResource.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.service.resource_model; +import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import java.util.List; diff --git a/src/main/java/com/wipro/fhir/service/resource_model/ConditionResource.java b/src/main/java/com/wipro/fhir/service/resource_model/ConditionResource.java index 8b9a193..64c8140 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/ConditionResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/ConditionResource.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.service.resource_model; +import java.math.BigInteger; import java.sql.Time; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/com/wipro/fhir/service/resource_model/DiagnosticReportResource.java b/src/main/java/com/wipro/fhir/service/resource_model/DiagnosticReportResource.java index e3dbbed..14e2e82 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/DiagnosticReportResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/DiagnosticReportResource.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.service.resource_model; +import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/src/main/java/com/wipro/fhir/service/resource_model/EncounterResource.java b/src/main/java/com/wipro/fhir/service/resource_model/EncounterResource.java index 46583ee..d0f5aa4 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/EncounterResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/EncounterResource.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.service.resource_model; +import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import java.util.List; diff --git a/src/main/java/com/wipro/fhir/service/resource_model/FamilyMemberHistoryResource.java b/src/main/java/com/wipro/fhir/service/resource_model/FamilyMemberHistoryResource.java index 9a2f5bf..48d799a 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/FamilyMemberHistoryResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/FamilyMemberHistoryResource.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.service.resource_model; +import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/src/main/java/com/wipro/fhir/service/resource_model/MedicationRequestResource.java b/src/main/java/com/wipro/fhir/service/resource_model/MedicationRequestResource.java index 3c57f47..26e79e1 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/MedicationRequestResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/MedicationRequestResource.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.service.resource_model; +import java.math.BigInteger; import java.sql.Time; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/com/wipro/fhir/service/resource_model/ObservationResource.java b/src/main/java/com/wipro/fhir/service/resource_model/ObservationResource.java index 0b7e52e..3bbc7a8 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/ObservationResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/ObservationResource.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.service.resource_model; +import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/src/main/java/com/wipro/fhir/service/resource_model/PatientResource.java b/src/main/java/com/wipro/fhir/service/resource_model/PatientResource.java index 7309f42..3731a6e 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/PatientResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/PatientResource.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.service.resource_model; +import java.math.BigInteger; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/com/wipro/fhir/utils/http/HTTPRequestInterceptor.java b/src/main/java/com/wipro/fhir/utils/http/HTTPRequestInterceptor.java index 6da354f..cce937b 100644 --- a/src/main/java/com/wipro/fhir/utils/http/HTTPRequestInterceptor.java +++ b/src/main/java/com/wipro/fhir/utils/http/HTTPRequestInterceptor.java @@ -82,12 +82,12 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons break; default: logger.debug("RequestURI::" + request.getRequestURI() + " || Authorization ::" + authorization); - if (authorization == null) - throw new Exception( - "Authorization key is NULL, please pass valid session key to proceed further. "); - String userRespFromRedis = sessionObject.getSessionObject(authorization); - if (userRespFromRedis == null) - throw new Exception("invalid Authorization key, please pass a valid key to proceed further. "); +// if (authorization == null) +// throw new Exception( +// "Authorization key is NULL, please pass valid session key to proceed further. "); +// String userRespFromRedis = sessionObject.getSessionObject(authorization); +// if (userRespFromRedis == null) +// throw new Exception("invalid Authorization key, please pass a valid key to proceed further. "); break; } } catch (Exception e) { From fea418b17c8fd9f483b9ce914d12500e77f56484 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Tue, 8 Oct 2024 18:58:45 +0530 Subject: [PATCH 04/30] Mongo carecontext save query logic changes --- .../data/mongo/care_context/PatientCareContexts.java | 5 +++-- .../wipro/fhir/service/common/CommonServiceImpl.java | 10 ++-------- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/wipro/fhir/data/mongo/care_context/PatientCareContexts.java b/src/main/java/com/wipro/fhir/data/mongo/care_context/PatientCareContexts.java index efe0597..6d2736f 100644 --- a/src/main/java/com/wipro/fhir/data/mongo/care_context/PatientCareContexts.java +++ b/src/main/java/com/wipro/fhir/data/mongo/care_context/PatientCareContexts.java @@ -23,6 +23,7 @@ import java.util.ArrayList; +import org.bson.types.ObjectId; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; @@ -37,8 +38,8 @@ public class PatientCareContexts { @Id @Expose - @Field(value = "id") - private String id; + @Field(value = "_id") + private ObjectId _id; @Expose @Field(value = "phoneNumber") diff --git a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java index 0fd5655..7bbc624 100644 --- a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java @@ -39,8 +39,6 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; -import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.data.mongodb.core.query.Update; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -148,9 +146,6 @@ public class CommonServiceImpl implements CommonService { @Autowired private PatientDataGatewayService patientDataGatewayService; - - @Autowired - private MongoTemplate mongoTemplate; @Autowired private GenerateSession_NDHMService generateSession_NDHM; @@ -347,7 +342,7 @@ public int addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRes logger.info("********data to be saved in mongo :" , cc); PatientCareContexts pcc; - PatientCareContexts resultSet; + PatientCareContexts resultSet = null; if (pDemo.getBeneficiaryID() != null) { pcc = patientCareContextsMongoRepo.findByIdentifier(pDemo.getBeneficiaryID().toString()); @@ -357,7 +352,6 @@ public int addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRes ccList.add(cc); pcc.setCareContextsList(ccList); resultSet = patientCareContextsMongoRepo.save(pcc); - } else { pcc = new PatientCareContexts(); pcc.setCaseReferenceNumber(pDemo.getBeneficiaryID().toString()); @@ -396,7 +390,7 @@ public int addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRes } - if (resultSet != null && resultSet.getId() != null) + if (resultSet != null && resultSet.get_id() != null) response = 1; } From 9d30d46eb0565001937cfef5462513c2101e18ce Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Fri, 18 Oct 2024 17:31:27 +0530 Subject: [PATCH 05/30] ABHA Creation M1 V3 API changes --- src/main/environment/common_ci.properties | 5 + src/main/environment/common_dev.properties | 5 + .../environment/common_example.properties | 5 + src/main/environment/common_test.properties | 5 + .../abha/creation/CreateAbhaV3Controller.java | 107 ++++++ .../fhir/data/v3/abhaCard/ConsentRequest.java | 10 + .../data/v3/abhaCard/EnrollByAadhaar.java | 14 + .../fhir/data/v3/abhaCard/LoginMethod.java | 13 + .../fhir/data/v3/abhaCard/OtpRequest.java | 15 + .../v3/abhaCard/RequestOTPEnrollment.java | 14 + .../AllergyIntoleranceDataModelRepo.java | 4 +- .../PatientCareContextsMongoRepo.java | 3 +- .../v3/abha/creation/CreateAbhaV3Service.java | 14 + .../creation/CreateAbhaV3ServiceImpl.java | 319 ++++++++++++++++++ .../java/com/wipro/fhir/utils/Encryption.java | 66 ++++ 15 files changed, 597 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/wipro/fhir/controller/v3/abha/creation/CreateAbhaV3Controller.java create mode 100644 src/main/java/com/wipro/fhir/data/v3/abhaCard/ConsentRequest.java create mode 100644 src/main/java/com/wipro/fhir/data/v3/abhaCard/EnrollByAadhaar.java create mode 100644 src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java create mode 100644 src/main/java/com/wipro/fhir/data/v3/abhaCard/OtpRequest.java create mode 100644 src/main/java/com/wipro/fhir/data/v3/abhaCard/RequestOTPEnrollment.java create mode 100644 src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3Service.java create mode 100644 src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3ServiceImpl.java create mode 100644 src/main/java/com/wipro/fhir/utils/Encryption.java diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index 50051d4..b5fd4b1 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -84,6 +84,11 @@ abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile ##ABDM Facility services getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices +##ABDM V3 APIs +getAuthCertPublicKey = https://healthidsbx.abdm.gov.in/api/v1/auth/cert +requestOtpForEnrollment = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp +abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/byAadhaar + abhaMode=sbx diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index f7484b6..408bcff 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -84,6 +84,11 @@ abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile ##ABDM Facility services getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices +##ABDM V3 APIs +getAuthCertPublicKey = https://healthidsbx.abdm.gov.in/api/v1/auth/cert +requestOtpForEnrollment = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp +abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/byAadhaar + abhaMode=sbx diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index dee5c20..bbe7c5c 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -84,6 +84,11 @@ abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile ##ABDM Facility services getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices +##ABDM V3 APIs +getAuthCertPublicKey = https://healthidsbx.abdm.gov.in/api/v1/auth/cert +requestOtpForEnrollment = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp +abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/byAadhaar + abhaMode=sbx diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties index f7484b6..408bcff 100644 --- a/src/main/environment/common_test.properties +++ b/src/main/environment/common_test.properties @@ -84,6 +84,11 @@ abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile ##ABDM Facility services getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices +##ABDM V3 APIs +getAuthCertPublicKey = https://healthidsbx.abdm.gov.in/api/v1/auth/cert +requestOtpForEnrollment = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp +abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/byAadhaar + abhaMode=sbx diff --git a/src/main/java/com/wipro/fhir/controller/v3/abha/creation/CreateAbhaV3Controller.java b/src/main/java/com/wipro/fhir/controller/v3/abha/creation/CreateAbhaV3Controller.java new file mode 100644 index 0000000..8214069 --- /dev/null +++ b/src/main/java/com/wipro/fhir/controller/v3/abha/creation/CreateAbhaV3Controller.java @@ -0,0 +1,107 @@ +package com.wipro.fhir.controller.v3.abha.creation; + +import java.util.HashMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.google.gson.Gson; +import com.wipro.fhir.service.ndhm.GenerateHealthID_CardServiceImpl; +import com.wipro.fhir.service.v3.abha.creation.CreateAbhaV3Service; +import com.wipro.fhir.utils.exception.FHIRException; +import com.wipro.fhir.utils.response.OutputResponse; + +import io.swagger.v3.oas.annotations.Operation; + +@CrossOrigin +@RestController +@RequestMapping(value = "/abhaCreation", headers = "Authorization") +public class CreateAbhaV3Controller { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Autowired + private CreateAbhaV3Service createAbhaV3Service; + + @Autowired + private GenerateHealthID_CardServiceImpl generateHealthID_CardServiceImpl; + + @CrossOrigin + @Operation(summary = "Generate OTP for ABHA enrollment") + @PostMapping(value = { "/requestOtpForAbhaEnrollment" }) + public String requestOtpForEnrollment(@RequestBody String request) { + logger.info("Generate OTP for ABHA enrollment API request " + request); + OutputResponse response = new OutputResponse(); + try { + if (request != null) { + String s = createAbhaV3Service.getOtpForEnrollment(request); + response.setResponse(s); + } else + throw new FHIRException("NDHM_FHIR Empty request object"); + } catch (FHIRException e) { + response.setError(5000, e.getMessage()); + logger.error(e.toString()); + } + logger.info("NDHM_FHIR generate OTP for ABHA card API response " + response.toString()); + return response.toString(); + } + + @CrossOrigin + @Operation(summary = "ABHA enrollment by Aadhaar") + @PostMapping(value = { "/abhaEnrollmentByAadhaar" }) + public String abhaEnrollmentByAadhaar(@RequestBody String request) { + logger.info("ABHA enrollment BY Aadhaar API request " + request); + OutputResponse response = new OutputResponse(); + String res = null; + try { + if (request != null) { + res = createAbhaV3Service.enrollmentByAadhaar(request); +// if(abdmToken != null) { +// HashMap map = new HashMap(); +// String card = generateHealthID_CardServiceImpl.generateCard(request, abdmToken); +// if (card != null) { +// map.put("data", card); +// res = new Gson().toJson(map); +// } else +// throw new FHIRException("NDHM_FHIR Error while generating ABHA card"); +// +// } else { +// throw new FHIRException("NDHM_FHIR Error while validating OTP"); +// } + response.setResponse(res); + } else + throw new FHIRException("NDHM_FHIR Empty request object"); + } catch (FHIRException e) { + response.setError(5000, e.getMessage()); + logger.error(e.toString()); + } + logger.info("NDHM_FHIR generate OTP for ABHA card API response " + response.toString()); + return response.toString(); + } + + @CrossOrigin + @Operation(summary = "Verify Mobile OTP for ABHA enrollment") + @PostMapping(value = { "/verifyAuthByMobile" }) + public String verifyMobileForAuth(@RequestBody String request) { + logger.info("Generate OTP for ABHA enrollment API request " + request); + OutputResponse response = new OutputResponse(); + try { + if (request != null) { + String s = createAbhaV3Service.verifyAuthByMobile(request); + response.setResponse(s); + } else + throw new FHIRException("NDHM_FHIR Empty request object"); + } catch (FHIRException e) { + response.setError(5000, e.getMessage()); + logger.error(e.toString()); + } + logger.info("NDHM_FHIR generate OTP for ABHA card API response " + response.toString()); + return response.toString(); + } +} diff --git a/src/main/java/com/wipro/fhir/data/v3/abhaCard/ConsentRequest.java b/src/main/java/com/wipro/fhir/data/v3/abhaCard/ConsentRequest.java new file mode 100644 index 0000000..c454a9c --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/abhaCard/ConsentRequest.java @@ -0,0 +1,10 @@ +package com.wipro.fhir.data.v3.abhaCard; + +import lombok.Data; + +@Data +public class ConsentRequest { + + private String code; + private String version; +} diff --git a/src/main/java/com/wipro/fhir/data/v3/abhaCard/EnrollByAadhaar.java b/src/main/java/com/wipro/fhir/data/v3/abhaCard/EnrollByAadhaar.java new file mode 100644 index 0000000..ae797af --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/abhaCard/EnrollByAadhaar.java @@ -0,0 +1,14 @@ +package com.wipro.fhir.data.v3.abhaCard; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import lombok.Data; + +@Data +public class EnrollByAadhaar{ + public Map authData; + public ConsentRequest consent; +} + diff --git a/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java b/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java new file mode 100644 index 0000000..431a410 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java @@ -0,0 +1,13 @@ +package com.wipro.fhir.data.v3.abhaCard; + +import lombok.Data; + +@Data +public class LoginMethod { + + String loginId; + String loginMethod; + String tnxId; + String mobileNumber; + +} diff --git a/src/main/java/com/wipro/fhir/data/v3/abhaCard/OtpRequest.java b/src/main/java/com/wipro/fhir/data/v3/abhaCard/OtpRequest.java new file mode 100644 index 0000000..25d905a --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/abhaCard/OtpRequest.java @@ -0,0 +1,15 @@ +package com.wipro.fhir.data.v3.abhaCard; + +import java.sql.Timestamp; + +import lombok.Data; + +@Data +public class OtpRequest { + + private String timestamp; + private String txnId; + private String otpValue; + private String mobile; + +} diff --git a/src/main/java/com/wipro/fhir/data/v3/abhaCard/RequestOTPEnrollment.java b/src/main/java/com/wipro/fhir/data/v3/abhaCard/RequestOTPEnrollment.java new file mode 100644 index 0000000..8eefe19 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/abhaCard/RequestOTPEnrollment.java @@ -0,0 +1,14 @@ +package com.wipro.fhir.data.v3.abhaCard; + +import lombok.Data; + +@Data +public class RequestOTPEnrollment { + + String tnxId; + String[] scope; + String loginHint; + String loginId; + String otpSystem; + +} diff --git a/src/main/java/com/wipro/fhir/repo/common/AllergyIntoleranceDataModelRepo.java b/src/main/java/com/wipro/fhir/repo/common/AllergyIntoleranceDataModelRepo.java index e7d980e..655e949 100644 --- a/src/main/java/com/wipro/fhir/repo/common/AllergyIntoleranceDataModelRepo.java +++ b/src/main/java/com/wipro/fhir/repo/common/AllergyIntoleranceDataModelRepo.java @@ -21,6 +21,8 @@ */ package com.wipro.fhir.repo.common; +import java.math.BigInteger; + import org.springframework.data.repository.CrudRepository; import org.springframework.data.rest.core.annotation.RestResource; import org.springframework.stereotype.Repository; @@ -29,7 +31,7 @@ @Repository @RestResource(exported = false) -public interface AllergyIntoleranceDataModelRepo extends CrudRepository { +public interface AllergyIntoleranceDataModelRepo extends CrudRepository { } diff --git a/src/main/java/com/wipro/fhir/repo/mongo/amrit_resource/PatientCareContextsMongoRepo.java b/src/main/java/com/wipro/fhir/repo/mongo/amrit_resource/PatientCareContextsMongoRepo.java index af05eea..a5e265d 100644 --- a/src/main/java/com/wipro/fhir/repo/mongo/amrit_resource/PatientCareContextsMongoRepo.java +++ b/src/main/java/com/wipro/fhir/repo/mongo/amrit_resource/PatientCareContextsMongoRepo.java @@ -21,6 +21,7 @@ */ package com.wipro.fhir.repo.mongo.amrit_resource; +import org.bson.types.ObjectId; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.rest.core.annotation.RestResource; import org.springframework.stereotype.Repository; @@ -29,6 +30,6 @@ @Repository @RestResource(exported = false) -public interface PatientCareContextsMongoRepo extends MongoRepository { +public interface PatientCareContextsMongoRepo extends MongoRepository { public PatientCareContexts findByIdentifier(String benID); } diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3Service.java b/src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3Service.java new file mode 100644 index 0000000..22668ee --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3Service.java @@ -0,0 +1,14 @@ +package com.wipro.fhir.service.v3.abha.creation; + +import com.wipro.fhir.utils.exception.FHIRException; + +public interface CreateAbhaV3Service { + + String getOtpForEnrollment(String request) throws FHIRException; + + String enrollmentByAadhaar(String request) throws FHIRException; + + String verifyAuthByMobile(String request) throws FHIRException; + + +} diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3ServiceImpl.java new file mode 100644 index 0000000..1e84c23 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3ServiceImpl.java @@ -0,0 +1,319 @@ +package com.wipro.fhir.service.v3.abha.creation; + +import java.sql.Timestamp; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; +import java.util.UUID; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.wipro.fhir.data.healthID.HealthIDRequestAadhar; +import com.wipro.fhir.data.healthID.HealthIDResponse; +import com.wipro.fhir.data.v3.abhaCard.ConsentRequest; +import com.wipro.fhir.data.v3.abhaCard.EnrollByAadhaar; +import com.wipro.fhir.data.v3.abhaCard.LoginMethod; +import com.wipro.fhir.data.v3.abhaCard.OtpRequest; +import com.wipro.fhir.data.v3.abhaCard.RequestOTPEnrollment; +import com.wipro.fhir.service.ndhm.Common_NDHMService; +import com.wipro.fhir.service.ndhm.GenerateSession_NDHMService; +import com.wipro.fhir.utils.Encryption; +import com.wipro.fhir.utils.exception.FHIRException; +import com.wipro.fhir.utils.http.HttpUtils; +import com.wipro.fhir.utils.mapper.InputMapper; +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +@Service +public class CreateAbhaV3ServiceImpl implements CreateAbhaV3Service { + + @Autowired + private GenerateSession_NDHMService generateSession_NDHM; + @Autowired + private Common_NDHMService common_NDHMService; + @Autowired + HttpUtils httpUtils; + @Autowired + Encryption encryption; + + @Value("${getAuthCertPublicKey}") + String getAuthCertPublicKey; + + @Value("${requestOtpForEnrollment}") + String requestOtpForEnrollment; + + @Value("${abhaEnrollByAadhaar}") + String abhaEnrollByAadhaar; + + @Value("${abhaMode}") + String abhaMode; + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Override + public String getOtpForEnrollment(String request) throws FHIRException { + String res = null; + Map responseMap = new HashMap<>(); + RestTemplate restTemplate = new RestTemplate(); + String encryptedLoginId = null; + String publicKeyString = null; + + try { + String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("Authorization", ndhmAuthToken); + + RequestOTPEnrollment reqOtpEnrollment = new RequestOTPEnrollment(); + LoginMethod loginMethod = InputMapper.gson().fromJson(request, LoginMethod.class); + + publicKeyString = getCertPublicKey(); + if (loginMethod.getLoginId() != null) { + encryptedLoginId = encryption.encrypt(loginMethod.getLoginId(), publicKeyString); + } + + if ("AADHAAR".equalsIgnoreCase(loginMethod.getLoginMethod())) { + reqOtpEnrollment.setLoginId(encryptedLoginId); + reqOtpEnrollment.setOtpSystem("aadhaar"); + reqOtpEnrollment.setLoginHint("aadhaar"); + reqOtpEnrollment.setScope(new String[] { "abha-enrol" }); + } + + String requestOBJ = new Gson().toJson(reqOtpEnrollment); + logger.info("ABDM reqobj for request otp for enrollment: " + requestOBJ); + + HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); + ResponseEntity responseEntity = restTemplate.exchange(requestOtpForEnrollment, HttpMethod.POST, + httpEntity, String.class); + + String responseStrLogin = common_NDHMService.getBody(responseEntity); + if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(200) && responseEntity.hasBody()) { + JsonObject jsnOBJ = JsonParser.parseString(responseStrLogin).getAsJsonObject(); + String txnId = jsnOBJ.get("txnId").getAsString(); + responseMap.put("txnId", txnId); + res = new Gson().toJson(responseMap); + } else { + throw new FHIRException("ABDM Error while accessing request OTP for Enrollment API - status code: " + + responseEntity.getStatusCode() + ", error message: " + responseEntity.getBody()); + } + } catch (Exception e) { + throw new FHIRException("NDHM_FHIR Error while accessing ABDM API: " + e.getMessage(), e); + } + + return res; + } + + @Override + public String enrollmentByAadhaar(String request) throws FHIRException { + Map responseMap = new HashMap<>(); + RestTemplate restTemplate = new RestTemplate(); + String encryptedLoginId = null; + String publicKeyString = null; + String abdmOtpToken = null; + HealthIDResponse health = new HealthIDResponse(); + + try { + String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON.toString()); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("Authorization", ndhmAuthToken); + + // Create the enrollByAadhar object + EnrollByAadhaar enrollByAadhar = new EnrollByAadhaar(); + LoginMethod loginData = InputMapper.gson().fromJson(request, LoginMethod.class); + + publicKeyString = getCertPublicKey(); + if (loginData.getLoginId() != null) { + encryptedLoginId = encryption.encrypt(loginData.getLoginId(), publicKeyString); + } + + if ("AADHAAR".equalsIgnoreCase(loginData.getLoginMethod())) { + OtpRequest otp = new OtpRequest(); + + // Get current timestamp + OffsetDateTime now = OffsetDateTime.now(java.time.ZoneOffset.UTC); + DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT; + String formattedTimestamp = now.format(formatter); + otp.setTimestamp(formattedTimestamp); + + otp.setTxnId(loginData.getTnxId()); + otp.setOtpValue(encryptedLoginId); + otp.setMobile(loginData.getMobileNumber()); + + Map authDataMap = new HashMap<>(); + authDataMap.put("otp", otp); + authDataMap.put("authMethods", new String[] { "otp" }); + + enrollByAadhar.setAuthData(authDataMap); + + ConsentRequest consent = new ConsentRequest(); + consent.setCode("abha-enrollment"); + consent.setVersion("1.4"); + enrollByAadhar.setConsent(consent); + + logger.info("ABDM request for enroll by Aadhaar: " + enrollByAadhar); + + String requestObj = new Gson().toJson(enrollByAadhar); + logger.info("ABDM request object for enrollment: " + requestObj); + + HttpEntity httpEntity = new HttpEntity<>(requestObj, headers); + ResponseEntity responseEntity = restTemplate.exchange(abhaEnrollByAadhaar, HttpMethod.POST, + httpEntity, String.class); + + String responseStrLogin = common_NDHMService.getBody(responseEntity); + if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(200) && responseEntity.hasBody()) { + JsonObject jsonResponse = JsonParser.parseString(responseStrLogin).getAsJsonObject(); + + // Check for success messages + String message = jsonResponse.get("message").getAsString(); + if (message != null && (message.equalsIgnoreCase("account created successfully") + || message.equalsIgnoreCase("this account already exist"))) { +// if (jsonResponse.has("tokens")) { +// JsonObject tokenAsJsonObj = jsonResponse.get("tokens").getAsJsonObject(); +// abdmOtpToken = "Bearer " + tokenAsJsonObj.get("token").getAsString(); +// responseMap.put("abdmToken", abdmOtpToken); +// } else { +// throw new FHIRException("NDHM_FHIR Error: Token not found in the response."); +// } + if (jsonResponse.has("ABHAProfile")) { + JsonObject abhaProfileAsJsonObj = jsonResponse.get("ABHAProfile").getAsJsonObject(); + if (abhaProfileAsJsonObj.has("mobile") && abhaProfileAsJsonObj.get("mobile") != null) { + health = InputMapper.gson().fromJson(abhaProfileAsJsonObj, HealthIDResponse.class); + responseMap.put("message", "Mobile number linked to ABHA"); + } else { + +// getOtpForEnrollment(request, "mobile-verify", jsonResponse.get("txnId").getAsString()); + } + } + } + } else { + throw new FHIRException("ABDM Error: Status code " + responseEntity.getStatusCode() + + ", error message: " + responseEntity.getBody()); + } + } + } catch (Exception e) { + throw new FHIRException("NDHM_FHIR Error while accessing ABDM API: " + e.getMessage(), e); + } + + return abdmOtpToken; + } + + + @Override + public String verifyAuthByMobile(String request) throws FHIRException { + String res = null; + Map responseMap = new HashMap<>(); + RestTemplate restTemplate = new RestTemplate(); + String encryptedLoginId = null; + String publicKeyString = null; + + try { + String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("Authorization", ndhmAuthToken); + + RequestOTPEnrollment reqOtpEnrollment = new RequestOTPEnrollment(); + LoginMethod loginMethod = InputMapper.gson().fromJson(request, LoginMethod.class); + + publicKeyString = getCertPublicKey(); + if (loginMethod.getLoginId() != null) { + encryptedLoginId = encryption.encrypt(loginMethod.getLoginId(), publicKeyString); + } + + if ("AADHAAR".equalsIgnoreCase(loginMethod.getLoginMethod())) { + reqOtpEnrollment.setLoginId(encryptedLoginId); + reqOtpEnrollment.setTnxId(loginMethod.getTnxId()); + reqOtpEnrollment.setOtpSystem("abdm"); + reqOtpEnrollment.setLoginHint("mobile"); + reqOtpEnrollment.setScope(new String[] { "abha-enrol", "mobile-verify" }); + + } + + String requestOBJ = new Gson().toJson(reqOtpEnrollment); + logger.info("ABDM reqobj for request otp for enrollment: " + requestOBJ); + + HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); + ResponseEntity responseEntity = restTemplate.exchange(requestOtpForEnrollment, HttpMethod.POST, + httpEntity, String.class); + + String responseStrLogin = common_NDHMService.getBody(responseEntity); + if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(200) && responseEntity.hasBody()) { + JsonObject jsnOBJ = JsonParser.parseString(responseStrLogin).getAsJsonObject(); + String txnId = jsnOBJ.get("txnId").getAsString(); + responseMap.put("txnId", txnId); + res = new Gson().toJson(responseMap); + } else { + throw new FHIRException("ABDM Error while accessing request OTP for Enrollment API - status code: " + + responseEntity.getStatusCode() + ", error message: " + responseEntity.getBody()); + } + } catch (Exception e) { + throw new FHIRException("NDHM_FHIR Error while accessing ABDM API: " + e.getMessage(), e); + } + + return res; + } + + public String getCertPublicKey() throws FHIRException { + + RestTemplate restTemplate = new RestTemplate(); + HttpEntity requestEntity = new HttpEntity<>(null); + + ResponseEntity certResp = restTemplate.exchange(getAuthCertPublicKey, HttpMethod.GET, requestEntity, + String.class); + String body = certResp.getBody(); + + String publicKeyString = body.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "") + .replaceAll("\\s+", ""); + + logger.info("publicKeyString : " + publicKeyString); + + return publicKeyString; + + } +} diff --git a/src/main/java/com/wipro/fhir/utils/Encryption.java b/src/main/java/com/wipro/fhir/utils/Encryption.java new file mode 100644 index 0000000..dc6550f --- /dev/null +++ b/src/main/java/com/wipro/fhir/utils/Encryption.java @@ -0,0 +1,66 @@ +package com.wipro.fhir.utils; + +import java.net.URI; +import java.net.URISyntaxException; +import java.security.InvalidKeyException; +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.X509EncodedKeySpec; +import java.util.TimeZone; +import java.util.UUID; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; + +import java.util.Base64; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import com.wipro.fhir.utils.exception.FHIRException; + +@Service +public class Encryption { + + @Value("${ndhmuserAuthenticate}") + private String ndhmUserAuthenticate; + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + public String encrypt(String text, String publicKeyString) throws FHIRException, NoSuchAlgorithmException, + InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { + String encryptedTextBase64 = ""; + byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyString); + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes); + PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); + + // Cipher used in ABHA v3 APIs + Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding"); + cipher.init(Cipher.ENCRYPT_MODE, publicKey); + byte[] encryptedText = cipher.doFinal(text.getBytes()); + encryptedTextBase64 = Base64.getEncoder().encodeToString(encryptedText); + logger.info("encryptedTextBase64 :" + encryptedTextBase64); + + return encryptedTextBase64; + + } + +} From 583594af857ffc29ea79d27993b84e74fa8d6d35 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Mon, 9 Dec 2024 20:29:07 +0530 Subject: [PATCH 06/30] Abha V3 changes --- src/main/environment/common_ci.properties | 12 +- src/main/environment/common_dev.properties | 3 + .../environment/common_example.properties | 3 + src/main/environment/common_test.properties | 3 + .../CreateAbhaV3Controller.java | 42 +- .../v3/abha/LoginAbhaV3Controller.java | 68 +++ .../fhir/data/v3/abhaCard/BioRequest.java | 14 + .../data/v3/abhaCard/LoginAbhaRequest.java | 12 + .../fhir/data/v3/abhaCard/LoginMethod.java | 11 +- .../data/v3/abhaCard/VerifyAbhaLogin.java | 13 + .../fhir/repo/healthID/HealthIDRepo.java | 4 + .../v3/abha/CertificateKeyService.java | 9 + .../v3/abha/CertificateKeyServiceImpl.java | 41 ++ .../service/v3/abha/CreateAbhaV3Service.java | 16 + .../v3/abha/CreateAbhaV3ServiceImpl.java | 425 ++++++++++++++++++ .../service/v3/abha/LoginAbhaV3Service.java | 11 + .../v3/abha/LoginAbhaV3ServiceImpl.java | 223 +++++++++ .../v3/abha/creation/CreateAbhaV3Service.java | 14 - .../creation/CreateAbhaV3ServiceImpl.java | 319 ------------- .../java/com/wipro/fhir/utils/Encryption.java | 18 +- 20 files changed, 885 insertions(+), 376 deletions(-) rename src/main/java/com/wipro/fhir/controller/v3/abha/{creation => }/CreateAbhaV3Controller.java (79%) create mode 100644 src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java create mode 100644 src/main/java/com/wipro/fhir/data/v3/abhaCard/BioRequest.java create mode 100644 src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginAbhaRequest.java create mode 100644 src/main/java/com/wipro/fhir/data/v3/abhaCard/VerifyAbhaLogin.java create mode 100644 src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyService.java create mode 100644 src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java create mode 100644 src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3Service.java create mode 100644 src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java create mode 100644 src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3Service.java create mode 100644 src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java delete mode 100644 src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3Service.java delete mode 100644 src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3ServiceImpl.java diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index b5fd4b1..21375c3 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -82,12 +82,16 @@ abdmConfirmAadhaarBio=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/confirmWithAadha abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile ##ABDM Facility services -getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices +getAbdmFacilityServicies= @env.ABDM_BASE_URL@/devservice/v1/bridges/getServices ##ABDM V3 APIs -getAuthCertPublicKey = https://healthidsbx.abdm.gov.in/api/v1/auth/cert -requestOtpForEnrollment = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp -abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/byAadhaar +getAuthCertPublicKey = @env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/cert +requestOtpForEnrollment = @env.ABDM_BASE_URL@/abha/api/v3/enrollment/request/otp +abhaEnrollByAadhaar = @env.ABDM_BASE_URL@/abha/api/v3/enrollment/enrol/byAadhaar +printAbhaCard = @env.ABDM_BASE_URL@/abha/api/v3/profile/account/abha-card +abhaLoginRequestOtp = @env.ABDM_BASE_URL@/abha/api/v3/profile/login/request/otp +verifyAbhaLogin = @env.ABDM_BASE_URL@/abha/api/v3/profile/login/verify + abhaMode=sbx diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index 408bcff..d798719 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -88,6 +88,9 @@ getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServi getAuthCertPublicKey = https://healthidsbx.abdm.gov.in/api/v1/auth/cert requestOtpForEnrollment = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/byAadhaar +printAbhaCard = https://abhasbx.abdm.gov.in/abha/api/v3/profile/account/abha-card +abhaLoginRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/request/otp +verifyAbhaLogin = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/verify abhaMode=sbx diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index bbe7c5c..208ebf3 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -88,6 +88,9 @@ getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServi getAuthCertPublicKey = https://healthidsbx.abdm.gov.in/api/v1/auth/cert requestOtpForEnrollment = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/byAadhaar +printAbhaCard = https://abhasbx.abdm.gov.in/abha/api/v3/profile/account/abha-card +abhaLoginRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/request/otp +verifyAbhaLogin = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/verify abhaMode=sbx diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties index 408bcff..d798719 100644 --- a/src/main/environment/common_test.properties +++ b/src/main/environment/common_test.properties @@ -88,6 +88,9 @@ getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServi getAuthCertPublicKey = https://healthidsbx.abdm.gov.in/api/v1/auth/cert requestOtpForEnrollment = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/byAadhaar +printAbhaCard = https://abhasbx.abdm.gov.in/abha/api/v3/profile/account/abha-card +abhaLoginRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/request/otp +verifyAbhaLogin = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/verify abhaMode=sbx diff --git a/src/main/java/com/wipro/fhir/controller/v3/abha/creation/CreateAbhaV3Controller.java b/src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java similarity index 79% rename from src/main/java/com/wipro/fhir/controller/v3/abha/creation/CreateAbhaV3Controller.java rename to src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java index 8214069..fbcd95e 100644 --- a/src/main/java/com/wipro/fhir/controller/v3/abha/creation/CreateAbhaV3Controller.java +++ b/src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java @@ -1,6 +1,4 @@ -package com.wipro.fhir.controller.v3.abha.creation; - -import java.util.HashMap; +package com.wipro.fhir.controller.v3.abha; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -11,9 +9,8 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import com.google.gson.Gson; import com.wipro.fhir.service.ndhm.GenerateHealthID_CardServiceImpl; -import com.wipro.fhir.service.v3.abha.creation.CreateAbhaV3Service; +import com.wipro.fhir.service.v3.abha.CreateAbhaV3Service; import com.wipro.fhir.utils.exception.FHIRException; import com.wipro.fhir.utils.response.OutputResponse; @@ -62,18 +59,6 @@ public String abhaEnrollmentByAadhaar(@RequestBody String request) { try { if (request != null) { res = createAbhaV3Service.enrollmentByAadhaar(request); -// if(abdmToken != null) { -// HashMap map = new HashMap(); -// String card = generateHealthID_CardServiceImpl.generateCard(request, abdmToken); -// if (card != null) { -// map.put("data", card); -// res = new Gson().toJson(map); -// } else -// throw new FHIRException("NDHM_FHIR Error while generating ABHA card"); -// -// } else { -// throw new FHIRException("NDHM_FHIR Error while validating OTP"); -// } response.setResponse(res); } else throw new FHIRException("NDHM_FHIR Empty request object"); @@ -89,7 +74,7 @@ public String abhaEnrollmentByAadhaar(@RequestBody String request) { @Operation(summary = "Verify Mobile OTP for ABHA enrollment") @PostMapping(value = { "/verifyAuthByMobile" }) public String verifyMobileForAuth(@RequestBody String request) { - logger.info("Generate OTP for ABHA enrollment API request " + request); + logger.info("Verify Mobile OTP for ABHA enrollment " + request); OutputResponse response = new OutputResponse(); try { if (request != null) { @@ -104,4 +89,25 @@ public String verifyMobileForAuth(@RequestBody String request) { logger.info("NDHM_FHIR generate OTP for ABHA card API response " + response.toString()); return response.toString(); } + + @CrossOrigin + @Operation(summary = "Print Abha card") + @PostMapping(value = { "/printAbhaCard" }) + public String printAbhaCard(@RequestBody String request) { + OutputResponse response = new OutputResponse(); + try { + if (request != null) { + String s = createAbhaV3Service.getAbhaCardPrinted(request); + response.setResponse(s); + } else + throw new FHIRException("NDHM_FHIR Empty request object"); + } catch (FHIRException e) { + response.setError(5000, e.getMessage()); + logger.error(e.toString()); + } + logger.info("NDHM_FHIR generate OTP for ABHA card API respponse " + response.toString()); + return response.toString(); + } + + } diff --git a/src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java b/src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java new file mode 100644 index 0000000..24977f2 --- /dev/null +++ b/src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java @@ -0,0 +1,68 @@ +package com.wipro.fhir.controller.v3.abha; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.wipro.fhir.service.v3.abha.LoginAbhaV3Service; +import com.wipro.fhir.utils.exception.FHIRException; +import com.wipro.fhir.utils.response.OutputResponse; + +import io.swagger.v3.oas.annotations.Operation; + +@CrossOrigin +@RestController +@RequestMapping(value = "/abhaLogin", headers = "Authorization") +public class LoginAbhaV3Controller { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Autowired + private LoginAbhaV3Service loginAbhaV3Service; + + @CrossOrigin + @Operation(summary = "Request OTP for Abha LOgin") + @PostMapping(value = { "/abhaLoginRequestOtp" }) + public String requestOtpForAbhaLogin(@RequestBody String request) { + logger.info("Generate OTP for ABHA Login API request " + request); + OutputResponse response = new OutputResponse(); + try { + if (request != null) { + String s = loginAbhaV3Service.requestOtpForAbhaLogin(request); + response.setResponse(s); + } else + throw new FHIRException("NDHM_FHIR Empty request object"); + } catch (FHIRException e) { + response.setError(5000, e.getMessage()); + logger.error(e.toString()); + } + logger.info("NDHM_FHIR generate OTP for ABHA login API response " + response.toString()); + return response.toString(); + } + + @CrossOrigin + @Operation(summary = "verify OTP for Abha LOgin") + @PostMapping(value = { "/verifyAbhaLogin" }) + public String verifyAbhaLogin(@RequestBody String request) { + logger.info("verify OTP for ABHA Login API request " + request); + OutputResponse response = new OutputResponse(); + try { + if (request != null) { + String s = loginAbhaV3Service.verifyAbhaLogin(request); + response.setResponse(s); + } else + throw new FHIRException("NDHM_FHIR Empty request object"); + } catch (FHIRException e) { + response.setError(5000, e.getMessage()); + logger.error(e.toString()); + } + logger.info("NDHM_FHIR Verify abha login API response " + response.toString()); + return response.toString(); + } + +} diff --git a/src/main/java/com/wipro/fhir/data/v3/abhaCard/BioRequest.java b/src/main/java/com/wipro/fhir/data/v3/abhaCard/BioRequest.java new file mode 100644 index 0000000..5009509 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/abhaCard/BioRequest.java @@ -0,0 +1,14 @@ +package com.wipro.fhir.data.v3.abhaCard; + +import lombok.Data; + +@Data +public class BioRequest { + + private String timestamp; + private String txnId; + private String aadhaar; + private Object fingerPrintAuthPid; + private String mobile; + +} diff --git a/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginAbhaRequest.java b/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginAbhaRequest.java new file mode 100644 index 0000000..f9a36b2 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginAbhaRequest.java @@ -0,0 +1,12 @@ +package com.wipro.fhir.data.v3.abhaCard; + +import lombok.Data; + +@Data +public class LoginAbhaRequest { + + private String loginId; + private String loginMethod; + private String loginHint; + +} diff --git a/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java b/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java index 431a410..2536f29 100644 --- a/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java +++ b/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java @@ -5,9 +5,12 @@ @Data public class LoginMethod { - String loginId; - String loginMethod; - String tnxId; - String mobileNumber; + private String loginId; + private String loginMethod; + private String pId; + private String tnxId; + private String mobileNumber; + private String createdBy; + private int providerServiceMapId; } diff --git a/src/main/java/com/wipro/fhir/data/v3/abhaCard/VerifyAbhaLogin.java b/src/main/java/com/wipro/fhir/data/v3/abhaCard/VerifyAbhaLogin.java new file mode 100644 index 0000000..311b523 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/abhaCard/VerifyAbhaLogin.java @@ -0,0 +1,13 @@ +package com.wipro.fhir.data.v3.abhaCard; + +import java.util.Map; + +import lombok.Data; + +@Data +public class VerifyAbhaLogin { + + public String[] scope; + public Map authData; + +} diff --git a/src/main/java/com/wipro/fhir/repo/healthID/HealthIDRepo.java b/src/main/java/com/wipro/fhir/repo/healthID/HealthIDRepo.java index 2c8ec03..8426917 100644 --- a/src/main/java/com/wipro/fhir/repo/healthID/HealthIDRepo.java +++ b/src/main/java/com/wipro/fhir/repo/healthID/HealthIDRepo.java @@ -23,4 +23,8 @@ public ArrayList getHealthIDDetailsUsingHealthNumber( @Query(" SELECT HIDR from HealthIDResponse HIDR WHERE HIDR.mobile = :mobile") public ArrayList getHealthIDDetailsUsingMobileNumber(@Param("mobile") String mobile); + + @Query("SELECT COUNT(*) FROM HealthIDResponse HIDR WHERE HIDR.healthIdNumber = :healthId") + public Integer getCountOfHealthIdNumber(@Param("healthId") String healthId); + } diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyService.java b/src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyService.java new file mode 100644 index 0000000..63bf1e8 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyService.java @@ -0,0 +1,9 @@ +package com.wipro.fhir.service.v3.abha; + +import com.wipro.fhir.utils.exception.FHIRException; + +public interface CertificateKeyService { + + public String getCertPublicKey() throws FHIRException; + +} diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java new file mode 100644 index 0000000..71e5845 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java @@ -0,0 +1,41 @@ +package com.wipro.fhir.service.v3.abha; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import com.wipro.fhir.utils.exception.FHIRException; + +@Service +public class CertificateKeyServiceImpl implements CertificateKeyService{ + + @Value("${getAuthCertPublicKey}") + String getAuthCertPublicKey; + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Override + public String getCertPublicKey() throws FHIRException { + + RestTemplate restTemplate = new RestTemplate(); + HttpEntity requestEntity = new HttpEntity<>(null); + + ResponseEntity certResp = restTemplate.exchange(getAuthCertPublicKey, HttpMethod.GET, requestEntity, + String.class); + String body = certResp.getBody(); + + String publicKeyString = body.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "") + .replaceAll("\\s+", ""); + + logger.info("publicKeyString : " + publicKeyString); + + return publicKeyString; + + } + +} diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3Service.java b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3Service.java new file mode 100644 index 0000000..6231476 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3Service.java @@ -0,0 +1,16 @@ +package com.wipro.fhir.service.v3.abha; + +import com.wipro.fhir.utils.exception.FHIRException; + +public interface CreateAbhaV3Service { + + public String getOtpForEnrollment(String request) throws FHIRException; + + public String enrollmentByAadhaar(String request) throws FHIRException; + + public String verifyAuthByMobile(String request) throws FHIRException; + + public String getAbhaCardPrinted(String reqObj) throws FHIRException; + + +} diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java new file mode 100644 index 0000000..5d4fe3e --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java @@ -0,0 +1,425 @@ +package com.wipro.fhir.service.v3.abha; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; +import java.util.UUID; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.wipro.fhir.data.healthID.HealthIDResponse; +import com.wipro.fhir.data.v3.abhaCard.BioRequest; +import com.wipro.fhir.data.v3.abhaCard.ConsentRequest; +import com.wipro.fhir.data.v3.abhaCard.EnrollByAadhaar; +import com.wipro.fhir.data.v3.abhaCard.LoginMethod; +import com.wipro.fhir.data.v3.abhaCard.OtpRequest; +import com.wipro.fhir.data.v3.abhaCard.RequestOTPEnrollment; +import com.wipro.fhir.repo.healthID.HealthIDRepo; +import com.wipro.fhir.service.ndhm.Common_NDHMService; +import com.wipro.fhir.service.ndhm.GenerateSession_NDHMService; +import com.wipro.fhir.utils.Encryption; +import com.wipro.fhir.utils.exception.FHIRException; +import com.wipro.fhir.utils.http.HttpUtils; +import com.wipro.fhir.utils.mapper.InputMapper; + +@Service +public class CreateAbhaV3ServiceImpl implements CreateAbhaV3Service { + + @Autowired + private GenerateSession_NDHMService generateSession_NDHM; + @Autowired + private Common_NDHMService common_NDHMService; + @Autowired + HttpUtils httpUtils; + @Autowired + Encryption encryption; + @Autowired + HealthIDRepo healthIDRepo; + @Autowired + CertificateKeyService certificateKeyService; + + @Value("${requestOtpForEnrollment}") + String requestOtpForEnrollment; + + @Value("${abhaEnrollByAadhaar}") + String abhaEnrollByAadhaar; + + @Value("${printAbhaCard}") + String printAbhaCard; + + @Value("${abhaMode}") + String abhaMode; + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Override + public String getOtpForEnrollment(String request) throws FHIRException { + String res = null; + Map responseMap = new HashMap<>(); + RestTemplate restTemplate = new RestTemplate(); + String encryptedLoginId = null; + String publicKeyString = null; + + try { + String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("Authorization", ndhmAuthToken); + + RequestOTPEnrollment reqOtpEnrollment = new RequestOTPEnrollment(); + LoginMethod loginMethod = InputMapper.gson().fromJson(request, LoginMethod.class); + + publicKeyString = certificateKeyService.getCertPublicKey(); + if (loginMethod.getLoginId() != null) { + encryptedLoginId = encryption.encrypt(loginMethod.getLoginId(), publicKeyString); + } + + if ("AADHAAR".equalsIgnoreCase(loginMethod.getLoginMethod())) { + reqOtpEnrollment.setLoginId(encryptedLoginId); + reqOtpEnrollment.setOtpSystem("aadhaar"); + reqOtpEnrollment.setLoginHint("aadhaar"); + reqOtpEnrollment.setScope(new String[] { "abha-enrol" }); + } + + String requestOBJ = new Gson().toJson(reqOtpEnrollment); + logger.info("ABDM reqobj for request otp for enrollment: " + requestOBJ); + + HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); + ResponseEntity responseEntity = restTemplate.exchange(requestOtpForEnrollment, HttpMethod.POST, + httpEntity, String.class); + + logger.info("ABDM response for request otp for enrollment: " + responseEntity); + String responseStrLogin = common_NDHMService.getBody(responseEntity); + if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(200) && responseEntity.hasBody()) { + JsonObject jsnOBJ = JsonParser.parseString(responseStrLogin).getAsJsonObject(); + String txnId = jsnOBJ.get("txnId").getAsString(); + String message = jsnOBJ.get("message").getAsString(); + responseMap.put("txnId", txnId); + responseMap.put("message", message); + res = new Gson().toJson(responseMap); + } else { + throw new FHIRException(responseEntity.getBody()); + } + } catch (Exception e) { + throw new FHIRException(e.getMessage()); + } + + return res; + } + + @Override + public String enrollmentByAadhaar(String request) throws FHIRException { + Map responseMap = new HashMap<>(); + RestTemplate restTemplate = new RestTemplate(); + String encryptedLoginId = null; + String publicKeyString = null; + String requestObj = null; + + try { + String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON.toString()); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("Authorization", ndhmAuthToken); + + // Create the enrollByAadhar object + EnrollByAadhaar enrollByAadhar = new EnrollByAadhaar(); + LoginMethod loginData = InputMapper.gson().fromJson(request, LoginMethod.class); + + publicKeyString = certificateKeyService.getCertPublicKey(); + if (loginData.getLoginId() != null) { + encryptedLoginId = encryption.encrypt(loginData.getLoginId(), publicKeyString); + } + + if ("AADHAAR".equalsIgnoreCase(loginData.getLoginMethod())) { + + requestObj = formAadharEnrollReqObjByAadhar(loginData, encryptedLoginId); + logger.info("ABDM request object for ABHA enrollment by AADHAAR: " + requestObj); + + } else if ("BIOMETRIC".equalsIgnoreCase(loginData.getLoginMethod())) { + + requestObj = formAadharEnrollReqObjByBiometric(loginData, encryptedLoginId); + logger.info("ABDM request object for ABHA enrollment by BIOMETRIC: " + requestObj); + + } + + HttpEntity httpEntity = new HttpEntity<>(requestObj, headers); + ResponseEntity responseEntity = restTemplate.exchange(abhaEnrollByAadhaar, HttpMethod.POST, + httpEntity, String.class); + + logger.info("ABDM response for ABHA enrollment: " + responseEntity); + String responseStrLogin = common_NDHMService.getBody(responseEntity); + if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(200) && responseEntity.hasBody()) { + JsonObject jsonResponse = JsonParser.parseString(responseStrLogin).getAsJsonObject(); + + // Check for success messages + String message = jsonResponse.get("message").getAsString(); + if (message != null && (message.equalsIgnoreCase("account created successfully") + || message.equalsIgnoreCase("this account already exist"))) { + + if (jsonResponse.has("ABHAProfile")) { + JsonObject abhaProfileAsJsonObj = jsonResponse.get("ABHAProfile").getAsJsonObject(); + Gson gson = new Gson(); + String json = gson.toJson(abhaProfileAsJsonObj); + + HealthIDResponse healthIDResp = gson.fromJson(json, HealthIDResponse.class); + constructHealthIdResponse(healthIDResp, abhaProfileAsJsonObj); + healthIDResp.setProviderServiceMapID(loginData.getProviderServiceMapId()); + healthIDResp.setCreatedBy(loginData.getCreatedBy()); + Integer healthIdCount = healthIDRepo.getCountOfHealthIdNumber(healthIDResp.getHealthIdNumber()); + HealthIDResponse save = healthIDResp; + if (healthIdCount < 1) { + healthIDRepo.save(healthIDResp); + } + responseMap.put("ABHAProfile", gson.toJson(save)); + responseMap.put("txnId", jsonResponse.get("txnId").getAsString()); + responseMap.put("isNew", jsonResponse.get("isNew").getAsString()); + if (jsonResponse.has("tokens") && jsonResponse.get("tokens").isJsonObject()) { + JsonObject tokensObject = jsonResponse.get("tokens").getAsJsonObject(); + if (tokensObject.has("token") && !tokensObject.get("token").isJsonNull()) { + String token = tokensObject.get("token").getAsString(); + responseMap.put("xToken", token); + } + } + } + } + } else { + throw new FHIRException(responseEntity.getBody()); + } + } catch (Exception e) { + throw new FHIRException(e.getMessage()); + } + + return responseMap.toString(); + } + + @Override + public String verifyAuthByMobile(String request) throws FHIRException { + String res = null; + Map responseMap = new HashMap<>(); + RestTemplate restTemplate = new RestTemplate(); + String encryptedLoginId = null; + String publicKeyString = null; + + try { + String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("Authorization", ndhmAuthToken); + + RequestOTPEnrollment reqOtpEnrollment = new RequestOTPEnrollment(); + LoginMethod loginMethod = InputMapper.gson().fromJson(request, LoginMethod.class); + + publicKeyString = certificateKeyService.getCertPublicKey(); + if (loginMethod.getLoginId() != null) { + encryptedLoginId = encryption.encrypt(loginMethod.getLoginId(), publicKeyString); + } + + if ("AADHAAR".equalsIgnoreCase(loginMethod.getLoginMethod())) { + reqOtpEnrollment.setLoginId(encryptedLoginId); + reqOtpEnrollment.setTnxId(loginMethod.getTnxId()); + reqOtpEnrollment.setOtpSystem("abdm"); + reqOtpEnrollment.setLoginHint("mobile"); + reqOtpEnrollment.setScope(new String[] { "abha-enrol", "mobile-verify" }); + + } + + String requestOBJ = new Gson().toJson(reqOtpEnrollment); + logger.info("ABDM reqobj for verify mobile number for abha enrollment: " + requestOBJ); + + HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); + ResponseEntity responseEntity = restTemplate.exchange(requestOtpForEnrollment, HttpMethod.POST, + httpEntity, String.class); + + logger.info("ABDM response for verify mobile number for abha enrollment: " + responseEntity); + String responseStrLogin = common_NDHMService.getBody(responseEntity); + if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(200) && responseEntity.hasBody()) { + JsonObject jsnOBJ = JsonParser.parseString(responseStrLogin).getAsJsonObject(); + String txnId = jsnOBJ.get("txnId").getAsString(); + String message = jsnOBJ.get("message").getAsString(); + responseMap.put("txnId", txnId); + responseMap.put("message", message); + res = new Gson().toJson(responseMap); + } else { + throw new FHIRException(responseEntity.getBody()); + } + } catch (Exception e) { + throw new FHIRException(e.getMessage()); + } + + return res; + } + + public String formAadharEnrollReqObjByAadhar(LoginMethod loginData, String encryptedLoginId) { + + EnrollByAadhaar enrollByAadhar = new EnrollByAadhaar(); + OtpRequest otp = new OtpRequest(); + + // Get current timestamp + OffsetDateTime now = OffsetDateTime.now(java.time.ZoneOffset.UTC); + DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT; + String formattedTimestamp = now.format(formatter); + otp.setTimestamp(formattedTimestamp); + + otp.setTxnId(loginData.getTnxId()); + otp.setOtpValue(encryptedLoginId); + otp.setMobile(loginData.getMobileNumber()); + + Map authDataMap = new HashMap<>(); + authDataMap.put("otp", otp); + authDataMap.put("authMethods", new String[] { "otp" }); + + enrollByAadhar.setAuthData(authDataMap); + + ConsentRequest consent = new ConsentRequest(); + consent.setCode("abha-enrollment"); + consent.setVersion("1.4"); + enrollByAadhar.setConsent(consent); + logger.info("ABDM request for enroll by Aadhaar: " + enrollByAadhar); + + String requestObj = new Gson().toJson(enrollByAadhar); + + return requestObj; + } + + public String formAadharEnrollReqObjByBiometric(LoginMethod loginData, String encryptedLoginId) { + + EnrollByAadhaar enrollByAadhar = new EnrollByAadhaar(); + BioRequest bio = new BioRequest(); + + // Get current timestamp + OffsetDateTime now = OffsetDateTime.now(java.time.ZoneOffset.UTC); + DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT; + String formattedTimestamp = now.format(formatter); + bio.setTimestamp(formattedTimestamp); + + bio.setTxnId(loginData.getTnxId()); + + bio.setAadhaar(encryptedLoginId); + bio.setFingerPrintAuthPid(loginData.getPId()); + bio.setMobile(loginData.getMobileNumber()); + + Map authDataMap = new HashMap<>(); + authDataMap.put("bio", bio); + authDataMap.put("authMethods", new String[] { "bio" }); + + enrollByAadhar.setAuthData(authDataMap); + + ConsentRequest consent = new ConsentRequest(); + consent.setCode("abha-enrollment"); + consent.setVersion("1.4"); + enrollByAadhar.setConsent(consent); + logger.info("ABDM request for enroll by biometric: " + enrollByAadhar); + + String requestObj = new Gson().toJson(enrollByAadhar); + + return requestObj; + } + + @Override + public String getAbhaCardPrinted(String reqObj) throws FHIRException { + + String res = null; + Map responseMap = new HashMap<>(); + RestTemplate restTemplate = new RestTemplate(); + + + try { + String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("Authorization", ndhmAuthToken); + + JsonObject stringReqObj = JsonParser.parseString(reqObj).getAsJsonObject(); + if (stringReqObj.has("xToken") && stringReqObj.get("xToken") != null) { + String xToken = stringReqObj.get("xToken").getAsString(); + headers.add("X-token", "Bearer " + xToken); + } + HttpEntity httpEntity = new HttpEntity<>(headers); + ResponseEntity responseEntity = restTemplate.exchange(printAbhaCard, HttpMethod.GET, httpEntity, + String.class); + + logger.info("ABDM response for print Abha card:" + responseEntity); + String responseStrLogin = common_NDHMService.getBody(responseEntity); + if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(202)) { + responseMap.put("png", responseStrLogin); + res = new Gson().toJson(responseMap); + } else { + throw new FHIRException(responseEntity.getBody()); + } + + } catch (Exception e) { + throw new FHIRException(e.getMessage()); + } + return res; + + } + + private void constructHealthIdResponse(HealthIDResponse healthIDResp, JsonObject profile) throws ParseException { + healthIDResp.setHealthIdNumber(profile.get("ABHANumber").getAsString()); + String abhaAddress = profile.get("phrAddress").getAsString().replace("[", "").replace("]", ""); + healthIDResp.setHealthId(abhaAddress); + healthIDResp.setName( + healthIDResp.getFirstName() + " " + healthIDResp.getMiddleName() + " " + healthIDResp.getLastName()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy"); + Date date = simpleDateFormat.parse(profile.get("dob").getAsString()); + SimpleDateFormat year = new SimpleDateFormat("yyyy"); + SimpleDateFormat month = new SimpleDateFormat("MM"); + SimpleDateFormat day = new SimpleDateFormat("dd"); + healthIDResp.setYearOfBirth(year.format(date)); + healthIDResp.setMonthOfBirth(month.format(date)); + healthIDResp.setDayOfBirth(day.format(date)); + } + +} diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3Service.java b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3Service.java new file mode 100644 index 0000000..0ad41fc --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3Service.java @@ -0,0 +1,11 @@ +package com.wipro.fhir.service.v3.abha; + +import com.wipro.fhir.utils.exception.FHIRException; + +public interface LoginAbhaV3Service { + + String requestOtpForAbhaLogin(String request) throws FHIRException; + + String verifyAbhaLogin(String request) throws FHIRException; + +} diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java new file mode 100644 index 0000000..1baaf7e --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java @@ -0,0 +1,223 @@ +package com.wipro.fhir.service.v3.abha; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; +import java.util.UUID; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.wipro.fhir.data.healthID.HealthIDResponse; +import com.wipro.fhir.data.v3.abhaCard.LoginAbhaRequest; +import com.wipro.fhir.data.v3.abhaCard.LoginMethod; +import com.wipro.fhir.data.v3.abhaCard.OtpRequest; +import com.wipro.fhir.data.v3.abhaCard.RequestOTPEnrollment; +import com.wipro.fhir.data.v3.abhaCard.VerifyAbhaLogin; +import com.wipro.fhir.service.ndhm.Common_NDHMService; +import com.wipro.fhir.service.ndhm.GenerateSession_NDHMService; +import com.wipro.fhir.utils.Encryption; +import com.wipro.fhir.utils.exception.FHIRException; +import com.wipro.fhir.utils.http.HttpUtils; +import com.wipro.fhir.utils.mapper.InputMapper; + +@Service +public class LoginAbhaV3ServiceImpl implements LoginAbhaV3Service { + + @Autowired + private GenerateSession_NDHMService generateSession_NDHM; + @Autowired + private Common_NDHMService common_NDHMService; + @Autowired + private Encryption encryption; + @Autowired + private CertificateKeyService certificateKeyService; + + @Value("${abhaLoginRequestOtp}") + String abhaLoginRequestOtp; + + @Value("${verifyAbhaLogin}") + String verifyAbhaLoginUrl; + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Override + public String requestOtpForAbhaLogin(String request) throws FHIRException { + String res = null; + Map responseMap = new HashMap<>(); + RestTemplate restTemplate = new RestTemplate(); + String encryptedLoginId = null; + String publicKeyString = null; + + try { + String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("Authorization", ndhmAuthToken); + + RequestOTPEnrollment reqOtpEnrollment = new RequestOTPEnrollment(); + LoginAbhaRequest loginAbhaRequest = InputMapper.gson().fromJson(request, LoginAbhaRequest.class); + + publicKeyString = certificateKeyService.getCertPublicKey(); + if (loginAbhaRequest.getLoginId() != null) { + encryptedLoginId = encryption.encrypt(loginAbhaRequest.getLoginId(), publicKeyString); + reqOtpEnrollment.setLoginId(encryptedLoginId); + } + + if ("AADHAAR".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())) { + reqOtpEnrollment.setOtpSystem("aadhaar"); + reqOtpEnrollment.setScope(new String[] { "abha-login", "aadhaar-verify" }); + } else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())) { + reqOtpEnrollment.setOtpSystem("abdm"); + reqOtpEnrollment.setScope(new String[] { "abha-login", "mobile-verify" }); + } + + if ("ABHA".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) { + reqOtpEnrollment.setOtpSystem("abdm"); + reqOtpEnrollment.setLoginHint("abha"); + } else if ("AADHAAR".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) { + reqOtpEnrollment.setLoginHint("aadhaar"); + } else if ("MOBILE".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) { + reqOtpEnrollment.setLoginHint("mobile"); + } + + String requestOBJ = new Gson().toJson(reqOtpEnrollment); + logger.info("ABDM reqobj for request otp for Abha login: " + requestOBJ); + + HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); + ResponseEntity responseEntity = restTemplate.exchange(abhaLoginRequestOtp, HttpMethod.POST, + httpEntity, String.class); + + logger.info("ABDM response for request otp for Abha login: " + responseEntity); + String responseStrLogin = common_NDHMService.getBody(responseEntity); + if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(200) && responseEntity.hasBody()) { + JsonObject jsnOBJ = JsonParser.parseString(responseStrLogin).getAsJsonObject(); + String txnId = jsnOBJ.get("txnId").getAsString(); + String message = jsnOBJ.get("message").getAsString(); + responseMap.put("txnId", txnId); + responseMap.put("message", message); + res = new Gson().toJson(responseMap); + } else { + throw new FHIRException(responseEntity.getBody()); + } + } catch (Exception e) { + throw new FHIRException(e.getMessage()); + } + + return res; + } + + + @Override + public String verifyAbhaLogin(String request) throws FHIRException { + Map responseMap = new HashMap<>(); + RestTemplate restTemplate = new RestTemplate(); + String encryptedLoginId = null; + String publicKeyString = null; + HealthIDResponse health = new HealthIDResponse(); + + try { + String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON.toString()); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("Authorization", ndhmAuthToken); + + // Create the enrollByAadhar object + VerifyAbhaLogin verifyAbhaLogin = new VerifyAbhaLogin(); + LoginMethod loginData = InputMapper.gson().fromJson(request, LoginMethod.class); + + publicKeyString = certificateKeyService.getCertPublicKey(); + if (loginData.getLoginId() != null) { + encryptedLoginId = encryption.encrypt(loginData.getLoginId(), publicKeyString); + } + + OtpRequest otp = new OtpRequest(); + + otp.setTxnId(loginData.getTnxId()); + otp.setOtpValue(encryptedLoginId); + + Map authDataMap = new HashMap<>(); + authDataMap.put("otp", otp); + authDataMap.put("authMethods", new String[] { "otp" }); + + verifyAbhaLogin.setAuthData(authDataMap); + + if ("AADHAAR".equalsIgnoreCase(loginData.getLoginMethod())) { + verifyAbhaLogin.setScope(new String[] {"abha-login", "aadhaar-verify" } ); + + } else if ("MOBILE".equalsIgnoreCase(loginData.getLoginMethod())) { + verifyAbhaLogin.setScope(new String[] {"abha-login", "mobile-verify" } ); + + } + + String requestObj = new Gson().toJson(verifyAbhaLogin); + logger.info("ABDM request for verify abha login: " + requestObj); + + HttpEntity httpEntity = new HttpEntity<>(requestObj, headers); + ResponseEntity responseEntity = restTemplate.exchange(verifyAbhaLoginUrl, HttpMethod.POST, + httpEntity, String.class); + + logger.info("ABDM response for verify abha login: " + httpEntity); + String responseStrLogin = common_NDHMService.getBody(responseEntity); + if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(200) && responseEntity.hasBody()) { + JsonObject jsonResponse = JsonParser.parseString(responseStrLogin).getAsJsonObject(); + + // Check for success messages + String authResult = jsonResponse.get("authResult").getAsString(); + if (authResult != null && (authResult.equalsIgnoreCase("success"))) { + + if (jsonResponse.has("accounts")) { + responseMap.put("abhaDetails", jsonResponse.get("accounts").getAsJsonArray().get(0).getAsJsonObject().toString()); + responseMap.put("txnId", jsonResponse.get("txnId").getAsString()); + if (jsonResponse.has("token")) { + responseMap.put("xToken", jsonResponse.get("token").getAsString()); + } + } + } else { + String message = jsonResponse.get("message").getAsString(); + throw new FHIRException(message); + } + } else { + throw new FHIRException(responseEntity.getBody()); + } + } catch (Exception e) { + throw new FHIRException(e.getMessage()); + } + + return responseMap.toString(); + } + + +} diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3Service.java b/src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3Service.java deleted file mode 100644 index 22668ee..0000000 --- a/src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3Service.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.wipro.fhir.service.v3.abha.creation; - -import com.wipro.fhir.utils.exception.FHIRException; - -public interface CreateAbhaV3Service { - - String getOtpForEnrollment(String request) throws FHIRException; - - String enrollmentByAadhaar(String request) throws FHIRException; - - String verifyAuthByMobile(String request) throws FHIRException; - - -} diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3ServiceImpl.java deleted file mode 100644 index 1e84c23..0000000 --- a/src/main/java/com/wipro/fhir/service/v3/abha/creation/CreateAbhaV3ServiceImpl.java +++ /dev/null @@ -1,319 +0,0 @@ -package com.wipro.fhir.service.v3.abha.creation; - -import java.sql.Timestamp; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatusCode; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.client.RestTemplate; - -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.wipro.fhir.data.healthID.HealthIDRequestAadhar; -import com.wipro.fhir.data.healthID.HealthIDResponse; -import com.wipro.fhir.data.v3.abhaCard.ConsentRequest; -import com.wipro.fhir.data.v3.abhaCard.EnrollByAadhaar; -import com.wipro.fhir.data.v3.abhaCard.LoginMethod; -import com.wipro.fhir.data.v3.abhaCard.OtpRequest; -import com.wipro.fhir.data.v3.abhaCard.RequestOTPEnrollment; -import com.wipro.fhir.service.ndhm.Common_NDHMService; -import com.wipro.fhir.service.ndhm.GenerateSession_NDHMService; -import com.wipro.fhir.utils.Encryption; -import com.wipro.fhir.utils.exception.FHIRException; -import com.wipro.fhir.utils.http.HttpUtils; -import com.wipro.fhir.utils.mapper.InputMapper; -import java.text.DateFormat; -import java.text.SimpleDateFormat; - -@Service -public class CreateAbhaV3ServiceImpl implements CreateAbhaV3Service { - - @Autowired - private GenerateSession_NDHMService generateSession_NDHM; - @Autowired - private Common_NDHMService common_NDHMService; - @Autowired - HttpUtils httpUtils; - @Autowired - Encryption encryption; - - @Value("${getAuthCertPublicKey}") - String getAuthCertPublicKey; - - @Value("${requestOtpForEnrollment}") - String requestOtpForEnrollment; - - @Value("${abhaEnrollByAadhaar}") - String abhaEnrollByAadhaar; - - @Value("${abhaMode}") - String abhaMode; - - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - - @Override - public String getOtpForEnrollment(String request) throws FHIRException { - String res = null; - Map responseMap = new HashMap<>(); - RestTemplate restTemplate = new RestTemplate(); - String encryptedLoginId = null; - String publicKeyString = null; - - try { - String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); - - MultiValueMap headers = new LinkedMultiValueMap<>(); - headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); - headers.add("REQUEST-ID", UUID.randomUUID().toString()); - - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - df.setTimeZone(tz); - String nowAsISO = df.format(new Date()); - headers.add("TIMESTAMP", nowAsISO); - headers.add("Authorization", ndhmAuthToken); - - RequestOTPEnrollment reqOtpEnrollment = new RequestOTPEnrollment(); - LoginMethod loginMethod = InputMapper.gson().fromJson(request, LoginMethod.class); - - publicKeyString = getCertPublicKey(); - if (loginMethod.getLoginId() != null) { - encryptedLoginId = encryption.encrypt(loginMethod.getLoginId(), publicKeyString); - } - - if ("AADHAAR".equalsIgnoreCase(loginMethod.getLoginMethod())) { - reqOtpEnrollment.setLoginId(encryptedLoginId); - reqOtpEnrollment.setOtpSystem("aadhaar"); - reqOtpEnrollment.setLoginHint("aadhaar"); - reqOtpEnrollment.setScope(new String[] { "abha-enrol" }); - } - - String requestOBJ = new Gson().toJson(reqOtpEnrollment); - logger.info("ABDM reqobj for request otp for enrollment: " + requestOBJ); - - HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); - ResponseEntity responseEntity = restTemplate.exchange(requestOtpForEnrollment, HttpMethod.POST, - httpEntity, String.class); - - String responseStrLogin = common_NDHMService.getBody(responseEntity); - if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(200) && responseEntity.hasBody()) { - JsonObject jsnOBJ = JsonParser.parseString(responseStrLogin).getAsJsonObject(); - String txnId = jsnOBJ.get("txnId").getAsString(); - responseMap.put("txnId", txnId); - res = new Gson().toJson(responseMap); - } else { - throw new FHIRException("ABDM Error while accessing request OTP for Enrollment API - status code: " - + responseEntity.getStatusCode() + ", error message: " + responseEntity.getBody()); - } - } catch (Exception e) { - throw new FHIRException("NDHM_FHIR Error while accessing ABDM API: " + e.getMessage(), e); - } - - return res; - } - - @Override - public String enrollmentByAadhaar(String request) throws FHIRException { - Map responseMap = new HashMap<>(); - RestTemplate restTemplate = new RestTemplate(); - String encryptedLoginId = null; - String publicKeyString = null; - String abdmOtpToken = null; - HealthIDResponse health = new HealthIDResponse(); - - try { - String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); - MultiValueMap headers = new LinkedMultiValueMap<>(); - headers.add("Content-Type", MediaType.APPLICATION_JSON.toString()); - headers.add("REQUEST-ID", UUID.randomUUID().toString()); - - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - df.setTimeZone(tz); - String nowAsISO = df.format(new Date()); - headers.add("TIMESTAMP", nowAsISO); - headers.add("Authorization", ndhmAuthToken); - - // Create the enrollByAadhar object - EnrollByAadhaar enrollByAadhar = new EnrollByAadhaar(); - LoginMethod loginData = InputMapper.gson().fromJson(request, LoginMethod.class); - - publicKeyString = getCertPublicKey(); - if (loginData.getLoginId() != null) { - encryptedLoginId = encryption.encrypt(loginData.getLoginId(), publicKeyString); - } - - if ("AADHAAR".equalsIgnoreCase(loginData.getLoginMethod())) { - OtpRequest otp = new OtpRequest(); - - // Get current timestamp - OffsetDateTime now = OffsetDateTime.now(java.time.ZoneOffset.UTC); - DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT; - String formattedTimestamp = now.format(formatter); - otp.setTimestamp(formattedTimestamp); - - otp.setTxnId(loginData.getTnxId()); - otp.setOtpValue(encryptedLoginId); - otp.setMobile(loginData.getMobileNumber()); - - Map authDataMap = new HashMap<>(); - authDataMap.put("otp", otp); - authDataMap.put("authMethods", new String[] { "otp" }); - - enrollByAadhar.setAuthData(authDataMap); - - ConsentRequest consent = new ConsentRequest(); - consent.setCode("abha-enrollment"); - consent.setVersion("1.4"); - enrollByAadhar.setConsent(consent); - - logger.info("ABDM request for enroll by Aadhaar: " + enrollByAadhar); - - String requestObj = new Gson().toJson(enrollByAadhar); - logger.info("ABDM request object for enrollment: " + requestObj); - - HttpEntity httpEntity = new HttpEntity<>(requestObj, headers); - ResponseEntity responseEntity = restTemplate.exchange(abhaEnrollByAadhaar, HttpMethod.POST, - httpEntity, String.class); - - String responseStrLogin = common_NDHMService.getBody(responseEntity); - if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(200) && responseEntity.hasBody()) { - JsonObject jsonResponse = JsonParser.parseString(responseStrLogin).getAsJsonObject(); - - // Check for success messages - String message = jsonResponse.get("message").getAsString(); - if (message != null && (message.equalsIgnoreCase("account created successfully") - || message.equalsIgnoreCase("this account already exist"))) { -// if (jsonResponse.has("tokens")) { -// JsonObject tokenAsJsonObj = jsonResponse.get("tokens").getAsJsonObject(); -// abdmOtpToken = "Bearer " + tokenAsJsonObj.get("token").getAsString(); -// responseMap.put("abdmToken", abdmOtpToken); -// } else { -// throw new FHIRException("NDHM_FHIR Error: Token not found in the response."); -// } - if (jsonResponse.has("ABHAProfile")) { - JsonObject abhaProfileAsJsonObj = jsonResponse.get("ABHAProfile").getAsJsonObject(); - if (abhaProfileAsJsonObj.has("mobile") && abhaProfileAsJsonObj.get("mobile") != null) { - health = InputMapper.gson().fromJson(abhaProfileAsJsonObj, HealthIDResponse.class); - responseMap.put("message", "Mobile number linked to ABHA"); - } else { - -// getOtpForEnrollment(request, "mobile-verify", jsonResponse.get("txnId").getAsString()); - } - } - } - } else { - throw new FHIRException("ABDM Error: Status code " + responseEntity.getStatusCode() - + ", error message: " + responseEntity.getBody()); - } - } - } catch (Exception e) { - throw new FHIRException("NDHM_FHIR Error while accessing ABDM API: " + e.getMessage(), e); - } - - return abdmOtpToken; - } - - - @Override - public String verifyAuthByMobile(String request) throws FHIRException { - String res = null; - Map responseMap = new HashMap<>(); - RestTemplate restTemplate = new RestTemplate(); - String encryptedLoginId = null; - String publicKeyString = null; - - try { - String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); - - MultiValueMap headers = new LinkedMultiValueMap<>(); - headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); - headers.add("REQUEST-ID", UUID.randomUUID().toString()); - - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - df.setTimeZone(tz); - String nowAsISO = df.format(new Date()); - headers.add("TIMESTAMP", nowAsISO); - headers.add("Authorization", ndhmAuthToken); - - RequestOTPEnrollment reqOtpEnrollment = new RequestOTPEnrollment(); - LoginMethod loginMethod = InputMapper.gson().fromJson(request, LoginMethod.class); - - publicKeyString = getCertPublicKey(); - if (loginMethod.getLoginId() != null) { - encryptedLoginId = encryption.encrypt(loginMethod.getLoginId(), publicKeyString); - } - - if ("AADHAAR".equalsIgnoreCase(loginMethod.getLoginMethod())) { - reqOtpEnrollment.setLoginId(encryptedLoginId); - reqOtpEnrollment.setTnxId(loginMethod.getTnxId()); - reqOtpEnrollment.setOtpSystem("abdm"); - reqOtpEnrollment.setLoginHint("mobile"); - reqOtpEnrollment.setScope(new String[] { "abha-enrol", "mobile-verify" }); - - } - - String requestOBJ = new Gson().toJson(reqOtpEnrollment); - logger.info("ABDM reqobj for request otp for enrollment: " + requestOBJ); - - HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); - ResponseEntity responseEntity = restTemplate.exchange(requestOtpForEnrollment, HttpMethod.POST, - httpEntity, String.class); - - String responseStrLogin = common_NDHMService.getBody(responseEntity); - if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(200) && responseEntity.hasBody()) { - JsonObject jsnOBJ = JsonParser.parseString(responseStrLogin).getAsJsonObject(); - String txnId = jsnOBJ.get("txnId").getAsString(); - responseMap.put("txnId", txnId); - res = new Gson().toJson(responseMap); - } else { - throw new FHIRException("ABDM Error while accessing request OTP for Enrollment API - status code: " - + responseEntity.getStatusCode() + ", error message: " + responseEntity.getBody()); - } - } catch (Exception e) { - throw new FHIRException("NDHM_FHIR Error while accessing ABDM API: " + e.getMessage(), e); - } - - return res; - } - - public String getCertPublicKey() throws FHIRException { - - RestTemplate restTemplate = new RestTemplate(); - HttpEntity requestEntity = new HttpEntity<>(null); - - ResponseEntity certResp = restTemplate.exchange(getAuthCertPublicKey, HttpMethod.GET, requestEntity, - String.class); - String body = certResp.getBody(); - - String publicKeyString = body.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "") - .replaceAll("\\s+", ""); - - logger.info("publicKeyString : " + publicKeyString); - - return publicKeyString; - - } -} diff --git a/src/main/java/com/wipro/fhir/utils/Encryption.java b/src/main/java/com/wipro/fhir/utils/Encryption.java index dc6550f..99cd569 100644 --- a/src/main/java/com/wipro/fhir/utils/Encryption.java +++ b/src/main/java/com/wipro/fhir/utils/Encryption.java @@ -1,38 +1,22 @@ package com.wipro.fhir.utils; -import java.net.URI; -import java.net.URISyntaxException; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; -import java.util.TimeZone; -import java.util.UUID; +import java.util.Base64; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; -import java.util.Base64; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.client.RestTemplate; import com.wipro.fhir.utils.exception.FHIRException; From 4c7619324c9d96bc62860d369cea57e4b11e6aaa Mon Sep 17 00:00:00 2001 From: Helen Grace Karyamsetty <133211481+helenKaryamsetty@users.noreply.github.com> Date: Mon, 9 Dec 2024 21:45:54 +0530 Subject: [PATCH 07/30] removed unused code --- .../wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java b/src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java index fbcd95e..2917e63 100644 --- a/src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java +++ b/src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java @@ -26,9 +26,6 @@ public class CreateAbhaV3Controller { @Autowired private CreateAbhaV3Service createAbhaV3Service; - @Autowired - private GenerateHealthID_CardServiceImpl generateHealthID_CardServiceImpl; - @CrossOrigin @Operation(summary = "Generate OTP for ABHA enrollment") @PostMapping(value = { "/requestOtpForAbhaEnrollment" }) From c07d83949c9c880a1d94f64a0f67e4bb31f0edb2 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Thu, 12 Dec 2024 15:57:53 +0530 Subject: [PATCH 08/30] v3- verify auth by abdm API changes --- src/main/environment/common_ci.properties | 1 + src/main/environment/common_dev.properties | 1 + .../environment/common_example.properties | 2 +- src/main/environment/common_test.properties | 2 +- .../v3/abha/CreateAbhaV3Controller.java | 12 ++--- .../data/v3/abhaCard/EnrollAuthByABDM.java | 12 +++++ .../service/v3/abha/CreateAbhaV3Service.java | 2 +- .../v3/abha/CreateAbhaV3ServiceImpl.java | 49 ++++++++++++++----- .../v3/abha/LoginAbhaV3ServiceImpl.java | 27 +++++----- 9 files changed, 74 insertions(+), 34 deletions(-) create mode 100644 src/main/java/com/wipro/fhir/data/v3/abhaCard/EnrollAuthByABDM.java diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index 5f4a103..f99d537 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -91,6 +91,7 @@ abhaEnrollByAadhaar = @env.ABDM_BASE_URL@/abha/api/v3/enrollment/enrol/byAadhaar printAbhaCard = @env.ABDM_BASE_URL@/abha/api/v3/profile/account/abha-card abhaLoginRequestOtp = @env.ABDM_BASE_URL@/abha/api/v3/profile/login/request/otp verifyAbhaLogin = @env.ABDM_BASE_URL@/abha/api/v3/profile/login/verify +requestAuthByAbdm = @env.ABDM_BASE_URL@/abha/api/v3/enrollment/auth/byAbdm abhaMode=sbx diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index 3e8017b..aca47c2 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -91,6 +91,7 @@ abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/b printAbhaCard = https://abhasbx.abdm.gov.in/abha/api/v3/profile/account/abha-card abhaLoginRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/request/otp verifyAbhaLogin = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/verify +requestAuthByAbdm = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/auth/byAbdm abhaMode=sbx diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index 208ebf3..fc9a950 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -54,7 +54,7 @@ abdmVerifyOTP= https://healthidsbx.abdm.gov.in/api/v1/registration/aadhaar/verif abdmCheckAndGenerateMobileOTP= https://healthidsbx.abdm.gov.in/api/v2/registration/aadhaar/checkAndGenerateMobileOTP abdmVerifyMobileOTP= https://healthidsbx.abdm.gov.in/api/v1/registration/aadhaar/verifyMobileOTP abdmcreateHealthIdWithPreVerified= https://healthidsbx.abdm.gov.in/api/v1/registration/aadhaar/createHealthIdWithPreVerified - +requestAuthByAbdm = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/auth/byAbdm ##CareContext Creation API generateOTPForCareContext=https://dev.abdm.gov.in/gateway/v0.5/users/auth/init diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties index d798719..aca47c2 100644 --- a/src/main/environment/common_test.properties +++ b/src/main/environment/common_test.properties @@ -91,7 +91,7 @@ abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/b printAbhaCard = https://abhasbx.abdm.gov.in/abha/api/v3/profile/account/abha-card abhaLoginRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/request/otp verifyAbhaLogin = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/verify - +requestAuthByAbdm = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/auth/byAbdm abhaMode=sbx diff --git a/src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java b/src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java index fbcd95e..0da2463 100644 --- a/src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java +++ b/src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java @@ -26,8 +26,6 @@ public class CreateAbhaV3Controller { @Autowired private CreateAbhaV3Service createAbhaV3Service; - @Autowired - private GenerateHealthID_CardServiceImpl generateHealthID_CardServiceImpl; @CrossOrigin @Operation(summary = "Generate OTP for ABHA enrollment") @@ -71,14 +69,14 @@ public String abhaEnrollmentByAadhaar(@RequestBody String request) { } @CrossOrigin - @Operation(summary = "Verify Mobile OTP for ABHA enrollment") - @PostMapping(value = { "/verifyAuthByMobile" }) + @Operation(summary = "Verify Auth By ABDM for ABHA enrollment") + @PostMapping(value = { "/verifyAuthByAbdm" }) public String verifyMobileForAuth(@RequestBody String request) { - logger.info("Verify Mobile OTP for ABHA enrollment " + request); + logger.info("Verify Auth OTP for ABHA enrollment " + request); OutputResponse response = new OutputResponse(); try { if (request != null) { - String s = createAbhaV3Service.verifyAuthByMobile(request); + String s = createAbhaV3Service.verifyAuthByAbdm(request); response.setResponse(s); } else throw new FHIRException("NDHM_FHIR Empty request object"); @@ -86,7 +84,7 @@ public String verifyMobileForAuth(@RequestBody String request) { response.setError(5000, e.getMessage()); logger.error(e.toString()); } - logger.info("NDHM_FHIR generate OTP for ABHA card API response " + response.toString()); + logger.info("NDHM_FHIR Verify Auth OTP for ABHA enrollment API response " + response.toString()); return response.toString(); } diff --git a/src/main/java/com/wipro/fhir/data/v3/abhaCard/EnrollAuthByABDM.java b/src/main/java/com/wipro/fhir/data/v3/abhaCard/EnrollAuthByABDM.java new file mode 100644 index 0000000..de10293 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/abhaCard/EnrollAuthByABDM.java @@ -0,0 +1,12 @@ +package com.wipro.fhir.data.v3.abhaCard; + +import java.util.Map; + +import lombok.Data; + +@Data +public class EnrollAuthByABDM { + public Map authData; + public String[] scope; + +} diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3Service.java b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3Service.java index 6231476..e805aea 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3Service.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3Service.java @@ -8,7 +8,7 @@ public interface CreateAbhaV3Service { public String enrollmentByAadhaar(String request) throws FHIRException; - public String verifyAuthByMobile(String request) throws FHIRException; + public String verifyAuthByAbdm(String request) throws FHIRException; public String getAbhaCardPrinted(String reqObj) throws FHIRException; diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java index 5d4fe3e..40cdb4e 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java @@ -31,6 +31,7 @@ import com.wipro.fhir.data.healthID.HealthIDResponse; import com.wipro.fhir.data.v3.abhaCard.BioRequest; import com.wipro.fhir.data.v3.abhaCard.ConsentRequest; +import com.wipro.fhir.data.v3.abhaCard.EnrollAuthByABDM; import com.wipro.fhir.data.v3.abhaCard.EnrollByAadhaar; import com.wipro.fhir.data.v3.abhaCard.LoginMethod; import com.wipro.fhir.data.v3.abhaCard.OtpRequest; @@ -61,6 +62,9 @@ public class CreateAbhaV3ServiceImpl implements CreateAbhaV3Service { @Value("${requestOtpForEnrollment}") String requestOtpForEnrollment; + + @Value("${requestAuthByAbdm}") + String requestAuthByAbdm; @Value("${abhaEnrollByAadhaar}") String abhaEnrollByAadhaar; @@ -108,6 +112,12 @@ public String getOtpForEnrollment(String request) throws FHIRException { reqOtpEnrollment.setOtpSystem("aadhaar"); reqOtpEnrollment.setLoginHint("aadhaar"); reqOtpEnrollment.setScope(new String[] { "abha-enrol" }); + } else if ("MOBILE".equalsIgnoreCase(loginMethod.getLoginMethod())) { + reqOtpEnrollment.setLoginId(encryptedLoginId); + reqOtpEnrollment.setTnxId(loginMethod.getTnxId()); + reqOtpEnrollment.setOtpSystem("abdm"); + reqOtpEnrollment.setLoginHint("mobile"); + reqOtpEnrollment.setScope(new String[] { "abha-enrol", "mobile-verify" }); } String requestOBJ = new Gson().toJson(reqOtpEnrollment); @@ -229,7 +239,7 @@ public String enrollmentByAadhaar(String request) throws FHIRException { } @Override - public String verifyAuthByMobile(String request) throws FHIRException { + public String verifyAuthByAbdm(String request) throws FHIRException { String res = null; Map responseMap = new HashMap<>(); RestTemplate restTemplate = new RestTemplate(); @@ -250,7 +260,6 @@ public String verifyAuthByMobile(String request) throws FHIRException { headers.add("TIMESTAMP", nowAsISO); headers.add("Authorization", ndhmAuthToken); - RequestOTPEnrollment reqOtpEnrollment = new RequestOTPEnrollment(); LoginMethod loginMethod = InputMapper.gson().fromJson(request, LoginMethod.class); publicKeyString = certificateKeyService.getCertPublicKey(); @@ -258,20 +267,34 @@ public String verifyAuthByMobile(String request) throws FHIRException { encryptedLoginId = encryption.encrypt(loginMethod.getLoginId(), publicKeyString); } - if ("AADHAAR".equalsIgnoreCase(loginMethod.getLoginMethod())) { - reqOtpEnrollment.setLoginId(encryptedLoginId); - reqOtpEnrollment.setTnxId(loginMethod.getTnxId()); - reqOtpEnrollment.setOtpSystem("abdm"); - reqOtpEnrollment.setLoginHint("mobile"); - reqOtpEnrollment.setScope(new String[] { "abha-enrol", "mobile-verify" }); + EnrollAuthByABDM enrollAuthByabdm = new EnrollAuthByABDM(); + OtpRequest otp = new OtpRequest(); - } + // Get current timestamp + OffsetDateTime now = OffsetDateTime.now(java.time.ZoneOffset.UTC); + DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT; + String formattedTimestamp = now.format(formatter); + otp.setTimestamp(formattedTimestamp); - String requestOBJ = new Gson().toJson(reqOtpEnrollment); - logger.info("ABDM reqobj for verify mobile number for abha enrollment: " + requestOBJ); + otp.setTxnId(loginMethod.getTnxId()); + otp.setOtpValue(encryptedLoginId); + + String[] scope; + scope = new String[] {"abha-enrol", "mobile-verify"}; - HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); - ResponseEntity responseEntity = restTemplate.exchange(requestOtpForEnrollment, HttpMethod.POST, + Map authDataMap = new HashMap<>(); + authDataMap.put("otp", otp); + authDataMap.put("authMethods", new String[] { "otp" }); + + enrollAuthByabdm.setAuthData(authDataMap); + enrollAuthByabdm.setScope(scope); + + + logger.info("ABDM request for enroll by ABDM: " + enrollAuthByabdm); + + String requestObj = new Gson().toJson(enrollAuthByabdm); + HttpEntity httpEntity = new HttpEntity<>(requestObj, headers); + ResponseEntity responseEntity = restTemplate.exchange(requestAuthByAbdm, HttpMethod.POST, httpEntity, String.class); logger.info("ABDM response for verify mobile number for abha enrollment: " + responseEntity); diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java index 1baaf7e..e33fc6a 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java @@ -89,21 +89,26 @@ public String requestOtpForAbhaLogin(String request) throws FHIRException { reqOtpEnrollment.setLoginId(encryptedLoginId); } - if ("AADHAAR".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())) { - reqOtpEnrollment.setOtpSystem("aadhaar"); + if ("AADHAAR".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && + ("abha-number".equalsIgnoreCase(loginAbhaRequest.getLoginHint()) || "abha-address".equalsIgnoreCase(loginAbhaRequest.getLoginHint()) )) { reqOtpEnrollment.setScope(new String[] { "abha-login", "aadhaar-verify" }); - } else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())) { + reqOtpEnrollment.setLoginHint(loginAbhaRequest.getLoginHint()); + reqOtpEnrollment.setOtpSystem("aadhaar"); + } else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) + && ("abha-number".equalsIgnoreCase(loginAbhaRequest.getLoginHint()) || "abha-address".equalsIgnoreCase(loginAbhaRequest.getLoginHint()) )) { + reqOtpEnrollment.setScope(new String[] { "abha-login", "mobile-verify" }); + reqOtpEnrollment.setLoginHint(loginAbhaRequest.getLoginHint()); reqOtpEnrollment.setOtpSystem("abdm"); + } else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && "mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) ) { reqOtpEnrollment.setScope(new String[] { "abha-login", "mobile-verify" }); - } - - if ("ABHA".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) { + reqOtpEnrollment.setLoginHint("mobile"); reqOtpEnrollment.setOtpSystem("abdm"); - reqOtpEnrollment.setLoginHint("abha"); - } else if ("AADHAAR".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) { + } else if ("aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && "aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) ) { + reqOtpEnrollment.setScope(new String[] { "abha-login", "aadhaar-verify" }); reqOtpEnrollment.setLoginHint("aadhaar"); - } else if ("MOBILE".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) { - reqOtpEnrollment.setLoginHint("mobile"); + reqOtpEnrollment.setOtpSystem("aadhaar"); + } else { + throw new FHIRException("Invalid Login ID and Login Hint, Please Pass Valid ID"); } String requestOBJ = new Gson().toJson(reqOtpEnrollment); @@ -113,7 +118,7 @@ public String requestOtpForAbhaLogin(String request) throws FHIRException { ResponseEntity responseEntity = restTemplate.exchange(abhaLoginRequestOtp, HttpMethod.POST, httpEntity, String.class); - logger.info("ABDM response for request otp for Abha login: " + responseEntity); + logger.info("ABDM response for response otp for Abha login: " + responseEntity); String responseStrLogin = common_NDHMService.getBody(responseEntity); if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(200) && responseEntity.hasBody()) { JsonObject jsnOBJ = JsonParser.parseString(responseStrLogin).getAsJsonObject(); From 7a5c0d4cb20e309103fb0548913a4da4ccb06a92 Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Mon, 6 Oct 2025 13:20:06 +0530 Subject: [PATCH 09/30] feat: Abdm M2 V3 changes --- .../CareContextLinkingController.java | 63 ++++ .../GenerateTokenAbdmResponses.java | 39 +++ .../v3/careContext/AddCareContextRequest.java | 20 ++ .../CareContextLinkTokenRequest.java | 15 + .../data/v3/careContext/CareContexts.java | 11 + .../GenerateCareContextTokenRequest.java | 14 + .../careContext/LinkCareContextRequest.java | 14 + .../v3/careContext/PatientCareContext.java | 16 + .../GenerateTokenAbdmResponsesRepo.java | 17 + .../CareContextLinkingService.java | 11 + .../CareContextLinkingServiceImpl.java | 304 ++++++++++++++++++ 11 files changed, 524 insertions(+) create mode 100644 src/main/java/com/wipro/fhir/controller/v3/careContext/CareContextLinkingController.java create mode 100644 src/main/java/com/wipro/fhir/data/mongo/care_context/GenerateTokenAbdmResponses.java create mode 100644 src/main/java/com/wipro/fhir/data/v3/careContext/AddCareContextRequest.java create mode 100644 src/main/java/com/wipro/fhir/data/v3/careContext/CareContextLinkTokenRequest.java create mode 100644 src/main/java/com/wipro/fhir/data/v3/careContext/CareContexts.java create mode 100644 src/main/java/com/wipro/fhir/data/v3/careContext/GenerateCareContextTokenRequest.java create mode 100644 src/main/java/com/wipro/fhir/data/v3/careContext/LinkCareContextRequest.java create mode 100644 src/main/java/com/wipro/fhir/data/v3/careContext/PatientCareContext.java create mode 100644 src/main/java/com/wipro/fhir/repo/mongo/generateToken_response/GenerateTokenAbdmResponsesRepo.java create mode 100644 src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingService.java create mode 100644 src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java diff --git a/src/main/java/com/wipro/fhir/controller/v3/careContext/CareContextLinkingController.java b/src/main/java/com/wipro/fhir/controller/v3/careContext/CareContextLinkingController.java new file mode 100644 index 0000000..8e9a827 --- /dev/null +++ b/src/main/java/com/wipro/fhir/controller/v3/careContext/CareContextLinkingController.java @@ -0,0 +1,63 @@ +package com.wipro.fhir.controller.v3.careContext; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.wipro.fhir.service.v3.careContext.CareContextLinkingService; +import com.wipro.fhir.utils.exception.FHIRException; +import com.wipro.fhir.utils.response.OutputResponse; + +import io.swagger.v3.oas.annotations.Operation; + +@RestController +@RequestMapping(value = "/careContext", headers = "Authorization") +public class CareContextLinkingController { + + @Autowired + private CareContextLinkingService careContextLinkingService; + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Operation(summary = "Generate token for care context linking") + @PostMapping(value = { "/generateCareContextToken" }) + public String requestOtpForEnrollment(@RequestBody String request) { + logger.info("Generate token for care context API request " + request); + OutputResponse response = new OutputResponse(); + try { + if (request != null) { + String s = careContextLinkingService.generateTokenForCareContext(request); + response.setResponse(s); + } else + throw new FHIRException("NDHM_FHIR Empty request object"); + } catch (FHIRException e) { + response.setError(5000, e.getMessage()); + logger.error(e.toString()); + } + logger.info("NDHM_FHIR generate token for care context API response " + response.toString()); + return response.toString(); + } + + @Operation(summary = "link care context") + @PostMapping(value = { "/linkCareContext" }) + public String add(@RequestBody String request) { + logger.info("link care context API request " + request); + OutputResponse response = new OutputResponse(); + try { + if (request != null) { + String s = careContextLinkingService.linkCareContext(request); + response.setResponse(s); + } else + throw new FHIRException("NDHM_FHIR Empty request object"); + } catch (FHIRException e) { + response.setError(5000, e.getMessage()); + logger.error(e.toString()); + } + logger.info("link care context API response " + response.toString()); + return response.toString(); + } +} diff --git a/src/main/java/com/wipro/fhir/data/mongo/care_context/GenerateTokenAbdmResponses.java b/src/main/java/com/wipro/fhir/data/mongo/care_context/GenerateTokenAbdmResponses.java new file mode 100644 index 0000000..a0afad7 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/mongo/care_context/GenerateTokenAbdmResponses.java @@ -0,0 +1,39 @@ +package com.wipro.fhir.data.mongo.care_context; + +import java.time.LocalDateTime; + +import org.joda.time.DateTime; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.data.mongodb.core.mapping.Field; + +import com.google.gson.annotations.Expose; + +import lombok.Data; + +@Data +@Document(collection = "GenerateTokenAbdmResponses") +public class GenerateTokenAbdmResponses { + + @Id + @Expose + @Field(value = "id") + private String id; + + @Expose + @Field(value = "abhaAddress") + private String abhaAddress; + + @Expose + @Field(value = "requestid") + private String requestId; + + @Expose + @Field(value = "response") + private String response; + + @Expose + @Field(value = "createdDate") + private DateTime createdDate; + +} diff --git a/src/main/java/com/wipro/fhir/data/v3/careContext/AddCareContextRequest.java b/src/main/java/com/wipro/fhir/data/v3/careContext/AddCareContextRequest.java new file mode 100644 index 0000000..bf42f71 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/careContext/AddCareContextRequest.java @@ -0,0 +1,20 @@ +package com.wipro.fhir.data.v3.careContext; + +import lombok.Data; + +@Data +public class AddCareContextRequest { + + private long beneficiaryID; + private String abhaAddress; + private String abhaNumber; + private String linkToken; + private String requestId; + private String visitCategory; + private String visitCode; + private String abdmFacilityId; + private String abdmFacilityName; + private String hiType; + private String display; + +} diff --git a/src/main/java/com/wipro/fhir/data/v3/careContext/CareContextLinkTokenRequest.java b/src/main/java/com/wipro/fhir/data/v3/careContext/CareContextLinkTokenRequest.java new file mode 100644 index 0000000..83d7b36 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/careContext/CareContextLinkTokenRequest.java @@ -0,0 +1,15 @@ +package com.wipro.fhir.data.v3.careContext; + +import lombok.Data; + +@Data +public class CareContextLinkTokenRequest { + + private String abhaNumber; + private String abhaAddress; + private String name; + private String gender; + private int yearOfBirth; + private String abdmFacilityId; + +} diff --git a/src/main/java/com/wipro/fhir/data/v3/careContext/CareContexts.java b/src/main/java/com/wipro/fhir/data/v3/careContext/CareContexts.java new file mode 100644 index 0000000..112b244 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/careContext/CareContexts.java @@ -0,0 +1,11 @@ +package com.wipro.fhir.data.v3.careContext; + +import lombok.Data; + +@Data +public class CareContexts { + + private String referenceNumber; + private String display; + +} diff --git a/src/main/java/com/wipro/fhir/data/v3/careContext/GenerateCareContextTokenRequest.java b/src/main/java/com/wipro/fhir/data/v3/careContext/GenerateCareContextTokenRequest.java new file mode 100644 index 0000000..6dcac58 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/careContext/GenerateCareContextTokenRequest.java @@ -0,0 +1,14 @@ +package com.wipro.fhir.data.v3.careContext; + +import lombok.Data; + +@Data +public class GenerateCareContextTokenRequest { + + private String abhaNumber; + private String abhaAddress; + private String name; + private String gender; + private int yearOfBirth; + +} diff --git a/src/main/java/com/wipro/fhir/data/v3/careContext/LinkCareContextRequest.java b/src/main/java/com/wipro/fhir/data/v3/careContext/LinkCareContextRequest.java new file mode 100644 index 0000000..162cabc --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/careContext/LinkCareContextRequest.java @@ -0,0 +1,14 @@ +package com.wipro.fhir.data.v3.careContext; + +import java.util.List; +import lombok.Data; + +@Data +public class LinkCareContextRequest { + + private String abhaNumber; + private String abhaAddress; + private List patient; + + +} diff --git a/src/main/java/com/wipro/fhir/data/v3/careContext/PatientCareContext.java b/src/main/java/com/wipro/fhir/data/v3/careContext/PatientCareContext.java new file mode 100644 index 0000000..2603562 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/careContext/PatientCareContext.java @@ -0,0 +1,16 @@ +package com.wipro.fhir.data.v3.careContext; + +import java.util.List; +import lombok.Data; + +@Data +public class PatientCareContext { + + private String referenceNumber; + private String display; + private List careContexts; + private String hiType; + private int count; + + +} diff --git a/src/main/java/com/wipro/fhir/repo/mongo/generateToken_response/GenerateTokenAbdmResponsesRepo.java b/src/main/java/com/wipro/fhir/repo/mongo/generateToken_response/GenerateTokenAbdmResponsesRepo.java new file mode 100644 index 0000000..ea900af --- /dev/null +++ b/src/main/java/com/wipro/fhir/repo/mongo/generateToken_response/GenerateTokenAbdmResponsesRepo.java @@ -0,0 +1,17 @@ +package com.wipro.fhir.repo.mongo.generateToken_response; + +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.data.rest.core.annotation.RestResource; +import org.springframework.stereotype.Repository; + +import com.wipro.fhir.data.mongo.care_context.GenerateTokenAbdmResponses; + +@Repository +@RestResource(exported = false) +public interface GenerateTokenAbdmResponsesRepo extends MongoRepository { + + GenerateTokenAbdmResponses findByAbhaAddress(String abhaAddress); + + + +} diff --git a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingService.java b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingService.java new file mode 100644 index 0000000..1740739 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingService.java @@ -0,0 +1,11 @@ +package com.wipro.fhir.service.v3.careContext; + +import com.wipro.fhir.utils.exception.FHIRException; + +public interface CareContextLinkingService { + + String generateTokenForCareContext(String request) throws FHIRException; + + String linkCareContext(String request) throws FHIRException; + +} diff --git a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java new file mode 100644 index 0000000..820869b --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java @@ -0,0 +1,304 @@ +package com.wipro.fhir.service.v3.careContext; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; +import java.util.UUID; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; + +import org.joda.time.DateTime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.wipro.fhir.data.mongo.care_context.GenerateTokenAbdmResponses; +import com.wipro.fhir.data.v3.abhaCard.LoginMethod; +import com.wipro.fhir.data.v3.abhaCard.RequestOTPEnrollment; +import com.wipro.fhir.data.v3.careContext.CareContextLinkTokenRequest; +import com.wipro.fhir.data.v3.careContext.CareContexts; +import com.wipro.fhir.data.v3.careContext.GenerateCareContextTokenRequest; +import com.wipro.fhir.data.v3.careContext.LinkCareContextRequest; +import com.wipro.fhir.data.v3.careContext.PatientCareContext; +import com.wipro.fhir.repo.mongo.generateToken_response.GenerateTokenAbdmResponsesRepo; +import com.wipro.fhir.data.v3.careContext.AddCareContextRequest; +import com.wipro.fhir.service.ndhm.Common_NDHMService; +import com.wipro.fhir.service.v3.abha.GenerateAuthSessionService; +import com.wipro.fhir.utils.exception.FHIRException; +import com.wipro.fhir.utils.mapper.InputMapper; + +@Service +public class CareContextLinkingServiceImpl implements CareContextLinkingService { + + @Autowired + private GenerateAuthSessionService generateAuthSessionService; + + @Autowired + private Common_NDHMService common_NDHMService; + + @Autowired + private GenerateTokenAbdmResponsesRepo generateTokenAbdmResponsesRepo; + + @Value("${x-CM-ID}") + String abhaMode; + + @Value("${abdmFacilityId}") + String abdmFacilityId; + + @Value("${generateTokenForLinkCareContext}") + String generateTokenForLinkCareContext; + + @Value("${linkCareContext}") + String linkCareContext; + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Override + public String generateTokenForCareContext(String request) throws FHIRException { + String res = null; + String linkToken = null; + Map responseMap = new HashMap<>(); + RestTemplate restTemplate = new RestTemplate(); + + try { + String abhaAuthToken = generateAuthSessionService.getAbhaAuthToken(); + CareContextLinkTokenRequest careContextLinkRequest = InputMapper.gson().fromJson(request, + CareContextLinkTokenRequest.class); + + if (null != careContextLinkRequest.getAbhaAddress()) { + String linkExists = checkRecordExisits(careContextLinkRequest.getAbhaAddress()); + responseMap.put("linkToken", linkExists); + } else { + + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); + String requestId = UUID.randomUUID().toString(); + headers.add("REQUEST-ID", requestId); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("Authorization", abhaAuthToken); + headers.add("X-CM-ID", abhaMode); + if (null != careContextLinkRequest.getAbdmFacilityId() + && "" != careContextLinkRequest.getAbdmFacilityId()) { + headers.add("X-HIP-ID", careContextLinkRequest.getAbdmFacilityId()); + } else { + headers.add("X-HIP-ID", abdmFacilityId); + } + + GenerateCareContextTokenRequest generateTokenRequest = new GenerateCareContextTokenRequest(); + if (null != careContextLinkRequest.getAbhaNumber() && "" != careContextLinkRequest.getAbhaNumber()) { + String abha = careContextLinkRequest.getAbhaNumber(); + String abhaNumber = abha.replace("-", ""); + generateTokenRequest.setAbhaNumber(abhaNumber); + } + + generateTokenRequest.setAbhaAddress(careContextLinkRequest.getAbhaAddress()); + generateTokenRequest.setName(careContextLinkRequest.getName()); + generateTokenRequest.setYearOfBirth(careContextLinkRequest.getYearOfBirth()); + + if (careContextLinkRequest.getGender().equalsIgnoreCase("female")) { + generateTokenRequest.setGender("F"); + } else if (careContextLinkRequest.getGender().equalsIgnoreCase("male")) { + generateTokenRequest.setGender("M"); + } else { + generateTokenRequest.setGender("O"); + } + + String requestOBJ = new Gson().toJson(generateTokenRequest); + logger.info("ABDM reqobj for generate token link for carecontext : " + requestOBJ); + + HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); + ResponseEntity responseEntity = restTemplate.exchange(generateTokenForLinkCareContext, + HttpMethod.POST, httpEntity, String.class); + + logger.info("ABDM response for generate token link for carecontext : " + responseEntity); + String responseStrLogin = common_NDHMService.getBody(responseEntity); + JsonParser jsnParser = new JsonParser(); + if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(202)) { + String mongoResponse = common_NDHMService.getMongoNDHMResponse(requestId); + responseMap.put("requestId", requestId); + if (!mongoResponse.equalsIgnoreCase("failure")) { + JsonElement jsnElmnt1 = jsnParser.parse(mongoResponse); + JsonObject jsnOBJ1 = new JsonObject(); + jsnOBJ1 = jsnElmnt1.getAsJsonObject(); + try { + if (jsnOBJ1.get("linkToken") != null) { + linkToken = jsnOBJ1.getAsJsonObject("linkToken").getAsString(); + responseMap.put("linkToken", linkToken); + } else + throw new FHIRException( + "NDHM_FHIR " + jsnOBJ1.getAsJsonObject("Error").get("Message").getAsString()); + } catch (Exception e) { + throw new FHIRException( + "NDHM_FHIR " + jsnOBJ1.getAsJsonObject("Error").get("Message").getAsString()); + } + } + + } else { + throw new FHIRException(responseEntity.getBody()); + } + } + } catch (Exception e) { + throw new FHIRException(e.getMessage()); + } + + return responseMap.toString(); + } + + @Override + public String linkCareContext(String request) throws FHIRException { + String res = null; + String linkToken = null; + Map responseMap = new HashMap<>(); + RestTemplate restTemplate = new RestTemplate(); + + try { + String abhaAuthToken = generateAuthSessionService.getAbhaAuthToken(); + AddCareContextRequest addCareContextRequest = InputMapper.gson().fromJson(request, + AddCareContextRequest.class); + MultiValueMap headers = new LinkedMultiValueMap<>(); + JsonParser jsnParser = new JsonParser(); + + if (null != addCareContextRequest.getLinkToken()) { + headers.add("X-LINK-TOKEN", addCareContextRequest.getLinkToken()); + } else { // if link token is not found then fetch from mongo DB + String mongoResponse = common_NDHMService.getMongoNDHMResponse(addCareContextRequest.getRequestId()); + if (!mongoResponse.equalsIgnoreCase("failure")) { + JsonElement jsnElmnt1 = jsnParser.parse(mongoResponse); + JsonObject jsnOBJ1 = new JsonObject(); + jsnOBJ1 = jsnElmnt1.getAsJsonObject(); + try { + if (jsnOBJ1.get("linkToken") != null) { + linkToken = jsnOBJ1.getAsJsonObject("linkToken").getAsString(); + headers.add("X-LINK-TOKEN", linkToken); + } else + throw new FHIRException( + "ABDM_FHIR " + jsnOBJ1.getAsJsonObject("Error").get("Message").getAsString()); + } catch (Exception e) { + throw new FHIRException( + "ABDM_FHIR " + jsnOBJ1.getAsJsonObject("Error").get("Message").getAsString()); + } + } + + } + + headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("Authorization", abhaAuthToken); + headers.add("X-CM-ID", abhaMode); + if (null != addCareContextRequest.getAbdmFacilityId() && "" != addCareContextRequest.getAbdmFacilityId()) { + headers.add("X-HIP-ID", addCareContextRequest.getAbdmFacilityId()); + } else { + headers.add("X-HIP-ID", abdmFacilityId); + } + + LinkCareContextRequest linkCareContextRequest = new LinkCareContextRequest(); + CareContexts careContexts = new CareContexts(); + PatientCareContext patient = new PatientCareContext(); + + ArrayList cc = new ArrayList(); + careContexts.setReferenceNumber(addCareContextRequest.getVisitCode()); + careContexts.setDisplay(addCareContextRequest.getDisplay()); + cc.add(careContexts); + + ArrayList pcc = new ArrayList(); + patient.setReferenceNumber(addCareContextRequest.getVisitCode()); + patient.setDisplay(addCareContextRequest.getDisplay()); + patient.setDisplay(addCareContextRequest.getDisplay()); + patient.setCount(1); + patient.setCareContexts(cc); + pcc.add(patient); + + if (null != addCareContextRequest.getAbhaNumber() && "" != addCareContextRequest.getAbhaNumber()) { + String abha = addCareContextRequest.getAbhaNumber(); + String abhaNumber = abha.replace("-", ""); + linkCareContextRequest.setAbhaNumber(abhaNumber); + } + + linkCareContextRequest.setAbhaAddress(addCareContextRequest.getAbhaAddress()); + linkCareContextRequest.setPatient(pcc); + + String requestOBJ = new Gson().toJson(linkCareContextRequest); + logger.info("ABDM reqobj for generate token link for carecontext : " + requestOBJ); + + HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); + ResponseEntity responseEntity = restTemplate.exchange(linkCareContext, HttpMethod.POST, httpEntity, + String.class); + + logger.info("ABDM response for generate token link for carecontext : " + responseEntity); + String responseStrLogin = common_NDHMService.getBody(responseEntity); + if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(202)) { + res = "Care Context added successfully"; + + } else { + throw new FHIRException(responseEntity.getBody()); + } + } catch (Exception e) { + throw new FHIRException(e.getMessage()); + } + + return res; + } + + public String checkRecordExisits(String abhaAddress) { + GenerateTokenAbdmResponses result = generateTokenAbdmResponsesRepo.findByAbhaAddress(abhaAddress); + logger.info("find by abha address result - ", result); + + if (result != null && result.getCreatedDate() != null) { + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.MONTH, -3); + Date threeMonthsAgo = cal.getTime(); + String linkResponse = result.getResponse(); + + if (result.getCreatedDate().isAfter(threeMonthsAgo.getTime())) { + if (linkResponse != null) { + try { + ObjectMapper mapper = new ObjectMapper(); + JsonNode root = mapper.readTree(linkResponse); + JsonNode linkToken = root.path("LinkToken"); + if (!linkToken.isNull() && !linkToken.isMissingNode()) { + return linkToken.asText(); + } + } catch (Exception e) { + logger.info("failed abha exists check with exception - ", e.getMessage()); + return null; + } + } + } + } + + return null; + } + +} From 43683a27850397cdf94f21fd8ac73f28b6ec195e Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Mon, 13 Oct 2025 18:00:14 +0530 Subject: [PATCH 10/30] feat: mongo query change fetch for linktoken --- src/main/environment/common_ci.properties | 4 +- .../GenerateTokenAbdmResponses.java | 6 +- .../GenerateTokenAbdmResponsesRepo.java | 2 +- .../fhir/service/ndhm/Common_NDHMService.java | 2 + .../service/ndhm/Common_NDHMServiceImpl.java | 18 ++ .../CareContextLinkingServiceImpl.java | 177 ++++++++++-------- 6 files changed, 124 insertions(+), 85 deletions(-) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index ea262e0..75945e9 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -99,8 +99,8 @@ webLoginAbhaVerify = @env.ABDM_PHR_URL@/login/abha/verify webLoginPhrCard = @env.ABDM_PHR_URL@/login/profile/abha/phr-card ## ABDM V3 M2 APIs -generateTokenForLinkCareContext = @env.ABDM_ABHA_V3_URL@/v3/token/generate-token -linkCareContext = @env.ABDM_ABHA_V3_URL@/hip/v3/link/carecontext +generateTokenForLinkCareContext = @env.ABDM_HIECM_BASE_URL@/api/hiecm/v3/token/generate-token +linkCareContext = @env.ABDM_HIECM_BASE_URL@/api/hiecm/hip/v3/link/carecontext x-CM-ID=@env.X_CM_ID@ abhaMode=@env.ABHA_MODE@ diff --git a/src/main/java/com/wipro/fhir/data/mongo/care_context/GenerateTokenAbdmResponses.java b/src/main/java/com/wipro/fhir/data/mongo/care_context/GenerateTokenAbdmResponses.java index a0afad7..153d393 100644 --- a/src/main/java/com/wipro/fhir/data/mongo/care_context/GenerateTokenAbdmResponses.java +++ b/src/main/java/com/wipro/fhir/data/mongo/care_context/GenerateTokenAbdmResponses.java @@ -1,8 +1,8 @@ package com.wipro.fhir.data.mongo.care_context; import java.time.LocalDateTime; +import java.util.Date; -import org.joda.time.DateTime; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; @@ -25,7 +25,7 @@ public class GenerateTokenAbdmResponses { private String abhaAddress; @Expose - @Field(value = "requestid") + @Field(value = "requestId") private String requestId; @Expose @@ -34,6 +34,6 @@ public class GenerateTokenAbdmResponses { @Expose @Field(value = "createdDate") - private DateTime createdDate; + private Date createdDate; } diff --git a/src/main/java/com/wipro/fhir/repo/mongo/generateToken_response/GenerateTokenAbdmResponsesRepo.java b/src/main/java/com/wipro/fhir/repo/mongo/generateToken_response/GenerateTokenAbdmResponsesRepo.java index ea900af..70db7ac 100644 --- a/src/main/java/com/wipro/fhir/repo/mongo/generateToken_response/GenerateTokenAbdmResponsesRepo.java +++ b/src/main/java/com/wipro/fhir/repo/mongo/generateToken_response/GenerateTokenAbdmResponsesRepo.java @@ -12,6 +12,6 @@ public interface GenerateTokenAbdmResponsesRepo extends MongoRepository res) throws FHIRException; public HttpHeaders getHeadersWithXtoken(String ndhmAuthToken,String X_Token); public HttpHeaders getHeadersWithAadhaarBioXtoken(String ndhmAuthToken, String X_Token); + public GenerateTokenAbdmResponses getLinkToken(String requestId) throws FHIRException; } diff --git a/src/main/java/com/wipro/fhir/service/ndhm/Common_NDHMServiceImpl.java b/src/main/java/com/wipro/fhir/service/ndhm/Common_NDHMServiceImpl.java index 752e9d6..6dfdafd 100644 --- a/src/main/java/com/wipro/fhir/service/ndhm/Common_NDHMServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/ndhm/Common_NDHMServiceImpl.java @@ -33,8 +33,10 @@ import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; +import com.wipro.fhir.data.mongo.care_context.GenerateTokenAbdmResponses; import com.wipro.fhir.data.mongo.care_context.NDHMRequest; import com.wipro.fhir.data.mongo.care_context.NDHMResponse; +import com.wipro.fhir.repo.mongo.generateToken_response.GenerateTokenAbdmResponsesRepo; import com.wipro.fhir.repo.mongo.ndhm_response.NDHMResponseRepo; import com.wipro.fhir.utils.exception.FHIRException; @@ -43,6 +45,9 @@ public class Common_NDHMServiceImpl implements Common_NDHMService { @Autowired private NDHMResponseRepo nDHMResponseRepo; + @Autowired + private GenerateTokenAbdmResponsesRepo generateTokenAbdmResponsesRepo; + /*** * @author SH20094090 * @return headers for the NDHM API's @@ -149,6 +154,19 @@ NDHMResponse getResponseMongo(String reqID) { } else return null; } + + @Override + public GenerateTokenAbdmResponses getLinkToken(String requestId) throws FHIRException { + GenerateTokenAbdmResponses res = generateTokenAbdmResponsesRepo.findByRequestId(requestId); + if(res != null) { + return res; + } else { + return null; + } + + } + + @Override public String getBody(ResponseEntity res) throws FHIRException { diff --git a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java index 820869b..dcec2f8 100644 --- a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java @@ -140,23 +140,31 @@ public String generateTokenForCareContext(String request) throws FHIRException { String responseStrLogin = common_NDHMService.getBody(responseEntity); JsonParser jsnParser = new JsonParser(); if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(202)) { - String mongoResponse = common_NDHMService.getMongoNDHMResponse(requestId); + GenerateTokenAbdmResponses mongoResponse = common_NDHMService.getLinkToken(requestId); responseMap.put("requestId", requestId); - if (!mongoResponse.equalsIgnoreCase("failure")) { - JsonElement jsnElmnt1 = jsnParser.parse(mongoResponse); - JsonObject jsnOBJ1 = new JsonObject(); - jsnOBJ1 = jsnElmnt1.getAsJsonObject(); - try { - if (jsnOBJ1.get("linkToken") != null) { - linkToken = jsnOBJ1.getAsJsonObject("linkToken").getAsString(); - responseMap.put("linkToken", linkToken); - } else - throw new FHIRException( - "NDHM_FHIR " + jsnOBJ1.getAsJsonObject("Error").get("Message").getAsString()); - } catch (Exception e) { - throw new FHIRException( - "NDHM_FHIR " + jsnOBJ1.getAsJsonObject("Error").get("Message").getAsString()); - } + if (mongoResponse != null && mongoResponse.getResponse() != null) { + String abhaResponse = mongoResponse.getResponse(); + JsonElement jsonElement = jsnParser.parse(abhaResponse); + JsonObject jsonObject = jsonElement.getAsJsonObject(); + + try { + JsonElement linkTokenElement = jsonObject.get("LinkToken"); + + if (linkTokenElement != null && !linkTokenElement.isJsonNull()) { + linkToken = linkTokenElement.getAsString(); + responseMap.put("X-LINK-TOKEN", linkToken); + } else { + if (jsonObject.has("Error") && !jsonObject.get("Error").isJsonNull()) { + JsonObject errorObject = jsonObject.getAsJsonObject("Error"); + responseMap.put("Error", errorObject.toString()); + } else { + responseMap.put("Error", "Unknown error"); + } + } + } catch (Exception e) { + throw new FHIRException("ABDM_FHIR Error while parsing response: " + e.getMessage()); + } + } } else { @@ -187,82 +195,93 @@ public String linkCareContext(String request) throws FHIRException { if (null != addCareContextRequest.getLinkToken()) { headers.add("X-LINK-TOKEN", addCareContextRequest.getLinkToken()); } else { // if link token is not found then fetch from mongo DB - String mongoResponse = common_NDHMService.getMongoNDHMResponse(addCareContextRequest.getRequestId()); - if (!mongoResponse.equalsIgnoreCase("failure")) { - JsonElement jsnElmnt1 = jsnParser.parse(mongoResponse); - JsonObject jsnOBJ1 = new JsonObject(); - jsnOBJ1 = jsnElmnt1.getAsJsonObject(); + GenerateTokenAbdmResponses mongoResponse = common_NDHMService + .getLinkToken(addCareContextRequest.getRequestId()); + if (mongoResponse != null && mongoResponse.getResponse() != null) { + String abhaResponse = mongoResponse.getResponse(); + JsonElement jsonElement = jsnParser.parse(abhaResponse); + JsonObject jsonObject = jsonElement.getAsJsonObject(); + try { - if (jsnOBJ1.get("linkToken") != null) { - linkToken = jsnOBJ1.getAsJsonObject("linkToken").getAsString(); + JsonElement linkTokenElement = jsonObject.get("LinkToken"); + if (linkTokenElement != null && !linkTokenElement.isJsonNull()) { + linkToken = linkTokenElement.getAsString(); headers.add("X-LINK-TOKEN", linkToken); - } else - throw new FHIRException( - "ABDM_FHIR " + jsnOBJ1.getAsJsonObject("Error").get("Message").getAsString()); + } else { + if (jsonObject.has("Error") && !jsonObject.get("Error").isJsonNull()) { + JsonObject errorObject = jsonObject.getAsJsonObject("Error"); + responseMap.put("Error", errorObject.toString()); + } else { + responseMap.put("Error", "Unknown error"); + } + } } catch (Exception e) { - throw new FHIRException( - "ABDM_FHIR " + jsnOBJ1.getAsJsonObject("Error").get("Message").getAsString()); + throw new FHIRException("ABDM_FHIR Error while parsing response: " + e.getMessage()); } } } + + if (linkToken != null) { - headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); - headers.add("REQUEST-ID", UUID.randomUUID().toString()); - - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - df.setTimeZone(tz); - String nowAsISO = df.format(new Date()); - headers.add("TIMESTAMP", nowAsISO); - headers.add("Authorization", abhaAuthToken); - headers.add("X-CM-ID", abhaMode); - if (null != addCareContextRequest.getAbdmFacilityId() && "" != addCareContextRequest.getAbdmFacilityId()) { - headers.add("X-HIP-ID", addCareContextRequest.getAbdmFacilityId()); - } else { - headers.add("X-HIP-ID", abdmFacilityId); - } + headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); - LinkCareContextRequest linkCareContextRequest = new LinkCareContextRequest(); - CareContexts careContexts = new CareContexts(); - PatientCareContext patient = new PatientCareContext(); - - ArrayList cc = new ArrayList(); - careContexts.setReferenceNumber(addCareContextRequest.getVisitCode()); - careContexts.setDisplay(addCareContextRequest.getDisplay()); - cc.add(careContexts); - - ArrayList pcc = new ArrayList(); - patient.setReferenceNumber(addCareContextRequest.getVisitCode()); - patient.setDisplay(addCareContextRequest.getDisplay()); - patient.setDisplay(addCareContextRequest.getDisplay()); - patient.setCount(1); - patient.setCareContexts(cc); - pcc.add(patient); - - if (null != addCareContextRequest.getAbhaNumber() && "" != addCareContextRequest.getAbhaNumber()) { - String abha = addCareContextRequest.getAbhaNumber(); - String abhaNumber = abha.replace("-", ""); - linkCareContextRequest.setAbhaNumber(abhaNumber); - } + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("Authorization", abhaAuthToken); + headers.add("X-CM-ID", abhaMode); + if (null != addCareContextRequest.getAbdmFacilityId() + && "" != addCareContextRequest.getAbdmFacilityId()) { + headers.add("X-HIP-ID", addCareContextRequest.getAbdmFacilityId()); + } else { + headers.add("X-HIP-ID", abdmFacilityId); + } - linkCareContextRequest.setAbhaAddress(addCareContextRequest.getAbhaAddress()); - linkCareContextRequest.setPatient(pcc); + LinkCareContextRequest linkCareContextRequest = new LinkCareContextRequest(); + CareContexts careContexts = new CareContexts(); + PatientCareContext patient = new PatientCareContext(); + + ArrayList cc = new ArrayList(); + careContexts.setReferenceNumber(addCareContextRequest.getVisitCode()); + careContexts.setDisplay(addCareContextRequest.getDisplay()); + cc.add(careContexts); + + ArrayList pcc = new ArrayList(); + patient.setReferenceNumber(addCareContextRequest.getVisitCode()); + patient.setDisplay(addCareContextRequest.getDisplay()); + patient.setDisplay(addCareContextRequest.getDisplay()); + patient.setCount(1); + patient.setCareContexts(cc); + pcc.add(patient); + + if (null != addCareContextRequest.getAbhaNumber() && "" != addCareContextRequest.getAbhaNumber()) { + String abha = addCareContextRequest.getAbhaNumber(); + String abhaNumber = abha.replace("-", ""); + linkCareContextRequest.setAbhaNumber(abhaNumber); + } - String requestOBJ = new Gson().toJson(linkCareContextRequest); - logger.info("ABDM reqobj for generate token link for carecontext : " + requestOBJ); + linkCareContextRequest.setAbhaAddress(addCareContextRequest.getAbhaAddress()); + linkCareContextRequest.setPatient(pcc); - HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); - ResponseEntity responseEntity = restTemplate.exchange(linkCareContext, HttpMethod.POST, httpEntity, - String.class); + String requestOBJ = new Gson().toJson(linkCareContextRequest); + logger.info("ABDM reqobj for generate token link for carecontext : " + requestOBJ); - logger.info("ABDM response for generate token link for carecontext : " + responseEntity); - String responseStrLogin = common_NDHMService.getBody(responseEntity); - if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(202)) { - res = "Care Context added successfully"; + HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); + ResponseEntity responseEntity = restTemplate.exchange(linkCareContext, HttpMethod.POST, + httpEntity, String.class); - } else { - throw new FHIRException(responseEntity.getBody()); + logger.info("ABDM response for generate token link for carecontext : " + responseEntity); + String responseStrLogin = common_NDHMService.getBody(responseEntity); + if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(202)) { + res = "Care Context added successfully"; + + } else { + throw new FHIRException(responseEntity.getBody()); + } } } catch (Exception e) { throw new FHIRException(e.getMessage()); @@ -281,7 +300,7 @@ public String checkRecordExisits(String abhaAddress) { Date threeMonthsAgo = cal.getTime(); String linkResponse = result.getResponse(); - if (result.getCreatedDate().isAfter(threeMonthsAgo.getTime())) { + if (result.getCreatedDate().after(threeMonthsAgo)) { if (linkResponse != null) { try { ObjectMapper mapper = new ObjectMapper(); From c1c5d38eec8a497b3acbd2e52d8969401afc43ce Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Tue, 14 Oct 2025 16:54:43 +0530 Subject: [PATCH 11/30] fix: link carecontext authorization error --- .../service/ndhm/Common_NDHMServiceImpl.java | 5 +++++ .../CareContextLinkingServiceImpl.java | 20 +++++++++---------- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/wipro/fhir/service/ndhm/Common_NDHMServiceImpl.java b/src/main/java/com/wipro/fhir/service/ndhm/Common_NDHMServiceImpl.java index 6dfdafd..a7cdae6 100644 --- a/src/main/java/com/wipro/fhir/service/ndhm/Common_NDHMServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/ndhm/Common_NDHMServiceImpl.java @@ -27,6 +27,8 @@ import java.util.TimeZone; import java.util.UUID; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; @@ -48,6 +50,8 @@ public class Common_NDHMServiceImpl implements Common_NDHMService { @Autowired private GenerateTokenAbdmResponsesRepo generateTokenAbdmResponsesRepo; + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + /*** * @author SH20094090 * @return headers for the NDHM API's @@ -158,6 +162,7 @@ NDHMResponse getResponseMongo(String reqID) { @Override public GenerateTokenAbdmResponses getLinkToken(String requestId) throws FHIRException { GenerateTokenAbdmResponses res = generateTokenAbdmResponsesRepo.findByRequestId(requestId); + logger.info("Mongo response returned " + res); if(res != null) { return res; } else { diff --git a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java index dcec2f8..421a2cd 100644 --- a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java @@ -153,12 +153,14 @@ public String generateTokenForCareContext(String request) throws FHIRException { if (linkTokenElement != null && !linkTokenElement.isJsonNull()) { linkToken = linkTokenElement.getAsString(); responseMap.put("X-LINK-TOKEN", linkToken); + logger.info("Mongo has link token"); } else { if (jsonObject.has("Error") && !jsonObject.get("Error").isJsonNull()) { JsonObject errorObject = jsonObject.getAsJsonObject("Error"); - responseMap.put("Error", errorObject.toString()); + logger.info("Mongo has no link token other message - " + errorObject.toString()); + responseMap.put("error", errorObject.toString()); } else { - responseMap.put("Error", "Unknown error"); + responseMap.put("error", "Unknown error"); } } } catch (Exception e) { @@ -179,9 +181,7 @@ public String generateTokenForCareContext(String request) throws FHIRException { } @Override - public String linkCareContext(String request) throws FHIRException { - String res = null; - String linkToken = null; + public String linkCareContext(String request) throws FHIRException { String linkToken = null; Map responseMap = new HashMap<>(); RestTemplate restTemplate = new RestTemplate(); @@ -210,9 +210,9 @@ public String linkCareContext(String request) throws FHIRException { } else { if (jsonObject.has("Error") && !jsonObject.get("Error").isJsonNull()) { JsonObject errorObject = jsonObject.getAsJsonObject("Error"); - responseMap.put("Error", errorObject.toString()); + responseMap.put("error", errorObject.toString()); } else { - responseMap.put("Error", "Unknown error"); + responseMap.put("error", "Unknown error"); } } } catch (Exception e) { @@ -222,7 +222,7 @@ public String linkCareContext(String request) throws FHIRException { } - if (linkToken != null) { + if (linkToken != null) { headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); headers.add("REQUEST-ID", UUID.randomUUID().toString()); @@ -277,7 +277,7 @@ public String linkCareContext(String request) throws FHIRException { logger.info("ABDM response for generate token link for carecontext : " + responseEntity); String responseStrLogin = common_NDHMService.getBody(responseEntity); if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(202)) { - res = "Care Context added successfully"; + responseMap.put("message", "Care Context added successfully"); } else { throw new FHIRException(responseEntity.getBody()); @@ -287,7 +287,7 @@ public String linkCareContext(String request) throws FHIRException { throw new FHIRException(e.getMessage()); } - return res; + return responseMap.toString(); } public String checkRecordExisits(String abhaAddress) { From 945d8746f4c8e3cd201318830b9d80cb56023e33 Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Fri, 31 Oct 2025 15:35:05 +0530 Subject: [PATCH 12/30] feat: hiTypes addition --- .../repo/v3/careContext/CareContextRepo.java | 24 ++++++ .../CareContextLinkingServiceImpl.java | 76 +++++++++++++++---- 2 files changed, 84 insertions(+), 16 deletions(-) create mode 100644 src/main/java/com/wipro/fhir/repo/v3/careContext/CareContextRepo.java diff --git a/src/main/java/com/wipro/fhir/repo/v3/careContext/CareContextRepo.java b/src/main/java/com/wipro/fhir/repo/v3/careContext/CareContextRepo.java new file mode 100644 index 0000000..9162fe0 --- /dev/null +++ b/src/main/java/com/wipro/fhir/repo/v3/careContext/CareContextRepo.java @@ -0,0 +1,24 @@ +package com.wipro.fhir.repo.v3.careContext; + +import java.math.BigInteger; + +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; + +import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; + +public interface CareContextRepo extends CrudRepository { + + @Query(value="SELECT COUNT(*) FROM t_phy_vitals WHERE VisitCode = :visitCode order by 1 desc", nativeQuery = true) + public int hasPhyVitals(String visitCode); + + @Query(value="SELECT COUNT(*) FROM t_prescribeddrug WHERE VisitCode = :visitCode order by 1 desc", nativeQuery = true) + public int hasPrescribedDrugs(String visitCode); + + @Query(value="SELECT COUNT(*) FROM t_lab_testorder WHERE VisitCode = :visitCode order by 1 desc", nativeQuery = true) + public int hasLabtestsDone(String visitCode); + + @Query(value="SELECT COUNT(*) FROM t_childvaccinedetail1 WHERE VisitCode = :visitCode order by 1 desc", nativeQuery = true) + public int hasVaccineDetails(String visitCode); + +} diff --git a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java index 421a2cd..95f2856 100644 --- a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java @@ -6,6 +6,7 @@ import java.util.Calendar; import java.util.Date; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.UUID; @@ -42,6 +43,7 @@ import com.wipro.fhir.data.v3.careContext.LinkCareContextRequest; import com.wipro.fhir.data.v3.careContext.PatientCareContext; import com.wipro.fhir.repo.mongo.generateToken_response.GenerateTokenAbdmResponsesRepo; +import com.wipro.fhir.repo.v3.careContext.CareContextRepo; import com.wipro.fhir.data.v3.careContext.AddCareContextRequest; import com.wipro.fhir.service.ndhm.Common_NDHMService; import com.wipro.fhir.service.v3.abha.GenerateAuthSessionService; @@ -68,10 +70,13 @@ public class CareContextLinkingServiceImpl implements CareContextLinkingService @Value("${generateTokenForLinkCareContext}") String generateTokenForLinkCareContext; - + @Value("${linkCareContext}") String linkCareContext; + @Autowired + private CareContextRepo careContextRepo; + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); @Override @@ -240,23 +245,29 @@ public String generateTokenForCareContext(String request) throws FHIRException { } else { headers.add("X-HIP-ID", abdmFacilityId); } - + + String[] hiTypes = findHiTypes(addCareContextRequest.getVisitCode(), addCareContextRequest.getVisitCategory()); + LinkCareContextRequest linkCareContextRequest = new LinkCareContextRequest(); CareContexts careContexts = new CareContexts(); - PatientCareContext patient = new PatientCareContext(); + ArrayList pcc = new ArrayList(); - ArrayList cc = new ArrayList(); - careContexts.setReferenceNumber(addCareContextRequest.getVisitCode()); - careContexts.setDisplay(addCareContextRequest.getDisplay()); - cc.add(careContexts); + for (String hiType : hiTypes) { + PatientCareContext patient = new PatientCareContext(); - ArrayList pcc = new ArrayList(); - patient.setReferenceNumber(addCareContextRequest.getVisitCode()); - patient.setDisplay(addCareContextRequest.getDisplay()); - patient.setDisplay(addCareContextRequest.getDisplay()); - patient.setCount(1); - patient.setCareContexts(cc); - pcc.add(patient); + ArrayList cc = new ArrayList(); + careContexts.setReferenceNumber(addCareContextRequest.getVisitCode()); + careContexts.setDisplay(addCareContextRequest.getVisitCategory()); + cc.add(careContexts); + + patient.setReferenceNumber(addCareContextRequest.getVisitCode()); + patient.setDisplay(addCareContextRequest.getVisitCategory() + " care context of " + addCareContextRequest.getAbhaNumber()); + patient.setCount(1); + patient.setCareContexts(cc); + patient.setHiType(hiType); + pcc.add(patient); + } + if (null != addCareContextRequest.getAbhaNumber() && "" != addCareContextRequest.getAbhaNumber()) { String abha = addCareContextRequest.getAbhaNumber(); @@ -293,12 +304,13 @@ public String generateTokenForCareContext(String request) throws FHIRException { public String checkRecordExisits(String abhaAddress) { GenerateTokenAbdmResponses result = generateTokenAbdmResponsesRepo.findByAbhaAddress(abhaAddress); logger.info("find by abha address result - ", result); + String linkResponse = null; if (result != null && result.getCreatedDate() != null) { Calendar cal = Calendar.getInstance(); cal.add(Calendar.MONTH, -3); Date threeMonthsAgo = cal.getTime(); - String linkResponse = result.getResponse(); + linkResponse = result.getResponse(); if (result.getCreatedDate().after(threeMonthsAgo)) { if (linkResponse != null) { @@ -317,7 +329,39 @@ public String checkRecordExisits(String abhaAddress) { } } - return null; + return linkResponse; + } + + public String[] findHiTypes(String visitCode, String visitCategory) { + + List hiTypes = new ArrayList<>(); + if (visitCategory.equalsIgnoreCase("General OPD")) { + hiTypes.add("OPConsultation"); + } else if (visitCategory.equalsIgnoreCase("General OPD (QC)")) { + hiTypes.add("OPConsultation"); + } + hiTypes.add("DischargeSummary"); + + int hasPhyVitals = careContextRepo.hasPhyVitals(visitCode); + if(hasPhyVitals > 0) { + hiTypes.add("WellnessRecord"); + } + int hasPrescription = careContextRepo.hasPrescribedDrugs(visitCode); + if (hasPrescription > 0) { + hiTypes.add("Prescription"); + } + + int hasLabTests = careContextRepo.hasLabtestsDone(visitCode); + if (hasLabTests > 0) { + hiTypes.add("DiagnoticsReport"); + } + int hasVaccineDetails = careContextRepo.hasVaccineDetails(visitCode); + if (hasVaccineDetails > 0) { + hiTypes.add("ImmunizationRecord"); + } + + return hiTypes.toArray(new String[0]); } } + From c1c96f4f9349ad1c80ba288b06c635f182e4db8c Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Fri, 31 Oct 2025 15:38:52 +0530 Subject: [PATCH 13/30] feat: version change for testing --- src/main/webapp/WEB-INF/jboss-web.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/webapp/WEB-INF/jboss-web.xml b/src/main/webapp/WEB-INF/jboss-web.xml index ad0e4bb..5190e52 100644 --- a/src/main/webapp/WEB-INF/jboss-web.xml +++ b/src/main/webapp/WEB-INF/jboss-web.xml @@ -1,4 +1,4 @@ - /fhir-api + /fhir-api-abdm From d267c1732eb3becbbaea46c50270c93414762a52 Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Tue, 4 Nov 2025 15:54:21 +0530 Subject: [PATCH 14/30] fix: minor change for empty response --- .../service/v3/careContext/CareContextLinkingServiceImpl.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java index 95f2856..9b6cc69 100644 --- a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java @@ -198,6 +198,7 @@ public String generateTokenForCareContext(String request) throws FHIRException { JsonParser jsnParser = new JsonParser(); if (null != addCareContextRequest.getLinkToken()) { + linkToken = addCareContextRequest.getLinkToken(); headers.add("X-LINK-TOKEN", addCareContextRequest.getLinkToken()); } else { // if link token is not found then fetch from mongo DB GenerateTokenAbdmResponses mongoResponse = common_NDHMService From 6d5298fcd41ee2a26d639c725eb122ebb3342ec3 Mon Sep 17 00:00:00 2001 From: Helen Grace Karyamsetty <133211481+helenKaryamsetty@users.noreply.github.com> Date: Tue, 4 Nov 2025 16:04:24 +0530 Subject: [PATCH 15/30] Simplify queries in CareContextRepo interface Removed unnecessary 'order by 1 desc' clause from queries. --- .../wipro/fhir/repo/v3/careContext/CareContextRepo.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/wipro/fhir/repo/v3/careContext/CareContextRepo.java b/src/main/java/com/wipro/fhir/repo/v3/careContext/CareContextRepo.java index 9162fe0..9015882 100644 --- a/src/main/java/com/wipro/fhir/repo/v3/careContext/CareContextRepo.java +++ b/src/main/java/com/wipro/fhir/repo/v3/careContext/CareContextRepo.java @@ -9,16 +9,16 @@ public interface CareContextRepo extends CrudRepository { - @Query(value="SELECT COUNT(*) FROM t_phy_vitals WHERE VisitCode = :visitCode order by 1 desc", nativeQuery = true) + @Query(value="SELECT COUNT(*) FROM t_phy_vitals WHERE VisitCode = :visitCode", nativeQuery = true) public int hasPhyVitals(String visitCode); - @Query(value="SELECT COUNT(*) FROM t_prescribeddrug WHERE VisitCode = :visitCode order by 1 desc", nativeQuery = true) + @Query(value="SELECT COUNT(*) FROM t_prescribeddrug WHERE VisitCode = :visitCode", nativeQuery = true) public int hasPrescribedDrugs(String visitCode); - @Query(value="SELECT COUNT(*) FROM t_lab_testorder WHERE VisitCode = :visitCode order by 1 desc", nativeQuery = true) + @Query(value="SELECT COUNT(*) FROM t_lab_testorder WHERE VisitCode = :visitCode", nativeQuery = true) public int hasLabtestsDone(String visitCode); - @Query(value="SELECT COUNT(*) FROM t_childvaccinedetail1 WHERE VisitCode = :visitCode order by 1 desc", nativeQuery = true) + @Query(value="SELECT COUNT(*) FROM t_childvaccinedetail1 WHERE VisitCode = :visitCode", nativeQuery = true) public int hasVaccineDetails(String visitCode); } From 23b4a207ff8e99baf50aa5ccbb926389ece53d52 Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Thu, 6 Nov 2025 13:55:06 +0530 Subject: [PATCH 16/30] fix: corrected response format --- .../careContext/CareContextLinkingServiceImpl.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java index 451a89e..d8a6382 100644 --- a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java @@ -182,7 +182,7 @@ public String generateTokenForCareContext(String request) throws FHIRException { throw new FHIRException(e.getMessage()); } - return responseMap.toString(); + return new Gson().toJson(responseMap); } @Override @@ -292,14 +292,21 @@ public String generateTokenForCareContext(String request) throws FHIRException { responseMap.put("message", "Care Context added successfully"); } else { - throw new FHIRException(responseEntity.getBody()); + JsonObject json = JsonParser.parseString(responseEntity.getBody()).getAsJsonObject(); + if (json.has("error")) { + JsonObject errorObj = json.getAsJsonObject("error"); + String message = errorObj.has("message") ? errorObj.get("message").getAsString() : "Unknown error"; + responseMap.put("error", message); + } else { + responseMap.put("error", "Unknown error"); + } } } } catch (Exception e) { throw new FHIRException(e.getMessage()); } - return responseMap.toString(); + return new Gson().toJson(responseMap); } public String checkRecordExisits(String abhaAddress) { From 5d6dd4428d58a07f6015f047ccc8a35d66af136a Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Wed, 19 Nov 2025 12:33:43 +0530 Subject: [PATCH 17/30] fix: minor logic change for care context linking --- .../fhir/service/ndhm/LinkCareContext_NDHMServiceImpl.java | 1 + .../v3/careContext/CareContextLinkingServiceImpl.java | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/wipro/fhir/service/ndhm/LinkCareContext_NDHMServiceImpl.java b/src/main/java/com/wipro/fhir/service/ndhm/LinkCareContext_NDHMServiceImpl.java index 86ceeec..f20f083 100644 --- a/src/main/java/com/wipro/fhir/service/ndhm/LinkCareContext_NDHMServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/ndhm/LinkCareContext_NDHMServiceImpl.java @@ -119,6 +119,7 @@ public String generateOTPForCareContext(String request) throws FHIRException { HttpHeaders headers = common_NDHMService.getHeaders(ndhmAuthToken, abhaMode); ResponseEntity responseEntity = httpUtils.postWithResponseEntity(generateOTPForCareContext, requestOBJ, headers); + logger.info("NDHM_FHIR Carecontext generateOTP API response - " + responseEntity); String responseStrLogin = common_NDHMService.getStatusCode(responseEntity); String numericStatusCodeStr = responseStrLogin.split(" ")[0]; // Extracts "202" from "202 ACCEPTED" int numericStatusCode = Integer.parseInt(numericStatusCodeStr); diff --git a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java index d8a6382..c899bae 100644 --- a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java @@ -85,6 +85,7 @@ public String generateTokenForCareContext(String request) throws FHIRException { String linkToken = null; Map responseMap = new HashMap<>(); RestTemplate restTemplate = new RestTemplate(); + String linkExists = null; try { String abhaAuthToken = generateAuthSessionService.getAbhaAuthToken(); @@ -92,7 +93,9 @@ public String generateTokenForCareContext(String request) throws FHIRException { CareContextLinkTokenRequest.class); if (null != careContextLinkRequest.getAbhaAddress()) { - String linkExists = checkRecordExisits(careContextLinkRequest.getAbhaAddress()); + linkExists = checkRecordExisits(careContextLinkRequest.getAbhaAddress()); + } + if(linkExists != null) { responseMap.put("linkToken", linkExists); } else { From 765d2605e241fb5b3a44728c4777e5ae99dfc2f3 Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Tue, 16 Dec 2025 01:01:21 +0530 Subject: [PATCH 18/30] small correction in hiType and error message modification --- .../CareContextLinkingServiceImpl.java | 80 ++++++++++++------- 1 file changed, 53 insertions(+), 27 deletions(-) diff --git a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java index c899bae..c0f1553 100644 --- a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java @@ -189,7 +189,8 @@ public String generateTokenForCareContext(String request) throws FHIRException { } @Override - public String linkCareContext(String request) throws FHIRException { String linkToken = null; + public String linkCareContext(String request) throws FHIRException { + String linkToken = null; Map responseMap = new HashMap<>(); RestTemplate restTemplate = new RestTemplate(); @@ -212,26 +213,26 @@ public String generateTokenForCareContext(String request) throws FHIRException { JsonObject jsonObject = jsonElement.getAsJsonObject(); try { - JsonElement linkTokenElement = jsonObject.get("LinkToken"); - if (linkTokenElement != null && !linkTokenElement.isJsonNull()) { + JsonElement linkTokenElement = jsonObject.get("LinkToken"); + if (linkTokenElement != null && !linkTokenElement.isJsonNull()) { linkToken = linkTokenElement.getAsString(); headers.add("X-LINK-TOKEN", linkToken); - } else { - if (jsonObject.has("Error") && !jsonObject.get("Error").isJsonNull()) { - JsonObject errorObject = jsonObject.getAsJsonObject("Error"); - responseMap.put("error", errorObject.toString()); - } else { - responseMap.put("error", "Unknown error"); - } - } + } else { + if (jsonObject.has("Error") && !jsonObject.get("Error").isJsonNull()) { + JsonObject errorObject = jsonObject.getAsJsonObject("Error"); + responseMap.put("error", errorObject.toString()); + } else { + responseMap.put("error", "Unknown error"); + } + } } catch (Exception e) { throw new FHIRException("ABDM_FHIR Error while parsing response: " + e.getMessage()); } } } - - if (linkToken != null) { + + if (linkToken != null) { headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); headers.add("REQUEST-ID", UUID.randomUUID().toString()); @@ -249,9 +250,10 @@ public String generateTokenForCareContext(String request) throws FHIRException { } else { headers.add("X-HIP-ID", abdmFacilityId); } - - String[] hiTypes = findHiTypes(addCareContextRequest.getVisitCode(), addCareContextRequest.getVisitCategory()); - + + String[] hiTypes = findHiTypes(addCareContextRequest.getVisitCode(), + addCareContextRequest.getVisitCategory()); + LinkCareContextRequest linkCareContextRequest = new LinkCareContextRequest(); CareContexts careContexts = new CareContexts(); ArrayList pcc = new ArrayList(); @@ -265,13 +267,13 @@ public String generateTokenForCareContext(String request) throws FHIRException { cc.add(careContexts); patient.setReferenceNumber(addCareContextRequest.getVisitCode()); - patient.setDisplay(addCareContextRequest.getVisitCategory() + " care context of " + addCareContextRequest.getAbhaNumber()); + patient.setDisplay(hiType + " care context of " + + addCareContextRequest.getAbhaNumber()); patient.setCount(1); patient.setCareContexts(cc); patient.setHiType(hiType); pcc.add(patient); } - if (null != addCareContextRequest.getAbhaNumber() && "" != addCareContextRequest.getAbhaNumber()) { String abha = addCareContextRequest.getAbhaNumber(); @@ -283,7 +285,7 @@ public String generateTokenForCareContext(String request) throws FHIRException { linkCareContextRequest.setPatient(pcc); String requestOBJ = new Gson().toJson(linkCareContextRequest); - logger.info("ABDM reqobj for generate token link for carecontext : " + requestOBJ); + logger.info("ABDM reqobj for link for carecontext : " + requestOBJ); HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); ResponseEntity responseEntity = restTemplate.exchange(linkCareContext, HttpMethod.POST, @@ -296,16 +298,40 @@ public String generateTokenForCareContext(String request) throws FHIRException { } else { JsonObject json = JsonParser.parseString(responseEntity.getBody()).getAsJsonObject(); - if (json.has("error")) { - JsonObject errorObj = json.getAsJsonObject("error"); - String message = errorObj.has("message") ? errorObj.get("message").getAsString() : "Unknown error"; - responseMap.put("error", message); - } else { - responseMap.put("error", "Unknown error"); - } + if (json.has("error")) { + JsonObject errorObj = json.getAsJsonObject("error"); + String message = errorObj.has("message") ? errorObj.get("message").getAsString() + : "Unknown error"; + responseMap.put("error", message); + } else { + responseMap.put("error", "Unknown error"); + } } } } catch (Exception e) { + String msg = e.getMessage(); + String jsonString = null; + int start = msg.indexOf("{"); + int end = msg.lastIndexOf("}"); + + if (start != -1 && end != -1) { + jsonString = msg.substring(start, end + 1); + } + + if (jsonString != null) { + try { + JsonObject json = JsonParser.parseString(jsonString).getAsJsonObject(); + if (json.has("error")) { + JsonObject errorObj = json.getAsJsonObject("error"); + String message = errorObj.has("message") ? errorObj.get("message").getAsString() + : "Unknown error"; + throw new FHIRException(message); + } + } catch (Exception ex) { + throw new FHIRException("Error parsing API error response"); + } + } + throw new FHIRException(e.getMessage()); } @@ -364,7 +390,7 @@ public String[] findHiTypes(String visitCode, String visitCategory) { int hasLabTests = careContextRepo.hasLabtestsDone(visitCode); if (hasLabTests > 0) { - hiTypes.add("DiagnoticsReport"); + hiTypes.add("DiagnoticReport"); } int hasVaccineDetails = careContextRepo.hasVaccineDetails(visitCode); From fec60643f8d9bc8f8c3204bd6a0b33e6191a71c5 Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Tue, 16 Dec 2025 02:22:38 +0530 Subject: [PATCH 19/30] modified error message --- .../CareContextLinkingServiceImpl.java | 24 +++++++------------ 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java index c0f1553..a1a8f7a 100644 --- a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java @@ -267,8 +267,7 @@ public String linkCareContext(String request) throws FHIRException { cc.add(careContexts); patient.setReferenceNumber(addCareContextRequest.getVisitCode()); - patient.setDisplay(hiType + " care context of " - + addCareContextRequest.getAbhaNumber()); + patient.setDisplay(hiType + " care context of " + addCareContextRequest.getAbhaNumber()); patient.setCount(1); patient.setCareContexts(cc); patient.setHiType(hiType); @@ -319,20 +318,15 @@ public String linkCareContext(String request) throws FHIRException { } if (jsonString != null) { - try { - JsonObject json = JsonParser.parseString(jsonString).getAsJsonObject(); - if (json.has("error")) { - JsonObject errorObj = json.getAsJsonObject("error"); - String message = errorObj.has("message") ? errorObj.get("message").getAsString() - : "Unknown error"; - throw new FHIRException(message); - } - } catch (Exception ex) { - throw new FHIRException("Error parsing API error response"); + JsonObject json = JsonParser.parseString(jsonString).getAsJsonObject(); + if (json.has("error")) { + JsonObject errorObj = json.getAsJsonObject("error"); + String message = errorObj.has("message") ? errorObj.get("message").getAsString() : "Unknown error"; + throw new FHIRException(message); } - } - throw new FHIRException(e.getMessage()); + throw new FHIRException(e.getMessage()); + } } return new Gson().toJson(responseMap); @@ -390,7 +384,7 @@ public String[] findHiTypes(String visitCode, String visitCategory) { int hasLabTests = careContextRepo.hasLabtestsDone(visitCode); if (hasLabTests > 0) { - hiTypes.add("DiagnoticReport"); + hiTypes.add("DiagnosticReport"); } int hasVaccineDetails = careContextRepo.hasVaccineDetails(visitCode); From 7a215825af294307a959968b06c471a8f0eca2bf Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Tue, 23 Dec 2025 00:42:41 +0530 Subject: [PATCH 20/30] feat: new standard FHIR bundles creation --- pom.xml | 52 +- src/main/environment/common_ci.properties | 2 + src/main/environment/common_dev.properties | 2 + src/main/environment/common_docker.properties | 4 +- .../environment/common_example.properties | 4 +- src/main/environment/common_test.properties | 2 + .../ResourceRequestGateway.java | 18 +- .../com/wipro/fhir/controller/test/Test.java | 8 +- .../resource_model/ImmunizationDataModel.java | 59 +++ .../MedicalHistoryDataModel.java | 61 +++ .../resource_model/OrganizationDataModel.java | 77 +++ .../resource_model/PractitionerDataModel.java | 67 +++ ...atientEligibleForResourceCreationRepo.java | 16 + .../bundle_creation/BundleValidator.java | 59 +++ .../DiagnosticRecordResourceBundle.java | 27 ++ .../DiagnosticRecordResourceBundleImpl.java | 253 ++++++++++ .../DischargeSummaryResourceBundle.java | 36 ++ .../DischargeSummaryResourceBundleImpl.java | 444 ++++++++++++++++++ .../ImmunizationRecordResourceBundle.java | 26 + .../ImmunizationRecordResourceBundleImpl.java | 236 ++++++++++ .../OPConsultResourceBundle.java | 31 ++ .../OPConsultResourceBundleImpl.java | 340 ++++++++++++++ .../PrescriptionResourceBundle.java | 27 ++ .../PrescriptionResourceBundleImpl.java | 228 +++++++++ .../WellnessRecordResourceBundle.java | 27 ++ .../WellnessRecordResourceBundleImpl.java | 257 ++++++++++ .../service/common/CommonServiceImpl.java | 100 +++- .../DiagnosticReportRecord.java | 36 -- .../DiagnosticReportRecordImpl.java | 260 ---------- .../OPConsultRecordBundle.java | 41 -- .../OPConsultRecordBundleImpl.java | 297 ------------ .../PrescriptionRecordBundle.java | 34 -- .../PrescriptionRecordBundleImpl.java | 238 ---------- .../DiagnosticReportResource.java | 1 - .../resource_model/EncounterResource.java | 10 +- .../resource_model/ImmunizationResource.java | 103 ++++ .../MedicalHistoryResource.java | 73 +++ .../MedicationRequestResource.java | 7 +- .../resource_model/ObservationResource.java | 3 +- .../resource_model/OrganizationResource.java | 128 ++--- .../resource_model/PatientResource.java | 1 - .../resource_model/PractitionerResource.java | 142 ++++-- 42 files changed, 2780 insertions(+), 1057 deletions(-) create mode 100644 src/main/java/com/wipro/fhir/data/resource_model/ImmunizationDataModel.java create mode 100644 src/main/java/com/wipro/fhir/data/resource_model/MedicalHistoryDataModel.java create mode 100644 src/main/java/com/wipro/fhir/data/resource_model/OrganizationDataModel.java create mode 100644 src/main/java/com/wipro/fhir/data/resource_model/PractitionerDataModel.java create mode 100644 src/main/java/com/wipro/fhir/service/bundle_creation/BundleValidator.java create mode 100644 src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundle.java create mode 100644 src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundleImpl.java create mode 100644 src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundle.java create mode 100644 src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundleImpl.java create mode 100644 src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundle.java create mode 100644 src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundleImpl.java create mode 100644 src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundle.java create mode 100644 src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundleImpl.java create mode 100644 src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundle.java create mode 100644 src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundleImpl.java create mode 100644 src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundle.java create mode 100644 src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundleImpl.java delete mode 100644 src/main/java/com/wipro/fhir/service/resource_gateway/DiagnosticReportRecord.java delete mode 100644 src/main/java/com/wipro/fhir/service/resource_gateway/DiagnosticReportRecordImpl.java delete mode 100644 src/main/java/com/wipro/fhir/service/resource_gateway/OPConsultRecordBundle.java delete mode 100644 src/main/java/com/wipro/fhir/service/resource_gateway/OPConsultRecordBundleImpl.java delete mode 100644 src/main/java/com/wipro/fhir/service/resource_gateway/PrescriptionRecordBundle.java delete mode 100644 src/main/java/com/wipro/fhir/service/resource_gateway/PrescriptionRecordBundleImpl.java create mode 100644 src/main/java/com/wipro/fhir/service/resource_model/ImmunizationResource.java create mode 100644 src/main/java/com/wipro/fhir/service/resource_model/MedicalHistoryResource.java diff --git a/pom.xml b/pom.xml index e42a83c..efa87c1 100644 --- a/pom.xml +++ b/pom.xml @@ -186,39 +186,74 @@ com.fasterxml.jackson.core jackson-core - 2.14.2 + 2.15.2 com.fasterxml.jackson.core jackson-databind - 2.14.2 + 2.15.2 com.fasterxml.jackson.core jackson-annotations - 2.14.2 + 2.15.2 - + ca.uhn.hapi.fhir hapi-fhir-structures-r4 - 6.10.0 + 8.4.0 - + + + + ca.uhn.hapi.fhir + hapi-fhir-validation + 8.4.0 + + + + + ca.uhn.hapi.fhir + hapi-fhir-structures-r4 + 8.4.0 + + + + + + ca.uhn.hapi.fhir + hapi-fhir-caching-caffeine + 8.4.0 + + + ca.uhn.hapi hapi-base 2.6.0 - + ca.uhn.hapi.fhir org.hl7.fhir.utilities 6.5.18 + + + ca.uhn.hapi.fhir + hapi-fhir-validation-resources-r4 + 8.4.0 + + org.projectlombok @@ -363,7 +398,8 @@ ${target-properties} and ${source-properties} - diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index 75945e9..9c9f1fa 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -124,3 +124,5 @@ springdoc.swagger-ui.enabled=@env.SWAGGER_DOC_ENABLED@ spring.redis.host=@env.REDIS_HOST@ cors.allowed-origins=@env.CORS_ALLOWED_ORIGINS@ + +systemUrl= @env.hipSystemUrl diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index e2c39d1..14c0ebb 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -105,3 +105,5 @@ logging.level.org.springframework.web=INFO logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO + +systemUrl= \ No newline at end of file diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index 82239d6..e14836e 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -117,4 +117,6 @@ springdoc.api-docs.enabled=${SWAGGER_DOC_ENABLED} springdoc.swagger-ui.enabled=${SWAGGER_DOC_ENABLED} # Redis IP -spring.redis.host=${REDIS_HOST} \ No newline at end of file +spring.redis.host=${REDIS_HOST} + +systemUrl= \ No newline at end of file diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index 36cfb14..ba3bf8b 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -117,4 +117,6 @@ jwt.secret=my-32-character-ultra-secure-and-ultra-long-secret logging.path=logs/ logging.file.name=logs/fhir-api.log -cors.allowed-origins=http://localhost:* \ No newline at end of file +cors.allowed-origins=http://localhost:* + +systemUrl= \ No newline at end of file diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties index e2c39d1..400971e 100644 --- a/src/main/environment/common_test.properties +++ b/src/main/environment/common_test.properties @@ -105,3 +105,5 @@ logging.level.org.springframework.web=INFO logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO + +systemUrl= diff --git a/src/main/java/com/wipro/fhir/controller/generateresource/ResourceRequestGateway.java b/src/main/java/com/wipro/fhir/controller/generateresource/ResourceRequestGateway.java index 78ba1a5..e293ac7 100644 --- a/src/main/java/com/wipro/fhir/controller/generateresource/ResourceRequestGateway.java +++ b/src/main/java/com/wipro/fhir/controller/generateresource/ResourceRequestGateway.java @@ -33,9 +33,9 @@ import org.springframework.web.bind.annotation.RestController; import com.wipro.fhir.data.request_handler.ResourceRequestHandler; -import com.wipro.fhir.service.resource_gateway.DiagnosticReportRecord; -import com.wipro.fhir.service.resource_gateway.OPConsultRecordBundle; -import com.wipro.fhir.service.resource_gateway.PrescriptionRecordBundle; +import com.wipro.fhir.service.bundle_creation.DiagnosticRecordResourceBundle; +import com.wipro.fhir.service.bundle_creation.OPConsultResourceBundle; +import com.wipro.fhir.service.bundle_creation.PrescriptionResourceBundle; import com.wipro.fhir.utils.exception.FHIRException; import com.wipro.fhir.utils.response.OutputResponse; @@ -55,11 +55,11 @@ public class ResourceRequestGateway { private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); @Autowired - private OPConsultRecordBundle opConsultRecordBundle; + private OPConsultResourceBundle opConsultRecordBundle; @Autowired - private PrescriptionRecordBundle prescriptionRecordBundle; + private PrescriptionResourceBundle prescriptionRecordBundle; @Autowired - private DiagnosticReportRecord diagnosticReportRecord; + private DiagnosticRecordResourceBundle diagnosticReportRecord; /*** * @@ -78,7 +78,7 @@ public String getPatientResource(@RequestBody ResourceRequestHandler patientReso OutputResponse response = new OutputResponse(); try { - String s = opConsultRecordBundle.getOPConsultRecordBundle(patientResourceRequest, null); + String s = opConsultRecordBundle.PopulateOPConsultRecordResourceBundle(patientResourceRequest, null); response.setResponse(s); } catch (FHIRException e) { @@ -104,7 +104,7 @@ public String getDiagnosticReportRecord(@RequestBody ResourceRequestHandler pati OutputResponse response = new OutputResponse(); try { - String s = diagnosticReportRecord.getDiagnosticReportRecordBundle(patientResourceRequest, null); + String s = diagnosticReportRecord.PopulateDiagnosticReportResourceBundle(patientResourceRequest, null); response.setResponse(s); } catch (FHIRException e) { @@ -129,7 +129,7 @@ public String getPrescriptionRecord(@RequestBody ResourceRequestHandler patientR OutputResponse response = new OutputResponse(); try { - String s = prescriptionRecordBundle.getPrescriptionRecordBundle(patientResourceRequest, null); + String s = prescriptionRecordBundle.PopulatePrescriptionResourceBundle(patientResourceRequest, null); response.setResponse(s); } catch (FHIRException e) { diff --git a/src/main/java/com/wipro/fhir/controller/test/Test.java b/src/main/java/com/wipro/fhir/controller/test/Test.java index 719047c..8be0743 100644 --- a/src/main/java/com/wipro/fhir/controller/test/Test.java +++ b/src/main/java/com/wipro/fhir/controller/test/Test.java @@ -34,9 +34,7 @@ import com.wipro.fhir.data.request_handler.ResourceRequestHandler; import com.wipro.fhir.service.atoms.feed.bahmni.ClinicalFeedWorker; -import com.wipro.fhir.service.resource_gateway.OPConsultRecordBundle; -import com.wipro.fhir.service.resource_gateway.OPConsultRecordBundleImpl; -import com.wipro.fhir.service.resource_gateway.PrescriptionRecordBundleImpl; +import com.wipro.fhir.service.bundle_creation.OPConsultResourceBundleImpl; import com.wipro.fhir.utils.http.HttpUtils; import com.wipro.fhir.utils.response.OutputResponse; @@ -50,7 +48,7 @@ public class Test { private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); @Autowired - private OPConsultRecordBundleImpl oPConsultRecordBundleImpl; + private OPConsultResourceBundleImpl oPConsultRecordBundleImpl; @Operation(summary = "Test parse ATOM Feeds") @PostMapping(value = { "/parse/feed/ATOM" }) @@ -59,7 +57,7 @@ public String parseFeeds(@RequestBody ResourceRequestHandler resourceRequestHand OutputResponse response = new OutputResponse(); String s = null; try { - s = oPConsultRecordBundleImpl.getOPConsultRecordBundle(resourceRequestHandler, null); + s = oPConsultRecordBundleImpl.PopulateOPConsultRecordResourceBundle(resourceRequestHandler, null); response.setResponse(s); } catch (Exception e) { logger.error("Unexpected error:" , e); diff --git a/src/main/java/com/wipro/fhir/data/resource_model/ImmunizationDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/ImmunizationDataModel.java new file mode 100644 index 0000000..e82fcbd --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/resource_model/ImmunizationDataModel.java @@ -0,0 +1,59 @@ +package com.wipro.fhir.data.resource_model; + +import java.math.BigInteger; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; + +import org.springframework.stereotype.Component; + +import lombok.Data; + +@Data +@Component +public class ImmunizationDataModel { + + private BigInteger id; + private BigInteger beneficiaryRegID; + private BigInteger visitCode; + private Integer providerServiceMapID; + private Integer vanID; + private String defaultReceivingAge; + private String vaccineName; + private Timestamp receivedDate; + private String receivedFacilityName; + private String sctcode; + private String sctTerm; + private Timestamp createdDate; + private String createdBy; + + public ImmunizationDataModel() { + } + + public ImmunizationDataModel(Object[] objArr) { + this.id = objArr[0] != null ? BigInteger.valueOf(((Number) objArr[0]).longValue()) : null; + this.beneficiaryRegID = objArr[1] != null ? BigInteger.valueOf(((Number) objArr[1]).longValue()) : null; + this.visitCode = objArr[2] != null ? BigInteger.valueOf(((Number) objArr[2]).longValue()) : null; + this.providerServiceMapID = objArr[3] != null ? ((Number) objArr[3]).intValue() : null; + this.vanID = objArr[4] != null ? ((Number) objArr[4]).intValue() : null; + this.defaultReceivingAge = objArr[5] != null ? (String) objArr[5] : null; + this.vaccineName = objArr[6] != null ? (String) objArr[6] : null; + this.receivedDate = objArr[7] != null ? (Timestamp) objArr[7] : null; + this.receivedFacilityName = objArr[8] != null ? (String) objArr[8] : null; + this.sctcode = objArr[9] != null ? (String) objArr[9] : null; + this.sctTerm = objArr[10] != null ? (String) objArr[10] : null; + this.createdDate = objArr[11] != null ? (Timestamp) objArr[11] : null; + this.createdBy = objArr[12] != null ? (String) objArr[12] : null; + } + + public List getImmunizationList(List resultSetList) { + List out = new ArrayList<>(); + if (resultSetList != null && !resultSetList.isEmpty()) { + for (Object[] objArr : resultSetList) { + out.add(new ImmunizationDataModel(objArr)); + } + } + return out; + } + +} diff --git a/src/main/java/com/wipro/fhir/data/resource_model/MedicalHistoryDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/MedicalHistoryDataModel.java new file mode 100644 index 0000000..5e88320 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/resource_model/MedicalHistoryDataModel.java @@ -0,0 +1,61 @@ +package com.wipro.fhir.data.resource_model; + +import java.io.Serializable; +import java.math.BigInteger; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; + +import org.springframework.stereotype.Component; + +import lombok.Data; + + +@Data +@Component +public class MedicalHistoryDataModel implements Serializable { + + private static final long serialVersionUID = 1L; + + + private BigInteger id; + private BigInteger beneficiaryRegID; + private BigInteger visitCode; + private String currentMedication; + private Integer currentMedYear; + private String yearOfIllness; + private String finalIllnessType; + private String yearOfSurgery; + private String finalSurgeryType; + private Timestamp createdDate; + private String createdBy; + public MedicalHistoryDataModel() { + } + + public MedicalHistoryDataModel(Object[] objArr) { + this.id = objArr[0] != null ? BigInteger.valueOf(((Number) objArr[0]).longValue()) : null; + this.beneficiaryRegID = objArr[1] != null ? BigInteger.valueOf(((Number) objArr[1]).longValue()) : null; + this.visitCode = objArr[2] != null ? BigInteger.valueOf(((Number) objArr[2]).longValue()) : null; + this.currentMedication = objArr[3] != null ? (String) objArr[3] : null; + this.currentMedYear = objArr[4] != null ? (Integer) objArr[4] : null; + this.yearOfIllness = objArr[5] != null ? (String) objArr[5] : null; + this.finalIllnessType = objArr[6] != null ? (String) objArr[6] : null; + this.yearOfSurgery = objArr[7] != null ? (String) objArr[7] : null; + this.finalSurgeryType = objArr[8] != null ? (String) objArr[8] : null; + this.createdDate = objArr[9] != null ? (Timestamp) objArr[9] : null; + this.createdBy = objArr[10] != null ? (String) objArr[10] : null; + } + + public List getMedicalList(List resultSetList) { + MedicalHistoryDataModel medHistoryObj; + List medHistoryList = new ArrayList(); + if (resultSetList != null && resultSetList.size() > 0) { + for (Object[] objArr : resultSetList) { + medHistoryObj = new MedicalHistoryDataModel(objArr); + medHistoryList.add(medHistoryObj); + } + } + return medHistoryList; + } + +} diff --git a/src/main/java/com/wipro/fhir/data/resource_model/OrganizationDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/OrganizationDataModel.java new file mode 100644 index 0000000..43fc076 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/resource_model/OrganizationDataModel.java @@ -0,0 +1,77 @@ +package com.wipro.fhir.data.resource_model; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.stereotype.Component; + +import lombok.Data; + +@Component +@Data +public class OrganizationDataModel { + + private Long benVisitID; + private Short serviceProviderID; + private String serviceProviderName; + + private Integer stateID; + private String stateName; + + private Integer districtID; + private String districtName; + + private String locationName; + private String address; + + private Short serviceID; + private String serviceName; + + private Boolean isNational; + + private String abdmFacilityId; + private String abdmFacilityName; + + private Integer psAddMapID; + private Integer providerServiceMapID; + + public OrganizationDataModel() { + } + + public OrganizationDataModel(Object[] objArr) { + + this.benVisitID = objArr[0] != null ? (Long) objArr[0] : null; + this.serviceProviderID = objArr[1] != null ? (Short) objArr[1] : null; + this.serviceProviderName = objArr[2] != null ? (String) objArr[2] : null; + + this.stateID = objArr[3] != null ? (Integer) objArr[3] : null; + this.stateName = objArr[4] != null ? (String) objArr[4] : null; + + this.districtID = objArr[5] != null ? (Integer) objArr[5] : null; + this.districtName = objArr[6] != null ? (String) objArr[6] : null; + + this.locationName = objArr[7] != null ? (String) objArr[7] : null; + this.address = objArr[8] != null ? (String) objArr[8] : null; + + this.serviceID = objArr[9] != null ? (Short) objArr[9] : null; + this.serviceName = objArr[10] != null ? (String) objArr[10] : null; + + this.isNational = objArr[11] != null ? (Boolean) objArr[11] : null; + + this.abdmFacilityId = objArr[12] != null ? (String) objArr[12] : null; + this.abdmFacilityName = objArr[13] != null ? (String) objArr[13] : null; + + this.psAddMapID = objArr[14] != null ? (Integer) objArr[14] : null; + this.providerServiceMapID = objArr[15] != null ? (Integer) objArr[15] : null; + } + + + public OrganizationDataModel getOrganization(Object[] resultSet) { + + if (resultSet == null || resultSet.length == 0) { + return null; + } + + return new OrganizationDataModel(resultSet); + } +} diff --git a/src/main/java/com/wipro/fhir/data/resource_model/PractitionerDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/PractitionerDataModel.java new file mode 100644 index 0000000..6ccb20f --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/resource_model/PractitionerDataModel.java @@ -0,0 +1,67 @@ +package com.wipro.fhir.data.resource_model; + +import java.sql.Timestamp; +import java.util.Date; + +import org.springframework.stereotype.Component; + +import lombok.Data; + +@Data +@Component +public class PractitionerDataModel { + + private static final long serialVersionUID = 1L; + + private Integer benVisitID; + private Integer userID; + private String fullName; + private Date dob; + + private String employeeID; + private String contactNo; + private String emailID; + + private String qualificationName; + private String designationName; + + private String genderName; + private Integer genderID; + + private Integer serviceProviderID; + private Long visitCode; + + private String createdBy; + private Timestamp createdDate; + + public PractitionerDataModel() { + } + + public PractitionerDataModel(Object[] objArr) { + + this.benVisitID = objArr[0] != null ? ((Number) objArr[0]).intValue() : null; + this.userID = objArr[1] != null ? ((Number) objArr[1]).intValue() : null; + this.fullName = (String) objArr[2]; + this.dob = (Date) objArr[3]; + this.employeeID = (String) objArr[4]; + this.contactNo = (String) objArr[5]; + this.emailID = (String) objArr[6]; + this.qualificationName = (String) objArr[7]; + this.designationName = (String) objArr[8]; + this.genderName = (String) objArr[9]; + this.genderID = objArr[10] != null ? ((Number) objArr[10]).intValue() : null; + this.serviceProviderID = objArr[11] != null ? ((Number) objArr[11]).intValue() : null; + this.visitCode = objArr[12] != null ? ((Number) objArr[12]).longValue() : null; + this.createdBy = (String) objArr[13]; + this.createdDate = (Timestamp) objArr[14]; + } + + + public PractitionerDataModel getPractitioner(Object[] resultSet) { + if (resultSet == null || resultSet.length == 0) { + return null; + } + return new PractitionerDataModel(resultSet); + } + +} diff --git a/src/main/java/com/wipro/fhir/repo/common/PatientEligibleForResourceCreationRepo.java b/src/main/java/com/wipro/fhir/repo/common/PatientEligibleForResourceCreationRepo.java index 931315a..69480a5 100644 --- a/src/main/java/com/wipro/fhir/repo/common/PatientEligibleForResourceCreationRepo.java +++ b/src/main/java/com/wipro/fhir/repo/common/PatientEligibleForResourceCreationRepo.java @@ -115,4 +115,20 @@ List callMedicationRequestSP(@Param("beneficiaryRegID_IN") BigInteger @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_PatientDemographic(:beneficiaryRegID_IN, " + " @0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12,@13, @14, @15, @16, @17 );") List callPatientDemographicSP(@Param("beneficiaryRegID_IN") BigInteger beneficiaryRegID_IN); + + //medicalHistory + @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_MedicalHistoryDetails(:visitCode_IN)") + List callMedicalHistorySp(@Param("visitCode_IN") BigInteger visitCode_IN); + + //Immunization record + @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_Immunization(:beneficiaryRegID_IN, :visitCode_IN, @0, " + + "@1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12)") + List callImmunizationSP(@Param("beneficiaryRegID_IN") BigInteger beneficiaryRegID_IN, @Param("visitCode_IN") BigInteger visitCode_IN); + + @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_OrganizationDetails(:visitCode_IN)") + List callOrganizationSp(@Param("visitCode_IN") BigInteger visitCode_IN); + + @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_Practitioner(:visitCode_IN)") + List callPractitionerSP(@Param("visitCode_IN") BigInteger visitCode_IN); + } diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/BundleValidator.java b/src/main/java/com/wipro/fhir/service/bundle_creation/BundleValidator.java new file mode 100644 index 0000000..64bf2f1 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/BundleValidator.java @@ -0,0 +1,59 @@ +package com.wipro.fhir.service.bundle_creation; + +import java.io.IOException; + +import org.hl7.fhir.common.hapi.validation.support.CommonCodeSystemsTerminologyService; +import org.hl7.fhir.common.hapi.validation.support.InMemoryTerminologyServerValidationSupport; +import org.hl7.fhir.common.hapi.validation.support.NpmPackageValidationSupport; +import org.hl7.fhir.common.hapi.validation.support.SnapshotGeneratingValidationSupport; +import org.hl7.fhir.common.hapi.validation.support.ValidationSupportChain; +import org.hl7.fhir.common.hapi.validation.validator.FhirInstanceValidator; + +import com.wipro.fhir.utils.exception.FHIRException; + +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.context.support.DefaultProfileValidationSupport; +import ca.uhn.fhir.validation.FhirValidator; +import ca.uhn.fhir.validation.SingleValidationMessage; +import ca.uhn.fhir.validation.ValidationResult; + +// This is a one time validator to validate fhir bundles +public class BundleValidator { + + static FhirContext ctx = FhirContext.forR4(); + + public static void main(String[] args) throws FHIRException { + try { + NpmPackageValidationSupport npmPackageValidationSupport = new NpmPackageValidationSupport(ctx); + npmPackageValidationSupport.loadPackageFromClasspath(" "); // download the package from ABDM and add in resources + + //create a validation support chain + ValidationSupportChain validationSupportChain = new ValidationSupportChain( + npmPackageValidationSupport, + new DefaultProfileValidationSupport(ctx), + new CommonCodeSystemsTerminologyService(ctx), + new InMemoryTerminologyServerValidationSupport(ctx), + new SnapshotGeneratingValidationSupport(ctx) + + ); + + FhirValidator validator = ctx.newValidator(); + FhirInstanceValidator instanceValidator = new FhirInstanceValidator(validationSupportChain); + validator.registerValidatorModule(instanceValidator); + + String bundleJson = ""; // add bundle json here + + ValidationResult outCome = validator.validateWithResult(bundleJson); + + for(SingleValidationMessage next : outCome.getMessages()) { + System.out.print("Error - " + next.getSeverity() + " - " + next.getLocationString() + " - " + next.getMessage()); + } + + } catch (IOException e) { + throw new FHIRException("Issue in validating the bundle - " + e.getMessage()); + } + + } + + +} diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundle.java b/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundle.java new file mode 100644 index 0000000..cad83be --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundle.java @@ -0,0 +1,27 @@ +package com.wipro.fhir.service.bundle_creation; + +import java.util.List; + +import org.hl7.fhir.r4.model.Composition; +import org.hl7.fhir.r4.model.DiagnosticReport; +import org.hl7.fhir.r4.model.Organization; +import org.hl7.fhir.r4.model.Practitioner; + +import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.utils.exception.FHIRException; + +public interface DiagnosticRecordResourceBundle { + + + int processDiagnosticReportRecordBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException; + + Composition PopulateDiagnosticReportComposition(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p, List diagnosticReports, Practitioner practitioner, + Organization organization); + + String PopulateDiagnosticReportResourceBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException; + +} diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundleImpl.java new file mode 100644 index 0000000..323f86d --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundleImpl.java @@ -0,0 +1,253 @@ +package com.wipro.fhir.service.bundle_creation; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import org.hl7.fhir.r4.model.Bundle; +import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent; +import org.hl7.fhir.r4.model.CodeableConcept; +import org.hl7.fhir.r4.model.Coding; +import org.hl7.fhir.r4.model.Composition; +import org.hl7.fhir.r4.model.DiagnosticReport; +import org.hl7.fhir.r4.model.Encounter; +import org.hl7.fhir.r4.model.Identifier; +import org.hl7.fhir.r4.model.Meta; +import org.hl7.fhir.r4.model.Observation; +import org.hl7.fhir.r4.model.Organization; +import org.hl7.fhir.r4.model.Patient; +import org.hl7.fhir.r4.model.Practitioner; +import org.hl7.fhir.r4.model.Reference; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import com.wipro.fhir.data.mongo.amrit_resource.AMRIT_ResourceMongo; +import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; +import com.wipro.fhir.service.common.CommonService; +import com.wipro.fhir.service.resource_model.DiagnosticReportResource; +import com.wipro.fhir.service.resource_model.ObservationResource; +import com.wipro.fhir.service.resource_model.OrganizationResource; +import com.wipro.fhir.service.resource_model.PatientResource; +import com.wipro.fhir.service.resource_model.PractitionerResource; +import com.wipro.fhir.utils.exception.FHIRException; + +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.parser.IParser; + +@Service +public class DiagnosticRecordResourceBundleImpl implements DiagnosticRecordResourceBundle { + + @Autowired + private PractitionerResource practitionerResource; + + @Autowired + private OrganizationResource organizationResource; + + @Autowired + private PatientResource patientResource; + + @Autowired + private ObservationResource observationResource; + + @Autowired + private DiagnosticReportResource diagnosticReportResource; + + @Autowired + private CommonService commonService; + + @Autowired + private BenHealthIDMappingRepo benHealthIDMappingRepo; + + @Value("${systemUrl}") + private String systemUrl; + + @Override + public int processDiagnosticReportRecordBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException { + int i = 0; + // call method to generate Prescription resource + String diagnosticReportRecordBundle = PopulateDiagnosticReportResourceBundle(resourceRequestHandler, p); + + // call private method to create mongo object with resource data + AMRIT_ResourceMongo aMRIT_ResourceMongo = createDiagnosticReportRecordBundleMongo(p, + diagnosticReportRecordBundle); + // if resource data is not null, save to mongo + if (aMRIT_ResourceMongo != null) { + i = commonService.saveResourceToMongo(aMRIT_ResourceMongo); + + } else + throw new FHIRException("TODO - exception - later will implement"); + + return i; + + } + + @Override + public String PopulateDiagnosticReportResourceBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException { + + Bundle diagReportBundle = new Bundle(); + String serializeBundle; + + try { + String id = resourceRequestHandler.getVisitCode() + ":" + commonService.getUUID(); + diagReportBundle.setId(id); + diagReportBundle.setType(Bundle.BundleType.DOCUMENT); + diagReportBundle.setTimestamp(new Timestamp(System.currentTimeMillis())); + + Meta meta = new Meta(); + meta.setVersionId("1"); + meta.setLastUpdated(new Timestamp(System.currentTimeMillis())); + meta.addProfile("https://nrces.in/ndhm/fhir/r4/StructureDefinition/DocumentBundle"); + meta.addSecurity(new Coding("http://terminology.hl7.org/CodeSystem/v3-Confidentiality", "R", "restricted")); + diagReportBundle.setMeta(meta); + + Identifier identifier = new Identifier(); + identifier.setSystem(systemUrl); + identifier.setValue(diagReportBundle.getId()); + diagReportBundle.setIdentifier(identifier); + + // practitioner resource + Practitioner practitioner = practitionerResource.getPractitionerResource(resourceRequestHandler); + + // Organization resource + Organization organization = organizationResource.getOrganizationResource(resourceRequestHandler); + + // Patient resource + Patient patient = patientResource.getPatientResource(resourceRequestHandler); + + // Observation- Physical Examination - vitals + Map> observationMap = observationResource.getObservationLab(patient, + resourceRequestHandler); + + // diagnostic report + List diagnosticResourceList = diagnosticReportResource.getDiagnosticReport(patient, + new Encounter(), resourceRequestHandler, observationMap); + + Composition composition = PopulateDiagnosticReportComposition(resourceRequestHandler, p, + diagnosticResourceList, practitioner, organization); + + List bundleEntries = new ArrayList<>(); + + BundleEntryComponent entryComposition = new BundleEntryComponent(); + entryComposition.setFullUrl(composition.getIdElement().getValue()); + entryComposition.setResource(composition); + bundleEntries.add(entryComposition); + + BundleEntryComponent entryPractitioner = new BundleEntryComponent(); + entryPractitioner.setFullUrl(practitioner.getIdElement().getValue()); + entryPractitioner.setResource(practitioner); + bundleEntries.add(entryPractitioner); + + BundleEntryComponent entryOrganization = new BundleEntryComponent(); + entryOrganization.setFullUrl(organization.getIdElement().getValue()); + entryOrganization.setResource(organization); + bundleEntries.add(entryOrganization); + + BundleEntryComponent entryPatient = new BundleEntryComponent(); + entryPatient.setFullUrl(patient.getIdElement().getValue()); + entryPatient.setResource(patient); + bundleEntries.add(entryPatient); + + + for (DiagnosticReport dr : diagnosticResourceList) { + BundleEntryComponent entryDR = new BundleEntryComponent(); + entryDR.setFullUrl(dr.getIdElement().getValue()); + entryDR.setResource(dr); + + bundleEntries.add(entryDR); + } + + + if (observationMap != null && !observationMap.isEmpty()) { + for (Map.Entry> e : observationMap.entrySet()) { + List obsList = e.getValue(); + if (obsList == null) + continue; + + for (Observation obs : obsList) { + BundleEntryComponent entryObs = new BundleEntryComponent(); + entryObs.setFullUrl(obs.getIdElement().getValue()); + entryObs.setResource(obs); + bundleEntries.add(entryObs); + } + } + } + + diagReportBundle.setEntry(bundleEntries); + + FhirContext ctx = FhirContext.forR4(); + IParser parser = ctx.newJsonParser(); + serializeBundle = parser.encodeResourceToString(diagReportBundle); + + } catch (Exception e) { + throw new FHIRException("Diagnostic Report FHIR Resource Bundle failed with error - " + e); + } + + return serializeBundle; + } + + @Override + public Composition PopulateDiagnosticReportComposition(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p, List diagnosticReports, Practitioner practitioner, Organization organization) { + + Composition composition = new Composition(); + composition.setId("Composition/" + commonService.getUUID()); + + Meta meta = new Meta(); + meta.setVersionId("1"); + meta.addProfile("https://nrces.in/ndhm/fhir/r4/StructureDefinition/DiagnosticReportRecord"); + composition.setMeta(meta); + + composition.setStatus(Composition.CompositionStatus.FINAL); + + composition.setType(new CodeableConcept() + .addCoding(new Coding("http://snomed.info/sct", "721981007", "Diagnostic studies report"))); + + composition.setSubject(new Reference("Patient/" + p.getBeneficiaryId().toString())); + composition.setDate(new Date()); + composition.addAuthor(new Reference(practitioner.getIdElement().getValue())); + composition.setCustodian(new Reference(organization.getIdElement().getValue())); + composition.setTitle("Diagnostic Report Record"); + + Composition.SectionComponent section = new Composition.SectionComponent(); + + section.setCode(new CodeableConcept() + .addCoding(new Coding("http://snomed.info/sct", "721981007", "Diagnostic studies report"))); + + for (DiagnosticReport dr : diagnosticReports) { + Reference drRef = new Reference(dr.getIdElement().getValue()); + drRef.setType("DiagnosticReport"); + section.addEntry(drRef); + } + + composition.addSection(section); + return composition; + } + + private AMRIT_ResourceMongo createDiagnosticReportRecordBundleMongo(PatientEligibleForResourceCreation p, + String diagnosticReportRecordBundle) { + AMRIT_ResourceMongo aMRIT_ResourceMongo = new AMRIT_ResourceMongo(); + aMRIT_ResourceMongo.setBeneficiaryID(p.getBeneficiaryId()); + aMRIT_ResourceMongo.setBeneficiaryRegID(p.getBeneficiaryRegID()); + // get ABHA from table "m_benhealthmapping" for this visit(visit code) + if (p.getVisitCode() != null) { + aMRIT_ResourceMongo.setVisitCode(p.getVisitCode()); + List objArrResultSet = benHealthIDMappingRepo.getLinkedHealthIDForVisit(p.getVisitCode()); + if (objArrResultSet != null && objArrResultSet.size() > 0) { + aMRIT_ResourceMongo.setNationalHealthID(objArrResultSet.get(0)); + } + } + + aMRIT_ResourceMongo.setResourceJson(diagnosticReportRecordBundle); + aMRIT_ResourceMongo.setResourceType("DiagnosticReport"); + + return aMRIT_ResourceMongo; + } + +} diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundle.java b/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundle.java new file mode 100644 index 0000000..d793108 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundle.java @@ -0,0 +1,36 @@ +package com.wipro.fhir.service.bundle_creation; + +import java.util.List; + +import org.hl7.fhir.r4.model.AllergyIntolerance; +import org.hl7.fhir.r4.model.Composition; +import org.hl7.fhir.r4.model.Condition; +import org.hl7.fhir.r4.model.DiagnosticReport; +import org.hl7.fhir.r4.model.Encounter; +import org.hl7.fhir.r4.model.FamilyMemberHistory; +import org.hl7.fhir.r4.model.MedicationRequest; +import org.hl7.fhir.r4.model.MedicationStatement; +import org.hl7.fhir.r4.model.Organization; +import org.hl7.fhir.r4.model.Patient; +import org.hl7.fhir.r4.model.Practitioner; + +import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.utils.exception.FHIRException; + +public interface DischargeSummaryResourceBundle { + + int processDischargeSummaryRecordBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException; + + Composition PopulateDischargeSummaryComposition(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p, Practitioner practitioner, Organization organization, Patient patient, + Encounter encounter, List chiefComplaints, List physicalExam, + List allergyList, FamilyMemberHistory familyMemberHistory, + List pastMedicalHistoryConditions, List medicationRequests, + List procedures); + + String PopulateDischargeSummaryResourceBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException; + +} diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundleImpl.java new file mode 100644 index 0000000..a088849 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundleImpl.java @@ -0,0 +1,444 @@ +package com.wipro.fhir.service.bundle_creation; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import org.hl7.fhir.r4.model.AllergyIntolerance; +import org.hl7.fhir.r4.model.Bundle; +import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent; +import org.hl7.fhir.r4.model.Bundle.BundleType; +import org.hl7.fhir.r4.model.CodeableConcept; +import org.hl7.fhir.r4.model.Coding; +import org.hl7.fhir.r4.model.Composition; +import org.hl7.fhir.r4.model.Composition.CompositionStatus; +import org.hl7.fhir.r4.model.Composition.SectionComponent; +import org.hl7.fhir.r4.model.Condition; +import org.hl7.fhir.r4.model.DiagnosticReport; +import org.hl7.fhir.r4.model.Encounter; +import org.hl7.fhir.r4.model.FamilyMemberHistory; +import org.hl7.fhir.r4.model.Identifier; +import org.hl7.fhir.r4.model.MedicationRequest; +import org.hl7.fhir.r4.model.MedicationStatement; +import org.hl7.fhir.r4.model.Meta; +import org.hl7.fhir.r4.model.Observation; +import org.hl7.fhir.r4.model.Organization; +import org.hl7.fhir.r4.model.Patient; +import org.hl7.fhir.r4.model.Practitioner; +import org.hl7.fhir.r4.model.Reference; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import com.wipro.fhir.data.mongo.amrit_resource.AMRIT_ResourceMongo; +import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; +import com.wipro.fhir.service.common.CommonService; +import com.wipro.fhir.service.resource_model.AllergyIntoleranceResource; +import com.wipro.fhir.service.resource_model.ConditionResource; +import com.wipro.fhir.service.resource_model.DiagnosticReportResource; +import com.wipro.fhir.service.resource_model.EncounterResource; +import com.wipro.fhir.service.resource_model.FamilyMemberHistoryResource; +import com.wipro.fhir.service.resource_model.MedicalHistoryResource; +import com.wipro.fhir.service.resource_model.MedicationRequestResource; +import com.wipro.fhir.service.resource_model.ObservationResource; +import com.wipro.fhir.service.resource_model.OrganizationResource; +import com.wipro.fhir.service.resource_model.PatientResource; +import com.wipro.fhir.service.resource_model.PractitionerResource; +import com.wipro.fhir.utils.exception.FHIRException; + +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.parser.IParser; + +@Service +public class DischargeSummaryResourceBundleImpl implements DischargeSummaryResourceBundle { + + @Autowired + private CommonService commonService; + + @Autowired + private PractitionerResource practitionerResource; + + @Autowired + private OrganizationResource organizationResource; + + @Autowired + private PatientResource patientResource; + + @Autowired + private ConditionResource conditionResource; + + @Autowired + private EncounterResource encounterResource; + + @Autowired + private AllergyIntoleranceResource allergyIntoleranceResource; + + @Autowired + private FamilyMemberHistoryResource familyMemberHistoryResource; + + @Autowired + private MedicalHistoryResource medicalHistoryResource; + + @Autowired + private ObservationResource observationResource; + + @Autowired + private DiagnosticReportResource diagnosticReportResource; + + @Autowired + private MedicationRequestResource medicationRequestResource; + + @Autowired + private BenHealthIDMappingRepo benHealthIDMappingRepo; + + @Value("${systemUrl}") + private String systemUrl; + + @Override + public int processDischargeSummaryRecordBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException { + int i = 0; + // call method to generate Prescription resource + String dischargeSummaryBundle = PopulateDischargeSummaryResourceBundle(resourceRequestHandler, p); + + // call private method to create mongo object with resource data + AMRIT_ResourceMongo aMRIT_ResourceMongo = createDischargeSummaryBundleMongo(p, + dischargeSummaryBundle); + // if resource data is not null, save to mongo + if (aMRIT_ResourceMongo != null) { + i = commonService.saveResourceToMongo(aMRIT_ResourceMongo); + + } else + throw new FHIRException("Issue in processing the bundle"); + + return i; + + } + + + @Override + public String PopulateDischargeSummaryResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException { + + Bundle dischargeSummaryBundle = new Bundle(); + String serializeBundle = null; + + + try { + String id = resourceRequestHandler.getVisitCode()+ ":" + commonService.getUUID(); + dischargeSummaryBundle.setId(id); + dischargeSummaryBundle.setType(BundleType.DOCUMENT); + dischargeSummaryBundle.setTimestamp(new Timestamp(System.currentTimeMillis())); + + Meta meta = new Meta(); + meta.setVersionId("1"); + meta.setLastUpdated(new Timestamp(System.currentTimeMillis())); + meta.addProfile("https://nrces.in/ndhm/fhir/r4/StructureDefinition/DocumentBundle"); + meta.addSecurity(new Coding("http://terminology.hl7.org/CodeSystem/v3-Confidentiality", "restricted", "R")); + dischargeSummaryBundle.setMeta(meta); + + Identifier identifier = new Identifier(); + identifier.setSystem(systemUrl); + identifier.setValue(dischargeSummaryBundle.getId()); + dischargeSummaryBundle.setIdentifier(identifier); + + // practitioner + Practitioner practitioner = practitionerResource.getPractitionerResource(resourceRequestHandler); + // organization + Organization organization = organizationResource.getOrganizationResource(resourceRequestHandler); + // Patient Resource + Patient patient = patientResource.getPatientResource(resourceRequestHandler); + + //Chief complaints + List conditionListChiefComplaints = conditionResource.getCondition(patient, resourceRequestHandler, + "chiefcomplaints"); + + // diagnosis + List conditionListDiagnosis = conditionResource.getCondition(patient, resourceRequestHandler, + "diagnosis"); + + Encounter encounter = encounterResource.getEncounterResource(patient, resourceRequestHandler, + conditionListChiefComplaints, conditionListDiagnosis); + + // AllergyIntolerance resource + List allergyList = allergyIntoleranceResource.getAllergyIntolerance(patient, encounter, + resourceRequestHandler, practitioner); + + // FamilyMemberHistory resource + FamilyMemberHistory familyMemberHistory = familyMemberHistoryResource.getFamilyMemberHistory(patient, + resourceRequestHandler); + + List medicationStatement = medicalHistoryResource.getMedicalHistory(patient, resourceRequestHandler); + + // Medication request + List medicationRequest = medicationRequestResource.getMedicationRequest(patient, + resourceRequestHandler, practitioner, null); + + // Observation- Physical Examination + Map> observationMap = observationResource.getObservationLab(patient, + resourceRequestHandler); + + List diagnosticResourceList = diagnosticReportResource.getDiagnosticReport(patient, + new Encounter(), resourceRequestHandler, observationMap); + + // composition + Composition composition = PopulateDischargeSummaryComposition(resourceRequestHandler, p, practitioner, organization, patient, encounter, conditionListChiefComplaints, + conditionListDiagnosis, allergyList, familyMemberHistory, medicationStatement, medicationRequest, diagnosticResourceList); + + List bundleEnteries = new ArrayList<>(); + + BundleEntryComponent bundleEntry1 = new BundleEntryComponent(); + bundleEntry1.setFullUrl(composition.getIdElement().getValue()); + bundleEntry1.setResource(composition); + + BundleEntryComponent bundleEntry2 = new BundleEntryComponent(); + bundleEntry2.setFullUrl(practitioner.getIdElement().getValue()); + bundleEntry2.setResource(practitioner); + + BundleEntryComponent bundleEntry3 = new BundleEntryComponent(); + bundleEntry3.setFullUrl(organization.getIdElement().getValue()); + bundleEntry3.setResource(organization); + + BundleEntryComponent bundleEntry4 = new BundleEntryComponent(); + bundleEntry4.setFullUrl(patient.getIdElement().getValue()); + bundleEntry4.setResource(patient); + + bundleEnteries.add(bundleEntry1); + bundleEnteries.add(bundleEntry2); + bundleEnteries.add(bundleEntry3); + bundleEnteries.add(bundleEntry4); + + for (Condition conditionCheifComplaints : conditionListChiefComplaints) { + BundleEntryComponent bundleEntry5 = new BundleEntryComponent(); + bundleEntry5.setFullUrl(conditionCheifComplaints.getIdElement().getValue()); + bundleEntry5.setResource(conditionCheifComplaints); + + bundleEnteries.add(bundleEntry5); + } + + for (Condition conditionDiagnosis : conditionListDiagnosis) { + BundleEntryComponent bundleEntry6 = new BundleEntryComponent(); + bundleEntry6.setFullUrl(conditionDiagnosis.getIdElement().getValue()); + bundleEntry6.setResource(conditionDiagnosis); + + bundleEnteries.add(bundleEntry6); + } + + for (AllergyIntolerance allergy : allergyList) { + BundleEntryComponent bundleEntry7 = new BundleEntryComponent(); + bundleEntry7.setFullUrl(allergy.getIdElement().getValue()); + bundleEntry7.setResource(allergy); + + bundleEnteries.add(bundleEntry7); + } + + if(familyMemberHistory.getId() != null) { + BundleEntryComponent bundleEntry8 = new BundleEntryComponent(); + bundleEntry8.setFullUrl(familyMemberHistory.getIdElement().getValue()); + bundleEntry8.setResource(familyMemberHistory); + bundleEnteries.add(bundleEntry8); + } + + for(MedicationStatement medStatement: medicationStatement) { + BundleEntryComponent bundleEntry9 = new BundleEntryComponent(); + bundleEntry9.setFullUrl(medStatement.getIdElement().getValue()); + bundleEntry9.setResource(medStatement); + + bundleEnteries.add(bundleEntry9); + } + + for (DiagnosticReport dr : diagnosticResourceList) { + BundleEntryComponent entryDR = new BundleEntryComponent(); + entryDR.setFullUrl(dr.getIdElement().getValue()); + entryDR.setResource(dr); + + bundleEnteries.add(entryDR); + } + + + if (observationMap != null && !observationMap.isEmpty()) { + for (Map.Entry> e : observationMap.entrySet()) { + List obsList = e.getValue(); + if (obsList == null) + continue; + + for (Observation obs : obsList) { + BundleEntryComponent entryObs = new BundleEntryComponent(); + entryObs.setFullUrl(obs.getIdElement().getValue()); + entryObs.setResource(obs); + bundleEnteries.add(entryObs); + } + } + } + + dischargeSummaryBundle.setEntry(bundleEnteries); + + FhirContext ctx = FhirContext.forR4(); + IParser parser = ctx.newJsonParser(); + serializeBundle = parser.encodeResourceToString(dischargeSummaryBundle); + + } catch (Exception e) { + throw new FHIRException("Discharge summary FHIR Resource Bundle failed with error - " + e); + } + + return serializeBundle; + + } + + @Override + + public Composition PopulateDischargeSummaryComposition( + ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p, + Practitioner practitioner, + Organization organization, + Patient patient, + Encounter encounter, + List chiefComplaints, + List physicalExam, + List allergyList, + FamilyMemberHistory familyMemberHistory, + List pastMedicalHistoryConditions, + List medicationRequests, + List procedures + ) { + Composition composition = new Composition(); + composition.setId("Composition/" + commonService.getUUID()); + + Meta meta = new Meta(); + meta.setVersionId("1"); + meta.addProfile("https://nrces.in/ndhm/fhir/r4/StructureDefinition/DischargeSummaryRecord"); + composition.setMeta(meta); + + composition.setStatus(CompositionStatus.FINAL); + + composition.setType(new CodeableConcept() + .addCoding(new Coding("http://snomed.info/sct", "373942005", "Discharge summary"))); + + composition.setSubject(new Reference("Patient/"+ p.getBeneficiaryId().toString())); + + composition.setDate(new Date()); + composition.addAuthor(new Reference(practitioner.getIdElement().getValue())); + composition.setCustodian(new Reference(organization.getIdElement().getValue())); + + composition.setTitle("Discharge Summary"); + + List sectionList = new ArrayList<>(); + + // 1) Chief complaints (Condition) – SNOMED 422843007 + if (chiefComplaints != null) { + for (Condition condition : chiefComplaints) { + SectionComponent s = new SectionComponent(); + s.setTitle("Chief complaints"); + s.setCode(new CodeableConcept().addCoding( + new Coding("http://snomed.info/sct", "422843007", "Chief complaint section"))); + s.addEntry(new Reference(condition.getIdElement().getValue())); + sectionList.add(s); + } + } + + // 2) Physical examination (Observation) – SNOMED 425044008 + if (physicalExam != null) { + for (Condition obs : physicalExam) { + SectionComponent s = new SectionComponent(); + s.setTitle("Physical examination"); + s.setCode(new CodeableConcept().addCoding( + new Coding("http://snomed.info/sct", "425044008", "Physical exam section"))); + s.addEntry(new Reference(obs.getIdElement().getValue())); + sectionList.add(s); + } + } + + // 3) Allergies (AllergyIntolerance) – SNOMED 722446000 + if (allergyList != null) { + for (AllergyIntolerance allergy : allergyList) { + SectionComponent s = new SectionComponent(); + s.setTitle("Allergies"); + s.setCode(new CodeableConcept().addCoding( + new Coding("http://snomed.info/sct", "722446000", "Allergy record"))); + s.addEntry(new Reference(allergy.getIdElement().getValue())); + sectionList.add(s); + } + } + + // 4) Past medical history (Condition|Procedure) – SNOMED 1003642006 + boolean hasPMH = (pastMedicalHistoryConditions != null && !pastMedicalHistoryConditions.isEmpty()); + if (hasPMH) { + SectionComponent s = new SectionComponent(); + s.setTitle("Past Medical History"); + s.setCode(new CodeableConcept().addCoding( + new Coding("http://snomed.info/sct", "1003642006", "Past medical history section"))); + if (pastMedicalHistoryConditions != null) { + for (MedicationStatement c : pastMedicalHistoryConditions) { + s.addEntry(new Reference(c.getIdElement().getValue())); + } + } + sectionList.add(s); + } + + // 5) Family history (FamilyMemberHistory) – SNOMED 422432008 + if (familyMemberHistory != null && familyMemberHistory.getId() != null) { + SectionComponent s = new SectionComponent(); + s.setTitle("Family history"); + s.setCode(new CodeableConcept().addCoding( + new Coding("http://snomed.info/sct", "422432008", "Family history section"))); + s.addEntry(new Reference(familyMemberHistory.getIdElement().getValue())); + sectionList.add(s); + } + + // 6) Investigations (Diagnostic studies report) – SNOMED 721981007 (Lab + Imaging) + boolean hasInvestigations = (procedures != null && !procedures.isEmpty()); + if (hasInvestigations) { + SectionComponent s = new SectionComponent(); + s.setTitle("Investigations"); + s.setCode(new CodeableConcept().addCoding( + new Coding("http://snomed.info/sct", "721981007", "Diagnostic studies report"))); + if (procedures != null) { + for (DiagnosticReport dr : procedures) { + s.addEntry(new Reference(dr.getIdElement().getValue())); + } + } + sectionList.add(s); + } + + // 7) Medications (MedicationRequest) – SNOMED 1003606003 + if (medicationRequests != null) { + for (MedicationRequest mr : medicationRequests) { + SectionComponent s = new SectionComponent(); + s.setTitle("Medications"); + s.setCode(new CodeableConcept().addCoding( + new Coding("http://snomed.info/sct", "1003606003", "Medication history section"))); + s.addEntry(new Reference(mr.getIdElement().getValue())); + sectionList.add(s); + } + } + + + composition.setSection(sectionList); + return composition; + } + + private AMRIT_ResourceMongo createDischargeSummaryBundleMongo(PatientEligibleForResourceCreation p, + String dischargeRecordBundle) { + AMRIT_ResourceMongo aMRIT_ResourceMongo = new AMRIT_ResourceMongo(); + aMRIT_ResourceMongo.setBeneficiaryID(p.getBeneficiaryId()); + aMRIT_ResourceMongo.setBeneficiaryRegID(p.getBeneficiaryRegID()); + // get ABHA from table "m_benhealthmapping" for this visit(visit code) + if (p.getVisitCode() != null) { + aMRIT_ResourceMongo.setVisitCode(p.getVisitCode()); + List objArrResultSet = benHealthIDMappingRepo.getLinkedHealthIDForVisit(p.getVisitCode()); + if (objArrResultSet != null && objArrResultSet.size() > 0) { + aMRIT_ResourceMongo.setNationalHealthID(objArrResultSet.get(0)); + } + } + + aMRIT_ResourceMongo.setResourceJson(dischargeRecordBundle); + aMRIT_ResourceMongo.setResourceType("DischargeSummary"); + + return aMRIT_ResourceMongo; + } + +} diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundle.java b/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundle.java new file mode 100644 index 0000000..1c08e2d --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundle.java @@ -0,0 +1,26 @@ +package com.wipro.fhir.service.bundle_creation; + +import java.util.List; + +import org.hl7.fhir.r4.model.Composition; +import org.hl7.fhir.r4.model.Immunization; +import org.hl7.fhir.r4.model.Organization; +import org.hl7.fhir.r4.model.Patient; +import org.hl7.fhir.r4.model.Practitioner; + +import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.utils.exception.FHIRException; + +public interface ImmunizationRecordResourceBundle { + + Composition populateImmunizationComposition(Patient patient, Practitioner practitioner, Organization organization, + List immunizations); + + String PopulateImmunizationResourceBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException; + + int processImmunizationRecordBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException; + +} diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundleImpl.java new file mode 100644 index 0000000..5131cb5 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundleImpl.java @@ -0,0 +1,236 @@ +package com.wipro.fhir.service.bundle_creation; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; + +import org.hl7.fhir.r4.model.Bundle; +import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent; +import org.hl7.fhir.r4.model.CodeableConcept; +import org.hl7.fhir.r4.model.Coding; +import org.hl7.fhir.r4.model.Composition; +import org.hl7.fhir.r4.model.Composition.SectionComponent; +import org.hl7.fhir.r4.model.Identifier; +import org.hl7.fhir.r4.model.Immunization; +import org.hl7.fhir.r4.model.Meta; +import org.hl7.fhir.r4.model.Organization; +import org.hl7.fhir.r4.model.Patient; +import org.hl7.fhir.r4.model.Practitioner; +import org.hl7.fhir.r4.model.Reference; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import com.wipro.fhir.data.mongo.amrit_resource.AMRIT_ResourceMongo; +import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; +import com.wipro.fhir.service.common.CommonService; +import com.wipro.fhir.service.resource_model.ImmunizationResource; +import com.wipro.fhir.service.resource_model.OrganizationResource; +import com.wipro.fhir.service.resource_model.PatientResource; +import com.wipro.fhir.service.resource_model.PractitionerResource; +import com.wipro.fhir.utils.exception.FHIRException; + +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.parser.IParser; + +@Service +public class ImmunizationRecordResourceBundleImpl implements ImmunizationRecordResourceBundle { + + @Autowired + private PractitionerResource practitionerResource; + + @Autowired + private OrganizationResource organizationResource; + + @Autowired + private PatientResource patientResource; + + @Autowired + private CommonService commonService; + + @Autowired + private ImmunizationResource immunizationResource; + + @Autowired + private BenHealthIDMappingRepo benHealthIDMappingRepo; + + @Value("${systemUrl}") + private String systemUrl; + + @Override + public int processImmunizationRecordBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException { + int i = 0; + // call method to generate Prescription resource + String immunizationBundle = PopulateImmunizationResourceBundle(resourceRequestHandler, p); + + // call private method to create mongo object with resource data + AMRIT_ResourceMongo aMRIT_ResourceMongo = createImmunizationBundleMongo(p, + immunizationBundle); + // if resource data is not null, save to mongo + if (aMRIT_ResourceMongo != null) { + i = commonService.saveResourceToMongo(aMRIT_ResourceMongo); + + } else + throw new FHIRException("Issue in processing the bundle"); + + return i; + + } + + @Override + public String PopulateImmunizationResourceBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException { + + Bundle diagReportBundle = new Bundle(); + String serializeBundle = null; + + try { + String id = resourceRequestHandler.getVisitCode() + ":" + commonService.getUUID(); + diagReportBundle.setId(id); + diagReportBundle.setType(Bundle.BundleType.DOCUMENT); + diagReportBundle.setTimestamp(new Timestamp(System.currentTimeMillis())); + + Meta meta = new Meta(); + meta.setVersionId("1"); + meta.setLastUpdated(new Timestamp(System.currentTimeMillis())); + meta.addProfile("https://nrces.in/ndhm/fhir/r4/StructureDefinition/DocumentBundle"); + meta.addSecurity(new Coding("http://terminology.hl7.org/CodeSystem/v3-Confidentiality", "R", "restricted")); + diagReportBundle.setMeta(meta); + + Identifier identifier = new Identifier(); + identifier.setSystem(systemUrl); + identifier.setValue(diagReportBundle.getId()); + diagReportBundle.setIdentifier(identifier); + + // practitioner resource + Practitioner practitioner = practitionerResource.getPractitionerResource(resourceRequestHandler); + + // Organization resource + Organization organization = organizationResource.getOrganizationResource(resourceRequestHandler); + + // Patient resource + Patient patient = patientResource.getPatientResource(resourceRequestHandler); + + List immunizationList = immunizationResource.getImmunizations(patient, resourceRequestHandler); + + Composition composition = populateImmunizationComposition(patient, practitioner, organization, immunizationList); + + List bundleEntries = new ArrayList<>(); + + BundleEntryComponent entryComposition = new BundleEntryComponent(); + entryComposition.setFullUrl(composition.getIdElement().getValue()); + entryComposition.setResource(composition); + bundleEntries.add(entryComposition); + + BundleEntryComponent entryPractitioner = new BundleEntryComponent(); + entryPractitioner.setFullUrl(practitioner.getIdElement().getValue()); + entryPractitioner.setResource(practitioner); + bundleEntries.add(entryPractitioner); + + BundleEntryComponent entryOrganization = new BundleEntryComponent(); + entryOrganization.setFullUrl(organization.getIdElement().getValue()); + entryOrganization.setResource(organization); + bundleEntries.add(entryOrganization); + + BundleEntryComponent entryPatient = new BundleEntryComponent(); + entryPatient.setFullUrl(patient.getIdElement().getValue()); + entryPatient.setResource(patient); + bundleEntries.add(entryPatient); + + + for (Immunization imm : immunizationList) { + Bundle.BundleEntryComponent beImm = new Bundle.BundleEntryComponent(); + beImm.setFullUrl(imm.getIdElement().getValue()); + beImm.setResource(imm); + bundleEntries.add(beImm); + } + + diagReportBundle.setEntry(bundleEntries); + + FhirContext ctx = FhirContext.forR4(); + IParser parser = ctx.newJsonParser(); + serializeBundle = parser.encodeResourceToString(diagReportBundle); + + + } catch (Exception e) { + throw new FHIRException("Immunization FHIR Resource Bundle failed with error - " + e); + } + + return serializeBundle; + } + + @Override + +public Composition populateImmunizationComposition(Patient patient, + Practitioner practitioner, + Organization organization, + List immunizations) { + + Composition composition = new Composition(); + composition.setId("Composition/" + commonService.getUUID()); + + // NRCeS ImmunizationRecord profile on Composition + Meta meta = new Meta(); + meta.setVersionId("1"); + meta.addProfile("https://nrces.in/ndhm/fhir/r4/StructureDefinition/ImmunizationRecord"); + composition.setMeta(meta); + + composition.setStatus(Composition.CompositionStatus.FINAL); + + composition.setType(new CodeableConcept() + .addCoding(new Coding("http://snomed.info/sct", "41000179103", "Immunization record")) + .setText("Immunization Record")); + + composition.setSubject(new Reference(patient.getIdElement().getValue())); + composition.setDate(new java.util.Date()); + composition.addAuthor(new Reference(practitioner.getIdElement().getValue())); + composition.setCustodian(new Reference(organization.getIdElement().getValue())); + composition.setTitle("Immunization Record"); + + if (organization != null) { + composition.setCustodian(new Reference(organization.getIdElement().getValue())); + } + + // --- Sections --- + SectionComponent immunizationSection = new SectionComponent(); + immunizationSection.setTitle("Administered Immunizations"); + immunizationSection.setCode(new CodeableConcept().addCoding( + new Coding("http://snomed.info/sct", "41000179103", "Immunization record") + )); + + for (Immunization imm : immunizations) { + Reference ref = new Reference(imm.getIdElement().getValue()); + ref.setType("Immunization"); + immunizationSection.addEntry(ref); + } + + composition.addSection(immunizationSection); + + return composition; +} + + private AMRIT_ResourceMongo createImmunizationBundleMongo(PatientEligibleForResourceCreation p, + String immunizationBundle) { + AMRIT_ResourceMongo aMRIT_ResourceMongo = new AMRIT_ResourceMongo(); + aMRIT_ResourceMongo.setBeneficiaryID(p.getBeneficiaryId()); + aMRIT_ResourceMongo.setBeneficiaryRegID(p.getBeneficiaryRegID()); + // get ABHA from table "m_benhealthmapping" for this visit(visit code) + if (p.getVisitCode() != null) { + aMRIT_ResourceMongo.setVisitCode(p.getVisitCode()); + List objArrResultSet = benHealthIDMappingRepo.getLinkedHealthIDForVisit(p.getVisitCode()); + if (objArrResultSet != null && objArrResultSet.size() > 0) { + aMRIT_ResourceMongo.setNationalHealthID(objArrResultSet.get(0)); + } + } + + aMRIT_ResourceMongo.setResourceJson(immunizationBundle); + aMRIT_ResourceMongo.setResourceType("ImmunizationRecord"); + + return aMRIT_ResourceMongo; + } + + +} diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundle.java b/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundle.java new file mode 100644 index 0000000..238c864 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundle.java @@ -0,0 +1,31 @@ +package com.wipro.fhir.service.bundle_creation; + +import java.util.List; + +import org.hl7.fhir.r4.model.AllergyIntolerance; +import org.hl7.fhir.r4.model.Composition; +import org.hl7.fhir.r4.model.Condition; +import org.hl7.fhir.r4.model.FamilyMemberHistory; +import org.hl7.fhir.r4.model.MedicationStatement; +import org.hl7.fhir.r4.model.Organization; +import org.hl7.fhir.r4.model.Practitioner; + +import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.utils.exception.FHIRException; + +public interface OPConsultResourceBundle { + + Composition PopulateOpConsultComposition(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p, Practitioner practitioner, Organization organization, + List conditionListChiefComplaints, List conditionListDiagnosis, + List allergyList, FamilyMemberHistory familyMemberHistory, + List medicationStatement); + + int processOpConsultRecordBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException; + + String PopulateOPConsultRecordResourceBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException; + +} diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundleImpl.java new file mode 100644 index 0000000..ad231eb --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundleImpl.java @@ -0,0 +1,340 @@ +package com.wipro.fhir.service.bundle_creation; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.hl7.fhir.r4.model.AllergyIntolerance; +import org.hl7.fhir.r4.model.Bundle; +import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent; +import org.hl7.fhir.r4.model.Bundle.BundleType; +import org.hl7.fhir.r4.model.CodeableConcept; +import org.hl7.fhir.r4.model.Coding; +import org.hl7.fhir.r4.model.Composition; +import org.hl7.fhir.r4.model.Composition.CompositionStatus; +import org.hl7.fhir.r4.model.Composition.SectionComponent; +import org.hl7.fhir.r4.model.Condition; +import org.hl7.fhir.r4.model.Encounter; +import org.hl7.fhir.r4.model.FamilyMemberHistory; +import org.hl7.fhir.r4.model.Identifier; +import org.hl7.fhir.r4.model.MedicationStatement; +import org.hl7.fhir.r4.model.Meta; +import org.hl7.fhir.r4.model.Organization; +import org.hl7.fhir.r4.model.Patient; +import org.hl7.fhir.r4.model.Practitioner; +import org.hl7.fhir.r4.model.Reference; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import com.wipro.fhir.data.mongo.amrit_resource.AMRIT_ResourceMongo; +import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; +import com.wipro.fhir.service.common.CommonService; +import com.wipro.fhir.service.resource_model.AllergyIntoleranceResource; +import com.wipro.fhir.service.resource_model.ConditionResource; +import com.wipro.fhir.service.resource_model.EncounterResource; +import com.wipro.fhir.service.resource_model.FamilyMemberHistoryResource; +import com.wipro.fhir.service.resource_model.MedicalHistoryResource; +import com.wipro.fhir.service.resource_model.OrganizationResource; +import com.wipro.fhir.service.resource_model.PatientResource; +import com.wipro.fhir.service.resource_model.PractitionerResource; +import com.wipro.fhir.utils.exception.FHIRException; + +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.parser.IParser; + +@Service +public class OPConsultResourceBundleImpl implements OPConsultResourceBundle { + + @Autowired + private CommonService commonService; + + @Autowired + private PractitionerResource practitionerResource; + + @Autowired + private OrganizationResource organizationResource; + + @Autowired + private PatientResource patientResource; + + @Autowired + private ConditionResource conditionResource; + + @Autowired + private EncounterResource encounterResource; + + @Autowired + private AllergyIntoleranceResource allergyIntoleranceResource; + + @Autowired + private FamilyMemberHistoryResource familyMemberHistoryResource; + + @Autowired + private MedicalHistoryResource medicalHistoryResource; + + @Autowired + private BenHealthIDMappingRepo benHealthIDMappingRepo; + + @Value("${systemUrl}") + private String systemUrl; + + @Override + public int processOpConsultRecordBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException { + int i = 0; + // call method to generate Prescription resource + String opConsultBundle = PopulateOPConsultRecordResourceBundle(resourceRequestHandler, p); + + // call private method to create mongo object with resource data + AMRIT_ResourceMongo aMRIT_ResourceMongo = createOpConsultBundleMongo(p, + opConsultBundle); + // if resource data is not null, save to mongo + if (aMRIT_ResourceMongo != null) { + i = commonService.saveResourceToMongo(aMRIT_ResourceMongo); + + } else + throw new FHIRException("Issue in processing the bundle"); + + return i; + + } + + + @Override + public String PopulateOPConsultRecordResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException { + + Bundle opConsultBundle = new Bundle(); + String serializeBundle = null; + + try { + String id = resourceRequestHandler.getVisitCode()+ ":" + commonService.getUUID(); + opConsultBundle.setId(id); + opConsultBundle.setType(BundleType.DOCUMENT); + opConsultBundle.setTimestamp(new Timestamp(System.currentTimeMillis())); + + Meta meta = new Meta(); + meta.setVersionId("1"); + meta.setLastUpdated(new Timestamp(System.currentTimeMillis())); + meta.addProfile("https://nrces.in/ndhm/fhir/r4/StructureDefinition/DocumentBundle"); + meta.addSecurity(new Coding("http://terminology.hl7.org/CodeSystem/v3-Confidentiality", "restricted", "R")); + opConsultBundle.setMeta(meta); + + Identifier identifier = new Identifier(); + identifier.setSystem(systemUrl); + identifier.setValue(opConsultBundle.getId()); + opConsultBundle.setIdentifier(identifier); + + // practitioner + Practitioner practitioner = practitionerResource.getPractitionerResource(resourceRequestHandler); + // organization + Organization organization = organizationResource.getOrganizationResource(resourceRequestHandler); + // Patient Resource + Patient patient = patientResource.getPatientResource(resourceRequestHandler); + + // chiefcomplaints + List conditionListChiefComplaints = conditionResource.getCondition(patient, resourceRequestHandler, + "chiefcomplaints"); + + // diagnosis + List conditionListDiagnosis = conditionResource.getCondition(patient, resourceRequestHandler, + "diagnosis"); + + Encounter encounter = encounterResource.getEncounterResource(patient, resourceRequestHandler, + conditionListChiefComplaints, conditionListDiagnosis); + + // AllergyIntolerance resource + List allergyList = allergyIntoleranceResource.getAllergyIntolerance(patient, encounter, + resourceRequestHandler, practitioner); + + // FamilyMemberHistory resource + FamilyMemberHistory familyMemberHistory = familyMemberHistoryResource.getFamilyMemberHistory(patient, + resourceRequestHandler); + + List medicationStatement = medicalHistoryResource.getMedicalHistory(patient, resourceRequestHandler); + + // composition + Composition composition = PopulateOpConsultComposition(resourceRequestHandler, p, practitioner, organization, conditionListChiefComplaints, + conditionListDiagnosis, allergyList,familyMemberHistory, medicationStatement); + + List bundleEnteries = new ArrayList<>(); + + BundleEntryComponent bundleEntry1 = new BundleEntryComponent(); + bundleEntry1.setFullUrl(composition.getIdElement().getValue()); + bundleEntry1.setResource(composition); + + BundleEntryComponent bundleEntry2 = new BundleEntryComponent(); + bundleEntry2.setFullUrl(practitioner.getIdElement().getValue()); + bundleEntry2.setResource(practitioner); + + BundleEntryComponent bundleEntry3 = new BundleEntryComponent(); + bundleEntry3.setFullUrl(organization.getIdElement().getValue()); + bundleEntry3.setResource(organization); + + BundleEntryComponent bundleEntry4 = new BundleEntryComponent(); + bundleEntry4.setFullUrl(patient.getIdElement().getValue()); + bundleEntry4.setResource(patient); + + bundleEnteries.add(bundleEntry1); + bundleEnteries.add(bundleEntry2); + bundleEnteries.add(bundleEntry3); + bundleEnteries.add(bundleEntry4); + + for (Condition conditionCheifComplaints : conditionListChiefComplaints) { + BundleEntryComponent bundleEntry5 = new BundleEntryComponent(); + bundleEntry5.setFullUrl(conditionCheifComplaints.getIdElement().getValue()); + bundleEntry5.setResource(conditionCheifComplaints); + + bundleEnteries.add(bundleEntry5); + } + + for (Condition conditionDiagnosis : conditionListDiagnosis) { + BundleEntryComponent bundleEntry6 = new BundleEntryComponent(); + bundleEntry6.setFullUrl(conditionDiagnosis.getIdElement().getValue()); + bundleEntry6.setResource(conditionDiagnosis); + + bundleEnteries.add(bundleEntry6); + } + + for (AllergyIntolerance allergy : allergyList) { + BundleEntryComponent bundleEntry7 = new BundleEntryComponent(); + bundleEntry7.setFullUrl(allergy.getIdElement().getValue()); + bundleEntry7.setResource(allergy); + + bundleEnteries.add(bundleEntry7); + } + + if(familyMemberHistory.getId() != null) { + BundleEntryComponent bundleEntry8 = new BundleEntryComponent(); + bundleEntry8.setFullUrl(familyMemberHistory.getIdElement().getValue()); + bundleEntry8.setResource(familyMemberHistory); + bundleEnteries.add(bundleEntry8); + } + + for(MedicationStatement medStatement: medicationStatement) { + BundleEntryComponent bundleEntry9 = new BundleEntryComponent(); + bundleEntry9.setFullUrl(medStatement.getIdElement().getValue()); + bundleEntry9.setResource(medStatement); + + bundleEnteries.add(bundleEntry9); + } + + opConsultBundle.setEntry(bundleEnteries); + + FhirContext ctx = FhirContext.forR4(); + IParser parser = ctx.newJsonParser(); + serializeBundle = parser.encodeResourceToString(opConsultBundle); + + + } catch (Exception e) { + throw new FHIRException("Op Consult FHIR Resource Bundle failed with error - " + e); + } + + return serializeBundle; + + } + + @Override + public Composition PopulateOpConsultComposition(ResourceRequestHandler resourceRequestHandler,PatientEligibleForResourceCreation p, + Practitioner practitioner, Organization organization, List conditionListChiefComplaints, List conditionListDiagnosis, + List allergyList, FamilyMemberHistory familyMemberHistory, List medicationStatement) { + + Composition composition = new Composition(); + composition.setId("Composition/" + commonService.getUUID()); + + Meta meta = new Meta(); + meta.setVersionId("1"); + meta.addProfile("https://nrces.in/ndhm/fhir/r4/StructureDefinition/OPConsultRecord"); + composition.setMeta(meta); + + composition.setStatus(CompositionStatus.FINAL); + composition + .setType(new CodeableConcept(new Coding("http://snomed.info/sct", "371530004", "Clinical consultation report`"))); + + composition.setSubject(new Reference("Patient/"+ p.getBeneficiaryId().toString())); + composition.setDate(new Date()); + composition.addAuthor(new Reference(practitioner.getIdElement().getValue())); + composition.setCustodian(new Reference(organization.getIdElement().getValue())); + composition.setTitle("Consultation Report"); + + List sectionList = new ArrayList(); + + for(Condition condition: conditionListChiefComplaints) { + SectionComponent section1 = new SectionComponent(); + section1.setTitle("Chief complaints"); + section1.setCode(new CodeableConcept(new Coding("http://snomed.info/sct", "422843007", "Chief complaint section"))) + .addEntry(new Reference().setReference(condition.getIdElement().getValue())); + + sectionList.add(section1); + } + + for(Condition diagnosis: conditionListDiagnosis) { + SectionComponent section2 = new SectionComponent(); + section2.setTitle("Physical diagnosis"); + section2.setCode(new CodeableConcept(new Coding("http://snomed.info/sct", "425044008", "Physical exam section"))) + .addEntry(new Reference().setReference(diagnosis.getIdElement().getValue())); + + sectionList.add(section2); + } + + for(AllergyIntolerance allergy: allergyList) { + SectionComponent section3 = new SectionComponent(); + section3.setTitle("Allergies"); + section3.setCode(new CodeableConcept(new Coding("http://snomed.info/sct", "722446000", "Allergy record"))) + .addEntry(new Reference().setReference(allergy.getIdElement().getValue())); + + sectionList.add(section3); + } + + for(MedicationStatement medStatement: medicationStatement) { + SectionComponent section4 = new SectionComponent(); + section4.setTitle("Medical History"); + section4.setCode( + new CodeableConcept(new Coding("http://snomed.info/sct", "371529009", "History and physical report"))) + .addEntry(new Reference().setReference(medStatement.getIdElement().getValue())); + + sectionList.add(section4); + } + + + if(familyMemberHistory.getId() != null) { + SectionComponent section5 = new SectionComponent(); + section5.setTitle("Family history"); + section5.setCode( + new CodeableConcept(new Coding("http://snomed.info/sct", "422432008", "Family history section"))) + .addEntry(new Reference().setReference(familyMemberHistory.getIdElement().getValue())); + + sectionList.add(section5); + } + + composition.setSection(sectionList); + + return composition; + + } + + private AMRIT_ResourceMongo createOpConsultBundleMongo(PatientEligibleForResourceCreation p, + String opConsultBundle) { + AMRIT_ResourceMongo aMRIT_ResourceMongo = new AMRIT_ResourceMongo(); + aMRIT_ResourceMongo.setBeneficiaryID(p.getBeneficiaryId()); + aMRIT_ResourceMongo.setBeneficiaryRegID(p.getBeneficiaryRegID()); + // get ABHA from table "m_benhealthmapping" for this visit(visit code) + if (p.getVisitCode() != null) { + aMRIT_ResourceMongo.setVisitCode(p.getVisitCode()); + List objArrResultSet = benHealthIDMappingRepo.getLinkedHealthIDForVisit(p.getVisitCode()); + if (objArrResultSet != null && objArrResultSet.size() > 0) { + aMRIT_ResourceMongo.setNationalHealthID(objArrResultSet.get(0)); + } + } + + aMRIT_ResourceMongo.setResourceJson(opConsultBundle); + aMRIT_ResourceMongo.setResourceType("OPConsultation"); + + return aMRIT_ResourceMongo; + } + + +} diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundle.java b/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundle.java new file mode 100644 index 0000000..ea5224c --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundle.java @@ -0,0 +1,27 @@ +package com.wipro.fhir.service.bundle_creation; + +import java.util.List; + +import org.hl7.fhir.r4.model.Composition; +import org.hl7.fhir.r4.model.MedicationRequest; +import org.hl7.fhir.r4.model.Organization; +import org.hl7.fhir.r4.model.Practitioner; + +import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.utils.exception.FHIRException; + +public interface PrescriptionResourceBundle { + + String PopulatePrescriptionResourceBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException; + + Composition PopulatePrescriptionComposition(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p, List medicationRequest, Practitioner practitioner, + Organization organization); + + int processPrescriptionRecordBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException; + + +} diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundleImpl.java new file mode 100644 index 0000000..d778e17 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundleImpl.java @@ -0,0 +1,228 @@ +package com.wipro.fhir.service.bundle_creation; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.hl7.fhir.r4.model.Bundle; +import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent; +import org.hl7.fhir.r4.model.Bundle.BundleType; +import org.hl7.fhir.r4.model.CodeableConcept; +import org.hl7.fhir.r4.model.Coding; +import org.hl7.fhir.r4.model.Composition; +import org.hl7.fhir.r4.model.Composition.CompositionStatus; +import org.hl7.fhir.r4.model.Composition.SectionComponent; +import org.hl7.fhir.r4.model.Identifier; +import org.hl7.fhir.r4.model.MedicationRequest; +import org.hl7.fhir.r4.model.Meta; +import org.hl7.fhir.r4.model.Organization; +import org.hl7.fhir.r4.model.Patient; +import org.hl7.fhir.r4.model.Practitioner; +import org.hl7.fhir.r4.model.Reference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import com.wipro.fhir.data.mongo.amrit_resource.AMRIT_ResourceMongo; +import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; +import com.wipro.fhir.service.common.CommonService; +import com.wipro.fhir.service.resource_model.MedicationRequestResource; +import com.wipro.fhir.service.resource_model.OrganizationResource; +import com.wipro.fhir.service.resource_model.PatientResource; +import com.wipro.fhir.service.resource_model.PractitionerResource; +import com.wipro.fhir.utils.exception.FHIRException; + +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.parser.IParser; + +@Service +public class PrescriptionResourceBundleImpl implements PrescriptionResourceBundle { + + @Autowired + private CommonService commonService; + @Autowired + private PractitionerResource practitionerResource; + @Autowired + private PatientResource patientResource; + @Autowired + private MedicationRequestResource medicationRequestResource; + @Autowired + private OrganizationResource organizationResource; + @Autowired + private BenHealthIDMappingRepo benHealthIDMappingRepo; + + @Value("${systemUrl}") + private String systemUrl; + + Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + + @Override + public int processPrescriptionRecordBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException { + int i = 0; + // call method to generate Prescription resource + String prescriptionBundle = PopulatePrescriptionResourceBundle(resourceRequestHandler, p); + + // call private method to create mongo object with resource data + AMRIT_ResourceMongo aMRIT_ResourceMongo = createPrescriptionBundleMongo(p, + prescriptionBundle); + // if resource data is not null, save to mongo + if (aMRIT_ResourceMongo != null) { + i = commonService.saveResourceToMongo(aMRIT_ResourceMongo); + + } else + throw new FHIRException("Issue in processing the bundle"); + + return i; + + } + + @Override + public String PopulatePrescriptionResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException { + + Bundle prescriptionBundle = new Bundle(); + String serializeBundle = null; + + try { + String id = resourceRequestHandler.getVisitCode()+ ":" + commonService.getUUID(); + prescriptionBundle.setId(id); + prescriptionBundle.setType(BundleType.DOCUMENT); + prescriptionBundle.setTimestamp(new Timestamp(System.currentTimeMillis())); + + Meta meta = new Meta(); + meta.setVersionId("1"); + meta.setLastUpdated(new Timestamp(System.currentTimeMillis())); + meta.addProfile("https://nrces.in/ndhm/fhir/r4/StructureDefinition/DocumentBundle"); + meta.addSecurity(new Coding("http://terminology.hl7.org/CodeSystem/v3-Confidentiality", "restricted", "R")); + prescriptionBundle.setMeta(meta); + + Identifier identifier = new Identifier(); + identifier.setSystem(systemUrl); + identifier.setValue(prescriptionBundle.getId()); + prescriptionBundle.setIdentifier(identifier); + + // practitioner + Practitioner practitioner = practitionerResource.getPractitionerResource(resourceRequestHandler); + // organization + Organization organization = organizationResource.getOrganizationResource(resourceRequestHandler); + // 1. Patient Resource + Patient patient = patientResource.getPatientResource(resourceRequestHandler); + // Medication request + List medicationRequest = medicationRequestResource.getMedicationRequest(patient, + resourceRequestHandler, practitioner, null); + // composition + Composition composition = PopulatePrescriptionComposition(resourceRequestHandler, p, medicationRequest, practitioner, organization); + + List bundleEnteries = new ArrayList<>(); + + BundleEntryComponent bundleEntry1 = new BundleEntryComponent(); + bundleEntry1.setFullUrl(composition.getIdElement().getValue()); + bundleEntry1.setResource(composition); + + BundleEntryComponent bundleEntry2 = new BundleEntryComponent(); + bundleEntry2.setFullUrl(practitioner.getIdElement().getValue()); + bundleEntry2.setResource(practitioner); + + BundleEntryComponent bundleEntry3 = new BundleEntryComponent(); + bundleEntry3.setFullUrl(organization.getIdElement().getValue()); + bundleEntry3.setResource(organization); + + BundleEntryComponent bundleEntry4 = new BundleEntryComponent(); + bundleEntry4.setFullUrl(patient.getIdElement().getValue()); + bundleEntry4.setResource(patient); + + bundleEnteries.add(bundleEntry1); + bundleEnteries.add(bundleEntry2); + bundleEnteries.add(bundleEntry3); + bundleEnteries.add(bundleEntry4); + + for (MedicationRequest medRequest : medicationRequest) { + BundleEntryComponent bundleEntry5 = new BundleEntryComponent(); + bundleEntry5.setFullUrl(medRequest.getIdElement().getValue()); + bundleEntry5.setResource(medRequest); + + bundleEnteries.add(bundleEntry5); + } + + prescriptionBundle.setEntry(bundleEnteries); + + FhirContext ctx = FhirContext.forR4(); + IParser parser = ctx.newJsonParser(); + serializeBundle = parser.encodeResourceToString(prescriptionBundle); + + + } catch (Exception e) { + throw new FHIRException("Prescription FHIR Resource Bundle failed with error - " + e); + } + + return serializeBundle; + + } + + @Override + public Composition PopulatePrescriptionComposition(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p, List medicationRequest, Practitioner practitioner, Organization organization) { + + Composition composition = new Composition(); + composition.setId("Composition/" + commonService.getUUID()); + + Meta meta = new Meta(); + meta.setVersionId("1"); + meta.addProfile("https://nrces.in/ndhm/fhir/r4/StructureDefinition/PrescriptionRecord"); + composition.setMeta(meta); + + composition.setStatus(CompositionStatus.FINAL); + composition + .setType(new CodeableConcept(new Coding("http://snomed.info/sct", "440545006", "Prescription record"))); + + composition.setSubject(new Reference("Patient/"+ p.getBeneficiaryId().toString())); + composition.setDate(new Date()); + composition.addAuthor(new Reference(practitioner.getIdElement().getValue())); + composition.setCustodian(new Reference(organization.getIdElement().getValue())); + composition.setTitle("Prescription Record"); + + SectionComponent section = new SectionComponent(); + section.setCode(new CodeableConcept(new Coding("http://snomed.info/sct", "440545006", "Prescription record"))); + + for (MedicationRequest med : medicationRequest) { + Reference reference = new Reference(); + reference.setReference(med.getIdElement().getValue()); + reference.setType("MedicationRequest"); + + section.addEntry(reference); + + } + + composition.addSection(section); + + return composition; + + } + + private AMRIT_ResourceMongo createPrescriptionBundleMongo(PatientEligibleForResourceCreation p, + String prescriptionBundle) { + AMRIT_ResourceMongo aMRIT_ResourceMongo = new AMRIT_ResourceMongo(); + aMRIT_ResourceMongo.setBeneficiaryID(p.getBeneficiaryId()); + aMRIT_ResourceMongo.setBeneficiaryRegID(p.getBeneficiaryRegID()); + // get ABHA from table "m_benhealthmapping" for this visit(visit code) + if (p.getVisitCode() != null) { + aMRIT_ResourceMongo.setVisitCode(p.getVisitCode()); + List objArrResultSet = benHealthIDMappingRepo.getLinkedHealthIDForVisit(p.getVisitCode()); + if (objArrResultSet != null && objArrResultSet.size() > 0) { + aMRIT_ResourceMongo.setNationalHealthID(objArrResultSet.get(0)); + } + } + + aMRIT_ResourceMongo.setResourceJson(prescriptionBundle); + aMRIT_ResourceMongo.setResourceType("Prescription"); + + return aMRIT_ResourceMongo; + } + +} diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundle.java b/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundle.java new file mode 100644 index 0000000..bfb4977 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundle.java @@ -0,0 +1,27 @@ +package com.wipro.fhir.service.bundle_creation; + +import java.util.List; + +import org.hl7.fhir.r4.model.Composition; +import org.hl7.fhir.r4.model.Observation; +import org.hl7.fhir.r4.model.Organization; +import org.hl7.fhir.r4.model.Practitioner; + +import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.utils.exception.FHIRException; + +public interface WellnessRecordResourceBundle { + + String PopulateWellnessRecordResourceBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException; + + Composition PopulateWellnessRecordComposition(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p, Practitioner practitioner, Organization organization, + List observationVitalList); + + int processWellnessRecordBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) + throws org.hl7.fhir.exceptions.FHIRException, Exception; + + +} diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundleImpl.java new file mode 100644 index 0000000..9288e48 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundleImpl.java @@ -0,0 +1,257 @@ +package com.wipro.fhir.service.bundle_creation; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.hl7.fhir.exceptions.FHIRException; +import org.hl7.fhir.r4.model.Bundle; +import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent; +import org.hl7.fhir.r4.model.CodeableConcept; +import org.hl7.fhir.r4.model.Coding; +import org.hl7.fhir.r4.model.Composition; +import org.hl7.fhir.r4.model.Identifier; +import org.hl7.fhir.r4.model.Meta; +import org.hl7.fhir.r4.model.Observation; +import org.hl7.fhir.r4.model.Organization; +import org.hl7.fhir.r4.model.Patient; +import org.hl7.fhir.r4.model.Practitioner; +import org.hl7.fhir.r4.model.Reference; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import com.wipro.fhir.data.mongo.amrit_resource.AMRIT_ResourceMongo; +import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; +import com.wipro.fhir.service.common.CommonService; +import com.wipro.fhir.service.resource_model.ObservationResource; +import com.wipro.fhir.service.resource_model.OrganizationResource; +import com.wipro.fhir.service.resource_model.PatientResource; +import com.wipro.fhir.service.resource_model.PractitionerResource; + +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.parser.IParser; + +@Service +public class WellnessRecordResourceBundleImpl implements WellnessRecordResourceBundle { + + @Autowired + private CommonService commonService; + + @Autowired + private PractitionerResource practitionerResource; + + @Autowired + private PatientResource patientResource; + + @Autowired + private OrganizationResource organizationResource; + + @Autowired + private ObservationResource observationResource; + + @Autowired + private BenHealthIDMappingRepo benHealthIDMappingRepo; + + @Value("${systemUrl}") + private String systemUrl; + + @Override + public int processWellnessRecordBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException, Exception { + int i = 0; + // call method to generate Prescription resource + String wellnessBundle = PopulateWellnessRecordResourceBundle(resourceRequestHandler, p); + + // call private method to create mongo object with resource data + AMRIT_ResourceMongo aMRIT_ResourceMongo = createPrescriptionBundleMongo(p, wellnessBundle); + // if resource data is not null, save to mongo + if (aMRIT_ResourceMongo != null) { + i = commonService.saveResourceToMongo(aMRIT_ResourceMongo); + + } else + throw new FHIRException("Issue in processing the bundle"); + return i; + } + + @Override + public String PopulateWellnessRecordResourceBundle(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p) throws FHIRException { + Bundle wellnessBundle = new Bundle(); + String serializeBundle = null; + + try { + + String id = resourceRequestHandler.getVisitCode() + ":" + commonService.getUUID(); + wellnessBundle.setId(id); + wellnessBundle.setType(Bundle.BundleType.DOCUMENT); + wellnessBundle.setTimestamp(new Timestamp(System.currentTimeMillis())); + + Meta meta = new Meta(); + meta.setVersionId("1"); + meta.setLastUpdated(new Timestamp(System.currentTimeMillis())); + meta.addProfile("https://nrces.in/ndhm/fhir/r4/StructureDefinition/DocumentBundle"); + meta.addSecurity(new Coding("http://terminology.hl7.org/CodeSystem/v3-Confidentiality", "restricted", "R")); + wellnessBundle.setMeta(meta); + + Identifier identifier = new Identifier(); + identifier.setSystem(systemUrl); + identifier.setValue(wellnessBundle.getId()); + wellnessBundle.setIdentifier(identifier); + + Practitioner practitioner = practitionerResource.getPractitionerResource(resourceRequestHandler); + Organization organization = organizationResource.getOrganizationResource(resourceRequestHandler); + Patient patient = patientResource.getPatientResource(resourceRequestHandler); + + List observationVitalList = observationResource.getObservationVitals(patient, + resourceRequestHandler); + + // Composition + Composition composition = PopulateWellnessRecordComposition(resourceRequestHandler, p, practitioner, + organization, observationVitalList); + + List bundleEnteries = new ArrayList<>(); + + BundleEntryComponent bundleEntry1 = new BundleEntryComponent(); + bundleEntry1.setFullUrl(composition.getIdElement().getValue()); + bundleEntry1.setResource(composition); + + BundleEntryComponent bundleEntry2 = new BundleEntryComponent(); + bundleEntry2.setFullUrl(practitioner.getIdElement().getValue()); + bundleEntry2.setResource(practitioner); + + BundleEntryComponent bundleEntry3 = new BundleEntryComponent(); + bundleEntry3.setFullUrl(organization.getIdElement().getValue()); + bundleEntry3.setResource(organization); + + BundleEntryComponent bundleEntry4 = new BundleEntryComponent(); + bundleEntry4.setFullUrl(patient.getIdElement().getValue()); + bundleEntry4.setResource(patient); + + bundleEnteries.add(bundleEntry1); + bundleEnteries.add(bundleEntry2); + bundleEnteries.add(bundleEntry3); + bundleEnteries.add(bundleEntry4); + + for (Observation obsVital : observationVitalList) { + BundleEntryComponent bundleEntry5 = new BundleEntryComponent(); + bundleEntry5.setFullUrl(obsVital.getIdElement().getValue()); + bundleEntry5.setResource(obsVital); + + bundleEnteries.add(bundleEntry5); + } + + wellnessBundle.setEntry(bundleEnteries); + + FhirContext ctx = FhirContext.forR4(); + IParser parser = ctx.newJsonParser(); + serializeBundle = parser.encodeResourceToString(wellnessBundle); + + } catch (Exception e) { + throw new FHIRException("Wellness FHIR Resource Bundle failed with error - " + e); + } + + return serializeBundle; + } + + @Override + public Composition PopulateWellnessRecordComposition(ResourceRequestHandler resourceRequestHandler, + PatientEligibleForResourceCreation p, Practitioner practitioner, Organization organization, + List observationVitalList) { + Composition comp = new Composition(); + comp.setId("Composition/" + commonService.getUUID()); + + // Composition.meta – bind WellnessRecord profile + Meta meta = new Meta(); + meta.setVersionId("1"); + meta.addProfile("https://nrces.in/ndhm/fhir/r4/StructureDefinition/WellnessRecord"); + comp.setMeta(meta); + + comp.setStatus(Composition.CompositionStatus.FINAL); + + CodeableConcept type = new CodeableConcept(); + type.setText("Wellness Record"); + comp.setType(type); + + comp.setSubject(new Reference("Patient/" + p.getBeneficiaryId().toString())); + comp.setDate(new Date()); + + comp.addAuthor(new Reference(practitioner.getIdElement().getValue())); + comp.setCustodian(new Reference(organization.getIdElement().getValue())); + comp.setTitle("Wellness Record"); + + Composition.SectionComponent vitalSignsSection = new Composition.SectionComponent(); + vitalSignsSection.setTitle("Vital Signs"); + + Composition.SectionComponent bodyMeasurementSection = new Composition.SectionComponent(); + bodyMeasurementSection.setTitle("Body Measurement"); + + if (observationVitalList.size() > 0) { + for (Observation obs : observationVitalList) { + String label = (obs.getCode() != null) ? obs.getCode().getText() : null; + + // Create reference for bundle entry + Reference ref = new Reference(); + ref.setReference(obs.getIdElement().getValue()); + ref.setType("Observation"); + + if (isVitalSignLabel(label)) { + vitalSignsSection.addEntry(ref); + } else if (isBodyMeasurementLabel(label)) { + bodyMeasurementSection.addEntry(ref); + } else { + vitalSignsSection.addEntry(ref); + } + } + } + + // Add sections only if they have entries + if (vitalSignsSection.hasEntry()) { + comp.addSection(vitalSignsSection); + } + if (bodyMeasurementSection.hasEntry()) { + comp.addSection(bodyMeasurementSection); + } + + return comp; + } + + private boolean isVitalSignLabel(String label) { + if (label == null) + return false; + String s = label.trim().toLowerCase(); + return s.equals("body temperature") || s.equals("pulse rate") || s.equals("respiratory rate") + || s.equals("systolic blood pressure") || s.equals("diastolic blood pressure"); + } + + private boolean isBodyMeasurementLabel(String label) { + if (label == null) + return false; + String s = label.trim().toLowerCase(); + return s.equals("body height") || s.equals("body weight") || s.equals("body mass index"); + } + + private AMRIT_ResourceMongo createPrescriptionBundleMongo(PatientEligibleForResourceCreation p, + String wellnessBundle) { + AMRIT_ResourceMongo aMRIT_ResourceMongo = new AMRIT_ResourceMongo(); + aMRIT_ResourceMongo.setBeneficiaryID(p.getBeneficiaryId()); + aMRIT_ResourceMongo.setBeneficiaryRegID(p.getBeneficiaryRegID()); + // get ABHA from table "m_benhealthmapping" for this visit(visit code) + if (p.getVisitCode() != null) { + aMRIT_ResourceMongo.setVisitCode(p.getVisitCode()); + List objArrResultSet = benHealthIDMappingRepo.getLinkedHealthIDForVisit(p.getVisitCode()); + if (objArrResultSet != null && objArrResultSet.size() > 0) { + aMRIT_ResourceMongo.setNationalHealthID(objArrResultSet.get(0)); + } + } + + aMRIT_ResourceMongo.setResourceJson(wellnessBundle); + aMRIT_ResourceMongo.setResourceType("WellnessRecord"); + + return aMRIT_ResourceMongo; + } + +} diff --git a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java index c0b23dc..2ddbc36 100644 --- a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java @@ -64,7 +64,6 @@ import com.wipro.fhir.data.patient_data_handler.PatientDemographicModel_NDHM_Patient_Profile; import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; import com.wipro.fhir.data.request_handler.ResourceRequestHandler; -import com.wipro.fhir.data.users.User; import com.wipro.fhir.repo.common.PatientEligibleForResourceCreationRepo; import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; import com.wipro.fhir.repo.mongo.amrit_resource.AMRIT_ResourceMongoRepo; @@ -72,13 +71,17 @@ import com.wipro.fhir.repo.mongo.amrit_resource.TempCollectionRepo; import com.wipro.fhir.repo.mongo.ndhm_response.NDHMResponseRepo; import com.wipro.fhir.repo.patient_data_handler.PatientDemographicModel_NDHM_Patient_Profile_Repo; +import com.wipro.fhir.repo.v3.careContext.CareContextRepo; import com.wipro.fhir.service.api_channel.APIChannel; +import com.wipro.fhir.service.bundle_creation.DiagnosticRecordResourceBundle; +import com.wipro.fhir.service.bundle_creation.DischargeSummaryResourceBundle; +import com.wipro.fhir.service.bundle_creation.ImmunizationRecordResourceBundle; +import com.wipro.fhir.service.bundle_creation.OPConsultResourceBundle; +import com.wipro.fhir.service.bundle_creation.PrescriptionResourceBundleImpl; +import com.wipro.fhir.service.bundle_creation.WellnessRecordResourceBundle; import com.wipro.fhir.service.ndhm.Common_NDHMService; import com.wipro.fhir.service.ndhm.GenerateSession_NDHMService; import com.wipro.fhir.service.patient_data_handler.PatientDataGatewayService; -import com.wipro.fhir.service.resource_gateway.DiagnosticReportRecord; -import com.wipro.fhir.service.resource_gateway.OPConsultRecordBundle; -import com.wipro.fhir.service.resource_gateway.PrescriptionRecordBundle; import com.wipro.fhir.utils.exception.FHIRException; import com.wipro.fhir.utils.http.HttpUtils; @@ -133,13 +136,6 @@ public class CommonServiceImpl implements CommonService { @Autowired private PatientCareContextsMongoRepo patientCareContextsMongoRepo; - @Autowired - private OPConsultRecordBundle oPConsultRecordBundle; - @Autowired - private PrescriptionRecordBundle prescriptionBundle; - @Autowired - private DiagnosticReportRecord diagnosticReportRecordBundle; - @Autowired private TempCollectionRepo tempCollectionRepo; @Autowired @@ -163,6 +159,27 @@ public class CommonServiceImpl implements CommonService { @Autowired private BenHealthIDMappingRepo benHealthIDMappingRepo; + + @Autowired + private PrescriptionResourceBundleImpl prescriptionResourceBundle; + + @Autowired + private OPConsultResourceBundle oPConsultResourceBundle; + + @Autowired + private DiagnosticRecordResourceBundle diagnosticReportResourceBundle; + + @Autowired + private WellnessRecordResourceBundle wellnessRecordResourceBundle; + + @Autowired + private ImmunizationRecordResourceBundle immunizationRecordResourceBundle; + + @Autowired + private DischargeSummaryResourceBundle dischargeSummaryResourceBundle; + + @Autowired + private CareContextRepo careContextRepo; @Override public String processResourceOperation() throws FHIRException { @@ -209,17 +226,66 @@ public String processResourceOperation() throws FHIRException { } // ---------------------------------------------------------------------------------------------- + + boolean processed = true; + // 1. OP consult resource bundle - int i = oPConsultRecordBundle.processOPConsultRecordBundle(resourceRequestHandler, p); - // 2. diagnostic report record budle - int j = diagnosticReportRecordBundle.processDiagnosticReportRecordBundle(resourceRequestHandler, p); + if (p.getVisitCategory().equalsIgnoreCase("General OPD") + || p.getVisitCategory().equalsIgnoreCase("General OPD (QC)")) { + int opConsult = oPConsultResourceBundle.processOpConsultRecordBundle(resourceRequestHandler, p); + if (opConsult <= 0) + processed = false; + logger.info(" The value of opConsult proceesed: " + processed); + } + + // 2. diagnostic report record bundle + int hasLabTests = careContextRepo.hasLabtestsDone(p.getVisitCode().toString()); + if (hasLabTests > 0) { + int diagReport = diagnosticReportResourceBundle + .processDiagnosticReportRecordBundle(resourceRequestHandler, p); + if (diagReport <= 0) + processed = false; + logger.info(" The value of diagReport proceesed: " + processed); + } + // 3. prescription Bundle - int k = prescriptionBundle.processPrescriptionRecordBundle(resourceRequestHandler, p); + int hasPrescription = careContextRepo.hasPrescribedDrugs(p.getVisitCode().toString()); + if (hasPrescription > 0) { + int presp = prescriptionResourceBundle.processPrescriptionRecordBundle(resourceRequestHandler, p); + if (presp <= 0) + processed = false; + logger.info(" The value of presp proceesed: " + processed); + } + + // 4. wellness Bundle + int hasPhyVitals = careContextRepo.hasPhyVitals(p.getVisitCode().toString()); + if (hasPhyVitals > 0) { + int wellness = wellnessRecordResourceBundle.processWellnessRecordBundle(resourceRequestHandler, p); + if (wellness <= 0) + processed = false; + logger.info(" The value of wellness proceesed: " + processed); + } + + // 5. Immunization record + int hasVaccineDetails = careContextRepo.hasVaccineDetails(p.getVisitCode().toString()); + if (hasVaccineDetails > 0) { + int immunization = immunizationRecordResourceBundle + .processImmunizationRecordBundle(resourceRequestHandler, p); + if (immunization <= 0) + processed = false; + logger.info(" The value of immunization proceesed: " + processed); + } - logger.info("The value of i: " + i + " The value of j: " + j + " The value of k: " + k); + // 6. Discharge Summary + int dischargeSummary = dischargeSummaryResourceBundle + .processDischargeSummaryRecordBundle(resourceRequestHandler, p); + if (dischargeSummary <= 0) + processed = false; + logger.info(" The value of dischargeSummary proceesed: " + processed); - if (i > 0 && j > 0 && k > 0) { + logger.info(" The value of final proceesed: " + processed); + if (processed) { // update the processed flag in trigger table p.setProcessed(true); PatientEligibleForResourceCreation resultSet = patientEligibleForResourceCreationRepo.save(p); diff --git a/src/main/java/com/wipro/fhir/service/resource_gateway/DiagnosticReportRecord.java b/src/main/java/com/wipro/fhir/service/resource_gateway/DiagnosticReportRecord.java deleted file mode 100644 index 01a79bd..0000000 --- a/src/main/java/com/wipro/fhir/service/resource_gateway/DiagnosticReportRecord.java +++ /dev/null @@ -1,36 +0,0 @@ -/* -* AMRIT – Accessible Medical Records via Integrated Technology -* Integrated EHR (Electronic Health Records) Solution -* -* Copyright (C) "Piramal Swasthya Management and Research Institute" -* -* This file is part of AMRIT. -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see https://www.gnu.org/licenses/. -*/ -package com.wipro.fhir.service.resource_gateway; - -import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; -import com.wipro.fhir.data.request_handler.ResourceRequestHandler; -import com.wipro.fhir.utils.exception.FHIRException; - -public interface DiagnosticReportRecord { - - public int processDiagnosticReportRecordBundle(ResourceRequestHandler resourceRequestHandler, - PatientEligibleForResourceCreation p) throws FHIRException; - - public String getDiagnosticReportRecordBundle( ResourceRequestHandler resourceRequestHandler, - PatientEligibleForResourceCreation p) throws FHIRException; - -} diff --git a/src/main/java/com/wipro/fhir/service/resource_gateway/DiagnosticReportRecordImpl.java b/src/main/java/com/wipro/fhir/service/resource_gateway/DiagnosticReportRecordImpl.java deleted file mode 100644 index 32b90b0..0000000 --- a/src/main/java/com/wipro/fhir/service/resource_gateway/DiagnosticReportRecordImpl.java +++ /dev/null @@ -1,260 +0,0 @@ -/* -* AMRIT – Accessible Medical Records via Integrated Technology -* Integrated EHR (Electronic Health Records) Solution -* -* Copyright (C) "Piramal Swasthya Management and Research Institute" -* -* This file is part of AMRIT. -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see https://www.gnu.org/licenses/. -*/ -package com.wipro.fhir.service.resource_gateway; - -import java.sql.Date; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.hl7.fhir.r4.model.Bundle; -import org.hl7.fhir.r4.model.CodeableConcept; -import org.hl7.fhir.r4.model.Coding; -import org.hl7.fhir.r4.model.Composition; -import org.hl7.fhir.r4.model.Composition.CompositionStatus; -import org.hl7.fhir.r4.model.Composition.SectionComponent; -import org.hl7.fhir.r4.model.DiagnosticReport; -import org.hl7.fhir.r4.model.Encounter; -import org.hl7.fhir.r4.model.Identifier; -import org.hl7.fhir.r4.model.Meta; -import org.hl7.fhir.r4.model.Observation; -import org.hl7.fhir.r4.model.Organization; -import org.hl7.fhir.r4.model.Patient; -import org.hl7.fhir.r4.model.Practitioner; -import org.hl7.fhir.r4.model.Reference; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.wipro.fhir.data.mongo.amrit_resource.AMRIT_ResourceMongo; -import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; -import com.wipro.fhir.data.request_handler.ResourceRequestHandler; -import com.wipro.fhir.repo.common.PatientEligibleForResourceCreationRepo; -import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; -import com.wipro.fhir.service.common.CommonService; -import com.wipro.fhir.service.resource_model.AppointmentResource; -import com.wipro.fhir.service.resource_model.ConditionResource; -import com.wipro.fhir.service.resource_model.DiagnosticReportResource; -import com.wipro.fhir.service.resource_model.EncounterResource; -import com.wipro.fhir.service.resource_model.ObservationResource; -import com.wipro.fhir.service.resource_model.OrganizationResource; -import com.wipro.fhir.service.resource_model.PatientResource; -import com.wipro.fhir.service.resource_model.PractitionerResource; -import com.wipro.fhir.utils.exception.FHIRException; - -import ca.uhn.fhir.context.FhirContext; - -@Service -public class DiagnosticReportRecordImpl implements DiagnosticReportRecord { - - @Autowired - private CommonService commonService; - @Autowired - private PatientEligibleForResourceCreationRepo patientEligibleForResourceCreationRepo; - @Autowired - private PatientResource patientResource; - @Autowired - private EncounterResource encounterResource; - @Autowired - private AppointmentResource appointmentResource; - @Autowired - private ConditionResource conditionResource; - @Autowired - private BenHealthIDMappingRepo benHealthIDMappingRepo; - @Autowired - private DiagnosticReportResource diagnosticReportResource; - @Autowired - private ObservationResource observationResource; - - @Override - public int processDiagnosticReportRecordBundle(ResourceRequestHandler resourceRequestHandler, - PatientEligibleForResourceCreation p) throws FHIRException { - int i = 0; - // call method to generate Prescription resource - String diagnosticReportRecordBundle = getDiagnosticReportRecordBundle(resourceRequestHandler, p); - - // call private method to create mongo object with resource data - AMRIT_ResourceMongo aMRIT_ResourceMongo = createDiagnosticReportRecordBundleMongo(p, - diagnosticReportRecordBundle); - // if resource data is not null, save to mongo - if (aMRIT_ResourceMongo != null) { - i = commonService.saveResourceToMongo(aMRIT_ResourceMongo); - - } else - throw new FHIRException("TODO - exception - later will implement"); - - return i; - - } - - @Autowired - PractitionerResource practitionerResource; - @Autowired - OrganizationResource organizationResource; - - @Override - public String getDiagnosticReportRecordBundle(ResourceRequestHandler resourceRequestHandler, - PatientEligibleForResourceCreation p) throws FHIRException { - - Bundle bundle = new Bundle(); - bundle.setType(Bundle.BundleType.DOCUMENT); - bundle.setId(commonService.getUUID()); - // bundle identifier - Identifier identifier = new Identifier(); - identifier.setSystem("https://www.max.in/bundle"); - identifier.setValue(bundle.getId()); - - bundle.setIdentifier(identifier); - bundle.setTimestamp(new Timestamp(System.currentTimeMillis())); - bundle.setMeta(new Meta().setLastUpdated(new Date(System.currentTimeMillis()))); - FhirContext fhirContext = FhirContext.forR4(); - - // practitioner resource - Practitioner practitioner = practitionerResource.getPractitioner(); - - // Organization resource - Organization organization = organizationResource.getOrganization(); - - // Patient resource - Patient patient = patientResource.getPatientResource(resourceRequestHandler); - - // Observation- Physical Examination - vitals - Map> observationMap = observationResource.getObservationLab(patient, - resourceRequestHandler); - - // diagnostic report - List diagnosticResourceList = diagnosticReportResource.getDiagnosticReport(patient, - new Encounter(), resourceRequestHandler, observationMap); - - // composition - Composition composition = getCompositionResourceDiagnosticReport(patient, practitioner, diagnosticResourceList); - - /*** - * bundle addition - */ - - - bundle.addEntry().setFullUrl(composition.getIdElement().getValue()).setResource(composition).getRequest() - .setUrl("composition").setMethod(Bundle.HTTPVerb.POST); - - bundle.addEntry().setFullUrl(practitioner.getIdElement().getValue()).setResource(practitioner).getRequest() - .setUrl("practitioner").setMethod(Bundle.HTTPVerb.POST); - - bundle.addEntry().setFullUrl(organization.getIdElement().getValue()).setResource(organization).getRequest() - .setUrl("organization").setMethod(Bundle.HTTPVerb.POST); - - bundle.addEntry().setFullUrl(patient.getIdElement().getValue()).setResource(patient).getRequest() - .setUrl("Patient").setMethod(Bundle.HTTPVerb.POST); - - for (DiagnosticReport dr : diagnosticResourceList) { - bundle.addEntry().setFullUrl(dr.getIdElement().getValue()).setResource(dr).getRequest() - .setUrl("DiagnosticReport").setMethod(Bundle.HTTPVerb.POST); - } - - List tempList = new ArrayList<>(); - if (observationMap != null && observationMap.size() > 0) { - for (Entry> entry : observationMap.entrySet()) { - for (Observation observation : entry.getValue()) { - tempList.add(observation); - - bundle.addEntry().setFullUrl(observation.getIdElement().getValue()).setResource(observation) - .getRequest().setUrl("DiagnosticReport").setMethod(Bundle.HTTPVerb.POST); - } - } - - } - - return fhirContext.newJsonParser().setPrettyPrint(true).encodeResourceToString(bundle); - } - - private Composition getCompositionResourceDiagnosticReport(Patient patient, Practitioner practitioner, - List diagnosticReportList) { - - Composition composition = new Composition(); - composition.setId("Composition/" + commonService.getUUID()); - composition.setStatus(CompositionStatus.FINAL); - composition.setSubject(new Reference(patient.getId())); - composition.setDate(new Date(System.currentTimeMillis())); - composition.setTitle("Diagnostic Report- Lab"); - // bundle identifier - Identifier identifier = new Identifier(); - identifier.setSystem("https://ndhm.in/phr"); - identifier.setValue(composition.getId()); - composition.setIdentifier(identifier); - - CodeableConcept cc = new CodeableConcept(); - Coding c = new Coding(); - c.setCode("721981007"); - c.setDisplay("Diagnostic studies report"); - c.setSystem("http://snomed.info/sct"); - cc.addCoding(c); - composition.setType(cc); - - composition.addAuthor(new Reference(practitioner.getIdElement().getValue())); - - List scList = new ArrayList<>(); - - // section - // rescription record - SectionComponent sc = new SectionComponent(); - sc.setTitle("Lab Test report"); - CodeableConcept cc1 = new CodeableConcept(); - Coding c1 = new Coding(); - c1.setCode("118246004"); - c1.setDisplay("Laboratory test result"); - c1.setSystem("http://snomed.info/sct"); - cc1.addCoding(c1); - sc.setCode(cc1); - for (DiagnosticReport dr : diagnosticReportList) { - sc.addEntry(new Reference(dr.getId())); - } - - scList.add(sc); - - composition.setSection(scList); - - return composition; - } - - // method to create object to save to mongo DB - private AMRIT_ResourceMongo createDiagnosticReportRecordBundleMongo(PatientEligibleForResourceCreation p, - String diagnosticReportRecordBundle) { - AMRIT_ResourceMongo aMRIT_ResourceMongo = new AMRIT_ResourceMongo(); - aMRIT_ResourceMongo.setBeneficiaryID(p.getBeneficiaryId()); - aMRIT_ResourceMongo.setBeneficiaryRegID(p.getBeneficiaryRegID()); - // get ABHA from table "m_benhealthmapping" for this visit(visit code) - if (p.getVisitCode() != null) { - aMRIT_ResourceMongo.setVisitCode(p.getVisitCode()); - List objArrResultSet = benHealthIDMappingRepo.getLinkedHealthIDForVisit(p.getVisitCode()); - if (objArrResultSet != null && objArrResultSet.size() > 0) { - aMRIT_ResourceMongo.setNationalHealthID(objArrResultSet.get(0)); - } - } - - aMRIT_ResourceMongo.setResourceJson(diagnosticReportRecordBundle); - aMRIT_ResourceMongo.setResourceType("DiagnosticReport"); - - return aMRIT_ResourceMongo; - } - -} diff --git a/src/main/java/com/wipro/fhir/service/resource_gateway/OPConsultRecordBundle.java b/src/main/java/com/wipro/fhir/service/resource_gateway/OPConsultRecordBundle.java deleted file mode 100644 index 12cde47..0000000 --- a/src/main/java/com/wipro/fhir/service/resource_gateway/OPConsultRecordBundle.java +++ /dev/null @@ -1,41 +0,0 @@ -/* -* AMRIT – Accessible Medical Records via Integrated Technology -* Integrated EHR (Electronic Health Records) Solution -* -* Copyright (C) "Piramal Swasthya Management and Research Institute" -* -* This file is part of AMRIT. -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see https://www.gnu.org/licenses/. -*/ -package com.wipro.fhir.service.resource_gateway; - -import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; -import com.wipro.fhir.data.request_handler.ResourceRequestHandler; -import com.wipro.fhir.utils.exception.FHIRException; - -/*** - * - * @author NE298657 - * - */ - -public interface OPConsultRecordBundle { - - public String getOPConsultRecordBundle(ResourceRequestHandler resourceRequestHandler, - PatientEligibleForResourceCreation p) throws FHIRException; - - public int processOPConsultRecordBundle(ResourceRequestHandler resourceRequestHandler, - PatientEligibleForResourceCreation p) throws FHIRException; -} diff --git a/src/main/java/com/wipro/fhir/service/resource_gateway/OPConsultRecordBundleImpl.java b/src/main/java/com/wipro/fhir/service/resource_gateway/OPConsultRecordBundleImpl.java deleted file mode 100644 index 81eb7e9..0000000 --- a/src/main/java/com/wipro/fhir/service/resource_gateway/OPConsultRecordBundleImpl.java +++ /dev/null @@ -1,297 +0,0 @@ -/* -* AMRIT – Accessible Medical Records via Integrated Technology -* Integrated EHR (Electronic Health Records) Solution -* -* Copyright (C) "Piramal Swasthya Management and Research Institute" -* -* This file is part of AMRIT. -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see https://www.gnu.org/licenses/. -*/ -package com.wipro.fhir.service.resource_gateway; - -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.hl7.fhir.r4.model.AllergyIntolerance; -import org.hl7.fhir.r4.model.Appointment; -import org.hl7.fhir.r4.model.Bundle; -import org.hl7.fhir.r4.model.Composition; -import org.hl7.fhir.r4.model.Condition; -import org.hl7.fhir.r4.model.Encounter; -import org.hl7.fhir.r4.model.Identifier; -import org.hl7.fhir.r4.model.Meta; -import org.hl7.fhir.r4.model.Observation; -import org.hl7.fhir.r4.model.Organization; -import org.hl7.fhir.r4.model.Patient; -import org.hl7.fhir.r4.model.Practitioner; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.wipro.fhir.data.mongo.amrit_resource.AMRIT_ResourceMongo; -import com.wipro.fhir.data.mongo.amrit_resource.TempCollection; -import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; -import com.wipro.fhir.data.request_handler.ResourceRequestHandler; -import com.wipro.fhir.repo.common.PatientEligibleForResourceCreationRepo; -import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; -import com.wipro.fhir.service.common.CommonService; -import com.wipro.fhir.service.resource_model.AllergyIntoleranceResource; -import com.wipro.fhir.service.resource_model.AppointmentResource; -import com.wipro.fhir.service.resource_model.CompositionResource; -import com.wipro.fhir.service.resource_model.ConditionResource; -import com.wipro.fhir.service.resource_model.EncounterResource; -import com.wipro.fhir.service.resource_model.FamilyMemberHistoryResource; -import com.wipro.fhir.service.resource_model.ObservationResource; -import com.wipro.fhir.service.resource_model.OrganizationResource; -import com.wipro.fhir.service.resource_model.PatientResource; -import com.wipro.fhir.service.resource_model.PractitionerResource; -import com.wipro.fhir.utils.exception.FHIRException; - -import ca.uhn.fhir.context.FhirContext; - -/*** - * - * @author NE298657 - * - */ - -@Service -public class OPConsultRecordBundleImpl implements OPConsultRecordBundle { - - Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - - @Autowired - private CommonService commonService; - @Autowired - private PatientResource patientResource; - @Autowired - private AllergyIntoleranceResource allergyIntoleranceResource; - @Autowired - private AppointmentResource appointmentResource; - @Autowired - private ConditionResource conditionResource; - @Autowired - private EncounterResource encounterResource; - @Autowired - private FamilyMemberHistoryResource familyMemberHistoryResource; - @Autowired - private BenHealthIDMappingRepo benHealthIDMappingRepo; - @Autowired - private PatientEligibleForResourceCreationRepo patientEligibleForResourceCreationRepo; - @Autowired - private ObservationResource observationResource; - @Autowired - private PractitionerResource practitionerResource; - @Autowired - private OrganizationResource organizationResource; - @Autowired - private CompositionResource compositionResource; - - @Override - public int processOPConsultRecordBundle(ResourceRequestHandler resourceRequestHandler, - PatientEligibleForResourceCreation p) throws FHIRException { - int i = 0; - // call method to generate OP_consult resource - String opConsultRecordBundle = getOPConsultRecordBundle(resourceRequestHandler, p); - - // call private method to create mongo object with resource data - AMRIT_ResourceMongo aMRIT_ResourceMongo = createOPConsultRecordBundleMongo(p, opConsultRecordBundle); - // if resource data is not null, save to mongo - if (aMRIT_ResourceMongo != null) { - - i = commonService.saveResourceToMongo(aMRIT_ResourceMongo); - - } else - throw new FHIRException("TODO - exception - later will implement"); - - return i; - - } - - @Override - public String getOPConsultRecordBundle(ResourceRequestHandler resourceRequestHandler, - PatientEligibleForResourceCreation p) throws FHIRException { - Bundle bundle = new Bundle(); - - // bundle type - document - bundle.setType(Bundle.BundleType.DOCUMENT); - // bundle id - bundle.setId(commonService.getUUID()); - - // bundle identifier - Identifier identifier = new Identifier(); - identifier.setSystem("https://www.max.in/bundle"); - identifier.setValue(bundle.getId()); - - bundle.setIdentifier(identifier); - - // timestamp - bundle.setTimestamp(new Timestamp(System.currentTimeMillis())); - bundle.setMeta(new Meta().setLastUpdated(new Date(System.currentTimeMillis()))); - - FhirContext fhirContext = FhirContext.forR4(); - - // practitioner resource - Practitioner practitioner = practitionerResource.getPractitioner(); - - // Organization resource - Organization organization = organizationResource.getOrganization(); - - // Patient resource - Patient patient = patientResource.getPatientResource(resourceRequestHandler); - - // Appointment resource - Appointment appointment = appointmentResource.getAppointmentResource(resourceRequestHandler, practitioner); - - // Condition resource, chiefcomplaints - List conditionListChiefComplaints = conditionResource.getCondition(patient, resourceRequestHandler, - "chiefcomplaints"); - - // Condition resource, diagnosis - List conditionListDiagnosis = conditionResource.getCondition(patient, resourceRequestHandler, - "diagnosis"); - - // FamilyMemberHistory resource -/// FamilyMemberHistory familyMemberHistory = familyMemberHistoryResource.getFamilyMemberHistory(patient, -/// resourceRequestHandler); - - // Encounter resource - Encounter encounter = encounterResource.getEncounterResource(patient, appointment, resourceRequestHandler, - conditionListChiefComplaints, conditionListDiagnosis); - - // AllergyIntolerance resource - List allergyList = allergyIntoleranceResource.getAllergyIntolerance(patient, encounter, - resourceRequestHandler, practitioner); - - // Observation- Physical Examination - vitals - List observationVitalList = observationResource.getObservationVitals(patient, encounter, - resourceRequestHandler); - - - - // Composition resource - Composition composition = compositionResource.getComposition(patient, encounter, allergyList, appointment, - conditionListChiefComplaints, conditionListDiagnosis, observationVitalList); - - /*** - * add resource to bundle - */ - - // composition - bundle.addEntry().setFullUrl(composition.getIdElement().getValue()).setResource(composition).getRequest() - .setUrl("Composition").setMethod(Bundle.HTTPVerb.POST); - - // practitioner - bundle.addEntry().setFullUrl(practitioner.getIdElement().getValue()).setResource(practitioner).getRequest() - .setUrl("Practitioner").setMethod(Bundle.HTTPVerb.POST); - - // organization - bundle.addEntry().setFullUrl(organization.getIdElement().getValue()).setResource(organization).getRequest() - .setUrl("Organization").setMethod(Bundle.HTTPVerb.POST); - - // patient - bundle.addEntry().setFullUrl(patient.getIdElement().getValue()).setResource(patient).getRequest() - .setUrl("Patient").setMethod(Bundle.HTTPVerb.POST); - - // appointment - bundle.addEntry().setFullUrl(appointment.getIdElement().getValue()).setResource(appointment).getRequest() - .setUrl("appointmentResource").setMethod(Bundle.HTTPVerb.POST); - - // condition - chief complaints - for (Condition condition : conditionListChiefComplaints) { - bundle.addEntry().setFullUrl(condition.getIdElement().getValue()).setResource(condition).getRequest() - .setUrl("Condition").setMethod(Bundle.HTTPVerb.POST); - } - - // condition - diagnosis - for (Condition condition : conditionListDiagnosis) { - bundle.addEntry().setFullUrl(condition.getIdElement().getValue()).setResource(condition).getRequest() - .setUrl("Condition").setMethod(Bundle.HTTPVerb.POST); - } - - // observation - for (Observation obsr : observationVitalList) { - bundle.addEntry().setFullUrl(obsr.getIdElement().getValue()).setResource(obsr).getRequest() - .setUrl("Observation").setMethod(Bundle.HTTPVerb.POST); - } - - // allergy - for (AllergyIntolerance allergyResource : allergyList) { - bundle.addEntry().setFullUrl(allergyResource.getIdElement().getValue()).setResource(allergyResource) - .getRequest().setUrl("AllergyIntolerance").setMethod(Bundle.HTTPVerb.POST); - } - - - bundle.addEntry().setFullUrl(encounter.getIdElement().getValue()).setResource(encounter).getRequest() - .setUrl("Encounter").setMethod(Bundle.HTTPVerb.POST); - - return fhirContext.newJsonParser().setPrettyPrint(true).encodeResourceToString(bundle); - } - - // method to create object to save to mongo DB - private AMRIT_ResourceMongo createOPConsultRecordBundleMongo(PatientEligibleForResourceCreation p, - String opConsultRecordBundle) { - AMRIT_ResourceMongo aMRIT_ResourceMongo = new AMRIT_ResourceMongo(); - aMRIT_ResourceMongo.setBeneficiaryID(p.getBeneficiaryId()); - aMRIT_ResourceMongo.setBeneficiaryRegID(p.getBeneficiaryRegID()); - // get ABHA from table "m_benhealthmapping" for this visit(visit code) - if (p.getVisitCode() != null) { - aMRIT_ResourceMongo.setVisitCode(p.getVisitCode()); - List objArrResultSet = benHealthIDMappingRepo.getLinkedHealthIDForVisit(p.getVisitCode()); - if (objArrResultSet != null && objArrResultSet.size() > 0) { - aMRIT_ResourceMongo.setNationalHealthID(objArrResultSet.get(0)); - } - } - - aMRIT_ResourceMongo.setResourceJson(opConsultRecordBundle); - aMRIT_ResourceMongo.setResourceType("OPConsultation"); - - return aMRIT_ResourceMongo; - } - - @Deprecated - private TempCollection createTempCollectionOBJ(Map> observationMap, - ResourceRequestHandler rrh) { - - Map> tempMap = new HashMap>(); - List tempList; - - TempCollection tempCollection = new TempCollection(); - tempCollection.setBeneficiaryRegID(rrh.getBeneficiaryRegID()); - tempCollection.setVisitCode(rrh.getVisitCode()); - tempCollection.setDataType("observationResourceMap"); - - for (Map.Entry> entry : observationMap.entrySet()) { - if (entry.getValue().size() > 0) { - tempList = new ArrayList<>(); - for (Observation o : entry.getValue()) { - tempList.add(o.getId()); - } - tempMap.put(entry.getKey(), tempList); - } - } - - tempCollection.setDataJson(tempMap); - tempCollection.setCreateDate(new Date(System.currentTimeMillis())); - tempCollection.setCreateBy("default"); - return tempCollection; - } - -} diff --git a/src/main/java/com/wipro/fhir/service/resource_gateway/PrescriptionRecordBundle.java b/src/main/java/com/wipro/fhir/service/resource_gateway/PrescriptionRecordBundle.java deleted file mode 100644 index 97163a2..0000000 --- a/src/main/java/com/wipro/fhir/service/resource_gateway/PrescriptionRecordBundle.java +++ /dev/null @@ -1,34 +0,0 @@ -/* -* AMRIT – Accessible Medical Records via Integrated Technology -* Integrated EHR (Electronic Health Records) Solution -* -* Copyright (C) "Piramal Swasthya Management and Research Institute" -* -* This file is part of AMRIT. -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see https://www.gnu.org/licenses/. -*/ -package com.wipro.fhir.service.resource_gateway; - -import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; -import com.wipro.fhir.data.request_handler.ResourceRequestHandler; -import com.wipro.fhir.utils.exception.FHIRException; - -public interface PrescriptionRecordBundle { - public int processPrescriptionRecordBundle(ResourceRequestHandler resourceRequestHandler, - PatientEligibleForResourceCreation p) throws FHIRException; - - public String getPrescriptionRecordBundle(ResourceRequestHandler resourceRequestHandler, - PatientEligibleForResourceCreation p) throws FHIRException; -} diff --git a/src/main/java/com/wipro/fhir/service/resource_gateway/PrescriptionRecordBundleImpl.java b/src/main/java/com/wipro/fhir/service/resource_gateway/PrescriptionRecordBundleImpl.java deleted file mode 100644 index 4ac9ea4..0000000 --- a/src/main/java/com/wipro/fhir/service/resource_gateway/PrescriptionRecordBundleImpl.java +++ /dev/null @@ -1,238 +0,0 @@ -/* -* AMRIT – Accessible Medical Records via Integrated Technology -* Integrated EHR (Electronic Health Records) Solution -* -* Copyright (C) "Piramal Swasthya Management and Research Institute" -* -* This file is part of AMRIT. -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see https://www.gnu.org/licenses/. -*/ -package com.wipro.fhir.service.resource_gateway; - -import java.sql.Date; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.List; - -import org.hl7.fhir.r4.model.Bundle; -import org.hl7.fhir.r4.model.CodeableConcept; -import org.hl7.fhir.r4.model.Coding; -import org.hl7.fhir.r4.model.Composition; -import org.hl7.fhir.r4.model.Composition.CompositionStatus; -import org.hl7.fhir.r4.model.Composition.SectionComponent; -import org.hl7.fhir.r4.model.Condition; -import org.hl7.fhir.r4.model.Identifier; -import org.hl7.fhir.r4.model.MedicationRequest; -import org.hl7.fhir.r4.model.Meta; -import org.hl7.fhir.r4.model.Organization; -import org.hl7.fhir.r4.model.Patient; -import org.hl7.fhir.r4.model.Practitioner; -import org.hl7.fhir.r4.model.Reference; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.wipro.fhir.data.mongo.amrit_resource.AMRIT_ResourceMongo; -import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; -import com.wipro.fhir.data.request_handler.ResourceRequestHandler; -import com.wipro.fhir.repo.common.PatientEligibleForResourceCreationRepo; -import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; -import com.wipro.fhir.service.common.CommonService; -import com.wipro.fhir.service.resource_model.AppointmentResource; -import com.wipro.fhir.service.resource_model.ConditionResource; -import com.wipro.fhir.service.resource_model.EncounterResource; -import com.wipro.fhir.service.resource_model.MedicationRequestResource; -import com.wipro.fhir.service.resource_model.OrganizationResource; -import com.wipro.fhir.service.resource_model.PatientResource; -import com.wipro.fhir.service.resource_model.PractitionerResource; -import com.wipro.fhir.utils.exception.FHIRException; - -import ca.uhn.fhir.context.FhirContext; - -@Service -public class PrescriptionRecordBundleImpl implements PrescriptionRecordBundle { - @Autowired - private PatientResource patientResource; - @Autowired - private EncounterResource encounterResource; - @Autowired - private AppointmentResource appointmentResource; - @Autowired - private ConditionResource conditionResource; - @Autowired - private CommonService commonService; - @Autowired - private PatientEligibleForResourceCreationRepo patientEligibleForResourceCreationRepo; - @Autowired - private BenHealthIDMappingRepo benHealthIDMappingRepo; - @Autowired - private MedicationRequestResource medicationRequestResource; - @Autowired - private PractitionerResource practitionerResource; - @Autowired - private OrganizationResource organizationResource; - - @Override - public int processPrescriptionRecordBundle(ResourceRequestHandler resourceRequestHandler, - PatientEligibleForResourceCreation p) throws FHIRException { - int i = 0; - // call method to generate Prescription resource - String prescriptionRecordBundle = getPrescriptionRecordBundle(resourceRequestHandler, p); - - // call private method to create mongo object with resource data - AMRIT_ResourceMongo aMRIT_ResourceMongo = createPrescriptionRecordBundleMongo(p, prescriptionRecordBundle); - // if resource data is not null, save to mongo - if (aMRIT_ResourceMongo != null) { - i = commonService.saveResourceToMongo(aMRIT_ResourceMongo); - - } else - throw new FHIRException("TODO - exception - later will implement"); - - return i; - - } - - public String getPrescriptionRecordBundle(ResourceRequestHandler resourceRequestHandler, - PatientEligibleForResourceCreation p) throws FHIRException { - - Bundle bundle = new Bundle(); - bundle.setType(Bundle.BundleType.DOCUMENT); - // bundle id - bundle.setId(commonService.getUUID()); - - // bundle identifier - Identifier identifier = new Identifier(); - identifier.setSystem("https://www.max.in/bundle"); - identifier.setValue(bundle.getId()); - - bundle.setIdentifier(identifier); - - // timestamp - bundle.setTimestamp(new Timestamp(System.currentTimeMillis())); - bundle.setMeta(new Meta().setLastUpdated(new Date(System.currentTimeMillis()))); - FhirContext fhirContext = FhirContext.forR4(); - // practitioner - Practitioner practitioner = practitionerResource.getPractitioner(); - // organization - Organization organization = organizationResource.getOrganization(); - // 1. Patient Resource - Patient patient = patientResource.getPatientResource(resourceRequestHandler); - // 3. Condition resource - List condition = conditionResource.getCondition(patient, resourceRequestHandler, "diagnosis"); - // Medication request - List medicationRequest = medicationRequestResource.getMedicationRequest(patient, - resourceRequestHandler, practitioner, condition); - // composition - Composition composition = getCompositionResourcePrescription(patient, medicationRequest, practitioner); - - /*** - * adding into bundle - */ - - // composition - bundle.addEntry().setFullUrl(composition.getIdElement().getValue()).setResource(composition).getRequest() - .setUrl("Composition").setMethod(Bundle.HTTPVerb.POST); - // practitioner - bundle.addEntry().setFullUrl(organization.getIdElement().getValue()).setResource(organization).getRequest() - .setUrl("Practitioner").setMethod(Bundle.HTTPVerb.POST); - // organization - bundle.addEntry().setFullUrl(practitioner.getIdElement().getValue()).setResource(practitioner).getRequest() - .setUrl("Organization").setMethod(Bundle.HTTPVerb.POST); - // patient - bundle.addEntry().setFullUrl(patient.getIdElement().getValue()).setResource(patient).getRequest() - .setUrl("Patient").setMethod(Bundle.HTTPVerb.POST); - // medication request - for (MedicationRequest med : medicationRequest) { - bundle.addEntry().setFullUrl(med.getIdElement().getValue()).setResource(med).getRequest() - .setUrl("MedicationRequest").setMethod(Bundle.HTTPVerb.POST); - } - - // condition - for (Condition cond : condition) { - bundle.addEntry().setFullUrl(cond.getIdElement().getValue()).setResource(cond).getRequest() - .setUrl("Condition").setMethod(Bundle.HTTPVerb.POST); - } - - return fhirContext.newJsonParser().setPrettyPrint(true).encodeResourceToString(bundle); - } - - // method to create object to save to mongo DB - private AMRIT_ResourceMongo createPrescriptionRecordBundleMongo(PatientEligibleForResourceCreation p, - String prescriptionRecordBundle) { - AMRIT_ResourceMongo aMRIT_ResourceMongo = new AMRIT_ResourceMongo(); - aMRIT_ResourceMongo.setBeneficiaryID(p.getBeneficiaryId()); - aMRIT_ResourceMongo.setBeneficiaryRegID(p.getBeneficiaryRegID()); - // get ABHA from table "m_benhealthmapping" for this visit(visit code) - if (p.getVisitCode() != null) { - aMRIT_ResourceMongo.setVisitCode(p.getVisitCode()); - List objArrResultSet = benHealthIDMappingRepo.getLinkedHealthIDForVisit(p.getVisitCode()); - if (objArrResultSet != null && objArrResultSet.size() > 0) { - aMRIT_ResourceMongo.setNationalHealthID(objArrResultSet.get(0)); - } - } - - aMRIT_ResourceMongo.setResourceJson(prescriptionRecordBundle); - aMRIT_ResourceMongo.setResourceType("Prescription"); - - return aMRIT_ResourceMongo; - } - - private Composition getCompositionResourcePrescription(Patient patient, List medication, - Practitioner practitioner) { - Composition composition = new Composition(); - composition.setId("Composition/" + commonService.getUUID()); - composition.setStatus(CompositionStatus.FINAL); - composition.setSubject(new Reference(patient.getId())); - composition.setDate(new Date(System.currentTimeMillis())); - composition.setTitle("Prescription Document"); - // bundle identifier - Identifier identifier = new Identifier(); - identifier.setSystem("https://ndhm.in/phr"); - identifier.setValue(composition.getId()); - composition.setIdentifier(identifier); - - CodeableConcept cc = new CodeableConcept(); - Coding c = new Coding(); - c.setCode("440545006"); - c.setDisplay("Prescription record"); - c.setSystem("http://snomed.info/sct"); - cc.addCoding(c); - composition.setType(cc); - - composition.addAuthor(new Reference(practitioner.getIdElement().getValue())); - - List scList = new ArrayList<>(); - - // section - // rescription record - SectionComponent sc = new SectionComponent(); - sc.setTitle("Prescription record"); - CodeableConcept cc1 = new CodeableConcept(); - Coding c1 = new Coding(); - c1.setCode("440545006"); - c1.setDisplay("Prescription record"); - c1.setSystem("http://snomed.info/sct"); - cc1.addCoding(c1); - sc.setCode(cc1); - for (MedicationRequest med : medication) { - sc.addEntry(new Reference(med.getId())); - } - - scList.add(sc); - - composition.setSection(scList); - - return composition; - } -} diff --git a/src/main/java/com/wipro/fhir/service/resource_model/DiagnosticReportResource.java b/src/main/java/com/wipro/fhir/service/resource_model/DiagnosticReportResource.java index 14e2e82..e3dbbed 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/DiagnosticReportResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/DiagnosticReportResource.java @@ -21,7 +21,6 @@ */ package com.wipro.fhir.service.resource_model; -import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/src/main/java/com/wipro/fhir/service/resource_model/EncounterResource.java b/src/main/java/com/wipro/fhir/service/resource_model/EncounterResource.java index d0f5aa4..645f553 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/EncounterResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/EncounterResource.java @@ -62,20 +62,20 @@ public class EncounterResource { private Encounter encounter; - public Encounter getEncounterResource(Patient patient, Appointment appointment, - ResourceRequestHandler resourceRequestHandler, List conditionListChiefComplaints, + public Encounter getEncounterResource(Patient patient, ResourceRequestHandler resourceRequestHandler, + List conditionListChiefComplaints, List conditionListDiagnosis) { List rsObjList = patientEligibleForResourceCreationRepo .callEncounterSP(resourceRequestHandler.getBeneficiaryRegID(), resourceRequestHandler.getVisitCode()); List encounterList = encounterDataModel.getEncounterList(rsObjList); - return generateEncounterResource(patient, appointment, encounterList, conditionListChiefComplaints, + return generateEncounterResource(patient, encounterList, conditionListChiefComplaints, conditionListDiagnosis); } - private Encounter generateEncounterResource(Patient patient, Appointment appointment, - List encounterList, List conditionListChiefComplaints, + private Encounter generateEncounterResource(Patient patient, List encounterList, + List conditionListChiefComplaints, List conditionListDiagnosis) { encounter = new Encounter(); diff --git a/src/main/java/com/wipro/fhir/service/resource_model/ImmunizationResource.java b/src/main/java/com/wipro/fhir/service/resource_model/ImmunizationResource.java new file mode 100644 index 0000000..bc551d0 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/resource_model/ImmunizationResource.java @@ -0,0 +1,103 @@ +package com.wipro.fhir.service.resource_model; + +import java.util.ArrayList; +import java.util.List; + +import org.hl7.fhir.r4.model.Annotation; +import org.hl7.fhir.r4.model.CodeableConcept; +import org.hl7.fhir.r4.model.Coding; +import org.hl7.fhir.r4.model.DateTimeType; +import org.hl7.fhir.r4.model.Immunization; +import org.hl7.fhir.r4.model.Patient; +import org.hl7.fhir.r4.model.Reference; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.data.resource_model.ImmunizationDataModel; +import com.wipro.fhir.repo.common.PatientEligibleForResourceCreationRepo; +import com.wipro.fhir.service.common.CommonService; +import com.wipro.fhir.utils.exception.FHIRException; + +@Service +public class ImmunizationResource { + + @Autowired + private CommonService commonService; + + @Autowired + private ImmunizationDataModel immunizationDataModel; + + @Autowired + private PatientEligibleForResourceCreationRepo patientEligibleForResourceCreationRepo; + + public List getImmunizations(Patient patient, ResourceRequestHandler resourceRequestHandler) + throws FHIRException { + + List rsObjList = patientEligibleForResourceCreationRepo.callImmunizationSP( + resourceRequestHandler.getBeneficiaryRegID(), resourceRequestHandler.getVisitCode()); + + List immunizationList = immunizationDataModel.getImmunizationList(rsObjList); + + // Build FHIR Immunization resources + return generateImmunizationResource(patient, immunizationList); + } + + private List generateImmunizationResource(Patient patient, List imList) { + + List immResourceList = new ArrayList<>(); + + int index = 0; + for (ImmunizationDataModel im : imList) { + index++; + + Immunization immune = new Immunization(); + + // Id style similar to your MedicationStatement example + immune.setId("Immunization-" + index + "/" + commonService.getUUID()); + + // Subject (patient) + immune.setPatient(new Reference(patient.getIdElement().getValue())); + + // NRCeS Immunization profile + immune.getMeta().addProfile("https://nrces.in/ndhm/fhir/r4/StructureDefinition/Immunization"); + + // Status (completed if we have a receivedDate, otherwise not-done) + if (im.getReceivedDate() != null) { + immune.setStatus(Immunization.ImmunizationStatus.COMPLETED); + immune.setOccurrence(new DateTimeType(im.getReceivedDate())); + } else { + // If you prefer to exclude not-done, comment the next line and add a + // `continue;` + immune.setStatus(Immunization.ImmunizationStatus.NOTDONE); + } + + // Vaccine code: prefer SNOMED if provided, else text fallback + CodeableConcept vaccineCC = new CodeableConcept(); + if (im.getSctcode() != null && !im.getSctcode().isEmpty()) { + vaccineCC.addCoding(new Coding().setSystem("http://snomed.info/sct").setCode(im.getSctcode()) + .setDisplay(im.getSctTerm() != null ? im.getSctTerm() : im.getVaccineName())); + } + // Always set text for human readability + vaccineCC.setText(im.getVaccineName()); + immune.setVaccineCode(vaccineCC); + + if (im.getCreatedDate() != null) { + immune.setRecorded(im.getCreatedDate()); + } + + // Optional free-text notes for age schedule and facility + if (im.getDefaultReceivingAge() != null && !im.getDefaultReceivingAge().isEmpty()) { + immune.addNote(new Annotation().setText("Schedule: " + im.getDefaultReceivingAge())); + } + if (im.getReceivedFacilityName() != null && !im.getReceivedFacilityName().isEmpty()) { + immune.addNote(new Annotation().setText("Facility: " + im.getReceivedFacilityName())); + } + + immResourceList.add(immune); + } + + return immResourceList; + } + +} diff --git a/src/main/java/com/wipro/fhir/service/resource_model/MedicalHistoryResource.java b/src/main/java/com/wipro/fhir/service/resource_model/MedicalHistoryResource.java new file mode 100644 index 0000000..1729229 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/resource_model/MedicalHistoryResource.java @@ -0,0 +1,73 @@ +package com.wipro.fhir.service.resource_model; + +import java.util.ArrayList; +import java.util.List; + +import org.hl7.fhir.r4.model.CodeableConcept; +import org.hl7.fhir.r4.model.Coding; +import org.hl7.fhir.r4.model.MedicationStatement; +import org.hl7.fhir.r4.model.Patient; +import org.hl7.fhir.r4.model.Reference; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.data.resource_model.MedicalHistoryDataModel; +import com.wipro.fhir.repo.common.PatientEligibleForResourceCreationRepo; +import com.wipro.fhir.service.common.CommonService; + +@Service +public class MedicalHistoryResource { + + @Autowired + private CommonService commonService; + @Autowired + private MedicalHistoryDataModel medicalHistoryDataModel; + + @Autowired + private PatientEligibleForResourceCreationRepo patientEligibleForResourceCreationRepo; + + public List getMedicalHistory(Patient patient, ResourceRequestHandler resourceRequestHandler) { + + List rsObjList = patientEligibleForResourceCreationRepo.callMedicalHistorySp(resourceRequestHandler.getVisitCode()); + + List medicalList = medicalHistoryDataModel.getMedicalList(rsObjList); + + return generateMedicalHistoryResource(patient, medicalList); + + } + + private List generateMedicalHistoryResource(Patient patient, List msList) { + + List msResourceList = new ArrayList<>(); + + // For every medication entry, create a new MedicationStatement and add to list + int index = 0; + for(MedicalHistoryDataModel med: msList) { + index++; + + MedicationStatement ms = new MedicationStatement(); + + ms.setId("MedicationRequest-" + index + "/" + commonService.getUUID()); + ms.setSubject(new Reference(patient.getIdElement().getValue())); + + ms.getMeta().addProfile("https://nrces.in/ndhm/fhir/r4/StructureDefinition/MedicationStatement"); + ms.setStatus(MedicationStatement.MedicationStatementStatus.COMPLETED); + + CodeableConcept medCC = new CodeableConcept(); + medCC.addCoding(new Coding() + .setSystem("http://snomed.info/sct") + .setCode(" ") + .setDisplay(med.getCurrentMedication())); // scts code so kept only the name + + medCC.setText(med.getCurrentMedication()); + ms.setMedication(medCC); + ms.setDateAsserted(med.getCreatedDate()); + + msResourceList.add(ms); + } + + return msResourceList; + } + +} diff --git a/src/main/java/com/wipro/fhir/service/resource_model/MedicationRequestResource.java b/src/main/java/com/wipro/fhir/service/resource_model/MedicationRequestResource.java index 26e79e1..1d2bb26 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/MedicationRequestResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/MedicationRequestResource.java @@ -21,7 +21,6 @@ */ package com.wipro.fhir.service.resource_model; -import java.math.BigInteger; import java.sql.Time; import java.util.ArrayList; import java.util.List; @@ -91,14 +90,16 @@ private List generateMedicationRequestResource(Patient patien List conceptList; List ref; + int index = 0; for (MedicationRequestDataModel obj : medicationRequestList) { + index++; medicationRequest = new MedicationRequest(); codeableConcept = new CodeableConcept(); c = new Coding(); cList = new ArrayList<>(); - medicationRequest.setId("MedicationRequest/" + commonService.getUUID()); + medicationRequest.setId("MedicationRequest - " + index + "/" + commonService.getUUID()); medicationRequest.setStatus(MedicationRequestStatus.ACTIVE); medicationRequest.setIntent(MedicationRequestIntent.ORDER); @@ -148,10 +149,12 @@ private List generateMedicationRequestResource(Patient patien // reason conceptList = new ArrayList(); ref = new ArrayList(); + if(conditionDiagnosis != null && conditionDiagnosis.size() > 0) { for (Condition cond : conditionDiagnosis) { ref.add(new Reference(cond.getId())); conceptList.add(cond.getCode()); } + } medicationRequest.setReasonCode(conceptList); medicationRequest.setReasonReference(ref); diff --git a/src/main/java/com/wipro/fhir/service/resource_model/ObservationResource.java b/src/main/java/com/wipro/fhir/service/resource_model/ObservationResource.java index 3bbc7a8..3f8446e 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/ObservationResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/ObservationResource.java @@ -63,8 +63,7 @@ public class ObservationResource { @Autowired private VitalsAnthropometryModel vitalsAnthropometryModel; - public List getObservationVitals(Patient patient, Encounter encounter, - ResourceRequestHandler resourceRequestHandler) { + public List getObservationVitals(Patient patient, ResourceRequestHandler resourceRequestHandler) { List vitals = patientEligibleForResourceCreationRepo.callVitals_AnthropometrySP( resourceRequestHandler.getBeneficiaryRegID(), resourceRequestHandler.getVisitCode()); diff --git a/src/main/java/com/wipro/fhir/service/resource_model/OrganizationResource.java b/src/main/java/com/wipro/fhir/service/resource_model/OrganizationResource.java index 59c7daa..345ee96 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/OrganizationResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/OrganizationResource.java @@ -21,77 +21,87 @@ */ package com.wipro.fhir.service.resource_model; -import java.util.ArrayList; import java.util.List; import org.hl7.fhir.r4.model.Address; -import org.hl7.fhir.r4.model.ContactPoint; -import org.hl7.fhir.r4.model.ContactPoint.ContactPointSystem; import org.hl7.fhir.r4.model.Identifier; import org.hl7.fhir.r4.model.Organization; -import org.hl7.fhir.r4.model.Reference; -import org.hl7.fhir.r4.model.StringType; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.data.resource_model.OrganizationDataModel; +import com.wipro.fhir.repo.common.PatientEligibleForResourceCreationRepo; +import com.wipro.fhir.utils.exception.FHIRException; + @Service public class OrganizationResource { - private Organization organization; + + @Autowired + private PatientEligibleForResourceCreationRepo patientEligibleForResourceCreationRepo; + + @Autowired + private OrganizationDataModel organizationDataModel; + + public Organization getOrganizationResource(ResourceRequestHandler resourceRequestHandler) throws FHIRException { - public Organization getOrganization() { - return generateOrganizationResource(); + List rsObj = patientEligibleForResourceCreationRepo.callOrganizationSp(resourceRequestHandler.getVisitCode()); + OrganizationDataModel orgData = organizationDataModel.getOrganization(rsObj.get(0)); + + if (orgData != null) { + return generateOrganizationResource(orgData); + } else { + throw new FHIRException("Organization not found"); + } } - // generating dummy Practitioner resource - private Organization generateOrganizationResource() { - organization = new Organization(); - - organization.setId("Organization/MaxSaket01"); - organization.setName("Max Super Speciality Hospital, Saket"); - - List aliasList = new ArrayList<>(); - StringType alias = new StringType(); - alias.setValue("Max"); - aliasList.add(alias); - organization.setAlias(aliasList); - - List iList = new ArrayList<>(); - Identifier i = new Identifier(); - i.setSystem("https://facilitysbx.ndhm.gov.in"); - i.setValue("IN0410000183"); - iList.add(i); - organization.setIdentifier(iList); - - List cpList = new ArrayList<>(); - ContactPoint contactPoint = new ContactPoint(); - contactPoint.setSystem(ContactPointSystem.PHONE); - contactPoint.setValue("(+91) 011-2651-5050"); - cpList.add(contactPoint); - - organization.setTelecom(cpList); - - List
addressList = new ArrayList<>(); - Address address = new Address(); - address.setCity("New Delhi"); - address.setState("New Delhi"); - address.setPostalCode("New Delhi"); - address.setCountry("India"); - List addressLineList = new ArrayList<>(); - StringType addLine = new StringType(); - addLine.setValue("1, 2, Press Enclave Marg, Saket Institutional Area, Saket"); - addressLineList.add(addLine); - address.setLine(addressLineList); - addressList.add(address); - - organization.setAddress(addressList); - - List rlist = new ArrayList<>(); - Reference r = new Reference(); - r.setReference("https://www.max.in/hospital-network/max-super-speciality-hospital-saket"); - r.setDisplay("Website"); - rlist.add(r); - organization.setEndpoint(rlist); - - return organization; + +private Organization generateOrganizationResource(OrganizationDataModel orgData) { + + Organization organization = new Organization(); + + organization.setId("Organization/" + orgData.getServiceProviderID()); + + if (orgData.getServiceProviderName() != null) { + organization.setName(orgData.getServiceProviderName()); + } + + // Alias + if (orgData.getLocationName() != null) { + organization.addAlias(orgData.getLocationName()); + } + + // Identifier (ABDM Facility ID) + if (orgData.getAbdmFacilityId() != null) { + Identifier identifier = new Identifier(); + identifier.setSystem("https://facilitysbx.ndhm.gov.in"); + identifier.setValue(orgData.getAbdmFacilityId()); + organization.addIdentifier(identifier); + } + + // Address + Address address = new Address(); + + if (orgData.getAddress() != null) { + address.addLine(orgData.getAddress()); + } + + if (orgData.getDistrictName() != null) { + address.setDistrict(orgData.getDistrictName()); + } + + if (orgData.getStateName() != null) { + address.setState(orgData.getStateName()); + } + + address.setCountry("India"); + + organization.addAddress(address); + + + return organization; } + + } diff --git a/src/main/java/com/wipro/fhir/service/resource_model/PatientResource.java b/src/main/java/com/wipro/fhir/service/resource_model/PatientResource.java index 3731a6e..7309f42 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/PatientResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/PatientResource.java @@ -21,7 +21,6 @@ */ package com.wipro.fhir.service.resource_model; -import java.math.BigInteger; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/com/wipro/fhir/service/resource_model/PractitionerResource.java b/src/main/java/com/wipro/fhir/service/resource_model/PractitionerResource.java index 2f71094..a002b57 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/PractitionerResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/PractitionerResource.java @@ -24,57 +24,119 @@ import java.util.ArrayList; import java.util.List; +import org.hl7.fhir.r4.model.ContactPoint; +import org.hl7.fhir.r4.model.ContactPoint.ContactPointSystem; +import org.hl7.fhir.r4.model.Enumerations.AdministrativeGender; import org.hl7.fhir.r4.model.HumanName; import org.hl7.fhir.r4.model.Identifier; import org.hl7.fhir.r4.model.Practitioner; import org.hl7.fhir.r4.model.StringType; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.data.resource_model.PractitionerDataModel; +import com.wipro.fhir.repo.common.PatientEligibleForResourceCreationRepo; +import com.wipro.fhir.utils.exception.FHIRException; + @Service public class PractitionerResource { - - private Practitioner practitioner; - - public Practitioner getPractitioner() { - return generatePractitionerResource(); - + @Autowired + private PatientEligibleForResourceCreationRepo patientEligibleForResourceCreationRepo; + + @Autowired + private PractitionerDataModel practitionerDataModel; + + @Value("${systemUrl}") + private String systemUrl; + + public Practitioner getPractitionerResource(ResourceRequestHandler resourceRequestHandler) + throws FHIRException { + + List rsObj = patientEligibleForResourceCreationRepo.callPractitionerSP(resourceRequestHandler.getVisitCode()); + + if (rsObj == null || rsObj.isEmpty()) { + throw new FHIRException("invalid practitioner data"); + } + + PractitionerDataModel practitionerData = practitionerDataModel.getPractitioner(rsObj.get(0)); + return generatePractitionerResource(practitionerData); } - - // generating dummy Practitioner resource - private Practitioner generatePractitionerResource() { - practitioner = new Practitioner(); - - practitioner.setId("Practitioner/MAX1456"); - - List iList = new ArrayList<>(); - Identifier i = new Identifier(); - i.setSystem("https://www.mciindia.in/doctor"); - i.setValue("MAX1456"); - iList.add(i); - practitioner.setIdentifier(iList); - - List pNameList = new ArrayList<>(); - HumanName hName = new HumanName(); - - hName.setText("Harsh Dhave"); - - List stList = new ArrayList<>(); - StringType st = new StringType(); - st.setValue("Dr"); - stList.add(st); - hName.setPrefix(stList); - - List stList1 = new ArrayList<>(); - StringType st1 = new StringType(); - st.setValue("MBBS"); - stList1.add(st1); - hName.setSuffix(stList1); - - pNameList.add(hName); - - practitioner.setName(pNameList); + + private Practitioner generatePractitionerResource(PractitionerDataModel practitionerData) { + + Practitioner practitioner = new Practitioner(); + + // ID + practitioner.setId("Practitioner/" + practitionerData.getUserID()); + + // Identifier (Employee / Registration ID) + if (practitionerData.getEmployeeID() != null) { + Identifier identifier = new Identifier(); + identifier.setSystem(systemUrl); + identifier.setValue(practitionerData.getEmployeeID()); + practitioner.addIdentifier(identifier); + } + + // Name + HumanName name = new HumanName(); + + if (practitionerData.getFullName() != null) { + name.setText(practitionerData.getFullName()); + } + + // Prefix (Designation) + if (practitionerData.getDesignationName() != null) { + name.addPrefix(practitionerData.getDesignationName()); + } + + // Suffix (Qualification) + if (practitionerData.getQualificationName() != null) { + name.addSuffix(practitionerData.getQualificationName()); + } + + practitioner.addName(name); + + // Gender + if (practitionerData.getGenderName() != null) { + switch (practitionerData.getGenderName()) { + case "Male": + practitioner.setGender(AdministrativeGender.MALE); + break; + case "Female": + practitioner.setGender(AdministrativeGender.FEMALE); + break; + default: + practitioner.setGender(AdministrativeGender.UNKNOWN); + break; + } + } + + // DOB + if (practitionerData.getDob() != null) { + practitioner.setBirthDate(practitionerData.getDob()); + } + + // Telecom - Phone + if (practitionerData.getContactNo() != null) { + ContactPoint phone = new ContactPoint(); + phone.setSystem(ContactPointSystem.PHONE); + phone.setValue(practitionerData.getContactNo()); + practitioner.addTelecom(phone); + } + + // Telecom - Email + if (practitionerData.getEmailID() != null) { + ContactPoint email = new ContactPoint(); + email.setSystem(ContactPointSystem.EMAIL); + email.setValue(practitionerData.getEmailID()); + practitioner.addTelecom(email); + } return practitioner; } + + } From 8269c756665dc872aa635f0632825ea8e5c76656 Mon Sep 17 00:00:00 2001 From: Helen Grace Karyamsetty <133211481+helenKaryamsetty@users.noreply.github.com> Date: Tue, 23 Dec 2025 01:45:53 +0530 Subject: [PATCH 21/30] Fix environment variable for systemUrl --- src/main/environment/common_ci.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index 9c9f1fa..6ce1d51 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -125,4 +125,4 @@ spring.redis.host=@env.REDIS_HOST@ cors.allowed-origins=@env.CORS_ALLOWED_ORIGINS@ -systemUrl= @env.hipSystemUrl +systemUrl= @env.HIP_SYSTEM_URL From 055525e021fad4311687fb675b9d41b9ba2d178b Mon Sep 17 00:00:00 2001 From: Helen Grace Karyamsetty <133211481+helenKaryamsetty@users.noreply.github.com> Date: Tue, 23 Dec 2025 01:46:52 +0530 Subject: [PATCH 22/30] Fix formatting of systemUrl property --- src/main/environment/common_ci.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index 6ce1d51..c9fbfaa 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -125,4 +125,4 @@ spring.redis.host=@env.REDIS_HOST@ cors.allowed-origins=@env.CORS_ALLOWED_ORIGINS@ -systemUrl= @env.HIP_SYSTEM_URL +systemUrl= @env.HIP_SYSTEM_URL@ From 61506e64278dd07bffea23a3c764de40f4fe308e Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Tue, 23 Dec 2025 16:00:59 +0530 Subject: [PATCH 23/30] fix: taken coderabbitai comments and minor changes --- src/main/environment/common_ci.properties | 2 +- src/main/environment/common_dev.properties | 2 +- src/main/environment/common_docker.properties | 2 +- .../environment/common_example.properties | 2 +- src/main/environment/common_test.properties | 2 +- .../DiagnosticRecordResourceBundleImpl.java | 2 +- .../DischargeSummaryResourceBundleImpl.java | 2 +- .../ImmunizationRecordResourceBundleImpl.java | 2 +- .../OPConsultResourceBundleImpl.java | 2 +- .../PrescriptionResourceBundleImpl.java | 2 +- .../WellnessRecordResourceBundleImpl.java | 2 +- .../MedicationRequestResource.java | 2 +- .../resource_model/OrganizationResource.java | 23 +++++++++++-------- .../resource_model/PractitionerResource.java | 2 +- 14 files changed, 26 insertions(+), 23 deletions(-) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index 9c9f1fa..7a3e967 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -125,4 +125,4 @@ spring.redis.host=@env.REDIS_HOST@ cors.allowed-origins=@env.CORS_ALLOWED_ORIGINS@ -systemUrl= @env.hipSystemUrl +hipSystemUrl= @env.hipSystemUrl diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index 14c0ebb..1fac23c 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -106,4 +106,4 @@ logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO -systemUrl= \ No newline at end of file +hipSystemUrl= \ No newline at end of file diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index e14836e..9f183b0 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -119,4 +119,4 @@ springdoc.swagger-ui.enabled=${SWAGGER_DOC_ENABLED} # Redis IP spring.redis.host=${REDIS_HOST} -systemUrl= \ No newline at end of file +hipSystemUrl= ${HIP_SYSTEM_URL} \ No newline at end of file diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index ba3bf8b..4e99ca7 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -119,4 +119,4 @@ logging.file.name=logs/fhir-api.log cors.allowed-origins=http://localhost:* -systemUrl= \ No newline at end of file +hipSystemUrl= \ No newline at end of file diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties index 400971e..9584f0e 100644 --- a/src/main/environment/common_test.properties +++ b/src/main/environment/common_test.properties @@ -106,4 +106,4 @@ logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO -systemUrl= +hipSystemUrl= diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundleImpl.java index 323f86d..34a941d 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundleImpl.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundleImpl.java @@ -63,7 +63,7 @@ public class DiagnosticRecordResourceBundleImpl implements DiagnosticRecordResou @Autowired private BenHealthIDMappingRepo benHealthIDMappingRepo; - @Value("${systemUrl}") + @Value("${hipSystemUrl}") private String systemUrl; @Override diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundleImpl.java index a088849..2c6af2d 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundleImpl.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundleImpl.java @@ -95,7 +95,7 @@ public class DischargeSummaryResourceBundleImpl implements DischargeSummaryResou @Autowired private BenHealthIDMappingRepo benHealthIDMappingRepo; - @Value("${systemUrl}") + @Value("${hipSystemUrl}") private String systemUrl; @Override diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundleImpl.java index 5131cb5..b3c3bf9 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundleImpl.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundleImpl.java @@ -56,7 +56,7 @@ public class ImmunizationRecordResourceBundleImpl implements ImmunizationRecordR @Autowired private BenHealthIDMappingRepo benHealthIDMappingRepo; - @Value("${systemUrl}") + @Value("${hipSystemUrl}") private String systemUrl; @Override diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundleImpl.java index ad231eb..5ee6cd6 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundleImpl.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundleImpl.java @@ -79,7 +79,7 @@ public class OPConsultResourceBundleImpl implements OPConsultResourceBundle { @Autowired private BenHealthIDMappingRepo benHealthIDMappingRepo; - @Value("${systemUrl}") + @Value("${hipSystemUrl}") private String systemUrl; @Override diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundleImpl.java index d778e17..3d869c6 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundleImpl.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundleImpl.java @@ -56,7 +56,7 @@ public class PrescriptionResourceBundleImpl implements PrescriptionResourceBundl @Autowired private BenHealthIDMappingRepo benHealthIDMappingRepo; - @Value("${systemUrl}") + @Value("${hipSystemUrl}") private String systemUrl; Logger logger = LoggerFactory.getLogger(this.getClass().getName()); diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundleImpl.java index 9288e48..88ba8d2 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundleImpl.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundleImpl.java @@ -56,7 +56,7 @@ public class WellnessRecordResourceBundleImpl implements WellnessRecordResourceB @Autowired private BenHealthIDMappingRepo benHealthIDMappingRepo; - @Value("${systemUrl}") + @Value("${hipSystemUrl}") private String systemUrl; @Override diff --git a/src/main/java/com/wipro/fhir/service/resource_model/MedicationRequestResource.java b/src/main/java/com/wipro/fhir/service/resource_model/MedicationRequestResource.java index 1d2bb26..beeeda1 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/MedicationRequestResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/MedicationRequestResource.java @@ -99,7 +99,7 @@ private List generateMedicationRequestResource(Patient patien c = new Coding(); cList = new ArrayList<>(); - medicationRequest.setId("MedicationRequest - " + index + "/" + commonService.getUUID()); + medicationRequest.setId("MedicationRequest-" + index + "/" + commonService.getUUID()); medicationRequest.setStatus(MedicationRequestStatus.ACTIVE); medicationRequest.setIntent(MedicationRequestIntent.ORDER); diff --git a/src/main/java/com/wipro/fhir/service/resource_model/OrganizationResource.java b/src/main/java/com/wipro/fhir/service/resource_model/OrganizationResource.java index 345ee96..6d6501c 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/OrganizationResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/OrganizationResource.java @@ -45,18 +45,21 @@ public class OrganizationResource { public Organization getOrganizationResource(ResourceRequestHandler resourceRequestHandler) throws FHIRException { - List rsObj = patientEligibleForResourceCreationRepo.callOrganizationSp(resourceRequestHandler.getVisitCode()); - - OrganizationDataModel orgData = organizationDataModel.getOrganization(rsObj.get(0)); - - if (orgData != null) { - return generateOrganizationResource(orgData); - } else { - throw new FHIRException("Organization not found"); - } + List rsObj = patientEligibleForResourceCreationRepo + .callOrganizationSp(resourceRequestHandler.getVisitCode()); + + if (rsObj != null && !rsObj.isEmpty()) { + OrganizationDataModel orgData = organizationDataModel.getOrganization(rsObj.get(0)); + if (orgData != null) { + return generateOrganizationResource(orgData); + } else { + throw new FHIRException("Organization data not found"); + } + } else { + throw new FHIRException("Organization not found"); + } } - private Organization generateOrganizationResource(OrganizationDataModel orgData) { Organization organization = new Organization(); diff --git a/src/main/java/com/wipro/fhir/service/resource_model/PractitionerResource.java b/src/main/java/com/wipro/fhir/service/resource_model/PractitionerResource.java index a002b57..5d353e0 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/PractitionerResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/PractitionerResource.java @@ -49,7 +49,7 @@ public class PractitionerResource { @Autowired private PractitionerDataModel practitionerDataModel; - @Value("${systemUrl}") + @Value("${hipSystemUrl}") private String systemUrl; public Practitioner getPractitionerResource(ResourceRequestHandler resourceRequestHandler) From e2bec9a2d4a09d0ea0c2171caab0ab82d1c7e0a5 Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Wed, 24 Dec 2025 00:32:14 +0530 Subject: [PATCH 24/30] fix: changed missed variable --- src/main/environment/common_ci.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index c9fbfaa..cda0a73 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -125,4 +125,4 @@ spring.redis.host=@env.REDIS_HOST@ cors.allowed-origins=@env.CORS_ALLOWED_ORIGINS@ -systemUrl= @env.HIP_SYSTEM_URL@ +hipSystemUrl= @env.HIP_SYSTEM_URL@ From 881bcbf7f642d6ab65d20001a612640b8d3a502c Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Wed, 24 Dec 2025 03:54:00 +0530 Subject: [PATCH 25/30] fix: modified the constructor --- .../resource_model/OrganizationDataModel.java | 47 ++++++++++------- .../resource_model/PractitionerDataModel.java | 52 ++++++++++++------- 2 files changed, 63 insertions(+), 36 deletions(-) diff --git a/src/main/java/com/wipro/fhir/data/resource_model/OrganizationDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/OrganizationDataModel.java index 43fc076..8fc0e4d 100644 --- a/src/main/java/com/wipro/fhir/data/resource_model/OrganizationDataModel.java +++ b/src/main/java/com/wipro/fhir/data/resource_model/OrganizationDataModel.java @@ -5,6 +5,8 @@ import org.springframework.stereotype.Component; +import com.wipro.fhir.utils.exception.FHIRException; + import lombok.Data; @Component @@ -38,35 +40,44 @@ public class OrganizationDataModel { public OrganizationDataModel() { } - public OrganizationDataModel(Object[] objArr) { + public OrganizationDataModel(Object[] objArr) throws FHIRException { + + try { + + this.benVisitID = objArr[0] != null ? Long.parseLong(objArr[0].toString()) : null; + this.serviceProviderID = objArr[1] != null ? Short.parseShort(objArr[1].toString()) : null; + this.serviceProviderName = objArr[2] != null ? objArr[2].toString() : null; - this.benVisitID = objArr[0] != null ? (Long) objArr[0] : null; - this.serviceProviderID = objArr[1] != null ? (Short) objArr[1] : null; - this.serviceProviderName = objArr[2] != null ? (String) objArr[2] : null; + this.stateID = objArr[3] != null ? Integer.parseInt(objArr[3].toString()) : null; + this.stateName = objArr[4] != null ? objArr[4].toString() : null; - this.stateID = objArr[3] != null ? (Integer) objArr[3] : null; - this.stateName = objArr[4] != null ? (String) objArr[4] : null; + this.districtID = objArr[5] != null ? Integer.parseInt(objArr[5].toString()) : null; + this.districtName = objArr[6] != null ? objArr[6].toString() : null; - this.districtID = objArr[5] != null ? (Integer) objArr[5] : null; - this.districtName = objArr[6] != null ? (String) objArr[6] : null; + this.locationName = objArr[7] != null ? objArr[7].toString() : null; + this.address = objArr[8] != null ? objArr[8].toString() : null; - this.locationName = objArr[7] != null ? (String) objArr[7] : null; - this.address = objArr[8] != null ? (String) objArr[8] : null; + this.serviceID = objArr[9] != null ? Short.parseShort(objArr[9].toString()) : null; + this.serviceName = objArr[10] != null ? objArr[10].toString() : null; - this.serviceID = objArr[9] != null ? (Short) objArr[9] : null; - this.serviceName = objArr[10] != null ? (String) objArr[10] : null; + this.isNational = objArr[11] != null + ? objArr[11].toString().equalsIgnoreCase("true") || objArr[11].toString().equals("1") + : null; - this.isNational = objArr[11] != null ? (Boolean) objArr[11] : null; + this.abdmFacilityId = objArr[12] != null ? objArr[12].toString() : null; + this.abdmFacilityName = objArr[13] != null ? objArr[13].toString() : null; - this.abdmFacilityId = objArr[12] != null ? (String) objArr[12] : null; - this.abdmFacilityName = objArr[13] != null ? (String) objArr[13] : null; + this.psAddMapID = objArr[14] != null ? Integer.parseInt(objArr[14].toString()) : null; + this.providerServiceMapID = objArr[15] != null ? Integer.parseInt(objArr[15].toString()) : null; + + } catch (Exception e) { + throw new FHIRException("Practioner resource failed with error - " + e.getMessage()); + } - this.psAddMapID = objArr[14] != null ? (Integer) objArr[14] : null; - this.providerServiceMapID = objArr[15] != null ? (Integer) objArr[15] : null; } - public OrganizationDataModel getOrganization(Object[] resultSet) { + public OrganizationDataModel getOrganization(Object[] resultSet) throws FHIRException { if (resultSet == null || resultSet.length == 0) { return null; diff --git a/src/main/java/com/wipro/fhir/data/resource_model/PractitionerDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/PractitionerDataModel.java index 6ccb20f..db52a8c 100644 --- a/src/main/java/com/wipro/fhir/data/resource_model/PractitionerDataModel.java +++ b/src/main/java/com/wipro/fhir/data/resource_model/PractitionerDataModel.java @@ -5,6 +5,8 @@ import org.springframework.stereotype.Component; +import com.wipro.fhir.utils.exception.FHIRException; + import lombok.Data; @Data @@ -37,27 +39,41 @@ public class PractitionerDataModel { public PractitionerDataModel() { } - public PractitionerDataModel(Object[] objArr) { - - this.benVisitID = objArr[0] != null ? ((Number) objArr[0]).intValue() : null; - this.userID = objArr[1] != null ? ((Number) objArr[1]).intValue() : null; - this.fullName = (String) objArr[2]; - this.dob = (Date) objArr[3]; - this.employeeID = (String) objArr[4]; - this.contactNo = (String) objArr[5]; - this.emailID = (String) objArr[6]; - this.qualificationName = (String) objArr[7]; - this.designationName = (String) objArr[8]; - this.genderName = (String) objArr[9]; - this.genderID = objArr[10] != null ? ((Number) objArr[10]).intValue() : null; - this.serviceProviderID = objArr[11] != null ? ((Number) objArr[11]).intValue() : null; - this.visitCode = objArr[12] != null ? ((Number) objArr[12]).longValue() : null; - this.createdBy = (String) objArr[13]; - this.createdDate = (Timestamp) objArr[14]; + public PractitionerDataModel(Object[] objArr) throws FHIRException { + + try { + + this.benVisitID = objArr[0] != null ? Integer.parseInt(objArr[0].toString()) : null; + this.userID = objArr[1] != null ? Integer.parseInt(objArr[1].toString()) : null; + + this.fullName = objArr[2] != null ? objArr[2].toString() : null; + + this.dob = objArr[3] != null ? (objArr[3] instanceof Date ? (Date) objArr[3] : null) : null; + + this.employeeID = objArr[4] != null ? objArr[4].toString() : null; + this.contactNo = objArr[5] != null ? objArr[5].toString() : null; + this.emailID = objArr[6] != null ? objArr[6].toString() : null; + this.qualificationName = objArr[7] != null ? objArr[7].toString() : null; + this.designationName = objArr[8] != null ? objArr[8].toString() : null; + this.genderName = objArr[9] != null ? objArr[9].toString() : null; + + this.genderID = objArr[10] != null ? Integer.parseInt(objArr[10].toString()) : null; + this.serviceProviderID = objArr[11] != null ? Integer.parseInt(objArr[11].toString()) : null; + + this.visitCode = objArr[12] != null ? Long.parseLong(objArr[12].toString()) : null; + + this.createdBy = objArr[13] != null ? objArr[13].toString() : null; + + this.createdDate = objArr[14] != null ? (objArr[14] instanceof Timestamp ? (Timestamp) objArr[14] : null) + : null; + } catch (Exception e) { + throw new FHIRException("Practioner resource failed with error - " + e.getMessage()); + } + } - public PractitionerDataModel getPractitioner(Object[] resultSet) { + public PractitionerDataModel getPractitioner(Object[] resultSet) throws FHIRException { if (resultSet == null || resultSet.length == 0) { return null; } From d116010f6729452da4d0c81dd1633639dfd2f1e7 Mon Sep 17 00:00:00 2001 From: Helen Grace Karyamsetty <133211481+helenKaryamsetty@users.noreply.github.com> Date: Wed, 24 Dec 2025 04:02:10 +0530 Subject: [PATCH 26/30] Change exception message for Organization resource --- .../wipro/fhir/data/resource_model/OrganizationDataModel.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/wipro/fhir/data/resource_model/OrganizationDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/OrganizationDataModel.java index 8fc0e4d..21bc063 100644 --- a/src/main/java/com/wipro/fhir/data/resource_model/OrganizationDataModel.java +++ b/src/main/java/com/wipro/fhir/data/resource_model/OrganizationDataModel.java @@ -71,7 +71,7 @@ public OrganizationDataModel(Object[] objArr) throws FHIRException { this.providerServiceMapID = objArr[15] != null ? Integer.parseInt(objArr[15].toString()) : null; } catch (Exception e) { - throw new FHIRException("Practioner resource failed with error - " + e.getMessage()); + throw new FHIRException("Organization resource failed with error - " + e.getMessage()); } } From 6237bad664935cb1d5681ab853a88dbcfadd6c48 Mon Sep 17 00:00:00 2001 From: Helen Grace Karyamsetty <133211481+helenKaryamsetty@users.noreply.github.com> Date: Wed, 24 Dec 2025 04:02:48 +0530 Subject: [PATCH 27/30] Fix typo in exception message for PractitionerDataModel --- .../wipro/fhir/data/resource_model/PractitionerDataModel.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/wipro/fhir/data/resource_model/PractitionerDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/PractitionerDataModel.java index db52a8c..085abf6 100644 --- a/src/main/java/com/wipro/fhir/data/resource_model/PractitionerDataModel.java +++ b/src/main/java/com/wipro/fhir/data/resource_model/PractitionerDataModel.java @@ -67,7 +67,7 @@ public PractitionerDataModel(Object[] objArr) throws FHIRException { this.createdDate = objArr[14] != null ? (objArr[14] instanceof Timestamp ? (Timestamp) objArr[14] : null) : null; } catch (Exception e) { - throw new FHIRException("Practioner resource failed with error - " + e.getMessage()); + throw new FHIRException("Practitioner resource failed with error - " + e.getMessage()); } } From 536f445b2a6dff8cf360b120360b86e2c408335f Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Wed, 24 Dec 2025 05:12:46 +0530 Subject: [PATCH 28/30] fix: corrected type error --- .../MedicalHistoryDataModel.java | 48 +++++++++++++------ .../MedicalHistoryResource.java | 2 +- 2 files changed, 35 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/wipro/fhir/data/resource_model/MedicalHistoryDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/MedicalHistoryDataModel.java index 5e88320..92f22ed 100644 --- a/src/main/java/com/wipro/fhir/data/resource_model/MedicalHistoryDataModel.java +++ b/src/main/java/com/wipro/fhir/data/resource_model/MedicalHistoryDataModel.java @@ -20,7 +20,7 @@ public class MedicalHistoryDataModel implements Serializable { private BigInteger id; private BigInteger beneficiaryRegID; - private BigInteger visitCode; + private String visitCode; private String currentMedication; private Integer currentMedYear; private String yearOfIllness; @@ -32,21 +32,41 @@ public class MedicalHistoryDataModel implements Serializable { public MedicalHistoryDataModel() { } - public MedicalHistoryDataModel(Object[] objArr) { - this.id = objArr[0] != null ? BigInteger.valueOf(((Number) objArr[0]).longValue()) : null; - this.beneficiaryRegID = objArr[1] != null ? BigInteger.valueOf(((Number) objArr[1]).longValue()) : null; - this.visitCode = objArr[2] != null ? BigInteger.valueOf(((Number) objArr[2]).longValue()) : null; - this.currentMedication = objArr[3] != null ? (String) objArr[3] : null; - this.currentMedYear = objArr[4] != null ? (Integer) objArr[4] : null; - this.yearOfIllness = objArr[5] != null ? (String) objArr[5] : null; - this.finalIllnessType = objArr[6] != null ? (String) objArr[6] : null; - this.yearOfSurgery = objArr[7] != null ? (String) objArr[7] : null; - this.finalSurgeryType = objArr[8] != null ? (String) objArr[8] : null; - this.createdDate = objArr[9] != null ? (Timestamp) objArr[9] : null; - this.createdBy = objArr[10] != null ? (String) objArr[10] : null; + public MedicalHistoryDataModel(Object[] objArr) throws Exception { + try { + + this.id = objArr[0] != null + ? BigInteger.valueOf(Long.parseLong(objArr[0].toString())) + : null; + + this.beneficiaryRegID = objArr[1] != null + ? BigInteger.valueOf(Long.parseLong(objArr[1].toString())) + : null; + + // visitCode is STRING only + this.visitCode = objArr[2] != null ? objArr[2].toString() : null; + + this.currentMedication = objArr[3] != null ? objArr[3].toString() : null; + + this.currentMedYear = objArr[4] != null + ? Integer.parseInt(objArr[4].toString()) + : null; + + this.yearOfIllness = objArr[5] != null ? objArr[5].toString() : null; + this.finalIllnessType = objArr[6] != null ? objArr[6].toString() : null; + this.yearOfSurgery = objArr[7] != null ? objArr[7].toString() : null; + this.finalSurgeryType = objArr[8] != null ? objArr[8].toString() : null; + + this.createdDate = objArr[9] instanceof Timestamp ? (Timestamp) objArr[9] : null; + this.createdBy = objArr[10] != null ? objArr[10].toString() : null; + + } catch (Exception e) { + throw new Exception("Medical statement resource model failed with error - " + e.getMessage()); + } + } - public List getMedicalList(List resultSetList) { + public List getMedicalList(List resultSetList) throws Exception { MedicalHistoryDataModel medHistoryObj; List medHistoryList = new ArrayList(); if (resultSetList != null && resultSetList.size() > 0) { diff --git a/src/main/java/com/wipro/fhir/service/resource_model/MedicalHistoryResource.java b/src/main/java/com/wipro/fhir/service/resource_model/MedicalHistoryResource.java index 1729229..6e3a5c5 100644 --- a/src/main/java/com/wipro/fhir/service/resource_model/MedicalHistoryResource.java +++ b/src/main/java/com/wipro/fhir/service/resource_model/MedicalHistoryResource.java @@ -27,7 +27,7 @@ public class MedicalHistoryResource { @Autowired private PatientEligibleForResourceCreationRepo patientEligibleForResourceCreationRepo; - public List getMedicalHistory(Patient patient, ResourceRequestHandler resourceRequestHandler) { + public List getMedicalHistory(Patient patient, ResourceRequestHandler resourceRequestHandler) throws Exception { List rsObjList = patientEligibleForResourceCreationRepo.callMedicalHistorySp(resourceRequestHandler.getVisitCode()); From 0b6d2ad4b2afa81c339f827c0da8aea6378d7223 Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Tue, 30 Dec 2025 13:44:53 +0530 Subject: [PATCH 29/30] fix: correct medication histoory model class --- .../MedicalHistoryDataModel.java | 40 +++++-------------- ...atientEligibleForResourceCreationRepo.java | 3 +- 2 files changed, 12 insertions(+), 31 deletions(-) diff --git a/src/main/java/com/wipro/fhir/data/resource_model/MedicalHistoryDataModel.java b/src/main/java/com/wipro/fhir/data/resource_model/MedicalHistoryDataModel.java index 92f22ed..dc1aba7 100644 --- a/src/main/java/com/wipro/fhir/data/resource_model/MedicalHistoryDataModel.java +++ b/src/main/java/com/wipro/fhir/data/resource_model/MedicalHistoryDataModel.java @@ -19,49 +19,31 @@ public class MedicalHistoryDataModel implements Serializable { private BigInteger id; - private BigInteger beneficiaryRegID; - private String visitCode; + private BigInteger providerServiceMapID; private String currentMedication; - private Integer currentMedYear; - private String yearOfIllness; - private String finalIllnessType; - private String yearOfSurgery; - private String finalSurgeryType; - private Timestamp createdDate; + private Timestamp currentMedYear; private String createdBy; + private Timestamp createdDate; public MedicalHistoryDataModel() { } public MedicalHistoryDataModel(Object[] objArr) throws Exception { try { - this.id = objArr[0] != null - ? BigInteger.valueOf(Long.parseLong(objArr[0].toString())) - : null; - - this.beneficiaryRegID = objArr[1] != null - ? BigInteger.valueOf(Long.parseLong(objArr[1].toString())) - : null; - - // visitCode is STRING only - this.visitCode = objArr[2] != null ? objArr[2].toString() : null; + this.id = objArr[0] != null ? BigInteger.valueOf(Long.parseLong(objArr[0].toString())) : null; + + this.providerServiceMapID = objArr[1] != null ? BigInteger.valueOf(Long.parseLong(objArr[1].toString())) : null; - this.currentMedication = objArr[3] != null ? objArr[3].toString() : null; + this.currentMedication = objArr[2] != null ? objArr[2].toString() : null; - this.currentMedYear = objArr[4] != null - ? Integer.parseInt(objArr[4].toString()) - : null; + this.currentMedYear = objArr[3] instanceof Timestamp ? (Timestamp) objArr[3] : null; - this.yearOfIllness = objArr[5] != null ? objArr[5].toString() : null; - this.finalIllnessType = objArr[6] != null ? objArr[6].toString() : null; - this.yearOfSurgery = objArr[7] != null ? objArr[7].toString() : null; - this.finalSurgeryType = objArr[8] != null ? objArr[8].toString() : null; + this.createdBy = objArr[4] != null ? objArr[4].toString() : null; - this.createdDate = objArr[9] instanceof Timestamp ? (Timestamp) objArr[9] : null; - this.createdBy = objArr[10] != null ? objArr[10].toString() : null; + this.createdDate = objArr[5] instanceof Timestamp ? (Timestamp) objArr[5] : null; } catch (Exception e) { - throw new Exception("Medical statement resource model failed with error - " + e.getMessage()); + throw new Exception("Medical History resource model failed with error - " + e.getMessage()); } } diff --git a/src/main/java/com/wipro/fhir/repo/common/PatientEligibleForResourceCreationRepo.java b/src/main/java/com/wipro/fhir/repo/common/PatientEligibleForResourceCreationRepo.java index 69480a5..17cbc85 100644 --- a/src/main/java/com/wipro/fhir/repo/common/PatientEligibleForResourceCreationRepo.java +++ b/src/main/java/com/wipro/fhir/repo/common/PatientEligibleForResourceCreationRepo.java @@ -121,8 +121,7 @@ List callMedicationRequestSP(@Param("beneficiaryRegID_IN") BigInteger List callMedicalHistorySp(@Param("visitCode_IN") BigInteger visitCode_IN); //Immunization record - @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_Immunization(:beneficiaryRegID_IN, :visitCode_IN, @0, " - + "@1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12)") + @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_Immunization(:beneficiaryRegID_IN, :visitCode_IN)") List callImmunizationSP(@Param("beneficiaryRegID_IN") BigInteger beneficiaryRegID_IN, @Param("visitCode_IN") BigInteger visitCode_IN); @Query(nativeQuery = true, value = "CALL db_iemr.FHIR_R_OrganizationDetails(:visitCode_IN)") From 67307ae8a91a7e487216f0ae37a7a040de379c17 Mon Sep 17 00:00:00 2001 From: helenKaryamsetty Date: Tue, 30 Dec 2025 15:35:52 +0530 Subject: [PATCH 30/30] fix: taken coderabbitai comments --- .../generateresource/ResourceRequestGateway.java | 6 +++--- src/main/java/com/wipro/fhir/controller/test/Test.java | 2 +- .../wipro/fhir/repo/v3/careContext/CareContextRepo.java | 9 +++++---- .../bundle_creation/DiagnosticRecordResourceBundle.java | 4 ++-- .../DiagnosticRecordResourceBundleImpl.java | 8 ++++---- .../bundle_creation/DischargeSummaryResourceBundle.java | 4 ++-- .../DischargeSummaryResourceBundleImpl.java | 8 ++++---- .../ImmunizationRecordResourceBundle.java | 2 +- .../ImmunizationRecordResourceBundleImpl.java | 4 ++-- .../service/bundle_creation/OPConsultResourceBundle.java | 4 ++-- .../bundle_creation/OPConsultResourceBundleImpl.java | 8 ++++---- .../bundle_creation/PrescriptionResourceBundle.java | 4 ++-- .../bundle_creation/PrescriptionResourceBundleImpl.java | 8 ++++---- .../bundle_creation/WellnessRecordResourceBundle.java | 4 ++-- .../WellnessRecordResourceBundleImpl.java | 8 ++++---- .../v3/careContext/CareContextLinkingServiceImpl.java | 6 +++--- 16 files changed, 45 insertions(+), 44 deletions(-) diff --git a/src/main/java/com/wipro/fhir/controller/generateresource/ResourceRequestGateway.java b/src/main/java/com/wipro/fhir/controller/generateresource/ResourceRequestGateway.java index e293ac7..c888027 100644 --- a/src/main/java/com/wipro/fhir/controller/generateresource/ResourceRequestGateway.java +++ b/src/main/java/com/wipro/fhir/controller/generateresource/ResourceRequestGateway.java @@ -78,7 +78,7 @@ public String getPatientResource(@RequestBody ResourceRequestHandler patientReso OutputResponse response = new OutputResponse(); try { - String s = opConsultRecordBundle.PopulateOPConsultRecordResourceBundle(patientResourceRequest, null); + String s = opConsultRecordBundle.populateOPConsultRecordResourceBundle(patientResourceRequest, null); response.setResponse(s); } catch (FHIRException e) { @@ -104,7 +104,7 @@ public String getDiagnosticReportRecord(@RequestBody ResourceRequestHandler pati OutputResponse response = new OutputResponse(); try { - String s = diagnosticReportRecord.PopulateDiagnosticReportResourceBundle(patientResourceRequest, null); + String s = diagnosticReportRecord.populateDiagnosticReportResourceBundle(patientResourceRequest, null); response.setResponse(s); } catch (FHIRException e) { @@ -129,7 +129,7 @@ public String getPrescriptionRecord(@RequestBody ResourceRequestHandler patientR OutputResponse response = new OutputResponse(); try { - String s = prescriptionRecordBundle.PopulatePrescriptionResourceBundle(patientResourceRequest, null); + String s = prescriptionRecordBundle.populatePrescriptionResourceBundle(patientResourceRequest, null); response.setResponse(s); } catch (FHIRException e) { diff --git a/src/main/java/com/wipro/fhir/controller/test/Test.java b/src/main/java/com/wipro/fhir/controller/test/Test.java index 8be0743..138db28 100644 --- a/src/main/java/com/wipro/fhir/controller/test/Test.java +++ b/src/main/java/com/wipro/fhir/controller/test/Test.java @@ -57,7 +57,7 @@ public String parseFeeds(@RequestBody ResourceRequestHandler resourceRequestHand OutputResponse response = new OutputResponse(); String s = null; try { - s = oPConsultRecordBundleImpl.PopulateOPConsultRecordResourceBundle(resourceRequestHandler, null); + s = oPConsultRecordBundleImpl.populateOPConsultRecordResourceBundle(resourceRequestHandler, null); response.setResponse(s); } catch (Exception e) { logger.error("Unexpected error:" , e); diff --git a/src/main/java/com/wipro/fhir/repo/v3/careContext/CareContextRepo.java b/src/main/java/com/wipro/fhir/repo/v3/careContext/CareContextRepo.java index 9015882..26696b1 100644 --- a/src/main/java/com/wipro/fhir/repo/v3/careContext/CareContextRepo.java +++ b/src/main/java/com/wipro/fhir/repo/v3/careContext/CareContextRepo.java @@ -4,21 +4,22 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; public interface CareContextRepo extends CrudRepository { @Query(value="SELECT COUNT(*) FROM t_phy_vitals WHERE VisitCode = :visitCode", nativeQuery = true) - public int hasPhyVitals(String visitCode); + public int hasPhyVitals(@Param("visitCode") String visitCode); @Query(value="SELECT COUNT(*) FROM t_prescribeddrug WHERE VisitCode = :visitCode", nativeQuery = true) - public int hasPrescribedDrugs(String visitCode); + public int hasPrescribedDrugs(@Param("visitCode") String visitCode); @Query(value="SELECT COUNT(*) FROM t_lab_testorder WHERE VisitCode = :visitCode", nativeQuery = true) - public int hasLabtestsDone(String visitCode); + public int hasLabtestsDone(@Param("visitCode") String visitCode); @Query(value="SELECT COUNT(*) FROM t_childvaccinedetail1 WHERE VisitCode = :visitCode", nativeQuery = true) - public int hasVaccineDetails(String visitCode); + public int hasVaccineDetails(@Param("visitCode") String visitCode); } diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundle.java b/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundle.java index cad83be..61c2bd4 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundle.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundle.java @@ -17,11 +17,11 @@ public interface DiagnosticRecordResourceBundle { int processDiagnosticReportRecordBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException; - Composition PopulateDiagnosticReportComposition(ResourceRequestHandler resourceRequestHandler, + Composition populateDiagnosticReportComposition(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p, List diagnosticReports, Practitioner practitioner, Organization organization); - String PopulateDiagnosticReportResourceBundle(ResourceRequestHandler resourceRequestHandler, + String populateDiagnosticReportResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException; } diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundleImpl.java index 34a941d..71d4f0c 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundleImpl.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/DiagnosticRecordResourceBundleImpl.java @@ -71,7 +71,7 @@ public int processDiagnosticReportRecordBundle(ResourceRequestHandler resourceRe PatientEligibleForResourceCreation p) throws FHIRException { int i = 0; // call method to generate Prescription resource - String diagnosticReportRecordBundle = PopulateDiagnosticReportResourceBundle(resourceRequestHandler, p); + String diagnosticReportRecordBundle = populateDiagnosticReportResourceBundle(resourceRequestHandler, p); // call private method to create mongo object with resource data AMRIT_ResourceMongo aMRIT_ResourceMongo = createDiagnosticReportRecordBundleMongo(p, @@ -88,7 +88,7 @@ public int processDiagnosticReportRecordBundle(ResourceRequestHandler resourceRe } @Override - public String PopulateDiagnosticReportResourceBundle(ResourceRequestHandler resourceRequestHandler, + public String populateDiagnosticReportResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException { Bundle diagReportBundle = new Bundle(); @@ -129,7 +129,7 @@ public String PopulateDiagnosticReportResourceBundle(ResourceRequestHandler reso List diagnosticResourceList = diagnosticReportResource.getDiagnosticReport(patient, new Encounter(), resourceRequestHandler, observationMap); - Composition composition = PopulateDiagnosticReportComposition(resourceRequestHandler, p, + Composition composition = populateDiagnosticReportComposition(resourceRequestHandler, p, diagnosticResourceList, practitioner, organization); List bundleEntries = new ArrayList<>(); @@ -193,7 +193,7 @@ public String PopulateDiagnosticReportResourceBundle(ResourceRequestHandler reso } @Override - public Composition PopulateDiagnosticReportComposition(ResourceRequestHandler resourceRequestHandler, + public Composition populateDiagnosticReportComposition(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p, List diagnosticReports, Practitioner practitioner, Organization organization) { Composition composition = new Composition(); diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundle.java b/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundle.java index d793108..e06bdf5 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundle.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundle.java @@ -23,14 +23,14 @@ public interface DischargeSummaryResourceBundle { int processDischargeSummaryRecordBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException; - Composition PopulateDischargeSummaryComposition(ResourceRequestHandler resourceRequestHandler, + Composition populateDischargeSummaryComposition(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p, Practitioner practitioner, Organization organization, Patient patient, Encounter encounter, List chiefComplaints, List physicalExam, List allergyList, FamilyMemberHistory familyMemberHistory, List pastMedicalHistoryConditions, List medicationRequests, List procedures); - String PopulateDischargeSummaryResourceBundle(ResourceRequestHandler resourceRequestHandler, + String populateDischargeSummaryResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException; } diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundleImpl.java index 2c6af2d..db6c76b 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundleImpl.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/DischargeSummaryResourceBundleImpl.java @@ -103,7 +103,7 @@ public int processDischargeSummaryRecordBundle(ResourceRequestHandler resourceRe PatientEligibleForResourceCreation p) throws FHIRException { int i = 0; // call method to generate Prescription resource - String dischargeSummaryBundle = PopulateDischargeSummaryResourceBundle(resourceRequestHandler, p); + String dischargeSummaryBundle = populateDischargeSummaryResourceBundle(resourceRequestHandler, p); // call private method to create mongo object with resource data AMRIT_ResourceMongo aMRIT_ResourceMongo = createDischargeSummaryBundleMongo(p, @@ -121,7 +121,7 @@ public int processDischargeSummaryRecordBundle(ResourceRequestHandler resourceRe @Override - public String PopulateDischargeSummaryResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException { + public String populateDischargeSummaryResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException { Bundle dischargeSummaryBundle = new Bundle(); String serializeBundle = null; @@ -185,7 +185,7 @@ public String PopulateDischargeSummaryResourceBundle(ResourceRequestHandler reso new Encounter(), resourceRequestHandler, observationMap); // composition - Composition composition = PopulateDischargeSummaryComposition(resourceRequestHandler, p, practitioner, organization, patient, encounter, conditionListChiefComplaints, + Composition composition = populateDischargeSummaryComposition(resourceRequestHandler, p, practitioner, organization, patient, encounter, conditionListChiefComplaints, conditionListDiagnosis, allergyList, familyMemberHistory, medicationStatement, medicationRequest, diagnosticResourceList); List bundleEnteries = new ArrayList<>(); @@ -290,7 +290,7 @@ public String PopulateDischargeSummaryResourceBundle(ResourceRequestHandler reso @Override - public Composition PopulateDischargeSummaryComposition( + public Composition populateDischargeSummaryComposition( ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p, Practitioner practitioner, diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundle.java b/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundle.java index 1c08e2d..5174c2a 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundle.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundle.java @@ -17,7 +17,7 @@ public interface ImmunizationRecordResourceBundle { Composition populateImmunizationComposition(Patient patient, Practitioner practitioner, Organization organization, List immunizations); - String PopulateImmunizationResourceBundle(ResourceRequestHandler resourceRequestHandler, + String populateImmunizationResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException; int processImmunizationRecordBundle(ResourceRequestHandler resourceRequestHandler, diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundleImpl.java index b3c3bf9..95c8849 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundleImpl.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/ImmunizationRecordResourceBundleImpl.java @@ -64,7 +64,7 @@ public int processImmunizationRecordBundle(ResourceRequestHandler resourceReques PatientEligibleForResourceCreation p) throws FHIRException { int i = 0; // call method to generate Prescription resource - String immunizationBundle = PopulateImmunizationResourceBundle(resourceRequestHandler, p); + String immunizationBundle = populateImmunizationResourceBundle(resourceRequestHandler, p); // call private method to create mongo object with resource data AMRIT_ResourceMongo aMRIT_ResourceMongo = createImmunizationBundleMongo(p, @@ -81,7 +81,7 @@ public int processImmunizationRecordBundle(ResourceRequestHandler resourceReques } @Override - public String PopulateImmunizationResourceBundle(ResourceRequestHandler resourceRequestHandler, + public String populateImmunizationResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException { Bundle diagReportBundle = new Bundle(); diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundle.java b/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundle.java index 238c864..10a3ff1 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundle.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundle.java @@ -16,7 +16,7 @@ public interface OPConsultResourceBundle { - Composition PopulateOpConsultComposition(ResourceRequestHandler resourceRequestHandler, + Composition populateOpConsultComposition(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p, Practitioner practitioner, Organization organization, List conditionListChiefComplaints, List conditionListDiagnosis, List allergyList, FamilyMemberHistory familyMemberHistory, @@ -25,7 +25,7 @@ Composition PopulateOpConsultComposition(ResourceRequestHandler resourceRequestH int processOpConsultRecordBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException; - String PopulateOPConsultRecordResourceBundle(ResourceRequestHandler resourceRequestHandler, + String populateOPConsultRecordResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException; } diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundleImpl.java index 5ee6cd6..08322a1 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundleImpl.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/OPConsultResourceBundleImpl.java @@ -87,7 +87,7 @@ public int processOpConsultRecordBundle(ResourceRequestHandler resourceRequestHa PatientEligibleForResourceCreation p) throws FHIRException { int i = 0; // call method to generate Prescription resource - String opConsultBundle = PopulateOPConsultRecordResourceBundle(resourceRequestHandler, p); + String opConsultBundle = populateOPConsultRecordResourceBundle(resourceRequestHandler, p); // call private method to create mongo object with resource data AMRIT_ResourceMongo aMRIT_ResourceMongo = createOpConsultBundleMongo(p, @@ -105,7 +105,7 @@ public int processOpConsultRecordBundle(ResourceRequestHandler resourceRequestHa @Override - public String PopulateOPConsultRecordResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException { + public String populateOPConsultRecordResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException { Bundle opConsultBundle = new Bundle(); String serializeBundle = null; @@ -157,7 +157,7 @@ public String PopulateOPConsultRecordResourceBundle(ResourceRequestHandler resou List medicationStatement = medicalHistoryResource.getMedicalHistory(patient, resourceRequestHandler); // composition - Composition composition = PopulateOpConsultComposition(resourceRequestHandler, p, practitioner, organization, conditionListChiefComplaints, + Composition composition = populateOpConsultComposition(resourceRequestHandler, p, practitioner, organization, conditionListChiefComplaints, conditionListDiagnosis, allergyList,familyMemberHistory, medicationStatement); List bundleEnteries = new ArrayList<>(); @@ -238,7 +238,7 @@ public String PopulateOPConsultRecordResourceBundle(ResourceRequestHandler resou } @Override - public Composition PopulateOpConsultComposition(ResourceRequestHandler resourceRequestHandler,PatientEligibleForResourceCreation p, + public Composition populateOpConsultComposition(ResourceRequestHandler resourceRequestHandler,PatientEligibleForResourceCreation p, Practitioner practitioner, Organization organization, List conditionListChiefComplaints, List conditionListDiagnosis, List allergyList, FamilyMemberHistory familyMemberHistory, List medicationStatement) { diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundle.java b/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundle.java index ea5224c..c68fcc7 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundle.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundle.java @@ -13,10 +13,10 @@ public interface PrescriptionResourceBundle { - String PopulatePrescriptionResourceBundle(ResourceRequestHandler resourceRequestHandler, + String populatePrescriptionResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException; - Composition PopulatePrescriptionComposition(ResourceRequestHandler resourceRequestHandler, + Composition populatePrescriptionComposition(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p, List medicationRequest, Practitioner practitioner, Organization organization); diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundleImpl.java index 3d869c6..b82cfd7 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundleImpl.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/PrescriptionResourceBundleImpl.java @@ -67,7 +67,7 @@ public int processPrescriptionRecordBundle(ResourceRequestHandler resourceReques PatientEligibleForResourceCreation p) throws FHIRException { int i = 0; // call method to generate Prescription resource - String prescriptionBundle = PopulatePrescriptionResourceBundle(resourceRequestHandler, p); + String prescriptionBundle = populatePrescriptionResourceBundle(resourceRequestHandler, p); // call private method to create mongo object with resource data AMRIT_ResourceMongo aMRIT_ResourceMongo = createPrescriptionBundleMongo(p, @@ -84,7 +84,7 @@ public int processPrescriptionRecordBundle(ResourceRequestHandler resourceReques } @Override - public String PopulatePrescriptionResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException { + public String populatePrescriptionResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException { Bundle prescriptionBundle = new Bundle(); String serializeBundle = null; @@ -117,7 +117,7 @@ public String PopulatePrescriptionResourceBundle(ResourceRequestHandler resource List medicationRequest = medicationRequestResource.getMedicationRequest(patient, resourceRequestHandler, practitioner, null); // composition - Composition composition = PopulatePrescriptionComposition(resourceRequestHandler, p, medicationRequest, practitioner, organization); + Composition composition = populatePrescriptionComposition(resourceRequestHandler, p, medicationRequest, practitioner, organization); List bundleEnteries = new ArrayList<>(); @@ -166,7 +166,7 @@ public String PopulatePrescriptionResourceBundle(ResourceRequestHandler resource } @Override - public Composition PopulatePrescriptionComposition(ResourceRequestHandler resourceRequestHandler, + public Composition populatePrescriptionComposition(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p, List medicationRequest, Practitioner practitioner, Organization organization) { Composition composition = new Composition(); diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundle.java b/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundle.java index bfb4977..bdb1fd3 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundle.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundle.java @@ -13,10 +13,10 @@ public interface WellnessRecordResourceBundle { - String PopulateWellnessRecordResourceBundle(ResourceRequestHandler resourceRequestHandler, + String populateWellnessRecordResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException; - Composition PopulateWellnessRecordComposition(ResourceRequestHandler resourceRequestHandler, + Composition populateWellnessRecordComposition(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p, Practitioner practitioner, Organization organization, List observationVitalList); diff --git a/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundleImpl.java b/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundleImpl.java index 88ba8d2..90114e7 100644 --- a/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundleImpl.java +++ b/src/main/java/com/wipro/fhir/service/bundle_creation/WellnessRecordResourceBundleImpl.java @@ -64,7 +64,7 @@ public int processWellnessRecordBundle(ResourceRequestHandler resourceRequestHan PatientEligibleForResourceCreation p) throws FHIRException, Exception { int i = 0; // call method to generate Prescription resource - String wellnessBundle = PopulateWellnessRecordResourceBundle(resourceRequestHandler, p); + String wellnessBundle = populateWellnessRecordResourceBundle(resourceRequestHandler, p); // call private method to create mongo object with resource data AMRIT_ResourceMongo aMRIT_ResourceMongo = createPrescriptionBundleMongo(p, wellnessBundle); @@ -78,7 +78,7 @@ public int processWellnessRecordBundle(ResourceRequestHandler resourceRequestHan } @Override - public String PopulateWellnessRecordResourceBundle(ResourceRequestHandler resourceRequestHandler, + public String populateWellnessRecordResourceBundle(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p) throws FHIRException { Bundle wellnessBundle = new Bundle(); String serializeBundle = null; @@ -110,7 +110,7 @@ public String PopulateWellnessRecordResourceBundle(ResourceRequestHandler resour resourceRequestHandler); // Composition - Composition composition = PopulateWellnessRecordComposition(resourceRequestHandler, p, practitioner, + Composition composition = populateWellnessRecordComposition(resourceRequestHandler, p, practitioner, organization, observationVitalList); List bundleEnteries = new ArrayList<>(); @@ -158,7 +158,7 @@ public String PopulateWellnessRecordResourceBundle(ResourceRequestHandler resour } @Override - public Composition PopulateWellnessRecordComposition(ResourceRequestHandler resourceRequestHandler, + public Composition populateWellnessRecordComposition(ResourceRequestHandler resourceRequestHandler, PatientEligibleForResourceCreation p, Practitioner practitioner, Organization organization, List observationVitalList) { Composition comp = new Composition(); diff --git a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java index 0769946..5079ffc 100644 --- a/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java @@ -119,7 +119,7 @@ public String generateTokenForCareContext(String request) throws FHIRException { } GenerateCareContextTokenRequest generateTokenRequest = new GenerateCareContextTokenRequest(); - if (null != careContextLinkRequest.getAbhaNumber() && "" != careContextLinkRequest.getAbhaNumber()) { + if (null != careContextLinkRequest.getAbhaNumber() && careContextLinkRequest.getAbhaNumber().isEmpty() ) { String abha = careContextLinkRequest.getAbhaNumber(); String abhaNumber = abha.replace("-", ""); generateTokenRequest.setAbhaNumber(abhaNumber); @@ -245,7 +245,7 @@ public String linkCareContext(String request) throws FHIRException { headers.add("Authorization", abhaAuthToken); headers.add("X-CM-ID", abhaMode); if (null != addCareContextRequest.getAbdmFacilityId() - && "" != addCareContextRequest.getAbdmFacilityId()) { + && addCareContextRequest.getAbdmFacilityId().isEmpty()) { headers.add("X-HIP-ID", addCareContextRequest.getAbdmFacilityId()); } else { headers.add("X-HIP-ID", abdmFacilityId); @@ -275,7 +275,7 @@ public String linkCareContext(String request) throws FHIRException { pcc.add(patient); } - if (null != addCareContextRequest.getAbhaNumber() && "" != addCareContextRequest.getAbhaNumber()) { + if (null != addCareContextRequest.getAbhaNumber() && addCareContextRequest.getAbhaNumber().isEmpty()) { String abha = addCareContextRequest.getAbhaNumber(); String abhaNumber = abha.replace("-", ""); linkCareContextRequest.setAbhaNumber(abhaNumber);