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/throw" "git.haelnorr.com/h/oslstats/internal/validation" "git.haelnorr.com/h/oslstats/internal/view/seasonsview" "git.haelnorr.com/h/timefmt" "github.com/pkg/errors" "github.com/uptrace/bun" ) func SeasonEditPage( s *hws.Server, conn *bun.DB, ) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seasonStr := r.PathValue("season_short_name") var season *db.Season var allLeagues []*db.League if ok := db.WithReadTx(s, w, r, conn, func(ctx context.Context, tx bun.Tx) (bool, error) { var err error 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 } if season == nil { throw.NotFound(s, w, r, r.URL.Path) return } renderSafely(seasonsview.EditPage(season, allLeagues), s, r, w) }) } func SeasonEditSubmit( 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") getter, ok := validation.ParseFormOrNotify(s, w, r) if !ok { return } format := timefmt.NewBuilder(). DayNumeric2().Slash(). MonthNumeric2().Slash(). Year4().Build() version := getter.String("slap_version"). TrimSpace().Required().AllowedValues([]string{"rebound", "slapshot1"}).Value start := getter.Time("start_date", format).Required().Value end := getter.Time("end_date", format).Value finalsStart := getter.Time("finals_start_date", format).Value finalsEnd := getter.Time("finals_end_date", format).Value if !getter.ValidateAndNotify(s, w, r) { return } var season *db.Season if ok := db.WithNotifyTx(s, w, r, conn, func(ctx context.Context, tx bun.Tx) (bool, error) { var err error season, err = db.GetSeason(ctx, tx, seasonStr) if err != nil { return false, errors.Wrap(err, "db.GetSeason") } if season == nil { return false, errors.New("season does not exist") } season.Update(version, start, end, finalsStart, finalsEnd) err = db.Update(tx, season).WherePK(). Column("slap_version", "start_date", "end_date", "finals_start_date", "finals_end_date"). WithAudit(r, audit.Callback()).Exec(ctx) if err != nil { return false, errors.Wrap(err, "db.Update") } return true, nil }); !ok { return } if season == nil { throw.NotFound(s, w, r, r.URL.Path) return } w.Header().Set("HX-Redirect", fmt.Sprintf("/seasons/%s", season.ShortName)) w.WriteHeader(http.StatusOK) notify.SuccessWithDelay(s, w, r, "Season Updated", fmt.Sprintf("Successfully updated season: %s", season.Name), nil) }) }