90 lines
2.7 KiB
Go
90 lines
2.7 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"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/respond"
|
|
"git.haelnorr.com/h/oslstats/internal/validation"
|
|
seasonsview "git.haelnorr.com/h/oslstats/internal/view/seasonsview"
|
|
"github.com/pkg/errors"
|
|
"github.com/uptrace/bun"
|
|
)
|
|
|
|
// ManageTeamRoster handles saving a full team roster (manager + players)
|
|
func ManageTeamRoster(
|
|
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 {
|
|
respond.BadRequest(w, errors.New("failed to parse form"))
|
|
return
|
|
}
|
|
|
|
seasonID := getter.Int("season_id").Required().Value
|
|
leagueID := getter.Int("league_id").Required().Value
|
|
teamID := getter.Int("team_id").Required().Value
|
|
managerID := getter.Int("manager_id").Required().Value
|
|
playerIDs := getter.IntList("player_ids").Values()
|
|
|
|
if !getter.ValidateAndNotify(s, w, r) {
|
|
respond.BadRequest(w, errors.New("invalid form data"))
|
|
return
|
|
}
|
|
|
|
// Write transaction: manage the roster
|
|
if !conn.WithNotifyTx(s, w, r, func(ctx context.Context, tx bun.Tx) (bool, error) {
|
|
err := db.ManageTeamRoster(ctx, tx, seasonID, leagueID, teamID, managerID, playerIDs, db.NewAuditFromRequest(r))
|
|
if err != nil {
|
|
return false, errors.Wrap(err, "db.ManageTeamRoster")
|
|
}
|
|
return true, nil
|
|
}) {
|
|
return
|
|
}
|
|
|
|
// Re-fetch updated data for HTMX swap
|
|
var twr *db.TeamWithRoster
|
|
var available []*db.Player
|
|
|
|
if !conn.WithReadTx(s, w, r, func(ctx context.Context, tx bun.Tx) (bool, error) {
|
|
var err error
|
|
|
|
// We need season/league short names to call GetTeamRoster
|
|
season, err := db.GetByID[db.Season](tx, seasonID).Get(ctx)
|
|
if err != nil {
|
|
return false, errors.Wrap(err, "db.GetSeason")
|
|
}
|
|
league, err := db.GetByID[db.League](tx, leagueID).Get(ctx)
|
|
if err != nil {
|
|
return false, errors.Wrap(err, "db.GetLeague")
|
|
}
|
|
|
|
twr, err = db.GetTeamRoster(ctx, tx, season.ShortName, league.ShortName, teamID)
|
|
if err != nil {
|
|
return false, errors.Wrap(err, "db.GetTeamRoster")
|
|
}
|
|
|
|
available, err = db.GetPlayersNotOnTeam(ctx, tx, seasonID, leagueID)
|
|
if err != nil {
|
|
return false, errors.Wrap(err, "db.GetPlayersNotOnTeam")
|
|
}
|
|
|
|
return true, nil
|
|
}) {
|
|
return
|
|
}
|
|
|
|
// Respond with HTMX swap of the roster section
|
|
w.Header().Set("HX-Retarget", "#team-roster-section")
|
|
w.Header().Set("HX-Reswap", "outerHTML")
|
|
notify.Success(s, w, r, "Roster Updated", "Team roster has been saved successfully.", nil)
|
|
renderSafely(seasonsview.TeamRosterSection(twr, available), s, r, w)
|
|
})
|
|
}
|