public IActionResult AddEmployer(string employerIdentifier, string returnUrl) { //Check the parameters are populated if (string.IsNullOrWhiteSpace(employerIdentifier)) { return(new HttpBadRequestResult($"Missing {nameof(employerIdentifier)}")); } if (string.IsNullOrWhiteSpace(returnUrl)) { return(new HttpBadRequestResult($"Missing {nameof(returnUrl)}")); } //Get the employer from the encrypted identifier EmployerSearchModel employer = GetEmployer(employerIdentifier); //Add the employer to the compare list CompareViewService.AddToBasket(employer.OrganisationIdEncrypted); //Save the compared employers to the cookie CompareViewService.SaveComparedEmployersToCookie(Request); //Redirect the user to the original page return(LocalRedirect(returnUrl)); }
private EmployerSearchModel GetEmployer(string employerIdentifier, bool activeOnly = true) { EmployerSearchModel employer = SearchViewService.LastSearchResults?.GetEmployer(employerIdentifier); if (employer == null) { //Get the employer from the database CustomResult <Organisation> organisationResult = activeOnly ? OrganisationBusinessLogic.LoadInfoFromActiveEmployerIdentifier(employerIdentifier) : OrganisationBusinessLogic.LoadInfoFromEmployerIdentifier(employerIdentifier); if (organisationResult.Failed) { throw organisationResult.ErrorMessage.ToHttpException(); } if (organisationResult.Result.OrganisationId == 0) { throw new HttpException(HttpStatusCode.NotFound, "Employer not found"); } employer = organisationResult.Result.ToEmployerSearchResult(); } return(employer); }
private void PurgeOrganisation(Organisation org) { EmployerSearchModel searchRecord = org.ToEmployerSearchResult(true); auditLogger.AuditChangeToOrganisation( AuditedAction.PurgeOrganisation, org, new { org.OrganisationId, Address = org.GetLatestAddress()?.GetAddressString(), org.EmployerReference, org.CompanyNumber, org.OrganisationName, org.SectorType, org.Status, SicCodes = org.GetSicSectionIdsString(), SicSource = org.GetSicSource(), org.DateOfCessation }); // Un-register all users for this Organisation org.UserOrganisations.ForEach(uo => dataRepository.Delete(uo)); // Soft-Delete the Organisation org.SetStatus(OrganisationStatuses.Deleted, details: "Organisation deleted by PurgeOrganisationJob"); dataRepository.SaveChanges(); }
public async Task Functions_UpdateSearch_AddAllIndexes() { //ARRANGE //Ensure all orgs are in scope for current year IEnumerable <Organisation> orgs = _functions.SharedBusinessLogic.DataRepository.GetAll <Organisation>(); //Add a random number of in scope orgs var inScope = Numeric.Rand(1, orgs.Count()); OrganisationHelper.AddScopeStatus(ScopeStatuses.InScope, VirtualDateTime.Now.Year, orgs.Take(inScope).ToArray()); //Add returns to remaining orgs ReturnHelper.CreateTestReturns(orgs.Skip(inScope).ToArray(), VirtualDateTime.Now.Year); var log = new Mock <ILogger>(); orgs = orgs .Where( o => o.Status == OrganisationStatuses.Active && (o.Returns.Any(r => r.Status == ReturnStatuses.Submitted) || o.OrganisationScopes.Any( sc => sc.Status == ScopeRowStatuses.Active && (sc.ScopeStatus == ScopeStatuses.InScope || sc.ScopeStatus == ScopeStatuses.PresumedInScope)))) .ToList(); //ACT await _functions.UpdateSearchAsync(log.Object, "*****@*****.**", true); //ASSERT //Check for correct number of indexes var documentCount = await _functions.SearchBusinessLogic.EmployerSearchRepository.GetDocumentCountAsync(); Assert.That(documentCount == orgs.Count(), $"Expected '{documentCount}' indexes "); //Get the actual results var actualResults = await _functions.SearchBusinessLogic.EmployerSearchRepository.ListAsync(); //Generate the expected results var expectedResults = orgs.Select(o => EmployerSearchModel.Create(o)); //Check the results expectedResults.Compare(actualResults); }
public IActionResult AddEmployerJs(string employerIdentifier, string returnUrl) { //Check the parameters are populated if (string.IsNullOrWhiteSpace(employerIdentifier)) { return(new HttpBadRequestResult($"Missing {nameof(employerIdentifier)}")); } if (string.IsNullOrWhiteSpace(returnUrl)) { return(new HttpBadRequestResult($"Missing {nameof(returnUrl)}")); } //Get the employer from the encrypted identifier EmployerSearchModel employer = GetEmployer(employerIdentifier); //Add the employer to the compare list CompareViewService.AddToBasket(employer.OrganisationIdEncrypted); //Save the compared employers to the cookie CompareViewService.SaveComparedEmployersToCookie(Request); //Setup compare basket bool fromSearchResults = returnUrl.Contains("/search-results"); bool fromEmployer = returnUrl.StartsWithI("/employer"); ViewBag.BasketViewModel = new CompareBasketViewModel { CanAddEmployers = false, CanClearCompare = true, CanViewCompare = fromSearchResults && CompareViewService.BasketItemCount > 1 || fromEmployer && CompareViewService.BasketItemCount > 0, IsSearchPage = fromSearchResults, IsEmployerPage = fromEmployer }; ViewBag.ReturnUrl = returnUrl; var model = new AddRemoveButtonViewModel { OrganisationIdEncrypted = employer.OrganisationIdEncrypted, OrganisationName = employer.Name }; return(PartialView("Basket_Button", model)); }
public EmployerSearchModel ToEmployerSearchResult(bool keyOnly = false, List <SicCodeSearchModel> listOfSicCodeSearchModels = null) { if (keyOnly) { return(new EmployerSearchModel { OrganisationId = OrganisationId.ToString() }); } // Get the last two names for the org. Most recent name first string[] names = OrganisationNames.Select(n => n.Name).Reverse().Take(2).ToArray(); var abbreviations = new SortedSet <string>(StringComparer.OrdinalIgnoreCase); names.ForEach(n => abbreviations.Add(n.ToAbbr())); names.ForEach(n => abbreviations.Add(n.ToAbbr("."))); var excludes = new[] { "Ltd", "Limited", "PLC", "Corporation", "Incorporated", "LLP", "The", "And", "&", "For", "Of", "To" }; names.ForEach(n => abbreviations.Add(n.ToAbbr(excludeWords: excludes))); names.ForEach(n => abbreviations.Add(n.ToAbbr(".", excludeWords: excludes))); abbreviations.RemoveWhere(a => string.IsNullOrWhiteSpace(a)); abbreviations.Remove(OrganisationName); // extract the prev org name (if exists) var prevOrganisationName = ""; if (names.Length > 1) { prevOrganisationName = names[names.Length - 1]; abbreviations.Remove(prevOrganisationName); } //Get the latest sic codes IEnumerable <OrganisationSicCode> sicCodes = GetSicCodes(); Return[] submittedReports = GetSubmittedReports().ToArray(); var result = new EmployerSearchModel { OrganisationId = OrganisationId.ToString(), OrganisationIdEncrypted = GetEncryptedId(), Name = OrganisationName, PreviousName = prevOrganisationName, PartialNameForSuffixSearches = OrganisationName, PartialNameForCompleteTokenSearches = OrganisationName, Abbreviations = abbreviations.ToArray(), Size = GetLatestReturn() == null ? 0 : (int)GetLatestReturn().OrganisationSize, SicSectionIds = sicCodes.Select(sic => sic.SicCode.SicSectionId.ToString()).Distinct().ToArray(), SicSectionNames = sicCodes.Select(sic => sic.SicCode.SicSection.Description).Distinct().ToArray(), SicCodeIds = sicCodes.Select(sicCode => sicCode.SicCodeId.ToString()).Distinct().ToArray(), Address = GetLatestAddress()?.GetAddressString(), LatestReportedDate = submittedReports.Select(x => x.Created).FirstOrDefault(), ReportedYears = submittedReports.Select(x => x.AccountingDate.Year.ToString()).ToArray(), ReportedLateYears = submittedReports.Where(x => x.IsLateSubmission).Select(x => x.AccountingDate.Year.ToString()).ToArray(), ReportedExplanationYears = submittedReports.Where(x => string.IsNullOrEmpty(x.CompanyLinkToGPGInfo) == false) .Select(x => x.AccountingDate.Year.ToString()) .ToArray() }; if (listOfSicCodeSearchModels != null) { result.SicCodeListOfSynonyms = GetListOfSynonyms(result.SicCodeIds, listOfSicCodeSearchModels); } return(result); }
public async Task <IActionResult> ConfirmCancellation(OrganisationViewModel model, string command) { //Ensure user has completed the registration process User currentUser; IActionResult checkResult = CheckUserRegisteredOk(out currentUser); if (checkResult != null) { return(checkResult); } // Validate cancellation reason model.ParseAndValidateParameters(Request, m => m.CancellationReason); if (model.HasAnyErrors()) { View("ConfirmCancellation", model); } //If cancel button clicked the n return to review page if (command.EqualsI("Cancel")) { return(RedirectToAction("ReviewRequest")); } //Unwrap code UserOrganisation userOrg; ActionResult result = UnwrapRegistrationRequest(model, out userOrg); if (result != null) { return(result); } //Log the rejection auditLogger.AuditChangeToOrganisation( AuditedAction.RegistrationLog, userOrg.Organisation, new { Status = "Manually Rejected", Sector = userOrg.Organisation.SectorType, Organisation = userOrg.Organisation.OrganisationName, CompanyNo = userOrg.Organisation.CompanyNumber, Address = userOrg?.Address.GetAddressString(), SicCodes = userOrg.Organisation.GetSicCodeIdsString(), UserFirstname = userOrg.User.Firstname, UserLastname = userOrg.User.Lastname, UserJobtitle = userOrg.User.JobTitle, UserEmail = userOrg.User.EmailAddress, userOrg.User.ContactFirstName, userOrg.User.ContactLastName, userOrg.User.ContactJobTitle, userOrg.User.ContactOrganisation, userOrg.User.ContactPhoneNumber }, User); //Delete address for this user and organisation if (userOrg.Address.Status != AddressStatuses.Active && userOrg.Address.CreatedByUserId == userOrg.UserId) { DataRepository.Delete(userOrg.Address); } //Delete the org user long orgId = userOrg.OrganisationId; string emailAddress = userOrg.User.ContactEmailAddress.Coalesce(userOrg.User.EmailAddress); //Delete the organisation if it has no returns, is not in scopes table, and is not registered to another user if (userOrg.Organisation != null && !userOrg.Organisation.Returns.Any() && !userOrg.Organisation.OrganisationScopes.Any() && !await DataRepository.GetAll <UserOrganisation>() .AnyAsync(uo => uo.OrganisationId == userOrg.Organisation.OrganisationId && uo.UserId != userOrg.UserId)) { CustomLogger.Information( $"Unused organisation {userOrg.OrganisationId}:'{userOrg.Organisation.OrganisationName}' deleted by {(OriginalUser == null ? currentUser.EmailAddress : OriginalUser.EmailAddress)} when declining manual registration for {userOrg.User.EmailAddress}"); DataRepository.Delete(userOrg.Organisation); } EmployerSearchModel searchRecord = userOrg.Organisation.ToEmployerSearchResult(true); DataRepository.Delete(userOrg); //Send the declined email to the applicant SendRegistrationDeclined( emailAddress, string.IsNullOrWhiteSpace(model.CancellationReason) ? "We haven't been able to verify your employer's identity. So we have declined your application." : model.CancellationReason); //Save the changes and redirect DataRepository.SaveChanges(); //Save the model for the redirect this.StashModel(model); //If private sector then send the pin return(RedirectToAction("RequestCancelled")); }
public async Task AdminController_ReviewRequest_POST_ManualRegistration_ServiceActivated() { //ARRANGE: //create a user who does exist in the db var user = new User { UserId = 1, EmailAddress = "*****@*****.**", EmailVerifiedDate = VirtualDateTime.Now }; var org = new Core.Entities.Organisation { OrganisationId = 1, SectorType = SectorTypes.Private, Status = OrganisationStatuses.Pending }; //TODO: Refactoring to user the same Helpers (ie AddScopeStatus.AddScopeStatus) org.OrganisationScopes.Add( new OrganisationScope { Organisation = org, ScopeStatus = ScopeStatuses.InScope, SnapshotDate = org.SectorType.GetAccountingStartDate(VirtualDateTime.Now.Year), Status = ScopeRowStatuses.Active }); var address = new OrganisationAddress { AddressId = 1, OrganisationId = 1, Organisation = org, Status = AddressStatuses.Pending }; var userOrg = new UserOrganisation { UserId = 1, OrganisationId = 1, AddressId = address.AddressId, Address = address, User = user, Organisation = org }; var routeData = new RouteData(); routeData.Values.Add("Action", nameof(RegistrationController.OrganisationType)); routeData.Values.Add("Controller", "Registration"); var controller = UiTestHelper.GetController <AdminController>(user.UserId, routeData, user, org, address, userOrg); var model = new OrganisationViewModel { ReviewCode = userOrg.GetReviewCode() }; controller.StashModel(model); //ACT: var result = await controller.ReviewRequest(model, "approve") as RedirectToActionResult; //ASSERT: Assert.That(result != null, "Expected RedirectToActionResult"); Assert.That(result.ActionName == "RequestAccepted", "Expected redirect to RequestAccepted"); Assert.That(userOrg.PINConfirmedDate > DateTime.MinValue); Assert.That(userOrg.Organisation.Status == OrganisationStatuses.Active); Assert.That(userOrg.Organisation.LatestAddress.AddressId == address.AddressId); Assert.That(!string.IsNullOrWhiteSpace(userOrg.Organisation.EmployerReference)); Assert.That(address.Status == AddressStatuses.Active); //Check the organisation exists in search EmployerSearchModel actualIndex = await controller.AdminService.SearchBusinessLogic.EmployerSearchRepository.GetAsync(org.OrganisationId.ToString()); EmployerSearchModel expectedIndex = EmployerSearchModel.Create(org); expectedIndex.Compare(actualIndex); }