Beispiel #1
0
        public async override Task <ActionResult> Index(ContentModel contentModel)
        {
            if (contentModel is null)
            {
                throw new System.ArgumentNullException(nameof(contentModel));
            }

            var model = new SeasonViewModel(contentModel.Content, Services?.UserService)
            {
                Season = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl).ConfigureAwait(false)
            };

            if (model.Season == null)
            {
                return(new HttpNotFoundResult());
            }
            else
            {
                model.IsAuthorized = _authorizationPolicy.IsAuthorized(model.Season.Competition);

                model.Metadata.PageTitle = "Edit " + model.Season.SeasonFullNameAndPlayerType();

                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = Constants.Pages.Competitions, Url = new Uri(Constants.Pages.CompetitionsUrl, UriKind.Relative)
                });
                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = model.Season.Competition.CompetitionName, Url = new Uri(model.Season.Competition.CompetitionRoute, UriKind.Relative)
                });
                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = model.Season.SeasonName(), Url = new Uri(model.Season.SeasonRoute, UriKind.Relative)
                });

                return(CurrentTemplate(model));
            }
        }
Beispiel #2
0
        public async Task ConfigureModelPossibleTeams(IEditMatchViewModel model, IEnumerable <Season> possibleSeasons)
        {
            if (model is null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (possibleSeasons is null)
            {
                throw new ArgumentNullException(nameof(possibleSeasons));
            }

            var possibleTeams = new List <Team>();

            foreach (var season in possibleSeasons)
            {
                var teamsInSeason = (await _seasonDataSource.ReadSeasonByRoute(season.SeasonRoute, true).ConfigureAwait(false))?.Teams.Where(x => x.WithdrawnDate == null).Select(x => x.Team);
                if (teamsInSeason != null)
                {
                    possibleTeams.AddRange(teamsInSeason);
                }
            }
            model.PossibleHomeTeams.AddRange(possibleTeams.OfType <Team>().Distinct(new TeamEqualityComparer()).Select(x => new SelectListItem {
                Text = x.TeamName, Value = x.TeamId.Value.ToString()
            }));
            model.PossibleHomeTeams.Sort(new TeamComparer(model.Team.TeamId));
            model.PossibleAwayTeams.AddRange(possibleTeams.OfType <Team>().Distinct(new TeamEqualityComparer()).Select(x => new SelectListItem {
                Text = x.TeamName, Value = x.TeamId.Value.ToString()
            }));
            model.PossibleAwayTeams.Sort(new TeamComparer(model.Team.TeamId));
        }
        public async override Task <ActionResult> Index(ContentModel contentModel)
        {
            if (contentModel is null)
            {
                throw new ArgumentNullException(nameof(contentModel));
            }

            var model = new SeasonViewModel(contentModel.Content, Services?.UserService)
            {
                Season           = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl, false).ConfigureAwait(false),
                GoogleMapsApiKey = _apiKeyProvider.GetApiKey("GoogleMaps")
            };

            if (model.Season == null)
            {
                return(new HttpNotFoundResult());
            }
            else
            {
                var the = model.Season.Competition.CompetitionName.StartsWith("THE ", StringComparison.OrdinalIgnoreCase);
                model.Metadata.PageTitle   = $"Map of teams in {(the ? string.Empty : "the ")}{model.Season.SeasonFullNameAndPlayerType()}";
                model.Metadata.Description = model.Season.Description();

                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = Constants.Pages.Competitions, Url = new Uri(Constants.Pages.CompetitionsUrl, UriKind.Relative)
                });
                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = model.Season.Competition.CompetitionName, Url = new Uri(model.Season.Competition.CompetitionRoute, UriKind.Relative)
                });

                return(CurrentTemplate(model));
            }
        }
        public async Task <ActionResult> UpdateSeason([Bind(Prefix = "Season", Include = "Teams")] Season season)
        {
            if (season is null)
            {
                season = new Season(); // if there are no teams, season is null
            }

            var beforeUpdate = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl).ConfigureAwait(false);

            season.SeasonId = beforeUpdate.SeasonId;

            ReplaceDateFormatErrorMessages("Date withdrew");

            // We're not interested in validating the details of the selected teams
            foreach (var key in ModelState.Keys.Where(x => x.StartsWith("Season.Teams", StringComparison.OrdinalIgnoreCase)))
            {
                ModelState[key].Errors.Clear();
            }

            var isAuthorized = _authorizationPolicy.IsAuthorized(beforeUpdate.Competition);

            if (isAuthorized[AuthorizedAction.EditCompetition] && ModelState.IsValid)
            {
                // Update the season
                var currentMember = Members.GetCurrentMember();
                await _seasonRepository.UpdateTeams(season, currentMember.Key, currentMember.Name).ConfigureAwait(false);

                // Redirect to the season actions page that led here
                return(Redirect(beforeUpdate.SeasonRoute + "/edit"));
            }

            var viewModel = new SeasonViewModel(CurrentPage, Services.UserService)
            {
                Season = season,
            };

            viewModel.IsAuthorized = isAuthorized;
            season.Competition     = beforeUpdate.Competition;
            season.FromYear        = beforeUpdate.FromYear;
            season.UntilYear       = beforeUpdate.UntilYear;
            season.SeasonRoute     = beforeUpdate.SeasonRoute;

            viewModel.Metadata.PageTitle = $"Teams in the {beforeUpdate.SeasonFullNameAndPlayerType()}";

            viewModel.Breadcrumbs.Add(new Breadcrumb {
                Name = Constants.Pages.Competitions, Url = new Uri(Constants.Pages.CompetitionsUrl, UriKind.Relative)
            });
            viewModel.Breadcrumbs.Add(new Breadcrumb {
                Name = viewModel.Season.Competition.CompetitionName, Url = new Uri(viewModel.Season.Competition.CompetitionRoute, UriKind.Relative)
            });
            viewModel.Breadcrumbs.Add(new Breadcrumb {
                Name = viewModel.Season.SeasonName(), Url = new Uri(viewModel.Season.SeasonRoute, UriKind.Relative)
            });

            return(View("EditSeasonTeams", viewModel));
        }
