Skip to content

Commit

Permalink
Disable rating history in frontend and backend so that we dont go bro…
Browse files Browse the repository at this point in the history
…ke (#862)

hopefully this fixes things!
  • Loading branch information
lowtorola authored Dec 7, 2024
1 parent eac40ec commit ee15f42
Show file tree
Hide file tree
Showing 12 changed files with 212 additions and 174 deletions.
243 changes: 125 additions & 118 deletions backend/siarnaq/api/compete/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
import google.cloud.storage as storage
import structlog
from django.conf import settings
from django.contrib.postgres.aggregates import ArrayAgg

# from django.contrib.postgres.aggregates import ArrayAgg
from django.db import NotSupportedError, transaction
from django.db.models import Exists, F, OuterRef, Q, Subquery
from django.db.models import Exists, OuterRef, Q, Subquery
from django.utils import timezone
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
from rest_framework import mixins, status, viewsets
Expand Down Expand Up @@ -39,7 +40,7 @@
)
from siarnaq.api.episodes.models import ReleaseStatus, Tournament
from siarnaq.api.episodes.permissions import IsEpisodeAvailable, IsEpisodeMutable
from siarnaq.api.teams.models import Rating, Team, TeamStatus
from siarnaq.api.teams.models import Team, TeamStatus
from siarnaq.api.teams.permissions import IsOnTeam
from siarnaq.gcloud import titan

Expand Down Expand Up @@ -442,59 +443,61 @@ def get_top_historical_rating_ranking(self, episode_id, limit=None):
descending order. The number of items is capped by
the 'limit' parameter if provided.
"""
matches = self.get_rated_matches(episode_id)
match_participants = MatchParticipant.objects.filter(match__in=matches)

# Subquery to get the last rating value
last_rating_subquery = (
match_participants.filter(team_id=OuterRef("team_id"))
.values("rating__value")
.order_by("-match__created")[:1]
)

# Aggregate rating history per each team
rating_history = (
match_participants.values("team_id")
.annotate(
timestamps_list=ArrayAgg(
F("match__created"), ordering="match__created"
),
ratings_pk_list=ArrayAgg(F("rating__pk"), ordering="match__created"),
last_rating_value=Subquery(last_rating_subquery),
)
.order_by("-last_rating_value")[:limit]
)

# Fetch all teams and ratings in bulk
team_ids = [team_data["team_id"] for team_data in rating_history]
rating_pks = {
pk for team_data in rating_history for pk in team_data["ratings_pk_list"]
}

teams = Team.objects.in_bulk(team_ids)
ratings = Rating.objects.in_bulk(rating_pks)

# Parse query results into required format
grouped = [
{
"team_id": team_data["team_id"],
"team_rating": {
"team": teams[team_data["team_id"]],
"rating_history": [
{
"timestamp": timestamp,
"rating": ratings[rating_pk],
}
for rating_pk, timestamp in zip(
team_data["ratings_pk_list"], team_data["timestamps_list"]
)
],
},
}
for team_data in rating_history
]

return grouped
return []

# matches = self.get_rated_matches(episode_id)
# match_participants = MatchParticipant.objects.filter(match__in=matches)

# # Subquery to get the last rating value
# last_rating_subquery = (
# match_participants.filter(team_id=OuterRef("team_id"))
# .values("rating__value")
# .order_by("-match__created")[:1]
# )

# # Aggregate rating history per each team
# rating_history = (
# match_participants.values("team_id")
# .annotate(
# timestamps_list=ArrayAgg(
# F("match__created"), ordering="match__created"
# ),
# ratings_pk_list=ArrayAgg(F("rating__pk"), ordering="match__created"),
# last_rating_value=Subquery(last_rating_subquery),
# )
# .order_by("-last_rating_value")[:limit]
# )

# # Fetch all teams and ratings in bulk
# team_ids = [team_data["team_id"] for team_data in rating_history]
# rating_pks = {
# pk for team_data in rating_history for pk in team_data["ratings_pk_list"]
# }

# teams = Team.objects.in_bulk(team_ids)
# ratings = Rating.objects.in_bulk(rating_pks)

# # Parse query results into required format
# grouped = [
# {
# "team_id": team_data["team_id"],
# "team_rating": {
# "team": teams[team_data["team_id"]],
# "rating_history": [
# {
# "timestamp": timestamp,
# "rating": ratings[rating_pk],
# }
# for rating_pk, timestamp in zip(
# team_data["ratings_pk_list"], team_data["timestamps_list"]
# )
# ],
# },
# }
# for team_data in rating_history
# ]

# return grouped

@extend_schema(
parameters=[
Expand Down Expand Up @@ -556,49 +559,50 @@ def historical_rating(self, request, pk=None, *, episode_id):
- The function returns an empty list if no valid team is found.
- Historical ratings are ordered by match creation date.
"""
team_id = self.request.query_params.get("team_id")

