예제 #1
0
        public void Agent_phone_null_SearchRequestOrdered_should_map_normally()
        {
            SearchRequestOrdered searchRequestOrdered = new SearchRequestOrdered()
            {
                Action           = RequestAction.NEW,
                RequestId        = "requestId",
                SearchRequestKey = "requestKey",
                SearchRequestId  = Guid.NewGuid(),
                Person           = new Person()
                {
                    Agency = new Agency()
                    {
                        Agent = new Name()
                        {
                        },
                        AgentContact = new List <Phone>
                        {
                        },
                        Code      = "FMEP",
                        RequestId = "QFP-12422509096920180928083433",
                    },
                },
            };
            SearchRequestEntity entity = _mapper.Map <SearchRequestEntity>(searchRequestOrdered);

            Assert.AreEqual(null, entity.AgentFirstName);
            Assert.AreEqual(null, entity.AgentLastName);
            Assert.AreEqual(null, entity.AgentPhoneNumber);
            Assert.AreEqual(null, entity.AgentPhoneExtension);
            Assert.AreEqual(null, entity.AgentFax);
            Assert.AreEqual(null, entity.Notes);
        }
예제 #2
0
        private async Task <SSG_SearchRequest> VerifySearchRequest(SearchRequestOrdered searchRequestOrdered)
        {
            //get existedSearchRequest
            SSG_SearchRequest existedSearchRequest = await _searchRequestService.GetSearchRequest(searchRequestOrdered.SearchRequestKey, _cancellationToken);

            if (existedSearchRequest == null)
            {
                string error = "the search request does not exist.";
                _logger.LogInformation(error);
                throw new Exception(error);
            }
            if (existedSearchRequest.StatusCode == SearchRequestStatusCode.SearchRequestCancelled.Value)
            {
                throw new AgencyRequestException("fileCancelled", new Exception($"File {searchRequestOrdered.SearchRequestKey} is cancelled."));
            }
            if (existedSearchRequest.StatusCode == SearchRequestStatusCode.SearchRequestClosed.Value)
            {
                throw new AgencyRequestException("fileClosed", new Exception($"File {searchRequestOrdered.SearchRequestKey} is closed."));
            }
            if (existedSearchRequest.Agency == null || existedSearchRequest.Agency.AgencyCode != searchRequestOrdered?.Person?.Agency?.Code)
            {
                throw new AgencyRequestException("wrongAgency", new Exception($"Wrong Agency Code."));
            }
            return(existedSearchRequest);
        }
예제 #3
0
        public void Agent_invliad_request_ID_SearchRequestOrdered_should_map_normally()
        {
            SearchRequestOrdered searchRequestOrdered = new SearchRequestOrdered()
            {
                Action = RequestAction.NEW,
                Person = new Person()
                {
                    Agency = new Agency()
                    {
                        Agent = new Name()
                        {
                        },
                        AgentContact = new List <Phone>
                        {
                        },
                        Code      = "FMEP",
                        RequestId = "12222393288",
                    },
                },
            };
            SearchRequestEntity entity = _mapper.Map <SearchRequestEntity>(searchRequestOrdered);

            Assert.AreEqual("12222393288", entity.OriginalRequestorReference);
            Assert.AreEqual(null, entity.PayerId);
            Assert.AreEqual(null, entity.CaseTrackingId);
            Assert.AreEqual(null, entity.PersonSoughtRole);
        }
예제 #4
0
        public async Task With_exception_throws_searchRequestOrdered_CreateSearchRequest_should_return_InternalServerError_systemCancel_sr()
        {
            string requestId = "exception";
            SearchRequestOrdered updateSearchRequestOrdered = new SearchRequestOrdered()
            {
                Action    = RequestAction.NEW,
                RequestId = requestId,
                TimeStamp = DateTime.Now,
            };

            _agencyRequestServiceMock.Setup(
                x => x.ProcessSearchRequestOrdered(It.Is <SearchRequestOrdered>(x => x.RequestId == requestId)))
            .Throws(new Exception("exception throws"));

            _agencyRequestServiceMock.Setup(
                x => x.GetSSGSearchRequest())
            .Returns(new SSG_SearchRequest {
                FileId = "111111"
            });

            _agencyRequestServiceMock.Setup(
                x => x.SystemCancelSSGSearchRequest(It.IsAny <SSG_SearchRequest>()))
            .Returns(Task.FromResult <bool>(true));

            var result = await _sut.CreateSearchRequest("exceptionrequest", updateSearchRequestOrdered);

            _agencyRequestServiceMock.Verify(x => x.ProcessSearchRequestOrdered(It.IsAny <SearchRequestOrdered>()), Times.Once);
            _agencyRequestServiceMock.Verify(x => x.SystemCancelSSGSearchRequest(It.Is <SSG_SearchRequest>(m => m.FileId == "111111")), Times.Once);
            Assert.AreEqual(500, ((ObjectResult)result).StatusCode);
        }
예제 #5
0
        public async Task <SSG_SearchRequest> ProcessCancelSearchRequest(SearchRequestOrdered searchRequestOrdered)
        {
            var cts = new CancellationTokenSource();

            _cancellationToken = cts.Token;
            await VerifySearchRequest(searchRequestOrdered);

            return(await _searchRequestService.CancelSearchRequest(searchRequestOrdered.SearchRequestKey, searchRequestOrdered?.Person?.Agency?.Notes, _cancellationToken));
        }
예제 #6
0
        public async Task With_update_action_searchRequestOrdered_CreateSearchRequest_should_return_BadRequest()
        {
            SearchRequestOrdered updateSearchRequestOrdered = new SearchRequestOrdered()
            {
                Action    = RequestAction.UPDATE,
                RequestId = Guid.NewGuid().ToString(),
                TimeStamp = DateTime.Now,
            };
            var result = await _sut.CreateSearchRequest("requestId", updateSearchRequestOrdered);

            _agencyRequestServiceMock.Verify(x => x.ProcessSearchRequestOrdered(It.IsAny <SearchRequestOrdered>()), Times.Never);
            Assert.IsInstanceOf(typeof(BadRequestObjectResult), result);
        }
예제 #7
0
        public async Task <IActionResult> UpdateSearchRequest(string requestId, [FromBody] SearchRequestOrdered searchRequestOrdered)
        {
            using (LogContext.PushProperty("RequestRef", $"{requestId}"))
                using (LogContext.PushProperty("AgencyCode", $"{searchRequestOrdered?.Person?.Agency?.Code}"))
                    using (LogContext.PushProperty("SearchRequestKey", $"{searchRequestOrdered?.SearchRequestKey}"))
                    {
                        _logger.LogInformation("Get UpdateSearchRequest");
                        if (string.IsNullOrEmpty(requestId))
                        {
                            return(BadRequest(new { Message = "requestId cannot be empty." }));
                        }

                        if (searchRequestOrdered == null)
                        {
                            return(BadRequest(new { Message = "SearchRequestOrdered cannot be empty." }));
                        }

                        if (searchRequestOrdered.Action != RequestAction.UPDATE)
                        {
                            return(BadRequest(new { Message = "UpdateSearchRequest should only get Update request." }));
                        }

                        if (String.IsNullOrEmpty(searchRequestOrdered.SearchRequestKey))
                        {
                            return(BadRequest(new { Message = "FileId cannot be empty for updating request." }));
                        }

                        SSG_SearchRequest updatedSearchRequest = null;
                        try
                        {
                            updatedSearchRequest = await _agencyRequestService.ProcessUpdateSearchRequest(searchRequestOrdered);

                            if (updatedSearchRequest == null)
                            {
                                return(BadRequest(new { Message = $"FileId ( {searchRequestOrdered.SearchRequestKey} ) is invalid." }));
                            }
                        }
                        catch (AgencyRequestException ex)
                        {
                            _logger.LogError(ex.Message);
                            return(StatusCode(StatusCodes.Status500InternalServerError, new { ReasonCode = ex.Message, Message = ex.InnerException?.Message }));
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex.Message);
                            return(StatusCode(StatusCodes.Status500InternalServerError, new { ReasonCode = "error", Message = "error" }));
                        }
                        _logger.LogInformation("UpdateSearchRequest successfully");
                        return(Ok(BuildSearchRequestSaved_Update(updatedSearchRequest, searchRequestOrdered)));
                    }
        }