Beispiel #5
0
        public async Task <ActionResult> DeleteSeason([Bind(Prefix = "ConfirmDeleteRequest", Include = "RequiredText,ConfirmationText")] MatchingTextConfirmation model)
        {
            if (model is null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var viewModel = new DeleteSeasonViewModel(CurrentPage, Services.UserService)
            {
                Season = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl, true).ConfigureAwait(false),
            };

            viewModel.IsAuthorized = _authorizationPolicy.IsAuthorized(viewModel.Season.Competition);

            // Create a version without circular references before it gets serialised for audit
            viewModel.Season.Teams = viewModel.Season.Teams.Select(x => new TeamInSeason {
                Team = x.Team, WithdrawnDate = x.WithdrawnDate
            }).ToList();

            if (viewModel.IsAuthorized[AuthorizedAction.DeleteCompetition] && ModelState.IsValid)
            {
                var currentMember = Members.GetCurrentMember();
                await _seasonRepository.DeleteSeason(viewModel.Season, currentMember.Key, currentMember.Name).ConfigureAwait(false);

                viewModel.Deleted = true;
            }
            else
            {
                viewModel.TotalMatches = await _matchDataSource.ReadTotalMatches(new MatchFilter
                {
                    SeasonIds = new List <Guid> {
                        viewModel.Season.SeasonId.Value
                    },
                    IncludeTournamentMatches = true
                }).ConfigureAwait(false);
            }

            viewModel.Metadata.PageTitle = $"Delete {viewModel.Season.SeasonFullNameAndPlayerType()}";

            viewModel.Breadcrumbs.Add(new Breadcrumb {
                Name = Constants.Pages.Competitions, Url = new Uri(Constants.Pages.CompetitionsUrl, UriKind.Relative)
            });
            viewModel.Breadcrumbs.Add(new Breadcrumb {
                Name = viewModel.Season.Competition.CompetitionName, Url = new Uri(viewModel.Season.Competition.CompetitionRoute, UriKind.Relative)
            });
            if (!viewModel.Deleted)
            {
                viewModel.Breadcrumbs.Add(new Breadcrumb {
                    Name = viewModel.Season.SeasonName(), Url = new Uri(viewModel.Season.SeasonRoute, UriKind.Relative)
                });
            }

            return(View("DeleteSeason", viewModel));
        }
        public async override Task <ActionResult> Index(ContentModel contentModel)
        {
            if (contentModel is null)
            {
                throw new ArgumentNullException(nameof(contentModel));
            }

            var model = new SeasonViewModel(contentModel.Content, Services?.UserService)
            {
                Season = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl, true).ConfigureAwait(false)
            };

            if (model.Season == null || (!model.Season.MatchTypes.Contains(MatchType.LeagueMatch) &&
                                         !model.Season.MatchTypes.Contains(MatchType.KnockoutMatch) &&
                                         !model.Season.MatchTypes.Contains(MatchType.FriendlyMatch) &&
                                         string.IsNullOrEmpty(model.Season.Results)))
            {
                return(new HttpNotFoundResult());
            }
            else
            {
                model.Matches = new MatchListingViewModel(contentModel.Content, Services?.UserService)
                {
                    Matches = await _matchDataSource.ReadMatchListings(new MatchFilter
                    {
                        SeasonIds = new List <Guid> {
                            model.Season.SeasonId.Value
                        },
                        IncludeTournaments = false
                    }, MatchSortOrder.MatchDateEarliestFirst).ConfigureAwait(false),
                    DateTimeFormatter = _dateTimeFormatter
                };
                model.Season.PointsRules.AddRange(await _seasonDataSource.ReadPointsRules(model.Season.SeasonId.Value).ConfigureAwait(false));
                model.Season.PointsAdjustments.AddRange(await _seasonDataSource.ReadPointsAdjustments(model.Season.SeasonId.Value).ConfigureAwait(false));

                model.Season.Results = _emailProtector.ProtectEmailAddresses(model.Season.Results, User.Identity.IsAuthenticated);

                model.IsAuthorized = _authorizationPolicy.IsAuthorized(model.Season.Competition);

                var the = model.Season.Competition.CompetitionName.StartsWith("THE ", StringComparison.OrdinalIgnoreCase);
                model.Metadata.PageTitle   = $"Results table for {(the ? string.Empty : "the ")}{model.Season.SeasonFullNameAndPlayerType()}";
                model.Metadata.Description = model.Season.Description();

                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = Constants.Pages.Competitions, Url = new Uri(Constants.Pages.CompetitionsUrl, UriKind.Relative)
                });
                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = model.Season.Competition.CompetitionName, Url = new Uri(model.Season.Competition.CompetitionRoute, UriKind.Relative)
                });

                return(CurrentTemplate(model));
            }
        }
        public async override Task <ActionResult> Index(ContentModel contentModel)
        {
            if (contentModel is null)
            {
                throw new ArgumentNullException(nameof(contentModel));
            }

            var model = new EditTrainingSessionViewModel(contentModel.Content, Services?.UserService)
            {
                Match = new Match
                {
                    MatchType     = MatchType.TrainingSession,
                    MatchLocation = new MatchLocation()
                }
            };

            if (Request.RawUrl.StartsWith("/teams/", StringComparison.OrdinalIgnoreCase))
            {
                model.Team = await _teamDataSource.ReadTeamByRoute(Request.RawUrl, true).ConfigureAwait(false);

                if (model.Team == null)
                {
                    return(new HttpNotFoundResult());
                }

                var possibleSeasons = _createMatchSeasonSelector.SelectPossibleSeasons(model.Team.Seasons, model.Match.MatchType);
                model.PossibleSeasons = _editMatchHelper.PossibleSeasonsAsListItems(possibleSeasons);

                model.Match.Teams.Add(new TeamInMatch {
                    Team = model.Team
                });
                model.MatchLocationId   = model.Team.MatchLocations.FirstOrDefault()?.MatchLocationId;
                model.MatchLocationName = model.Team.MatchLocations.FirstOrDefault()?.NameAndLocalityOrTownIfDifferent();
            }
            else if (Request.RawUrl.StartsWith("/competitions/", StringComparison.OrdinalIgnoreCase))
            {
                model.Match.Season = model.Season = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl, false).ConfigureAwait(false);

                if (model.Season == null || !model.Season.MatchTypes.Contains(MatchType.TrainingSession))
                {
                    return(new HttpNotFoundResult());
                }
            }

            model.IsAuthorized[AuthorizedAction.CreateMatch] = User.Identity.IsAuthenticated;

            _editMatchHelper.ConfigureAddMatchModelMetadata(model);

            model.Breadcrumbs.Add(new Breadcrumb {
                Name = Constants.Pages.Matches, Url = new Uri(Constants.Pages.MatchesUrl, UriKind.Relative)
            });
            return(CurrentTemplate(model));
        }
