public async Task <IActionResult> Notify([FromBody] Notification notification) { using (LogContext.PushProperty("RequestRef", $"{notification?.AgencyFileId}")) using (LogContext.PushProperty("AgencyCode", $"{notification?.Agency}")) using (LogContext.PushProperty("SearchRequestKey", $"{notification?.FileId}")) { _logger.Log(LogLevel.Information, $"receive {notification?.Acvitity} notification"); if (notification == null) { _logger.Log(LogLevel.Error, $"Notification request cannot be null"); return(BadRequest("Notification request cannot be null")); } if (!ModelState.IsValid) { _logger.Log(LogLevel.Error, $"Notification request is invalid"); return(BadRequest(ModelState)); } _logger.Log(LogLevel.Debug, $"Receving notification from FAMS3 - Dynamics Platform for Search Request - File Id: {notification.FileId} (Agency SR Id {notification.AgencyFileId})"); var notifyEvent = new SearchRequestNotificationEvent { ProviderProfile = new ProviderProfile { Name = notification.Agency }, NotificationType = (NotificationType)Enum.Parse(typeof(NotificationType), notification.Acvitity, true), RequestId = notification.AgencyFileId, SearchRequestKey = notification.FileId, QueuePosition = notification.PositionInQueue, Message = $"Activity {notification.Acvitity} occured. FSO : {notification.FSOName}", TimeStamp = notification.ActivityDate, EstimatedCompletion = notification.EstimatedCompletionDate, FSOName = notification.FSOName, Person = notification.Person }; await _publisher.PublishSearchRequestNotification(notifyEvent); return(Ok()); } }
private async Task NotifySearchRequestOrderedEvent( string requestId, SearchRequestOrdered searchRequestOrdered, CancellationToken cancellationToken, int retryTimes, int maxRetryTimes) { var webHookName = "SearchRequest"; if (searchRequestOrdered == null) { throw new ArgumentNullException(nameof(SearchRequestOrdered)); } string eventName = searchRequestOrdered.Action switch { RequestAction.NEW => "CreateSearchRequest", RequestAction.UPDATE => "UpdateSearchRequest", RequestAction.CANCEL => "CancelSearchRequest", _ => null }; foreach (var webHook in _searchRequestOptions.WebHooks) { _logger.LogDebug( $"The webHook {webHookName} notification is attempting to send {eventName} for {webHook.Name} webhook."); if (!URLHelper.TryCreateUri(webHook.Uri, eventName, $"{requestId}", out var endpoint)) { _logger.LogWarning( $"The webHook {webHookName} notification uri is not established or is not an absolute Uri for {webHook.Name}. Set the WebHook.Uri value on SearchApi.WebHooks settings."); throw new Exception($"The webHook {webHookName} notification uri is not established or is not an absolute Uri for {webHook.Name}."); } using var request = new HttpRequestMessage(); try { StringContent content = new StringContent(JsonConvert.SerializeObject(searchRequestOrdered)); content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request.Content = content; request.Method = HttpMethod.Post; request.Headers.Accept.Add( System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); request.Headers.Add("X-ApiKey", _searchRequestOptions.ApiKeyForDynadaptor); request.RequestUri = endpoint; var response = await _httpClient.SendAsync(request, cancellationToken); if (!response.IsSuccessStatusCode) { if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError || response.StatusCode == System.Net.HttpStatusCode.GatewayTimeout) { string reason = await response.Content.ReadAsStringAsync(); _logger.LogError( $"The webHook {webHookName} notification has not executed status {eventName} successfully for {webHook.Name} webHook. The error code is {response.StatusCode.GetHashCode()}.Reason is {reason}."); throw(new Exception($"The webHook {webHookName} notification has not executed status {eventName} successfully for {webHook.Name} webHook. The error code is {response.StatusCode.GetHashCode()}.")); } else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) { string reason = await response.Content.ReadAsStringAsync(); RejectReason reasonObj = JsonConvert.DeserializeObject <RejectReason>(reason); if (reasonObj.ReasonCode.Equals("error", StringComparison.InvariantCultureIgnoreCase)) { throw new Exception("should not get here. the request is wrong."); } await _searchRequestEventPublisher.PublishSearchRequestRejected( searchRequestOrdered, new List <ValidationResult>() { new ValidationResultData() { PropertyName = reasonObj.ReasonCode, ErrorMessage = reasonObj.Message } }); return; } var exContent = await response.Content.ReadAsStringAsync(); throw new Exception($"Message Failed {response.StatusCode}, {exContent}"); } _logger.LogInformation("get response successfully from webhook."); string responseContent = await response.Content.ReadAsStringAsync(); var saved = JsonConvert.DeserializeObject <SearchRequestSavedEvent>(responseContent); //for the new action, we changed from Dynamics push the notification to here, openshift publish notification once sr is created. //for the update action, fmep needs notified and notification from dynamics. if (saved.Action == RequestAction.NEW) { _logger.LogInformation("create sr get success, publish accepted notification"); var notifyEvent = new SearchRequestNotificationEvent { ProviderProfile = saved.ProviderProfile, NotificationType = NotificationType.RequestSaved, RequestId = saved.RequestId, SearchRequestKey = saved.SearchRequestKey, QueuePosition = saved.QueuePosition, Message = $"Activity RequestSaved occured. ", TimeStamp = DateTime.Now, EstimatedCompletion = saved.EstimatedCompletion, FSOName = null, Person = null }; await _searchRequestEventPublisher.PublishSearchRequestNotification(notifyEvent); } if (saved.Action == RequestAction.UPDATE) { _logger.LogInformation($"publish SearchRequestSaved"); await _searchRequestEventPublisher.PublishSearchRequestSaved(saved); _logger.LogInformation("update sr get success, publish accepted notification"); var notifyEvent = new SearchRequestNotificationEvent { ProviderProfile = saved.ProviderProfile, NotificationType = NotificationType.RequestSaved, RequestId = saved.RequestId, SearchRequestKey = saved.SearchRequestKey, QueuePosition = saved.QueuePosition, Message = $"Activity RequestSaved occured. ", TimeStamp = DateTime.Now, EstimatedCompletion = saved.EstimatedCompletion, FSOName = null, Person = null }; await _searchRequestEventPublisher.PublishSearchRequestNotification(notifyEvent); } if (saved.Action == RequestAction.CANCEL) { _logger.LogInformation( $"publish SearchRequestSaved"); await _searchRequestEventPublisher.PublishSearchRequestSaved(saved); } } catch (Exception exception) { _logger.LogError(exception, exception.Message); throw; } } }