diff --git a/.factorypath b/.factorypath
index cdf2ab4..71f998d 100644
--- a/.factorypath
+++ b/.factorypath
@@ -1,4 +1,4 @@
-
+
diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties
index d1a7ec3..ea262e0 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_ABHA_V3_URL@/v3/token/generate-token
+linkCareContext = @env.ABDM_ABHA_V3_URL@/hip/v3/link/carecontext
+
x-CM-ID=@env.X_CM_ID@
abhaMode=@env.ABHA_MODE@
diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties
new file mode 100644
index 0000000..e2c39d1
--- /dev/null
+++ b/src/main/environment/common_dev.properties
@@ -0,0 +1,107 @@
+benSearchByBenIDURL=/commonapi-v1.0/beneficiary/searchUserByID
+userAuthURL=/commonapi-v1.0/user/userAuthenticate
+
+# E-aushadhi
+eaushadhiStoreStockDetailsUrl=https://uatbiharsso.dcservices.in/eAushadhi_BIHAR/rest/storeStockDetailsService/
+eaushadhiStoreStockAckUrl=https://uatbiharsso.dcservices.in/eAushadhi_BIHAR/rest/AcknowledgeStoreStockService/
+
+fhirUserName=
+fhirPassword=
+
+# DB Connections (MySQL)
+spring.datasource.url=
+spring.datasource.username=
+spring.datasource.password=
+spring.datasource.driver-class-name=com.mysql.jdbc.Driver
+
+# DB Connection (Mongo DB)
+spring.data.mongodb.host=
+spring.data.mongodb.port=27017
+spring.data.mongodb.authentication-database=
+spring.data.mongodb.database=
+spring.data.mongodb.username=
+spring.data.mongodb.password=
+
+atomsFeedStartPage=1
+parentUrl=https://demo.mybahmni.org
+
+atomFeedURLPatientDemographic=/openmrs/ws/atomfeed/patient/
+atomFeedURLPatientEncounter=/openmrs/ws/atomfeed/encounter/
+
+feedAuthUserName=
+feedAuthPassword=
+
+eAushadhiDummy=yes
+
+##NDHM ABHA API
+clientID=
+clientSecret=
+
+##Default ABDM Facility ID
+abdmFacilityId=
+
+ndhmuserAuthenticate=https://dev.abdm.gov.in/gateway/v0.5/sessions
+ndhmGenerateOTP=https://healthidsbx.abdm.gov.in/api/v1/registration/mobile/generateOtp
+ndhmVerifyOTP=https://healthidsbx.abdm.gov.in/api/v1/registration/mobile/verifyOtp
+ndhmCreateHealthID=https://healthidsbx.abdm.gov.in/api/v1/registration/mobile/createHealthId
+
+## ABHA with aadhaar
+ndhmGenerateOTPWithAadhaar=https://healthidsbx.abdm.gov.in/api/v1/registration/aadhaar/generateOtp
+ndhmCreateHealthIDWithAadhaar=https://healthidsbx.abdm.gov.in/api/v1/registration/aadhaar/createHealthIdWithAadhaarOtp
+
+## ABHA Creation New APIs
+abdmVerifyOTP= https://healthidsbx.abdm.gov.in/api/v1/registration/aadhaar/verifyOTP
+abdmCheckAndGenerateMobileOTP= https://healthidsbx.abdm.gov.in/api/v2/registration/aadhaar/checkAndGenerateMobileOTP
+abdmVerifyMobileOTP= https://healthidsbx.abdm.gov.in/api/v1/registration/aadhaar/verifyMobileOTP
+abdmcreateHealthIdWithPreVerified= https://healthidsbx.abdm.gov.in/api/v1/registration/aadhaar/createHealthIdWithPreVerified
+
+
+##CareContext Creation API
+generateOTPForCareContext=https://dev.abdm.gov.in/gateway/v0.5/users/auth/init
+addCareContext = https://dev.abdm.gov.in/gateway/v0.5/links/link/add-contexts
+validateOTPForCareContext=https://dev.abdm.gov.in/gateway/v0.5/users/auth/confirm
+
+##ABHA Card API
+## Auth init - aadhar / mobile
+generateOTP_ForCard=https://healthidsbx.abdm.gov.in/api/v1/auth/init
+## confirm with mobile OTP
+verifyOTP_ForCard=https://healthidsbx.abdm.gov.in/api/v1/auth/confirmWithMobileOTP
+## confirm with Aadhaar
+verifyOTP_ForCard_Aadhaar=https://healthidsbx.abdm.gov.in/api/v1/auth/confirmWithAadhaarOtp
+## print ABHA card - PNG
+generateHealthCard=https://healthidsbx.abdm.gov.in/api/v1/health/facility/getPngCard
+generateHealthIDCard=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/account/getPngCard
+
+## Generate Notify SMS once episode completed
+generateABDM_NotifySMS=https://dev.abdm.gov.in/gateway/v1/patients/sms/notify2
+
+##verifyBio
+abdmVerifyBio=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/registration/aadhaar/verifyBio
+abdmGenerateMobileOTP=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/registration/aadhaar/generateMobileOTP
+abdmConfirmAadhaarBio=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/confirmWithAadhaarBio
+abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile
+
+##ABDM Facility services
+getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices
+
+##ABDM V3 APIs
+getAuthCertPublicKey = https://healthidsbx.abdm.gov.in/api/v1/auth/cert
+requestOtpForEnrollment = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp
+abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/byAadhaar
+printAbhaCard = https://abhasbx.abdm.gov.in/abha/api/v3/profile/account/abha-card
+abhaLoginRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/request/otp
+verifyAbhaLogin = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/verify
+requestAuthByAbdm = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/auth/byAbdm
+
+## 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
+
+abhaMode=sbx
+
+#logging.pattern.level=DEBUG
+logging.level.root=INFO
+logging.level.org.springframework.web=INFO
+logging.level.org.hibernate=INFO
+logging.level.com.iemr=DEBUG
+logging.level.org.springframework=INFO
diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties
index b54379b..36cfb14 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
diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties
new file mode 100644
index 0000000..e2c39d1
--- /dev/null
+++ b/src/main/environment/common_test.properties
@@ -0,0 +1,107 @@
+benSearchByBenIDURL=/commonapi-v1.0/beneficiary/searchUserByID
+userAuthURL=/commonapi-v1.0/user/userAuthenticate
+
+# E-aushadhi
+eaushadhiStoreStockDetailsUrl=https://uatbiharsso.dcservices.in/eAushadhi_BIHAR/rest/storeStockDetailsService/
+eaushadhiStoreStockAckUrl=https://uatbiharsso.dcservices.in/eAushadhi_BIHAR/rest/AcknowledgeStoreStockService/
+
+fhirUserName=
+fhirPassword=
+
+# DB Connections (MySQL)
+spring.datasource.url=
+spring.datasource.username=
+spring.datasource.password=
+spring.datasource.driver-class-name=com.mysql.jdbc.Driver
+
+# DB Connection (Mongo DB)
+spring.data.mongodb.host=
+spring.data.mongodb.port=27017
+spring.data.mongodb.authentication-database=
+spring.data.mongodb.database=
+spring.data.mongodb.username=
+spring.data.mongodb.password=
+
+atomsFeedStartPage=1
+parentUrl=https://demo.mybahmni.org
+
+atomFeedURLPatientDemographic=/openmrs/ws/atomfeed/patient/
+atomFeedURLPatientEncounter=/openmrs/ws/atomfeed/encounter/
+
+feedAuthUserName=
+feedAuthPassword=
+
+eAushadhiDummy=yes
+
+##NDHM ABHA API
+clientID=
+clientSecret=
+
+##Default ABDM Facility ID
+abdmFacilityId=
+
+ndhmuserAuthenticate=https://dev.abdm.gov.in/gateway/v0.5/sessions
+ndhmGenerateOTP=https://healthidsbx.abdm.gov.in/api/v1/registration/mobile/generateOtp
+ndhmVerifyOTP=https://healthidsbx.abdm.gov.in/api/v1/registration/mobile/verifyOtp
+ndhmCreateHealthID=https://healthidsbx.abdm.gov.in/api/v1/registration/mobile/createHealthId
+
+## ABHA with aadhaar
+ndhmGenerateOTPWithAadhaar=https://healthidsbx.abdm.gov.in/api/v1/registration/aadhaar/generateOtp
+ndhmCreateHealthIDWithAadhaar=https://healthidsbx.abdm.gov.in/api/v1/registration/aadhaar/createHealthIdWithAadhaarOtp
+
+## ABHA Creation New APIs
+abdmVerifyOTP= https://healthidsbx.abdm.gov.in/api/v1/registration/aadhaar/verifyOTP
+abdmCheckAndGenerateMobileOTP= https://healthidsbx.abdm.gov.in/api/v2/registration/aadhaar/checkAndGenerateMobileOTP
+abdmVerifyMobileOTP= https://healthidsbx.abdm.gov.in/api/v1/registration/aadhaar/verifyMobileOTP
+abdmcreateHealthIdWithPreVerified= https://healthidsbx.abdm.gov.in/api/v1/registration/aadhaar/createHealthIdWithPreVerified
+
+
+##CareContext Creation API
+generateOTPForCareContext=https://dev.abdm.gov.in/gateway/v0.5/users/auth/init
+addCareContext = https://dev.abdm.gov.in/gateway/v0.5/links/link/add-contexts
+validateOTPForCareContext=https://dev.abdm.gov.in/gateway/v0.5/users/auth/confirm
+
+##ABHA Card API
+## Auth init - aadhar / mobile
+generateOTP_ForCard=https://healthidsbx.abdm.gov.in/api/v1/auth/init
+## confirm with mobile OTP
+verifyOTP_ForCard=https://healthidsbx.abdm.gov.in/api/v1/auth/confirmWithMobileOTP
+## confirm with Aadhaar
+verifyOTP_ForCard_Aadhaar=https://healthidsbx.abdm.gov.in/api/v1/auth/confirmWithAadhaarOtp
+## print ABHA card - PNG
+generateHealthCard=https://healthidsbx.abdm.gov.in/api/v1/health/facility/getPngCard
+generateHealthIDCard=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/account/getPngCard
+
+## Generate Notify SMS once episode completed
+generateABDM_NotifySMS=https://dev.abdm.gov.in/gateway/v1/patients/sms/notify2
+
+##verifyBio
+abdmVerifyBio=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/registration/aadhaar/verifyBio
+abdmGenerateMobileOTP=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/registration/aadhaar/generateMobileOTP
+abdmConfirmAadhaarBio=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/confirmWithAadhaarBio
+abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile
+
+##ABDM Facility services
+getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices
+
+##ABDM V3 APIs
+getAuthCertPublicKey = https://healthidsbx.abdm.gov.in/api/v1/auth/cert
+requestOtpForEnrollment = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp
+abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/byAadhaar
+printAbhaCard = https://abhasbx.abdm.gov.in/abha/api/v3/profile/account/abha-card
+abhaLoginRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/request/otp
+verifyAbhaLogin = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/verify
+requestAuthByAbdm = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/auth/byAbdm
+
+## 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
+
+abhaMode=sbx
+
+#logging.pattern.level=DEBUG
+logging.level.root=INFO
+logging.level.org.springframework.web=INFO
+logging.level.org.hibernate=INFO
+logging.level.com.iemr=DEBUG
+logging.level.org.springframework=INFO
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..a0afad7
--- /dev/null
+++ b/src/main/java/com/wipro/fhir/data/mongo/care_context/GenerateTokenAbdmResponses.java
@@ -0,0 +1,39 @@
+package com.wipro.fhir.data.mongo.care_context;
+
+import java.time.LocalDateTime;
+
+import org.joda.time.DateTime;
+import org.springframework.data.annotation.Id;
+import org.springframework.data.mongodb.core.mapping.Document;
+import org.springframework.data.mongodb.core.mapping.Field;
+
+import com.google.gson.annotations.Expose;
+
+import lombok.Data;
+
+@Data
+@Document(collection = "GenerateTokenAbdmResponses")
+public class GenerateTokenAbdmResponses {
+
+ @Id
+ @Expose
+ @Field(value = "id")
+ private String id;
+
+ @Expose
+ @Field(value = "abhaAddress")
+ private String abhaAddress;
+
+ @Expose
+ @Field(value = "requestid")
+ private String requestId;
+
+ @Expose
+ @Field(value = "response")
+ private String response;
+
+ @Expose
+ @Field(value = "createdDate")
+ private DateTime createdDate;
+
+}
diff --git a/src/main/java/com/wipro/fhir/data/v3/careContext/AddCareContextRequest.java b/src/main/java/com/wipro/fhir/data/v3/careContext/AddCareContextRequest.java
new file mode 100644
index 0000000..bf42f71
--- /dev/null
+++ b/src/main/java/com/wipro/fhir/data/v3/careContext/AddCareContextRequest.java
@@ -0,0 +1,20 @@
+package com.wipro.fhir.data.v3.careContext;
+
+import lombok.Data;
+
+@Data
+public class AddCareContextRequest {
+
+ private long beneficiaryID;
+ private String abhaAddress;
+ private String abhaNumber;
+ private String linkToken;
+ private String requestId;
+ private String visitCategory;
+ private String visitCode;
+ private String abdmFacilityId;
+ private String abdmFacilityName;
+ private String hiType;
+ private String display;
+
+}
diff --git a/src/main/java/com/wipro/fhir/data/v3/careContext/CareContextLinkTokenRequest.java b/src/main/java/com/wipro/fhir/data/v3/careContext/CareContextLinkTokenRequest.java
new file mode 100644
index 0000000..83d7b36
--- /dev/null
+++ b/src/main/java/com/wipro/fhir/data/v3/careContext/CareContextLinkTokenRequest.java
@@ -0,0 +1,15 @@
+package com.wipro.fhir.data.v3.careContext;
+
+import lombok.Data;
+
+@Data
+public class CareContextLinkTokenRequest {
+
+ private String abhaNumber;
+ private String abhaAddress;
+ private String name;
+ private String gender;
+ private int yearOfBirth;
+ private String abdmFacilityId;
+
+}
diff --git a/src/main/java/com/wipro/fhir/data/v3/careContext/CareContexts.java b/src/main/java/com/wipro/fhir/data/v3/careContext/CareContexts.java
new file mode 100644
index 0000000..112b244
--- /dev/null
+++ b/src/main/java/com/wipro/fhir/data/v3/careContext/CareContexts.java
@@ -0,0 +1,11 @@
+package com.wipro.fhir.data.v3.careContext;
+
+import lombok.Data;
+
+@Data
+public class CareContexts {
+
+ private String referenceNumber;
+ private String display;
+
+}
diff --git a/src/main/java/com/wipro/fhir/data/v3/careContext/GenerateCareContextTokenRequest.java b/src/main/java/com/wipro/fhir/data/v3/careContext/GenerateCareContextTokenRequest.java
new file mode 100644
index 0000000..6dcac58
--- /dev/null
+++ b/src/main/java/com/wipro/fhir/data/v3/careContext/GenerateCareContextTokenRequest.java
@@ -0,0 +1,14 @@
+package com.wipro.fhir.data.v3.careContext;
+
+import lombok.Data;
+
+@Data
+public class GenerateCareContextTokenRequest {
+
+ private String abhaNumber;
+ private String abhaAddress;
+ private String name;
+ private String gender;
+ private int yearOfBirth;
+
+}
diff --git a/src/main/java/com/wipro/fhir/data/v3/careContext/LinkCareContextRequest.java b/src/main/java/com/wipro/fhir/data/v3/careContext/LinkCareContextRequest.java
new file mode 100644
index 0000000..162cabc
--- /dev/null
+++ b/src/main/java/com/wipro/fhir/data/v3/careContext/LinkCareContextRequest.java
@@ -0,0 +1,14 @@
+package com.wipro.fhir.data.v3.careContext;
+
+import java.util.List;
+import lombok.Data;
+
+@Data
+public class LinkCareContextRequest {
+
+ private String abhaNumber;
+ private String abhaAddress;
+ private List patient;
+
+
+}
diff --git a/src/main/java/com/wipro/fhir/data/v3/careContext/PatientCareContext.java b/src/main/java/com/wipro/fhir/data/v3/careContext/PatientCareContext.java
new file mode 100644
index 0000000..2603562
--- /dev/null
+++ b/src/main/java/com/wipro/fhir/data/v3/careContext/PatientCareContext.java
@@ -0,0 +1,16 @@
+package com.wipro.fhir.data.v3.careContext;
+
+import java.util.List;
+import lombok.Data;
+
+@Data
+public class PatientCareContext {
+
+ private String referenceNumber;
+ private String display;
+ private List careContexts;
+ private String hiType;
+ private int count;
+
+
+}
diff --git a/src/main/java/com/wipro/fhir/repo/mongo/generateToken_response/GenerateTokenAbdmResponsesRepo.java b/src/main/java/com/wipro/fhir/repo/mongo/generateToken_response/GenerateTokenAbdmResponsesRepo.java
new file mode 100644
index 0000000..ea900af
--- /dev/null
+++ b/src/main/java/com/wipro/fhir/repo/mongo/generateToken_response/GenerateTokenAbdmResponsesRepo.java
@@ -0,0 +1,17 @@
+package com.wipro.fhir.repo.mongo.generateToken_response;
+
+import org.springframework.data.mongodb.repository.MongoRepository;
+import org.springframework.data.rest.core.annotation.RestResource;
+import org.springframework.stereotype.Repository;
+
+import com.wipro.fhir.data.mongo.care_context.GenerateTokenAbdmResponses;
+
+@Repository
+@RestResource(exported = false)
+public interface GenerateTokenAbdmResponsesRepo extends MongoRepository {
+
+ GenerateTokenAbdmResponses findByAbhaAddress(String abhaAddress);
+
+
+
+}
diff --git a/src/main/java/com/wipro/fhir/service/v3/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..820869b
--- /dev/null
+++ b/src/main/java/com/wipro/fhir/service/v3/careContext/CareContextLinkingServiceImpl.java
@@ -0,0 +1,304 @@
+package com.wipro.fhir.service.v3.careContext;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.TimeZone;
+import java.util.UUID;
+import java.time.LocalDateTime;
+import java.time.temporal.ChronoUnit;
+
+import org.joda.time.DateTime;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatusCode;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Service;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.client.RestTemplate;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.wipro.fhir.data.mongo.care_context.GenerateTokenAbdmResponses;
+import com.wipro.fhir.data.v3.abhaCard.LoginMethod;
+import com.wipro.fhir.data.v3.abhaCard.RequestOTPEnrollment;
+import com.wipro.fhir.data.v3.careContext.CareContextLinkTokenRequest;
+import com.wipro.fhir.data.v3.careContext.CareContexts;
+import com.wipro.fhir.data.v3.careContext.GenerateCareContextTokenRequest;
+import com.wipro.fhir.data.v3.careContext.LinkCareContextRequest;
+import com.wipro.fhir.data.v3.careContext.PatientCareContext;
+import com.wipro.fhir.repo.mongo.generateToken_response.GenerateTokenAbdmResponsesRepo;
+import com.wipro.fhir.data.v3.careContext.AddCareContextRequest;
+import com.wipro.fhir.service.ndhm.Common_NDHMService;
+import com.wipro.fhir.service.v3.abha.GenerateAuthSessionService;
+import com.wipro.fhir.utils.exception.FHIRException;
+import com.wipro.fhir.utils.mapper.InputMapper;
+
+@Service
+public class CareContextLinkingServiceImpl implements CareContextLinkingService {
+
+ @Autowired
+ private GenerateAuthSessionService generateAuthSessionService;
+
+ @Autowired
+ private Common_NDHMService common_NDHMService;
+
+ @Autowired
+ private GenerateTokenAbdmResponsesRepo generateTokenAbdmResponsesRepo;
+
+ @Value("${x-CM-ID}")
+ String abhaMode;
+
+ @Value("${abdmFacilityId}")
+ String abdmFacilityId;
+
+ @Value("${generateTokenForLinkCareContext}")
+ String generateTokenForLinkCareContext;
+
+ @Value("${linkCareContext}")
+ String linkCareContext;
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
+
+ @Override
+ public String generateTokenForCareContext(String request) throws FHIRException {
+ String res = null;
+ String linkToken = null;
+ Map responseMap = new HashMap<>();
+ RestTemplate restTemplate = new RestTemplate();
+
+ try {
+ String abhaAuthToken = generateAuthSessionService.getAbhaAuthToken();
+ CareContextLinkTokenRequest careContextLinkRequest = InputMapper.gson().fromJson(request,
+ CareContextLinkTokenRequest.class);
+
+ if (null != careContextLinkRequest.getAbhaAddress()) {
+ String linkExists = checkRecordExisits(careContextLinkRequest.getAbhaAddress());
+ responseMap.put("linkToken", linkExists);
+ } else {
+
+ MultiValueMap headers = new LinkedMultiValueMap<>();
+ headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8");
+ String requestId = UUID.randomUUID().toString();
+ headers.add("REQUEST-ID", requestId);
+
+ TimeZone tz = TimeZone.getTimeZone("UTC");
+ DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+ df.setTimeZone(tz);
+ String nowAsISO = df.format(new Date());
+ headers.add("TIMESTAMP", nowAsISO);
+ headers.add("Authorization", abhaAuthToken);
+ headers.add("X-CM-ID", abhaMode);
+ if (null != careContextLinkRequest.getAbdmFacilityId()
+ && "" != careContextLinkRequest.getAbdmFacilityId()) {
+ headers.add("X-HIP-ID", careContextLinkRequest.getAbdmFacilityId());
+ } else {
+ headers.add("X-HIP-ID", abdmFacilityId);
+ }
+
+ GenerateCareContextTokenRequest generateTokenRequest = new GenerateCareContextTokenRequest();
+ if (null != careContextLinkRequest.getAbhaNumber() && "" != careContextLinkRequest.getAbhaNumber()) {
+ String abha = careContextLinkRequest.getAbhaNumber();
+ String abhaNumber = abha.replace("-", "");
+ generateTokenRequest.setAbhaNumber(abhaNumber);
+ }
+
+ generateTokenRequest.setAbhaAddress(careContextLinkRequest.getAbhaAddress());
+ generateTokenRequest.setName(careContextLinkRequest.getName());
+ generateTokenRequest.setYearOfBirth(careContextLinkRequest.getYearOfBirth());
+
+ if (careContextLinkRequest.getGender().equalsIgnoreCase("female")) {
+ generateTokenRequest.setGender("F");
+ } else if (careContextLinkRequest.getGender().equalsIgnoreCase("male")) {
+ generateTokenRequest.setGender("M");
+ } else {
+ generateTokenRequest.setGender("O");
+ }
+
+ String requestOBJ = new Gson().toJson(generateTokenRequest);
+ logger.info("ABDM reqobj for generate token link for carecontext : " + requestOBJ);
+
+ HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers);
+ ResponseEntity responseEntity = restTemplate.exchange(generateTokenForLinkCareContext,
+ HttpMethod.POST, httpEntity, String.class);
+
+ logger.info("ABDM response for generate token link for carecontext : " + responseEntity);
+ String responseStrLogin = common_NDHMService.getBody(responseEntity);
+ JsonParser jsnParser = new JsonParser();
+ if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(202)) {
+ String mongoResponse = common_NDHMService.getMongoNDHMResponse(requestId);
+ responseMap.put("requestId", requestId);
+ if (!mongoResponse.equalsIgnoreCase("failure")) {
+ JsonElement jsnElmnt1 = jsnParser.parse(mongoResponse);
+ JsonObject jsnOBJ1 = new JsonObject();
+ jsnOBJ1 = jsnElmnt1.getAsJsonObject();
+ try {
+ if (jsnOBJ1.get("linkToken") != null) {
+ linkToken = jsnOBJ1.getAsJsonObject("linkToken").getAsString();
+ responseMap.put("linkToken", linkToken);
+ } else
+ throw new FHIRException(
+ "NDHM_FHIR " + jsnOBJ1.getAsJsonObject("Error").get("Message").getAsString());
+ } catch (Exception e) {
+ throw new FHIRException(
+ "NDHM_FHIR " + jsnOBJ1.getAsJsonObject("Error").get("Message").getAsString());
+ }
+ }
+
+ } else {
+ throw new FHIRException(responseEntity.getBody());
+ }
+ }
+ } catch (Exception e) {
+ throw new FHIRException(e.getMessage());
+ }
+
+ return responseMap.toString();
+ }
+
+ @Override
+ public String linkCareContext(String request) throws FHIRException {
+ String res = null;
+ String linkToken = null;
+ Map responseMap = new HashMap<>();
+ RestTemplate restTemplate = new RestTemplate();
+
+ try {
+ String abhaAuthToken = generateAuthSessionService.getAbhaAuthToken();
+ AddCareContextRequest addCareContextRequest = InputMapper.gson().fromJson(request,
+ AddCareContextRequest.class);
+ MultiValueMap headers = new LinkedMultiValueMap<>();
+ JsonParser jsnParser = new JsonParser();
+
+ if (null != addCareContextRequest.getLinkToken()) {
+ headers.add("X-LINK-TOKEN", addCareContextRequest.getLinkToken());
+ } else { // if link token is not found then fetch from mongo DB
+ String mongoResponse = common_NDHMService.getMongoNDHMResponse(addCareContextRequest.getRequestId());
+ if (!mongoResponse.equalsIgnoreCase("failure")) {
+ JsonElement jsnElmnt1 = jsnParser.parse(mongoResponse);
+ JsonObject jsnOBJ1 = new JsonObject();
+ jsnOBJ1 = jsnElmnt1.getAsJsonObject();
+ try {
+ if (jsnOBJ1.get("linkToken") != null) {
+ linkToken = jsnOBJ1.getAsJsonObject("linkToken").getAsString();
+ headers.add("X-LINK-TOKEN", linkToken);
+ } else
+ throw new FHIRException(
+ "ABDM_FHIR " + jsnOBJ1.getAsJsonObject("Error").get("Message").getAsString());
+ } catch (Exception e) {
+ throw new FHIRException(
+ "ABDM_FHIR " + jsnOBJ1.getAsJsonObject("Error").get("Message").getAsString());
+ }
+ }
+
+ }
+
+ headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8");
+ headers.add("REQUEST-ID", UUID.randomUUID().toString());
+
+ TimeZone tz = TimeZone.getTimeZone("UTC");
+ DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+ df.setTimeZone(tz);
+ String nowAsISO = df.format(new Date());
+ headers.add("TIMESTAMP", nowAsISO);
+ headers.add("Authorization", abhaAuthToken);
+ headers.add("X-CM-ID", abhaMode);
+ if (null != addCareContextRequest.getAbdmFacilityId() && "" != addCareContextRequest.getAbdmFacilityId()) {
+ headers.add("X-HIP-ID", addCareContextRequest.getAbdmFacilityId());
+ } else {
+ headers.add("X-HIP-ID", abdmFacilityId);
+ }
+
+ LinkCareContextRequest linkCareContextRequest = new LinkCareContextRequest();
+ CareContexts careContexts = new CareContexts();
+ PatientCareContext patient = new PatientCareContext();
+
+ ArrayList cc = new ArrayList();
+ careContexts.setReferenceNumber(addCareContextRequest.getVisitCode());
+ careContexts.setDisplay(addCareContextRequest.getDisplay());
+ cc.add(careContexts);
+
+ ArrayList pcc = new ArrayList();
+ patient.setReferenceNumber(addCareContextRequest.getVisitCode());
+ patient.setDisplay(addCareContextRequest.getDisplay());
+ patient.setDisplay(addCareContextRequest.getDisplay());
+ patient.setCount(1);
+ patient.setCareContexts(cc);
+ pcc.add(patient);
+
+ if (null != addCareContextRequest.getAbhaNumber() && "" != addCareContextRequest.getAbhaNumber()) {
+ String abha = addCareContextRequest.getAbhaNumber();
+ String abhaNumber = abha.replace("-", "");
+ linkCareContextRequest.setAbhaNumber(abhaNumber);
+ }
+
+ linkCareContextRequest.setAbhaAddress(addCareContextRequest.getAbhaAddress());
+ linkCareContextRequest.setPatient(pcc);
+
+ String requestOBJ = new Gson().toJson(linkCareContextRequest);
+ logger.info("ABDM reqobj for generate token link for carecontext : " + requestOBJ);
+
+ HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers);
+ ResponseEntity responseEntity = restTemplate.exchange(linkCareContext, HttpMethod.POST, httpEntity,
+ String.class);
+
+ logger.info("ABDM response for generate token link for carecontext : " + responseEntity);
+ String responseStrLogin = common_NDHMService.getBody(responseEntity);
+ if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(202)) {
+ res = "Care Context added successfully";
+
+ } else {
+ throw new FHIRException(responseEntity.getBody());
+ }
+ } catch (Exception e) {
+ throw new FHIRException(e.getMessage());
+ }
+
+ return res;
+ }
+
+ public String checkRecordExisits(String abhaAddress) {
+ GenerateTokenAbdmResponses result = generateTokenAbdmResponsesRepo.findByAbhaAddress(abhaAddress);
+ logger.info("find by abha address result - ", result);
+
+ if (result != null && result.getCreatedDate() != null) {
+ Calendar cal = Calendar.getInstance();
+ cal.add(Calendar.MONTH, -3);
+ Date threeMonthsAgo = cal.getTime();
+ String linkResponse = result.getResponse();
+
+ if (result.getCreatedDate().isAfter(threeMonthsAgo.getTime())) {
+ if (linkResponse != null) {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ JsonNode root = mapper.readTree(linkResponse);
+ JsonNode linkToken = root.path("LinkToken");
+ if (!linkToken.isNull() && !linkToken.isMissingNode()) {
+ return linkToken.asText();
+ }
+ } catch (Exception e) {
+ logger.info("failed abha exists check with exception - ", e.getMessage());
+ return null;
+ }
+ }
+ }
+ }
+
+ return null;
+ }
+
+}