97 lines
2.5 KiB
Go
97 lines
2.5 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/auditlog"
|
|
"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,
|
|
conn *bun.DB,
|
|
) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == "GET" {
|
|
renderSafely(leaguesview.NewPage(), s, r, w)
|
|
return
|
|
}
|
|
})
|
|
}
|
|
|
|
func NewLeagueSubmit(
|
|
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(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 := 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.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 = &db.League{
|
|
Name: name,
|
|
ShortName: shortname,
|
|
Description: description,
|
|
}
|
|
err = db.Insert(tx, league).WithAudit(r, audit.Callback()).Exec(ctx)
|
|
if err != nil {
|
|
return false, errors.Wrap(err, "db.Insert")
|
|
}
|
|
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)
|
|
})
|
|
}
|