예제 #8
0
        public void Person_null_SearchRequestOrdered_should_return_throw_null_exception()
        {
            SearchRequestOrdered searchRequestOrdered = new SearchRequestOrdered()
            {
                Action           = RequestAction.NEW,
                RequestId        = "requestId",
                SearchRequestKey = "requestKey",
                SearchRequestId  = Guid.NewGuid(),
                TimeStamp        = DateTime.Now,
                Person           = null,
            };

            Assert.Throws <ArgumentNullException>(() => _mapper.Map <SearchRequestEntity>(searchRequestOrdered));
        }
예제 #9
0
        public async Task With_nonexist_fileID_searchRequestOrdered_CancelSearchRequest_should_return_BadRequest()
        {
            SearchRequestOrdered updateSearchRequestOrdered = new SearchRequestOrdered()
            {
                Action           = RequestAction.CANCEL,
                RequestId        = Guid.NewGuid().ToString(),
                TimeStamp        = DateTime.Now,
                SearchRequestKey = "notexist"
            };

            _agencyRequestServiceMock.Setup(x => x.ProcessCancelSearchRequest(It.IsAny <SearchRequestOrdered>()))
            .ThrowsAsync(new Exception("search request does not exist."));
            var result = await _sut.CancelSearchRequest("requestId", updateSearchRequestOrdered);

            _agencyRequestServiceMock.Verify(x => x.ProcessSearchRequestOrdered(It.IsAny <SearchRequestOrdered>()), Times.Never);
            Assert.AreEqual(500, ((ObjectResult)result).StatusCode);
        }
예제 #10
0
        public async Task With_nonexist_fileID_searchRequestOrdered_UpdateSearchRequest_should_return_BadRequest()
        {
            SearchRequestOrdered updateSearchRequestOrdered = new SearchRequestOrdered()
            {
                Action           = RequestAction.UPDATE,
                RequestId        = Guid.NewGuid().ToString(),
                TimeStamp        = DateTime.Now,
                SearchRequestKey = "notexist"
            };

            _agencyRequestServiceMock.Setup(x => x.ProcessUpdateSearchRequest(It.IsAny <SearchRequestOrdered>()))
            .Returns(Task.FromResult <SSG_SearchRequest>(null));
            var result = await _sut.UpdateSearchRequest("requestId", updateSearchRequestOrdered);

            _agencyRequestServiceMock.Verify(x => x.ProcessUpdateSearchRequest(It.IsAny <SearchRequestOrdered>()), Times.Once);
            Assert.IsInstanceOf(typeof(BadRequestObjectResult), result);
        }
예제 #11
0
        public async Task <IActionResult> CancelSearchRequest(string requestId, [FromBody] SearchRequestOrdered searchRequestOrdered)
        {
            using (LogContext.PushProperty("AgencyCode", $"{searchRequestOrdered?.Person?.Agency?.Code}"))
                using (LogContext.PushProperty("SearchRequestKey", $"{searchRequestOrdered?.SearchRequestKey}"))
                {
                    _logger.LogInformation("Get CancelSearchRequest");

                    if (searchRequestOrdered == null)
                    {
                        return(BadRequest(new { ReasonCode = "error", Message = "SearchRequestOrdered cannot be empty." }));
                    }

                    if (searchRequestOrdered.Action != RequestAction.CANCEL)
                    {
                        return(BadRequest(new { ReasonCode = "error", Message = "CancelSearchRequest should only get Cancel request." }));
                    }

                    if (String.IsNullOrEmpty(searchRequestOrdered.SearchRequestKey))
                    {
                        return(BadRequest(new { ReasonCode = "error", Message = "FileId cannot be empty for cancelling request." }));
                    }

                    SSG_SearchRequest cancelledSearchRequest;
                    try
                    {
                        cancelledSearchRequest = await _agencyRequestService.ProcessCancelSearchRequest(searchRequestOrdered);
                    }
                    catch (AgencyRequestException ex)
                    {
                        _logger.LogInformation(ex.Message);
                        return(BadRequest(new { ReasonCode = ex.Message, Message = $"FileId ( {searchRequestOrdered.SearchRequestKey} ) is invalid. {ex.Message}" }));
                    }
                    catch (Exception ex)
                    {
                        if (ex is Simple.OData.Client.WebRequestException)
                        {
                            _logger.LogError(((Simple.OData.Client.WebRequestException)ex).Response);
                        }
                        _logger.LogError(ex.Message);
                        return(StatusCode(StatusCodes.Status500InternalServerError, new { ReasonCode = "error", Message = "error" }));
                    }
                    _logger.LogInformation("CancelSearchRequest successfully");
                    return(Ok(BuildSearchRequestSaved_Cancel(cancelledSearchRequest, searchRequestOrdered)));
                }
        }
예제 #12
0
        public async Task With_valid_searchRequestOrdered_CreateSearchRequest_should_return_ok_with_correct_content()
        {
            SearchRequestOrdered validSearchRequestOrdered = new SearchRequestOrdered()
            {
                Action    = RequestAction.NEW,
                RequestId = "121212121212",
                TimeStamp = DateTime.Now,
                Person    = new Person()
                {
                    Agency = new Agency()
                    {
                        RequestId = "121212121212",
                        Code      = "FMEP"
                    }
                }
            };

            SSG_SearchRequest tempSearchRequest = new SSG_SearchRequest()
            {
                FileId          = "fileId",
                SearchRequestId = Guid.NewGuid()
            };

            _agencyRequestServiceMock.Setup(x => x.ProcessSearchRequestOrdered(It.IsAny <SearchRequestOrdered>()))
            .Returns(Task.FromResult <SSG_SearchRequest>(tempSearchRequest));
            _agencyRequestServiceMock.Setup(x => x.SubmitSearchRequestToQueue(It.IsAny <Guid>()))
            .Returns(Task.CompletedTask);

            _agencyRequestServiceMock.Setup(x => x.RefreshSearchRequest(It.IsAny <Guid>()))
            .Returns(Task.FromResult <SSG_SearchRequest>(tempSearchRequest));

            var result = await _sut.CreateSearchRequest("normalsearchRequest", validSearchRequestOrdered);

            _agencyRequestServiceMock.Verify(x => x.ProcessSearchRequestOrdered(It.IsAny <SearchRequestOrdered>()), Times.Once);
            var resultValue = result as OkObjectResult;

            Assert.NotNull(resultValue);
            var saved = resultValue.Value as SearchRequestSaved;

            Assert.NotNull(saved);
            Assert.AreEqual("fileId", saved.SearchRequestKey);
            Assert.AreEqual("FMEP", saved.ProviderProfile.Name);
            Assert.AreEqual("The new Search Request reference: 121212121212 has been submitted successfully.", saved.Message);
        }
