61 lines
1.5 KiB
Go
61 lines
1.5 KiB
Go
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/notify"
|
|
"git.haelnorr.com/h/oslstats/internal/validation"
|
|
"github.com/pkg/errors"
|
|
"github.com/uptrace/bun"
|
|
)
|
|
|
|
func SeasonLeagueAddTeam(
|
|
s *hws.Server,
|
|
conn *db.DB,
|
|
) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
seasonShortName := r.PathValue("season_short_name")
|
|
leagueShortName := 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 := conn.WithNotifyTx(s, w, r, func(ctx context.Context, tx bun.Tx) (bool, error) {
|
|
var err error
|
|
team, season, league, err = db.NewTeamParticipation(ctx, tx, seasonShortName, leagueShortName, teamID, db.NewAuditFromRequest(r))
|
|
if err != nil {
|
|
if db.IsBadRequest(err) {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return false, nil
|
|
}
|
|
return false, errors.Wrap(err, "db.NewTeamParticipation")
|
|
}
|
|
return true, nil
|
|
}); !ok {
|
|
return
|
|
}
|
|
|
|
// Redirect to refresh the page
|
|
w.Header().Set("HX-Redirect", fmt.Sprintf("/seasons/%s/leagues/%s/teams", 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)
|
|
})
|
|
}
|