Skip to content

Commit

Permalink
#99 split out ofm views into new package
Browse files Browse the repository at this point in the history
  • Loading branch information
Sh4kE committed Dec 10, 2016
1 parent 5d71550 commit 6ca14d3
Show file tree
Hide file tree
Showing 9 changed files with 943 additions and 915 deletions.
10 changes: 6 additions & 4 deletions core/ofm_urls.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from django.conf.urls import url

from core.ofm_views import PlayerDetailView, PlayerStatisticsView, PlayerStatisticsAsJsonView, FinanceDataView, \
FinancesAsJsonView, MatchesView, MatchesAsJsonView, StadiumStatisticsView, StadiumStatisticsAsJsonView, \
StadiumDetailView, StadiumStandStatisticsView, FinanceIncomeChartView, FinanceExpensesChartView, \
FinanceBalanceChartView, PlayerChartView, MatchesSummaryJsonView, StadiumStandStatisticsChartView
from core.rename_me_views.stadium_views import StadiumStatisticsView, StadiumStatisticsAsJsonView, StadiumDetailView, \
StadiumStandStatisticsView, StadiumStandStatisticsChartView
from core.rename_me_views.match_views import MatchesView, MatchesAsJsonView, MatchesSummaryJsonView
from core.rename_me_views.finance_views import FinanceDataView, FinancesAsJsonView, FinanceBalanceChartView, \
FinanceIncomeChartView, FinanceExpensesChartView
from core.rename_me_views.player_views import PlayerStatisticsView, PlayerStatisticsAsJsonView, PlayerDetailView, PlayerChartView

app_name = 'ofm'
urlpatterns = [
Expand Down
911 changes: 0 additions & 911 deletions core/ofm_views.py

This file was deleted.

Empty file.
354 changes: 354 additions & 0 deletions core/rename_me_views/finance_views.py

Large diffs are not rendered by default.

113 changes: 113 additions & 0 deletions core/rename_me_views/match_views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import locale

from braces.views import CsrfExemptMixin, JsonRequestResponseMixin
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views import View
from django.views.generic import TemplateView

from core.models import Matchday, Match


@method_decorator(login_required, name='dispatch')
class MatchesView(TemplateView):
template_name = 'core/ofm/matches.html'

def get_context_data(self, **kwargs):
context = super(MatchesView, self).get_context_data(**kwargs)

matchdays = Matchday.objects.filter(matches__isnull=False).distinct()
seasons = set(m.season.number for m in matchdays)

context['seasons'] = sorted(seasons, reverse=True)

return context


@method_decorator(login_required, name='dispatch')
class MatchesAsJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View):
def get(self, request, *args, **kwargs):
season = self.request.GET.get('season', default=Matchday.objects.all()[0].season.number)
matches = Match.objects.filter(user=self.request.user, matchday__season__number=season)

match_json = [self._get_match_in_json(match) for match in matches]

return self.render_json_response(match_json)

@staticmethod
def _get_match_in_json(match):
"""
Returns:
A dictionary of match data.
"""
locale.setlocale(locale.LC_ALL, '')

if match.is_home_match:
home_team_name = "<span class='users-team'>" + match.home_team_statistics.team_name + "</span>"
guest_team_name = match.guest_team_statistics.team_name
if hasattr(match, 'stadium_statistics'):
venue = "<a href='" + match.stadium_statistics.get_absolute_url() + "'>" + match.venue + "</a>"
else:
venue = match.venue
else:
home_team_name = match.home_team_statistics.team_name
guest_team_name = "<span class='users-team'>" + match.guest_team_statistics.team_name + "</span>"
venue = match.venue

result_score = str(match.home_team_statistics.score) + ":" + str(match.guest_team_statistics.score)
if match.is_in_future:
result = "<span class='match_scheduled alert-info'>-:-</span>"
elif match.is_won:
result = "<span class='match_won alert-success'>" + result_score + "</span>"
elif match.is_draw:
result = "<span class='match_draw alert-warning'>" + result_score + "</span>"
else:
result = "<span class='match_lost alert-danger'>" + result_score + "</span>"

