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/respond" "git.haelnorr.com/h/oslstats/internal/validation" teamsview "git.haelnorr.com/h/oslstats/internal/view/teamsview" ) func NewTeamPage( s *hws.Server, ) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { renderSafely(teamsview.NewPage(), s, r, w) }) } func NewTeamSubmit( 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(25).MinLength(3).Value shortName := getter.String("short_name"). TrimSpace().Required().ToUpper(). MaxLength(3).MinLength(3).Value altShortName := getter.String("alt_short_name"). TrimSpace().Required().ToUpper(). MaxLength(3).MinLength(3).Value color := getter.String("color"). TrimSpace().MaxLength(7).Value if !getter.ValidateAndNotify(s, w, r) { return } // Check that short names are different if shortName == altShortName { notify.Warn(s, w, r, "Invalid Short Names", "Short name and alternative short name must be different.", nil) return } nameUnique := false shortNameComboUnique := false 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.Team)(nil), "name", name) if err != nil { return false, errors.Wrap(err, "db.IsTeamNameUnique") } shortNameComboUnique, err = db.TeamShortNamesUnique(ctx, tx, shortName, altShortName) if err != nil { return false, errors.Wrap(err, "db.TeamShortNamesUnique") } if !nameUnique || !shortNameComboUnique { return true, nil } _, err = db.NewTeam(ctx, tx, name, shortName, altShortName, color, db.NewAudit(r, nil)) if err != nil { return false, errors.Wrap(err, "db.NewTeam") } return true, nil }); !ok { return } if !nameUnique { notify.Warn(s, w, r, "Duplicate Name", "This team name is already taken.", nil) return } if !shortNameComboUnique { notify.Warn(s, w, r, "Duplicate Short Names", "This combination of short names is already taken.", nil) return } respond.HXRedirect(w, "/teams") notify.SuccessWithDelay(s, w, r, "Team Created", fmt.Sprintf("Successfully created team: %s", name), nil) }) }