diff --git a/.factorypath b/.factorypath index cdf2ab4..71f998d 100644 --- a/.factorypath +++ b/.factorypath @@ -1,4 +1,4 @@ - + diff --git a/pom.xml b/pom.xml index e1f2944..2909c01 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ com.wipro.fhir.r4 fhir-api - 3.6.0 + 3.6.1 war FHIR-API FHIR_NDHM standard integration in AMRIT @@ -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 d1a7ec3..cda0a73 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -98,6 +98,10 @@ webLoginAbhaRequestOtp = @env.ABDM_PHR_URL@/login/abha/request/otp 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_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@ @@ -120,3 +124,5 @@ springdoc.swagger-ui.enabled=@env.SWAGGER_DOC_ENABLED@ spring.redis.host=@env.REDIS_HOST@ cors.allowed-origins=@env.CORS_ALLOWED_ORIGINS@ + +hipSystemUrl= @env.HIP_SYSTEM_URL@ diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index 82239d6..496239d 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -98,6 +98,10 @@ webLoginAbhaRequestOtp = ${ABDM_PHR_URL}/login/abha/request/otp webLoginAbhaVerify = ${ABDM_PHR_URL}/login/abha/verify webLoginPhrCard = ${ABDM_PHR_URL}/login/profile/abha/phr-card +## ABDM V3 M2 APIs +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=${X_CM_ID} abhaMode=${ABHA_MODE} @@ -117,4 +121,7 @@ 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} + + +hipSystemUrl= ${HIP_SYSTEM_URL} diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index b54379b..4e99ca7 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -100,6 +100,10 @@ requestAuthByAbdm = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/auth/byAb webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify webLoginPhrCard = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/profile/abha/phr-card +## ABDM V3 M2 APIs +generateTokenForLinkCareContext = https://dev.abdm.gov.in/api/hiecm/v3/token/generate-token +linkCareContext = https://dev.abdm.gov.in/api/hiecm/hip/v3/link/carecontext + x-CM-ID= sbx abhaMode=sbx @@ -113,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:* + +hipSystemUrl= \ No newline at end of file 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..c888027 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..138db28 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/controller/v3/abha/CreateAbhaV3Controller.java b/src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java index 4d95154..3c08ece 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 @@ -3,7 +3,7 @@ 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; @@ -60,6 +60,8 @@ public String abhaEnrollmentByAadhaar(@RequestBody String request) { logger.info("NDHM_FHIR generate OTP for ABHA card API response " + response.toString()); return response.toString(); } + + @CrossOrigin @Operation(summary = "Verify Auth By ABDM for ABHA enrollment") @PostMapping(value = { "/verifyAuthByAbdm" }) public String verifyMobileForAuth(@RequestBody String request) { 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..153d393 --- /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 java.util.Date; + +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 Date createdDate; + +} 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..dc1aba7 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/resource_model/MedicalHistoryDataModel.java @@ -0,0 +1,63 @@ +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 providerServiceMapID; + private String currentMedication; + 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.providerServiceMapID = objArr[1] != null ? BigInteger.valueOf(Long.parseLong(objArr[1].toString())) : null; + + this.currentMedication = objArr[2] != null ? objArr[2].toString() : null; + + this.currentMedYear = objArr[3] instanceof Timestamp ? (Timestamp) objArr[3] : null; + + this.createdBy = objArr[4] != null ? objArr[4].toString() : null; + + this.createdDate = objArr[5] instanceof Timestamp ? (Timestamp) objArr[5] : null; + + } catch (Exception e) { + throw new Exception("Medical History resource model failed with error - " + e.getMessage()); + } + + } + + public List getMedicalList(List resultSetList) throws Exception { + 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..21bc063 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/resource_model/OrganizationDataModel.java @@ -0,0 +1,88 @@ +package com.wipro.fhir.data.resource_model; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.stereotype.Component; + +import com.wipro.fhir.utils.exception.FHIRException; + +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) 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.stateID = objArr[3] != null ? Integer.parseInt(objArr[3].toString()) : null; + this.stateName = objArr[4] != null ? objArr[4].toString() : null; + + this.districtID = objArr[5] != null ? Integer.parseInt(objArr[5].toString()) : null; + this.districtName = objArr[6] != null ? objArr[6].toString() : null; + + this.locationName = objArr[7] != null ? objArr[7].toString() : null; + this.address = objArr[8] != null ? objArr[8].toString() : null; + + this.serviceID = objArr[9] != null ? Short.parseShort(objArr[9].toString()) : null; + this.serviceName = objArr[10] != null ? objArr[10].toString() : null; + + this.isNational = objArr[11] != null + ? objArr[11].toString().equalsIgnoreCase("true") || objArr[11].toString().equals("1") + : null; + + this.abdmFacilityId = objArr[12] != null ? objArr[12].toString() : null; + this.abdmFacilityName = objArr[13] != null ? objArr[13].toString() : 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("Organization resource failed with error - " + e.getMessage()); + } + + } + + + public OrganizationDataModel getOrganization(Object[] resultSet) throws FHIRException { + + 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..085abf6 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/resource_model/PractitionerDataModel.java @@ -0,0 +1,83 @@ +package com.wipro.fhir.data.resource_model; + +import java.sql.Timestamp; +import java.util.Date; + +import org.springframework.stereotype.Component; + +import com.wipro.fhir.utils.exception.FHIRException; + +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) 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("Practitioner resource failed with error - " + e.getMessage()); + } + + } + + + public PractitionerDataModel getPractitioner(Object[] resultSet) throws FHIRException { + if (resultSet == null || resultSet.length == 0) { + return null; + } + return new PractitionerDataModel(resultSet); + } + +} 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/common/PatientEligibleForResourceCreationRepo.java b/src/main/java/com/wipro/fhir/repo/common/PatientEligibleForResourceCreationRepo.java index 931315a..17cbc85 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,19 @@ 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)") + 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/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..70db7ac --- /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); + + GenerateTokenAbdmResponses findByRequestId(String requestId); + +} 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..26696b1 --- /dev/null +++ b/src/main/java/com/wipro/fhir/repo/v3/careContext/CareContextRepo.java @@ -0,0 +1,25 @@ +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 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(@Param("visitCode") String visitCode); + + @Query(value="SELECT COUNT(*) FROM t_prescribeddrug WHERE VisitCode = :visitCode", nativeQuery = true) + public int hasPrescribedDrugs(@Param("visitCode") String visitCode); + + @Query(value="SELECT COUNT(*) FROM t_lab_testorder WHERE VisitCode = :visitCode", nativeQuery = true) + public int hasLabtestsDone(@Param("visitCode") String visitCode); + + @Query(value="SELECT COUNT(*) FROM t_childvaccinedetail1 WHERE VisitCode = :visitCode", nativeQuery = true) + public int hasVaccineDetails(@Param("visitCode") String visitCode); + +} 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..61c2bd4 --- /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..71d4f0c --- /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("${hipSystemUrl}") + 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..e06bdf5 --- /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..db6c76b --- /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("${hipSystemUrl}") + 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..5174c2a --- /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..95c8849 --- /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("${hipSystemUrl}") + 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..10a3ff1 --- /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..08322a1 --- /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("${hipSystemUrl}") + 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..c68fcc7 --- /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..b82cfd7 --- /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("${hipSystemUrl}") + 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..bdb1fd3 --- /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..90114e7 --- /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("${hipSystemUrl}") + 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/ndhm/Common_NDHMService.java b/src/main/java/com/wipro/fhir/service/ndhm/Common_NDHMService.java index a20245a..45fc15e 100644 --- a/src/main/java/com/wipro/fhir/service/ndhm/Common_NDHMService.java +++ b/src/main/java/com/wipro/fhir/service/ndhm/Common_NDHMService.java @@ -24,6 +24,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; +import com.wipro.fhir.data.mongo.care_context.GenerateTokenAbdmResponses; import com.wipro.fhir.data.mongo.care_context.NDHMRequest; import com.wipro.fhir.utils.exception.FHIRException; @@ -36,4 +37,5 @@ public interface Common_NDHMService { public String getStatusCode(ResponseEntity 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..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,14 +27,18 @@ 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; 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 +47,11 @@ public class Common_NDHMServiceImpl implements Common_NDHMService { @Autowired private NDHMResponseRepo nDHMResponseRepo; + @Autowired + private GenerateTokenAbdmResponsesRepo generateTokenAbdmResponsesRepo; + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + /*** * @author SH20094090 * @return headers for the NDHM API's @@ -149,6 +158,20 @@ NDHMResponse getResponseMongo(String reqID) { } else return null; } + + @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 { + return null; + } + + } + + @Override public String getBody(ResponseEntity res) throws FHIRException { 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/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..6e3a5c5 --- /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) throws Exception { + + 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..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 @@ -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..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 @@ -21,77 +21,90 @@ */ 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()); + 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"); + } } - // 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..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 @@ -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("${hipSystemUrl}") + 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; } + + } 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 e25211d..2e27d8e 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 @@ -280,7 +280,6 @@ public String verifyAuthByAbdm(String request) throws FHIRException { DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT; String formattedTimestamp = now.format(formatter); otp.setTimestamp(formattedTimestamp); - otp.setTxnId(loginMethod.getTxnId()); otp.setOtpValue(encryptedLoginId); 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..5079ffc --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java @@ -0,0 +1,400 @@ +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.List; +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.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; +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; + + @Autowired + private CareContextRepo careContextRepo; + + 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(); + String linkExists = null; + + try { + String abhaAuthToken = generateAuthSessionService.getAbhaAuthToken(); + CareContextLinkTokenRequest careContextLinkRequest = InputMapper.gson().fromJson(request, + CareContextLinkTokenRequest.class); + + if (null != careContextLinkRequest.getAbhaAddress()) { + linkExists = checkRecordExisits(careContextLinkRequest.getAbhaAddress()); + } + if(linkExists != null) { + 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().isEmpty() ) { + 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)) { + GenerateTokenAbdmResponses mongoResponse = common_NDHMService.getLinkToken(requestId); + responseMap.put("requestId", requestId); + 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); + logger.info("Mongo has link token"); + } else { + if (jsonObject.has("Error") && !jsonObject.get("Error").isJsonNull()) { + JsonObject errorObject = jsonObject.getAsJsonObject("Error"); + logger.info("Mongo has no link token other message - " + errorObject.toString()); + 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 { + throw new FHIRException(responseEntity.getBody()); + } + } + } catch (Exception e) { + throw new FHIRException(e.getMessage()); + } + + return new Gson().toJson(responseMap); + } + + @Override + public String linkCareContext(String request) throws FHIRException { + 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()) { + 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 + .getLinkToken(addCareContextRequest.getRequestId()); + 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(); + 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"); + } + } + } catch (Exception e) { + 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().isEmpty()) { + headers.add("X-HIP-ID", addCareContextRequest.getAbdmFacilityId()); + } else { + headers.add("X-HIP-ID", abdmFacilityId); + } + + String[] hiTypes = findHiTypes(addCareContextRequest.getVisitCode(), + addCareContextRequest.getVisitCategory()); + + LinkCareContextRequest linkCareContextRequest = new LinkCareContextRequest(); + CareContexts careContexts = new CareContexts(); + ArrayList pcc = new ArrayList(); + + for (String hiType : hiTypes) { + PatientCareContext patient = new PatientCareContext(); + + ArrayList cc = new ArrayList(); + careContexts.setReferenceNumber(addCareContextRequest.getVisitCode()); + careContexts.setDisplay(addCareContextRequest.getVisitCategory()); + cc.add(careContexts); + + patient.setReferenceNumber(addCareContextRequest.getVisitCode()); + patient.setDisplay(addCareContextRequest.getVisitCategory() + " - " + hiType + " care context of " + + addCareContextRequest.getAbhaNumber()); + patient.setCount(1); + patient.setCareContexts(cc); + patient.setHiType(hiType); + pcc.add(patient); + } + + if (null != addCareContextRequest.getAbhaNumber() && addCareContextRequest.getAbhaNumber().isEmpty()) { + 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 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)) { + responseMap.put("message", "Care Context added successfully"); + + } 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"); + } + } + } + } 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) { + 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()); + } + } + + return new Gson().toJson(responseMap); + } + + 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(); + linkResponse = result.getResponse(); + + if (result.getCreatedDate().after(threeMonthsAgo)) { + 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 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("DiagnosticReport"); + } + + int hasVaccineDetails = careContextRepo.hasVaccineDetails(visitCode); + if (hasVaccineDetails > 0) { + hiTypes.add("ImmunizationRecord"); + } + logger.info("HiTypes", hiTypes); + return hiTypes.toArray(new String[0]); + } + +} +