예제 #13
0
        public async Task <IActionResult> CreateSearchRequest(string requestId, [FromBody] SearchRequestOrdered searchRequestOrdered)
        {
            using (LogContext.PushProperty("RequestRef", $"{requestId}"))
                using (LogContext.PushProperty("AgencyCode", $"{searchRequestOrdered?.Person?.Agency?.Code}"))
                {
                    _logger.LogInformation("Get CreateSearchRequest");
                    if (string.IsNullOrEmpty(requestId))
                    {
                        return(BadRequest(new { Message = "requestId cannot be empty." }));
                    }
                    if (searchRequestOrdered == null)
                    {
                        return(BadRequest(new { Message = "SearchRequestOrdered cannot be empty." }));
                    }
                    if (searchRequestOrdered.Action != RequestAction.NEW)
                    {
                        return(BadRequest(new { Message = "CreateSearchRequest should only get NEW request." }));
                    }

                    try
                    {
                        SSG_SearchRequest createdSearchRequest = await _agencyRequestService.ProcessSearchRequestOrdered(searchRequestOrdered);

                        if (createdSearchRequest == null)
                        {
                            return(StatusCode(StatusCodes.Status500InternalServerError));
                        }

                        _logger.LogInformation("SearchRequest is created successfully.");
                        return(Ok(BuildSearchRequestSaved_Create(createdSearchRequest, searchRequestOrdered)));
                    }
                    catch (AgencyRequestException ex)
                    {
                        _logger.LogError(ex.Message);
                        return(StatusCode(StatusCodes.Status500InternalServerError, new { ReasonCode = ex.Message, Message = ex.InnerException?.Message }));
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex.Message);
                        return(StatusCode(StatusCodes.Status500InternalServerError, new { ReasonCode = "error", Message = "error" }));
                    }
                }
        }
예제 #14
0
        public async Task With_exception_UpdateSearchRequest_should_return_OK_with_failed_message()
        {
            SearchRequestOrdered updateSearchRequestOrdered = new SearchRequestOrdered()
            {
                Action           = RequestAction.UPDATE,
                RequestId        = "23232321",
                TimeStamp        = DateTime.Now,
                SearchRequestKey = "exceptionFileId"
            };

            _agencyRequestServiceMock.Setup(
                x => x.ProcessUpdateSearchRequest(It.Is <SearchRequestOrdered>(x => x.SearchRequestKey == "exceptionFileId")))
            .Throws(new Exception("exception throws"));

            var result = await _sut.UpdateSearchRequest("requestId", updateSearchRequestOrdered);

            _agencyRequestServiceMock.Verify(x => x.ProcessUpdateSearchRequest(It.IsAny <SearchRequestOrdered>()), Times.Once);
            Assert.AreEqual(500, ((ObjectResult)result).StatusCode);
        }
예제 #15
0
        public async Task <SSG_SearchRequest> ProcessSearchRequestOrdered(SearchRequestOrdered searchRequestOrdered)
        {
            _personSought = searchRequestOrdered.Person;
            var cts = new CancellationTokenSource();

            _cancellationToken = cts.Token;

            SearchRequestEntity searchRequestEntity = _mapper.Map <SearchRequestEntity>(searchRequestOrdered);

            searchRequestEntity.CreatedByApi = true;
            searchRequestEntity.SendNotificationOnCreation = true;
            _uploadedSearchRequest = await _searchRequestService.CreateSearchRequest(searchRequestEntity, cts.Token);

            if (_uploadedSearchRequest == null)
            {
                return(null);
            }
            _logger.LogInformation("Create Search Request successfully");

            PersonEntity personEntity = _mapper.Map <PersonEntity>(_personSought);

            personEntity.SearchRequest     = _uploadedSearchRequest;
            personEntity.InformationSource = InformationSourceType.Request.Value;
            personEntity.IsCreatedByAgency = true;
            personEntity.IsPrimary         = true;
            _uploadedPerson = await _searchRequestService.SavePerson(personEntity, _cancellationToken);

            _logger.LogInformation("Create Person successfully");

            await UploadIdentifiers();
            await UploadAddresses();
            await UploadPhones();
            await UploadEmployment();
            await UploadRelatedPersons();
            await UploadRelatedApplicant(_uploadedSearchRequest.ApplicantFirstName, _uploadedSearchRequest.ApplicantLastName);
            await UploadAliases();
            await UploadSafetyConcern();

            return(_uploadedSearchRequest);
        }
예제 #16
0
        public async Task With_valid_searchRequestOrdered_CancelSearchRequest_should_return_ok_with_correct_content()
        {
            SearchRequestOrdered validSearchRequestOrdered = new SearchRequestOrdered()
            {
                Action           = RequestAction.CANCEL,
                RequestId        = "121212121212",
                SearchRequestKey = "fileId",
                TimeStamp        = DateTime.Now,
                Person           = new Person()
                {
                    Agency = new Agency()
                    {
                        RequestId = "121212121212",
                        Code      = "FMEP"
                    }
                }
            };

            _agencyRequestServiceMock.Setup(x => x.ProcessCancelSearchRequest(It.IsAny <SearchRequestOrdered>()))
            .Returns(Task.FromResult <SSG_SearchRequest>(new SSG_SearchRequest()
            {
                FileId          = "fileId",
                SearchRequestId = Guid.NewGuid(),
                StatusCode      = SearchRequestStatusCode.AgencyCancelled.Value
            }));

            var result = await _sut.CancelSearchRequest("requestId", validSearchRequestOrdered);

            _agencyRequestServiceMock.Verify(x => x.ProcessCancelSearchRequest(It.IsAny <SearchRequestOrdered>()), Times.Once);
            var resultValue = result as OkObjectResult;

            Assert.NotNull(resultValue);
            var saved = resultValue.Value as SearchRequestSaved;

            Assert.NotNull(saved);
            Assert.AreEqual("fileId", saved.SearchRequestKey);
            Assert.AreEqual("FMEP", saved.ProviderProfile.Name);
            Assert.AreEqual("The Search Request fileId has been cancelled successfully upon the request 121212121212.", saved.Message);
        }
        public async Task null_identifiers_addresses_phones_employments_relatedPersons_searchRequestOrdered_ProcessSearchRequestOrdered_should_succeed()
        {
            Person nullPerson = new Person()
            {
                DateOfBirth    = DateTime.Now,
                FirstName      = "TEST1",
                LastName       = "TEST2",
                Identifiers    = null,
                Addresses      = null,
                Phones         = null,
                Names          = null,
                RelatedPersons = null,
                Employments    = null
            };
            SearchRequestOrdered searchRequstOrdered = new SearchRequestOrdered()
            {
                Action           = RequestAction.NEW,
                RequestId        = "1111111",
                SearchRequestId  = Guid.NewGuid(),
                TimeStamp        = new DateTime(2010, 1, 1),
                SearchRequestKey = "key",
                Person           = nullPerson
            };
            SSG_SearchRequest ssgSearchRequest = await _sut.ProcessSearchRequestOrdered(searchRequstOrdered);

            _searchRequestServiceMock.Verify(m => m.CreateSearchRequest(It.IsAny <SearchRequestEntity>(), It.IsAny <CancellationToken>()), Times.Once);
            _searchRequestServiceMock.Verify(m => m.SavePerson(It.IsAny <PersonEntity>(), It.IsAny <CancellationToken>()), Times.Once);
            _searchRequestServiceMock.Verify(m => m.CreateIdentifier(It.IsAny <IdentifierEntity>(), It.IsAny <CancellationToken>()), Times.Never);
            _searchRequestServiceMock.Verify(m => m.CreateAddress(It.IsAny <AddressEntity>(), It.IsAny <CancellationToken>()), Times.Never);
            _searchRequestServiceMock.Verify(m => m.CreatePhoneNumber(It.IsAny <PhoneNumberEntity>(), It.IsAny <CancellationToken>()), Times.Never);
            _searchRequestServiceMock.Verify(m => m.CreateEmployment(It.IsAny <EmploymentEntity>(), It.IsAny <CancellationToken>()), Times.Never);
            _searchRequestServiceMock.Verify(m => m.CreateEmploymentContact(It.IsAny <EmploymentContactEntity>(), It.IsAny <CancellationToken>()), Times.Never);
            _searchRequestServiceMock.Verify(m => m.CreateRelatedPerson(It.IsAny <RelatedPersonEntity>(), It.IsAny <CancellationToken>()), Times.Never);
            _searchRequestServiceMock.Verify(m => m.CreateName(It.IsAny <AliasEntity>(), It.IsAny <CancellationToken>()), Times.Never);
            _searchRequestServiceMock.Verify(m => m.CreateSafetyConcern(It.IsAny <SafetyConcernEntity>(), It.IsAny <CancellationToken>()), Times.Never);
        }
