Example #1
0
        /// <summary>
        /// This test ensures that the OnActionExecuting filter doesn't interupt the action when the configuration
        /// has data returns enabled, the specified "pcsId" parameter is for a non-approved scheme and the user
        /// is requesting the "AuthorisationRequired" action. This prevents an infinite loop from occuring.
        /// </summary>
        public void OnActionExecuting_ConfigEnabledAndSpecifiedSchemeIsNotApprovedAndActionIsAuthorisationRequired_DoesNothing()
        {
            // Arrange
            IAppConfiguration configuration = A.Fake <IAppConfiguration>();

            A.CallTo(() => configuration.EnableDataReturns).Returns(true);

            ConfigurationService configurationService = A.Fake <ConfigurationService>();

            A.CallTo(() => configurationService.CurrentConfiguration).Returns(configuration);

            IWeeeClient weeeClient = A.Fake <IWeeeClient>();

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <VerifyOrganisationExists> ._))
            .WhenArgumentsMatch(a => a.Get <VerifyOrganisationExists>("request").OrganisationId == new Guid("51254A73-D885-4F9A-BC47-2787CB1416B9"))
            .Returns(true);

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <GetSchemeStatus> ._))
            .WhenArgumentsMatch(a => a.Get <GetSchemeStatus>("request").PcsId == new Guid("51254A73-D885-4F9A-BC47-2787CB1416B9"))
            .Returns(SchemeStatus.Pending);

            DataReturnsController controller = new DataReturnsController(
                () => weeeClient,
                A.Dummy <IWeeeCache>(),
                A.Dummy <BreadcrumbService>(),
                A.Dummy <CsvWriterFactory>(),
                A.Dummy <IMapper>(),
                configurationService);

            // Act
            ActionDescriptor actionDescriptor = A.Fake <ActionDescriptor>();

            A.CallTo(() => actionDescriptor.ActionName == "AuthorisationRequired");

            ActionExecutingContext actionExecutingContext = new ActionExecutingContext();

            actionExecutingContext.ActionParameters          = new Dictionary <string, object>();
            actionExecutingContext.ActionParameters["pcsId"] = new Guid("51254A73-D885-4F9A-BC47-2787CB1416B9");
            actionExecutingContext.ActionDescriptor          = actionDescriptor;

            MethodInfo onActionExecutingMethod = typeof(DataReturnsController).GetMethod(
                "OnActionExecuting",
                BindingFlags.NonPublic | BindingFlags.Instance);

            Action testCode = () =>
            {
                object[] args = new object[] { actionExecutingContext };
                try
                {
                    onActionExecutingMethod.Invoke(controller, args);
                }
                catch (TargetInvocationException ex)
                {
                    throw ex.InnerException;
                }
            };

            // Assert
            Assert.Null(actionExecutingContext.Result);
        }
Example #2
0
        public async void IndexGet_GivenValidViewModel_BreadcrumbShouldBeSet()
        {
            var          organisationId = Guid.NewGuid();
            const string orgName        = "orgName";

            var @return       = A.Fake <ReturnData>();
            var quarterData   = new Quarter(2019, QuarterType.Q1);
            var quarterWindow = QuarterWindowTestHelper.GetDefaultQuarterWindow();
            var aatfInfo      = A.Fake <AatfData>();
            var aatfId        = Guid.NewGuid();

            const string reportingQuarter = "2019 Q1 Jan - Mar";
            const string reportingPeriod  = "Test (WEE/QW1234RE/ATF)";

            @return.Quarter       = quarterData;
            @return.QuarterWindow = quarterWindow;
            const string aatfName = "Test";

            aatfInfo.ApprovalNumber = "WEE/QW1234RE/ATF";

            A.CallTo(() => cache.FetchOrganisationName(organisationId)).Returns(orgName);

            A.CallTo(() => apiClient.SendAsync(A <string> ._, A <GetReturn> ._)).Returns(@return);
            A.CallTo(() => cache.FetchAatfData(organisationId, aatfId)).Returns(aatfInfo);
            A.CallTo(() => aatfInfo.Name).Returns(aatfName);

            await controller.Index(organisationId, A.Dummy <Guid>(), aatfId, A.Dummy <Guid>());

            breadcrumb.ExternalActivity.Should().Be(BreadCrumbConstant.AatfReturn);
            breadcrumb.ExternalOrganisation.Should().Be(orgName);
            breadcrumb.OrganisationId.Should().Be(organisationId);

            Assert.Contains(reportingQuarter, breadcrumb.QuarterDisplayInfo);
            Assert.Contains(reportingPeriod, breadcrumb.AatfDisplayInfo);
        }
