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

68 lines
1.8 KiB
Go

package db
import (
"context"
"github.com/pkg/errors"
"github.com/uptrace/bun"
)
type TeamParticipation struct {
SeasonID int `bun:",pk,unique:season_team"`
Season *Season `bun:"rel:belongs-to,join:season_id=id"`
LeagueID int `bun:",pk"`
League *League `bun:"rel:belongs-to,join:league_id=id"`
TeamID int `bun:",pk,unique:season_team"`
Team *Team `bun:"rel:belongs-to,join:team_id=id"`
}
func NewTeamParticipation(ctx context.Context, tx bun.Tx,
seasonShortName, leagueShortName string, teamID int, audit *AuditMeta,
) (*Team, *Season, *League, error) {
season, err := GetSeason(ctx, tx, seasonShortName)
if err != nil {
return nil, nil, nil, errors.Wrap(err, "GetSeason")
}
if season == nil {
return nil, nil, nil, errors.New("season not found")
}
league, err := GetLeague(ctx, tx, leagueShortName)
if err != nil {
return nil, nil, nil, errors.Wrap(err, "GetLeague")
}
if league == nil {
return nil, nil, nil, errors.New("league not found")
}
if !season.HasLeague(league.ID) {
return nil, nil, nil, errors.New("league is not assigned to the season")
}
team, err := GetTeam(ctx, tx, teamID)
if err != nil {
return nil, nil, nil, errors.Wrap(err, "GetTeam")
}
if team == nil {
return nil, nil, nil, errors.New("team not found")
}
if team.InSeason(season.ID) {
return nil, nil, nil, errors.New("team already in season")
}
participation := &TeamParticipation{
SeasonID: season.ID,
LeagueID: league.ID,
TeamID: team.ID,
}
info := &AuditInfo{
"teams.join_season",
"team",
teamID,
map[string]any{"season_id": season.ID, "league_id": league.ID},
}
err = Insert(tx, participation).
WithAudit(audit, info).Exec(ctx)
if err != nil {
return nil, nil, nil, errors.Wrap(err, "db.Insert")
}
return team, season, league, nil
}