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/respond" "git.haelnorr.com/h/oslstats/internal/validation" seasonsview "git.haelnorr.com/h/oslstats/internal/view/seasonsview" "git.haelnorr.com/h/timefmt" "github.com/pkg/errors" "github.com/uptrace/bun" ) func NewSeason( s *hws.Server, ) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { renderSafely(seasonsview.NewPage(), s, r, w) }) } func NewSeasonSubmit( s *hws.Server, conn *db.DB, ) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { getter, ok := validation.ParseFormOrNotify(s, w, r) if !ok { return } name := getter.String("name"). TrimSpace().Required(). MaxLength(20).MinLength(5).Value shortname := getter.String("short_name"). TrimSpace().ToUpper().Required(). MaxLength(6).MinLength(2).Value version := getter.String("slap_version"). TrimSpace().Required().AllowedValues([]string{"rebound", "slapshot1"}).Value format := timefmt.NewBuilder(). DayNumeric2().Slash(). MonthNumeric2().Slash(). Year4().Build() start := getter.Time("start_date", format).Required().Value if !getter.ValidateAndNotify(s, w, r) { return } nameUnique := false shortNameUnique := false var season *db.Season if ok := conn.WithNotifyTx(s, w, r, func(ctx context.Context, tx bun.Tx) (bool, error) { var err error nameUnique, err = db.IsUnique(ctx, tx, (*db.Season)(nil), "name", name) if err != nil { return false, errors.Wrap(err, "db.IsSeasonNameUnique") } shortNameUnique, err = db.IsUnique(ctx, tx, (*db.Season)(nil), "short_name", shortname) if err != nil { return false, errors.Wrap(err, "db.IsSeasonShortNameUnique") } if !nameUnique || !shortNameUnique { return true, nil } season, err = db.NewSeason(ctx, tx, name, version, shortname, start, db.NewAudit(r, nil)) if err != nil { return false, errors.Wrap(err, "db.NewSeason") } return true, nil }); !ok { return } if !nameUnique { notify.Warn(s, w, r, "Duplicate Name", "This season name is already taken.", nil) return } if !shortNameUnique { notify.Warn(s, w, r, "Duplicate Short Name", "This short name is already taken.", nil) return } respond.HXRedirect(w, "/seasons/%s", season.ShortName) notify.SuccessWithDelay(s, w, r, "Season Created", fmt.Sprintf("Successfully created season: %s", name), nil) }) }