Beispiel #8
0
        public async Task <ActionResult> UpdateSeason([Bind(Prefix = "Season", Include = "PointsRules,ResultsTableType,EnableRunsScored,EnableRunsConceded")] Season season)
        {
            if (season is null)
            {
                throw new ArgumentNullException(nameof(season));
            }

            var beforeUpdate = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl).ConfigureAwait(false);

            season.SeasonId = beforeUpdate.SeasonId;

            var isAuthorized = _authorizationPolicy.IsAuthorized(beforeUpdate.Competition);

            if (isAuthorized[AuthorizedAction.EditCompetition] && ModelState.IsValid)
            {
                // Update the season
                var currentMember = Members.GetCurrentMember();
                await _seasonRepository.UpdateResultsTable(season, currentMember.Key, currentMember.Name).ConfigureAwait(false);

                return(_postSaveRedirector.WorkOutRedirect(beforeUpdate.SeasonRoute, beforeUpdate.SeasonRoute, "/edit", Request.Form["UrlReferrer"], null));
            }

            var viewModel = new SeasonViewModel(CurrentPage, Services.UserService)
            {
                Season      = season,
                UrlReferrer = string.IsNullOrEmpty(Request.Form["UrlReferrer"]) ? null : new Uri(Request.Form["UrlReferrer"])
            };

            viewModel.IsAuthorized = isAuthorized;
            season.Competition     = beforeUpdate.Competition;
            season.FromYear        = beforeUpdate.FromYear;
            season.UntilYear       = beforeUpdate.UntilYear;
            season.SeasonRoute     = beforeUpdate.SeasonRoute;

            viewModel.Metadata.PageTitle = $"Edit results table for {beforeUpdate.SeasonFullNameAndPlayerType()}";

            viewModel.Breadcrumbs.Add(new Breadcrumb {
                Name = Constants.Pages.Competitions, Url = new Uri(Constants.Pages.CompetitionsUrl, UriKind.Relative)
            });
            viewModel.Breadcrumbs.Add(new Breadcrumb {
                Name = viewModel.Season.Competition.CompetitionName, Url = new Uri(viewModel.Season.Competition.CompetitionRoute, UriKind.Relative)
            });
            viewModel.Breadcrumbs.Add(new Breadcrumb {
                Name = viewModel.Season.SeasonName(), Url = new Uri(viewModel.Season.SeasonRoute, UriKind.Relative)
            });

            return(View("EditSeasonResultsTable", viewModel));
        }
Beispiel #9
0
        public async override Task <ActionResult> Index(ContentModel contentModel)
        {
            if (contentModel is null)
            {
                throw new ArgumentNullException(nameof(contentModel));
            }

            var model = new DeleteSeasonViewModel(contentModel.Content, Services?.UserService)
            {
                Season = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl, true).ConfigureAwait(false)
            };

            if (model.Season == null)
            {
                return(new HttpNotFoundResult());
            }
            else
            {
                model.TotalMatches = await _matchDataSource.ReadTotalMatches(new MatchFilter
                {
                    SeasonIds = new List <Guid> {
                        model.Season.SeasonId.Value
                    },
                    IncludeTournamentMatches = true
                }).ConfigureAwait(false);

                model.ConfirmDeleteRequest.RequiredText = model.Season.SeasonFullName();

                model.IsAuthorized = _authorizationPolicy.IsAuthorized(model.Season.Competition);

                model.Metadata.PageTitle = "Delete " + model.Season.SeasonFullNameAndPlayerType();

                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = Constants.Pages.Competitions, Url = new Uri(Constants.Pages.CompetitionsUrl, UriKind.Relative)
                });
                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = model.Season.Competition.CompetitionName, Url = new Uri(model.Season.Competition.CompetitionRoute, UriKind.Relative)
                });
                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = model.Season.SeasonName(), Url = new Uri(model.Season.SeasonRoute, UriKind.Relative)
                });

                return(CurrentTemplate(model));
            }
        }
        public async override Task <ActionResult> Index(ContentModel contentModel)
        {
            if (contentModel is null)
            {
                throw new ArgumentNullException(nameof(contentModel));
            }

            var season = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl, false).ConfigureAwait(false);

            if (season == null)
            {
                return(new HttpNotFoundResult());
            }
            else
            {
                var filter = _matchFilterFactory.MatchesForSeason(season.SeasonId.Value);
                var model  = new SeasonViewModel(contentModel.Content, Services?.UserService)
                {
                    Season  = season,
                    Matches = new MatchListingViewModel(contentModel.Content, Services?.UserService)
                    {
                        Matches           = await _matchDataSource.ReadMatchListings(filter.filter, filter.sortOrder).ConfigureAwait(false),
                        DateTimeFormatter = _dateFormatter
                    },
                };
                if (model.Season.MatchTypes.Contains(MatchType.LeagueMatch) || model.Season.MatchTypes.Contains(MatchType.KnockoutMatch))
                {
                    model.Matches.MatchTypesToLabel.Add(MatchType.FriendlyMatch);
                }

                model.IsAuthorized = _authorizationPolicy.IsAuthorized(model.Season.Competition);

                model.Metadata.PageTitle = $"Matches and tournaments in {model.Season.SeasonFullNameAndPlayerType()}";

                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = Constants.Pages.Competitions, Url = new Uri(Constants.Pages.CompetitionsUrl, UriKind.Relative)
                });
                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = model.Season.Competition.CompetitionName, Url = new Uri(model.Season.Competition.CompetitionRoute, UriKind.Relative)
                });

                return(CurrentTemplate(model));
            }
        }
        public async override Task <ActionResult> Index(ContentModel contentModel)
        {
            if (contentModel is null)
            {
                throw new ArgumentNullException(nameof(contentModel));
            }

            var model = new StatisticsSummaryViewModel <Season>(contentModel.Content, Services?.UserService)
            {
                Context = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl, true).ConfigureAwait(false),
            };

            if (model.Context == null)
            {
                return(new HttpNotFoundResult());
            }
            else
            {
                model.DefaultFilter = new StatisticsFilter {
                    Season = model.Context, MaxResultsAllowingExtraResultsIfValuesAreEqual = 10
                };
                model.AppliedFilter  = model.DefaultFilter.Clone();
                model.PlayerInnings  = (await _bestPerformanceDataSource.ReadPlayerInnings(model.AppliedFilter, StatisticsSortOrder.BestFirst).ConfigureAwait(false)).ToList();
                model.BowlingFigures = (await _bestPerformanceDataSource.ReadBowlingFigures(model.AppliedFilter, StatisticsSortOrder.BestFirst).ConfigureAwait(false)).ToList();
                model.MostRuns       = (await _bestPlayerTotalDataSource.ReadMostRunsScored(model.AppliedFilter).ConfigureAwait(false)).ToList();
                model.MostWickets    = (await _bestPlayerTotalDataSource.ReadMostWickets(model.AppliedFilter).ConfigureAwait(false)).ToList();
                model.MostCatches    = (await _bestPlayerTotalDataSource.ReadMostCatches(model.AppliedFilter).ConfigureAwait(false)).ToList();

                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = Constants.Pages.Competitions, Url = new Uri(Constants.Pages.CompetitionsUrl, UriKind.Relative)
                });
                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = model.Context.Competition.CompetitionName, Url = new Uri(model.Context.Competition.CompetitionRoute, UriKind.Relative)
                });

                model.Metadata.PageTitle   = $"Statistics for {model.Context.SeasonFullNameAndPlayerType()}";
                model.Metadata.Description = $"Statistics for stoolball matches played in the {model.Context.SeasonFullName()}.";

                return(CurrentTemplate(model));
            }
        }
