package handlers import ( "context" "fmt" "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" ) // redirectDraftSeasonLeague checks if a season is a draft type and redirects // GET requests from /seasons/{short}/leagues/Draft/{tab} to /seasons/{short}/{tab}. // Returns true if a redirect was issued (caller should return early). // POST requests are not redirected since they are HTMX partial content requests. func redirectDraftSeasonLeague(season *db.Season, tab string, w http.ResponseWriter, r *http.Request) bool { if r.Method == "GET" && season.Type == db.SeasonTypeDraft.String() { redirectURL := fmt.Sprintf("/seasons/%s/%s", season.ShortName, tab) http.Redirect(w, r, redirectURL, http.StatusSeeOther) return true } return false } // DraftSeasonTabPage handles GET requests for draft season tab pages at // /seasons/{season_short_name}/{tab}. It renders the full DraftSeasonDetailPage // with the appropriate tab content pre-rendered. func DraftSeasonTabPage( s *hws.Server, conn *db.DB, tab string, ) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seasonStr := r.PathValue("season_short_name") var season *db.Season var league *db.League var teams []*db.Team var availableTeams []*db.Team var fixtures []*db.Fixture if ok := conn.WithReadTx(s, w, r, func(ctx context.Context, tx bun.Tx) (bool, error) { var err error // Verify this is a draft season season, err = db.GetSeason(ctx, tx, seasonStr) if err != nil { if db.IsBadRequest(err) { throw.NotFound(s, w, r, r.URL.Path) return false, nil } return false, errors.Wrap(err, "db.GetSeason") } if season.Type != db.SeasonTypeDraft.String() { throw.NotFound(s, w, r, r.URL.Path) return false, nil } // Fetch the Draft league and teams season, league, teams, err = db.GetSeasonLeague(ctx, tx, seasonStr, "Draft") if err != nil { return false, errors.Wrap(err, "db.GetSeasonLeague") } // Fetch tab-specific data switch tab { case "teams": availableTeams, err = db.GetList[db.Team](tx). Join("LEFT JOIN team_participations tp ON tp.team_id = t.id"). Where("NOT tp.season_id = ? OR tp.season_id IS NULL", season.ID). GetAll(ctx) if err != nil { return false, errors.Wrap(err, "db.GetList[Team]") } case "fixtures": season, league, fixtures, err = db.GetFixtures(ctx, tx, seasonStr, "Draft") if err != nil { return false, errors.Wrap(err, "db.GetFixtures") } } return true, nil }); !ok { return } renderSafely(seasonsview.DraftSeasonDetailPage( season, league, teams, availableTeams, fixtures, tab, ), s, r, w) }) }