package handlers import ( "context" "fmt" "net/http" "git.haelnorr.com/h/golib/hws" "git.haelnorr.com/h/oslstats/internal/auditlog" "git.haelnorr.com/h/oslstats/internal/db" "git.haelnorr.com/h/oslstats/internal/notify" "git.haelnorr.com/h/oslstats/internal/validation" "github.com/pkg/errors" "github.com/uptrace/bun" ) func SeasonLeagueAddTeam( s *hws.Server, conn *bun.DB, audit *auditlog.Logger, ) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seasonStr := r.PathValue("season_short_name") leagueStr := r.PathValue("league_short_name") getter, ok := validation.ParseFormOrNotify(s, w, r) if !ok { return } teamID := getter.Int("team_id").Required().Value if ok := getter.ValidateAndNotify(s, w, r); !ok { return } var season *db.Season var league *db.League var team *db.Team if ok := db.WithNotifyTx(s, w, r, conn, func(ctx context.Context, tx bun.Tx) (bool, error) { var err error // Get season season, err = db.GetSeason(ctx, tx, seasonStr) if err != nil { return false, errors.Wrap(err, "db.GetSeason") } if season == nil { notify.Warn(s, w, r, "Not Found", "Season not found.", nil) return false, nil } // Get league league, err = db.GetLeague(ctx, tx, leagueStr) if err != nil { return false, errors.Wrap(err, "db.GetLeague") } if league == nil { notify.Warn(s, w, r, "Not Found", "League not found.", nil) return false, nil } if !season.HasLeague(league.ID) { notify.Warn(s, w, r, "Invalid League", "This league is not associated with this season.", nil) return false, nil } // Get team team, err = db.GetTeam(ctx, tx, teamID) if err != nil { return false, errors.Wrap(err, "db.GetTeam") } if team == nil { notify.Warn(s, w, r, "Not Found", "Team not found.", nil) return false, nil } // Check if team is already in this season (in any league) var tpCount int tpCount, err = tx.NewSelect(). Model((*db.TeamParticipation)(nil)). Where("season_id = ? AND team_id = ?", season.ID, team.ID). Count(ctx) if err != nil { return false, errors.Wrap(err, "tx.NewSelect") } if tpCount > 0 { notify.Warn(s, w, r, "Already In Season", fmt.Sprintf( "Team '%s' is already participating in this season.", team.Name, ), nil) return false, nil } // Add team to league participation := &db.TeamParticipation{ SeasonID: season.ID, LeagueID: league.ID, TeamID: team.ID, } err = db.Insert(tx, participation).WithAudit(r, audit.Callback()).Exec(ctx) if err != nil { return false, errors.Wrap(err, "db.Insert") } return true, nil }); !ok { return } // Redirect to refresh the page w.Header().Set("HX-Redirect", fmt.Sprintf("/seasons/%s/leagues/%s", season.ShortName, league.ShortName)) w.WriteHeader(http.StatusOK) notify.Success(s, w, r, "Team Added", fmt.Sprintf( "Successfully added '%s' to the league.", team.Name, ), nil) }) }