public async Task <ActionResult> EditAcademyOpening(int?urn) { if (!urn.HasValue) { return(HttpNotFound()); } var result = await _establishmentReadService.GetAsync((int)urn, User); var estabTypes = await _lookupService.EstablishmentTypesGetAllAsync(); var links = await _establishmentReadService.GetLinkedEstablishmentsAsync((int)urn, User); var link = links.FirstOrDefault(e => e.LinkTypeId == (int)eLookupEstablishmentLinkType.ParentOrPredecessor); var establishment = (result).GetResult(); var viewModel = new EditAcademyOpeningViewModel() { Urn = (int)urn, EstablishmentName = establishment.Name, EstablishmentType = establishment.TypeId.HasValue ? estabTypes.FirstOrDefault(t => t.Id == establishment.TypeId)?.Name : null, PredecessorUrn = link?.Urn.GetValueOrDefault().ToString(), PredecessorName = link?.EstablishmentName, OpeningDate = new UI.Models.DateTimeViewModel(establishment.OpenDate) }; return(View(viewModel)); }
internal async Task <GovernorsGridViewModel> CreateGovernorsViewModel(int?groupUId = null, int?establishmentUrn = null, EstablishmentModel establishmentModel = null, IPrincipal user = null) { user = user ?? User; establishmentUrn = establishmentUrn ?? establishmentModel?.Urn; var domainModel = await _governorsReadService.GetGovernorListAsync(establishmentUrn, groupUId, user); var viewModel = new GovernorsGridViewModel(domainModel, false, groupUId, establishmentUrn, _nomenclatureService, (await _cachedLookupService.NationalitiesGetAllAsync()), (await _cachedLookupService.GovernorAppointingBodiesGetAllAsync())); if (establishmentUrn.HasValue || establishmentModel != null) { var estabDomainModel = establishmentModel ?? (await _establishmentReadService.GetAsync(establishmentUrn.Value, user)).GetResult(); var items = await _establishmentReadService.GetPermissibleLocalGovernorsAsync(establishmentUrn.Value, user); // The API uses 1 as a default value, hence we have to call another API to deduce whether to show the Governance mode UI section viewModel.GovernanceMode = items.Any() ? estabDomainModel.GovernanceMode : null; } if (groupUId.HasValue) { var groupModel = (await _groupReadService.GetAsync(groupUId.Value, user)).GetResult(); viewModel.ShowDelegationInformation = groupModel.GroupTypeId == (int)eLookupGroupType.MultiacademyTrust; viewModel.DelegationInformation = groupModel.DelegationInformation; } return(viewModel); }
private async Task AddLinkedEstablishment(GroupEditorViewModel viewModel) { var model = (await _establishmentReadService.GetAsync(viewModel.LinkedEstablishments.LinkedEstablishmentSearch.FoundUrn.Value, User)).GetResult(); viewModel.LinkedEstablishments.Establishments.Add(new EstablishmentGroupViewModel { Address = await model.GetAddressAsync(_lookup), HeadFirstName = model.HeadFirstName, HeadLastName = model.HeadLastName, HeadTitleName = await _lookup.GetNameAsync(() => model.HeadTitleId), JoinedDate = viewModel.LinkedEstablishments.LinkedEstablishmentSearch.JoinedDate.ToDateTime(), Name = model.Name, TypeName = await _lookup.GetNameAsync(() => model.TypeId), Urn = model.Urn.Value }); viewModel.LinkedEstablishments.LinkedEstablishmentSearch.Reset(); }
public async Task PopulateLayoutProperties(object viewModel, int?establishmentUrn, int?groupUId, IPrincipal user, Action <EstablishmentModel> processEstablishment = null, Action <GroupModel> processGroup = null) { if (establishmentUrn.HasValue && groupUId.HasValue) { throw new InvalidParameterException("Both urn and uid cannot be populated"); } if (!establishmentUrn.HasValue && !groupUId.HasValue) { throw new InvalidParameterException($"Both {nameof(establishmentUrn)} and {nameof(groupUId)} parameters are null"); } if (establishmentUrn.HasValue) { var domainModel = (await _establishmentReadService.GetAsync(establishmentUrn.Value, user)).GetResult(); var displayPolicy = await _establishmentReadService.GetDisplayPolicyAsync(domainModel, user); var permissibleGovernanceModes = await _establishmentReadService.GetPermissibleLocalGovernorsAsync(establishmentUrn.Value, user); if (!permissibleGovernanceModes.Any()) { domainModel.GovernanceModeId = null; // hack the model returned. } var vm = (IEstablishmentPageViewModel)viewModel; vm.Layout = EstabLayout; vm.Name = domainModel.Name; if (domainModel.TypeId.HasValue) { vm.TypeName = (await _cls.GetNameAsync(() => domainModel.TypeId)); } vm.SelectedTab = "governance"; vm.Urn = domainModel.Urn; vm.TabDisplayPolicy = new TabDisplayPolicy(domainModel, displayPolicy, user); vm.LegalParentGroup = EstablishmentController.GetLegalParent(vm.Urn.Value, await _groupReadService.GetAllByEstablishmentUrnAsync(vm.Urn.Value, user), user); // I agree, this shouldn't be a static. We should refector all this. We should have a base view model class. processEstablishment?.Invoke(domainModel); } else if (groupUId.HasValue) { var domainModel = (await _groupReadService.GetAsync(groupUId.Value, user)).GetResult(); var vm = (IGroupPageViewModel)viewModel; vm.Layout = GroupsLayout; vm.GroupName = domainModel.Name; vm.GroupTypeId = domainModel.GroupTypeId.Value; vm.GroupUId = groupUId; if (vm.GroupTypeId.HasValue) { vm.GroupTypeName = (await _cls.GetNameAsync(() => vm.GroupTypeId)); } vm.SelectedTabName = "governance"; vm.ListOfEstablishmentsPluralName = _nomenclatureService.GetEstablishmentsPluralName((eLookupGroupType)vm.GroupTypeId.Value); processGroup?.Invoke(domainModel); } }
public async Task <IHttpActionResult> Get(int urn) { var retVal = await _establishmentReadService.GetAsync(urn, User); if (retVal.ReturnValue == null) { return(NotFound()); } else { return(Ok(retVal)); } }
internal async Task <GovernorsGridViewModel> CreateGovernorsViewModel(int?groupUId = null, int?establishmentUrn = null, EstablishmentModel establishmentModel = null, IPrincipal user = null) { user = user ?? User; establishmentUrn = establishmentUrn ?? establishmentModel?.Urn; GovernorsGridViewModel viewModel; try { var domainModel = await _governorsReadService.GetGovernorListAsync(establishmentUrn, groupUId, user); var governorPermissions = await _governorsReadService.GetGovernorPermissions(establishmentUrn, groupUId, user); viewModel = new GovernorsGridViewModel(domainModel, false, groupUId, establishmentUrn, _nomenclatureService, await _cachedLookupService.NationalitiesGetAllAsync(), await _cachedLookupService.GovernorAppointingBodiesGetAllAsync(), governorPermissions); if (establishmentUrn.HasValue || establishmentModel != null) { var estabDomainModel = establishmentModel ?? (await _establishmentReadService.GetAsync(establishmentUrn.Value, user)).GetResult(); var items = await _establishmentReadService.GetPermissibleLocalGovernorsAsync(establishmentUrn.Value, user); // The API uses 1 as a default value, hence we have to call another API to deduce whether to show the Governance mode UI section viewModel.GovernanceMode = items.Any() ? estabDomainModel.GovernanceMode : null; } if (groupUId.HasValue) { var groupModel = (await _groupReadService.GetAsync(groupUId.Value, user)).GetResult(); viewModel.ShowDelegationAndCorpContactInformation = groupModel.GroupTypeId == (int)eLookupGroupType.MultiacademyTrust; viewModel.DelegationInformation = groupModel.DelegationInformation; viewModel.CorporateContact = groupModel.CorporateContact; } } catch (Exception) // to more gracefully handle Texuna services UsageQuotaExceededException { viewModel = new GovernorsGridViewModel { DomainModel = new GovernorsDetailsDto() }; } return(viewModel); }
public SearchForEstablishmentViewModelValidator(IEstablishmentReadService establishmentReadService, IPrincipal principal) { RuleFor(x => x.SearchUrn) .Cascade(CascadeMode.StopOnFirstFailure) .Must(x => x.ToInteger().HasValue) .WithMessage("Please enter a valid URN") .Must((vm, x) => x.ToInteger() != vm.Urn) .WithMessage("Establishment cannot link to itself") .MustAsync(async(vm, x, ct) => { var links = await establishmentReadService.GetLinkedEstablishmentsAsync(vm.Urn.Value, principal); return(links.All(a => a.Urn != x.ToInteger())); }).WithMessage("This URN is already linked to this establishment") .MustAsync(async(vm, x, ct) => (await establishmentReadService.GetAsync(x.ToInteger().Value, principal)).ReturnValue != null) .WithMessage("Establishment not found"); }
public async Task <ActionResult> BulkAcademies(BulkAcademiesViewModel model, int?removeUrn, int?editUrn, string action) { var establishmentTypeFullList = (await _lookup.EstablishmentTypesGetAllAsync()).ToList(); model.ItemTypes = establishmentTypeFullList.ToSelectList(); EstablishmentModel est = null; SelectListItem[] filteredItems = null; // validation if (action == "search") { if (model.SearchUrn == null) { if (ModelState.ContainsKey(nameof(model.SearchUrn)) && ModelState[nameof(model.SearchUrn)].Errors.Any()) { // remove the existing error, as we'll add a fresh one ModelState[nameof(model.SearchUrn)].Errors.Clear(); } ModelState.AddModelError(nameof(model.SearchUrn), "Please enter a valid URN"); } else if (model.ItemsToAdd?.Any(x => x.Urn == model.SearchUrn) == true) { ModelState.AddModelError(nameof(model.SearchUrn), "URN is a duplicate"); } else { var estCall = await _establishmentReadService.GetAsync((int)model.SearchUrn, User); est = estCall.GetResult(); if (est == null) { ModelState.AddModelError(nameof(model.SearchUrn), "Please enter a valid URN"); } else { filteredItems = (await GetFilteredBulkAcademyTypes((int)est.Urn, establishmentTypeFullList)).ToSelectList(est?.TypeId)?.ToArray(); if (filteredItems?.Length == 0) { ModelState.AddModelError(nameof(model.SearchUrn), "Please enter a valid URN"); } } } } if (action == "add") { model.FilteredItemTypes = (await GetFilteredBulkAcademyTypes(model.FoundItem.Urn ?? 0, establishmentTypeFullList)).ToSelectList(model.FoundItem.EstablishmentTypeId); if (model.FoundItem.EstablishmentTypeId == null) { ModelState.AddModelError(nameof(model.FilteredItemTypes), "Please select an establishment type"); } } // cancel either an original addition or an edit if (action == "cancel") { model.SearchUrn = null; model.FoundItem = null; ModelState.Clear(); return(View(model)); } if (!ModelState.IsValid) { return(View(model)); } ModelState.Clear(); // remove if (removeUrn != null) { model.ItemsToAdd?.RemoveAll(x => x.Urn == removeUrn); return(View(model)); } // edit/find if (editUrn != null || model.SearchUrn != null) { if (editUrn != null) { var itm = model.ItemsToAdd?.First(x => x.Urn == editUrn); model.FilteredItemTypes = (await GetFilteredBulkAcademyTypes((int)editUrn, establishmentTypeFullList)).ToSelectList(itm?.EstablishmentTypeId); model.FoundItem = itm; ViewBag.ButtonText = "Update establishment"; } else { model.FilteredItemTypes = filteredItems; model.FoundItem = new BulkAcademyViewModel() { Urn = est.Urn, Name = est.Name, EstablishmentTypeId = est.TypeId, OpeningDate = DateTime.Now, Address = StringUtil.ConcatNonEmpties(", ", est.Address_Line1, est.Address_Locality, est.Address_Line3, est.Address_CityOrTown, est.Address_PostCode) }; } return(View(model)); } // save/review list if (model.FoundItem != null) { if (model.ItemsToAdd == null) { model.ItemsToAdd = new List <BulkAcademyViewModel>(); } if (model.ItemsToAdd != null) { model.ItemsToAdd.RemoveAll(x => x.Urn == model.FoundItem.Urn); model.ItemsToAdd.Add(new BulkAcademyViewModel { Urn = model.FoundItem.Urn, Name = model.FoundItem.Name, EstablishmentTypeId = model.FoundItem.EstablishmentTypeId, OpeningDate = model.FoundItem.OpeningDate, Address = model.FoundItem.Address }); } model.FoundItem = null; return(View(model)); } // submit if (action == "create" && model.ItemsToAdd?.Any() == true) { var processResponse = await ProcessBulkAcademies(model.ItemsToAdd); model.ProgressGuid = processResponse.Item1; model.ItemsToAdd = processResponse.Item2; model.IsComplete = true; } return(View(model)); }
public GroupEditorViewModelValidator(IGroupReadService groupReadService, IEstablishmentReadService establishmentReadService, IPrincipal principal, ISecurityService securityService) { _groupReadService = groupReadService; _establishmentReadService = establishmentReadService; CascadeMode = CascadeMode.StopOnFirstFailure; // Searching for an establishment to link.... When(x => x.Action == ActionLinkedEstablishmentSearch, () => { RuleFor(x => x.LinkedEstablishments.LinkedEstablishmentSearch.Urn) .Cascade(CascadeMode.StopOnFirstFailure) .Must(x => x.IsInteger()) .WithMessage("Please enter a valid URN") .WithSummaryMessage("The supplied URN is not valid") .Must((model, x) => !model.LinkedEstablishments.Establishments.Select(e => e.Urn).Contains(x.ToInteger().Value)) .WithMessage("This establishment is already in this group. Please enter a different URN") .WithSummaryMessage("This establishment is already in this group. Please enter a different URN") .MustAsync(async(x, ct) => { return((await _establishmentReadService.GetAsync(x.ToInteger().Value, principal).ConfigureAwait(false)).ReturnValue != null); }).WithMessage("The establishment was not found").WithSummaryMessage("The establishment was not found"); }); // Having found an establishment to link, validate the joined date if supplied... When(x => x.Action == ActionLinkedEstablishmentAdd, () => { RuleFor(x => x.LinkedEstablishments.LinkedEstablishmentSearch.JoinedDate) .Must(x => x.IsValid()) .WithMessage("This is not a valid date") .WithSummaryMessage("The Joined Date specified is not valid") .Must((model, joinDate) => VerifyJoinedDate(joinDate.ToDateTime(), model)) .WithMessage(x => $"The join date you entered is before the {x.GroupType}'s open date of {x.OpenDate}. Please enter a later date."); }); // Having edited a joined date, validate the date... When(x => x.Action == ActionLinkedEstablishmentSave, () => { RuleFor(x => x.LinkedEstablishments.Establishments.Single(e => e.EditMode).JoinedDateEditable).Must(x => x.IsValid()) .WithMessage("This is not a valid date") .WithSummaryMessage("The Joined Date specified is not valid") .Must((model, joinDate) => VerifyJoinedDate(joinDate.ToDateTime(), model)) .WithMessage(x => $"The join date you entered is before the {x.GroupType}'s open date of {x.OpenDate}. Please enter a later date."); }); // On getting to the save page.... When(x => x.Action == ActionSave || x.Action == ActionDetails, () => { When(m => m.GroupTypeMode == eGroupTypeMode.ChildrensCentre, () => { RuleFor(x => x.LocalAuthorityId).NotNull() .WithMessage("This field is mandatory") .WithSummaryMessage("Please select a local authority for the group") .When(x => x.SaveGroupDetail); }); RuleFor(x => x.GroupTypeId).NotNull().WithMessage("Group Type must be supplied"); RuleFor(x => x.OpenDate) .Must(x => !x.IsEmpty()) .WithMessage(x => $"{x.OpenDateLabel} missing. Please enter the date") .When(x => !x.GroupUId.HasValue, ApplyConditionTo.CurrentValidator) .Must(x => x.IsValid() || x.IsEmpty()) .WithMessage(x => $"{x.OpenDateLabel} is invalid. Please enter a valid date"); When(x => x.CanUserEditClosedDate && x.GroupType == eLookupGroupType.MultiacademyTrust && x.OriginalStatusId != (int)eLookupGroupStatus.Closed && x.StatusId == (int)eLookupGroupStatus.Closed && x.SaveGroupDetail, () => { RuleFor(x => x.ClosedDate) .Must(x => !x.IsEmpty()) .WithMessage("Please enter a date for the closure of this multi-academy trust") .Must(x => x.IsValid() || x.IsEmpty()) .WithMessage("Closed date is invalid. Please enter a valid date."); }); RuleFor(x => x.GroupName) .Cascade(CascadeMode.StopOnFirstFailure) .NotEmpty() .WithMessage(x => $"Please enter the {x.FieldNamePrefix.ToLower()} name") .When(x => x.SaveGroupDetail); RuleFor(x => x.GroupId) .Cascade(CascadeMode.StopOnFirstFailure) .NotEmpty() .WithMessage("Please enter a Group ID") .WithSummaryMessage("Please enter a Group ID") .MustAsync(async(model, groupId, ct) => !(await _groupReadService.ExistsAsync(securityService.CreateAnonymousPrincipal(), groupId: groupId, existingGroupUId: model.GroupUId))) .WithMessage("Group ID already exists. Enter a different group ID.") .When(x => x.GroupTypeMode.OneOfThese(eGroupTypeMode.AcademyTrust, eGroupTypeMode.Sponsor) && x.SaveGroupDetail, ApplyConditionTo.AllValidators); When(x => x.OpenDate.ToDateTime().HasValue, () => { RuleForEach(x => x.LinkedEstablishments.Establishments) .Must((model, estab) => VerifyJoinedDate(estab.JoinedDateEditable.ToDateTime() ?? estab.JoinedDate, model)) .When(x => x.OpenDate.ToDateTime().GetValueOrDefault().Date == DateTime.Now.Date) .WithMessage("The join date you entered is before today. Please enter a later date.") .WithSummaryMessage("The join date you entered is before today. Please enter a later date.") .Must((model, estab) => VerifyJoinedDate(estab.JoinedDateEditable.ToDateTime() ?? estab.JoinedDate, model)) .When(x => x.OpenDate.ToDateTime().GetValueOrDefault().Date != DateTime.Now.Date) .WithMessage(x => $"The join date you entered is before the {x.GroupType}'s open date of {x.OpenDate}. Please enter a later date."); }); }); // Specific addition only triggered upon Saving ChildrensCentres through the creation tool When(x => x.Action == ActionSave && x.ActionName == eChildrensCentreActions.Step3, () => { When(m => m.GroupTypeMode == eGroupTypeMode.ChildrensCentre, () => { RuleFor(x => x.LinkedEstablishments.Establishments) .Must(x => x.Count >= 2) .WithMessage("Add more centres to the group") .WithSummaryMessage("You need to add at least two centres"); }); }); }
public async Task <ActionResult> ProcessMergeEstablishmentsAsync(MergeEstablishmentsModel model) { var viewModel = new MergeEstablishmentsModel(); var submittedUrns = new List <int>(); var leadHasErrors = ModelState.Keys.Where(k => k == "LeadEstablishmentUrn") .Select(k => ModelState[k].Errors).First().Select(e => e.ErrorMessage).Any(); var estab1HasErrors = ModelState.Keys.Where(k => k == "Establishment1Urn") .Select(k => ModelState[k].Errors).First().Select(e => e.ErrorMessage).Any(); if (!model.LeadEstablishmentUrn.HasValue && !leadHasErrors) { ModelState.AddModelError(nameof(model.LeadEstablishmentUrn), "Enter the lead establishment URN"); } if (!model.Establishment1Urn.HasValue && !model.Establishment2Urn.HasValue && !model.Establishment3Urn.HasValue && !estab1HasErrors) { ModelState.AddModelError(nameof(model.Establishment1Urn), "Enter the establishment 1 URN"); } // validate the establishments exist if (model.LeadEstablishmentUrn.HasValue) { var leadEstab = await _establishmentReadService.GetAsync(model.LeadEstablishmentUrn.GetValueOrDefault(), User); if (leadEstab.GetResult() == null) { ViewData.ModelState.AddModelError(nameof(model.LeadEstablishmentUrn), "The lead establishment URN is invalid"); } else { var estabTypes = await _lookupService.EstablishmentTypesGetAllAsync(); viewModel.LeadEstablishmentUrn = model.LeadEstablishmentUrn; viewModel.LeadEstablishmentName = leadEstab.GetResult().Name; viewModel.EstablishmentType = estabTypes.FirstOrDefault(t => t.Id == leadEstab.GetResult().TypeId)?.Name; submittedUrns.Add(model.LeadEstablishmentUrn.GetValueOrDefault()); } } if (model.Establishment1Urn.HasValue) { var estab1 = await _establishmentReadService.GetAsync(model.Establishment1Urn.GetValueOrDefault(), User); var hasErrors = ModelState.Keys.Where(k => k == "Establishment1Urn") .Select(k => ModelState[k].Errors).First().Select(e => e.ErrorMessage).Any(); if (estab1.GetResult() == null) { if (!hasErrors) { ViewData.ModelState.AddModelError(nameof(model.Establishment1Urn), "The establishment 1 URN is invalid"); } } else { viewModel.Establishment1Urn = model.Establishment1Urn; viewModel.Establishment1Name = estab1.GetResult().Name; submittedUrns.Add(model.Establishment1Urn.GetValueOrDefault()); } } if (model.Establishment2Urn.HasValue) { var estab2 = await _establishmentReadService.GetAsync(model.Establishment2Urn.GetValueOrDefault(), User); var hasErrors = ModelState.Keys.Where(k => k == "Establishment2Urn") .Select(k => ModelState[k].Errors).First().Select(e => e.ErrorMessage).Any(); if (estab2.GetResult() == null) { if (!hasErrors) { ViewData.ModelState.AddModelError(nameof(model.Establishment2Urn), "The establishment 2 URN is invalid"); } } else { viewModel.Establishment2Urn = model.Establishment2Urn; viewModel.Establishment2Name = estab2.GetResult().Name; submittedUrns.Add(model.Establishment2Urn.GetValueOrDefault()); } } if (model.Establishment3Urn.HasValue) { var estab3 = await _establishmentReadService.GetAsync(model.Establishment3Urn.GetValueOrDefault(), User); var hasErrors = ModelState.Keys.Where(k => k == "Establishment3Urn") .Select(k => ModelState[k].Errors).First().Select(e => e.ErrorMessage).Any(); if (estab3.GetResult() == null) { if (!hasErrors) { ViewData.ModelState.AddModelError(nameof(model.Establishment3Urn), "The establishment 3 URN is invalid"); } } else { viewModel.Establishment3Urn = model.Establishment3Urn; viewModel.Establishment3Name = estab3.GetResult().Name; submittedUrns.Add(model.Establishment3Urn.GetValueOrDefault()); } } var duplicates = submittedUrns.GroupBy(x => x) .Where(g => g.Count() > 1) .ToDictionary(x => x.Key, x => x.Count()); if (duplicates.ContainsKey(model.LeadEstablishmentUrn.GetValueOrDefault())) { ViewData.ModelState.AddModelError("LeadEstablishmentUrn", "Duplicate URN. Please correct the URN."); } if (duplicates.ContainsKey(model.Establishment1Urn.GetValueOrDefault())) { ViewData.ModelState.AddModelError("Establishment1Urn", "Duplicate URN. Please correct the URN."); } if (duplicates.ContainsKey(model.Establishment2Urn.GetValueOrDefault())) { ViewData.ModelState.AddModelError("Establishment2Urn", "Duplicate URN. Please correct the URN."); } if (duplicates.ContainsKey(model.Establishment3Urn.GetValueOrDefault())) { ViewData.ModelState.AddModelError("Establishment3Urn", "Duplicate URN. Please correct the URN."); } if (!ModelState.IsValid) { return(View("~/Views/Tools/Mergers/MergeEstablishments.cshtml", model)); } return(View("~/Views/Tools/Mergers/ConfirmMerger.cshtml", viewModel)); }
public GroupEditorViewModelValidator(IGroupReadService groupReadService, IEstablishmentReadService establishmentReadService, IPrincipal principal, ISecurityService securityService) { _groupReadService = groupReadService; _establishmentReadService = establishmentReadService; CascadeMode = CascadeMode.StopOnFirstFailure; // Searching for an establishment to link.... When(x => x.Action == ActionLinkedEstablishmentSearch, () => { RuleFor(x => x.LinkedEstablishments.LinkedEstablishmentSearch.Urn) .Cascade(CascadeMode.StopOnFirstFailure) .Must(x => x.IsInteger()) .WithMessage("Please enter a valid URN") .WithSummaryMessage("The supplied URN is not valid") .Must((model, x) => !model.LinkedEstablishments.Establishments.Select(e => e.Urn).Contains(x.ToInteger().Value)) .WithMessage("This establishment is already in this group. Please enter a different URN") .WithSummaryMessage("This establishment is already in this group. Please enter a different URN") .MustAsync(async(x, ct) => { return((await _establishmentReadService.GetAsync(x.ToInteger().Value, principal).ConfigureAwait(false)).ReturnValue != null); }).WithMessage("The establishment was not found").WithSummaryMessage("The establishment was not found"); }); // Having found an establishment to link, validate the joined date if supplied... When(x => x.Action == ActionLinkedEstablishmentAdd, () => { RuleFor(x => x.LinkedEstablishments.LinkedEstablishmentSearch.JoinedDate) .Must(x => x.IsValid()) .WithMessage("This is not a valid date") .WithSummaryMessage("The Joined Date specified is not valid") .Must((model, joinDate) => VerifyJoinedDate(joinDate.ToDateTime(), model)) .WithMessage("The join date you entered is before the {0}'s open date of {1}. Please enter a later date.", m => m.GroupType, m => m.OpenDate); }); // Having edited a joined date, validate the date... When(x => x.Action == ActionLinkedEstablishmentSave, () => { RuleFor(x => x.LinkedEstablishments.Establishments.Single(e => e.EditMode).JoinedDateEditable).Must(x => x.IsValid()) .WithMessage("This is not a valid date") .WithSummaryMessage("The Joined Date specified is not valid") .Must((model, joinDate) => VerifyJoinedDate(joinDate.ToDateTime(), model)) .WithMessage("The join date you entered is before the {0}'s open date of {1}. Please enter a later date.", m => m.GroupType, m => m.OpenDate); }); // On saving the group record.... When(x => x.Action == ActionSave, () => { When(m => m.GroupTypeMode == eGroupTypeMode.ChildrensCentre, () => { RuleFor(x => x.LocalAuthorityId).NotNull() .WithMessage("This field is mandatory") .WithSummaryMessage("Please select a local authority for the group") .When(x => x.SaveGroupDetail); }); RuleFor(x => x.GroupTypeId).NotNull().WithMessage("Group Type must be supplied"); RuleFor(x => x.OpenDate) .Must(x => !x.IsEmpty()) .WithMessage("{0} missing. Please enter the date", x => x.OpenDateLabel) .When(x => !x.GroupUId.HasValue, ApplyConditionTo.CurrentValidator) .Must(x => x.IsValid() || x.IsEmpty()) .WithMessage("{0} is invalid. Please enter a valid date", x => x.OpenDateLabel); RuleFor(x => x.GroupName) .Cascade(CascadeMode.StopOnFirstFailure) .NotEmpty() .WithMessage("Please enter the {0} name", x => x.FieldNamePrefix.ToLower()) .When(x => x.SaveGroupDetail); RuleFor(x => x.GroupId) .Cascade(CascadeMode.StopOnFirstFailure) .NotEmpty() .WithMessage("This field is mandatory") .WithSummaryMessage("Please enter a Group ID") .MustAsync(async(model, groupId, ct) => !(await _groupReadService.ExistsAsync(securityService.CreateAnonymousPrincipal(), groupId: groupId, existingGroupUId: model.GroupUId))) .WithMessage("Group ID already exists. Enter a different group ID.") .When(x => x.GroupTypeMode.OneOfThese(eGroupTypeMode.AcademyTrust, eGroupTypeMode.Sponsor) && x.SaveGroupDetail, ApplyConditionTo.AllValidators); RuleForEach(x => x.LinkedEstablishments.Establishments) .Must((model, estab) => VerifyJoinedDate(estab.JoinedDateEditable.ToDateTime() ?? estab.JoinedDate, model)) .When(x => x.OpenDate.ToDateTime().Value.Date == DateTime.Now.Date) .WithMessage("The join date you entered is before today. Please enter a later date.") .WithSummaryMessage("The join date you entered is before today. Please enter a later date.") .Must((model, estab) => VerifyJoinedDate(estab.JoinedDateEditable.ToDateTime() ?? estab.JoinedDate, model)) .When(x => x.OpenDate.ToDateTime().Value.Date != DateTime.Now.Date) .WithMessage("The join date you entered is before the {0}'s open date of {1}. Please enter a later date.", m => m.GroupType, m => m.OpenDate); }); }