86 lines
2.3 KiB
Go
86 lines
2.3 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"
|
|
homeview "git.haelnorr.com/h/oslstats/internal/view/homeview"
|
|
"github.com/pkg/errors"
|
|
"github.com/uptrace/bun"
|
|
)
|
|
|
|
// Index handles responses to the / path. Also serves a 404 Page for paths that
|
|
// don't have explicit handlers
|
|
func Index(s *hws.Server, conn *db.DB) http.Handler {
|
|
return http.HandlerFunc(
|
|
func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/" {
|
|
throw.NotFound(s, w, r, r.URL.Path)
|
|
return
|
|
}
|
|
|
|
var season *db.Season
|
|
var standings []homeview.LeagueStandings
|
|
|
|
if ok := conn.WithReadTx(s, w, r, func(ctx context.Context, tx bun.Tx) (bool, error) {
|
|
// Get the most recent season
|
|
seasons, err := db.ListSeasons(ctx, tx, &db.PageOpts{
|
|
Page: 1,
|
|
PerPage: 1,
|
|
Order: bun.OrderDesc,
|
|
OrderBy: "start_date",
|
|
})
|
|
if err != nil {
|
|
return false, errors.Wrap(err, "db.ListSeasons")
|
|
}
|
|
|
|
if seasons.Total == 0 || len(seasons.Items) == 0 {
|
|
return true, nil
|
|
}
|
|
|
|
season = seasons.Items[0]
|
|
|
|
// Build leaderboards for each league in this season
|
|
standings = make([]homeview.LeagueStandings, 0, len(season.Leagues))
|
|
for _, league := range season.Leagues {
|
|
_, l, teams, err := db.GetSeasonLeagueWithTeams(ctx, tx, season.ShortName, league.ShortName)
|
|
if err != nil {
|
|
return false, errors.Wrap(err, "db.GetSeasonLeagueWithTeams")
|
|
}
|
|
|
|
fixtures, err := db.GetAllocatedFixtures(ctx, tx, season.ID, l.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)
|
|
|
|
standings = append(standings, homeview.LeagueStandings{
|
|
League: l,
|
|
Leaderboard: leaderboard,
|
|
})
|
|
}
|
|
|
|
return true, nil
|
|
}); !ok {
|
|
return
|
|
}
|
|
|
|
renderSafely(homeview.IndexPage(season, standings), s, r, w)
|
|
},
|
|
)
|
|
}
|