public FileContentResult DownloadOrganisationAddresses() { List <Organisation> organisationAddresses = dataRepository.GetAll <Organisation>() .Where(org => org.Status == OrganisationStatuses.Active) .Include(org => org.OrganisationAddresses) // This .ToList() materialises the collection (i.e. runs the SQL query) .ToList() // We only want organisations with valid addresses // The following filter only works in code (cannot be converted to SQL) so must be done after the first .ToList() .Where(org => org.GetLatestAddress() != null) .ToList(); var records = organisationAddresses.Select( org => { OrganisationAddress address = org.GetLatestAddress(); return(new { org.OrganisationId, org.OrganisationName, address.PoBox, address.Address1, address.Address2, address.Address3, address.TownCity, address.County, address.Country, address.PostCode, }); }) .ToList(); string fileDownloadName = $"Gpg-OrganisationAddresses-{VirtualDateTime.Now:yyyy-MM-dd HH:mm}.csv"; FileContentResult fileContentResult = DownloadHelper.CreateCsvDownload(records, fileDownloadName); return(fileContentResult); }
public bool AddressMatches(OrganisationAddress firstOrganisationAddress, OrganisationAddress secondOrganisationAddress) { return(string.Equals( firstOrganisationAddress.Address1, secondOrganisationAddress.Address1, StringComparison.Ordinal) && string.Equals( firstOrganisationAddress.Address2, secondOrganisationAddress.Address2, StringComparison.Ordinal) && string.Equals( firstOrganisationAddress.Address3, secondOrganisationAddress.Address3, StringComparison.Ordinal) && string.Equals( firstOrganisationAddress.TownCity, secondOrganisationAddress.TownCity, StringComparison.Ordinal) && string.Equals( firstOrganisationAddress.County, secondOrganisationAddress.County, StringComparison.Ordinal) && string.Equals( firstOrganisationAddress.Country, secondOrganisationAddress.Country, StringComparison.Ordinal) && string.Equals( firstOrganisationAddress.PostCode, secondOrganisationAddress.PostCode, StringComparison.Ordinal) && string.Equals( firstOrganisationAddress.PoBox, secondOrganisationAddress.PoBox, StringComparison.Ordinal)); }
public IActionResult ReviewRequest(OrganisationViewModel model, string command) { //Ensure user has completed the registration process User currentUser; IActionResult checkResult = CheckUserRegisteredOk(out currentUser); if (checkResult != null) { return(checkResult); } //Make sure we can load employers from session var m = this.UnstashModel <OrganisationViewModel>(); if (m == null) { return(View("CustomError", new ErrorViewModel(1112))); } model.ManualEmployers = m.ManualEmployers; //Unwrap code UserOrganisation userOrg; ActionResult result = UnwrapRegistrationRequest(model, out userOrg); if (result != null) { return(result); } //Check model is valid //Exclude the address details var excludes = new HashSet <string>(); excludes.AddRange( nameof(model.Address1), nameof(model.Address2), nameof(model.Address3), nameof(model.City), nameof(model.County), nameof(model.Country), nameof(model.Postcode), nameof(model.PoBox)); //Exclude the contact details excludes.AddRange( nameof(model.ContactFirstName), nameof(model.ContactLastName), nameof(model.ContactJobTitle), nameof(model.ContactEmailAddress), nameof(model.ContactPhoneNumber)); //Exclude the SIC Codes excludes.Add(nameof(model.SicCodeIds)); excludes.Add(nameof(model.SearchText)); excludes.Add(nameof(model.OrganisationName)); excludes.AddRange( nameof(model.CompanyNumber), nameof(model.CharityNumber), nameof(model.MutualNumber), nameof(model.OtherName), nameof(model.OtherValue)); ModelState.Exclude(excludes.ToArray()); if (!ModelState.IsValid) { this.CleanModelErrors <OrganisationViewModel>(); return(View(nameof(ReviewRequest), model)); } if (command.EqualsI("decline")) { result = RedirectToAction("ConfirmCancellation"); } else if (command.EqualsI("approve")) { Organisation conflictOrg = null; //Check for company number conflicts if (!string.IsNullOrWhiteSpace(model.CompanyNumber)) { conflictOrg = DataRepository.GetAll <Organisation>() .FirstOrDefault( o => userOrg.OrganisationId != o.OrganisationId && o.CompanyNumber.ToLower() == model.CompanyNumber.ToLower()); if (conflictOrg != null) { ModelState.AddModelError( 3031, nameof(model.CompanyNumber), new { organisationName = conflictOrg.OrganisationName, referenceName = "Company number" }); } } //Check for charity number conflicts if (!string.IsNullOrWhiteSpace(model.CharityNumber)) { OrganisationReference orgRef = DataRepository.GetAll <OrganisationReference>() .FirstOrDefault( o => userOrg.OrganisationId != o.OrganisationId && o.ReferenceName.ToLower() == nameof(model.CharityNumber).ToLower() && o.ReferenceValue.ToLower() == model.CharityNumber.ToLower()); conflictOrg = orgRef?.Organisation; if (conflictOrg != null) { ModelState.AddModelError( 3031, nameof(model.CharityNumber), new { organisationName = conflictOrg.OrganisationName, referenceName = "Charity number" }); } } //Check for mutual number conflicts if (!string.IsNullOrWhiteSpace(model.MutualNumber)) { OrganisationReference orgRef = DataRepository.GetAll <OrganisationReference>() .FirstOrDefault( o => userOrg.OrganisationId != o.OrganisationId && o.ReferenceName.ToLower() == nameof(model.MutualNumber).ToLower() && o.ReferenceValue.ToLower() == model.MutualNumber.ToLower()); conflictOrg = orgRef?.Organisation; if (conflictOrg != null) { ModelState.AddModelError( 3031, nameof(model.MutualNumber), new { organisationName = conflictOrg.OrganisationName, referenceName = "Mutual partnership number" }); } } //Check for other reference conflicts if (!string.IsNullOrWhiteSpace(model.OtherValue)) { OrganisationReference orgRef = DataRepository.GetAll <OrganisationReference>() .FirstOrDefault( o => userOrg.OrganisationId != o.OrganisationId && o.ReferenceName.ToLower() == model.OtherName.ToLower() && o.ReferenceValue.ToLower() == model.OtherValue.ToLower()); conflictOrg = orgRef?.Organisation; if (conflictOrg != null) { ModelState.AddModelError( 3031, nameof(model.OtherValue), new { organisationName = conflictOrg.OrganisationName, referenceName = model.OtherValue }); } } if (!ModelState.IsValid) { this.CleanModelErrors <OrganisationViewModel>(); return(View("ReviewRequest", model)); } //Activate the org user userOrg.PINConfirmedDate = VirtualDateTime.Now; //Activate the organisation userOrg.Organisation.SetStatus( OrganisationStatuses.Active, OriginalUser == null ? currentUser.UserId : OriginalUser.UserId, "Manually registered"); // save any sic codes if (!string.IsNullOrEmpty(model.SicCodeIds)) { IOrderedEnumerable <int> newSicCodes = model.SicCodeIds.Split(',').Cast <int>().OrderBy(sc => sc); foreach (int sc in newSicCodes) { userOrg.Organisation.OrganisationSicCodes.Add( new OrganisationSicCode { SicCodeId = sc, OrganisationId = userOrg.OrganisationId, Created = VirtualDateTime.Now }); } } //Retire the old address OrganisationAddress latestAddress = userOrg.Organisation.GetLatestAddress(); if (latestAddress != null && latestAddress.AddressId != userOrg.Address.AddressId) { latestAddress.SetStatus( AddressStatuses.Retired, OriginalUser == null ? currentUser.UserId : OriginalUser.UserId, "Replaced by Manual registration"); } //Activate the address userOrg.Address.SetStatus( AddressStatuses.Active, OriginalUser == null ? currentUser.UserId : OriginalUser.UserId, "Manually registered"); //Send the approved email to the applicant SendRegistrationAccepted(userOrg.User.ContactEmailAddress.Coalesce(userOrg.User.EmailAddress)); //Log the approval auditLogger.AuditChangeToOrganisation( AuditedAction.RegistrationLog, userOrg.Organisation, new { Status = "Manually registered", 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); result = RedirectToAction("RequestAccepted"); } else { return(new HttpBadRequestResult($"Invalid command on '{command}'")); } //Save the changes and redirect DataRepository.SaveChanges(); //Send notification email to existing users EmailSendingServiceHelpers.SendUserAddedEmailToExistingUsers(userOrg.Organisation, userOrg.User, emailSendingService); //Save the model for the redirect this.StashModel(model); return(result); }
public override Dictionary <string, string> SubmitJobDiscloseInfo(DiscoDataContext Database, Job Job, OrganisationAddress Address, User TechUser, string RepairDescription, Dictionary <string, string> ProviderProperties) { return(Internal.LWTJobs.DiscloseInformation(Database, Job, Address, TechUser)); }
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); }
private IActionResult OfferNewCompaniesHouseAddress(Organisation organisation, OrganisationAddress addressFromCompaniesHouse) { var viewModel = new ChangeOrganisationAddressViewModel { Organisation = organisation, Action = ManuallyChangeOrganisationAddressViewModelActions.OfferNewCompaniesHouseAddress }; viewModel.PopulateFromOrganisationAddress(addressFromCompaniesHouse); return(View("OfferNewCompaniesHouseAddress", viewModel)); }
public async Task DnBImportAsync(ILogger log, long currentUserId) { if (RunningJobs.Contains(nameof(CompaniesHouseCheck)) || RunningJobs.Contains(nameof(DnBImportAsync))) { return; } RunningJobs.Add(nameof(DnBImportAsync)); string userEmail = null; string error = null; var startTime = VirtualDateTime.Now; var totalChanges = 0; var totalInserts = 0; try { #region Load and Prechecks //Load the D&B records var dnbOrgsPaths = await _SharedBusinessLogic.FileRepository.GetFilesAsync(_SharedBusinessLogic.SharedOptions.DataPath, Filenames.DnBOrganisations()); var dnbOrgsPath = dnbOrgsPaths.OrderByDescending(f => f).FirstOrDefault(); if (string.IsNullOrEmpty(dnbOrgsPath)) { return; } if (!await _SharedBusinessLogic.FileRepository.GetFileExistsAsync(dnbOrgsPath)) { throw new Exception("Could not find " + dnbOrgsPath); } var AllDnBOrgs = await _SharedBusinessLogic.FileRepository.ReadCSVAsync <DnBOrgsModel>(dnbOrgsPath); if (!AllDnBOrgs.Any()) { log.LogWarning($"No records found in '{dnbOrgsPath}'"); return; } AllDnBOrgs = AllDnBOrgs.OrderBy(o => o.OrganisationName).ToList(); //Check for duplicate DUNS var count = AllDnBOrgs.Count() - AllDnBOrgs.Select(o => o.DUNSNumber).Distinct().Count(); if (count > 0) { throw new Exception($"There are {count} duplicate DUNS numbers detected"); } //Check for no addresses count = AllDnBOrgs.Count(o => !o.IsValidAddress()); if (count > 0) { throw new Exception( $"There are {count} organisations with no address detected (i.e., no AddressLine1, AddressLine2, PostalCode, and PoBox)."); } //Check for no organisation name count = AllDnBOrgs.Count(o => string.IsNullOrWhiteSpace(o.OrganisationName)); if (count > 0) { throw new Exception($"There are {count} organisations with no OrganisationName detected."); } //Check for duplicate employer references var allEmployerReferenceCount = AllDnBOrgs.Count(o => !string.IsNullOrWhiteSpace(o.EmployerReference)); var employerReferences = new SortedSet <string>( AllDnBOrgs.Where(o => !string.IsNullOrWhiteSpace(o.EmployerReference)) .Select(o => o.EmployerReference).Distinct()); count = allEmployerReferenceCount - employerReferences.Count; if (count > 0) { throw new Exception($"There are {count} duplicate EmployerReferences detected"); } //Check companies have been updated count = AllDnBOrgs.Count( o => !string.IsNullOrWhiteSpace(o.CompanyNumber) && o.DateOfCessation == null && (o.StatusCheckedDate == null || o.StatusCheckedDate.Value.AddMonths(1) < VirtualDateTime.Now)); if (count > 0) { throw new Exception( $"There are {count} active companies who have not been checked with companies house within the last month"); } //Fix Company Number Parallel.ForEach( AllDnBOrgs.Where(o => !string.IsNullOrWhiteSpace(o.CompanyNumber)), dnbOrg => { if (dnbOrg.CompanyNumber.IsNumber()) { dnbOrg.CompanyNumber = dnbOrg.CompanyNumber.PadLeft(8, '0'); } }); //Check for duplicate company numbers var companyNumbers = AllDnBOrgs.Where(o => !string.IsNullOrWhiteSpace(o.CompanyNumber)).Select(o => o.CompanyNumber); count = companyNumbers.Count() - companyNumbers.Distinct().Count(); if (count > 0) { throw new Exception($"There are {count} duplicate CompanyNumbers detected"); } //Get the current users email address var user = await _SharedBusinessLogic.DataRepository.GetAll <User>() .FirstOrDefaultAsync(u => u.UserId == currentUserId); userEmail = user?.EmailAddress; //Count records requiring import count = AllDnBOrgs.Count( o => !o.GetIsDissolved() && (o.ImportedDate == null || string.IsNullOrWhiteSpace(o.CompanyNumber) || o.ImportedDate < o.StatusCheckedDate)); if (count == 0) { return; } var dbOrgs = _SharedBusinessLogic.DataRepository.GetAll <Organisation>().ToList(); #endregion //Set all existing org employer references await ReferenceEmployersAsync(); #region Set all existing org DUNS var dnbOrgs = AllDnBOrgs .Where(o => o.OrganisationId > 0 && string.IsNullOrWhiteSpace(o.EmployerReference)) .ToList(); if (dnbOrgs.Count > 0) { foreach (var dnbOrg in dnbOrgs) { var org = dbOrgs.FirstOrDefault(o => o.OrganisationId == dnbOrg.OrganisationId); if (org == null) { if (!_SharedBusinessLogic.SharedOptions.IsProduction()) { continue; } throw new Exception($"OrganisationId:{dnbOrg.OrganisationId} does not exist in database"); } if (!string.IsNullOrWhiteSpace(org.DUNSNumber)) { continue; } org.DUNSNumber = dnbOrg.DUNSNumber; dnbOrg.OrganisationId = null; } await _SharedBusinessLogic.DataRepository.SaveChangesAsync(); dbOrgs = await _SharedBusinessLogic.DataRepository.GetAll <Organisation>().ToListAsync(); await _SharedBusinessLogic.FileRepository.SaveCSVAsync(AllDnBOrgs, dnbOrgsPath); AllDnBOrgs = await _SharedBusinessLogic.FileRepository.ReadCSVAsync <DnBOrgsModel>(dnbOrgsPath); AllDnBOrgs = AllDnBOrgs.OrderBy(o => o.OrganisationName).ToList(); } #endregion var allSicCodes = await _SharedBusinessLogic.DataRepository.GetAll <SicCode>().ToListAsync(); dnbOrgs = AllDnBOrgs.Where(o => o.ImportedDate == null || o.ImportedDate < o.StatusCheckedDate) .ToList(); while (dnbOrgs.Count > 0) { var allBadSicCodes = new ConcurrentBag <OrganisationSicCode>(); var c = 0; var dbChanges = 0; var dnbChanges = 0; foreach (var dnbOrg in dnbOrgs) { //Only do 100 records at a time if (c > 100) { break; } var dbChanged = false; var dbOrg = dbOrgs.FirstOrDefault(o => o.DUNSNumber == dnbOrg.DUNSNumber); var dataSource = string.IsNullOrWhiteSpace(dnbOrg.NameSource) ? "D&B" : dnbOrg.NameSource; var orgName = new OrganisationName { Name = dnbOrg.OrganisationName.Left(100), Source = dataSource }; if (dbOrg == null) { dbOrg = string.IsNullOrWhiteSpace(dnbOrg.CompanyNumber) ? null : dbOrgs.FirstOrDefault(o => o.CompanyNumber == dnbOrg.CompanyNumber); if (dbOrg != null) { dbOrg.DUNSNumber = dnbOrg.DUNSNumber; } else { dbOrg = new Organisation { DUNSNumber = dnbOrg.DUNSNumber, EmployerReference = dnbOrg.EmployerReference, OrganisationName = orgName.Name, CompanyNumber = string.IsNullOrWhiteSpace(dnbOrg.CompanyNumber) ? null : dnbOrg.CompanyNumber, SectorType = dnbOrg.SectorType, DateOfCessation = dnbOrg.DateOfCessation }; dbOrg.OrganisationNames.Add(orgName); //Create a presumed in-scope for current year var newScope = new OrganisationScope { Organisation = dbOrg, ScopeStatus = ScopeStatuses.PresumedInScope, ScopeStatusDate = VirtualDateTime.Now, Status = ScopeRowStatuses.Active, SnapshotDate = _snapshotDateHelper.GetSnapshotDate(dbOrg.SectorType) }; _SharedBusinessLogic.DataRepository.Insert(newScope); dbOrg.OrganisationScopes.Add(newScope); //Create a presumed out-of-scope for previous year var oldScope = new OrganisationScope { Organisation = dbOrg, ScopeStatus = ScopeStatuses.PresumedOutOfScope, ScopeStatusDate = VirtualDateTime.Now, Status = ScopeRowStatuses.Active, SnapshotDate = newScope.SnapshotDate.AddYears(-1) }; _SharedBusinessLogic.DataRepository.Insert(oldScope); dbOrg.OrganisationScopes.Add(oldScope); dbOrg.SetStatus(OrganisationStatuses.Active, currentUserId, "Imported from D&B"); } } //Skip dissolved companies else if (_OrganisationBusinessLogic.GetOrganisationWasDissolvedBeforeCurrentAccountingYear(dbOrg)) { dnbOrg.ImportedDate = VirtualDateTime.Now; dnbChanges++; continue; } else if (dbOrg.OrganisationName != orgName.Name) { var oldOrgName = dbOrg.GetLatestName(); if (oldOrgName == null || _SharedBusinessLogic.SourceComparer.CanReplace(orgName.Source, oldOrgName.Source)) { dbOrg.OrganisationName = orgName.Name; dbOrg.OrganisationNames.Add(orgName); dbChanged = true; } } //Ensure D&B gas an organisationID if (dnbOrg.OrganisationId == null || dnbOrg.OrganisationId.Value == 0) { dnbOrg.OrganisationId = dbOrg.OrganisationId; dnbChanges++; } //Add the cessation date if (dbOrg.DateOfCessation == null && dbOrg.DateOfCessation != dnbOrg.DateOfCessation) { dbOrg.DateOfCessation = dnbOrg.DateOfCessation; dbChanged = true; } //Set the employer reference if (string.IsNullOrWhiteSpace(dbOrg.EmployerReference)) { string employerReference; do { employerReference = _OrganisationBusinessLogic.GenerateEmployerReference(); } while (employerReferences.Contains(employerReference)); dbOrg.EmployerReference = employerReference; employerReferences.Add(employerReference); dbChanged = true; } if (dnbOrg.EmployerReference != dbOrg.EmployerReference) { dnbOrg.EmployerReference = dbOrg.EmployerReference; dnbChanges++; } //Add the new address var fullAddress = dnbOrg.GetAddress(); var newAddress = dbOrg.LatestAddress; //add the address if there isnt one dataSource = string.IsNullOrWhiteSpace(dnbOrg.AddressSource) ? "D&B" : dnbOrg.AddressSource; if (newAddress == null || !newAddress.GetAddressString().EqualsI(fullAddress) && _SharedBusinessLogic.SourceComparer.CanReplace(dataSource, newAddress.Source)) { var statusDate = VirtualDateTime.Now; newAddress = new OrganisationAddress(); newAddress.Organisation = dbOrg; newAddress.CreatedByUserId = currentUserId; newAddress.Address1 = dnbOrg.AddressLine1; newAddress.Address2 = dnbOrg.AddressLine2; newAddress.Address3 = dnbOrg.AddressLine3; newAddress.County = dnbOrg.County; newAddress.Country = dnbOrg.Country; newAddress.TownCity = dnbOrg.City; newAddress.PostCode = dnbOrg.PostalCode; newAddress.PoBox = dnbOrg.PoBox; newAddress.Source = dataSource; newAddress.SetStatus(AddressStatuses.Active, currentUserId, "Imported from D&B"); if (dbOrg.LatestAddress != null) { dbOrg.LatestAddress.SetStatus(AddressStatuses.Retired, currentUserId, $"Replaced by {newAddress.Source}"); } } //Update the sic codes var newCodeIds = dnbOrg.GetSicCodesIds(); var newCodesList = dnbOrg.GetSicCodesIds().ToList(); for (var i = 0; i < newCodesList.Count; i++) { var code = newCodesList[i]; if (code <= 0) { continue; } var sicCode = allSicCodes.FirstOrDefault(sic => sic.SicCodeId == code); if (sicCode != null) { continue; } sicCode = allSicCodes.FirstOrDefault( sic => sic.SicCodeId == code * 10 && sic.Description.EqualsI(dnbOrg.SicDescription)); if (sicCode != null) { newCodesList[i] = sicCode.SicCodeId; } } newCodeIds = new SortedSet <int>(newCodesList); var newCodes = new List <OrganisationSicCode>(); var oldCodes = dbOrg.GetLatestSicCodes().ToList(); var oldSicSource = dbOrg.GetLatestSicSource(); var oldCodeIds = oldCodes.Select(s => s.SicCodeId); if (dbOrg.SectorType == SectorTypes.Public) { newCodeIds.Add(1); } if (!_SharedBusinessLogic.SharedOptions.IsProduction()) { Debug.WriteLine( $"OLD:{oldCodes.Select(s => s.SicCodeId).ToDelimitedString()} NEW:{newCodeIds.ToDelimitedString()}"); } dataSource = string.IsNullOrWhiteSpace(dnbOrg.SicSource) ? "D&B" : dnbOrg.SicSource; if (!newCodeIds.SetEquals(oldCodeIds) && _SharedBusinessLogic.SourceComparer.CanReplace(dataSource, oldSicSource)) { foreach (var code in newCodeIds) { if (code <= 0) { continue; } var sicCode = allSicCodes.FirstOrDefault(sic => sic.SicCodeId == code); var newSic = new OrganisationSicCode { Organisation = dbOrg, SicCodeId = code, Source = dataSource }; if (sicCode == null) { allBadSicCodes.Add(newSic); continue; } newCodes.Add(newSic); } if (newCodes.Any()) { //Add new codes only foreach (var newSic in newCodes) { dbOrg.OrganisationSicCodes.Add(newSic); dbChanged = true; } //Retire the old codes foreach (var oldSic in oldCodes) { oldSic.Retired = VirtualDateTime.Now; dbChanged = true; } } } await _SharedBusinessLogic.DataRepository.BeginTransactionAsync( async() => { try { //Save the name, Sic, EmployerReference, DateOfCessasion changes if (dbChanged) { await _SharedBusinessLogic.DataRepository.SaveChangesAsync(); } //Save the changes dnbOrg.ImportedDate = VirtualDateTime.Now; dnbChanges++; var insert = false; if (dbOrg.OrganisationId == 0) { _SharedBusinessLogic.DataRepository.Insert(dbOrg); await _SharedBusinessLogic.DataRepository.SaveChangesAsync(); dbChanged = true; insert = true; } if (newAddress != null && newAddress.AddressId == 0) { dbOrg.OrganisationAddresses.Add(newAddress); dbOrg.LatestAddress = newAddress; await _SharedBusinessLogic.DataRepository.SaveChangesAsync(); dbChanged = true; } if (dbChanged) { dbChanges++; _SharedBusinessLogic.DataRepository.CommitTransaction(); totalChanges++; if (insert) { totalInserts++; } //Add or remove this organisation to/from the search index await SearchBusinessLogic.UpdateSearchIndexAsync(dbOrg); } } catch { _SharedBusinessLogic.DataRepository.RollbackTransaction(); } }); c++; } //Reload all the changes if (dbChanges > 0) { dbOrgs = await _SharedBusinessLogic.DataRepository.GetAll <Organisation>().ToListAsync(); } //Save the D&B records if (dnbChanges > 0) { await _SharedBusinessLogic.FileRepository.SaveCSVAsync(AllDnBOrgs, dnbOrgsPath); AllDnBOrgs = await _SharedBusinessLogic.FileRepository.ReadCSVAsync <DnBOrgsModel>(dnbOrgsPath); AllDnBOrgs = AllDnBOrgs.OrderBy(o => o.OrganisationName).ToList(); dnbOrgs = AllDnBOrgs.Where(o => o.ImportedDate == null || o.ImportedDate < o.StatusCheckedDate) .ToList(); } //Save the bad sic codes if (allBadSicCodes.Count > 0) { //Create the logging tasks var badSicLoggingtasks = new List <Task>(); allBadSicCodes.ForEach( bsc => badSicLoggingtasks.Add( _BadSicLog.WriteAsync( new BadSicLogModel { OrganisationId = bsc.Organisation.OrganisationId, OrganisationName = bsc.Organisation.OrganisationName, SicCode = bsc.SicCodeId, Source = bsc.Source }))); //Wait for all the logging tasks to complete await Task.WhenAll(badSicLoggingtasks); } } } catch (Exception ex) { error = ex.Message; throw; } finally { if (!string.IsNullOrWhiteSpace(userEmail)) { var endTime = VirtualDateTime.Now; var duration = endTime - startTime; try { if (!string.IsNullOrWhiteSpace(error)) { await _Messenger.SendMessageAsync( "D&B Import Failed", userEmail, $"The D&B import failed at {endTime} after {duration.ToFriendly()}.\nChanged {totalChanges} organisations including {totalInserts} new.\n\nERROR:{error}"); } else if (totalChanges == 0) { await _Messenger.SendMessageAsync( "D&B Import Complete", userEmail, "The D&B import process completed successfully with no records requiring import."); } else { await _Messenger.SendMessageAsync( "D&B Import Complete", userEmail, $"The D&B import process completed successfully at {endTime} after {duration.ToFriendly()}.\nChanged {totalChanges} organisations including {totalInserts} new."); } } catch (Exception ex) { log.LogError(ex, ex.Message); } } RunningJobs.Remove(nameof(DnBImportAsync)); } }
public override Dictionary <string, string> SubmitJobParseProperties(DiscoDataContext Database, FormCollection form, Controller controller, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription) { Internal.LWTJobs.ValidateEnvironment(Database, controller, TechUser); return(null); }
public async Task AdministrationController_ManualChanges_prevAddress_SetStatus_Address_Statuses_Retired() { // Arrange var existingAddressExpectedToBeRetired = new OrganisationAddress { Address1 = "Previous Address1", Address2 = "Previous Address2", Address3 = "Previous Address3", TownCity = "Previous TownCity", County = "Previous County", Country = "Previous Country", PostCode = "Previous PostCode", Status = AddressStatuses.Active }; Core.Entities.Organisation privateOrgWhoseAddressWillBeChanged = OrganisationHelper.GetPrivateOrganisation("Employer_Reference_989898"); privateOrgWhoseAddressWillBeChanged.LatestAddress = existingAddressExpectedToBeRetired; #region setting up database and controller User notAdminUser = UserHelper.GetDatabaseAdmin(); var adminController = UiTestHelper.GetController <AdminController>(notAdminUser.UserId, null, null); Mock <IDataRepository> configurableDataRepository = AutoFacExtensions.ResolveAsMock <IDataRepository>(); configurableDataRepository .Setup(x => x.Get <User>(It.IsAny <long>())) .Returns(notAdminUser); configurableDataRepository .Setup(x => x.GetAll <Core.Entities.Organisation>()) .Returns(new[] { privateOrgWhoseAddressWillBeChanged }.AsQueryable().BuildMock().Object); var manualChangesViewModel = new ManualChangesViewModel { Command = SetOrganisationAddressesCommand, Parameters = $"{privateOrgWhoseAddressWillBeChanged.EmployerReference}=New Address1, New Address2, New Address3, New TownCity, New County, New Country, New PostCode" }; #endregion // Act IActionResult manualChangesResult = await adminController.ManualChanges(manualChangesViewModel); // Assert Assert.NotNull(manualChangesResult, "Expected a Result"); var manualChangesViewResult = manualChangesResult as ViewResult; Assert.NotNull(manualChangesViewResult, "Expected ViewResult"); var actualManualChangesViewModel = manualChangesViewResult.Model as ManualChangesViewModel; Assert.NotNull(actualManualChangesViewModel, "Expected ManualChangesViewModel"); Assert.Multiple( () => { Assert.AreEqual( "SUCCESSFULLY TESTED 'Set organisation addresses': 1 of 1", actualManualChangesViewModel.SuccessMessage); Assert.AreEqual( "1: EMPLOYER_REFERENCE_989898:Org123 Address=Previous Address1, Previous Address2, Previous Address3, Previous TownCity, Previous County, Previous Country, Previous PostCode will be set to New Address1, New Address2, New Address3, New TownCity, New County, New Country, New PostCode\r\n", actualManualChangesViewModel.Results); Assert.AreEqual("Set organisation addresses", actualManualChangesViewModel.LastTestedCommand); Assert.AreEqual( "Employer_Reference_989898=New Address1, New Address2, New Address3, New TownCity, New County, New Country, New PostCode", actualManualChangesViewModel.LastTestedInput); Assert.True(actualManualChangesViewModel.Tested, "Must be tested=true as this case is running in TEST mode"); Assert.IsNull(actualManualChangesViewModel.Comment); }); }
public override string SubmitJob(DiscoDataContext dbContext, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription, Dictionary <string, string> WarrantyProviderProperties) { // Send Job to NN var httpBody = new StringBuilder("Automated=1"); bool ntpDevice = bool.Parse(WarrantyProviderProperties["NTPDevice"]); // Determine if DEECD NTP job is to be processed or not. if (ntpDevice == true) { httpBody.Append("&txtContact="); httpBody.Append(HttpUtility.UrlEncode(Job.User.DisplayName)); httpBody.Append("&txtemail="); httpBody.Append(HttpUtility.UrlEncode(Job.User.EmailAddress)); } else { httpBody.Append("&txtContact="); httpBody.Append(HttpUtility.UrlEncode(TechUser.DisplayName)); httpBody.Append("&txtemail="); httpBody.Append(HttpUtility.UrlEncode(TechUser.EmailAddress)); } httpBody.Append("&txtorg="); httpBody.Append(HttpUtility.UrlEncode(Address.Name)); httpBody.Append("&txtorgaddress="); httpBody.Append(HttpUtility.UrlEncode(Address.Address)); httpBody.Append("&txtorgsub="); httpBody.Append(HttpUtility.UrlEncode(Address.Suburb)); httpBody.Append("&txtorgpost="); httpBody.Append(HttpUtility.UrlEncode(Address.Postcode)); httpBody.Append("&txtorgstate="); httpBody.Append(NNCompatibleContactState(Address.State)); httpBody.Append("&txtphone="); httpBody.Append(HttpUtility.UrlEncode(TechUser.PhoneNumber)); httpBody.Append("&txtSerial="); httpBody.Append(HttpUtility.UrlEncode(Job.DeviceSerialNumber)); httpBody.Append("&txtModel="); httpBody.Append(HttpUtility.UrlEncode(Job.Device.DeviceModel.Model)); httpBody.Append("&txtProblemDesc="); httpBody.Append(HttpUtility.UrlEncode(FaultDescription)); httpBody.Append("&nttpUnit="); httpBody.Append(ntpDevice ? "1" : "0"); httpBody.Append("&sltSuspectedIssue="); httpBody.Append(WarrantyProviderProperties["Issue"]); string stringResponse = null; try { HttpWebRequest wreq = HttpWebRequest.Create("http://portal.nn.net.au/ajax/warranty/ajaxWarrantyCreateJob.php") as HttpWebRequest; wreq.KeepAlive = false; wreq.Method = WebRequestMethods.Http.Post; wreq.ContentType = "application/x-www-form-urlencoded"; using (StreamWriter sw = new StreamWriter(wreq.GetRequestStream())) { sw.Write(httpBody.ToString()); } using (HttpWebResponse wres = (HttpWebResponse)wreq.GetResponse()) { using (StreamReader sr = new StreamReader(wres.GetResponseStream())) { stringResponse = sr.ReadToEnd(); } } // TODO: Parse the JSON Correctly - http://en.wikipedia.org/wiki/Json // JSON.net is used in Disco, eg: // dynamic response = JsonConvert.DeserializeObject(stringResponse); // string jobReference = response.SomeChildObject.SomeOtherObject.PropertyWhichHoldsJobReference; // return jobReference; // END TODO // NN Get last 6 Chars to gather jobID stringResponse = stringResponse.Substring(stringResponse.Length - 6); // remove end bracket to make it a proper number char[] remove = { '}' }; stringResponse = stringResponse.TrimEnd(remove); int jobReference = default(int); if (int.TryParse(stringResponse, out jobReference)) { return(jobReference.ToString()); } else { // Throw error if unable to get Job task ID throw new WarrantyProviderSubmitJobException(stringResponse); } } catch (Exception ex) { string errorMessage = string.Format("Unable to successfully log warranty:{0}{1}{0}{2}{0}Server Responded: {3}", Environment.NewLine, ex.GetType().Name, ex.Message, stringResponse ?? "Unknown/None"); throw new WarrantyProviderSubmitJobException(errorMessage); } }
public override Dictionary <string, string> SubmitJobDiscloseInfo(DiscoDataContext dbContext, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription, Dictionary <string, string> WarrantyProviderProperties) { Dictionary <String, String> info = new Dictionary <string, string>(); // If the device is a part of the NTP then change contact details to them bool ntpDevice = bool.Parse(WarrantyProviderProperties["NTPDevice"]); if (ntpDevice == true) { // Victorian Teacher notebook info.Add("Contact Name", Job.User.DisplayName); info.Add("Contact Email", Job.User.EmailAddress); } else { // School owned devices info.Add("Contact Name", TechUser.DisplayName); info.Add("Contact Email", TechUser.EmailAddress); } info.Add("Contact Company", Address.Name); info.Add("Contact Address", Address.Address); info.Add("Contact Suburb", Address.Suburb); info.Add("Contact State", NNCompatibleContactState(Address.State)); info.Add("Contact Postcode", Address.Postcode); info.Add("Contact Phone", TechUser.PhoneNumber); info.Add("Device Serial Number", Job.DeviceSerialNumber); info.Add("Device Product Description", String.Format("{0} {1}", Job.Device.DeviceModel.Manufacturer, Job.Device.DeviceModel.Model)); info.Add("NTP Device", ntpDevice ? "Yes" : "No"); info.Add("Suspected Issue", NNSuspectedIssues[int.Parse(WarrantyProviderProperties["Issue"])]); return(info); }
public override Dictionary <string, string> SubmitJobParseProperties(DiscoDataContext dbContext, FormCollection form, Controller controller, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription) { ViewModels.NNOptionsViewModel model = new ViewModels.NNOptionsViewModel(); controller.TryUpdateModel(model); SubmitJobValidateEnvironment(dbContext, controller, TechUser, Job, model); return(new Dictionary <string, string>() { { "NTPDevice", model.NTPDevice.ToString() }, { "Issue", model.Issue.ToString() } }); }
public override dynamic SubmitJobViewModel(DiscoDataContext dbContext, Controller controller, Job Job, OrganisationAddress Address, User TechUser) { SubmitJobValidateEnvironment(dbContext, controller, TechUser, Job, null); var model = new ViewModels.NNOptionsViewModel() { NTPDevice = null, Issue = 0 }; return(model); }
public static Dictionary <string, string> DiscloseInformation(DiscoDataContext Database, Job Job, OrganisationAddress Address, User TechUser) { var config = new ConfigurationStore(Database); string serialNumberMessage; if (Job.Device.HasAlternateSerialNumber(out serialNumberMessage)) { serialNumberMessage += " [Acer SNID]"; } else { serialNumberMessage = Job.DeviceSerialNumber; } return(new Dictionary <string, string>() { { "LWT Customer Entity Id", config.CustomerEntityId }, { "LWT Customer Username", config.CustomerUsername }, { "Contact Name", TechUser.DisplayName }, { "Contact Company", Address.Name }, { "Contact Address", Address.Address }, { "Contact Suburb", Address.Suburb }, { "Contact Postcode", Address.Postcode }, { "Contact Phone", TechUser.PhoneNumber }, { "Contact Email", TechUser.EmailAddress }, { "Device Serial Number", serialNumberMessage }, { "Device Product Description", String.Format("{0} {1}", Job.Device.DeviceModel.Manufacturer, Job.Device.DeviceModel.Model) }, { "Device Room Location", String.Format("Customer Job Id: {0}", Job.Id) } }); }
public EmployerRecord CreateEmployerRecord(Organisation org, long userId = 0) { OrganisationAddress address = null; if (userId > 0) { address = org.UserOrganisations.FirstOrDefault(uo => uo.UserId == userId)?.Address; } if (address == null) { address = org.LatestAddress; } if (address == null) { return new EmployerRecord { OrganisationId = org.OrganisationId, SectorType = org.SectorType, OrganisationName = org.OrganisationName, NameSource = GetOrganisationName(org)?.Source, EmployerReference = org.EmployerReference, DateOfCessation = org.DateOfCessation, DUNSNumber = org.DUNSNumber, CompanyNumber = org.CompanyNumber, SicSectors = GetOrganisationSicSectorsString(org, null, ",<br/>"), SicCodeIds = GetOrganisationSicCodeIdsString(org), SicSource = GetOrganisationSicSource(org), RegistrationStatus = org.GetRegistrationStatus(), References = org.OrganisationReferences.ToDictionary( r => r.ReferenceName, r => r.ReferenceValue, StringComparer.OrdinalIgnoreCase) } } ; return(new EmployerRecord { OrganisationId = org.OrganisationId, SectorType = org.SectorType, OrganisationName = org.OrganisationName, NameSource = GetOrganisationName(org)?.Source, EmployerReference = org.EmployerReference, DateOfCessation = org.DateOfCessation, DUNSNumber = org.DUNSNumber, CompanyNumber = org.CompanyNumber, SicSectors = GetOrganisationSicSectorsString(org, null, ",<br/>"), SicCodeIds = GetOrganisationSicCodeIdsString(org), SicSource = GetOrganisationSicSource(org), ActiveAddressId = address.AddressId, AddressSource = address.Source, Address1 = address.Address1, Address2 = address.Address2, Address3 = address.Address3, City = address.TownCity, County = address.County, Country = address.Country, PostCode = address.PostCode, PoBox = address.PoBox, IsUkAddress = address.IsUkAddress, RegistrationStatus = org.GetRegistrationStatus(), References = org.OrganisationReferences.ToDictionary( r => r.ReferenceName, r => r.ReferenceValue, StringComparer.OrdinalIgnoreCase) }); }
public static string SubmitWarrantyJob(DiscoDataContext Database, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription) { return(SubmitJob(Database, Job, Address, TechUser, FaultDescription)); }
public static List <string> GetAddressComponentsWithoutRepeatsOrUnnecessaryComponents(OrganisationAddress organisationAddress) { var address = new List <string>(); if (!string.IsNullOrWhiteSpace(organisationAddress.PoBox)) { string poBox = organisationAddress.PoBox; if (!poBox.Contains("PO Box", StringComparison.OrdinalIgnoreCase)) { poBox = $"PO Box {poBox}"; } address.Add("PO Box " + poBox); } if (!string.IsNullOrWhiteSpace(organisationAddress.Address1)) { address.Add(organisationAddress.Address1); } if (!string.IsNullOrWhiteSpace(organisationAddress.Address2)) { address.Add(organisationAddress.Address2); } if (!string.IsNullOrWhiteSpace(organisationAddress.Address3)) { address.Add(organisationAddress.Address3); } if (!string.IsNullOrWhiteSpace(organisationAddress.TownCity)) { address.Add(organisationAddress.TownCity); } if (!string.IsNullOrWhiteSpace(organisationAddress.County)) { address.Add(organisationAddress.County); } // Gov.UK Notify can only send post to the UK, so there's no need // to have 'UK' or 'United Kingdom' as part of the address if (!string.IsNullOrWhiteSpace(organisationAddress.Country) && organisationAddress.Country.ToUpper() != "UNITED KINGDOM" && organisationAddress.Country.ToUpper() != "UK") { address.Add(organisationAddress.Country); } return(address); }
public override dynamic SubmitJobViewModel(DiscoDataContext Database, Controller controller, Job Job, OrganisationAddress Address, User TechUser) { Internal.LWTJobs.ValidateEnvironment(Database, controller, TechUser); return(null); }
public void RegistrationController_AddAddress_POST_AuthorisedNoAddress_ToConfirm() { //ARRANGE: //1.Arrange the test setup variables var user = new User { UserId = 1, EmailAddress = "*****@*****.**", EmailVerifiedDate = VirtualDateTime.Now }; var address0 = new OrganisationAddress { AddressId = 1, Status = AddressStatuses.Active, Source = "CoHo", Address1 = "123", Address2 = "evergreen terrace", Address3 = "Westminster", TownCity = "City1", County = "County1", Country = "United Kingdom", PoBox = "PoBox 12", PostCode = "W1 5qr" }; var sicCode1 = new SicCode { SicCodeId = 2100, Description = "Desc1", SicSection = new SicSection { SicSectionId = "4321", Description = "Section1" } }; var sicCode2 = new SicCode { SicCodeId = 10520, Description = "Desc2", SicSection = new SicSection { SicSectionId = "4326", Description = "Section2" } }; var org0 = new Core.Entities.Organisation { OrganisationId = 1, OrganisationName = "Company1", SectorType = SectorTypes.Private, Status = OrganisationStatuses.Active, CompanyNumber = "12345678" }; org0.OrganisationAddresses.Add(address0); var name = new OrganisationName { OrganisationNameId = 1, Name = org0.OrganisationName, Created = org0.Created, Organisation = org0, OrganisationId = org0.OrganisationId }; org0.OrganisationNames.Add(name); var sic1 = new OrganisationSicCode { SicCode = sicCode1, SicCodeId = 2100, Created = org0.Created, Organisation = org0, OrganisationId = org0.OrganisationId }; org0.OrganisationSicCodes.Add(sic1); var sic2 = new OrganisationSicCode { SicCode = sicCode2, SicCodeId = 10520, Created = org0.Created, Organisation = org0, OrganisationId = org0.OrganisationId }; org0.OrganisationSicCodes.Add(sic2); //Set user email address verified code and expired sent date var routeData = new RouteData(); routeData.Values.Add("Action", nameof(RegistrationController.AddAddress)); routeData.Values.Add("Controller", "Registration"); var controller = UiTestHelper.GetController <RegistrationController>(user.UserId, routeData, user, org0, address0, name, sic1, sic2); var employerResult = new PagedResult <EmployerRecord>(); employerResult.Results = new List <EmployerRecord> { EmployerRecord.Create(org0) }; //use the include and exclude functions here to save typing var model = new OrganisationViewModel { NoReference = false, SearchText = "Searchtext", ManualAddress = true, SelectedAuthorised = true, ManualRegistration = false, SectorType = SectorTypes.Public, PINExpired = false, PINSent = false, SelectedEmployerIndex = 0, Employers = employerResult, //0 record returned ManualEmployers = new List <EmployerRecord>(), ManualEmployerIndex = -1, AddressReturnAction = nameof(RegistrationController.ConfirmOrganisation), ConfirmReturnAction = nameof(RegistrationController.ChooseOrganisation) }; //Stash the object for the unstash to happen in code controller.StashModel(model); OrganisationViewModel savedModel = model.GetClone(); savedModel.Address1 = "Unit 2"; savedModel.Address2 = "Bank Road"; savedModel.Address3 = "Essex"; savedModel.Postcode = "PoStCode 13"; controller.Bind(savedModel); //Set the expected model OrganisationViewModel expectedModel = savedModel.GetClone(); expectedModel.AddressSource = user.EmailAddress; expectedModel.ConfirmReturnAction = nameof(RegistrationController.AddAddress); //ACT: var result = controller.AddAddress(savedModel) as RedirectToActionResult; //ASSERTS: //3.Check that the result is not null Assert.NotNull(result, "Expected RedirectToActionResult"); //4.Check that the redirection went to the right url step. Assert.That(result.ActionName == nameof(RegistrationController.ConfirmOrganisation), "Redirected to the wrong view"); //5.If the redirection successfull retrieve the model stash sent with the redirect. var unstashedModel = controller.UnstashModel <OrganisationViewModel>(); //6.Check that the unstashed model is not null Assert.NotNull(unstashedModel, "Expected OrganisationViewModel"); //Check model is same as expected expectedModel.Compare(unstashedModel); }
public override string SubmitJob(DiscoDataContext Database, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription, Dictionary <string, string> WarrantyProviderProperties) { return(Internal.LWTJobs.SubmitWarrantyJob(Database, Job, Address, TechUser, FaultDescription)); }
public IActionResult ActivateService(CompleteViewModel model) { //Ensure user has completed the registration process User currentUser; IActionResult checkResult = CheckUserRegisteredOk(out currentUser); if (checkResult != null) { return(checkResult); } //Ensure they have entered a PIN if (!ModelState.IsValid) { this.CleanModelErrors <CompleteViewModel>(); return(View("ActivateService", model)); } //Get the user organisation UserOrganisation userOrg = DataRepository.GetAll <UserOrganisation>() .FirstOrDefault(uo => uo.UserId == currentUser.UserId && uo.OrganisationId == ReportingOrganisationId); ActionResult result1; TimeSpan remaining = userOrg.ConfirmAttemptDate == null ? TimeSpan.Zero : userOrg.ConfirmAttemptDate.Value.AddMinutes(Global.LockoutMinutes) - VirtualDateTime.Now; if (userOrg.ConfirmAttempts >= Global.MaxPinAttempts && remaining > TimeSpan.Zero) { return(View("CustomError", new ErrorViewModel(1113, new { remainingTime = remaining.ToFriendly(maxParts: 2) }))); } var updateSearchIndex = false; if (PinMatchesPinInDatabase(userOrg, model.PIN)) { //Set the user org as confirmed userOrg.PINConfirmedDate = VirtualDateTime.Now; //Set the pending organisation to active //Make sure the found organisation is active or pending if (userOrg.Organisation.Status.IsAny(OrganisationStatuses.Pending, OrganisationStatuses.Active)) { userOrg.Organisation.SetStatus( OrganisationStatuses.Active, OriginalUser == null ? currentUser.UserId : OriginalUser.UserId, "PIN Confirmed"); updateSearchIndex = true; } else { CustomLogger.Warning( $"Attempt to PIN activate a {userOrg.Organisation.Status} organisation", $"Organisation: '{userOrg.Organisation.OrganisationName}' Reference: '{userOrg.Organisation.EmployerReference}' User: '******'"); return(View("CustomError", new ErrorViewModel(1149))); } //Retire the old address OrganisationAddress latestAddress = userOrg.Organisation.GetLatestAddress(); if (latestAddress != null && latestAddress.AddressId != userOrg.Address.AddressId) { latestAddress.SetStatus( AddressStatuses.Retired, OriginalUser == null ? currentUser.UserId : OriginalUser.UserId, "Replaced by PIN in post"); updateSearchIndex = true; } //Activate the address the pin was sent to userOrg.Address.SetStatus( AddressStatuses.Active, OriginalUser == null ? currentUser.UserId : OriginalUser.UserId, "PIN Confirmed"); userOrg.ConfirmAttempts = 0; model.AccountingDate = userOrg.Organisation.SectorType.GetAccountingStartDate(); model.OrganisationId = userOrg.OrganisationId; this.StashModel(model); result1 = RedirectToAction("ServiceActivated"); //Send notification email to existing users EmailSendingServiceHelpers.SendUserAddedEmailToExistingUsers(userOrg.Organisation, userOrg.User, emailSendingService); } else { userOrg.ConfirmAttempts++; AddModelError(3015, "PIN"); result1 = View("ActivateService", model); } userOrg.ConfirmAttemptDate = VirtualDateTime.Now; //Save the changes DataRepository.SaveChanges(); //Log the registration auditLogger.AuditChangeToOrganisation( AuditedAction.RegistrationLog, userOrg.Organisation, new { Status = "PIN Confirmed", 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); //Prompt the user with confirmation return(result1); }