package handlers import ( "context" "net/http" "git.haelnorr.com/h/golib/hws" "github.com/pkg/errors" "github.com/uptrace/bun" "git.haelnorr.com/h/oslstats/internal/db" "git.haelnorr.com/h/oslstats/internal/notify" "git.haelnorr.com/h/oslstats/internal/respond" "git.haelnorr.com/h/oslstats/internal/view/seasonsview" ) func SeasonAddLeague( 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") var season *db.Season var allLeagues []*db.League if ok := conn.WithNotifyTx(s, w, r, func(ctx context.Context, tx bun.Tx) (bool, error) { err := db.NewSeasonLeague(ctx, tx, seasonShortName, leagueShortName, db.NewAuditFromRequest(r)) if err != nil { if db.IsBadRequest(err) { respond.BadRequest(w, err) return false, nil } return false, errors.Wrap(err, "db.NewSeasonLeague") } // Reload season with updated leagues season, err = db.GetSeason(ctx, tx, seasonShortName) if err != nil { return false, errors.Wrap(err, "db.GetSeason") } allLeagues, err = db.GetLeagues(ctx, tx) if err != nil { return false, errors.Wrap(err, "db.GetLeagues") } return true, nil }); !ok { return } notify.Success(s, w, r, "League Added", "League successfully added to season", nil) renderSafely(seasonsview.LeaguesSection(season, allLeagues), s, r, w) }) } func SeasonRemoveLeague( 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 allLeagues []*db.League if ok := conn.WithNotifyTx(s, w, r, func(ctx context.Context, tx bun.Tx) (bool, error) { var err error season, err = db.GetSeason(ctx, tx, seasonStr) if err != nil { if db.IsBadRequest(err) { respond.NotFound(w, err) return false, nil } return false, errors.Wrap(err, "db.GetSeason") } err = season.RemoveLeague(ctx, tx, leagueStr, db.NewAuditFromRequest(r)) if err != nil { if db.IsBadRequest(err) { respond.BadRequest(w, err) } return false, errors.Wrap(err, "season.RemoveLeague") } // Reload season with updated leagues season, err = db.GetSeason(ctx, tx, seasonStr) if err != nil { return false, errors.Wrap(err, "db.GetSeason") } allLeagues, err = db.GetLeagues(ctx, tx) if err != nil { return false, errors.Wrap(err, "db.GetLeagues") } return true, nil }); !ok { return } notify.Success(s, w, r, "League Removed", "League successfully removed from season", nil) renderSafely(seasonsview.LeaguesSection(season, allLeagues), s, r, w) }) }