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/permissions" "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, conn *bun.DB, ) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { renderSafely(seasonsview.NewPage(), s, r, w) return } }) } func NewSeasonSubmit( s *hws.Server, conn *bun.DB, audit *auditlog.Logger, ) 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 format := timefmt.NewBuilder(). DayNumeric2().Slash(). MonthNumeric2().Slash(). Year4().Build() startDate := getter.Time("start_date", format).Required().Value if !getter.ValidateAndNotify(s, w, r) { return } nameUnique := false shortNameUnique := false var season *db.Season if ok := db.WithNotifyTx(s, w, r, conn, 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, shortName, startDate) if err != nil { return false, errors.Wrap(err, "db.NewSeason") } user := db.CurrentUser(ctx) err = audit.LogSuccess(ctx, tx, user, permissions.SeasonsCreate.String(), "season", season.ID, nil, r) if err != nil { return false, errors.Wrap(err, "audit.LogSuccess") } 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 } notify.Success(s, w, r, "Season Created", fmt.Sprintf("Successfully created season: %s", name), nil) w.Header().Set("HX-Redirect", fmt.Sprintf("/seasons/%s", season.ShortName)) w.WriteHeader(http.StatusOK) }) }