Esempio n. 1
0
        public Dictionary <string, string> GetReferences(int i)
        {
            if (ManualEmployers == null || i >= ManualEmployers.Count)
            {
                return(null);
            }

            EmployerRecord employer = ManualEmployers[i];
            var            results  = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            if (!string.IsNullOrWhiteSpace(employer.CompanyNumber))
            {
                results["Company No"] = employer.CompanyNumber;
            }

            foreach (string key in employer.References.Keys)
            {
                if (key.EqualsI(nameof(CharityNumber)))
                {
                    results["Charity No"] = employer.References[nameof(CharityNumber)];
                }
                else if (key.EqualsI(nameof(MutualNumber)))
                {
                    results["Mutual No"] = employer.References[nameof(MutualNumber)];
                }
                else
                {
                    results[key] = employer.References[key];
                }
            }

            return(results);
        }
        public async Task RegistrationController_POST_When_User_Added_To_Organisation_Via_Fast_Track_Then_Email_Existing_Users()
        {
            // Arrange
            var organisationId = 100;

            Core.Entities.Organisation organisation = createPrivateOrganisation(organisationId, "Company1", 12345678);
            User             existingUser1          = CreateUser(1, "*****@*****.**");
            User             existingUser2          = CreateUser(2, "*****@*****.**");
            User             newUser = CreateUser(3, "*****@*****.**");
            UserOrganisation existingUserOrganisation1 = CreateUserOrganisation(organisation, existingUser1.UserId, VirtualDateTime.Now);
            UserOrganisation existingUserOrganisation2 = CreateUserOrganisation(organisation, existingUser2.UserId, VirtualDateTime.Now);
            UserOrganisation newUserOrganisation       = CreateUserOrganisation(organisation, newUser.UserId, VirtualDateTime.Now);

            newUserOrganisation.PINConfirmedDate = null;

            var employers = new PagedResult <EmployerRecord> {
                Results = new List <EmployerRecord>()
            };

            var employer = new EmployerRecord {
                OrganisationId   = organisationId,
                OrganisationName = organisation.OrganisationName,
                CompanyNumber    = organisation.CompanyNumber,
                SectorType       = SectorTypes.Private,
                Address1         = "Address 1",
                Address2         = "Address 2",
                Address3         = "Address 3",
                City             = "City",
                County           = "County",
                Country          = "UK",
                PostCode         = "NW5 1TL",
                PoBox            = "Po Box"
            };

            employers.Results.Add(employer);

            var routeData = new RouteData();

            routeData.Values.Add("Action", "ConfirmOrganisation");
            routeData.Values.Add("Controller", "Registration");

            var controller = UiTestHelper.GetController <RegistrationController>(
                newUser.UserId,
                routeData,
                organisation,
                existingUser1,
                existingUser2,
                newUser,
                existingUserOrganisation1,
                existingUserOrganisation2,
                newUserOrganisation);

            var testModel = new OrganisationViewModel {
                SectorType            = SectorTypes.Private,
                OrganisationName      = organisation.OrganisationName,
                Employers             = employers,
                IsFastTrackAuthorised = true
            };

            controller.StashModel(testModel);

            var mockNotifyEmailQueue = new Mock <IQueue>();

            mockNotifyEmailQueue
            .Setup(q => q.AddMessageAsync(It.IsAny <SendEmailRequest>()));

            // Act
            await controller.ConfirmOrganisation(testModel, "confirm");

            //ASSERT:
            mockNotifyEmailQueue.Verify(
                x => x.AddMessageAsync(It.Is <SendEmailRequest>(inst => inst.EmailAddress.Contains(existingUser1.EmailAddress))),
                Times.Once(),
                "Expected the existingUser1's email address to be in the email send queue");
            mockNotifyEmailQueue.Verify(
                x => x.AddMessageAsync(It.Is <SendEmailRequest>(inst => inst.EmailAddress.Contains(existingUser2.EmailAddress))),
                Times.Once(),
                "Expected the existingUser2's email address to be in the email send queue");
            mockNotifyEmailQueue.Verify(
                x => x.AddMessageAsync(It.Is <SendEmailRequest>(inst => inst.TemplateId.Contains(EmailTemplates.UserAddedToOrganisationEmail))),
                Times.Exactly(2),
                $"Expected the correct templateId to be in the email send queue, expected {EmailTemplates.UserAddedToOrganisationEmail}");
            mockNotifyEmailQueue.Verify(
                x => x.AddMessageAsync(It.Is <SendEmailRequest>(inst => inst.EmailAddress.Contains(newUser.EmailAddress))),
                Times.Never,
                "Do not expect new user's email address to be in the email send queue");
        }