Beispiel #12
0
        public async Task <StatisticsFilter> FromRoute(string route)
        {
            if (string.IsNullOrWhiteSpace(route))
            {
                throw new ArgumentException($"'{nameof(route)}' cannot be null or whitespace.", nameof(route));
            }

            var entityType = _stoolballEntityRouteParser.ParseRoute(route);

            var filter = new StatisticsFilter {
                Paging = new Paging {
                    PageSize = Constants.Defaults.PageSize
                }
            };

            if (entityType == StoolballEntityType.Player)
            {
                filter.Player = await _playerDataSource.ReadPlayerByRoute(_routeNormaliser.NormaliseRouteToEntity(route, "players")).ConfigureAwait(false);
            }
            else if (entityType == StoolballEntityType.Club)
            {
                filter.Club = await _clubDataSource.ReadClubByRoute(_routeNormaliser.NormaliseRouteToEntity(route, "clubs")).ConfigureAwait(false);
            }
            else if (entityType == StoolballEntityType.Team)
            {
                filter.Team = await _teamDataSource.ReadTeamByRoute(_routeNormaliser.NormaliseRouteToEntity(route, "teams"), true).ConfigureAwait(false); // true gets a lot of data but we only really want the club
            }
            else if (entityType == StoolballEntityType.MatchLocation)
            {
                filter.MatchLocation = await _matchLocationDataSource.ReadMatchLocationByRoute(_routeNormaliser.NormaliseRouteToEntity(route, "locations"), false).ConfigureAwait(false);
            }
            else if (entityType == StoolballEntityType.Season)
            {
                filter.Season = await _seasonDataSource.ReadSeasonByRoute(_routeNormaliser.NormaliseRouteToEntity(route, "competitions", Constants.Pages.SeasonUrlRegEx)).ConfigureAwait(false);
            }
            else if (entityType == StoolballEntityType.Competition)
            {
                filter.Competition = await _competitionDataSource.ReadCompetitionByRoute(_routeNormaliser.NormaliseRouteToEntity(route, "competitions")).ConfigureAwait(false);
            }
            return(filter);
        }
Beispiel #13
0
        private async Task AddMissingTeamsFromRequest(EditStartOfPlayViewModel model, ModelStateDictionary modelState)
        {
            if (model.Match.MatchType == MatchType.KnockoutMatch &&
                !string.IsNullOrEmpty(model.Match.Season?.SeasonRoute) &&
                (
                    model.Match.Teams.SingleOrDefault(x => x.TeamRole == TeamRole.Home) == null ||
                    model.Match.Teams.SingleOrDefault(x => x.TeamRole == TeamRole.Away) == null
                ))
            {
                var season = await _seasonDataSource.ReadSeasonByRoute(model.Match.Season?.SeasonRoute, true).ConfigureAwait(false);

                if (season != null)
                {
                    model.PossibleHomeTeams = _editMatchHelper.PossibleTeamsAsListItems(season.Teams);
                    model.PossibleAwayTeams = _editMatchHelper.PossibleTeamsAsListItems(season.Teams);

                    // Add teams to model.Teams only if they're missing and if the posted team is from the same season.
                    // By getting it from the season this also adds the team name, which is used to build the match name.
                    AddTeamIfMissing(model.Match.Teams, season.Teams, TeamRole.Home);
                    AddTeamIfMissing(model.Match.Teams, season.Teams, TeamRole.Away);
                }
            }

            if (model.Match.MatchType == MatchType.FriendlyMatch)
            {
                // Add teams to model.Teams only if they're missing,
                AddTeamIfMissing(model.Match.Teams, TeamRole.Home);
                AddTeamIfMissing(model.Match.Teams, TeamRole.Away);
            }

            if (model.Match.MatchType == MatchType.KnockoutMatch &&
                model.Match.Teams.Count == 2 &&
                model.Match.Teams[0].Team.TeamId == model.Match.Teams[1].Team.TeamId)
            {
                modelState.AddModelError("AwayTeamId", "The away team cannot be the same as the home team");
            }
        }