if team_id is not None:
team_query = Team.objects.filter(
episode_id=episode_id, pk=parse_int(team_id)
)
elif request.user.pk is not None:
team_query = Team.objects.filter(
members__pk=request.user.pk, episode_id=episode_id
)
else:
return Response([])

if not team_query.exists():
return Response(status=status.HTTP_400_BAD_REQUEST)

team = team_query.get()

rated_matches = self.get_rated_matches(episode_id, team.pk)

team_ratings = MatchParticipant.objects.filter(
match__in=rated_matches, team__pk=team.pk
).order_by("match__created")

# Prepare rating history
rating_history = [
{
"timestamp": match_data.match.created,
"rating": match_data.rating,
}
for match_data in team_ratings
]

historical_rating = {
"team_id": team.pk,
"team_rating": {
"team": team,
"rating_history": rating_history,
},
}

results = HistoricalRatingSerializer(historical_rating, many=False).data
return Response(results, status=status.HTTP_200_OK)
return Response(status=status.HTTP_204_NO_CONTENT)
# team_id = self.request.query_params.get("team_id")

# if team_id is not None:
# team_query = Team.objects.filter(
# episode_id=episode_id, pk=parse_int(team_id)
# )
# elif request.user.pk is not None:
# team_query = Team.objects.filter(
# members__pk=request.user.pk, episode_id=episode_id
# )
# else:
# return Response([])

# if not team_query.exists():
# return Response(status=status.HTTP_400_BAD_REQUEST)

# team = team_query.get()

# rated_matches = self.get_rated_matches(episode_id, team.pk)

# team_ratings = MatchParticipant.objects.filter(
# match__in=rated_matches, team__pk=team.pk
# ).order_by("match__created")

# # Prepare rating history
# rating_history = [
# {
# "timestamp": match_data.match.created,
# "rating": match_data.rating,
# }
# for match_data in team_ratings
# ]

# historical_rating = {
# "team_id": team.pk,
# "team_rating": {
# "team": team,
# "rating_history": rating_history,
# },
# }

# results = HistoricalRatingSerializer(historical_rating, many=False).data
# return Response(results, status=status.HTTP_200_OK)

