57 lines
1.5 KiB
Go
57 lines
1.5 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")
|
|
}
|
|
league, err := season.GetLeague(leagueShortName)
|
|
if err != nil {
|
|
return nil, nil, nil, errors.Wrap(err, "season.GetLeague")
|
|
}
|
|
team, err := GetTeam(ctx, tx, teamID)
|
|
if err != nil {
|
|
return nil, nil, nil, errors.Wrap(err, "GetTeam")
|
|
}
|
|
if team.InSeason(season.ID) {
|
|
return nil, nil, nil, BadRequestAssociated("season", "team",
|
|
"id", "id", season.ID, team.ID)
|
|
}
|
|
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
|
|
}
|