Example #3
0
        public async void IndexGet_GivenReturn_ApiShouldBeCalledWithReturnRequest()
        {
            var returnId = Guid.NewGuid();

            await controller.Index(returnId);

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <GetReturn> .That.Matches(g => g.ReturnId.Equals(returnId))))
            .MustHaveHappened(Repeated.Exactly.Once);
        }
Example #4
0
        public async void IndexGet_GivenActionExecutes_ApiShouldBeCalled()
        {
            var returnId = Guid.NewGuid();

            await controller.Index(returnId, A.Dummy <Guid>(), A.Dummy <Guid>(), A.Dummy <ObligatedType>());

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <GetReturn> .That.Matches(r => r.ReturnId.Equals(returnId))))
            .MustHaveHappened(Repeated.Exactly.Once);
        }
Example #5
0
        public async void IndexPost_GivenValidViewModel_ApiSendShouldBeCalled()
        {
            var model   = new ObligatedViewModel(calculator);
            var request = new AddObligatedReused();

            A.CallTo(() => requestCreator.ViewModelToRequest(model)).Returns(request);

            await controller.Index(model);

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, request)).MustHaveHappened(Repeated.Exactly.Once);
        }
Example #6
0
        public void PostIndex_InvokeApi()
        {
            // Arrange
            var controller = TestEmailController();

            // Act
            var result = controller.Index(A.Dummy <TestEmailViewModel>());

            // Assert
            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <SendTestEmail> ._))
            .MustHaveHappened();
        }
Example #7
0
        public async void IndexGet_GivenOrganisationId_ApiShouldBeCalled()
        {
            var organisationId = Guid.NewGuid();
            var model          = new HomeViewModel()
            {
                AatfList = A.Fake <List <AatfData> >()
            };

            A.CallTo(() => mapper.Map(A <AatfDataToHomeViewModelMapTransfer> ._)).Returns(model);

            await controller.Index(organisationId, fixture.Create <FacilityType>());

            A.CallTo(() => apiClient.SendAsync(A <string> ._, A <GetAatfByOrganisation> .That.Matches(w => w.OrganisationId == organisationId))).MustHaveHappened(Repeated.Exactly.Once);
        }
        public void RuleFor_RequestReturnsTrue_IsValidShouldBeFalse()
        {
            var exists    = true;
            var viewModel = new AddAatfViewModel()
            {
                ApprovalNumber = "WEE/AZ1234AZ/ATF"
            };

            A.CallTo(() => apiClient.SendAsync(A <string> ._, A <CheckApprovalNumberIsUnique> .That.Matches(c => c.ApprovalNumber == viewModel.ApprovalNumber))).Returns(exists);

            var validationResult = validator.Validate(viewModel);

            validationResult.IsValid.Should().Be(false);
        }
        public void OnActionExecuting_NoAATFs_ArgumentExceptionExpected()
        {
            Action action = () => attribute.OnActionExecuting(context);

            Guid orgId = Guid.NewGuid();

            var routeData = new RouteData();

            routeData.Values.Add("organisationId", orgId);

            A.CallTo(() => context.RouteData).Returns(routeData);
            A.CallTo(() => client.SendAsync(A <string> ._, new GetAatfByOrganisationFacilityType(orgId, FacilityType.Aatf))).Returns(new List <AatfData>());

            action.Should().Throw <InvalidOperationException>().WithMessage("No AATF found for this organisation.");
        }
