69 lines
1.8 KiB
Go
69 lines
1.8 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"git.haelnorr.com/h/golib/hws"
|
|
"git.haelnorr.com/h/oslstats/internal/db"
|
|
"git.haelnorr.com/h/oslstats/internal/throw"
|
|
seasonsview "git.haelnorr.com/h/oslstats/internal/view/seasonsview"
|
|
"github.com/pkg/errors"
|
|
"github.com/uptrace/bun"
|
|
)
|
|
|
|
// SeasonLeagueTablePage renders the table tab of a season league page
|
|
func SeasonLeagueTablePage(
|
|
s *hws.Server,
|
|
conn *db.DB,
|
|
) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
seasonStr := r.PathValue("season_short_name")
|
|
leagueStr := r.PathValue("league_short_name")
|
|
|
|
var season *db.Season
|
|
var league *db.League
|
|
var leaderboard []*db.LeaderboardEntry
|
|
|
|
if ok := conn.WithReadTx(s, w, r, func(ctx context.Context, tx bun.Tx) (bool, error) {
|
|
var err error
|
|
var teams []*db.Team
|
|
season, league, teams, err = db.GetSeasonLeagueWithTeams(ctx, tx, seasonStr, leagueStr)
|
|
if err != nil {
|
|
if db.IsBadRequest(err) {
|
|
throw.NotFound(s, w, r, r.URL.Path)
|
|
return false, nil
|
|
}
|
|
return false, errors.Wrap(err, "db.GetSeasonLeagueWithTeams")
|
|
}
|
|
|
|
fixtures, err := db.GetAllocatedFixtures(ctx, tx, season.ID, league.ID)
|
|
if err != nil {
|
|
return false, errors.Wrap(err, "db.GetAllocatedFixtures")
|
|
}
|
|
|
|
fixtureIDs := make([]int, len(fixtures))
|
|
for i, f := range fixtures {
|
|
fixtureIDs[i] = f.ID
|
|
}
|
|
|
|
resultMap, err := db.GetFinalizedResultsForFixtures(ctx, tx, fixtureIDs)
|
|
if err != nil {
|
|
return false, errors.Wrap(err, "db.GetFinalizedResultsForFixtures")
|
|
}
|
|
|
|
leaderboard = db.ComputeLeaderboard(teams, fixtures, resultMap)
|
|
|
|
return true, nil
|
|
}); !ok {
|
|
return
|
|
}
|
|
|
|
if r.Method == "GET" {
|
|
renderSafely(seasonsview.SeasonLeagueTablePage(season, league, leaderboard), s, r, w)
|
|
} else {
|
|
renderSafely(seasonsview.SeasonLeagueTable(season, league, leaderboard), s, r, w)
|
|
}
|
|
})
|
|
}
|