Files
oslstats/internal/handlers/leagues_new.go
2026-02-14 19:48:59 +11:00

86 lines
2.3 KiB
Go

package handlers
import (
"context"
"fmt"
"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/validation"
leaguesview "git.haelnorr.com/h/oslstats/internal/view/leaguesview"
)
func NewLeague(
s *hws.Server,
) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
renderSafely(leaguesview.NewPage(), s, r, w)
})
}
func NewLeagueSubmit(
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(50).MinLength(3).Value
shortname := getter.String("short_name").
TrimSpace().Required().
MaxLength(10).MinLength(2).Value
description := getter.String("description").
TrimSpace().MaxLength(500).Value
if !getter.ValidateAndNotify(s, w, r) {
return
}
nameUnique := false
shortNameUnique := false
var league *db.League
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.League)(nil), "name", name)
if err != nil {
return false, errors.Wrap(err, "db.IsLeagueNameUnique")
}
shortNameUnique, err = db.IsUnique(ctx, tx, (*db.League)(nil), "short_name", shortname)
if err != nil {
return false, errors.Wrap(err, "db.IsLeagueShortNameUnique")
}
if !nameUnique || !shortNameUnique {
return true, nil
}
league, err = db.NewLeague(ctx, tx, name, shortname, description, db.NewAudit(r, nil))
if err != nil {
return false, errors.Wrap(err, "db.NewLeague")
}
return true, nil
}); !ok {
return
}
if !nameUnique {
notify.Warn(s, w, r, "Duplicate Name", "This league name is already taken.", nil)
return
}
if !shortNameUnique {
notify.Warn(s, w, r, "Duplicate Short Name", "This short name is already taken.", nil)
return
}
w.Header().Set("HX-Redirect", fmt.Sprintf("/leagues/%s", league.ShortName))
w.WriteHeader(http.StatusOK)
notify.SuccessWithDelay(s, w, r, "League Created", fmt.Sprintf("Successfully created league: %s", name), nil)
})
}