Beispiel #14
0
        public async override Task <ActionResult> Index(ContentModel contentModel)
        {
            if (contentModel is null)
            {
                throw new ArgumentNullException(nameof(contentModel));
            }

            var model = new EditStartOfPlayViewModel(contentModel.Content, Services?.UserService)
            {
                Match         = await _matchDataSource.ReadMatchByRoute(Request.RawUrl).ConfigureAwait(false),
                DateFormatter = _dateFormatter
            };

            if (model.Match == null || model.Match.Tournament != null)
            {
                return(new HttpNotFoundResult());
            }
            else
            {
                // This page is only for matches in the past
                if (model.Match.StartTime > DateTime.UtcNow)
                {
                    return(new HttpNotFoundResult());
                }

                model.IsAuthorized = _authorizationPolicy.IsAuthorized(model.Match);

                if (model.Match.MatchResultType.HasValue)
                {
                    model.MatchWentAhead = (model.Match.MatchResultType == MatchResultType.HomeWin || model.Match.MatchResultType == MatchResultType.AwayWin || model.Match.MatchResultType == MatchResultType.Tie);
                }

                if (model.Match.MatchType == MatchType.KnockoutMatch && model.Match.Season != null)
                {
                    model.Match.Season = await _seasonDataSource.ReadSeasonByRoute(model.Match.Season.SeasonRoute, true).ConfigureAwait(false);

                    model.PossibleHomeTeams = _editMatchHelper.PossibleTeamsAsListItems(model.Match.Season?.Teams);
                    model.PossibleAwayTeams = _editMatchHelper.PossibleTeamsAsListItems(model.Match.Season?.Teams);
                }

                model.HomeTeamId        = model.Match.Teams.SingleOrDefault(x => x.TeamRole == TeamRole.Home)?.Team.TeamId;
                model.AwayTeamId        = model.Match.Teams.SingleOrDefault(x => x.TeamRole == TeamRole.Away)?.Team.TeamId;
                model.MatchLocationId   = model.Match.MatchLocation?.MatchLocationId;
                model.MatchLocationName = model.Match.MatchLocation?.NameAndLocalityOrTownIfDifferent();
                model.TossWonBy         = model.Match.Teams.FirstOrDefault(x => x.WonToss.HasValue && x.WonToss.Value)?.MatchTeamId.ToString();
                model.BattedFirst       = model.Match.InningsOrderIsKnown ? model.Match.MatchInnings.First().BattingTeam.MatchTeamId.ToString() : null;

                model.Metadata.PageTitle = "Edit " + model.Match.MatchFullName(x => _dateFormatter.FormatDate(x, false, false, false));

                if (model.Match.Season != null)
                {
                    model.Breadcrumbs.Add(new Breadcrumb {
                        Name = Constants.Pages.Competitions, Url = new Uri(Constants.Pages.CompetitionsUrl, UriKind.Relative)
                    });
                    model.Breadcrumbs.Add(new Breadcrumb {
                        Name = model.Match.Season.Competition.CompetitionName, Url = new Uri(model.Match.Season.Competition.CompetitionRoute, UriKind.Relative)
                    });
                    model.Breadcrumbs.Add(new Breadcrumb {
                        Name = model.Match.Season.SeasonName(), Url = new Uri(model.Match.Season.SeasonRoute, UriKind.Relative)
                    });
                }
                else
                {
                    model.Breadcrumbs.Add(new Breadcrumb {
                        Name = Constants.Pages.Matches, Url = new Uri(Constants.Pages.MatchesUrl, UriKind.Relative)
                    });
                }
                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = model.Match.MatchName, Url = new Uri(model.Match.MatchRoute, UriKind.Relative)
                });

                return(CurrentTemplate(model));
            }
        }
        public async Task <ActionResult> UpdateMatch([Bind(Prefix = "Match", Include = "MatchResultType")] Match postedMatch)
        {
            if (postedMatch is null)
            {
                throw new ArgumentNullException(nameof(postedMatch));
            }

            var beforeUpdate = await _matchDataSource.ReadMatchByRoute(Request.RawUrl).ConfigureAwait(false);

            // This controller is only for matches in the future
            if (beforeUpdate.StartTime <= DateTime.UtcNow || beforeUpdate.Tournament != null)
            {
                return(new HttpNotFoundResult());
            }

            var model = new EditLeagueMatchViewModel(CurrentPage, Services.UserService)
            {
                Match         = postedMatch,
                DateFormatter = _dateTimeFormatter
            };

            model.Match.MatchId    = beforeUpdate.MatchId;
            model.Match.MatchRoute = beforeUpdate.MatchRoute;
            model.Match.UpdateMatchNameAutomatically = beforeUpdate.UpdateMatchNameAutomatically;
            model.Match.Season = beforeUpdate.Season;

            _editMatchHelper.ConfigureModelFromRequestData(model, Request.Unvalidated.Form, Request.Form, ModelState);

            _matchValidator.DateIsValidForSqlServer(() => model.MatchDate, ModelState, "MatchDate", "match");
            _matchValidator.DateIsWithinTheSeason(() => model.MatchDate, model.Match.Season, ModelState, "MatchDate", "match");
            _matchValidator.TeamsMustBeDifferent(model, ModelState);

            model.IsAuthorized = _authorizationPolicy.IsAuthorized(beforeUpdate);

            if (model.IsAuthorized[AuthorizedAction.EditMatch] && ModelState.IsValid)
            {
                if ((int?)model.Match.MatchResultType == -1)
                {
                    model.Match.MatchResultType = null;
                }

                var currentMember = Members.GetCurrentMember();
                var updatedMatch  = await _matchRepository.UpdateMatch(model.Match, currentMember.Key, currentMember.Name).ConfigureAwait(false);

                await _cacheClearer.ClearCacheFor(updatedMatch).ConfigureAwait(false);

                return(Redirect(updatedMatch.MatchRoute));
            }

            model.Match.MatchName = beforeUpdate.MatchName;
            model.Match.Season    = model.Season = await _seasonDataSource.ReadSeasonByRoute(model.Match.Season.SeasonRoute, true).ConfigureAwait(false);

            model.PossibleSeasons    = _editMatchHelper.PossibleSeasonsAsListItems(new[] { model.Match.Season });
            model.PossibleHomeTeams  = _editMatchHelper.PossibleTeamsAsListItems(model.Season.Teams);
            model.PossibleAwayTeams  = _editMatchHelper.PossibleTeamsAsListItems(model.Season.Teams);
            model.Metadata.PageTitle = "Edit " + model.Match.MatchFullName(x => _dateTimeFormatter.FormatDate(x, false, false, false));

            if (model.Match.Season != null)
            {
                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = Constants.Pages.Competitions, Url = new Uri(Constants.Pages.CompetitionsUrl, UriKind.Relative)
                });
                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = model.Match.Season.Competition.CompetitionName, Url = new Uri(model.Match.Season.Competition.CompetitionRoute, UriKind.Relative)
                });
                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = model.Match.Season.SeasonName(), Url = new Uri(model.Match.Season.SeasonRoute, UriKind.Relative)
                });
            }
            else
            {
                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = Constants.Pages.Matches, Url = new Uri(Constants.Pages.MatchesUrl, UriKind.Relative)
                });
            }
            model.Breadcrumbs.Add(new Breadcrumb {
                Name = model.Match.MatchName, Url = new Uri(model.Match.MatchRoute, UriKind.Relative)
            });

            return(View("EditLeagueMatch", model));
        }
        public async Task <ActionResult> UpdateSeason([Bind(Prefix = "Season", Include = "EnableTournaments,PlayersPerTeam,DefaultOverSets,EnableLastPlayerBatsOn,EnableBonusOrPenaltyRuns")] Season season)
        {
            if (season is null)
            {
                throw new ArgumentNullException(nameof(season));
            }

            var beforeUpdate = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl).ConfigureAwait(false);

            season.DefaultOverSets.RemoveAll(x => !x.Overs.HasValue);

            // get this from the unvalidated form instead of via modelbinding so that HTML can be allowed
            season.SeasonId     = beforeUpdate.SeasonId;
            season.Introduction = Request.Unvalidated.Form["Season.Introduction"];
            season.Results      = Request.Unvalidated.Form["Season.Results"];

            try
            {
                // parse this because there's no way to get it via the standard modelbinder without requiring JavaScript to change the field names on submit
                season.MatchTypes = Request.Form["Season.MatchTypes"]?.Split(',').Select(x => (MatchType)Enum.Parse(typeof(MatchType), x)).ToList() ?? new List <MatchType>();
            }
            catch (InvalidCastException)
            {
                return(new HttpStatusCodeResult(400));
            }

            if (!season.MatchTypes.Any())
            {
                ModelState.AddModelError("Season.MatchTypes", $"Please select at least one type of match");
            }

            var isAuthorized = _authorizationPolicy.IsAuthorized(beforeUpdate.Competition);

            if (isAuthorized[AuthorizedAction.EditCompetition] && ModelState.IsValid)
            {
                // Update the season
                var currentMember = Members.GetCurrentMember();
                await _seasonRepository.UpdateSeason(season, currentMember.Key, currentMember.Name).ConfigureAwait(false);

                // Redirect to the season actions page that led here
                return(Redirect(beforeUpdate.SeasonRoute + "/edit"));
            }

            var viewModel = new SeasonViewModel(CurrentPage, Services.UserService)
            {
                Season = beforeUpdate,
            };

            viewModel.IsAuthorized       = isAuthorized;
            viewModel.Metadata.PageTitle = $"Edit {beforeUpdate.SeasonFullNameAndPlayerType()}";

            viewModel.Breadcrumbs.Add(new Breadcrumb {
                Name = Constants.Pages.Competitions, Url = new Uri(Constants.Pages.CompetitionsUrl, UriKind.Relative)
            });
            viewModel.Breadcrumbs.Add(new Breadcrumb {
                Name = viewModel.Season.Competition.CompetitionName, Url = new Uri(viewModel.Season.Competition.CompetitionRoute, UriKind.Relative)
            });
            viewModel.Breadcrumbs.Add(new Breadcrumb {
                Name = viewModel.Season.SeasonName(), Url = new Uri(viewModel.Season.SeasonRoute, UriKind.Relative)
            });

            return(View("EditSeason", viewModel));
        }