Example #10
0
        public async void OnActionExecuting_GivenOrganisationHasAScheme_ShouldBeRedirectedToManageSchemes()
        {
            SchemeData schemeData = new SchemeData();

            Guid organisationId = (Guid)context.ActionParameters["organisationId"];

            A.CallTo(() => client.SendAsync(A <string> ._,
                                            A <GetSchemeByOrganisationId> .That.Matches(r => r.OrganisationId.Equals(organisationId)))).Returns(schemeData);

            await attribute.OnAuthorizationAsync(context, organisationId);

            RedirectResult result = context.Result as RedirectResult;

            result.Url.Should().Be("~/admin/scheme/manage-schemes");
        }
Example #11
0
        private async Task <T> PopulateFacilityViewModelLists <T>(T viewModel, IList <CountryData> countries, IWeeeClient client, string accessToken)
            where T : FacilityViewModelBase
        {
            viewModel.SiteAddressData.Countries = countries;
            viewModel.CompetentAuthoritiesList  = await client.SendAsync(accessToken, new GetUKCompetentAuthorities());

            viewModel.PanAreaList = await client.SendAsync(accessToken, new GetPanAreas());

            viewModel.LocalAreaList = await client.SendAsync(accessToken, new GetLocalAreas());

            viewModel.SizeList   = Enumeration.GetAll <AatfSize>();
            viewModel.StatusList = Enumeration.GetAll <AatfStatus>();

            return(viewModel);
        }
        public async void IndexGet_GivenValidViewModel_BreadcrumbShouldBeSet()
        {
            var @return = fixture.Build <ReturnData>()
                          .With(r => r.Quarter, new Quarter(2019, QuarterType.Q1))
                          .With(r => r.QuarterWindow, QuarterWindowTestHelper.GetDefaultQuarterWindow())
                          .Create();

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <GetReturn> ._)).Returns(@return);

            SystemTime.Freeze(new DateTime(2019, 04, 01));
            await controller.Index(A.Dummy <Guid>());

            SystemTime.Unfreeze();

            Assert.Equal(breadcrumb.ExternalActivity, BreadCrumbConstant.AatfReturn);
        }
Example #13
0
        public async Task <ActionResult> ManagePendingCharges(CompetentAuthority authority, FormCollection formCollection)
        {
            using (IWeeeClient client = weeeClient())
            {
                IssuePendingCharges       request = new IssuePendingCharges(authority);
                IssuePendingChargesResult result  = await client.SendAsync(User.GetAccessToken(), request);

                if (Request.IsAjaxRequest())
                {
                    var jsonResult = new
                    {
                        Success      = result.Errors.Count == 0,
                        InvoiceRunId = result.InvoiceRunId,
                        Errors       = result.Errors
                    };
                    return(Json(jsonResult));
                }
                else
                {
                    if (result.Errors.Count == 0)
                    {
                        return(RedirectToAction("ChargesSuccessfullyIssued", new { authority, id = result.InvoiceRunId.Value }));
                    }
                    else
                    {
                        return(View("IssueChargesError", result.Errors));
                    }
                }
            }
        }
