This commit is contained in:
2026-10-03 13:00:50 +07:00
parent dd55079e06
commit 7a7808b4d1
28 changed files with 191 additions and 11 deletions
+8
View File
@@ -9,24 +9,29 @@ import (
)
var (
// ErrActionsNotFound indicates that no actions were found.
ErrActionsNotFound = errors.New("Ход не найден")
)
// ActionsRepo persists team actions.
type ActionsRepo struct {
pool *pgxpool.Pool
}
// Action describes a team action.
type Action struct {
Code string
ViaMCP bool
}
// NewActionsRepo creates an actions repository.
func NewActionsRepo(pool *pgxpool.Pool) *ActionsRepo {
return &ActionsRepo{
pool: pool,
}
}
// AddAction stores an action for a team.
func (r *ActionsRepo) AddAction(ctx context.Context, teamID int, code string, viaMCP bool) (int, error) {
id := 0
err := r.pool.QueryRow(
@@ -45,6 +50,7 @@ func (r *ActionsRepo) AddAction(ctx context.Context, teamID int, code string, vi
return id, nil
}
// GetActionsByTeamID returns actions for a team.
func (r *ActionsRepo) GetActionsByTeamID(ctx context.Context, teamID int) ([]Action, error) {
rows, err := r.pool.Query(
ctx,
@@ -80,6 +86,7 @@ func (r *ActionsRepo) GetActionsByTeamID(ctx context.Context, teamID int) ([]Act
return actions, nil
}
// GetActionsCountByTeamIDs returns action counts for teams.
func (r *ActionsRepo) GetActionsCountByTeamIDs(ctx context.Context, teamIDs []int) (map[int]int, error) {
rows, err := r.pool.Query(
ctx,
@@ -116,6 +123,7 @@ func (r *ActionsRepo) GetActionsCountByTeamIDs(ctx context.Context, teamIDs []in
return res, nil
}
// DeleteLastActionByTeamID removes the latest action for a team.
func (r *ActionsRepo) DeleteLastActionByTeamID(ctx context.Context, teamID int) error {
tag, err := r.pool.Exec(
ctx,
+7
View File
@@ -10,19 +10,23 @@ import (
)
var (
// ErrApplicationNotFound indicates that an application was not found.
ErrApplicationNotFound = errors.New("Улика не найдена")
)
// ApplicationsRepo persists team applications.
type ApplicationsRepo struct {
pool *pgxpool.Pool
}
// NewApplicationsRepo creates an applications repository.
func NewApplicationsRepo(pool *pgxpool.Pool) *ApplicationsRepo {
return &ApplicationsRepo{
pool: pool,
}
}
// AddApplication stores an application for a team.
func (r *ApplicationsRepo) AddApplication(
ctx context.Context,
teamID int,
@@ -48,6 +52,7 @@ func (r *ApplicationsRepo) AddApplication(
return id, nil
}
// GetApplicationsByTeamIDsAndState returns applications matching team IDs and state.
func (r *ApplicationsRepo) GetApplicationsByTeamIDsAndState(
ctx context.Context,
teamIDs []int,
@@ -91,6 +96,7 @@ func (r *ApplicationsRepo) GetApplicationsByTeamIDsAndState(
return res, nil
}
// UpdateApplicationStatus changes an application's status.
func (r *ApplicationsRepo) UpdateApplicationStatus(
ctx context.Context,
teamID int,
@@ -116,6 +122,7 @@ func (r *ApplicationsRepo) UpdateApplicationStatus(
return nil
}
// DeleteApplicationByTeamIDAndName removes an application by team and name.
func (r *ApplicationsRepo) DeleteApplicationByTeamIDAndName(ctx context.Context, teamID int, name string) error {
tag, err := r.pool.Exec(
ctx,
+17 -3
View File
@@ -11,12 +11,17 @@ import (
)
var (
// ErrReviewNotFound indicates that a review was not found.
ErrReviewNotFound = errors.New("Отзыв не найден")
ErrReviewExists = errors.New("Отзыв от команды уже оставлен")
ErrTeamNotFound = errors.New("Команда не найдена")
ErrInvalidStatus = errors.New("Недопустимый статус модерации")
// ErrReviewExists indicates that a team already submitted a review.
ErrReviewExists = errors.New("Отзыв от команды уже оставлен")
// ErrTeamNotFound indicates that a team was not found.
ErrTeamNotFound = errors.New("Команда не найдена")
// ErrInvalidStatus indicates that a moderation status is invalid.
ErrInvalidStatus = errors.New("Недопустимый статус модерации")
)
// Review describes a game review.
type Review struct {
ID int
GameID int
@@ -29,10 +34,13 @@ type Review struct {
CreatedAt time.Time
}
// Repo persists game reviews.
type Repo struct{ pool *pgxpool.Pool }
// NewGameReviewsRepo creates a game reviews repository.
func NewGameReviewsRepo(pool *pgxpool.Pool) *Repo { return &Repo{pool: pool} }
// Create stores a review.
func (r *Repo) Create(ctx context.Context, gameID, teamID int, rating int32, text string) (*Review, error) {
review := &Review{}
err := r.pool.QueryRow(
@@ -72,10 +80,12 @@ func (r *Repo) Create(ctx context.Context, gameID, teamID int, rating int32, tex
return review, err
}
// GetByID returns a review by ID.
func (r *Repo) GetByID(ctx context.Context, id int) (*Review, error) {
return r.queryOne(ctx, id)
}
// List returns reviews for a game and aggregate rating data.
func (r *Repo) List(ctx context.Context, gameID int, all bool) ([]*Review, float64, int32, error) {
rows, err := r.pool.Query(
ctx,
@@ -117,6 +127,7 @@ func (r *Repo) List(ctx context.Context, gameID int, all bool) ([]*Review, float
return reviews, average, int32(count), nil
}
// ListForModeration returns reviews awaiting moderation.
func (r *Repo) ListForModeration(ctx context.Context) ([]*Review, error) {
rows, err := r.pool.Query(
ctx,
@@ -141,6 +152,7 @@ func (r *Repo) ListForModeration(ctx context.Context) ([]*Review, error) {
return reviews, rows.Err()
}
// Moderate updates a review moderation status.
func (r *Repo) Moderate(ctx context.Context, id int, status string) (*Review, error) {
if status != "approved" && status != "rejected" && status != "hidden" {
return nil, ErrInvalidStatus
@@ -162,6 +174,7 @@ func (r *Repo) Moderate(ctx context.Context, id int, status string) (*Review, er
return r.queryOne(ctx, id)
}
// ScenarioRating returns aggregate ratings for a scenario.
func (r *Repo) ScenarioRating(ctx context.Context, scenarioID int) (float64, int32, error) {
var average float64
var count int64
@@ -176,6 +189,7 @@ func (r *Repo) ScenarioRating(ctx context.Context, scenarioID int) (float64, int
return average, int32(count), err
}
// ListByScenario returns reviews and aggregate ratings for a scenario.
func (r *Repo) ListByScenario(ctx context.Context, scenarioID int) ([]*Review, float64, int32, error) {
rows, err := r.pool.Query(
ctx,
+13
View File
@@ -12,19 +12,23 @@ import (
)
var (
// ErrGameNotFound indicates that a game was not found.
ErrGameNotFound = errors.New("Игра не найдена")
)
// GamesRepo persists games.
type GamesRepo struct {
pool *pgxpool.Pool
}
// NewGamesRepo creates a games repository.
func NewGamesRepo(pool *pgxpool.Pool) *GamesRepo {
return &GamesRepo{
pool: pool,
}
}
// AddGame stores a game.
func (r *GamesRepo) AddGame(
ctx context.Context,
name string,
@@ -54,6 +58,7 @@ func (r *GamesRepo) AddGame(
return id, nil
}
// GetGameByID returns a game by ID.
func (r *GamesRepo) GetGameByID(
ctx context.Context,
id int,
@@ -98,6 +103,7 @@ func (r *GamesRepo) GetGameByID(
return game, nil
}
// DeleteGameByID removes a game by ID.
func (r *GamesRepo) DeleteGameByID(
ctx context.Context,
id int,
@@ -117,6 +123,7 @@ func (r *GamesRepo) DeleteGameByID(
return nil
}
// GetGames returns games matching the requested filters.
func (r *GamesRepo) GetGames(
ctx context.Context,
) ([]*repos.Game, error) {
@@ -162,6 +169,7 @@ func (r *GamesRepo) GetGames(
return games, nil
}
// UpdateGame updates a game's editable fields.
func (r *GamesRepo) UpdateGame(
ctx context.Context,
id int,
@@ -201,6 +209,7 @@ func (r *GamesRepo) UpdateGame(
return nil
}
// StartGame marks a game as started.
func (r *GamesRepo) StartGame(ctx context.Context, id int) error {
tag, err := r.pool.Exec(
ctx,
@@ -221,6 +230,7 @@ func (r *GamesRepo) StartGame(ctx context.Context, id int) error {
return nil
}
// PauseGame marks a game as paused.
func (r *GamesRepo) PauseGame(ctx context.Context, id int) error {
tag, err := r.pool.Exec(
ctx,
@@ -240,6 +250,7 @@ func (r *GamesRepo) PauseGame(ctx context.Context, id int) error {
return nil
}
// PlayGame resumes a paused game.
func (r *GamesRepo) PlayGame(ctx context.Context, id int) error {
tag, err := r.pool.Exec(
ctx,
@@ -259,6 +270,7 @@ func (r *GamesRepo) PlayGame(ctx context.Context, id int) error {
return nil
}
// FinishGame marks a game as finished.
func (r *GamesRepo) FinishGame(ctx context.Context, id int) error {
tag, err := r.pool.Exec(
ctx,
@@ -279,6 +291,7 @@ func (r *GamesRepo) FinishGame(ctx context.Context, id int) error {
return nil
}
// ResetGame resets a game's state.
func (r *GamesRepo) ResetGame(ctx context.Context, id int) error {
tag, err := r.pool.Exec(
ctx,
@@ -10,8 +10,10 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
)
// ErrScreenNotFound indicates that a screen session was not found.
var ErrScreenNotFound = errors.New("Экран не найден")
// ScreenSession describes a screen session.
type ScreenSession struct {
ID int
GameID *int
@@ -29,14 +31,17 @@ type ScreenSession struct {
TimerEndsAt *time.Time
}
// ScreenSessionsRepo persists screen sessions.
type ScreenSessionsRepo struct {
pool *pgxpool.Pool
}
// NewScreenSessionsRepo creates a screen sessions repository.
func NewScreenSessionsRepo(pool *pgxpool.Pool) *ScreenSessionsRepo {
return &ScreenSessionsRepo{pool: pool}
}
// Create creates a screen session.
func (r *ScreenSessionsRepo) Create(ctx context.Context, tokenHash string) (int, error) {
var id int
err := r.pool.QueryRow(ctx, `
@@ -46,6 +51,7 @@ func (r *ScreenSessionsRepo) Create(ctx context.Context, tokenHash string) (int,
return id, err
}
// Get returns a screen session by ID and token hash.
func (r *ScreenSessionsRepo) Get(ctx context.Context, id int, tokenHash string) (*ScreenSession, error) {
session := &ScreenSession{ID: id}
err := r.pool.QueryRow(ctx, `
@@ -69,6 +75,7 @@ func (r *ScreenSessionsRepo) Get(ctx context.Context, id int, tokenHash string)
return session, nil
}
// ListByGame returns screen sessions for a game.
func (r *ScreenSessionsRepo) ListByGame(ctx context.Context, gameID int) ([]*ScreenSession, error) {
rows, err := r.pool.Query(ctx, `
SELECT id, game_id, sound_enabled, last_seen_at, mode, state_version, position_ms, command, volume,
@@ -93,21 +100,25 @@ func (r *ScreenSessionsRepo) ListByGame(ctx context.Context, gameID int) ([]*Scr
return sessions, rows.Err()
}
// SetMode updates the display mode for a game.
func (r *ScreenSessionsRepo) SetMode(ctx context.Context, gameID int, mode int32) error {
_, err := r.pool.Exec(ctx, `UPDATE screen_sessions SET mode = $2, command = 0, state_version = state_version + 1, updated_at = NOW() WHERE game_id = $1`, gameID, mode)
return err
}
// SetPosition updates the display position for a game.
func (r *ScreenSessionsRepo) SetPosition(ctx context.Context, gameID int, position int64) error {
_, err := r.pool.Exec(ctx, `UPDATE screen_sessions SET position_ms = $2, state_version = state_version + 1, updated_at = NOW() WHERE game_id = $1`, gameID, position)
return err
}
// SetCommand updates the display command for a game.
func (r *ScreenSessionsRepo) SetCommand(ctx context.Context, gameID int, command int32, position int64, volume int32) error {
_, err := r.pool.Exec(ctx, `UPDATE screen_sessions SET command = $2, position_ms = $3, volume = $4, state_version = state_version + 1, updated_at = NOW() WHERE game_id = $1`, gameID, command, position, volume)
return err
}
// SetTimer updates the display timer for a game.
func (r *ScreenSessionsRepo) SetTimer(ctx context.Context, gameID int, duration int64, label string) error {
_, err := r.pool.Exec(ctx, `
UPDATE screen_sessions
@@ -124,6 +135,7 @@ func (r *ScreenSessionsRepo) SetTimer(ctx context.Context, gameID int, duration
return err
}
// SetTimerCommand updates the timer command for a game.
func (r *ScreenSessionsRepo) SetTimerCommand(ctx context.Context, gameID int, command int32) error {
_, err := r.pool.Exec(ctx, `
UPDATE screen_sessions
@@ -154,6 +166,7 @@ func (r *ScreenSessionsRepo) SetTimerCommand(ctx context.Context, gameID int, co
return err
}
// Bind attaches a screen session to a game.
func (r *ScreenSessionsRepo) Bind(ctx context.Context, id, gameID int, tokenHash string) error {
result, err := r.pool.Exec(ctx, `
UPDATE screen_sessions
@@ -168,6 +181,7 @@ func (r *ScreenSessionsRepo) Bind(ctx context.Context, id, gameID int, tokenHash
return nil
}
// Unbind detaches a screen session from its game.
func (r *ScreenSessionsRepo) Unbind(ctx context.Context, id int) error {
result, err := r.pool.Exec(ctx, `
UPDATE screen_sessions
@@ -192,6 +206,7 @@ func (r *ScreenSessionsRepo) Unbind(ctx context.Context, id int) error {
return nil
}
// SetSound enables or disables sound for a screen session.
func (r *ScreenSessionsRepo) SetSound(ctx context.Context, id int, enabled bool) error {
query := `UPDATE screen_sessions SET sound_enabled = FALSE, updated_at = NOW() WHERE id = $1`
args := []any{id}
@@ -11,14 +11,20 @@ import (
"github.com/jackc/pgx/v5"
)
// ErrParticipationLink indicates that a participation link is invalid.
var ErrParticipationLink = errors.New("Ссылка недействительна")
// ErrParticipationClosed indicates that participation answers are closed.
var ErrParticipationClosed = errors.New("Приём ответов закрыт")
// ErrParticipationFinal indicates that a final answer cannot be changed.
var ErrParticipationFinal = errors.New("Решение уже принято и не может быть изменено")
const maxParticipationEmailAttempts = 8
const maxReviewReminderAttempts = 8
// Participation describes a team's participation state.
type Participation struct {
TeamID int
TeamName string
@@ -31,6 +37,7 @@ type Participation struct {
Attempts int
}
// ReviewReminder describes a pending review reminder.
type ReviewReminder struct {
TeamID int
TeamName string
@@ -53,6 +60,7 @@ func tokenHash(token string) ([]byte, error) {
return hash[:], nil
}
// GetParticipation returns participation data by token.
func (r *TeamsRepo) GetParticipation(ctx context.Context, token string) (*Participation, error) {
hash, err := tokenHash(token)
if err != nil {
@@ -69,6 +77,7 @@ func (r *TeamsRepo) GetParticipation(ctx context.Context, token string) (*Partic
return p, err
}
// AnswerParticipation stores a team's final answer.
func (r *TeamsRepo) AnswerParticipation(ctx context.Context, token, answer string) (*Participation, error) {
if answer != "confirmed" && answer != "cancelled" {
return nil, errors.New("Выберите подтверждение или отмену участия")
@@ -102,6 +111,7 @@ func (r *TeamsRepo) AnswerParticipation(ctx context.Context, token, answer strin
// Пятиминутная аренда переживает перезапуски и не позволяет рабочим процессам
// отправить одну задачу повторно.
// ClaimParticipationEmail claims the next participation email job.
func (r *TeamsRepo) ClaimParticipationEmail(ctx context.Context) (*Participation, error) {
p := &Participation{}
err := r.pool.QueryRow(ctx, `WITH candidate AS (
@@ -122,6 +132,7 @@ func (r *TeamsRepo) ClaimParticipationEmail(ctx context.Context) (*Participation
return p, err
}
// SetParticipationToken stores a participation token.
func (r *TeamsRepo) SetParticipationToken(ctx context.Context, id int, token string) error {
hash, err := tokenHash(token)
if err != nil {
@@ -131,6 +142,7 @@ func (r *TeamsRepo) SetParticipationToken(ctx context.Context, id int, token str
return err
}
// ConfirmParticipationByFirstAction confirms participation after the first action.
func (r *TeamsRepo) ConfirmParticipationByFirstAction(ctx context.Context, teamID int) error {
_, err := r.pool.Exec(ctx, `UPDATE teams SET participation_status='confirmed',
participation_source='first_action', participation_answered_at=NOW()
@@ -138,6 +150,7 @@ func (r *TeamsRepo) ConfirmParticipationByFirstAction(ctx context.Context, teamI
return err
}
// FinishParticipationEmail completes a participation email job.
func (r *TeamsRepo) FinishParticipationEmail(ctx context.Context, id, attempt int, sendErr error) error {
message := ""
if sendErr != nil {
@@ -149,6 +162,7 @@ func (r *TeamsRepo) FinishParticipationEmail(ctx context.Context, id, attempt in
return err
}
// ClaimReviewReminder claims the next review reminder job.
func (r *TeamsRepo) ClaimReviewReminder(ctx context.Context) (*ReviewReminder, error) {
job := &ReviewReminder{}
err := r.pool.QueryRow(ctx, `WITH candidate AS (
@@ -168,6 +182,7 @@ func (r *TeamsRepo) ClaimReviewReminder(ctx context.Context) (*ReviewReminder, e
return job, err
}
// FinishReviewReminder completes a review reminder job.
func (r *TeamsRepo) FinishReviewReminder(ctx context.Context, id, attempt int, sendErr error) error {
message := ""
if sendErr != nil {
+11
View File
@@ -10,19 +10,23 @@ import (
)
var (
// ErrTeamNotFound indicates that a team was not found.
ErrTeamNotFound = errors.New("Команда не найдена")
)
// TeamsRepo persists teams and their game membership.
type TeamsRepo struct {
pool *pgxpool.Pool
}
// NewTeamsRepo creates a teams repository.
func NewTeamsRepo(pool *pgxpool.Pool) *TeamsRepo {
return &TeamsRepo{
pool: pool,
}
}
// GetTeamByID returns a team by ID.
func (r *TeamsRepo) GetTeamByID(ctx context.Context, id int) (*repos.Team, error) {
team := &repos.Team{}
row := r.pool.QueryRow(
@@ -60,6 +64,7 @@ func (r *TeamsRepo) GetTeamByID(ctx context.Context, id int) (*repos.Team, error
return team, nil
}
// GetTeamsByGameID returns teams registered for a game.
func (r *TeamsRepo) GetTeamsByGameID(
ctx context.Context,
gameID int,
@@ -108,6 +113,7 @@ func (r *TeamsRepo) GetTeamsByGameID(
return teams, nil
}
// AddTeam creates a team.
func (r *TeamsRepo) AddTeam(
ctx context.Context,
creatorID int,
@@ -118,6 +124,7 @@ func (r *TeamsRepo) AddTeam(
return r.AddTeamWithParticipation(ctx, creatorID, gameID, name, password, "", false)
}
// AddTeamWithParticipation creates a team with participation data.
func (r *TeamsRepo) AddTeamWithParticipation(ctx context.Context, creatorID, gameID int, name, password, captainEmail string, autoConfirm bool) (int, error) {
id := 0
status, source := "pending", ""
@@ -144,6 +151,7 @@ func (r *TeamsRepo) AddTeamWithParticipation(ctx context.Context, creatorID, gam
return id, nil
}
// UpdateTeam changes a team's name.
func (r *TeamsRepo) UpdateTeam(ctx context.Context, teamID int, name string) error {
tag, err := r.pool.Exec(
ctx,
@@ -163,6 +171,7 @@ func (r *TeamsRepo) UpdateTeam(ctx context.Context, teamID int, name string) err
return nil
}
// DeleteTeam removes a team.
func (r *TeamsRepo) DeleteTeam(ctx context.Context, teamID int) error {
tag, err := r.pool.Exec(
ctx,
@@ -179,6 +188,7 @@ func (r *TeamsRepo) DeleteTeam(ctx context.Context, teamID int) error {
return nil
}
// ErrRegistrationClosed indicates that team registration is unavailable.
var ErrRegistrationClosed = errors.New("Игра не найдена или регистрация уже закрыта")
// RegisterTeam сохраняет одну команду на доставку, включая одновременные повторы.
@@ -186,6 +196,7 @@ func (r *TeamsRepo) RegisterTeam(ctx context.Context, gameID int, deliveryID, na
return r.RegisterTeamWithParticipation(ctx, gameID, deliveryID, name, email, participantsCount, password, false)
}
// RegisterTeamWithParticipation registers a team and its participation data.
func (r *TeamsRepo) RegisterTeamWithParticipation(ctx context.Context, gameID int, deliveryID, name, email string, participantsCount int32, password string, autoConfirm bool) (int, error) {
var id int
// Повтор уже принятой доставки успешен и после старта игры.
+9
View File
@@ -14,13 +14,16 @@ import (
)
var (
// ErrUserNotFound indicates that a user was not found.
ErrUserNotFound = errors.New("Пользователь не найден")
)
// UsersRepo persists users and their roles.
type UsersRepo struct {
pool *pgxpool.Pool
}
// NewUserRepo creates a users repository.
func NewUserRepo(pool *pgxpool.Pool) *UsersRepo {
return &UsersRepo{
pool: pool,
@@ -105,6 +108,7 @@ func (s *UsersRepo) AddUserWithAgreements(
return id, nil
}
// UpdateUserPassword changes a user's password hash.
func (s *UsersRepo) UpdateUserPassword(
ctx context.Context,
email string,
@@ -128,6 +132,7 @@ func (s *UsersRepo) UpdateUserPassword(
return nil
}
// GetUserByEmail returns a user by email.
func (s *UsersRepo) GetUserByEmail(
ctx context.Context,
email string,
@@ -158,6 +163,7 @@ func (s *UsersRepo) GetUserByEmail(
return user, nil
}
// GetUserByID returns a user by ID.
func (s *UsersRepo) GetUserByID(
ctx context.Context,
id int,
@@ -188,6 +194,7 @@ func (s *UsersRepo) GetUserByID(
return user, nil
}
// GetUsers returns users matching the requested filters.
func (s *UsersRepo) GetUsers(
ctx context.Context,
) ([]*repos.User, error) {
@@ -225,6 +232,7 @@ func (s *UsersRepo) GetUsers(
return users, nil
}
// AddUserRole assigns a role to a user.
func (s *UsersRepo) AddUserRole(
ctx context.Context,
userID int,
@@ -241,6 +249,7 @@ func (s *UsersRepo) AddUserRole(
return err
}
// DeleteUserRole removes a role from a user.
func (s *UsersRepo) DeleteUserRole(
ctx context.Context,
userID int,