Beispiel #17
0
        public async Task <ActionResult> CreateMatch([Bind(Prefix = "Match", Include = "Season")] Match postedMatch)
        {
            if (postedMatch is null)
            {
                throw new ArgumentNullException(nameof(postedMatch));
            }

            var model = new EditLeagueMatchViewModel(CurrentPage, Services.UserService)
            {
                Match = postedMatch
            };

            model.Match.MatchType = MatchType.LeagueMatch;
            _editMatchHelper.ConfigureModelFromRequestData(model, Request.Unvalidated.Form, Request.Form, ModelState);

            if (Request.RawUrl.StartsWith("/competitions/", StringComparison.OrdinalIgnoreCase))
            {
                model.Match.Season = model.Season = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl, true).ConfigureAwait(false);
            }
            else if (model.Match.Season != null && model.Match.Season.SeasonId.HasValue)
            {
                // Get the season, to support validation against season dates
                model.Match.Season = await _seasonDataSource.ReadSeasonById(model.Match.Season.SeasonId.Value).ConfigureAwait(false);
            }

            _matchValidator.DateIsValidForSqlServer(() => model.MatchDate, ModelState, "MatchDate", "match");
            _matchValidator.DateIsWithinTheSeason(() => model.MatchDate, model.Match.Season, ModelState, "MatchDate", "match");
            _matchValidator.TeamsMustBeDifferent(model, ModelState);

            model.IsAuthorized[AuthorizedAction.CreateMatch] = User.Identity.IsAuthenticated;

            if (model.IsAuthorized[AuthorizedAction.CreateMatch] && ModelState.IsValid &&
                (model.Team == null || (model.PossibleSeasons != null && model.PossibleSeasons.Any())) &&
                (model.Season == null || model.Season.MatchTypes.Contains(MatchType.LeagueMatch)))
            {
                var currentMember = Members.GetCurrentMember();
                var createdMatch  = await _matchRepository.CreateMatch(model.Match, currentMember.Key, currentMember.Name).ConfigureAwait(false);

                await _cacheClearer.ClearCacheFor(createdMatch).ConfigureAwait(false);

                return(Redirect(createdMatch.MatchRoute));
            }

            if (Request.RawUrl.StartsWith("/teams/", StringComparison.OrdinalIgnoreCase))
            {
                model.Team = await _teamDataSource.ReadTeamByRoute(Request.RawUrl, true).ConfigureAwait(false);

                var possibleSeasons = _createMatchSeasonSelector.SelectPossibleSeasons(model.Team.Seasons, model.Match.MatchType).ToList();
                if (possibleSeasons.Count == 1)
                {
                    model.Match.Season = possibleSeasons.First();
                }
                model.PossibleSeasons = _editMatchHelper.PossibleSeasonsAsListItems(possibleSeasons);
                await _editMatchHelper.ConfigureModelPossibleTeams(model, possibleSeasons).ConfigureAwait(false);

                model.Metadata.PageTitle = $"Add a {MatchType.LeagueMatch.Humanize(LetterCasing.LowerCase)} for {model.Team.TeamName}";
            }
            else
            {
                model.PossibleSeasons    = _editMatchHelper.PossibleSeasonsAsListItems(new[] { model.Match.Season });
                model.PossibleHomeTeams  = _editMatchHelper.PossibleTeamsAsListItems(model.Season?.Teams);
                model.PossibleAwayTeams  = _editMatchHelper.PossibleTeamsAsListItems(model.Season?.Teams);
                model.Metadata.PageTitle = $"Add a {MatchType.LeagueMatch.Humanize(LetterCasing.LowerCase)} in the {model.Season.SeasonFullName()}";
            }

            model.Breadcrumbs.Add(new Breadcrumb {
                Name = Constants.Pages.Matches, Url = new Uri(Constants.Pages.MatchesUrl, UriKind.Relative)
            });
            return(View("CreateLeagueMatch", model));
        }
        public async Task <ActionResult> CreateTournament([Bind(Prefix = "Tournament", Include = "TournamentName,QualificationType,PlayerType,PlayersPerTeam,DefaultOverSets")] Tournament postedTournament)
        {
            if (postedTournament is null)
            {
                throw new ArgumentNullException(nameof(postedTournament));
            }

            postedTournament.DefaultOverSets.RemoveAll(x => !x.Overs.HasValue);
            var model = new EditTournamentViewModel(CurrentPage, Services.UserService)
            {
                Tournament = postedTournament
            };

            // get this from the unvalidated form instead of via modelbinding so that HTML can be allowed
            model.Tournament.TournamentNotes = Request.Unvalidated.Form["Tournament.TournamentNotes"];

            if (!string.IsNullOrEmpty(Request.Form["TournamentDate"]) && DateTimeOffset.TryParse(Request.Form["TournamentDate"], out var parsedDate))
            {
                model.TournamentDate       = parsedDate;
                model.Tournament.StartTime = model.TournamentDate.Value;

                if (!string.IsNullOrEmpty(Request.Form["StartTime"]))
                {
                    if (DateTimeOffset.TryParse(Request.Form["StartTime"], out var parsedTime))
                    {
                        model.StartTime                   = parsedTime;
                        model.Tournament.StartTime        = model.Tournament.StartTime.Add(model.StartTime.Value.TimeOfDay);
                        model.Tournament.StartTimeIsKnown = true;
                    }
                    else
                    {
                        // This may be seen in browsers that don't support <input type="time" />, mainly Safari.
                        // Each browser that supports <input type="time" /> may have a very different interface so don't advertise
                        // this format up-front as it could confuse the majority. Instead, only reveal it here.
                        ModelState.AddModelError("StartTime", "Enter a time in 24-hour HH:MM format.");
                    }
                }
                else
                {
                    // If no start time specified, use a typical one but don't show it
                    model.Tournament.StartTime.AddHours(11);
                    model.Tournament.StartTimeIsKnown = false;
                }
            }
            else
            {
                // This may be seen in browsers that don't support <input type="date" />, mainly Safari.
                // This is the format <input type="date" /> expects and posts, so we have to repopulate the field in this format,
                // so although this code _can_ parse other formats we don't advertise that. We also don't want YYYY-MM-DD in
                // the field label as it could confuse the majority, so only reveal it here.
                ModelState.AddModelError("TournamentDate", "Enter a date in YYYY-MM-DD format.");
            }

            _matchValidator.DateIsValidForSqlServer(() => model.TournamentDate, ModelState, "TournamentDate", "tournament");

            if (Request.RawUrl.StartsWith("/teams/", StringComparison.OrdinalIgnoreCase))
            {
                model.Team = await _teamDataSource.ReadTeamByRoute(Request.RawUrl, true).ConfigureAwait(false);

                model.Tournament.Teams.Add(new TeamInTournament {
                    Team = model.Team, TeamRole = TournamentTeamRole.Organiser
                });
                model.Metadata.PageTitle = $"Add a tournament for {model.Team.TeamName}";
            }
            else if (Request.RawUrl.StartsWith("/competitions/", StringComparison.OrdinalIgnoreCase))
            {
                model.Season = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl, false).ConfigureAwait(false);

                model.Tournament.Seasons.Add(model.Season);
                model.Metadata.PageTitle = $"Add a tournament in the {model.Season.SeasonFullName()}";

                _matchValidator.DateIsWithinTheSeason(() => model.TournamentDate, model.Season, ModelState, "TournamentDate", "tournament");
            }

            if (!string.IsNullOrEmpty(Request.Form["TournamentLocationId"]))
            {
                model.TournamentLocationId          = new Guid(Request.Form["TournamentLocationId"]);
                model.TournamentLocationName        = Request.Form["TournamentLocationName"];
                model.Tournament.TournamentLocation = new MatchLocation
                {
                    MatchLocationId = model.TournamentLocationId
                };
            }

            model.IsAuthorized[AuthorizedAction.CreateTournament] = User.Identity.IsAuthenticated;

            if (model.IsAuthorized[AuthorizedAction.CreateTournament] && ModelState.IsValid &&
                (model.Team != null ||
                 (model.Season != null && model.Season.EnableTournaments)))
            {
                var currentMember     = Members.GetCurrentMember();
                var createdTournament = await _tournamentRepository.CreateTournament(model.Tournament, currentMember.Key, currentMember.Name).ConfigureAwait(false);

                await _cacheClearer.ClearCacheFor(createdTournament).ConfigureAwait(false);

                return(Redirect(createdTournament.TournamentRoute));
            }

            model.Breadcrumbs.Add(new Breadcrumb {
                Name = Constants.Pages.Tournaments, Url = new Uri(Constants.Pages.TournamentsUrl, UriKind.Relative)
            });

            return(View("CreateTournament", model));
        }
        public async override Task <ActionResult> Index(ContentModel contentModel)
        {
            if (contentModel is null)
            {
                throw new ArgumentNullException(nameof(contentModel));
            }

            var model = new EditLeagueMatchViewModel(contentModel.Content, Services?.UserService)
            {
                Match = new Match
                {
                    MatchType     = MatchType.LeagueMatch,
                    MatchLocation = new MatchLocation()
                }
            };

            if (Request.RawUrl.StartsWith("/teams/", StringComparison.OrdinalIgnoreCase))
            {
                model.Team = await _teamDataSource.ReadTeamByRoute(Request.RawUrl, true).ConfigureAwait(false);

                if (model.Team == null)
                {
                    return(new HttpNotFoundResult());
                }

                var possibleSeasons = _createMatchSeasonSelector.SelectPossibleSeasons(model.Team.Seasons, model.Match.MatchType).ToList();

                if (possibleSeasons.Count == 0)
                {
                    return(new HttpNotFoundResult());
                }

                if (possibleSeasons.Count == 1)
                {
                    model.Match.Season = possibleSeasons.First();
                }

                model.PossibleSeasons = _editMatchHelper.PossibleSeasonsAsListItems(possibleSeasons);

                await _editMatchHelper.ConfigureModelPossibleTeams(model, possibleSeasons).ConfigureAwait(false);

                model.HomeTeamId        = model.Team.TeamId;
                model.MatchLocationId   = model.Team.MatchLocations.FirstOrDefault()?.MatchLocationId;
                model.MatchLocationName = model.Team.MatchLocations.FirstOrDefault()?.NameAndLocalityOrTownIfDifferent();

                if (model.PossibleAwayTeams.Count > 1)
                {
                    model.AwayTeamId = new Guid(model.PossibleAwayTeams[1].Value);
                }
            }
            else if (Request.RawUrl.StartsWith("/competitions/", StringComparison.OrdinalIgnoreCase))
            {
                model.Match.Season = model.Season = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl, true).ConfigureAwait(false);

                if (model.Season == null || !model.Season.MatchTypes.Contains(MatchType.LeagueMatch))
                {
                    return(new HttpNotFoundResult());
                }
                model.PossibleSeasons = _editMatchHelper.PossibleSeasonsAsListItems(new[] { model.Match.Season });

                model.PossibleHomeTeams = _editMatchHelper.PossibleTeamsAsListItems(model.Season.Teams);
                if (model.PossibleHomeTeams.Count > 0)
                {
                    model.HomeTeamId = new Guid(model.PossibleHomeTeams[0].Value);
                }

                model.PossibleAwayTeams = _editMatchHelper.PossibleTeamsAsListItems(model.Season.Teams);
                if (model.PossibleAwayTeams.Count > 1)
                {
                    model.AwayTeamId = new Guid(model.PossibleAwayTeams[1].Value);
                }
            }

            model.IsAuthorized[AuthorizedAction.CreateMatch] = User.Identity.IsAuthenticated;
            if (model.Season != null && model.Season.Teams.Count <= 1 && model.Season.Competition != null)
            {
                _competitionAuthorizationPolicy.IsAuthorized(model.Season.Competition).TryGetValue(AuthorizedAction.EditCompetition, out var canEditCompetition);
                model.IsAuthorized[AuthorizedAction.EditCompetition] = canEditCompetition;
            }

            _editMatchHelper.ConfigureAddMatchModelMetadata(model);

            model.Breadcrumbs.Add(new Breadcrumb {
                Name = Constants.Pages.Matches, Url = new Uri(Constants.Pages.MatchesUrl, UriKind.Relative)
            });
            return(CurrentTemplate(model));
        }