Example #14
0
        public async Task GetDownloadEeeWeeeData_Always_CallsApiAndReturnsFileContents()
        {
            // Arrange
            Guid organisationId = new Guid("ADED8BDE-CF03-4696-B972-DDAB9306A6DD");

            FileInfo fileInfo = new FileInfo("Test file.csv", A.Dummy <byte[]>());

            IWeeeClient client = A.Fake <IWeeeClient>();

            A.CallTo(() => client.SendAsync(A <string> ._, A <FetchSummaryCsv> ._))
            .WhenArgumentsMatch(a => a.Get <FetchSummaryCsv>("request").OrganisationId == organisationId &&
                                a.Get <FetchSummaryCsv>("request").ComplianceYear == 2017)
            .Returns(fileInfo);

            DataReturnsController controller = new DataReturnsController(
                () => client,
                A.Dummy <IWeeeCache>(),
                A.Dummy <BreadcrumbService>(),
                A.Dummy <CsvWriterFactory>(),
                A.Dummy <IMapper>(),
                A.Dummy <ConfigurationService>());

            // Act
            ActionResult result = await controller.DownloadEeeWeeeData(organisationId, 2017);

            // Assert
            FileResult fileResult = result as FileResult;

            Assert.NotNull(fileResult);

            Assert.Equal("Test file.csv", fileResult.FileDownloadName);
        }
        public async void GetConfirmRemoval_ReturnsHttpForbiddenResult_WhenCanRemoveProducerIsFalse()
        {
            // Arrange
            IWeeeClient weeeClient = A.Fake <IWeeeClient>();

            ProducersController controller = new ProducersController(
                A.Dummy <BreadcrumbService>(),
                A.Dummy <ISearcher <ProducerSearchResult> >(),
                () => weeeClient,
                A.Dummy <IWeeeCache>(),
                configurationService);

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <GetProducerDetailsByRegisteredProducerId> ._))
            .Returns(
                new ProducerDetailsScheme
            {
                CanRemoveProducer = false
            });

            // Act
            var result = await controller.ConfirmRemoval(A.Dummy <Guid>());

            // Assert
            Assert.IsType <HttpForbiddenResult>(result);
        }
        public async void HttpGet_DownloadProducerEeeHistoryCsv_ShouldReturnFileContentType()
        {
            // Arrange
            BreadcrumbService breadcrumb = A.Dummy <BreadcrumbService>();
            ISearcher <ProducerSearchResult> producerSearcher = A.Dummy <ISearcher <ProducerSearchResult> >();
            IWeeeClient weeeClient = A.Fake <IWeeeClient>();
            CSVFileData csvData    = A.Dummy <CSVFileData>();

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <GetProducerEeeDataHistoryCsv> ._))
            .Returns(new CSVFileData
            {
                FileName    = "test.csv",
                FileContent = "123,abc"
            });

            Func <IWeeeClient> weeeClientFunc = A.Fake <Func <IWeeeClient> >();

            A.CallTo(() => weeeClientFunc())
            .Returns(weeeClient);

            ProducersController controller = new ProducersController(breadcrumb, producerSearcher, weeeClientFunc, cache, configurationService);

            //Act
            var result = await controller.DownloadProducerEeeDataHistoryCsv("WEE/AA1111AA");

            //Assert
            Assert.IsType <FileContentResult>(result);
        }
Example #17
0
 private async Task <OrganisationSearchDataResult> FetchOrganisations(string companyName, int?page)
 {
     using (IWeeeClient client = apiClient())
     {
         return(await client.SendAsync(User.GetAccessToken(), new FindMatchingOrganisations(companyName)));
     }
 }
Example #18
0
        public async Task GetDownloadIssuedChargesCsv_Always_CallsApiAndReturnsFileResultWithCorrectFileName()
        {
            // Arrange
            CompetentAuthority authority = A.Dummy <CompetentAuthority>();
            int  complianceYear          = A.Dummy <int>();
            Guid schemeId = A.Dummy <Guid>();

            IWeeeClient weeeClient = A.Fake <IWeeeClient>();

            FileInfo fileInfo = new FileInfo("filename", new byte[] { 1, 2, 3 });

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <FetchIssuedChargesCsv> ._))
            .WhenArgumentsMatch(a => a.Get <FetchIssuedChargesCsv>("request").Authority == authority &&
                                a.Get <FetchIssuedChargesCsv>("request").ComplianceYear == complianceYear &&
                                a.Get <FetchIssuedChargesCsv>("request").SchemeId == schemeId)
            .Returns(fileInfo);

            ChargeController controller = new ChargeController(
                A.Dummy <IAppConfiguration>(),
                A.Dummy <BreadcrumbService>(),
                () => weeeClient);

            // Act
            ActionResult result = await controller.DownloadIssuedChargesCsv(authority, complianceYear, schemeId);

            // Assert
            FileResult fileResult = result as FileResult;

            Assert.NotNull(fileResult);

            Assert.Equal("filename", fileResult.FileDownloadName);
        }