match_stat = dict()
match_stat['home_team'] = home_team_name
match_stat['guest_team'] = guest_team_name
match_stat['result'] = result
home_strength = match.home_team_statistics.strength
if home_strength == int(home_strength):
match_stat['home_strength'] = int(home_strength)
else:
match_stat['home_strength'] = locale.format("%.1f", home_strength)
guest_strength = match.guest_team_statistics.strength
if guest_strength == int(guest_strength):
match_stat['guest_strength'] = int(guest_strength)
else:
match_stat['guest_strength'] = locale.format("%.1f", guest_strength)
match_stat['home_ball_possession'] = locale.format("%.1f", match.home_team_statistics.ball_possession) + " %"
match_stat['guest_ball_possession'] = locale.format("%.1f", match.guest_team_statistics.ball_possession) + " %"
match_stat['home_chances'] = match.home_team_statistics.chances
match_stat['guest_chances'] = match.guest_team_statistics.chances
match_stat['home_yellow_cards'] = match.home_team_statistics.yellow_cards
match_stat['guest_yellow_cards'] = match.guest_team_statistics.yellow_cards
match_stat['home_red_cards'] = match.home_team_statistics.red_cards
match_stat['guest_red_cards'] = match.guest_team_statistics.red_cards
match_stat['venue'] = venue
match_stat['matchday'] = match.matchday.number

return match_stat


@method_decorator(login_required, name='dispatch')
class MatchesSummaryJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View):
def get(self, request, *args, **kwargs):
current_season = Matchday.objects.all()[0].season
season_number = self.request.GET.get('season_number', current_season.number)
matches_won = len(
[match for match in Match.objects.filter(matchday__season__number=season_number) if match.is_won])
matches_draw = len(
[match for match in Match.objects.filter(matchday__season__number=season_number) if match.is_draw])
matches_lost = len(
[match for match in Match.objects.filter(matchday__season__number=season_number) if match.is_lost])

json = {
"matches_won": matches_won,
"matches_draw": matches_draw,
"matches_lost": matches_lost
}

return self.render_json_response(json)
196 changes: 196 additions & 0 deletions core/rename_me_views/player_views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
from braces.views import CsrfExemptMixin, JsonRequestResponseMixin
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views import View
from django.views.generic import TemplateView, DetailView

from core.models import Matchday, Contract, PlayerStatistics, AwpBoundaries, Player
from core.rename_me_views.view_utils import validate_filtered_field


@method_decorator(login_required, name='dispatch')
class PlayerStatisticsView(TemplateView):
template_name = 'core/ofm/player_statistics.html'

def get_context_data(self, **kwargs):
matchdays = Matchday.objects.filter(player_statistics__isnull=False).distinct()

context = super(PlayerStatisticsView, self).get_context_data(**kwargs)
context['matchdays'] = matchdays
context['players_count'] = Contract.objects.filter(user=self.request.user, sold_on_matchday=None).count()

return context


@method_decorator(login_required, name='dispatch')
class PlayerStatisticsAsJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View):
def get(self, request, *args, **kwargs):
contracts = Contract.objects.filter(user=self.request.user, sold_on_matchday=None)
players = [contract.player for contract in contracts]
current_matchday = Matchday.objects.all()[0]

newer_matchday_season = self.request.GET.get('newer_matchday_season', default=current_matchday.season.number)
newer_matchday = self.request.GET.get('newer_matchday', default=current_matchday.number)
older_matchday_season = self.request.GET.get('older_matchday_season')
older_matchday = self.request.GET.get('older_matchday')
diff_mode_enabled = older_matchday and older_matchday_season

player_statistics_tuples = []
for player in players:
newer_player_statistics, older_player_statistics = self._get_statistics_from_player_and_matchday(
player,
newer_matchday_season, newer_matchday,
older_matchday_season, older_matchday
)
if newer_player_statistics and (older_player_statistics or not diff_mode_enabled):
player_statistics_tuples.append((newer_player_statistics, older_player_statistics))

player_statistics_json = [
self._get_player_statistics_diff_in_json(newer_player_statistics, older_player_statistics)
for (newer_player_statistics, older_player_statistics) in player_statistics_tuples
]

return self.render_json_response(player_statistics_json)

@staticmethod
def _get_statistics_from_player_and_matchday(player,
newer_matchday_season, newer_matchday,
older_matchday_season, older_matchday):

newer_player_statistics = PlayerStatistics.objects.filter(
player=player,
matchday__season__number=newer_matchday_season,
matchday__number=newer_matchday
)
older_player_statistics = PlayerStatistics.objects.filter(
player=player,
matchday__season__number=older_matchday_season,
matchday__number=older_matchday
)

newer_player_statistics = validate_filtered_field(newer_player_statistics)
older_player_statistics = validate_filtered_field(older_player_statistics)

if not newer_player_statistics:
newer_player_statistics = PlayerStatistics.objects.filter(
player=player,
matchday__season__number=newer_matchday_season
).order_by('matchday')[0]

return newer_player_statistics, older_player_statistics

@staticmethod
def _get_player_statistics_diff_in_json(newer_player_statistics, older_player_statistics):
"""
Args:
newer_player_statistics: newer statistic
older_player_statistics: older statistic
Returns:
A dictionary of player statistics data. If st2 is None st1 is returned
"""