Beispiel #20
0
        public async override Task <ActionResult> Index(ContentModel contentModel)
        {
            if (contentModel is null)
            {
                throw new ArgumentNullException(nameof(contentModel));
            }

            var model = new EditTrainingSessionViewModel(contentModel.Content, Services?.UserService)
            {
                Match         = await _matchDataSource.ReadMatchByRoute(Request.RawUrl).ConfigureAwait(false),
                DateFormatter = _dateFormatter
            };

            if (model.Match == null)
            {
                return(new HttpNotFoundResult());
            }
            else
            {
                model.IsAuthorized = _authorizationPolicy.IsAuthorized(model.Match);

                if (model.Match.Season != null)
                {
                    model.Match.Season = await _seasonDataSource.ReadSeasonByRoute(model.Match.Season.SeasonRoute, true).ConfigureAwait(false);

                    model.SeasonFullName = model.Match.Season.SeasonFullName();
                }

                model.MatchDate = model.Match.StartTime;
                if (model.Match.StartTimeIsKnown)
                {
                    model.StartTime = model.Match.StartTime;
                }
                model.MatchLocationId   = model.Match.MatchLocation?.MatchLocationId;
                model.MatchLocationName = model.Match.MatchLocation?.NameAndLocalityOrTownIfDifferent();

                model.Metadata.PageTitle = "Edit " + model.Match.MatchFullName(x => _dateFormatter.FormatDate(x, false, false, false));

                if (model.Match.Season != null)
                {
                    model.Breadcrumbs.Add(new Breadcrumb {
                        Name = Constants.Pages.Competitions, Url = new Uri(Constants.Pages.CompetitionsUrl, UriKind.Relative)
                    });
                    model.Breadcrumbs.Add(new Breadcrumb {
                        Name = model.Match.Season.Competition.CompetitionName, Url = new Uri(model.Match.Season.Competition.CompetitionRoute, UriKind.Relative)
                    });
                    model.Breadcrumbs.Add(new Breadcrumb {
                        Name = model.Match.Season.SeasonName(), Url = new Uri(model.Match.Season.SeasonRoute, UriKind.Relative)
                    });
                }
                else
                {
                    model.Breadcrumbs.Add(new Breadcrumb {
                        Name = Constants.Pages.Matches, Url = new Uri(Constants.Pages.MatchesUrl, UriKind.Relative)
                    });
                }
                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = model.Match.MatchName, Url = new Uri(model.Match.MatchRoute, UriKind.Relative)
                });

                return(CurrentTemplate(model));
            }
        }
        public async override Task <ActionResult> Index(ContentModel contentModel)
        {
            if (contentModel is null)
            {
                throw new ArgumentNullException(nameof(contentModel));
            }

            var model = new EditKnockoutMatchViewModel(contentModel.Content, Services?.UserService)
            {
                Match         = await _matchDataSource.ReadMatchByRoute(Request.RawUrl).ConfigureAwait(false),
                DateFormatter = _dateFormatter
            };

            if (model.Match == null)
            {
                return(new HttpNotFoundResult());
            }
            else
            {
                // This page is only for matches in the future
                if (model.Match.StartTime <= DateTime.UtcNow)
                {
                    return(new HttpNotFoundResult());
                }

                model.IsAuthorized = _authorizationPolicy.IsAuthorized(model.Match);

                model.MatchName = model.Match.UpdateMatchNameAutomatically ? string.Empty : model.Match.MatchName;
                if (model.Match.Season != null)
                {
                    model.Match.Season = model.Season = await _seasonDataSource.ReadSeasonByRoute(model.Match.Season.SeasonRoute, true).ConfigureAwait(false);

                    model.PossibleSeasons = _editMatchHelper.PossibleSeasonsAsListItems(new[] { model.Match.Season });
                }
                model.PossibleHomeTeams = _editMatchHelper.PossibleTeamsAsListItems(model.Season?.Teams);
                model.PossibleAwayTeams = _editMatchHelper.PossibleTeamsAsListItems(model.Season?.Teams);

                model.MatchDate = model.Match.StartTime;
                if (model.Match.StartTimeIsKnown)
                {
                    model.StartTime = model.Match.StartTime;
                }
                model.HomeTeamId        = model.Match.Teams.SingleOrDefault(x => x.TeamRole == TeamRole.Home)?.Team.TeamId;
                model.AwayTeamId        = model.Match.Teams.SingleOrDefault(x => x.TeamRole == TeamRole.Away)?.Team.TeamId;
                model.MatchLocationId   = model.Match.MatchLocation?.MatchLocationId;
                model.MatchLocationName = model.Match.MatchLocation?.NameAndLocalityOrTownIfDifferent();

                model.Metadata.PageTitle = "Edit " + model.Match.MatchFullName(x => _dateFormatter.FormatDate(x, false, false, false));

                if (model.Match.Season != null)
                {
                    model.Breadcrumbs.Add(new Breadcrumb {
                        Name = Constants.Pages.Competitions, Url = new Uri(Constants.Pages.CompetitionsUrl, UriKind.Relative)
                    });
                    model.Breadcrumbs.Add(new Breadcrumb {
                        Name = model.Match.Season.Competition.CompetitionName, Url = new Uri(model.Match.Season.Competition.CompetitionRoute, UriKind.Relative)
                    });
                    model.Breadcrumbs.Add(new Breadcrumb {
                        Name = model.Match.Season.SeasonName(), Url = new Uri(model.Match.Season.SeasonRoute, UriKind.Relative)
                    });
                }
                else
                {
                    model.Breadcrumbs.Add(new Breadcrumb {
                        Name = Constants.Pages.Matches, Url = new Uri(Constants.Pages.MatchesUrl, UriKind.Relative)
                    });
                }
                model.Breadcrumbs.Add(new Breadcrumb {
                    Name = model.Match.MatchName, Url = new Uri(model.Match.MatchRoute, UriKind.Relative)
                });

                return(CurrentTemplate(model));
            }
        }