Example #19
0
        public async Task PostManagePendingCharges_NonAjaxWithNoError_CallsApiAndRedirectsToChargesSuccessfullyIssuedActionWithAuthorityAndInvoiceRunId()
        {
            Guid invoiceRunId = new Guid("FB95F6E7-8809-488A-B23B-5B3F5A9B3D5F");

            IWeeeClient weeeClient = A.Fake <IWeeeClient>();

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <IssuePendingCharges> ._))
            .Returns(new IssuePendingChargesResult {
                Errors = new List <string>(), InvoiceRunId = invoiceRunId
            });

            // Arrange
            ChargeController controller = new ChargeController(
                A.Dummy <IAppConfiguration>(),
                A.Dummy <BreadcrumbService>(),
                () => weeeClient);

            HttpContextBase httpContext = A.Fake <HttpContextBase>();
            HttpRequestBase httpRequest = A.Fake <HttpRequestBase>();

            A.CallTo(() => httpContext.Request).Returns(httpRequest);
            controller.ControllerContext = new ControllerContext(httpContext, new RouteData(), controller);

            // Act
            ActionResult result = await controller.ManagePendingCharges(CompetentAuthority.NorthernIreland, A.Dummy <FormCollection>());

            // Assert
            RedirectToRouteResult redirectResult = result as RedirectToRouteResult;

            Assert.NotNull(redirectResult);

            Assert.Equal("ChargesSuccessfullyIssued", redirectResult.RouteValues["action"]);
            Assert.Equal(CompetentAuthority.NorthernIreland, redirectResult.RouteValues["authority"]);
            Assert.Equal(invoiceRunId, redirectResult.RouteValues["id"]);
        }
Example #20
0
 private async Task <bool> CheckOrganisationExists(Guid organisationID)
 {
     using (IWeeeClient client = apiClient())
     {
         return(await client.SendAsync(User.GetAccessToken(), new VerifyOrganisationExists(organisationID)));
     }
 }
Example #21
0
        public async Task <ActionResult> AuthorisationRequired(Guid pcsId)
        {
            using (IWeeeClient client = apiClient())
            {
                SchemeStatus status = await client.SendAsync(User.GetAccessToken(), new GetSchemeStatus(pcsId));

                if (status == SchemeStatus.Approved)
                {
                    return(RedirectToAction("Index", new { pcsId }));
                }

                string userIdString = User.GetUserId();
                bool   showLinkToSelectOrganisation = false;

                if (userIdString != null)
                {
                    Guid userId = new Guid(userIdString);

                    int activeUserCompleteOrganisationCount = await cache.FetchUserActiveCompleteOrganisationCount(userId);

                    showLinkToSelectOrganisation = (activeUserCompleteOrganisationCount > 1);
                }

                await SetBreadcrumb(pcsId);

                return(View(new AuthorizationRequiredViewModel
                {
                    Status = status,
                    ShowLinkToSelectOrganisation = showLinkToSelectOrganisation
                }));
            }
        }
