diff --git a/src/In.ProjectEKA.HipLibrary/Patient/Model/CareContextRepresentation.cs b/src/In.ProjectEKA.HipLibrary/Patient/Model/CareContextRepresentation.cs index 8ff0831fc..691a31e8c 100644 --- a/src/In.ProjectEKA.HipLibrary/Patient/Model/CareContextRepresentation.cs +++ b/src/In.ProjectEKA.HipLibrary/Patient/Model/CareContextRepresentation.cs @@ -5,13 +5,14 @@ namespace In.ProjectEKA.HipLibrary.Patient.Model { public class CareContextRepresentation { - [JsonConstructor] + public CareContextRepresentation(string referenceNumber, string display) { ReferenceNumber = referenceNumber; Display = display; } - + + [JsonConstructor] public CareContextRepresentation(string referenceNumber, string display, string type, IEnumerable hiTypes) { diff --git a/src/In.ProjectEKA.HipService/Common/Constants.cs b/src/In.ProjectEKA.HipService/Common/Constants.cs index bf5438f54..f12ebcb99 100644 --- a/src/In.ProjectEKA.HipService/Common/Constants.cs +++ b/src/In.ProjectEKA.HipService/Common/Constants.cs @@ -27,6 +27,9 @@ public static class Constants public const string APP_PATH_VERIFICATION_ABHAADDRESS_PROFILE = "/" + VERSION_V3 + "/hip/verification/abhaAddress/getProfile"; public const string APP_PATH_VERIFICATION_ABHAADDRESS_CARD = "/" + VERSION_V3 + "/hip/verification/abhaAddress/getCard"; + public const string PATH_GENERATE_TOKEN = "/api/hiecm/"+ VERSION_V3 +"/token/generate-token"; + public const string PATH_ON_GENERATE_TOKEN = "/api/"+ VERSION_V3 +"/hip/token/on-generate-token"; + public const string PATH_SESSIONS = "api/hiecm/gateway/"+VERSION_V3+"/sessions"; public const string PATH_CARE_CONTEXTS_DISCOVER = "/api/"+VERSION_V3 + "/hip/patient/care-context/discover"; public const string PATH_CONSENTS_HIP = "/api/" + VERSION_V3 + "/consent/request/hip/notify"; @@ -39,8 +42,8 @@ public static class Constants public const string PATH_ON_AUTH_CONFIRM = CURRENT_VERSION + "/users/auth/on-confirm"; public const string PATH_ON_AUTH_INIT = "/" + CURRENT_VERSION + "/users/auth/on-init"; public const string PATH_ON_FETCH_AUTH_MODES = "/" + CURRENT_VERSION + "/users/auth/on-fetch-modes"; - public const string PATH_ON_ADD_CONTEXTS = "/" + CURRENT_VERSION + "/links/link/on-add-contexts"; - public const string PATH_ON_NOTIFY_CONTEXTS = "/" + CURRENT_VERSION + "/links/context/on-notify"; + public const string PATH_ON_ADD_CONTEXTS = "/api/"+ VERSION_V3 +"/link/on_carecontext"; + public const string PATH_ON_NOTIFY_CONTEXTS = "/api/"+ VERSION_V3 +"/links/context/on-notify"; public static readonly string DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffZ"; public static readonly string PATH_ON_DISCOVER = "/api/hiecm/user-initiated-linking/"+VERSION_V3+"/patient/care-context/on-discover"; public static readonly string PATH_ON_LINK_INIT = "/api/hiecm/user-initiated-linking/"+VERSION_V3+"/link/care-context/on-init"; @@ -65,26 +68,23 @@ public static class Constants public const string TIMESTAMP = "TIMESTAMP"; public const string PATH_PATIENT_PROFILE_ON_SHARE = "/" + CURRENT_VERSION + "/patients/profile/on-share"; public const string PATH_FETCH_AUTH_MODES = "/" + CURRENT_VERSION + "/users/auth/fetch-modes"; - public const string PATH_ADD_PATIENT_CONTEXTS = "/" + CURRENT_VERSION + "/links/link/add-contexts"; - public const string PATH_NOTIFY_PATIENT_CONTEXTS = "/" + CURRENT_VERSION + "/links/context/notify"; + public const string PATH_ADD_PATIENT_CONTEXTS = "/api/hiecm/hip/" + VERSION_V3 + "/link/carecontext"; + public const string PATH_NOTIFY_PATIENT_CONTEXTS = "/api/hiecm/hip/"+ VERSION_V3 +"/link/context/notify"; public const string PATH_FETCH_MODES = "/" + CURRENT_VERSION + "/hip/fetch-modes"; public const string PATH_NEW_CARECONTEXT = "/" + CURRENT_VERSION + "/hip/new-carecontext"; - public const string PATH_ADD_CONTEXTS = "/" + CURRENT_VERSION + "/hip/add-contexts"; - public const string PATH_NOTIFY_CONTEXTS = "/" + CURRENT_VERSION + "/hip/notify"; public const string KYC_AND_LINK = "KYC_AND_LINK"; public const string HIP = "HIP"; public const string PATH_AUTH_INIT = "/" + CURRENT_VERSION + "/users/auth/init"; public const string PATH_HIP_AUTH_INIT = "/" + CURRENT_VERSION + "/hip/auth/init"; public const string PATH_HIP_AUTH_CONFIRM = "/" + CURRENT_VERSION + "/hip/auth/confirm"; public const string PATH_ADD_NDHM_DEMOGRAPHICS = "/" + CURRENT_VERSION + "/hip/ndhm-demographics"; - public const string PATH_DEMOGRAPHICS = "/" + CURRENT_VERSION + "/hip/auth/demographics"; public const string PATH_HIP_DIRECT_AUTH = "/" + CURRENT_VERSION + "/hip/auth/direct"; public const string PATH_AUTH_NOTIFY = "/" + CURRENT_VERSION + "/users/auth/notify"; public const string PATH_AUTH_ON_NOTIFY = "/" + CURRENT_VERSION + "/users/auth/on-notify"; public const string PATH_HIP_SMS_NOTIFY = "/" + CURRENT_VERSION + "/hip/patients/sms/notify"; - public const string PATH_SMS_NOTIFY = "/" + CURRENT_VERSION + "/patients/sms/notify2"; - public const string PATH_SMS_ON_NOTIFY = "/" + CURRENT_VERSION + "/patients/sms/on-notify"; + public const string PATH_SMS_NOTIFY = "/api/hiecm/hip/"+ VERSION_V3 +"/link/patient/links/sms/notify2"; + public const string PATH_SMS_ON_NOTIFY = "/api/"+ VERSION_V3 +"/patients/sms/on-notify"; public const string REPORTING_SESSION = "reporting_session"; public const string OPENMRS_SESSION_ID_COOKIE_NAME = "JSESSIONID"; diff --git a/src/In.ProjectEKA.HipService/Common/HttpRequestHelper.cs b/src/In.ProjectEKA.HipService/Common/HttpRequestHelper.cs index acb900191..c0c5e53f7 100644 --- a/src/In.ProjectEKA.HipService/Common/HttpRequestHelper.cs +++ b/src/In.ProjectEKA.HipService/Common/HttpRequestHelper.cs @@ -23,7 +23,11 @@ public static HttpRequestMessage CreateHttpRequest( string correlationId, string xtoken = null, string tToken = null, - string transactionId = null) + string transactionId = null, + string hipId = null, + string requestId = null, + string linkToken = null + ) { HttpRequestMessage httpRequestMessage = new HttpRequestMessage(method, new Uri($"{url}")); ; @@ -56,7 +60,11 @@ public static HttpRequestMessage CreateHttpRequest( httpRequestMessage.Headers.Add(CORRELATION_ID, correlationId); if (transactionId != null) httpRequestMessage.Headers.Add("Transaction_Id", transactionId); - httpRequestMessage.Headers.Add("REQUEST-ID", Guid.NewGuid().ToString()); + if(hipId != null) + httpRequestMessage.Headers.Add("X-HIP-ID", hipId); + if(linkToken !=null) + httpRequestMessage.Headers.Add("X-LINK-TOKEN", linkToken); + httpRequestMessage.Headers.Add("REQUEST-ID", requestId ?? Guid.NewGuid().ToString()); httpRequestMessage.Headers.Add("TIMESTAMP", DateTime.UtcNow.ToString(TIMESTAMP_FORMAT)); return httpRequestMessage; } diff --git a/src/In.ProjectEKA.HipService/Gateway/GatewayClient.cs b/src/In.ProjectEKA.HipService/Gateway/GatewayClient.cs index 5880de4ae..d598dc0ed 100644 --- a/src/In.ProjectEKA.HipService/Gateway/GatewayClient.cs +++ b/src/In.ProjectEKA.HipService/Gateway/GatewayClient.cs @@ -16,7 +16,7 @@ namespace In.ProjectEKA.HipService.Gateway public interface IGatewayClient { - Task SendDataToGateway(string urlPath, T response, string cmSuffix,string correlationId); + Task SendDataToGateway(string urlPath, T response, string cmSuffix,string correlationId, string hipId = null, string requestId = null, string linkToken = null); Task CallABHAService(HttpMethod method, string baseUrl, string urlPath, T representation, string correlationId, string xtoken = null, string tToken = null, string transactionId = null); } @@ -83,9 +83,9 @@ public virtual async Task> Authenticate(String correlationId) } } - public virtual async Task SendDataToGateway(string urlPath, T response, string cmSuffix, string correlationId) + public virtual async Task SendDataToGateway(string urlPath, T response, string cmSuffix, string correlationId, string hipId = null,string requestId=null, string linkToken = null) { - await PostTo(configuration.Url + urlPath, response, cmSuffix, correlationId).ConfigureAwait(false); + await PostTo(configuration.Url + urlPath, response, cmSuffix, correlationId, hipId,requestId,linkToken).ConfigureAwait(false); } public virtual async Task CallABHAService(HttpMethod method, string baseUrl,string urlPath, @@ -114,7 +114,7 @@ public virtual async Task CallABHAService(HttpMethod met return response; } - private async Task PostTo(string gatewayUrl, T representation, string cmSuffix, string correlationId) + private async Task PostTo(string gatewayUrl, T representation, string cmSuffix, string correlationId, string hipId, string requestId, string linkToken = null) { try { @@ -127,7 +127,7 @@ private async Task PostTo(string gatewayUrl, T representation, string cmSuffi Log.Debug("Request Payload {@payload}", representation); var responseMessage = await httpClient .SendAsync(CreateHttpRequest(HttpMethod.Post, gatewayUrl, representation, accessToken, - cmSuffix, correlationId)) + cmSuffix, correlationId, hipId: hipId,requestId:requestId,linkToken:linkToken)) .ConfigureAwait(false); Log.Information("Response Status from Gateway for URI {@uri} is {@status}", gatewayUrl, responseMessage.StatusCode); diff --git a/src/In.ProjectEKA.HipService/Link/CareContextController.cs b/src/In.ProjectEKA.HipService/Link/CareContextController.cs index 621cf48e7..a2b3ca0f1 100644 --- a/src/In.ProjectEKA.HipService/Link/CareContextController.cs +++ b/src/In.ProjectEKA.HipService/Link/CareContextController.cs @@ -1,14 +1,12 @@ using System; using System.Threading.Tasks; -using In.ProjectEKA.HipLibrary.Patient.Model; using In.ProjectEKA.HipService.Common; -using In.ProjectEKA.HipService.Gateway; using In.ProjectEKA.HipService.Link.Model; using In.ProjectEKA.HipService.Logger; using In.ProjectEKA.HipService.UserAuth.Model; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; namespace In.ProjectEKA.HipService.Link { @@ -17,106 +15,29 @@ namespace In.ProjectEKA.HipService.Link [ApiController] public class CareContextController : Controller { - private readonly GatewayConfiguration gatewayConfiguration; - private readonly IGatewayClient gatewayClient; - private readonly ILogger logger; private readonly ICareContextService careContextService; private readonly ILinkPatientRepository linkPatientRepository; - - public CareContextController(IGatewayClient gatewayClient, - ILogger logger, - GatewayConfiguration gatewayConfiguration, + public CareContextController( ICareContextService careContextService, ILinkPatientRepository linkPatientRepository ) { - this.gatewayClient = gatewayClient; - this.logger = logger; - this.gatewayConfiguration = gatewayConfiguration; this.careContextService = careContextService; this.linkPatientRepository = linkPatientRepository; + } - - [Route(PATH_ADD_CONTEXTS)] - public async Task AddContexts( - [FromHeader(Name = CORRELATION_ID)] string correlationId, [FromBody] AddContextsRequest addContextsRequest) - { - await careContextService.SetAccessToken(addContextsRequest.ConsentManagerUserId); - var cmSuffix = gatewayConfiguration.CmSuffix; - var (gatewayAddContextsRequestRepresentation, error) = - await careContextService.AddContextsResponse(addContextsRequest,cmSuffix); - if (error != null) - return StatusCode(StatusCodes.Status400BadRequest, error); - Guid requestId = gatewayAddContextsRequestRepresentation.RequestId; - try - { - logger.Log(LogLevel.Information, - LogEvents.AddContext, - "Request for add-context to gateway: {@GatewayResponse}", - gatewayAddContextsRequestRepresentation.dump(gatewayAddContextsRequestRepresentation)); - logger.Log(LogLevel.Information, LogEvents.AddContext, $"cmSuffix: {{cmSuffix}}," + - $" correlationId: {{correlationId}}, " + - $"requestId: {{requestId}}", - cmSuffix, correlationId, requestId); - await gatewayClient.SendDataToGateway(PATH_ADD_PATIENT_CONTEXTS, - gatewayAddContextsRequestRepresentation, - cmSuffix, correlationId); - return Accepted(); - } - catch (Exception exception) - { - logger.LogError(LogEvents.AddContext, exception, "Error happened for requestId: {RequestId} for" + - " add-care context request", requestId); - } - - return StatusCode(StatusCodes.Status504GatewayTimeout, - new ErrorRepresentation(new Error(ErrorCode.GatewayTimedOut, "Gateway timed out"))); - } - - [Route(PATH_NOTIFY_CONTEXTS)] - public async Task NotificationContext( - [FromHeader(Name = CORRELATION_ID)] string correlationId, - [FromBody] NotifyContextRequest notifyContextRequest) - { - var (gatewayNotificationContextRepresentation, error) = - careContextService.NotificationContextResponse(notifyContextRequest); - if (error != null) - return StatusCode(StatusCodes.Status400BadRequest, error); - Guid requestId = gatewayNotificationContextRepresentation.requestId; - var cmSuffix = gatewayConfiguration.CmSuffix; - try - { - logger.Log(LogLevel.Information, - LogEvents.AddContext, - "Request for notification-contexts to gateway: {@GatewayResponse}", - gatewayNotificationContextRepresentation.dump(gatewayNotificationContextRepresentation)); - await gatewayClient.SendDataToGateway(PATH_NOTIFY_PATIENT_CONTEXTS, - gatewayNotificationContextRepresentation, - cmSuffix, correlationId); - return Accepted(); - } - catch (Exception exception) - { - logger.LogError(LogEvents.AddContext, exception, "Error happened for requestId: {RequestId} for" + - " notification-care context request", requestId); - } - - return StatusCode(StatusCodes.Status504GatewayTimeout, - new ErrorRepresentation(new Error(ErrorCode.GatewayTimedOut, "Gateway timed out"))); - } - + + [Authorize] [HttpPost(PATH_ON_NOTIFY_CONTEXTS)] - public AcceptedResult HipLinkOnNotifyContexts(HipLinkContextConfirmation confirmation) + public AcceptedResult HipLinkOnNotifyContexts(HipLinkOnNotifyConfirmation confirmation) { - Log.Information("Link on-notify context received." + - $" RequestId:{confirmation.RequestId}, " + - $" Timestamp:{confirmation.Timestamp}"); + Log.Information("Link on-notify context received."); if (confirmation.Error != null) Log.Information($" Error Code:{confirmation.Error.Code}," + $" Error Message:{confirmation.Error.Message}"); else if (confirmation.Acknowledgement != null) Log.Information($" Acknowledgment Status:{confirmation.Acknowledgement.Status}"); - Log.Information($" Resp RequestId:{confirmation.Resp.RequestId}"); + Log.Information($" Resp RequestId:{confirmation.Response.RequestId}"); return Accepted(); } diff --git a/src/In.ProjectEKA.HipService/Link/CareContextService.cs b/src/In.ProjectEKA.HipService/Link/CareContextService.cs index 808378ff5..a37ef9f38 100644 --- a/src/In.ProjectEKA.HipService/Link/CareContextService.cs +++ b/src/In.ProjectEKA.HipService/Link/CareContextService.cs @@ -4,11 +4,14 @@ using System.Linq; using System.Net.Http; using System.Text; +using System.Threading; using System.Threading.Tasks; using In.ProjectEKA.HipLibrary.Patient.Model; using In.ProjectEKA.HipService.Common; using In.ProjectEKA.HipService.Common.Model; +using In.ProjectEKA.HipService.Gateway; using In.ProjectEKA.HipService.Link.Model; +using In.ProjectEKA.HipService.Logger; using In.ProjectEKA.HipService.OpenMrs; using In.ProjectEKA.HipService.UserAuth; using In.ProjectEKA.HipService.UserAuth.Model; @@ -25,13 +28,16 @@ public class CareContextService : ICareContextService { private readonly HttpClient httpClient; private readonly IUserAuthRepository userAuthRepository; + private readonly IUserAuthService userAuthService; private readonly BahmniConfiguration bahmniConfiguration; private readonly ILinkPatientRepository linkPatientRepository; private readonly LinkPatient linkPatient; private readonly IOptions hipConfiguration; - + private readonly IGatewayClient gatewayClient; + private readonly GatewayConfiguration gatewayConfiguration; public CareContextService(HttpClient httpClient, IUserAuthRepository userAuthRepository, - BahmniConfiguration bahmniConfiguration, ILinkPatientRepository linkPatientRepository, LinkPatient linkPatient, IOptions hipConfiguration) + BahmniConfiguration bahmniConfiguration, ILinkPatientRepository linkPatientRepository, LinkPatient linkPatient, IOptions hipConfiguration, IGatewayClient gatewayClient, GatewayConfiguration gatewayConfiguration, + IUserAuthService userAuthService) { this.httpClient = httpClient; this.userAuthRepository = userAuthRepository; @@ -39,19 +45,17 @@ public CareContextService(HttpClient httpClient, IUserAuthRepository userAuthRep this.linkPatientRepository = linkPatientRepository; this.linkPatient = linkPatient; this.hipConfiguration = hipConfiguration; + this.gatewayClient = gatewayClient; + this.gatewayConfiguration = gatewayConfiguration; + this.userAuthService = userAuthService; } public async Task> AddContextsResponse( - AddContextsRequest addContextsRequest, string cmSuffix) + NewContextRequest addContextsRequest, string cmSuffix, Guid requestId) { - var accessToken = UserAuthMap.HealthIdToAccessToken[addContextsRequest.ConsentManagerUserId]; - var referenceNumber = addContextsRequest.ReferenceNumber; var careContexts = addContextsRequest.CareContexts; - var display = addContextsRequest.Display; - var patient = new AddCareContextsPatient(referenceNumber, display, careContexts); - var link = new AddCareContextsLink(accessToken, patient); - var timeStamp = DateTime.Now.ToUniversalTime().ToString(DateTimeFormat); - var requestId = Guid.NewGuid(); + var abhaAddress = addContextsRequest.HealthId; + if (!await linkPatient.SaveInitiatedLinkRequest(requestId.ToString(), null, requestId.ToString()) .ConfigureAwait(false)) return new Tuple @@ -59,11 +63,22 @@ public async Task context.ReferenceNumber) .ToArray(); + var linkConfirmationRepresentations = careContexts + .Where(cc => cc.HiTypes != null && cc.HiTypes.Any()) + .SelectMany(cc => cc.HiTypes.Select(hiType => new { HiType = hiType, CareContext = cc })) + .GroupBy(x => x.HiType) + .Select(group => new LinkConfirmationRepresentation(addContextsRequest.PatientReferenceNumber, + addContextsRequest.PatientName, + group.Select(x => new CareContextRepresentation(x.CareContext.ReferenceNumber, x.CareContext.Display)) + .ToList(), + group.Key.ToString(), + group.Count())) + .ToList(); var (_, exception1) = await linkPatientRepository.SaveRequestWith( requestId.ToString(), cmSuffix, - addContextsRequest.ConsentManagerUserId, - addContextsRequest.ReferenceNumber, + abhaAddress, + addContextsRequest.PatientReferenceNumber, careContextReferenceNumbers) .ConfigureAwait(false); if (exception1 != null) @@ -71,73 +86,132 @@ public async Task - (new GatewayAddContextsRequestRepresentation(requestId, timeStamp, link), null); + (new GatewayAddContextsRequestRepresentation( abhaAddress,linkConfirmationRepresentations), null); } public async Task SetAccessToken(string healthId) { - var demographics = (userAuthRepository.GetDemographics(healthId).Result).ValueOrDefault(); - var request = new HttpRequestMessage(HttpMethod.Post, hipConfiguration.Value.Url + PATH_DEMOGRAPHICS); - request.Content = new StringContent(JsonConvert.SerializeObject(demographics), Encoding.UTF8, - "application/json"); - await httpClient.SendAsync(request).ConfigureAwait(false); - if (!UserAuthMap.HealthIdToAccessToken.TryGetValue(healthId, out _)) + if (UserAuthMap.HealthIdToAccessToken.ContainsKey(healthId)) { - var (accessToken, error) = await userAuthRepository.GetAccessToken(healthId); - UserAuthMap.HealthIdToAccessToken.Add(healthId, accessToken); + var linkToken = UserAuthMap.HealthIdToAccessToken[healthId]; + var error = userAuthService.CheckAccessToken(linkToken); + if (error == null) + return; } + var (linkTokenFromDb,exception) = await userAuthRepository.GetAccessToken(healthId); + if (linkTokenFromDb != null) + { + var error = userAuthService.CheckAccessToken(linkTokenFromDb); + if (error == null) + { + UserAuthMap.HealthIdToAccessToken.Add(healthId, linkTokenFromDb); + return; + } + } + + var demographics = (userAuthRepository.GetDemographics(healthId).Result).ValueOrDefault(); + var requestId = Guid.NewGuid(); + if (demographics == null) + return; + var generateTokenPayload = new GenerateLinkTokenRequest(demographics.HealthId, demographics.Name, + demographics.Gender, demographics.DateOfBirth.Split("-").First()); + + await gatewayClient.SendDataToGateway(PATH_GENERATE_TOKEN, generateTokenPayload, gatewayConfiguration.CmSuffix, + Guid.NewGuid().ToString(), bahmniConfiguration.Id, requestId.ToString() ); + var i = 0; + do + { + await Task.Delay(gatewayConfiguration.TimeOut + 8000); + if (UserAuthMap.RequestIdToErrorMessage.ContainsKey(requestId)) + { + var gatewayError = UserAuthMap.RequestIdToErrorMessage[requestId]; + UserAuthMap.RequestIdToErrorMessage.Remove(requestId); + break; + } + + if (UserAuthMap.RequestIdToAccessToken.ContainsKey(requestId)) + { + Log.Information( + "Response about to be send for requestId: {RequestId} with accessToken: {AccessToken}", + requestId, UserAuthMap.RequestIdToAccessToken[requestId] + ); + break; + } + i++; + } while (i < gatewayConfiguration.Counter); } public Tuple NotificationContextResponse( - NotifyContextRequest notifyContextRequest) + NewContextRequest notifyContextRequest, CareContextRepresentation context) { - var id = notifyContextRequest.PatientId; - var patientReference = notifyContextRequest.PatientReference; - var careContextReference = notifyContextRequest.CareContextReference; - var hiTypes = notifyContextRequest.HiTypes; - var hipId = notifyContextRequest.HipId; + var id = notifyContextRequest.HealthId; + var patientReference = notifyContextRequest.PatientReferenceNumber; + var careContextReference = context.ReferenceNumber; + var hiTypes = context.HiTypes.Select(hiType => hiType.ToString()).ToList(); + var hipId = bahmniConfiguration.Id; var patient = new NotificationPatientContext(id); var careContext = new NotificationCareContext(patientReference, careContextReference); var hip = new NotificationContextHip(hipId); var date = DateTime.Now.ToUniversalTime().ToString(DateTimeFormat); - var timeStamp = DateTime.Now.ToUniversalTime().ToString(DateTimeFormat); - var requestId = Guid.NewGuid(); var notification = new NotificationContext(patient, careContext, hiTypes, date, hip); return new Tuple - (new GatewayNotificationContextRepresentation(requestId, timeStamp, notification), null); + (new GatewayNotificationContextRepresentation(notification), null); } public async Task CallNotifyContext(NewContextRequest newContextRequest, CareContextRepresentation context) { - var request = - new HttpRequestMessage(HttpMethod.Get, hipConfiguration.Value.Url + PATH_NOTIFY_CONTEXTS); - var notifyContext = new NotifyContextRequest(newContextRequest.HealthId, - newContextRequest.PatientReferenceNumber, - context.ReferenceNumber, - Enum.GetValues(typeof(HiType)) - .Cast() - .Select(v => v.ToString()) - .ToList(), - bahmniConfiguration.Id - ); - request.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(notifyContext), - Encoding.UTF8, "application/json"); - - await httpClient.SendAsync(request).ConfigureAwait(false); + var (gatewayNotificationContextRepresentation, error) = + NotificationContextResponse(newContextRequest, context); + if (error != null) + Log.Error("Notify for Care Context failed with error: {@Error}", error); + + var cmSuffix = gatewayConfiguration.CmSuffix; + try + { + Log.Information( + "Request for notification-contexts to gateway: {@GatewayResponse}", + gatewayNotificationContextRepresentation.dump(gatewayNotificationContextRepresentation)); + await gatewayClient.SendDataToGateway(PATH_NOTIFY_PATIENT_CONTEXTS, + gatewayNotificationContextRepresentation, + cmSuffix, Guid.NewGuid().ToString(), hipId:bahmniConfiguration.Id); + + } + catch (Exception exception) + { + Log.Error("Error happened for notification-care context request", exception); + } } public async Task CallAddContext(NewContextRequest newContextRequest) { - var request = new HttpRequestMessage(HttpMethod.Post, hipConfiguration.Value.Url + PATH_ADD_CONTEXTS); - var addContextRequest = new AddContextsRequest( - newContextRequest.PatientReferenceNumber, - newContextRequest.CareContexts, - newContextRequest.PatientName, - newContextRequest.HealthId); - - request.Content = new StringContent(JsonConvert.SerializeObject(addContextRequest), - Encoding.UTF8, "application/json"); - await httpClient.SendAsync(request).ConfigureAwait(false); + var abhaAddress = newContextRequest.HealthId; + await SetAccessToken(abhaAddress); + if (!UserAuthMap.HealthIdToAccessToken.ContainsKey(abhaAddress)) + { + Log.Error("Unable to get link token for healthId: {healthId}", + abhaAddress); + throw new Exception("Unable to get link token"); + } + var linkToken = UserAuthMap.HealthIdToAccessToken[abhaAddress]; + var cmSuffix = gatewayConfiguration.CmSuffix; + var requestId = Guid.NewGuid(); + var (gatewayAddContextsRequestRepresentation, error) = + await AddContextsResponse(newContextRequest,cmSuffix,requestId); + if (error != null) + Log.Error("Linking Care Context failed with error: {@Error}", error); + try + { + Log.Information( + "Request for add-context to gateway: {@GatewayResponse}", + gatewayAddContextsRequestRepresentation.dump(gatewayAddContextsRequestRepresentation)); + await gatewayClient.SendDataToGateway(PATH_ADD_PATIENT_CONTEXTS, + gatewayAddContextsRequestRepresentation, + cmSuffix, null, linkToken:linkToken, requestId: requestId.ToString(), hipId:bahmniConfiguration.Id); + } + catch (Exception exception) + { + Log.Error("Error happened for add-care context request", exception); + } } public bool IsLinkedContext(List careContexts, string context) diff --git a/src/In.ProjectEKA.HipService/Link/HipLinkContextConfirmation.cs b/src/In.ProjectEKA.HipService/Link/HipLinkContextConfirmation.cs index 6e9272f33..4f617f6c3 100644 --- a/src/In.ProjectEKA.HipService/Link/HipLinkContextConfirmation.cs +++ b/src/In.ProjectEKA.HipService/Link/HipLinkContextConfirmation.cs @@ -6,20 +6,18 @@ namespace In.ProjectEKA.HipService.Link public class HipLinkContextConfirmation { - public HipLinkContextConfirmation(string requestId, DateTime timestamp, - AddContextsAcknowledgement acknowledgement, Error error, Resp resp) + public HipLinkContextConfirmation(string abhaAddress, string status, Error error, Resp response) { - RequestId = requestId; - Timestamp = timestamp; - Acknowledgement = acknowledgement; + AbhaAddress = abhaAddress; + Status = status; Error = error; - Resp = resp; + Response = response; } - public string RequestId { get; } - public DateTime Timestamp { get; } + public string AbhaAddress { get; } + public string Status { get; } public Error Error { get; } - public Resp Resp { get; } - public AddContextsAcknowledgement Acknowledgement { get; } + public Resp Response { get; } + } } \ No newline at end of file diff --git a/src/In.ProjectEKA.HipService/Link/ICareContextService.cs b/src/In.ProjectEKA.HipService/Link/ICareContextService.cs index ad8d35d39..a5f02cb5c 100644 --- a/src/In.ProjectEKA.HipService/Link/ICareContextService.cs +++ b/src/In.ProjectEKA.HipService/Link/ICareContextService.cs @@ -10,10 +10,10 @@ namespace In.ProjectEKA.HipService.Link public interface ICareContextService { public Task> AddContextsResponse( - AddContextsRequest addContextsRequest, string cmSuffix); + NewContextRequest addContextsRequest, string cmSuffix, Guid requestId); public Tuple NotificationContextResponse( - NotifyContextRequest notifyContextRequest); + NewContextRequest notifyContextRequest, CareContextRepresentation context); public Task CallNotifyContext(NewContextRequest newContextRequest, CareContextRepresentation context); diff --git a/src/In.ProjectEKA.HipService/Link/LinkController.cs b/src/In.ProjectEKA.HipService/Link/LinkController.cs index a35b1dee0..527066cc6 100644 --- a/src/In.ProjectEKA.HipService/Link/LinkController.cs +++ b/src/In.ProjectEKA.HipService/Link/LinkController.cs @@ -162,26 +162,21 @@ public async Task LinkPatientCareContextFor(LinkPatientRequest request, String c [HttpPost(PATH_ON_ADD_CONTEXTS)] public async Task HipLinkOnAddContexts(HipLinkContextConfirmation confirmation) { - Log.Information("Link on-add-context received." + - $" RequestId:{confirmation.RequestId}, " + - $" Timestamp:{confirmation.Timestamp}"); + Log.Information("Link on-add-context received."); if (confirmation.Error != null) Log.Information($" Error Code:{confirmation.Error.Code}," + $" Error Message:{confirmation.Error.Message}"); - else if (confirmation.Acknowledgement != null) + else if (confirmation.Status != null) { - if (confirmation.Acknowledgement.Status.Equals(Status.SUCCESS.ToString())) - { var error = - await linkPatient.VerifyAndLinkCareContexts(confirmation.Resp.RequestId); + await linkPatient.VerifyAndLinkCareContexts(confirmation.Response.RequestId); if (error != null) { Log.Error(error); } - } - Log.Information($" Acknowledgment Status:{confirmation.Acknowledgement.Status}"); + Log.Information($" Acknowledgment Status:{confirmation.Status}"); } - Log.Information($" Resp RequestId:{confirmation.Resp.RequestId}"); + Log.Information($" Resp RequestId:{confirmation.Response.RequestId}"); return Accepted(); } } diff --git a/src/In.ProjectEKA.HipService/Link/Model/GatewayAddContextsRequestRepresentation.cs b/src/In.ProjectEKA.HipService/Link/Model/GatewayAddContextsRequestRepresentation.cs index d8557ace8..72211cfae 100644 --- a/src/In.ProjectEKA.HipService/Link/Model/GatewayAddContextsRequestRepresentation.cs +++ b/src/In.ProjectEKA.HipService/Link/Model/GatewayAddContextsRequestRepresentation.cs @@ -1,19 +1,19 @@ using System; +using System.Collections.Generic; +using In.ProjectEKA.HipLibrary.Patient.Model; using Newtonsoft.Json; namespace In.ProjectEKA.HipService.Link.Model { public class GatewayAddContextsRequestRepresentation { - public Guid RequestId { get; } - public string Timestamp { get; } - public AddCareContextsLink Link { get; } - - public GatewayAddContextsRequestRepresentation(Guid requestId, string timestamp, AddCareContextsLink link) + public string AbhaAddress { get; } + public IEnumerable Patient { get; } + + public GatewayAddContextsRequestRepresentation(string abhaAddress, IEnumerable patient) { - RequestId = requestId; - Timestamp = timestamp; - Link = link; + AbhaAddress = abhaAddress; + Patient = patient; } public string dump(Object o) diff --git a/src/In.ProjectEKA.HipService/Link/Model/GatewayNotificationContextRepresentation.cs b/src/In.ProjectEKA.HipService/Link/Model/GatewayNotificationContextRepresentation.cs index a24ae6128..1bd2a865e 100644 --- a/src/In.ProjectEKA.HipService/Link/Model/GatewayNotificationContextRepresentation.cs +++ b/src/In.ProjectEKA.HipService/Link/Model/GatewayNotificationContextRepresentation.cs @@ -5,15 +5,11 @@ namespace In.ProjectEKA.HipService.Link.Model { public class GatewayNotificationContextRepresentation { - public Guid requestId { get; } - public string timestamp { get; } public NotificationContext notification { get; } - public GatewayNotificationContextRepresentation(Guid requestId, string timestamp, + public GatewayNotificationContextRepresentation( NotificationContext notification) { - this.requestId = requestId; - this.timestamp = timestamp; this.notification = notification; } diff --git a/src/In.ProjectEKA.HipService/Link/Model/GenerateLinkTokenRequest.cs b/src/In.ProjectEKA.HipService/Link/Model/GenerateLinkTokenRequest.cs new file mode 100644 index 000000000..886c90d80 --- /dev/null +++ b/src/In.ProjectEKA.HipService/Link/Model/GenerateLinkTokenRequest.cs @@ -0,0 +1,17 @@ +namespace In.ProjectEKA.HipService.Link.Model; + +public class GenerateLinkTokenRequest +{ + public string AbhaAddress { get; } + public string Name { get; } + public string Gender { get; } + public string YearOfBirth { get; } + + public GenerateLinkTokenRequest(string abhaAddress, string name, string gender, string yearOfBirth) + { + AbhaAddress = abhaAddress; + Name = name; + Gender = gender; + YearOfBirth = yearOfBirth; + } +} \ No newline at end of file diff --git a/src/In.ProjectEKA.HipService/Link/Model/HipLinkOnNotifyConfirmation.cs b/src/In.ProjectEKA.HipService/Link/Model/HipLinkOnNotifyConfirmation.cs new file mode 100644 index 000000000..db1f11180 --- /dev/null +++ b/src/In.ProjectEKA.HipService/Link/Model/HipLinkOnNotifyConfirmation.cs @@ -0,0 +1,23 @@ +using System; +using In.ProjectEKA.HipLibrary.Patient.Model; + +namespace In.ProjectEKA.HipService.Link.Model; + +public class HipLinkOnNotifyConfirmation +{ + public HipLinkOnNotifyConfirmation(string requestId, DateTime timestamp, + AddContextsAcknowledgement acknowledgement, Error error, Resp response) + { + RequestId = requestId; + Timestamp = timestamp; + Acknowledgement = acknowledgement; + Error = error; + Response = response; + } + + public string RequestId { get; } + public DateTime Timestamp { get; } + public Error Error { get; } + public Resp Response { get; } + public AddContextsAcknowledgement Acknowledgement { get; } +} diff --git a/src/In.ProjectEKA.HipService/SmsNotification/Model/GatewaySmsNotifyRequestRepresentation.cs b/src/In.ProjectEKA.HipService/SmsNotification/Model/GatewaySmsNotifyRequestRepresentation.cs index e8f22a813..e34192ce7 100644 --- a/src/In.ProjectEKA.HipService/SmsNotification/Model/GatewaySmsNotifyRequestRepresentation.cs +++ b/src/In.ProjectEKA.HipService/SmsNotification/Model/GatewaySmsNotifyRequestRepresentation.cs @@ -5,14 +5,10 @@ namespace In.ProjectEKA.HipService.SmsNotification.Model { public class GatewaySmsNotifyRequestRepresentation { - public Guid requestId { get; } - public string timestamp { get; } public SmsNotification notification { get; } - public GatewaySmsNotifyRequestRepresentation(Guid requestId, string timestamp, SmsNotification notification) + public GatewaySmsNotifyRequestRepresentation(SmsNotification notification) { - this.requestId = requestId; - this.timestamp = timestamp; this.notification = notification; } diff --git a/src/In.ProjectEKA.HipService/SmsNotification/Model/OnSmsNotifyRequest.cs b/src/In.ProjectEKA.HipService/SmsNotification/Model/OnSmsNotifyRequest.cs index 023d7d22a..01358a126 100644 --- a/src/In.ProjectEKA.HipService/SmsNotification/Model/OnSmsNotifyRequest.cs +++ b/src/In.ProjectEKA.HipService/SmsNotification/Model/OnSmsNotifyRequest.cs @@ -5,19 +5,15 @@ namespace In.ProjectEKA.HipService.SmsNotification.Model { public class OnSmsNotifyRequest { - public Guid requestId { get; } - public DateTime timestamp { get; } public string status { get; } public Error error { get; } - public Resp resp { get; } + public Resp response { get; } - public OnSmsNotifyRequest(Guid requestId, DateTime timestamp, string status, Error error, Resp resp) + public OnSmsNotifyRequest(string status, Error error, Resp response) { - this.requestId = requestId; - this.timestamp = timestamp; this.status = status; this.error = error; - this.resp = resp; + this.response = response; } } } \ No newline at end of file diff --git a/src/In.ProjectEKA.HipService/SmsNotification/SmsNotificationController.cs b/src/In.ProjectEKA.HipService/SmsNotification/SmsNotificationController.cs index 217cf208c..01f565c72 100644 --- a/src/In.ProjectEKA.HipService/SmsNotification/SmsNotificationController.cs +++ b/src/In.ProjectEKA.HipService/SmsNotification/SmsNotificationController.cs @@ -1,4 +1,5 @@ using System; +using System.ComponentModel.DataAnnotations; using System.Net.Http; using System.Threading.Tasks; using In.ProjectEKA.HipLibrary.Patient.Model; @@ -53,7 +54,6 @@ public async Task SendSMSNotification([FromHeader(Name = CORRELATI _smsNotificationService.SmsNotifyRequest(smsNotifyRequest, bahmniConfiguration); if (error != null) return StatusCode(StatusCodes.Status400BadRequest, error); - Guid requestId = gatewaySmsNotifyRequestRepresentation.requestId; var cmSuffix = gatewayConfiguration.CmSuffix; try @@ -69,8 +69,7 @@ await gatewayClient.SendDataToGateway(PATH_SMS_NOTIFY, gatewaySmsNotifyRequestRe } catch (Exception exception) { - logger.LogError(LogEvents.UserAuth, exception, "Error happened for requestId: {RequestId} for" + - " sms Notify request", requestId); + logger.LogError(LogEvents.UserAuth, exception, "Error happened for sms Notify request"); } return StatusCode(StatusCodes.Status504GatewayTimeout, new ErrorRepresentation(new Error(ErrorCode.GatewayTimedOut, "Gateway timed out"))); @@ -80,13 +79,15 @@ await gatewayClient.SendDataToGateway(PATH_SMS_NOTIFY, gatewaySmsNotifyRequestRe [Authorize] [HttpPost (PATH_SMS_ON_NOTIFY)] - public AcceptedResult SmsNotifyStatus(OnSmsNotifyRequest request) + public AcceptedResult SmsNotifyStatus(OnSmsNotifyRequest request, + [FromHeader(Name = REQUEST_ID), Required] string requestId, + [FromHeader(Name = TIMESTAMP)] string timestamp) { logger.Log(LogLevel.Information, LogEvents.SmsNotify, "On Sms Notify request received." + - $" RequestId:{request.requestId}, " + - $" Timestamp:{request.timestamp}," + - $" ResponseRequestId:{request.resp.RequestId}, "); + $" RequestId:{requestId}, " + + $" Timestamp:{timestamp}," + + $" ResponseRequestId:{request.response.RequestId}, "); if (request.error != null) { logger.Log(LogLevel.Information, diff --git a/src/In.ProjectEKA.HipService/SmsNotification/SmsNotificationService.cs b/src/In.ProjectEKA.HipService/SmsNotification/SmsNotificationService.cs index 79dd24b56..e6523a71a 100644 --- a/src/In.ProjectEKA.HipService/SmsNotification/SmsNotificationService.cs +++ b/src/In.ProjectEKA.HipService/SmsNotification/SmsNotificationService.cs @@ -12,13 +12,11 @@ public class SmsNotificationService : ISmsNotificationService public Tuple SmsNotifyRequest( SmsNotifyRequest smsNotifyRequest, BahmniConfiguration bahmniConfiguration) { - var timeStamp = DateTime.Now.ToUniversalTime().ToString(DateTimeFormat); - var requestId = Guid.NewGuid(); var hip = new SmsNotifyHip(bahmniConfiguration.Id, bahmniConfiguration.Id); var notification = new Model.SmsNotification(smsNotifyRequest.phoneNo,hip); return new Tuple( - new GatewaySmsNotifyRequestRepresentation(requestId, timeStamp, notification), null); + new GatewaySmsNotifyRequestRepresentation(notification), null); } } diff --git a/src/In.ProjectEKA.HipService/UserAuth/IUserAuthService.cs b/src/In.ProjectEKA.HipService/UserAuth/IUserAuthService.cs index 9ac72f9cf..a1bfe9560 100644 --- a/src/In.ProjectEKA.HipService/UserAuth/IUserAuthService.cs +++ b/src/In.ProjectEKA.HipService/UserAuth/IUserAuthService.cs @@ -28,7 +28,12 @@ public Task> OnAuthConfirmResponse( public Task AuthNotify(AuthNotifyRequest request); public Task Dump(NdhmDemographics ndhmDemographics); + + public Task> HandleOnGenerateLinkToken( + OnGenerateTokenRequest onGenerateTokenRequest); + + public Error CheckAccessToken(string accessToken); + - } } \ No newline at end of file diff --git a/src/In.ProjectEKA.HipService/UserAuth/Model/OnGenerateTokenRequest.cs b/src/In.ProjectEKA.HipService/UserAuth/Model/OnGenerateTokenRequest.cs new file mode 100644 index 000000000..0deb318c8 --- /dev/null +++ b/src/In.ProjectEKA.HipService/UserAuth/Model/OnGenerateTokenRequest.cs @@ -0,0 +1,23 @@ +using In.ProjectEKA.HipLibrary.Patient.Model; + +namespace In.ProjectEKA.HipService.UserAuth.Model; + +public class OnGenerateTokenRequest +{ + public string AbhaAddress { get; } + + public string LinkToken { get; } + + public Resp Response { get; } + + public Error Error { get; } + + public OnGenerateTokenRequest(string abhaAddress, string linkToken, Resp response, Error error) + { + AbhaAddress = abhaAddress; + LinkToken = linkToken; + Response = response; + Error = error; + } + +} \ No newline at end of file diff --git a/src/In.ProjectEKA.HipService/UserAuth/UserAuthController.cs b/src/In.ProjectEKA.HipService/UserAuth/UserAuthController.cs index e9bf395ef..46bbd4d32 100644 --- a/src/In.ProjectEKA.HipService/UserAuth/UserAuthController.cs +++ b/src/In.ProjectEKA.HipService/UserAuth/UserAuthController.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; using System.Net.Http; using System.Threading; using System.Threading.Tasks; @@ -230,25 +231,6 @@ public async Task SetDemographicDetails( var ndhmDemographics = new NdhmDemographics(healthId, name, gender, dateOfBirth, phoneNumber); await userAuthService.Dump(ndhmDemographics); } - - [Route(PATH_DEMOGRAPHICS)] - public async Task DemographicAuth([FromBody] NdhmDemographics ndhmDemographics) - { - var authInitRequest = new AuthInitRequest(ndhmDemographics.HealthId, "DEMOGRAPHICS", "LINK"); - - var initError = await userAuthService.AuthInit(authInitRequest, null, bahmniConfiguration,gatewayConfiguration); - if (initError != null) - return StatusCode(StatusCodes.Status500InternalServerError, initError); - - var identifier = new Identifier(MOBILE, ndhmDemographics.PhoneNumber); - var demographics = new Demographics(ndhmDemographics.Name, ndhmDemographics.Gender, - ndhmDemographics.DateOfBirth, identifier); - var authConfirmRequest = new AuthConfirmRequest(null, ndhmDemographics.HealthId, demographics); - - var (authConfirm, confirmError) = await userAuthService.AuthConfirm(authConfirmRequest, null ,gatewayConfiguration); - return confirmError != null ? StatusCode(ErrorCodeToStatusCode.GetValueOrDefault(confirmError.Error.Code,StatusCodes.Status400BadRequest),confirmError) : Accepted(authConfirm); - } - [Authorize] [HttpPost(PATH_AUTH_NOTIFY)] public async Task AuthNotify([FromHeader(Name = CORRELATION_ID)] string correlationId, @@ -285,5 +267,34 @@ public async Task GetPatientDetails([FromParameter("healthId")] st $" Error Message:{error.Error.Message}"); return StatusCode(ErrorCodeToStatusCode.GetValueOrDefault(error.Error.Code,StatusCodes.Status400BadRequest), error); } + + [Authorize] + [HttpPost(PATH_ON_GENERATE_TOKEN)] + public async Task OnGenerateLinkToken(OnGenerateTokenRequest request, + [FromHeader(Name = REQUEST_ID), Required] string requestId, + [FromHeader(Name = TIMESTAMP)] string timestamp) + { + logger.Log(LogLevel.Information, + LogEvents.UserAuth, "On generate token request received." + + $" RequestId:{requestId}, " + + $" Timestamp:{timestamp}," + + $" ResponseRequestId:{request.Response.RequestId}, "); + if (request.Error != null) + { + RequestIdToErrorMessage.Add(Guid.Parse(request.Response.RequestId), request.Error); + logger.Log(LogLevel.Information, + LogEvents.UserAuth, $" Error Code:{request.Error.Code}," + + $" Error Message:{request.Error.Message}."); + } + else if (request.LinkToken != null) + { + await userAuthService.HandleOnGenerateLinkToken(request); + } + + logger.Log(LogLevel.Information, + LogEvents.UserAuth, $"Response RequestId:{request.Response.RequestId}"); + + return Accepted(); + } } } \ No newline at end of file diff --git a/src/In.ProjectEKA.HipService/UserAuth/UserAuthService.cs b/src/In.ProjectEKA.HipService/UserAuth/UserAuthService.cs index 5249e4d90..7cdd7eba6 100644 --- a/src/In.ProjectEKA.HipService/UserAuth/UserAuthService.cs +++ b/src/In.ProjectEKA.HipService/UserAuth/UserAuthService.cs @@ -358,13 +358,38 @@ public async Task Dump(NdhmDemographics ndhmDemographics) { await userAuthRepository.AddDemographics(ndhmDemographics).ConfigureAwait(false); } - - private Error CheckAccessToken(string accessToken) + + public async Task> HandleOnGenerateLinkToken(OnGenerateTokenRequest onGenerateTokenRequest) + { + var accessToken = onGenerateTokenRequest.LinkToken; + var tokenError = CheckAccessToken(accessToken); + if (tokenError != null) + { + return new Tuple(null, + new ErrorRepresentation(tokenError)); + + } + var healthId = onGenerateTokenRequest.AbhaAddress; + if(healthId == null) + { + healthId = getHealthId(accessToken); + } + Tuple authConfirmResponse = await updateAuthConfirmRepository(healthId, accessToken); + if (authConfirmResponse.Item2 != null) + { + return authConfirmResponse; + } + var requestId = Guid.Parse(onGenerateTokenRequest.Response.RequestId); + updateUserAuthMaps(accessToken, healthId, requestId); + return authConfirmResponse; + } + + public Error CheckAccessToken(string accessToken) { if (accessToken != null) { var token = new JwtSecurityTokenHandler().ReadToken(accessToken) as JwtSecurityToken; - if (token?.Claims.First(c => c.Type == "patientId").Value == null) + if (token?.Claims.First(c => c.Type == "abhaAddress").Value == null) return new Error(ErrorCode.BadRequest, "Invalid Access token"); var expInUnixTimeStamp = token?.Claims.First(c => c.Type == "exp").Value; var exp = DateTimeOffset @@ -379,5 +404,40 @@ private Error CheckAccessToken(string accessToken) } + private void updateUserAuthMaps(string accessToken, string healthId, Guid requestId) + { + UserAuthMap.RequestIdToAccessToken.Add(requestId, accessToken); + if (UserAuthMap.HealthIdToAccessToken.ContainsKey(healthId)) + { + UserAuthMap.HealthIdToAccessToken[healthId] = accessToken; + } + else + { + UserAuthMap.HealthIdToAccessToken.Add(healthId, accessToken); + } + } + + private async Task> updateAuthConfirmRepository(string healthId, string accessToken) + { + var authConfirm = new AuthConfirm(healthId, accessToken); + var savedAuthConfirm = userAuthRepository.Get(healthId).Result; + if (savedAuthConfirm.Equals(Option.Some(null))) + { + var authConfirmResponse = await userAuthRepository.Add(authConfirm).ConfigureAwait(false); + if (!authConfirmResponse.HasValue) + { + return new Tuple(null, + new ErrorRepresentation(new Error(ErrorCode.DuplicateAuthConfirmRequest, + "Auth confirm request already exists"))); + } + } + else + { + userAuthRepository.Update(authConfirm); + } + + return new Tuple(authConfirm, null); + } + } } \ No newline at end of file diff --git a/test/In.ProjectEKA.HipServiceTest/Consent/ConsentNotificationControllerTest.cs b/test/In.ProjectEKA.HipServiceTest/Consent/ConsentNotificationControllerTest.cs index e09bb248e..e48cf8598 100644 --- a/test/In.ProjectEKA.HipServiceTest/Consent/ConsentNotificationControllerTest.cs +++ b/test/In.ProjectEKA.HipServiceTest/Consent/ConsentNotificationControllerTest.cs @@ -60,7 +60,7 @@ public ConsentNotificationControllerTest() It.IsAny(), It.IsAny(), It.IsAny(), - It.IsAny())) + It.IsAny(),null,null,null)) .Returns(Task.Run(() => { })); } @@ -147,7 +147,7 @@ async void ShouldInvokeGatewayWhenRevokingConsent() c.Acknowledgement.ConsentId == consentNotification.Notification.ConsentId && c.Response.RequestId == requestId), consentNotification.Notification.ConsentDetail.ConsentManager.Id, - correlationId), + correlationId,null,null,null), Times.Once); } } diff --git a/test/In.ProjectEKA.HipServiceTest/DataFlow/PatientDataFlowControllerTest.cs b/test/In.ProjectEKA.HipServiceTest/DataFlow/PatientDataFlowControllerTest.cs index 598ebcef8..d2c407e17 100644 --- a/test/In.ProjectEKA.HipServiceTest/DataFlow/PatientDataFlowControllerTest.cs +++ b/test/In.ProjectEKA.HipServiceTest/DataFlow/PatientDataFlowControllerTest.cs @@ -90,7 +90,7 @@ private async void ShouldSendDataFlowRequestToGateway() gatewayClient.Setup( client => client.SendDataToGateway(PATH_HEALTH_INFORMATION_ON_REQUEST, - It.IsAny(), "ncg", correlationId)); + It.IsAny(), "ncg", correlationId,null,null,null)); await patientDataFlowController.HealthInformationOf(request, correlationId, gatewayId, requestId); diff --git a/test/In.ProjectEKA.HipServiceTest/Discovery/PatientControllerTest.cs b/test/In.ProjectEKA.HipServiceTest/Discovery/PatientControllerTest.cs index 9e3cb9d40..5a2033a68 100644 --- a/test/In.ProjectEKA.HipServiceTest/Discovery/PatientControllerTest.cs +++ b/test/In.ProjectEKA.HipServiceTest/Discovery/PatientControllerTest.cs @@ -535,10 +535,10 @@ private static void SetupGatewayClientToSaveAllSentDiscoveryIntoThisList(Mock gatewayClient.SendDataToGateway( It.IsAny(), It.IsAny(), It.IsAny(), - It.IsAny()) + It.IsAny(),null,null,null) ) - .Callback( - (urlPath, response, cmSuffix, correlationId) => + .Callback( + (urlPath, response, cmSuffix, correlationId,hipId,requestId,linkToken) => { responsesSentToGateway.TryAdd(response.TransactionId, response); }); diff --git a/test/In.ProjectEKA.HipServiceTest/Link/CareContextControllerTest.cs b/test/In.ProjectEKA.HipServiceTest/Link/CareContextControllerTest.cs index c5a63394d..239d90abf 100644 --- a/test/In.ProjectEKA.HipServiceTest/Link/CareContextControllerTest.cs +++ b/test/In.ProjectEKA.HipServiceTest/Link/CareContextControllerTest.cs @@ -1,12 +1,10 @@ using System; using System.Collections.Generic; -using System.Net.Http; using Hl7.Fhir.Model; using In.ProjectEKA.HipLibrary.Patient.Model; using In.ProjectEKA.HipService.Gateway; using In.ProjectEKA.HipService.Link; using In.ProjectEKA.HipService.Link.Model; -using In.ProjectEKA.HipService.UserAuth; using In.ProjectEKA.HipService.UserAuth.Model; using Microsoft.Extensions.Logging; using Moq; @@ -27,82 +25,70 @@ public class CareContextControllerTest private readonly Mock gatewayClient = new Mock(MockBehavior.Strict, null, null); private readonly Mock careContextService = new Mock(); private readonly Mock linkPatientRepository = new Mock(); - private readonly Mock httpClient = new Mock(); - private readonly Mock userAuthRepository = new Mock(); - - private readonly GatewayConfiguration gatewayConfiguration = new GatewayConfiguration() - { - CmSuffix = "sbx" - }; - + public CareContextControllerTest() { careContextController = - new CareContextController(gatewayClient.Object, - logger.Object, gatewayConfiguration, careContextService.Object, linkPatientRepository.Object); + new CareContextController(careContextService.Object, linkPatientRepository.Object); } [Fact] private void ShouldAddContext() { - var timeStamp = DateTime.Now.ToUniversalTime(); var requestId = Guid.NewGuid(); var cmSuffix = "sbx"; var careContextRepresentation = new CareContextRepresentation("anc", "xyz"); var careContexts = new List(); careContexts.Add(careContextRepresentation); - var addCareContextPatient = new AddCareContextsPatient("1234", "qwqwqw", careContexts); - var careContextLink = new AddCareContextsLink("1222", addCareContextPatient); - var addContextsAcknowledgement = new AddContextsAcknowledgement("success"); var error = new Error(ErrorCode.GatewayTimedOut, "Gateway timed out"); var resp = new Resp("123"); var correlationId = Uuid.Generate().ToString(); + var linkConfirmationRepresentation = + new LinkConfirmationRepresentation("1234", "qwqwqw", careContexts, "Prescription", 1); var gatewayAddContextsRequestRepresentation = - new GatewayAddContextsRequestRepresentation(requestId, timeStamp.ToString(DateTimeFormat), careContextLink); + new GatewayAddContextsRequestRepresentation("doctest@sbx",new List(){linkConfirmationRepresentation}); var onAddContextRequest = - new HipLinkContextConfirmation(requestId.ToString(), timeStamp, addContextsAcknowledgement, error, + new HipLinkContextConfirmation( "doctest@sbx","Successfully Linked care context", error, resp); - var addContextRequest = new AddContextsRequest("abc", careContexts, "pqr","abcd@sbx"); + var addContextRequest = new NewContextRequest("abc", "pqr", careContexts, "abcd@sbx"); - careContextService.Setup(a => a.AddContextsResponse(addContextRequest,"sbx")) + careContextService.Setup(a => a.AddContextsResponse(addContextRequest,"sbx",requestId)) .Returns(Task.FromResult(new Tuple (gatewayAddContextsRequestRepresentation, null))); gatewayClient.Setup( client => client.SendDataToGateway(PATH_ADD_PATIENT_CONTEXTS, - gatewayAddContextsRequestRepresentation, cmSuffix, correlationId)) + gatewayAddContextsRequestRepresentation, cmSuffix, correlationId,null,null,null)) .Returns(Task.CompletedTask) - .Callback - ((path, gr, suffix, corId) + .Callback + ((path, gr, suffix, corId,hipId,requestId,linkToken) => careContextController.Accepted(onAddContextRequest)); } [Fact] private void ShouldNotify() { - var timeStamp = DateTime.Now.ToUniversalTime(); - var requestId = Guid.NewGuid(); var error = new Error(ErrorCode.GatewayTimedOut, "Gateway timed out"); var resp = new Resp("123"); - var addContextsAcknowledgement = new AddContextsAcknowledgement("success"); + var careContextRepresentation = new CareContextRepresentation("anc", "xyz","VISIT",new List(){HiType.Prescription}); var hiTypes = new List(); - hiTypes.Add("Medication"); - var notifyContextRequest = new NotifyContextRequest("123", "swjs", "wew", hiTypes, "456"); + hiTypes.Add("Prescription"); + var notifyContextRequest = new NewContextRequest("abc", "swjs", new List(){careContextRepresentation},"doctest@sbx"); var onNotifyContextRequest = - new HipLinkContextConfirmation(requestId.ToString(), timeStamp, addContextsAcknowledgement, error, + new HipLinkContextConfirmation("doctest@sbx", "Successfully Linked care context", error, resp); var patient = new NotificationPatientContext("12"); var notificationCareContext = new NotificationCareContext("abc", "qqwq"); var hipReference = new NotificationContextHip("1212"); var gatewayNotificationContextsRequestRepresentation = - new GatewayNotificationContextRepresentation(requestId, timeStamp.ToString(DateTimeFormat), + new GatewayNotificationContextRepresentation( new NotificationContext(patient, notificationCareContext, hiTypes, new DateTime().ToString(DateTimeFormat), hipReference)); - careContextService.Setup(a => a.NotificationContextResponse(notifyContextRequest)) + careContextService.Setup(a => a.NotificationContextResponse(notifyContextRequest, careContextRepresentation)) .Returns(new Tuple (gatewayNotificationContextsRequestRepresentation, null)); @@ -113,10 +99,10 @@ private void ShouldNotify() gatewayClient.Setup( client => client.SendDataToGateway(PATH_NOTIFY_PATIENT_CONTEXTS, - gatewayNotificationContextsRequestRepresentation, cmSuffix, correlationId)) + gatewayNotificationContextsRequestRepresentation, cmSuffix, correlationId,null,null,null)) .Returns(Task.CompletedTask) - .Callback - ((path, gr, suffix, corId) + .Callback + ((path, gr, suffix, corId,hipId,requestId,linkToken) => careContextController.Accepted(onNotifyContextRequest)); } diff --git a/test/In.ProjectEKA.HipServiceTest/Patient/PatientControllerTest.cs b/test/In.ProjectEKA.HipServiceTest/Patient/PatientControllerTest.cs index 85796a258..95bb55b0a 100644 --- a/test/In.ProjectEKA.HipServiceTest/Patient/PatientControllerTest.cs +++ b/test/In.ProjectEKA.HipServiceTest/Patient/PatientControllerTest.cs @@ -58,7 +58,7 @@ private void ShouldNotifyHip() _gatewayClient.Setup( client => client.SendDataToGateway(PATH_PATIENT_ON_NOTIFY, - hipPatientNotifyConfirmation, cmSuffix, correlationId)) + hipPatientNotifyConfirmation, cmSuffix, correlationId,null,null,null)) .Returns(Task.FromResult("")); Assert.Equal(_patientController.NotifyHip(correlationId, hipPatientStatusNotification).Result.StatusCode, StatusCodes.Status202Accepted); @@ -83,7 +83,7 @@ private void ShouldSaveAPatient() _gatewayClient.Setup( client => client.SendDataToGateway(PATH_PROFILE_ON_SHARE, - profileShareConfirmation, cmSuffix, correlationId)) + profileShareConfirmation, cmSuffix, correlationId,null,null,null)) .Returns(Task.FromResult("")); Assert.Equal( ((Microsoft.AspNetCore.Mvc.AcceptedResult) _patientController @@ -112,7 +112,7 @@ private void ShouldThrowBadRequest() _gatewayClient.Setup( client => client.SendDataToGateway(PATH_PROFILE_ON_SHARE, - profileShareConfirmation, cmSuffix, correlationId)) + profileShareConfirmation, cmSuffix, correlationId,null,null,null)) .Returns(Task.FromResult("")); Assert.Equal( ((Microsoft.AspNetCore.Mvc.BadRequestResult) _patientController diff --git a/test/In.ProjectEKA.HipServiceTest/SmsNotification/SmsNotificationControllerTest.cs b/test/In.ProjectEKA.HipServiceTest/SmsNotification/SmsNotificationControllerTest.cs index b83278046..f4df641b2 100644 --- a/test/In.ProjectEKA.HipServiceTest/SmsNotification/SmsNotificationControllerTest.cs +++ b/test/In.ProjectEKA.HipServiceTest/SmsNotification/SmsNotificationControllerTest.cs @@ -62,10 +62,10 @@ private void shouldSendSMSNotificationForNewCareContextAndReturnAccepted() gatewayClient.Setup( client => client.SendDataToGateway(PATH_SMS_NOTIFY, - gatewaySmsNotifyRequestRepresentation, cmSuffix, correlationId)) + gatewaySmsNotifyRequestRepresentation, cmSuffix, correlationId,null,null,null)) .Returns(Task.CompletedTask) - .Callback - ((path, gr, suffix, corId) + .Callback + ((path, gr, suffix, corId,hipId,requestId,linkToken) => smsNotificationController.Accepted(onSmsContextRequest)); } @@ -86,10 +86,10 @@ private void shouldSendSMSNotificationForNewCareContextAndReturnRejected() gatewayClient.Setup( client => client.SendDataToGateway(PATH_SMS_NOTIFY, - gatewaySmsNotifyRequestRepresentation, cmSuffix, correlationId)) + gatewaySmsNotifyRequestRepresentation, cmSuffix, correlationId,null,null,null)) .Returns(Task.CompletedTask) - .Callback - ((path, gr, suffix, corId) + .Callback + ((path, gr, suffix, corId,hipId,requestId,linkToken) => smsNotificationController.Problem()); } @@ -120,7 +120,7 @@ private bool shouldReturnOnSmsNotifyRequest() var smsNotificationAcknowledgement = new SmsNotificationAcknowledgement("success"); var onSmsNotify = - new OnSmsNotifyRequest(requestId, timeStamp, "Ok", error, resp); + new OnSmsNotifyRequest( "Ok", error, resp); if (onSmsNotify != null) return true; return false; @@ -150,7 +150,7 @@ private AcceptedResult shouldReturnOnSmsRequestObjectAndReturnAccepted() var smsNotificationAcknowledgement = new SmsNotificationAcknowledgement("success"); var onSmsNotifyRequest = - new OnSmsNotifyRequest(requestId, timeStamp, "Ok", error, resp); + new OnSmsNotifyRequest("Ok", error, resp); return new AcceptedResult(); } diff --git a/test/In.ProjectEKA.HipServiceTest/UserAuth/UserAuthControllerTest.cs b/test/In.ProjectEKA.HipServiceTest/UserAuth/UserAuthControllerTest.cs index 5aa54543e..6f3d84e87 100644 --- a/test/In.ProjectEKA.HipServiceTest/UserAuth/UserAuthControllerTest.cs +++ b/test/In.ProjectEKA.HipServiceTest/UserAuth/UserAuthControllerTest.cs @@ -86,10 +86,10 @@ private void ShouldFetchPatientsAuthModes() gatewayClient.Setup( client => client.SendDataToGateway(PATH_FETCH_AUTH_MODES, - gatewayFetchModesRequestRepresentation, cmSuffix, correlationId)) + gatewayFetchModesRequestRepresentation, cmSuffix, correlationId,null,null,null)) .Returns(Task.CompletedTask) - .Callback - ((path, gr, suffix, corId) + .Callback + ((path, gr, suffix, corId,hipId,requestId,linkToken) => userAuthController.SetAuthModes(onFetchAuthModeRequest)); List modesReturned = new List(); @@ -122,7 +122,7 @@ private void ShouldNotFetchPatientsAuthModes() gatewayClient.Setup( client => client.SendDataToGateway(PATH_FETCH_AUTH_MODES, - gatewayFetchModesRequestRepresentation, cmSuffix, correlationId)) + gatewayFetchModesRequestRepresentation, cmSuffix, correlationId,null,null,null)) .Returns(Task.FromResult("")); if (userAuthController.GetAuthModes(correlationId, request).Result is JsonResult authMode) @@ -304,7 +304,7 @@ private async void ShouldReturnGatewayErrorForAuthFetch() gatewayClient.Setup( client => client.SendDataToGateway(PATH_FETCH_AUTH_MODES, - gatewayFetchModesRequestRepresentation, gatewayConfiguration.CmSuffix, correlationId)) + gatewayFetchModesRequestRepresentation, gatewayConfiguration.CmSuffix, correlationId,null,null,null)) .Returns(Task.CompletedTask); var response = await userAuthController.GetAuthModes(correlationId, request) as ObjectResult;