public async Task LinkPatient(LinkReferenceRequest request)
        {
            var cmUserId = request.Patient.Id;
            var cmSuffix = cmUserId.Substring(
                cmUserId.LastIndexOf("@", StringComparison.Ordinal) + 1);
            var patient = new LinkEnquiry(
                cmSuffix,
                cmUserId,
                request.Patient.ReferenceNumber,
                request.Patient.CareContexts);

            try
            {
                var doesRequestExists = await discoveryRequestRepository.RequestExistsFor(
                    request.TransactionId,
                    request.Patient?.Id,
                    request.Patient?.ReferenceNumber);

                ErrorRepresentation errorRepresentation = null;
                if (!doesRequestExists)
                {
                    errorRepresentation = new ErrorRepresentation(
                        new Error(ErrorCode.DiscoveryRequestNotFound, ErrorMessage.DiscoveryRequestNotFound));
                }

                var patientReferenceRequest =
                    new PatientLinkEnquiry(request.TransactionId, request.RequestId, patient);
                var patientLinkEnquiryRepresentation = new PatientLinkEnquiryRepresentation();

                var(linkReferenceResponse, error) = errorRepresentation != null
                    ? (patientLinkEnquiryRepresentation, errorRepresentation)
                    : await linkPatient.LinkPatients(patientReferenceRequest);

                var linkedPatientRepresentation = new LinkEnquiryRepresentation();
                if (linkReferenceResponse != null)
                {
                    linkedPatientRepresentation = linkReferenceResponse.Link;
                }
                var response = new GatewayLinkResponse(
                    linkedPatientRepresentation,
                    error?.Error,
                    new Resp(request.RequestId),
                    request.TransactionId,
                    DateTime.Now.ToUniversalTime(),
                    Guid.NewGuid());

                await gatewayClient.SendDataToGateway(PATH_ON_LINK_INIT, response, cmSuffix);
            }
            catch (Exception exception)
            {
                Log.Error(exception, exception.StackTrace);
            }
        }
        public async Task GetPatientCareContext(DiscoveryRequest request, string correlationId)
        {
            try
            {
                var(response, error) = await patientDiscovery.PatientFor(request);

                var patientId = request.Patient.Id;
                var cmSuffix  = patientId.Substring(
                    patientId.LastIndexOf("@", StringComparison.Ordinal) + 1);
                var gatewayDiscoveryRepresentation = new GatewayDiscoveryRepresentation(
                    response?.Patient,
                    Guid.NewGuid(),
                    DateTime.Now.ToUniversalTime(),
                    request.TransactionId, //TODO: should be reading transactionId from contract
                    error?.Error,
                    new Resp(request.RequestId));
                logger.LogInformation(LogEvents.Discovery,
                                      "Response about to be send for {RequestId} with {@Patient}",
                                      request.RequestId,
                                      response?.Patient);
                await gatewayClient.SendDataToGateway(PATH_ON_DISCOVER, gatewayDiscoveryRepresentation, cmSuffix, correlationId);
            }
            catch (Exception exception)
            {
                logger.LogError(LogEvents.Discovery, exception, "Error happened for {RequestId}", request.RequestId);
            }
        }
        public async Task StoreConsent(ConsentArtefactRepresentation consentArtefact)
        {
            var notification = consentArtefact.Notification;

            if (notification.Status == ConsentStatus.GRANTED)
            {
                var consent = new Consent(notification.ConsentDetail.ConsentId,
                                          notification.ConsentDetail,
                                          notification.Signature,
                                          notification.Status,
                                          notification.ConsentId);
                await consentRepository.AddAsync(consent);
            }
            else
            {
                await consentRepository.UpdateAsync(notification.ConsentId, notification.Status);

                if (notification.Status == ConsentStatus.REVOKED)
                {
                    var consent = await consentRepository.GetFor(notification.ConsentId);

                    var cmSuffix        = consent.ConsentArtefact.ConsentManager.Id;
                    var gatewayResponse = new GatewayRevokedConsentRepresentation(
                        Guid.NewGuid(),
                        DateTime.Now.ToUniversalTime(),
                        new ConsentUpdateResponse(ConsentUpdateStatus.OK.ToString(),
                                                  notification.ConsentId),
                        null,
                        new Resp(consentArtefact.RequestId));
                    await gatewayClient.SendDataToGateway(PATH_CONSENT_ON_NOTIFY, gatewayResponse, cmSuffix);
                }
            }
        }
        public async Task StoreConsent(ConsentArtefactRepresentation consentArtefact, String correlationId)
        {
            var notification = consentArtefact.Notification;

            if (notification.Status == ConsentStatus.GRANTED)
            {
                var consent = new Consent(notification.ConsentDetail.ConsentId,
                                          notification.ConsentDetail,
                                          notification.Signature,
                                          notification.Status,
                                          notification.ConsentId);
                await consentRepository.AddAsync(consent);

                var patientId = consent.ConsentArtefact.Patient.Id;
                var cmSuffix  = patientId.Substring(
                    patientId.LastIndexOf("@", StringComparison.Ordinal) + 1);
                var gatewayResponse = new GatewayConsentRepresentation(
                    Guid.NewGuid(),
                    DateTime.Now.ToUniversalTime(),
                    new ConsentUpdateResponse(ConsentUpdateStatus.OK.ToString(), notification.ConsentId),
                    null,
                    new Resp(consentArtefact.RequestId));
                await gatewayClient.SendDataToGateway(PATH_CONSENT_ON_NOTIFY, gatewayResponse, cmSuffix, correlationId);
            }
            else
            {
                await consentRepository.UpdateAsync(notification.ConsentId, notification.Status);

                if (notification.Status == ConsentStatus.REVOKED)
                {
                    var consent = await consentRepository.GetFor(notification.ConsentId);

                    var patientId = consent.ConsentArtefact.Patient.Id;
                    var cmSuffix  = patientId.Substring(
                        patientId.LastIndexOf("@", StringComparison.Ordinal) + 1);
                    var gatewayResponse = new GatewayConsentRepresentation(
                        Guid.NewGuid(),
                        DateTime.Now.ToUniversalTime(),
                        new ConsentUpdateResponse(ConsentUpdateStatus.OK.ToString(), notification.ConsentId),
                        null,
                        new Resp(consentArtefact.RequestId));
                    await gatewayClient.SendDataToGateway(PATH_CONSENT_ON_NOTIFY, gatewayResponse, cmSuffix, correlationId);
                }
            }
        }
        private void ShouldReturnDataToGateway()
        {
            var handlerMock          = new Mock <HttpMessageHandler>(MockBehavior.Strict);
            var httpClient           = new HttpClient(handlerMock.Object);
            var gatewayConfiguration = new GatewayConfiguration {
                Url = "http://someUrl"
            };
            var authenticationUri            = new Uri($"{gatewayConfiguration.Url}/{PATH_SESSIONS}");
            var expectedUri                  = new Uri($"{gatewayConfiguration.Url}{PATH_ON_DISCOVER}");
            var patientEnquiryRepresentation = new PatientEnquiryRepresentation(
                "123",
                "Jack",
                new List <CareContextRepresentation>(),
                new List <string>());
            var gatewayDiscoveryRepresentation = new GatewayDiscoveryRepresentation(
                patientEnquiryRepresentation,
                Guid.NewGuid(),
                DateTime.Now,
                "transactionId",
                null,
                new Resp("requestId"));
            var gatewayClient = new GatewayClient(httpClient, gatewayConfiguration);
            var definition    = new { accessToken = "Whatever", tokenType = "Bearer" };
            var result        = JsonConvert.SerializeObject(definition);
            var correlationId = Uuid.Generate().ToString();

            handlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>())
            .ReturnsInOrder(() => Task.FromResult(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(result)
            }), () => Task.FromResult(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK
            }));

            gatewayClient.SendDataToGateway(PATH_ON_DISCOVER, gatewayDiscoveryRepresentation, "ncg", correlationId);

            handlerMock.Protected().Verify(
                "SendAsync",
                Times.Exactly(1),
                ItExpr.Is <HttpRequestMessage>(message => message.Method == HttpMethod.Post &&
                                               message.RequestUri == expectedUri),
                ItExpr.IsAny <CancellationToken>());
            handlerMock.Protected().Verify(
                "SendAsync",
                Times.Exactly(1),
                ItExpr.Is <HttpRequestMessage>(message => message.Method == HttpMethod.Post &&
                                               message.RequestUri == authenticationUri),
                ItExpr.IsAny <CancellationToken>());
        }
 public virtual async Task NotifyGateway(string cmSuffix, DataNotificationRequest dataNotificationRequest)
 {
     var notificationRequest = new GatewayDataNotificationRequest(Guid.NewGuid(),
                                                                  DateTime.Now.ToUniversalTime(),
                                                                  new DataFlowNotificationRequest(
                                                                      dataNotificationRequest.TransactionId,
                                                                      dataNotificationRequest.ConsentId,
                                                                      dataNotificationRequest.DoneAt,
                                                                      dataNotificationRequest.Notifier,
                                                                      dataNotificationRequest.StatusNotification));
     await gatewayClient.SendDataToGateway(PATH_HEALTH_INFORMATION_NOTIFY_GATEWAY,
                                           notificationRequest,
                                           cmSuffix);
 }
        public async Task ShareResponseFor(JObject request, String correlationId)
        {
            var patientProfileRequest = request.ToObject <PatientProfile>();

            logger.LogInformation("Patient Details: {@PatientProfile}", patientProfileRequest);
            var cmSuffix = patientProfileRequest.PatientDetails.UserDemographics.HealthId.Substring(
                patientProfileRequest.PatientDetails.UserDemographics.HealthId.LastIndexOf("@", StringComparison.Ordinal) + 1);
            var gatewayResponse = new PatientProfileAcknowledgementResponse(
                Guid.NewGuid(),
                DateTime.Now.ToUniversalTime(),
                new Acknowledgement(patientProfileRequest.PatientDetails.UserDemographics.HealthId, Status.SUCCESS),
                new Resp(patientProfileRequest.RequestId),
                null);
            await gatewayClient.SendDataToGateway(PATH_PATIENT_PROFILE_ON_SHARE,
                                                  gatewayResponse,
                                                  cmSuffix,
                                                  correlationId);
        }
        private void ShouldNotPostDataIfAuthenticationWithGatewayFailed()
        {
            var handlerMock          = new Mock <HttpMessageHandler>(MockBehavior.Strict);
            var httpClient           = new HttpClient(handlerMock.Object);
            var gatewayConfiguration = new GatewayConfiguration {
                Url = "http://someUrl"
            };
            var authenticationUri            = new Uri($"{gatewayConfiguration.Url}/{PATH_SESSIONS}");
            var patientEnquiryRepresentation = new PatientEnquiryRepresentation(
                "123",
                "Jack",
                new List <CareContextRepresentation>(),
                new List <string>());
            var gatewayDiscoveryRepresentation = new GatewayDiscoveryRepresentation(
                patientEnquiryRepresentation,
                Guid.NewGuid(),
                DateTime.Now,
                "transactionId",
                null,
                new Resp("requestId"));
            var gatewayClient = new GatewayClient(httpClient, gatewayConfiguration);
            var correlationId = Uuid.Generate().ToString();

            handlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.BadGateway
            })
            .Verifiable();

            gatewayClient.SendDataToGateway(PATH_ON_DISCOVER, gatewayDiscoveryRepresentation, "ncg", correlationId);

            handlerMock.Protected().Verify(
                "SendAsync",
                Times.Exactly(1),
                ItExpr.Is <HttpRequestMessage>(message => message.Method == HttpMethod.Post &&
                                               message.RequestUri == authenticationUri),
                ItExpr.IsAny <CancellationToken>());
        }
 public async Task AuthFor(JObject request)
 {
     await gatewayClient.SendDataToGateway(Constants.PATH_AUTH_CONFIRM, request, "ncg")
     .ConfigureAwait(false);
 }