Example #22
0
        public async Task GetDownloadInvoiceFiles_ForEngland_CallsApiAndReturnsFileResult()
        {
            // Arrange
            Guid invoiceRunId = new Guid("ADED8BDE-CF03-4696-B972-DDAB9306A6DD");

            FileInfo fileInfo = new FileInfo("Test file.zip", A.Dummy <byte[]>());

            IWeeeClient weeeClient = A.Fake <IWeeeClient>();

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <FetchInvoiceRunIbisZipFile> ._))
            .WhenArgumentsMatch(a => a.Get <FetchInvoiceRunIbisZipFile>("request").InvoiceRunId == invoiceRunId)
            .Returns(fileInfo);

            ChargeController controller = new ChargeController(
                A.Dummy <IAppConfiguration>(),
                A.Dummy <BreadcrumbService>(),
                () => weeeClient);

            // Act
            ActionResult result = await controller.DownloadInvoiceFiles(
                CompetentAuthority.England,
                invoiceRunId);

            // Assert
            FileResult fileResult = result as FileResult;

            Assert.NotNull(fileResult);

            Assert.Equal("Test file.zip", fileResult.FileDownloadName);
            Assert.Equal("text/plain", fileResult.ContentType);
        }
Example #23
0
        public async Task GetDownloadChargeBreakdown_CallsApiAndReturnsFileResult()
        {
            // Arrange
            Guid invoiceRunId = Guid.NewGuid();

            var csvFileData = new CSVFileData {
                FileName = "Test file.csv", FileContent = "CSV content"
            };

            IWeeeClient weeeClient = A.Fake <IWeeeClient>();

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <FetchInvoiceRunCsv> ._))
            .WhenArgumentsMatch(a => a.Get <FetchInvoiceRunCsv>("request").InvoiceRunId == invoiceRunId)
            .Returns(csvFileData);

            ChargeController controller = new ChargeController(
                A.Dummy <IAppConfiguration>(),
                A.Dummy <BreadcrumbService>(),
                () => weeeClient);

            // Act
            ActionResult result = await controller.DownloadChargeBreakdown(invoiceRunId);

            // Assert
            FileResult fileResult = result as FileResult;

            Assert.NotNull(fileResult);

            Assert.Equal("Test file.csv", fileResult.FileDownloadName);
            Assert.Equal("text/csv", fileResult.ContentType);
        }
Example #24
0
        public async Task GetInvoiceRuns_ForDevolvedAuthority_ReturnsInvoiceRunsViewWithModelNotAllowingInvoiceDownload()
        {
            // Arrange
            IReadOnlyList <InvoiceRunInfo> results = A.Dummy <IReadOnlyList <InvoiceRunInfo> >();

            IWeeeClient weeeClient = A.Fake <IWeeeClient>();

            A.CallTo(() => weeeClient.SendAsync(A <FetchInvoiceRuns> ._)).Returns(results);

            ChargeController controller = new ChargeController(
                A.Dummy <IAppConfiguration>(),
                A.Dummy <BreadcrumbService>(),
                () => weeeClient);

            // Act
            ActionResult result = await controller.InvoiceRuns(CompetentAuthority.Scotland);

            // Assert
            ViewResult viewResult = result as ViewResult;

            Assert.NotNull(viewResult);

            Assert.True(viewResult.ViewName == string.Empty || viewResult.ViewName == "InvoiceRuns");

            IReadOnlyList <InvoiceRunInfo> viewModel = viewResult.Model as IReadOnlyList <InvoiceRunInfo>;

            Assert.NotNull(viewModel);
            Assert.Equal(results, viewModel);
            Assert.Equal(false, viewResult.ViewBag.AllowDownloadOfInvoiceFiles);
        }