@extend_schema(
parameters=[
Expand Down Expand Up @@ -628,25 +632,28 @@ def historical_rating(self, request, pk=None, *, episode_id):
)
def historical_rating_topN(self, request, pk=None, *, episode_id):
"""List the historical top N rankings, N should be <= 10 and defaults to 10"""
N = request.query_params.get("N", 10)

try:
N = parse_int(N)
except ValueError:
return Response(
{"error": "Invalid parameter: N must be an integer"},
status=status.HTTP_400_BAD_REQUEST,
)

if N > 10:
return Response(
{"error": "Invalid parameter: N must be less than or equal to 10"},
status=status.HTTP_400_BAD_REQUEST,
)

grouped = self.get_top_historical_rating_ranking(episode_id=episode_id, limit=N)
results = HistoricalRatingSerializer(grouped, many=True).data
return Response(results, status=status.HTTP_200_OK)
return Response(status=status.HTTP_204_NO_CONTENT)

# N = request.query_params.get("N", 10)

# try:
# N = parse_int(N)
# except ValueError:
# return Response(
# {"error": "Invalid parameter: N must be an integer"},
# status=status.HTTP_400_BAD_REQUEST,
# )

# if N > 10:
# return Response(
# {"error": "Invalid parameter: N must be less than or equal to 10"},
# status=status.HTTP_400_BAD_REQUEST,
# )

# grouped = self.get_top_historical_rating_ranking(
# episode_id=episode_id, limit=N)
# results = HistoricalRatingSerializer(grouped, many=True).data
# return Response(results, status=status.HTTP_200_OK)

@extend_schema(
parameters=[
Expand Down
32 changes: 27 additions & 5 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,6 @@ const router = createBrowserRouter([
{
path: "my_team",
element: <MyTeam />,
errorElement: <ErrorBoundary />,
loader: myTeamLoader(queryClient),
},
{
Expand All @@ -171,41 +170,64 @@ const router = createBrowserRouter([
path: "",
element: <Home />,
loader: homeLoader(queryClient),
errorElement: <ErrorBoundary />,
},
{
path: "home",
element: <Home />,
loader: homeLoader(queryClient),
errorElement: <ErrorBoundary />,
},
{
path: "resources",
element: <Resources />,
errorElement: <ErrorBoundary />,
},
{
path: "quick_start",
element: <QuickStart />,
errorElement: <ErrorBoundary />,
},
{ path: "resources", element: <Resources /> },
{ path: "quick_start", element: <QuickStart /> },
{
path: "rankings",
element: <Rankings />,
loader: rankingsLoader(queryClient),
errorElement: <ErrorBoundary />,
},
{
path: "queue",
element: <Queue />,
loader: queueLoader(queryClient),
errorElement: <ErrorBoundary />,
},
{
path: "tournaments",
element: <Tournaments />,
loader: tournamentsLoader(queryClient),
errorElement: <ErrorBoundary />,
},
{
path: "tournament/:tournamentId",
element: <TournamentPage />,
loader: tournamentLoader(queryClient),
errorElement: <ErrorBoundary />,
},
{
path: "team/:teamId",
element: <TeamProfile />,
loader: teamProfileLoader(queryClient),
errorElement: <ErrorBoundary />,
},
{
path: "debugging_tips",
element: <DebuggingTips />,
errorElement: <ErrorBoundary />,
},
{
path: "common_issues",
element: <CommonIssues />,
errorElement: <ErrorBoundary />,
},
{ path: "debugging_tips", element: <DebuggingTips /> },
{ path: "common_issues", element: <CommonIssues /> },
{
path: "*",
element: <PageNotFound />,
Expand Down
12 changes: 6 additions & 6 deletions frontend/src/api/loaders/episodeLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { QueryClient } from "@tanstack/react-query";
import { ResponseError } from "api/_autogen";
import { loginCheck } from "api/auth/authApi";
import { episodeInfoFactory } from "api/episode/episodeFactories";
import { ratingHistoryTopNFactory } from "api/compete/competeFactories";
// import { ratingHistoryTopNFactory } from "api/compete/competeFactories";
import { buildKey, safeEnsureQueryData } from "api/helpers";
import { searchTeamsFactory, myTeamFactory } from "api/team/teamFactories";
import type { LoaderFunction } from "react-router-dom";
Expand Down Expand Up @@ -38,11 +38,11 @@ export const episodeLoader =
searchTeamsFactory,
queryClient,
);
safeEnsureQueryData(
{ episodeId: id, n: 10 },
ratingHistoryTopNFactory,
queryClient,
);
// safeEnsureQueryData(
// { episodeId: id, n: 10 },
// ratingHistoryTopNFactory,
// queryClient,
// );

// Prefetch the user's team
if (loggedIn) {
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/api/loaders/homeLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
nextTournamentFactory,
} from "../episode/episodeFactories";
import {
userRatingHistoryFactory,
// userRatingHistoryFactory,
scrimmagingRecordFactory,
} from "api/compete/competeFactories";
import { CompeteMatchScrimmagingRecordRetrieveScrimmageTypeEnum } from "api/_autogen";
Expand All @@ -24,7 +24,7 @@ export const homeLoader =
safeEnsureQueryData({ episodeId }, nextTournamentFactory, queryClient);

// User Team Rating History
safeEnsureQueryData({ episodeId }, userRatingHistoryFactory, queryClient);
// safeEnsureQueryData({ episodeId }, userRatingHistoryFactory, queryClient);

// User Team Scrimmage Record
safeEnsureQueryData(
Expand Down
Loading

0 comments on commit ee15f42

Please sign in to comment.