Beispiel #22
0
        public async override Task <ActionResult> Index(ContentModel contentModel)
        {
            if (contentModel is null)
            {
                throw new ArgumentNullException(nameof(contentModel));
            }

            var model = new EditTournamentViewModel(contentModel.Content, Services?.UserService)
            {
                Tournament = new Tournament
                {
                    QualificationType = TournamentQualificationType.OpenTournament,
                    PlayerType        = PlayerType.Mixed,
                    PlayersPerTeam    = 8,
                    DefaultOverSets   = new List <OverSet> {
                        new OverSet {
                            Overs = 4, BallsPerOver = 8
                        }
                    },
                    TournamentLocation = new MatchLocation()
                }
            };

            if (Request.RawUrl.StartsWith("/teams/", StringComparison.OrdinalIgnoreCase))
            {
                model.Team = await _teamDataSource.ReadTeamByRoute(Request.RawUrl, true).ConfigureAwait(false);

                if (model.Team == null)
                {
                    return(new HttpNotFoundResult());
                }

                model.Tournament.TournamentName = model.Team.TeamName;
                if (model.Tournament.TournamentName.IndexOf("tournament", StringComparison.OrdinalIgnoreCase) == -1)
                {
                    model.Tournament.TournamentName += " tournament";
                }

                model.TournamentLocationId   = model.Team.MatchLocations.FirstOrDefault()?.MatchLocationId;
                model.TournamentLocationName = model.Team.MatchLocations.FirstOrDefault()?.NameAndLocalityOrTownIfDifferent();

                model.Tournament.PlayerType = model.Team.PlayerType;

                model.Metadata.PageTitle = $"Add a tournament for {model.Team.TeamName}";
            }
            else if (Request.RawUrl.StartsWith("/competitions/", StringComparison.OrdinalIgnoreCase))
            {
                model.Season = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl, false).ConfigureAwait(false);

                if (model.Season == null || !model.Season.EnableTournaments)
                {
                    return(new HttpNotFoundResult());
                }

                model.Tournament.TournamentName = model.Season.Competition.CompetitionName;
                if (model.Tournament.TournamentName.IndexOf("tournament", StringComparison.OrdinalIgnoreCase) == -1)
                {
                    model.Tournament.TournamentName += " tournament";
                }

                model.Tournament.PlayerType = model.Season.Competition.PlayerType;

                model.Metadata.PageTitle = $"Add a tournament in the {model.Season.SeasonFullName()}";
            }

            model.IsAuthorized[AuthorizedAction.CreateTournament] = User.Identity.IsAuthenticated;

            model.Breadcrumbs.Add(new Breadcrumb {
                Name = Constants.Pages.Tournaments, Url = new Uri(Constants.Pages.TournamentsUrl, UriKind.Relative)
            });

            return(CurrentTemplate(model));
        }