public static OrganisationViewModel FromEnrichmentModel(UcasProviderEnrichmentGetModel ucasProviderEnrichmentGetModel, List <TrainingProviderViewModel> aboutAccreditingTrainingProviders, ProviderSummary providerSummary)
        {
            ucasProviderEnrichmentGetModel = ucasProviderEnrichmentGetModel ?? new UcasProviderEnrichmentGetModel {
                EnrichmentModel = new ProviderEnrichmentModel()
                {
                    AccreditingProviderEnrichments = new List <AccreditingProviderEnrichment>()
                }
            };

            var enrichmentModel = ucasProviderEnrichmentGetModel.EnrichmentModel;

            var result = new OrganisationViewModel
            {
                ProviderCode              = providerSummary.ProviderCode,
                ProviderName              = providerSummary.ProviderName,
                TrainWithUs               = enrichmentModel.TrainWithUs,
                TrainWithDisability       = enrichmentModel.TrainWithDisability,
                LastPublishedTimestampUtc = ucasProviderEnrichmentGetModel.LastPublishedTimestampUtc,
                Status = ucasProviderEnrichmentGetModel.Status,
                AboutTrainingProviders = aboutAccreditingTrainingProviders,

                Addr1        = enrichmentModel.Address1,
                Addr2        = enrichmentModel.Address2,
                Addr3        = enrichmentModel.Address3,
                Addr4        = enrichmentModel.Address4,
                Postcode     = enrichmentModel.Postcode,
                Url          = enrichmentModel.Website,
                Telephone    = enrichmentModel.Telephone,
                EmailAddress = enrichmentModel.Email
            };

            return(result);
        }
        private async Task <ActionResult> PublishOrgansation(UcasProviderEnrichmentGetModel ucasProviderEnrichmentGetModel, string providerCode)
        {
            var providerSummary = await _manageApi.GetProviderSummary(providerCode);

            var enrichmentModel = ucasProviderEnrichmentGetModel.EnrichmentModel;
            var aboutAccreditingTrainingProviders = await MergeTrainingProviderViewModels(providerCode, enrichmentModel);

            var model = OrganisationViewModel.FromEnrichmentModel(ucasProviderEnrichmentGetModel, aboutAccreditingTrainingProviders, providerSummary);

            ValidateModelForPublication(model);

            if (!ModelState.IsValid)
            {
                return(View("Details", model));
            }
            else
            {
                var result = await _manageApi.PublishAllCoursesOfProviderToSearchAndCompare(providerCode);

                if (result)
                {
                    TempData["MessageType"]  = "success";
                    TempData["MessageTitle"] = "Your changes have been published – this content will appear on all of your course pages";

                    return(RedirectToAction("Details", new { providerCode = providerCode }));
                }
                else
                {
                    // This is a no ops, there should not be any viable valid reason that api rejects, hence dead end.
                    throw new InvalidOperationException("attempting to publish nonexistent organisation enrichment: " + providerCode);
                }
            }
        }
        /// <summary>
        /// maps enrichment data from the data object to the returned enrichment model
        /// </summary>
        /// <param name="source">enrichment data object</param>
        /// <returns>enrichment model with enrichment data (if found). Null if there is no source record</returns>
        public UcasProviderEnrichmentGetModel Convert(ProviderEnrichment source)
        {
            if (source == null)
            {
                return(null);
            }

            var enrichmentToReturn = new UcasProviderEnrichmentGetModel();
            var enrichmentModel    = source.JsonData != null?JsonConvert.DeserializeObject <ProviderEnrichmentModel>(source.JsonData, _jsonSerializerSettings) : null;

            enrichmentToReturn.EnrichmentModel           = enrichmentModel;
            enrichmentToReturn.CreatedTimestampUtc       = source.CreatedAt;
            enrichmentToReturn.UpdatedTimestampUtc       = source.UpdatedAt;
            enrichmentToReturn.CreatedByUserId           = source.CreatedByUser.Id;
            enrichmentToReturn.UpdatedByUserId           = source.UpdatedByUser.Id;
            enrichmentToReturn.LastPublishedTimestampUtc = source.LastPublishedAt;
            enrichmentToReturn.Status = source.Status;
            return(enrichmentToReturn);
        }
        public void AboutPost_ModelState_WordCount()
        {
            var providerCode   = "PROVIDERCODE";
            var exceed100Words = "";

            for (int i = 0; i < 101; i++)
            {
                exceed100Words += i + " ";
            }
            var providerName = "ProviderName";

            var viewModel = new OrganisationViewModelForAbout
            {
                AboutTrainingProviders = new List <TrainingProviderViewModel>()
                {
                    new TrainingProviderViewModel {
                        Description  = exceed100Words,
                        ProviderName = providerName,
                        ProviderCode = providerCode + 1
                    }
                }
            };

            var providerCourses = new List <Course>
            {
                new Course {
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode.ToUpperInvariant()
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode.ToLowerInvariant()
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode + 1, ProviderName = providerName
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode + 2
                    }
                },
            };

            var apiMock = new Mock <IManageApi>();

            apiMock.Setup(x => x.GetCoursesOfProvider(providerCode))
            .ReturnsAsync(providerCourses);


            var enrichmentModel = new ProviderEnrichmentModel {
                AccreditingProviderEnrichments = new List <AccreditingProviderEnrichment> {
                }
            };

            var ucasProviderEnrichmentGetModel = new UcasProviderEnrichmentGetModel()
            {
                EnrichmentModel = enrichmentModel
            };

            apiMock.Setup(x => x.GetProviderSummaries())
            .ReturnsAsync(new List <ProviderSummary> {
                new ProviderSummary()
            });

            apiMock.Setup(x => x.GetProviderEnrichment(providerCode))
            .ReturnsAsync(ucasProviderEnrichmentGetModel);

            var objectValidator = new Mock <IObjectModelValidator>();

            objectValidator.Setup(o => o.Validate(It.IsAny <ActionContext>(),
                                                  It.IsAny <ValidationStateDictionary>(),
                                                  It.IsAny <string>(),
                                                  It.IsAny <Object>()));

            var frontendUrlMock = new Mock <IFrontendUrlService>();

            var controller = new OrganisationController(apiMock.Object, frontendUrlMock.Object);

            controller.ObjectValidator = objectValidator.Object;

            controller.TempData = new Mock <ITempDataDictionary>().Object;

            Assert.IsFalse(controller.ModelState.Any());
            Assert.IsTrue(controller.ModelState.IsValid);
            var result = controller.AboutPost(providerCode, viewModel).Result;


            Assert.IsTrue(controller.ModelState.Any());
            Assert.AreEqual($"Reduce word count for {providerName}", controller.ModelState["AboutTrainingProviders_0__Description"].Errors.First().ErrorMessage);
            Assert.IsFalse(controller.ModelState.IsValid);

            var viewResult = result as ViewResult;

            var organisationViewModel = viewResult.ViewData.Model as OrganisationViewModelForAbout;

            Assert.IsNotNull(viewResult);
            Assert.AreEqual(exceed100Words, organisationViewModel.AboutTrainingProviders.First(x => x.ProviderCode == providerCode + 1).Description);
            Assert.AreEqual(providerName, organisationViewModel.AboutTrainingProviders.First(x => x.ProviderCode == providerCode + 1).ProviderName);
        }
        public async Task AboutPost_SetAccreditingProviderToEmpty()
        {
            var existingEnrichment = new UcasProviderEnrichmentGetModel()
            {
                EnrichmentModel = new ProviderEnrichmentModel()
                {
                    AccreditingProviderEnrichments = new List <AccreditingProviderEnrichment>
                    {
                        new AccreditingProviderEnrichment
                        {
                            UcasProviderCode = "ACC",
                            Description      = "foo"
                        }
                    }
                }
            };

            var apiMock = new Mock <IManageApi>();

            apiMock.Setup(x => x.GetProviderEnrichment("ABC")).ReturnsAsync(existingEnrichment);

            UcasProviderEnrichmentPostModel result = null;

            apiMock.Setup(x => x.SaveProviderEnrichment("ABC", It.IsAny <UcasProviderEnrichmentPostModel>()))
            .Callback((string a, UcasProviderEnrichmentPostModel b) => result = b)
            .Returns(Task.CompletedTask);

            apiMock.Setup(x => x.GetCoursesOfProvider("ABC")).ReturnsAsync(new List <Course> {
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = "ACC"
                    }
                }
            });

            var objectValidator = new Mock <IObjectModelValidator>();

            objectValidator.Setup(o => o.Validate(It.IsAny <ActionContext>(),
                                                  It.IsAny <ValidationStateDictionary>(),
                                                  It.IsAny <string>(),
                                                  It.IsAny <Object>()));

            var frontendUrlMock = new Mock <IFrontendUrlService>();

            var controller = new OrganisationController(apiMock.Object, frontendUrlMock.Object);

            controller.ObjectValidator = objectValidator.Object;
            controller.TempData        = new Mock <ITempDataDictionary>().Object;

            var res = await controller.AboutPost("ABC", new OrganisationViewModelForAbout {
                AboutTrainingProviders = new List <TrainingProviderViewModel>
                {
                    new TrainingProviderViewModel
                    {
                        ProviderCode = "ACC",
                        Description  = null // not an empty string... this is how MVC model binding behaves
                    }
                }
            });


            result.Should().NotBeNull();
            result.EnrichmentModel.AccreditingProviderEnrichments[0].UcasProviderCode.Should().Be("ACC");
            result.EnrichmentModel.AccreditingProviderEnrichments[0].Description.Should().BeNullOrEmpty();
        }
        public async Task DetailsPost_PublishOrganisation_invalid()
        {
            var providerCode = "PROVIDERCODE";

            var organisationName = "OrganisationName";

            var providerSummaries = new List <ProviderSummary>
            {
                new ProviderSummary
                {
                    ProviderCode = providerCode,
                    ProviderName = organisationName
                }
            };

            var trainWithUs         = "TrainWithUs";
            var trainWithDisability = "TrainWithDisability";

            var description     = "Description";
            var providerName    = "ProviderName";
            var providerCourses = new List <Course>
            {
                new Course {
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode.ToUpperInvariant()
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode.ToLowerInvariant()
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode + 1, ProviderName = providerName
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode + 2
                    }
                },
            };

            var now = DateTime.Now;
            var ucasProviderEnrichmentGetModel = new UcasProviderEnrichmentGetModel()
            {
                LastPublishedTimestampUtc = now,
                Status          = EnumStatus.Published,
                EnrichmentModel = new ProviderEnrichmentModel
                {
                    AccreditingProviderEnrichments = new List <AccreditingProviderEnrichment>
                    {
                        new AccreditingProviderEnrichment {
                            UcasProviderCode = providerCode + 2, Description = description
                        }
                    },
                    TrainWithUs         = trainWithUs,
                    TrainWithDisability = trainWithDisability
                }
            };

            var viewModel = new OrganisationViewModel
            {
                AboutTrainingProviders = new List <TrainingProviderViewModel>()
            };

            var apiMock = new Mock <IManageApi>();

            apiMock.Setup(x => x.GetProviderSummary(providerCode))
            .ReturnsAsync(new ProviderSummary {
                ProviderCode = providerCode, ProviderName = organisationName
            });

            apiMock.Setup(x => x.GetProviderSummaries())
            .ReturnsAsync(providerSummaries);

            apiMock.Setup(x => x.GetCoursesOfProvider(providerCode))
            .ReturnsAsync(providerCourses);

            apiMock.Setup(x => x.GetProviderEnrichment(providerCode))
            .ReturnsAsync(ucasProviderEnrichmentGetModel);

            apiMock.Setup(x => x.PublishAllCoursesOfProviderToSearchAndCompare(providerCode))
            .ReturnsAsync(true);
            var frontendUrlMock = new Mock <IFrontendUrlService>();
            var controller      = new OrganisationControllerMockedValidation(apiMock.Object, frontendUrlMock.Object);

            var result = await controller.DetailsPost(providerCode, viewModel);

            var viewResult = result as ViewResult;

            Assert.IsNotNull(viewResult);
            var organisationViewModel = viewResult.ViewData.Model as OrganisationViewModel;

            Assert.AreEqual(organisationName, organisationViewModel.ProviderName);
            Assert.AreEqual(trainWithUs, organisationViewModel.TrainWithUs);
            Assert.AreEqual(2, organisationViewModel.AboutTrainingProviders.Count);
            Assert.AreEqual(description, organisationViewModel.AboutTrainingProviders.First(x => x.ProviderCode == providerCode + 2).Description);
            Assert.AreEqual(providerName, organisationViewModel.AboutTrainingProviders.First(x => x.ProviderCode == providerCode + 1).ProviderName);
            Assert.AreEqual(trainWithDisability, organisationViewModel.TrainWithDisability);
            Assert.AreEqual(now, organisationViewModel.LastPublishedTimestampUtc);
            Assert.AreEqual(EnumStatus.Published, organisationViewModel.Status);
        }
        public async Task DetailsPost_PublishOrganisation_WhenApiReturnsTrue()
        {
            var providerCode = "PROVIDERCODE";
            var viewModel    = new OrganisationViewModel
            {
                AboutTrainingProviders = new List <TrainingProviderViewModel>()
            };

            var providerName = "ProviderName";

            var providerCourses = new List <Course>
            {
                new Course {
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode.ToUpperInvariant()
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode.ToLowerInvariant()
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode + 1, ProviderName = providerName
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode + 2
                    }
                },
            };
            var apiMock = new Mock <IManageApi>();

            apiMock.Setup(x => x.GetProviderSummary(providerCode))
            .ReturnsAsync(new ProviderSummary {
                ProviderCode = providerCode, ProviderName = providerName
            });

            apiMock.Setup(x => x.GetCoursesOfProvider(providerCode))
            .ReturnsAsync(providerCourses);

            var enrichmentModel = new ProviderEnrichmentModel {
                AccreditingProviderEnrichments = new List <AccreditingProviderEnrichment>()
            };

            var ucasProviderEnrichmentGetModel = new UcasProviderEnrichmentGetModel()
            {
                EnrichmentModel = enrichmentModel
            };

            apiMock.Setup(x => x.GetProviderEnrichment(providerCode))
            .ReturnsAsync(ucasProviderEnrichmentGetModel);

            var objectValidator = new Mock <IObjectModelValidator>();

            objectValidator.Setup(o => o.Validate(It.IsAny <ActionContext>(),
                                                  It.IsAny <ValidationStateDictionary>(),
                                                  It.IsAny <string>(),
                                                  It.IsAny <Object>()));

            apiMock.Setup(x => x.PublishAllCoursesOfProviderToSearchAndCompare(providerCode))
            .ReturnsAsync(true);
            var frontendUrlMock = new Mock <IFrontendUrlService>();
            var controller      = new OrganisationController(apiMock.Object, frontendUrlMock.Object);

            controller.ObjectValidator = objectValidator.Object;

            controller.TempData = new Mock <ITempDataDictionary>().Object;

            var result = await controller.DetailsPost(providerCode, viewModel);

            var actionResult = result as RedirectToActionResult;

            Assert.IsNotNull(actionResult);
            Assert.AreEqual("Details", actionResult.ActionName);
            Assert.AreEqual(providerCode, actionResult.RouteValues[providerCode]);
        }
        public void DetailsPost_PublishOrganisation_WhenApiReturnsFalse()
        {
            var providerCode = "PROVIDERCODE";
            var providerName = "ProviderName";

            var viewModel = new OrganisationViewModel
            {
                AboutTrainingProviders = new List <TrainingProviderViewModel>()
            };

            var providerCourses = new List <Course>
            {
                new Course {
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode.ToUpperInvariant()
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode.ToLowerInvariant()
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode + 1, ProviderName = providerName
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode + 2
                    }
                },
            };

            var apiMock = new Mock <IManageApi>();

            apiMock.Setup(x => x.GetProviderSummary(providerCode))
            .ReturnsAsync(new ProviderSummary {
                ProviderCode = providerCode, ProviderName = providerName
            });

            apiMock.Setup(x => x.GetCoursesOfProvider(providerCode))
            .ReturnsAsync(providerCourses);

            var enrichmentModel = new ProviderEnrichmentModel {
                AccreditingProviderEnrichments = new List <AccreditingProviderEnrichment> {
                }
            };

            var ucasProviderEnrichmentGetModel = new UcasProviderEnrichmentGetModel()
            {
                EnrichmentModel = enrichmentModel
            };

            apiMock.Setup(x => x.GetProviderEnrichment(providerCode))
            .ReturnsAsync(ucasProviderEnrichmentGetModel);

            var objectValidator = new Mock <IObjectModelValidator>();

            objectValidator.Setup(o => o.Validate(It.IsAny <ActionContext>(),
                                                  It.IsAny <ValidationStateDictionary>(),
                                                  It.IsAny <string>(),
                                                  It.IsAny <Object>()));

            var frontendUrlMock = new Mock <IFrontendUrlService>();

            var controller = new OrganisationController(apiMock.Object, frontendUrlMock.Object);

            controller.ObjectValidator = objectValidator.Object;

            controller.TempData = new Mock <ITempDataDictionary>().Object;

            Assert.ThrowsAsync <InvalidOperationException>(async() => await controller.DetailsPost(providerCode, viewModel));
        }
        private Course GetCourse(string providerCode, string courseCode, string email, Provider ucasProviderData, UcasProviderEnrichmentGetModel orgEnrichmentData)
        {
            var ucasCourseData       = _dataService.GetCourseForUser(email, providerCode, courseCode);
            var courseEnrichmentData = _enrichmentService.GetCourseEnrichmentForPublish(providerCode, courseCode, email);

            var courseToReturn = _courseMapper.MapToSearchAndCompareCourse(
                ucasProviderData,
                ucasCourseData,
                orgEnrichmentData.EnrichmentModel,
                courseEnrichmentData?.EnrichmentModel);

            return(courseToReturn);
        }