Files
oslstats/internal/handlers/newseason.go

94 lines
2.4 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"
"git.haelnorr.com/h/oslstats/internal/view/page"
"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(page.NewSeason(), s, r, w)
return
}
})
}
func NewSeasonSubmit(
s *hws.Server,
conn *bun.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
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")
}
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)
})
}