Example #25
0
        public async Task GetDownloadInvoiceFiles_ForDevolvedAuthority_ThowsInvalidOperationException()
        {
            // Arrange
            Guid invoiceRunId = new Guid("ADED8BDE-CF03-4696-B972-DDAB9306A6DD");

            FileInfo fileInfo = new FileInfo("Test file.zip", A.Dummy <byte[]>());

            IWeeeClient weeeClient = A.Fake <IWeeeClient>();

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <FetchInvoiceRunIbisZipFile> ._))
            .WhenArgumentsMatch(a => a.Get <FetchInvoiceRunIbisZipFile>("request").InvoiceRunId == invoiceRunId)
            .Returns(fileInfo);

            ChargeController controller = new ChargeController(
                A.Dummy <IAppConfiguration>(),
                A.Dummy <BreadcrumbService>(),
                () => weeeClient);

            // Act
            Func <Task <ActionResult> > testCode = async() => await controller.DownloadInvoiceFiles(
                CompetentAuthority.Scotland,
                invoiceRunId);

            // Assert
            await Assert.ThrowsAsync <InvalidOperationException>(testCode);
        }
Example #26
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Ensure that Data Returns are enabled.
            if (!configService.CurrentConfiguration.EnableDataReturns)
            {
                throw new InvalidOperationException("Data returns are not enabled.");
            }

            // Ensure a organisation ID has been provided and that the organisation exists.
            object organisationIdActionParameter;

            if (!filterContext.ActionParameters.TryGetValue("pcsId", out organisationIdActionParameter))
            {
                throw new ArgumentException("No organisation ID was specified.");
            }

            if (!(organisationIdActionParameter is Guid))
            {
                throw new ArgumentException("The specified organisation ID is not valid.");
            }

            Guid organisationId = (Guid)organisationIdActionParameter;

            bool organisationExists;

            using (IWeeeClient client = apiClient())
            {
                Task <bool> task = Task.Run(() => client.SendAsync(User.GetAccessToken(), new VerifyOrganisationExists(organisationId)));
                task.Wait();
                organisationExists = task.Result;
            }

            if (!organisationExists)
            {
                throw new ArgumentException(string.Format("'{0}' is not a valid organisation Id.", organisationId));
            }

            /* Check whether the scheme representing the organisation has a status of "Approved".
             * If not, redirect the user to the "AuthorisationRequired" action (unless they are
             * already executing that action).
             */
            if (filterContext.ActionDescriptor.ActionName != "AuthorisationRequired")
            {
                SchemeStatus status;
                using (IWeeeClient client = apiClient())
                {
                    Task <SchemeStatus> schemeStatusTask = Task.Run(() => client.SendAsync(User.GetAccessToken(), new GetSchemeStatus(organisationId)));
                    schemeStatusTask.Wait();
                    status = schemeStatusTask.Result;
                }

                if (status != SchemeStatus.Approved)
                {
                    filterContext.Result = RedirectToAction("AuthorisationRequired", new { organisationId });
                    return;
                }
            }

            base.OnActionExecuting(filterContext);
        }
Example #27
0
        public async void HttpGet_Index_IfUserIsNotActive_ShouldRedirectToInternalUserAuthorizationRequired(
            UserStatus userStatus)
        {
            A.CallTo(() => apiClient.SendAsync(A <string> ._, A <IRequest <UserStatus> > ._))
            .Returns(userStatus);

            var result = await HomeController().Index();

            Assert.IsType <RedirectToRouteResult>(result);

            var routeValues = ((RedirectToRouteResult)result).RouteValues;

            Assert.Equal("InternalUserAuthorisationRequired", routeValues["action"]);
            Assert.Equal("Account", routeValues["controller"]);
            Assert.Equal(userStatus, routeValues["userStatus"]);
        }
        public async void GetConfirmRemoval_ReturnsConfirmRemovalView_WhenCanRemoveProducerIsTrue()
        {
            // Arrange
            IWeeeClient weeeClient = A.Fake <IWeeeClient>();

            ProducersController controller = new ProducersController(
                A.Dummy <BreadcrumbService>(),
                A.Dummy <ISearcher <ProducerSearchResult> >(),
                () => weeeClient,
                A.Dummy <IWeeeCache>(),
                configurationService);

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <GetProducerDetailsByRegisteredProducerId> ._))
            .Returns(
                new ProducerDetailsScheme
            {
                CanRemoveProducer = true
            });

            // Act
            ActionResult result = await controller.ConfirmRemoval(A.Dummy <Guid>());

            // Assert
            ViewResult viewResult = result as ViewResult;

            Assert.NotNull(viewResult);

            Assert.True(string.IsNullOrEmpty(viewResult.ViewName) || viewResult.ViewName.ToLowerInvariant() == "confirmremoval");
        }