strength = newer_player_statistics.strength
if older_player_statistics:
strength = newer_player_statistics.strength - older_player_statistics.strength
ep = newer_player_statistics.ep
if older_player_statistics:
ep = newer_player_statistics.ep - older_player_statistics.ep
tp = newer_player_statistics.tp
if older_player_statistics:
tp = newer_player_statistics.tp - older_player_statistics.tp
awp = newer_player_statistics.awp
if older_player_statistics:
awp = newer_player_statistics.awp - older_player_statistics.awp
freshness = newer_player_statistics.freshness
if older_player_statistics:
freshness = newer_player_statistics.freshness - older_player_statistics.freshness

awp_boundaries = AwpBoundaries.get_from_matchday(newer_player_statistics.matchday)
awp_to_next_bound = awp_boundaries[newer_player_statistics.strength + 1] - newer_player_statistics.awp

statistic_diff = dict()
statistic_diff['position'] = newer_player_statistics.player.position
statistic_diff['age'] = newer_player_statistics.age
statistic_diff['strength'] = strength
statistic_diff['name'] = '<a href="%s">%s</a>' % (newer_player_statistics.player.get_absolute_url(),
newer_player_statistics.player.name)
statistic_diff['ep'] = ep
statistic_diff['tp'] = tp
statistic_diff['awp'] = awp
statistic_diff['freshness'] = freshness
statistic_diff['games_in_season'] = newer_player_statistics.games_in_season
statistic_diff['goals_in_season'] = newer_player_statistics.goals_in_season
statistic_diff['won_tacklings_in_season'] = newer_player_statistics.won_tacklings_in_season
statistic_diff['lost_tacklings_in_season'] = newer_player_statistics.lost_tacklings_in_season
statistic_diff['won_friendly_tacklings_in_season'] = newer_player_statistics.won_friendly_tacklings_in_season
statistic_diff['lost_friendly_tacklings_in_season'] = newer_player_statistics.lost_friendly_tacklings_in_season
statistic_diff['yellow_cards_in_season'] = newer_player_statistics.yellow_cards_in_season
statistic_diff['red_cards_in_season'] = newer_player_statistics.red_cards_in_season
statistic_diff['equity'] = newer_player_statistics.equity
statistic_diff['awp_to_next_bound'] = awp_to_next_bound

return statistic_diff


@method_decorator(login_required, name='dispatch')
class PlayerDetailView(DetailView):
context_object_name = 'player'
template_name = 'core/ofm/player_detail.html'
queryset = Player.objects.all()

def get_context_data(self, **kwargs):
context = super(PlayerDetailView, self).get_context_data(**kwargs)

player = self.get_object()
current_season = Matchday.objects.all()[0].season
seasons = []
player_stats = PlayerStatistics.objects.filter(player=player).order_by('matchday')
for player_stat in player_stats:
if player_stat.matchday.season not in seasons:
seasons.append(player_stat.matchday.season)

context['seasons'] = seasons
if player:
context['player_age'] = current_season.number - player.birth_season.number
context['player_strength'] = player_stats[0].strength

return context

def get_object(self, **kwargs):
player = super(PlayerDetailView, self).get_object()
contracts = Contract.objects.filter(user=self.request.user, player=player, sold_on_matchday=None)
return player if contracts.count() > 0 else None


@method_decorator(login_required, name='dispatch')
class PlayerChartView(CsrfExemptMixin, JsonRequestResponseMixin, View):
def get(self, request, *args, **kwargs):
current_season_number = Matchday.objects.all()[0].season.number
season_number = self.request.GET.get('season_number', default=current_season_number)
player_id = self.request.GET.get('player_id')
player = Player.objects.filter(id=player_id)
player_statistics = PlayerStatistics.objects.filter(player=player, matchday__season__number=season_number)
awps = [player_stat.awp for player_stat in player_statistics]

chart_json = {
"series": [{
"name": 'AWP',
"data": awps
}],
"categories": [player_stat.matchday.number for player_stat in player_statistics]
}

matchdays = [p.matchday for p in player_statistics]
current_player_statistics = PlayerStatistics.objects.filter(player=player).order_by('matchday')[0]

current_awp_boundaries = AwpBoundaries.get_from_matchday(current_player_statistics.matchday)

for strength in current_awp_boundaries:
if current_awp_boundaries[strength] >= min(awps) and strength > current_player_statistics.strength:
awp_boundary_values = [AwpBoundaries.get_from_matchday(matchday)[strength] for matchday in matchdays]
chart_json['series'].append({'name': 'AWP-Grenze: %s' % strength, 'data': awp_boundary_values})
if current_awp_boundaries[strength] >= max(awps):
break

return self.render_json_response(chart_json)
Loading

0 comments on commit 6ca14d3

Please sign in to comment.