Esempio n. 3
0
        public async Task <IActionResult> AddAddress(OrganisationViewModel model)
        {
            //Ensure user has completed the registration process
            var checkResult = await CheckUserRegisteredOkAsync();

            if (checkResult != null)
            {
                return(checkResult);
            }

            //Make sure we can load employers from session
            var m = UnstashModel <OrganisationViewModel>();

            if (m == null)
            {
                return(View("CustomError", WebService.ErrorViewModelFactory.Create(1112)));
            }

            model.Employers       = m.Employers;
            model.ManualEmployers = m.ManualEmployers;

            //Exclude the contact details
            var excludes = new HashSet <string>();

            excludes.AddRange(
                nameof(model.ContactFirstName),
                nameof(model.ContactLastName),
                nameof(model.ContactJobTitle),
                nameof(model.ContactEmailAddress),
                nameof(model.ContactPhoneNumber));

            //Exclude the organisation details
            excludes.AddRange(
                nameof(model.OrganisationName),
                nameof(model.CompanyNumber),
                nameof(model.CharityNumber),
                nameof(model.MutualNumber),
                nameof(model.OtherName),
                nameof(model.OtherValue));

            //Exclude the search
            excludes.AddRange(nameof(model.SearchText));

            //Exclude the SIC Codes
            excludes.Add(nameof(model.SicCodeIds));

            //Exclude the SIC Codes
            excludes.Add(nameof(model.DUNSNumber));

            //Check model is valid
            ModelState.Exclude(excludes.ToArray());
            if (!ModelState.IsValid)
            {
                this.CleanModelErrors <OrganisationViewModel>();
                return(View(nameof(AddAddress), model));
            }

            var            sector     = model.SectorType;
            var            authorised = false;
            EmployerRecord employer   = null;

            if (!model.ManualRegistration)
            {
                employer = model.GetManualEmployer();

                if (employer != null)
                {
                    authorised = model.ManualAuthorised;
                }
                else
                {
                    employer   = model.GetSelectedEmployer();
                    authorised = model.SelectedAuthorised;
                }
            }

            //Set the address source to the user or original source if unchanged
            if (employer != null && model.GetAddressModel().Equals(employer.GetAddressModel()))
            {
                model.AddressSource = employer.AddressSource;
            }
            else
            {
                model.AddressSource = VirtualUser.EmailAddress;
            }

            if (model.WrongAddress)
            {
                model.ManualAddress = true;
            }

            //When doing manual address only and user is already authorised redirect to confirm page
            if (model.ManualAddress && sector == SectorTypes.Public && authorised && !employer.HasAnyAddress())
            {
                //We don't need contact info if there is no address only when there is an address
                model.ConfirmReturnAction = nameof(AddAddress);
                StashModel(model);
                return(RedirectToAction(nameof(ConfirmOrganisation)));
            }

            //When manual registration
            StashModel(model);
            return(RedirectToAction("AddContact"));
        }
        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 static List <EmployerRecord> SearchEmployers(out int totalRecords, string searchText, int page, int pageSize, bool test = false)
        {
            totalRecords = 0;
            var employers = new List <EmployerRecord>();

            if (test)
            {
                totalRecords = 1;
                var repository = MvcApplication.ContainerIOC.Resolve <IRepository>();
                var min        = repository.GetAll <Organisation>().Count();

                var id       = Extensions.Numeric.Rand(min, int.MaxValue - 1);
                var employer = new EmployerRecord
                {
                    Name          = MvcApplication.TestPrefix + "_Ltd_" + id,
                    CompanyNumber = ("_" + id).Left(10),
                    CompanyStatus = "active",
                    Address1      = "Test Address 1",
                    Address2      = "Test Address 2",
                    Address3      = "Test Address 3",
                    Country       = "Test Country",
                    PostCode      = "Test Post Code",
                    PoBox         = null
                };
                employers.Add(employer);
                return(employers);
            }

            Task <string> task;

            try
            {
                task = Task.Run <string>(async() => await GetCompanies(searchText, page, pageSize));

                dynamic companies = JsonConvert.DeserializeObject(task.Result);
                if (companies != null)
                {
                    totalRecords = companies.total_results;
                    if (totalRecords > 0)
                    {
                        foreach (var company in companies.items)
                        {
                            var employer = new EmployerRecord();
                            employer.Name          = company.title;
                            employer.CompanyNumber = company.company_number;
                            employer.CompanyStatus = company.company_status;

                            var premises = Misc.GetProperty(company.address, "premises");
                            if (!string.IsNullOrWhiteSpace(premises))
                            {
                                employer.Address1 = premises + ", " + company.address.address_line_1;
                            }
                            else
                            {
                                employer.Address1 = company.address.address_line_1;
                            }
                            employer.Address2 = company.address.address_line_2;
                            employer.Address3 = company.address.locality;
                            employer.Country  = company.address.country;
                            employer.PostCode = company.address.postal_code;
                            employer.PoBox    = company.address.po_box;
                            employers.Add(employer);
                        }
                    }
                }
            }
            catch (AggregateException aex)
            {
                var httpEx = aex.InnerException as HttpRequestException;
                if (httpEx != null && httpEx.Message != "Response status code does not indicate success: 404 (Not Found).")
                {
                    throw;
                }
            }
            return(employers);
        }
        public async Task <PagedResult <EmployerRecord> > SearchEmployersAsync(string searchText, int page, int pageSize,
                                                                               bool test = false)
        {
            if (searchText.IsNumber())
            {
                searchText = searchText.PadLeft(8, '0');
            }

            var employersPage = new PagedResult <EmployerRecord>
            {
                PageSize = pageSize, CurrentPage = page, Results = new List <EmployerRecord>()
            };

            if (test)
            {
                employersPage.ActualRecordTotal  = 1;
                employersPage.VirtualRecordTotal = 1;

                var id       = Numeric.Rand(100000, int.MaxValue - 1);
                var employer = new EmployerRecord
                {
                    OrganisationName = SharedOptions.TestPrefix + "_Ltd_" + id,
                    CompanyNumber    = ("_" + id).Left(10),
                    Address1         = "Test Address 1",
                    Address2         = "Test Address 2",
                    City             = "Test Address 3",
                    Country          = "Test Country",
                    PostCode         = "Test Post Code",
                    PoBox            = null
                };
                employersPage.Results.Add(employer);
                return(employersPage);
            }

            //Get the first page of results and the total records, number of pages, and page size
            var   tasks     = new List <Task <PagedResult <EmployerRecord> > >();
            var   page1task = SearchEmployersAsync(searchText, 1, pageSize);
            await page1task;

            //Calculate the maximum page size
            var maxPages = (int)Math.Ceiling((double)MaxRecords / page1task.Result.PageSize);

            maxPages = page1task.Result.PageCount > maxPages ? maxPages : page1task.Result.PageCount;

            //Add a task for ll pages from 2 upwards to maxpages
            for (var subPage = 2; subPage <= maxPages; subPage++)
            {
                tasks.Add(SearchEmployersAsync(searchText, subPage, page1task.Result.PageSize));
            }

            //Wait for all the tasks to complete
            await Task.WhenAll(tasks);

            //Add page 1 to the list of completed tasks
            tasks.Insert(0, page1task);

            //Merge the results from each page into a single page of results
            foreach (var task in tasks)
            {
                employersPage.Results.AddRange(task.Result.Results);
            }

            //Get the toal number of records
            employersPage.ActualRecordTotal  = page1task.Result.ActualRecordTotal;
            employersPage.VirtualRecordTotal = page1task.Result.VirtualRecordTotal;

            return(employersPage);
        }
        private async Task <PagedResult <EmployerRecord> > SearchEmployersAsync(string searchText, int page, int pageSize)
        {
            var employersPage = new PagedResult <EmployerRecord>
            {
                PageSize = pageSize, CurrentPage = page, Results = new List <EmployerRecord>()
            };

            var json = await GetCompaniesAsync(searchText, page, employersPage.PageSize);

            dynamic companies = JsonConvert.DeserializeObject(json);

            if (companies != null)
            {
                employersPage.ActualRecordTotal  = companies.total_results;
                employersPage.VirtualRecordTotal = companies.total_results;
                employersPage.PageSize           = companies.items_per_page;
                if (employersPage.ActualRecordTotal > 0)
                {
                    foreach (var company in companies.items)
                    {
                        var employer = new EmployerRecord();
                        employer.OrganisationName = company.title;
                        employer.NameSource       = "CoHo";
                        employer.CompanyNumber    = company.company_number;
                        if (employer.CompanyNumber.IsNumber())
                        {
                            employer.CompanyNumber = employer.CompanyNumber.PadLeft(8, '0');
                        }

                        var dateOfCessation = ((string)company?.date_of_cessation).ToDateTime();
                        if (dateOfCessation > DateTime.MinValue)
                        {
                            employer.DateOfCessation = dateOfCessation;
                        }

                        var company_type = (string)company?.company_type;
                        if (company.address != null)
                        {
                            string premises     = null,
                                   addressLine1 = null,
                                   addressLine2 = null,
                                   addressLine3 = null,
                                   city         = null,
                                   county       = null,
                                   country      = null,
                                   postalCode   = null,
                                   poBox        = null;
                            if (company.address.premises != null)
                            {
                                premises = ((string)company.address.premises).CorrectNull().TrimI(", ");
                            }

                            if (company.address.care_of != null)
                            {
                                addressLine1 = ((string)company.address.care_of).CorrectNull().TrimI(", ");
                            }

                            if (company.address.address_line_1 != null)
                            {
                                addressLine2 = ((string)company.address.address_line_1).CorrectNull().TrimI(", ");
                            }

                            if (!string.IsNullOrWhiteSpace(premises))
                            {
                                addressLine2 = premises + ", " + addressLine2;
                            }

                            if (company.address.address_line_2 != null)
                            {
                                addressLine3 = ((string)company.address.address_line_2).CorrectNull().TrimI(", ");
                            }

                            if (company.address.locality != null)
                            {
                                city = ((string)company.address.locality).CorrectNull().TrimI(", ");
                            }

                            if (company.address.region != null)
                            {
                                county = ((string)company.address.region).CorrectNull().TrimI(", ");
                            }

                            if (company.address.country != null)
                            {
                                country = ((string)company.address.country).CorrectNull().TrimI(", ");
                            }

                            if (company.address.postal_code != null)
                            {
                                postalCode = ((string)company.address.postal_code).CorrectNull().TrimI(", ");
                            }

                            if (company.address.po_box != null)
                            {
                                poBox = ((string)company.address.po_box).CorrectNull().TrimI(", ");
                            }

                            var addresses = new List <string>();
                            if (!string.IsNullOrWhiteSpace(addressLine1))
                            {
                                addresses.Add(addressLine1);
                            }

                            if (!string.IsNullOrWhiteSpace(addressLine2) && !addresses.ContainsI(addressLine2))
                            {
                                addresses.Add(addressLine2);
                            }

                            if (!string.IsNullOrWhiteSpace(addressLine3) && !addresses.ContainsI(addressLine3))
                            {
                                addresses.Add(addressLine3);
                            }

                            employer.Address1 = addresses.Count > 0 ? addresses[0] : null;
                            employer.Address2 = addresses.Count > 1 ? addresses[1] : null;
                            employer.Address3 = addresses.Count > 2 ? addresses[2] : null;

                            employer.City          = city;
                            employer.County        = county;
                            employer.Country       = country;
                            employer.PostCode      = postalCode;
                            employer.PoBox         = poBox;
                            employer.AddressSource = "CoHo";
                        }

                        employersPage.Results.Add(employer);
                    }
                }
            }

            return(employersPage);
        }