Example #29
0
        public async Task <ActionResult> FetchDetails(string registrationNumber, int complianceYear)
        {
            if (Request != null &&
                !Request.IsAjaxRequest())
            {
                throw new InvalidOperationException();
            }

            if (!ModelState.IsValid)
            {
                return(Json(null, JsonRequestBehavior.AllowGet));
            }

            using (IWeeeClient client = apiClient())
            {
                await SetBreadcrumb();

                GetProducerDetails request = new GetProducerDetails()
                {
                    RegistrationNumber = registrationNumber,
                    ComplianceYear     = complianceYear
                };

                ProducerDetails producerDetails = await client.SendAsync(User.GetAccessToken(), request);

                return(PartialView("_detailsResults", producerDetails));
            }
        }
Example #30
0
 private async Task <ProducerDetailsScheme> FetchProducerDetailsScheme(Guid registeredProducerId)
 {
     using (IWeeeClient client = apiClient())
     {
         GetProducerDetailsByRegisteredProducerId request = new GetProducerDetailsByRegisteredProducerId(registeredProducerId);
         return(await client.SendAsync(User.GetAccessToken(), request));
     }
 }
        private async Task<OrganisationData> GetOrganisation(Guid? organisationId, IWeeeClient client)
        {
            var organisationExistsAndIncomplete =
                await client.SendAsync(User.GetAccessToken(), new VerifyOrganisationExistsAndIncomplete(organisationId.Value));

            if (!organisationExistsAndIncomplete)
            {
                throw new ArgumentException("No organisation found for supplied organisation Id with Incomplete status",
                    "organisationId");
            }

            var organisation = await client.SendAsync(User.GetAccessToken(), new GetOrganisationInfo(organisationId.Value));
            return organisation;
        }
 private async Task AddAddressToOrganisation(AddressViewModel model, AddressType type, IWeeeClient client)
 {
     var request = model.ToAddRequest(type);
     await client.SendAsync(User.GetAccessToken(), request);
 }
        private async Task<AddressPrepopulateViewModel> GetAddressPrepopulateViewModel(Guid organisationId, IWeeeClient client)
        {
            var organisation = await client.SendAsync(User.GetAccessToken(), new GetOrganisationInfo(organisationId));
            var model = new AddressPrepopulateViewModel
            {
                OrganisationId = organisationId,
                OrganisationType = organisation.OrganisationType,
            };

            return model;
        }
        private async Task<AddressViewModel> GetAddressViewModel(Guid organisationId, IWeeeClient client, bool regionsOfUKOnly, AddressType addressType)
        {
            // Check the organisation Id is valid
            var organisation = await client.SendAsync(User.GetAccessToken(), new GetOrganisationInfo(organisationId));
            var model = new AddressViewModel
            {
                OrganisationId = organisationId,
                OrganisationType = organisation.OrganisationType,
            };

            if (addressType == AddressType.OrganisationAddress)
            {
                if (organisation.HasOrganisationAddress)
                {
                    model.Address = organisation.OrganisationAddress;
                }
            }
            else if (addressType == AddressType.RegisteredOrPPBAddress)
            {
                if (organisation.HasBusinessAddress)
                {
                    model.Address = organisation.BusinessAddress;
                }
            }
            else if (addressType == AddressType.ServiceOfNotice)
            {
                if (organisation.HasNotificationAddress)
                {
                    model.Address = organisation.NotificationAddress;
                }
            }

            model.Address.Countries = await GetCountries(regionsOfUKOnly);
            return model;
        }