예제 #18
0
        private async Task <SSG_SearchRequest> VerifySearchRequest(SearchRequestOrdered searchRequestOrdered)
        {
            //get existedSearchRequest
            SSG_SearchRequest existedSearchRequest = await _searchRequestService.GetSearchRequest(searchRequestOrdered.SearchRequestKey, _cancellationToken);

            if (existedSearchRequest == null)
            {
                _logger.LogInformation("the updating search request does not exist.");
                return(null);
            }
            if (existedSearchRequest.StatusCode == SEARCH_REQUEST_CANCELLED)
            {
                throw new AgencyRequestException("fileCancelled", new Exception($"File {searchRequestOrdered.SearchRequestKey} is cancelled."));
            }
            if (existedSearchRequest.StatusCode == SEARCH_REQUEST_CLOSED)
            {
                throw new AgencyRequestException("fileClosed", new Exception($"File {searchRequestOrdered.SearchRequestKey} is closed."));
            }
            if (existedSearchRequest.Agency == null || existedSearchRequest.Agency.AgencyCode != searchRequestOrdered?.Person?.Agency?.Code)
            {
                throw new AgencyRequestException("wrongAgency", new Exception($"Wrong Agency Code."));
            }
            return(existedSearchRequest);
        }
예제 #19
0
        public async Task <SSG_SearchRequest> ProcessUpdateSearchRequest(SearchRequestOrdered searchRequestOrdered)
        {
            var cts = new CancellationTokenSource();

            _cancellationToken = cts.Token;
            SSG_SearchRequest existedSearchRequest = await VerifySearchRequest(searchRequestOrdered);

            if (existedSearchRequest == null)
            {
                return(null);
            }
            existedSearchRequest.IsDuplicated = true;
            _uploadedSearchRequest            = existedSearchRequest;

            //get existedPersonSought
            SSG_Person existedSoughtPerson = existedSearchRequest?.SSG_Persons?.FirstOrDefault(
                m => m.IsPrimary == true);

            if (existedSoughtPerson == null)
            {
                string error = "the updating personSought does not exist. something is wrong.";
                _logger.LogError(error);
                throw new Exception(error);
            }
            existedSoughtPerson = await _searchRequestService.GetPerson(existedSoughtPerson.PersonId, _cancellationToken);

            existedSoughtPerson.IsDuplicated = true;
            _uploadedPerson = existedSoughtPerson;


            SearchRequestEntity newSearchRequest = _mapper.Map <SearchRequestEntity>(searchRequestOrdered);

            if (newSearchRequest == null)
            {
                string error = "cannot do updating as newSearchRequest is null";
                _logger.LogError(error);
                throw new Exception(error);
            }

            //update searchRequestEntity
            await UpdateSearchRequest(newSearchRequest);

            //update notesEntity
            if (!String.IsNullOrEmpty(newSearchRequest.Notes) &&
                !String.Equals(existedSearchRequest.Notes, newSearchRequest.Notes, StringComparison.InvariantCultureIgnoreCase))
            {
                await UploadNotes(newSearchRequest, existedSearchRequest);
            }

            //update PersonEntity
            if (searchRequestOrdered.Person == null)
            {
                string error = "the searchRequestOrdered does not contain Person. The request is wrong.";
                _logger.LogError(error);
                throw new Exception(error);
            }
            _personSought = searchRequestOrdered.Person;

            await UpdatePersonSought();
            await UpdateSafetyConcern();

            //update RelatedPerson applicant
            await UpdateRelatedApplicant((string.IsNullOrEmpty(newSearchRequest.ApplicantFirstName) && string.IsNullOrEmpty(newSearchRequest.ApplicantLastName))?null : new RelatedPersonEntity()
            {
                FirstName  = newSearchRequest.ApplicantFirstName,
                LastName   = newSearchRequest.ApplicantLastName,
                StatusCode = 1
            });

            //update identifiers
            //await UpdateIdentifiers();
            await UploadIdentifiers(true);

            //update employment
            await UploadEmployment(true);

            //for phones, addresses, relatedPersons, names are same as creation, as if different, add new one, if same, ignore
            await UploadAddresses(true);
            await UploadPhones(true);
            await UploadRelatedPersons(true);
            await UploadAliases(true);



            return(_uploadedSearchRequest);
        }
        public void Init()
        {
            _validRequestId           = Guid.NewGuid();
            _loggerMock               = new Mock <ILogger <AgencyRequestService> >();
            _searchRequestServiceMock = new Mock <ISearchRequestService>();
            _mapper = new Mock <IMapper>();

            _searchRequestPerson = new Person()
            {
                DateOfBirth   = DateTime.Now,
                FirstName     = "TEST1",
                LastName      = "TEST2",
                CautionFlag   = "cautionFlag",
                CautionReason = "violence",
                Identifiers   = new List <PersonalIdentifier>()
                {
                    new PersonalIdentifier()
                    {
                        Value = "test",
                        Type  = PersonalIdentifierType.BCDriverLicense,
                        Owner = OwnerType.PersonSought
                    },
                    new PersonalIdentifier()
                    {
                        Value = "test2",
                        Type  = PersonalIdentifierType.SocialInsuranceNumber,
                        Owner = OwnerType.PersonSought
                    }
                },
                Addresses = new List <Address>()
                {
                    new Address()
                    {
                        AddressLine1 = "AddressLine1",
                        AddressLine2 = "AddressLine2",
                        City         = "testCity",
                        Owner        = OwnerType.PersonSought
                    }
                },
                Phones = new List <Phone>()
                {
                    new Phone()
                    {
                        PhoneNumber = "4005678900"
                    }
                },
                Names = new List <Name>()
                {
                    new Name()
                    {
                        FirstName   = "firstName",
                        Owner       = OwnerType.PersonSought,
                        Identifiers = new List <PersonalIdentifier> {
                            new PersonalIdentifier {
                                Value = "123222", Type = PersonalIdentifierType.BCDriverLicense
                            }
                        },
                        Addresses = new List <Address> {
                            new Address {
                                AddressLine1 = "line1"
                            }
                        },
                        Phones = new List <Phone>
                        {
                            new Phone {
                                PhoneNumber = "12343"
                            }
                        }
                    },
                    new Name()
                    {
                        FirstName = "applicantFirstName",
                        Owner     = OwnerType.Applicant
                    }
                },
                RelatedPersons = new List <RelatedPerson>()
                {
                    new RelatedPerson()
                    {
                        FirstName = "firstName"
                    }
                },

                Employments = new List <Employment>()
                {
                    new Employment()
                    {
                        Occupation = "Occupation",
                        Employer   = new Employer()
                        {
                            Phones = new List <Phone>()
                            {
                                new Phone()
                                {
                                    PhoneNumber = "1111111", Type = "Phone"
                                }
                            }
                        }
                    }
                },
                Agency = new Agency {
                    Code = "FMEP"
                }
            };

            _searchRequstOrdered = new SearchRequestOrdered()
            {
                Action           = RequestAction.NEW,
                RequestId        = "1111111",
                SearchRequestId  = Guid.NewGuid(),
                TimeStamp        = new DateTime(2010, 1, 1),
                SearchRequestKey = "key",
                Person           = _searchRequestPerson
            };


            _fakePersoneIdentifier = new IdentifierEntity
            {
                Identification = "1234567",
                SearchRequest  = new SSG_SearchRequest
                {
                    SearchRequestId = _validRequestId
                }
            };
            _fakePersonAddress = new AddressEntity
            {
                SearchRequest = new SSG_SearchRequest
                {
                    SearchRequestId = _validRequestId
                },
                AddressLine1 = "addressLine1"
            };
            _fakeEmployment = new EmploymentEntity
            {
                SearchRequest = new SSG_SearchRequest
                {
                    SearchRequestId = _validRequestId
                }
            };

            _fakeEmploymentContact = new EmploymentContactEntity
            {
                PhoneNumber = "11111111"
            };

            _fakePersonPhoneNumber = new PhoneNumberEntity
            {
                SearchRequest = new SSG_SearchRequest
                {
                    SearchRequestId = _validRequestId
                }
            };

            _fakeRelatedPerson = new RelatedPersonEntity
            {
                SearchRequest = new SSG_SearchRequest
                {
                    SearchRequestId = _validRequestId
                }
            };

            _fakeName = new AliasEntity
            {
                SearchRequest = new SSG_SearchRequest
                {
                    SearchRequestId = _validRequestId
                }
            };

            _fakeSearchRequest = new SearchRequestEntity()
            {
                AgencyCode              = "FMEP",
                RequestPriority         = RequestPriorityType.Rush.Value,
                ApplicantAddressLine1   = "new Address line 1",
                ApplicantAddressLine2   = "",
                PersonSoughtDateOfBirth = new DateTime(1998, 1, 1),
                LocationRequested       = true,
                PHNRequested            = true,
                DateOfDeathRequested    = false
            };

            _fakeSafety = new SafetyConcernEntity {
                Detail = "safety"
            };

            _ssg_fakePerson = new PersonEntity
            {
            };

            _mapper.Setup(m => m.Map <IdentifierEntity>(It.IsAny <PersonalIdentifier>()))
            .Returns(_fakePersoneIdentifier);

            _mapper.Setup(m => m.Map <PhoneNumberEntity>(It.IsAny <Phone>()))
            .Returns(_fakePersonPhoneNumber);

            _mapper.Setup(m => m.Map <AddressEntity>(It.IsAny <Address>()))
            .Returns(_fakePersonAddress);

            _mapper.Setup(m => m.Map <AliasEntity>(It.IsAny <Name>()))
            .Returns(_fakeName);

            _mapper.Setup(m => m.Map <PersonEntity>(It.IsAny <Person>()))
            .Returns(_ssg_fakePerson);

            _mapper.Setup(m => m.Map <EmploymentEntity>(It.IsAny <Employment>()))
            .Returns(_fakeEmployment);

            _mapper.Setup(m => m.Map <EmploymentContactEntity>(It.IsAny <Phone>()))
            .Returns(_fakeEmploymentContact);

            _mapper.Setup(m => m.Map <RelatedPersonEntity>(It.IsAny <RelatedPerson>()))
            .Returns(_fakeRelatedPerson);

            _mapper.Setup(m => m.Map <SearchRequestEntity>(It.IsAny <SearchRequestOrdered>()))
            .Returns(_fakeSearchRequest);

            _mapper.Setup(m => m.Map <SafetyConcernEntity>(It.IsAny <Person>()))
            .Returns(_fakeSafety);

            _searchRequestServiceMock.Setup(x => x.CreateSearchRequest(It.Is <SearchRequestEntity>(x => x.AgencyCode == "FMEP"), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <SSG_SearchRequest>(new SSG_SearchRequest()
            {
                SearchRequestId = _validRequestId,
                AgencyCode      = "SUCCEED"
            }));

            _searchRequestServiceMock.Setup(x => x.CreateIdentifier(It.IsAny <IdentifierEntity>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <SSG_Identifier>(new SSG_Identifier()
            {
            }));

            _searchRequestServiceMock.Setup(x => x.CreateAddress(It.Is <AddressEntity>(x => x.SearchRequest.SearchRequestId == _validRequestId), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <SSG_Address>(new SSG_Address()
            {
                AddressLine1 = "test full line"
            }));

            _searchRequestServiceMock.Setup(x => x.CreatePhoneNumber(It.Is <PhoneNumberEntity>(x => x.SearchRequest.SearchRequestId == _validRequestId), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <SSG_PhoneNumber>(new SSG_PhoneNumber()
            {
                TelePhoneNumber = "4007678231"
            }));

            _searchRequestServiceMock.Setup(x => x.CreateName(It.Is <AliasEntity>(x => x.SearchRequest.SearchRequestId == _validRequestId), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <SSG_Aliase>(new SSG_Aliase()
            {
                FirstName = "firstName"
            }));

            _searchRequestServiceMock.Setup(x => x.SavePerson(It.Is <PersonEntity>(x => x.SearchRequest.SearchRequestId == _validRequestId), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <SSG_Person>(new SSG_Person()
            {
                FirstName = "First"
            }));

            _searchRequestServiceMock.Setup(x => x.CreateEmployment(It.Is <EmploymentEntity>(x => x.SearchRequest.SearchRequestId == _validRequestId), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <SSG_Employment>(new SSG_Employment()
            {
                EmploymentId = Guid.NewGuid(),
                Occupation   = "Occupation"
            }));

            _searchRequestServiceMock.Setup(x => x.CreateEmploymentContact(It.IsAny <EmploymentContactEntity>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <SSG_EmploymentContact>(new SSG_EmploymentContact()
            {
                PhoneNumber = "4007678231"
            }));

            _searchRequestServiceMock.Setup(x => x.CreateRelatedPerson(It.Is <RelatedPersonEntity>(x => x.SearchRequest.SearchRequestId == _validRequestId), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <SSG_Identity>(new SSG_Identity()
            {
                FirstName = "firstName"
            }));

            _searchRequestServiceMock.Setup(x => x.SubmitToQueue(It.IsAny <Guid>()))
            .Returns(Task.FromResult <bool>(true));
            _sut = new AgencyRequestService(_searchRequestServiceMock.Object, _loggerMock.Object, _mapper.Object);
        }
예제 #21
0
        private SearchRequestSaved BuildSearchRequestSaved_Update(SSG_SearchRequest ssgSearchRequest, SearchRequestOrdered requestOrdered)
        {
            SearchRequestSaved saved =
                new SearchRequestSaved()
            {
                Action              = requestOrdered.Action,
                RequestId           = requestOrdered.RequestId,
                SearchRequestKey    = requestOrdered.SearchRequestKey,
                SearchRequestId     = ssgSearchRequest == null ? Guid.Empty : ssgSearchRequest.SearchRequestId,
                TimeStamp           = DateTime.Now,
                EstimatedCompletion = ssgSearchRequest?.EstimatedCompletionDate,
                QueuePosition       = ssgSearchRequest?.QueuePosition,
                ProviderProfile     = new ProviderProfile()
                {
                    Name = requestOrdered?.Person?.Agency?.Code
                }
            };

            if (ssgSearchRequest != null)
            {
                saved.Message = $"The Search Request {requestOrdered.SearchRequestKey} has been updated successfully upon the request {requestOrdered.RequestId}.";
            }

            return(saved);
        }
예제 #22
0
        public void normal_SearchRequestOrdered_should_map_to_SearchRequestEntity_correctly()
        {
            SearchRequestOrdered searchRequestOrdered = new SearchRequestOrdered()
            {
                Action           = RequestAction.NEW,
                RequestId        = "requestId",
                SearchRequestKey = "requestKey",
                SearchRequestId  = Guid.NewGuid(),
                TimeStamp        = new DateTime(2001, 1, 1),
                Person           = new Person()
                {
                    Agency = new Agency()
                    {
                        Agent = new Name()
                        {
                            FirstName = "agentFirstName", LastName = "agentLastName", Owner = OwnerType.NotApplicable
                        },
                        AgentContact = new List <Phone> {
                            new Phone()
                            {
                                PhoneNumber = "agentPhoneNumber", Extension = "agentExt", Type = "Phone"
                            },
                            new Phone()
                            {
                                PhoneNumber = "agentFaxNumber", Type = "Fax"
                            }
                        },
                        Notes                = "agency notes",
                        RequestPriority      = RequestPriority.Rush,
                        Code                 = "FMEP",
                        RequestId            = "QFP-12422509096920180928083433",
                        ReasonCode           = SearchReasonCode.EnfPayAgr,
                        RequestDate          = new DateTimeOffset(2018, 9, 28, 0, 0, 0, new TimeSpan(1, 0, 0)),
                        Email                = "*****@*****.**",
                        InformationRequested = new List <InformationRequested> {
                            InformationRequested.Location, InformationRequested.PHN, InformationRequested.DL
                        },
                        LocationCode = "v"
                    },
                    FirstName   = "personSoughtFirstName",
                    LastName    = "personSoughtLastName",
                    MiddleName  = "middleName",
                    OtherName   = "otherName",
                    Gender      = "M",
                    DateOfBirth = new DateTimeOffset(1995, 1, 1, 0, 0, 0, new TimeSpan(1, 0, 0)),
                    CautionFlag = "flag",
                    Identifiers = new List <PersonalIdentifier>()
                    {
                        new PersonalIdentifier()
                        {
                            Value = "123456", TypeCode = "SIN", Type = PersonalIdentifierType.SocialInsuranceNumber, Owner = OwnerType.PersonSought
                        },
                        new PersonalIdentifier()
                        {
                            Value = "113456", TypeCode = "BCID", Type = PersonalIdentifierType.BCID, Owner = OwnerType.PersonSought
                        },
                        new PersonalIdentifier()
                        {
                            Value = "12222456", TypeCode = "BCDL", Type = PersonalIdentifierType.BCDriverLicense, Owner = OwnerType.PersonSought
                        },
                        new PersonalIdentifier()
                        {
                            Value = "33333456", TypeCode = "SIN", Type = PersonalIdentifierType.SocialInsuranceNumber, Owner = OwnerType.Applicant
                        },
                        new PersonalIdentifier()
                        {
                            Value = "4444456", TypeCode = "BCDL", Type = PersonalIdentifierType.BCDriverLicense, Owner = OwnerType.InvolvedPerson
                        }
                    },
                    HairColour = "hairColor",
                    EyeColour  = "eyeColor",
                    Names      = new List <Name>()
                    {
                        new Name()
                        {
                            FirstName = "applicantFirstName", LastName = "applicantLastName", Owner = OwnerType.Applicant
                        }
                    },
                    Addresses = new List <Address>()
                    {
                        new Address()
                        {
                            AddressLine1  = "applicantAddressLine1",
                            AddressLine2  = "applicantAddressLine2",
                            City          = "applicantCity",
                            StateProvince = "applicantProvince",
                            ZipPostalCode = "applicantPostalCode",
                            Owner         = OwnerType.Applicant
                        },
                        new Address()
                        {
                            AddressLine1  = "involvedPersonAddressLine1",
                            AddressLine2  = "involvedPersonAddressLine2",
                            City          = "involvedPersonCity",
                            StateProvince = "involvedPersonProvince",
                            ZipPostalCode = "involvedPersonPostalCode",
                            Owner         = OwnerType.InvolvedPerson
                        },
                    },
                    Phones = new List <Phone>()
                    {
                        new Phone()
                        {
                            PhoneNumber = "11111111",
                            Owner       = OwnerType.Applicant
                        }
                    }
                },
            };
            SearchRequestEntity entity = _mapper.Map <SearchRequestEntity>(searchRequestOrdered);

            Assert.AreEqual("agentFirstName", entity.AgentFirstName);
            Assert.AreEqual("agentLastName", entity.AgentLastName);
            Assert.AreEqual("agentPhoneNumber", entity.AgentPhoneNumber);
            Assert.AreEqual("agentExt", entity.AgentPhoneExtension);
            Assert.AreEqual("v", entity.AgencyOfficeLocationText);
            Assert.AreEqual("agentFaxNumber", entity.AgentFax);
            Assert.AreEqual("agency notes", entity.Notes);
            Assert.AreEqual("QFP-12422509096920180928083433", entity.OriginalRequestorReference);
            Assert.AreEqual("124225", entity.PayerId);
            Assert.AreEqual("090969", entity.CaseTrackingId);
            Assert.AreEqual(new DateTime(2018, 9, 28), entity.RequestDate);
            Assert.AreEqual("*****@*****.**", entity.AgentEmail);
            Assert.AreEqual(true, entity.LocationRequested);
            Assert.AreEqual(true, entity.PhoneNumberRequested);
            Assert.AreEqual(true, entity.PHNRequested);
            Assert.AreEqual(true, entity.DriverLicenseRequested);
            Assert.AreEqual("FMEP", entity.AgencyCode);
            Assert.AreEqual("EnfPayAgr", entity.SearchReasonCode);
            Assert.AreEqual(RequestPriorityType.Rush.Value, entity.RequestPriority);
            Assert.AreEqual(PersonSoughtType.P.Value, entity.PersonSoughtRole);
            Assert.AreEqual("personSoughtFirstName", entity.PersonSoughtFirstName);
            Assert.AreEqual("personSoughtLastName", entity.PersonSoughtLastName);
            Assert.AreEqual("middleName", entity.PersonSoughtMiddleName);
            Assert.AreEqual("otherName", entity.PersonSoughtThirdGiveName);
            Assert.AreEqual(GenderType.Male.Value, entity.PersonSoughtGender);
            Assert.AreEqual(new DateTime(1995, 1, 1), entity.PersonSoughtDateOfBirth);
            Assert.AreEqual("12222456", entity.PersonSoughtBCDL);
            Assert.AreEqual("113456", entity.PersonSoughtBCID);
            Assert.AreEqual("eyeColor", entity.PersonSoughtEyeColor);
            Assert.AreEqual("hairColor", entity.PersonSoughtHairColor);
            Assert.AreEqual("123456", entity.PersonSoughtSIN);

            Assert.AreEqual("applicantAddressLine1", entity.ApplicantAddressLine1);
            Assert.AreEqual("applicantAddressLine2", entity.ApplicantAddressLine2);
            Assert.AreEqual("applicantCity", entity.ApplicantCity);
            Assert.AreEqual("canada", entity.ApplicantCountry);
            Assert.AreEqual("applicantFirstName", entity.ApplicantFirstName);
            Assert.AreEqual("applicantLastName", entity.ApplicantLastName);
            Assert.AreEqual("11111111", entity.ApplicantPhoneNumber);
            Assert.AreEqual("applicantPostalCode", entity.ApplicantPostalCode);
            Assert.AreEqual("applicantProvince", entity.ApplicantProvince);
            Assert.AreEqual("33333456", entity.ApplicantSIN);
        }
예제 #23
0
        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;
                }
            }
        }
예제 #24
0
        public async Task <IActionResult> CreateSearchRequest(string requestId, [FromBody] SearchRequestOrdered searchRequestOrdered)
        {
            using (LogContext.PushProperty("RequestRef", $"{requestId}"))
                using (LogContext.PushProperty("AgencyCode", $"{searchRequestOrdered?.Person?.Agency?.Code}"))
                {
                    _logger.LogInformation("Get CreateSearchRequest");
                    _logger.LogDebug(JsonConvert.SerializeObject(searchRequestOrdered));
                    if (string.IsNullOrEmpty(requestId))
                    {
                        return(BadRequest(new { ReasonCode = "error", Message = "requestId cannot be empty." }));
                    }
                    if (searchRequestOrdered == null)
                    {
                        return(BadRequest(new { ReasonCode = "error", Message = "SearchRequestOrdered cannot be empty." }));
                    }
                    if (searchRequestOrdered.Action != RequestAction.NEW)
                    {
                        return(BadRequest(new { ReasonCode = "error", Message = "CreateSearchRequest should only get NEW request." }));
                    }

                    SSG_SearchRequest createdSearchRequest = null;
                    try
                    {
                        createdSearchRequest = await _agencyRequestService.ProcessSearchRequestOrdered(searchRequestOrdered);

                        if (createdSearchRequest == null)
                        {
                            return(StatusCode(StatusCodes.Status500InternalServerError));
                        }

                        _logger.LogInformation("SearchRequest is created successfully.");
                    }
                    catch (AgencyRequestException ex)
                    {
                        _logger.LogInformation(ex.Message);
                        return(StatusCode(StatusCodes.Status500InternalServerError, new { ReasonCode = ex.Message, Message = ex.InnerException?.Message }));
                    }
                    catch (Exception ex)
                    {
                        SSG_SearchRequest createdSR = _agencyRequestService.GetSSGSearchRequest();
                        if (createdSR != null)
                        {
                            await _agencyRequestService.SystemCancelSSGSearchRequest(createdSR);
                        }
                        if (ex is Simple.OData.Client.WebRequestException)
                        {
                            _logger.LogError(((Simple.OData.Client.WebRequestException)ex).RequestUri?.AbsoluteUri);
                            _logger.LogError(((Simple.OData.Client.WebRequestException)ex).Response);
                        }
                        _logger.LogError(ex.Message);
                        return(StatusCode(StatusCodes.Status500InternalServerError, new { ReasonCode = ex.Message, Message = ex.InnerException?.Message }));
                    }

                    //try to submit to queue and then get EstimatedDate and positionInQueue
                    try
                    {
                        await _agencyRequestService.SubmitSearchRequestToQueue(createdSearchRequest.SearchRequestId);

                        createdSearchRequest = await _agencyRequestService.RefreshSearchRequest(createdSearchRequest.SearchRequestId);
                    }catch (Exception e)
                    {
                        _logger.LogError(e, "submit to queue or get current search request failed.");
                        //default value, in case there is error, we still can return accept event.
                        createdSearchRequest.EstimatedCompletionDate = DateTime.UtcNow.AddMonths(3);
                        createdSearchRequest.QueuePosition           = 90;
                    }
                    return(Ok(BuildSearchRequestSaved_Create(createdSearchRequest, searchRequestOrdered)));
                }
        }
예제 #25
0
        public async Task <IActionResult> UpdateSearchRequest(string requestId, [FromBody] SearchRequestOrdered searchRequestOrdered)
        {
            using (LogContext.PushProperty("RequestRef", $"{requestId}"))
                using (LogContext.PushProperty("AgencyCode", $"{searchRequestOrdered?.Person?.Agency?.Code}"))
                    using (LogContext.PushProperty("SearchRequestKey", $"{searchRequestOrdered?.SearchRequestKey}"))
                    {
                        _logger.LogInformation("Get UpdateSearchRequest");
                        if (string.IsNullOrEmpty(requestId))
                        {
                            return(BadRequest(new { ReasonCode = "error", Message = "requestId cannot be empty." }));
                        }

                        if (searchRequestOrdered == null)
                        {
                            return(BadRequest(new { ReasonCode = "error", Message = "SearchRequestOrdered cannot be empty." }));
                        }

                        if (searchRequestOrdered.Action != RequestAction.UPDATE)
                        {
                            return(BadRequest(new { ReasonCode = "error", Message = "UpdateSearchRequest should only get Update request." }));
                        }

                        if (String.IsNullOrEmpty(searchRequestOrdered.SearchRequestKey))
                        {
                            return(BadRequest(new { ReasonCode = "error", Message = "FileId cannot be empty for updating request." }));
                        }

                        SSG_SearchRequest updatedSearchRequest = null;
                        try
                        {
                            updatedSearchRequest = await _agencyRequestService.ProcessUpdateSearchRequest(searchRequestOrdered);

                            if (updatedSearchRequest == null)
                            {
                                return(StatusCode(StatusCodes.Status500InternalServerError, new { ReasonCode = "error", Message = "error" }));
                            }
                        }
                        catch (AgencyRequestException ex)
                        {
                            _logger.LogInformation(ex.Message);
                            return(BadRequest(new { ReasonCode = ex.Message, Message = $"FileId ( {searchRequestOrdered.SearchRequestKey} ) is invalid. {ex.Message}" }));
                        }
                        catch (Exception ex)
                        {
                            if (ex is Simple.OData.Client.WebRequestException)
                            {
                                _logger.LogError(((Simple.OData.Client.WebRequestException)ex).Response);
                            }
                            _logger.LogError(ex.Message);
                            return(StatusCode(StatusCodes.Status500InternalServerError, new { ReasonCode = "error", Message = ex.Message }));
                        }
                        _logger.LogInformation("UpdateSearchRequest successfully");

                        //try to get EstimatedDate and positionInQueue
                        try
                        {
                            updatedSearchRequest = await _agencyRequestService.RefreshSearchRequest(updatedSearchRequest.SearchRequestId);
                        }
                        catch (Exception e)
                        {
                            _logger.LogError(e, "get current search request failed.");
                            //default value, in case there is error, we still can return accept event.
                            updatedSearchRequest.EstimatedCompletionDate = DateTime.UtcNow.AddMonths(3);
                            updatedSearchRequest.QueuePosition           = 90;
                        }
                        return(Ok(BuildSearchRequestSaved_Update(updatedSearchRequest, searchRequestOrdered)));
                    }
        }
예제 #26
0
        private SearchRequestSaved BuildSearchRequestSaved_Cancel(SSG_SearchRequest ssgSearchRequest, SearchRequestOrdered requestOrdered)
        {
            SearchRequestSaved saved =
                new SearchRequestSaved()
            {
                Action           = requestOrdered.Action,
                RequestId        = requestOrdered.RequestId,
                SearchRequestKey = requestOrdered.SearchRequestKey,
                SearchRequestId  = ssgSearchRequest == null ? Guid.Empty : ssgSearchRequest.SearchRequestId,
                TimeStamp        = DateTime.Now,
                ProviderProfile  = new ProviderProfile()
                {
                    Name = requestOrdered?.Person?.Agency?.Code
                },
                Message = $"The Search Request {requestOrdered.SearchRequestKey} has been cancelled successfully upon the request {requestOrdered.RequestId}."
            };

            return(saved);
        }
예제 #27
0
        public static SearchRequestEntity ConstructSearchRequestEntity(SearchRequestOrdered src)
        {
            if (src?.Person?.Agency?.RequestId == null)
            {
                throw new ArgumentNullException("SearchRequestOrdered.Person, Agency or RequestID are not allowed Null.");
            }
            SearchRequestEntity entity = new SearchRequestEntity();

            #region agency part
            entity.AgentEmail = src.Person.Agency.Email;
            if (src.Person.Agency.AgentContact != null)
            {
                Phone agencyPhone = src.Person.Agency.AgentContact.FirstOrDefault <Phone>(m => String.Equals(m.Type, "Phone", StringComparison.InvariantCultureIgnoreCase));
                entity.AgentPhoneNumber    = agencyPhone?.PhoneNumber;
                entity.AgentPhoneExtension = agencyPhone?.Extension;
                Phone agencyFax = src.Person.Agency.AgentContact.FirstOrDefault <Phone>(m => String.Equals(m.Type, "Fax", StringComparison.InvariantCultureIgnoreCase));
                if (string.IsNullOrEmpty(agencyFax?.Extension))
                {
                    entity.AgentFax = agencyFax?.PhoneNumber;
                }
                else
                {
                    entity.AgentFax = agencyFax?.PhoneNumber + " -" + agencyFax?.Extension;
                }
            }
            if (src.Person.Agency.Agent != null)
            {
                Name agentName = src.Person.Agency.Agent;
                entity.AgentFirstName = agentName.FirstName;
                entity.AgentLastName  = agentName.LastName;
            }
            if (src.Person.Agency.InformationRequested != null)
            {
                foreach (InformationRequested info in src.Person.Agency.InformationRequested)
                {
                    //todo: need to confirm with agency about the string
                    switch (info)
                    {
                    case InformationRequested.Location:
                    {
                        entity.LocationRequested    = true;
                        entity.PhoneNumberRequested = true;
                        //todo: set requested Email to be true
                        break;
                    }

                    case InformationRequested.Employment: entity.EmploymentRequested = true; break;

                    case InformationRequested.Asset: entity.AssetRequested = true; break;

                    case InformationRequested.SIN: entity.SINRequested = true; break;

                    case InformationRequested.DL: entity.DriverLicenseRequested = true; break;

                    case InformationRequested.PHN: entity.PHNRequested = true; break;

                    case InformationRequested.Phone: entity.PhoneNumberRequested = true; break;

                    case InformationRequested.Carceration: entity.CarcerationStatusRequested = true; break;

                    case InformationRequested.DateOfDeath: entity.DateOfDeathRequested = true; break;

                    case InformationRequested.IA: entity.IAStatusRequested = true; break;

                    case InformationRequested.SafetyConcern: entity.SafetyConcernRequested = true; break;
                    }
                    ;
                }
            }
            if (src.Person?.Agency.RequestId != null)
            {
                if (src.Person.Agency.RequestId.Length >= 30)
                {
                    string[] ids = src.Person.Agency.RequestId.Split('-');
                    if (ids.Length == 2)
                    {
                        entity.PayerId        = ids[1].Substring(0, 6);
                        entity.CaseTrackingId = ids[1].Substring(6, 6);
                        string role = ids[0].Substring(2, 1);
                        if (string.Equals(role, "P", StringComparison.InvariantCultureIgnoreCase))
                        {
                            entity.PersonSoughtRole = PersonSoughtType.P.Value;
                        }
                        if (string.Equals(role, "R", StringComparison.InvariantCultureIgnoreCase))
                        {
                            entity.PersonSoughtRole = PersonSoughtType.R.Value;
                        }
                    }
                }
            }
            #endregion


            if (src.Person.Addresses != null)
            {
                Address applicantAddress = src.Person.Addresses.FirstOrDefault <Address>(m => m.Owner == OwnerType.Applicant);
                entity.ApplicantAddressLine1 = applicantAddress?.AddressLine1;
                entity.ApplicantAddressLine2 = applicantAddress?.AddressLine2;
                entity.ApplicantCity         = applicantAddress?.City;
                entity.ApplicantPostalCode   = applicantAddress?.ZipPostalCode;
                entity.ApplicantProvince     = applicantAddress?.StateProvince;
                entity.ApplicantCountry      = "canada";
            }

            if (src.Person.Names != null)
            {
                Name applicantName = src.Person.Names.FirstOrDefault <Name>(m => m.Owner == OwnerType.Applicant);
                entity.ApplicantFirstName = applicantName.FirstName;
                entity.ApplicantLastName  = applicantName.LastName;
            }

            if (src.Person.Phones != null)
            {
                entity.ApplicantPhoneNumber = src.Person.Phones.FirstOrDefault <Phone>(m => m.Owner == OwnerType.Applicant)?.PhoneNumber;
            }
            if (src.Person.Identifiers != null)
            {
                entity.ApplicantSIN = src.Person.Identifiers.FirstOrDefault <PersonalIdentifier>(
                    m => m.Owner == OwnerType.Applicant && m.Type == PersonalIdentifierType.SocialInsuranceNumber)?.Value;
                entity.PersonSoughtSIN = src.Person.Identifiers.FirstOrDefault <PersonalIdentifier>(
                    m => m.Owner == OwnerType.PersonSought && m.Type == PersonalIdentifierType.SocialInsuranceNumber)?.Value;
                entity.PersonSoughtBCDL = src.Person.Identifiers.FirstOrDefault <PersonalIdentifier>(
                    m => m.Owner == OwnerType.PersonSought && m.Type == PersonalIdentifierType.BCDriverLicense)?.Value;
                entity.PersonSoughtBCID = src.Person.Identifiers.FirstOrDefault <PersonalIdentifier>(
                    m => m.Owner == OwnerType.PersonSought && m.Type == PersonalIdentifierType.BCID)?.Value;
            }

            return(entity);
        }
예제 #28
0
        private SearchRequestSaved BuildSearchRequestSaved_Create(SSG_SearchRequest ssgSearchRequest, SearchRequestOrdered requestOrdered)
        {
            SearchRequestSaved saved =
                new SearchRequestSaved()
            {
                Action              = requestOrdered.Action,
                RequestId           = requestOrdered.RequestId,
                SearchRequestKey    = ssgSearchRequest.FileId,
                SearchRequestId     = ssgSearchRequest.SearchRequestId,
                TimeStamp           = DateTime.Now,
                EstimatedCompletion = ssgSearchRequest?.EstimatedCompletionDate,
                QueuePosition       = ssgSearchRequest?.QueuePosition,
                Message             = $"The new Search Request reference: {requestOrdered.RequestId} has been submitted successfully.",
                ProviderProfile     = new ProviderProfile()
                {
                    Name = requestOrdered?.Person?.Agency?.Code
                }
            };

            return(saved);
        }