fix names

This commit is contained in:
2026-10-01 13:13:03 +07:00
parent 76af14cb96
commit f462bc6a03
24 changed files with 213 additions and 213 deletions
+2 -2
View File
@@ -18,7 +18,7 @@ func (c *JWTClaims) HasRole(role string) bool {
} }
type IProcessorJWT interface { type IProcessorJWT interface {
GenerateAccessToken(userId int, userEmail string, userRoles []string) (string, error) GenerateAccessToken(userID int, userEmail string, userRoles []string) (string, error)
GenerateRefreshToken(userId int) (string, error) GenerateRefreshToken(userID int) (string, error)
GetClaims(token string) (*JWTClaims, error) GetClaims(token string) (*JWTClaims, error)
} }
+4 -4
View File
@@ -18,11 +18,11 @@ func NewProcessor(secret string) IProcessorJWT {
} }
} }
func (p *processor) GenerateAccessToken(userId int, userEmail string, userRoles []string) (string, error) { func (p *processor) GenerateAccessToken(userID int, userEmail string, userRoles []string) (string, error) {
now := time.Now() now := time.Now()
claims := &JWTClaims{ claims := &JWTClaims{
UserID: userId, UserID: userID,
UserEmail: userEmail, UserEmail: userEmail,
Roles: userRoles, Roles: userRoles,
RegisteredClaims: jwt.RegisteredClaims{ RegisteredClaims: jwt.RegisteredClaims{
@@ -36,11 +36,11 @@ func (p *processor) GenerateAccessToken(userId int, userEmail string, userRoles
return token.SignedString(p.secret) return token.SignedString(p.secret)
} }
func (p *processor) GenerateRefreshToken(userId int) (string, error) { func (p *processor) GenerateRefreshToken(userID int) (string, error) {
now := time.Now() now := time.Now()
claims := &JWTClaims{ claims := &JWTClaims{
UserID: userId, UserID: userID,
RegisteredClaims: jwt.RegisteredClaims{ RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now.Add(7 * 24 * time.Hour)), ExpiresAt: jwt.NewNumericDate(now.Add(7 * 24 * time.Hour)),
IssuedAt: jwt.NewNumericDate(now), IssuedAt: jwt.NewNumericDate(now),
+9 -9
View File
@@ -26,7 +26,7 @@ func NewActionsRepo(pool *pgxpool.Pool) *ActionsRepo {
} }
} }
func (r *ActionsRepo) AddAction(ctx context.Context, teamId int, code string, viaMCP bool) (int, error) { func (r *ActionsRepo) AddAction(ctx context.Context, teamID int, code string, viaMCP bool) (int, error) {
id := 0 id := 0
err := r.pool.QueryRow( err := r.pool.QueryRow(
ctx, ctx,
@@ -34,7 +34,7 @@ func (r *ActionsRepo) AddAction(ctx context.Context, teamId int, code string, vi
VALUES ($1, $2, $3) VALUES ($1, $2, $3)
RETURNING id`, RETURNING id`,
code, code,
teamId, teamID,
viaMCP, viaMCP,
).Scan(&id) ).Scan(&id)
@@ -44,7 +44,7 @@ func (r *ActionsRepo) AddAction(ctx context.Context, teamId int, code string, vi
return id, nil return id, nil
} }
func (r *ActionsRepo) GetActionsByTeamID(ctx context.Context, teamId int) ([]Action, error) { func (r *ActionsRepo) GetActionsByTeamID(ctx context.Context, teamID int) ([]Action, error) {
rows, err := r.pool.Query( rows, err := r.pool.Query(
ctx, ctx,
`SELECT `SELECT
@@ -53,7 +53,7 @@ func (r *ActionsRepo) GetActionsByTeamID(ctx context.Context, teamId int) ([]Act
FROM actions FROM actions
WHERE team_id = $1 WHERE team_id = $1
ORDER BY created_at ASC`, ORDER BY created_at ASC`,
teamId, teamID,
) )
if err != nil { if err != nil {
return nil, err return nil, err
@@ -79,7 +79,7 @@ func (r *ActionsRepo) GetActionsByTeamID(ctx context.Context, teamId int) ([]Act
return actions, nil return actions, nil
} }
func (r *ActionsRepo) GetActionsCountByTeamIDs(ctx context.Context, teamIds []int) (map[int]int, error) { func (r *ActionsRepo) GetActionsCountByTeamIDs(ctx context.Context, teamIDs []int) (map[int]int, error) {
rows, err := r.pool.Query( rows, err := r.pool.Query(
ctx, ctx,
`SELECT `SELECT
@@ -88,14 +88,14 @@ func (r *ActionsRepo) GetActionsCountByTeamIDs(ctx context.Context, teamIds []in
FROM actions FROM actions
WHERE team_id = ANY($1) WHERE team_id = ANY($1)
GROUP BY team_id`, GROUP BY team_id`,
teamIds, teamIDs,
) )
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close()
res := make(map[int]int, len(teamIds)) res := make(map[int]int, len(teamIDs))
for rows.Next() { for rows.Next() {
id := 0 id := 0
count := 0 count := 0
@@ -115,7 +115,7 @@ func (r *ActionsRepo) GetActionsCountByTeamIDs(ctx context.Context, teamIds []in
return res, nil return res, nil
} }
func (r *ActionsRepo) DeleteLastActionByTeamId(ctx context.Context, teamId int) error { func (r *ActionsRepo) DeleteLastActionByTeamID(ctx context.Context, teamID int) error {
tag, err := r.pool.Exec( tag, err := r.pool.Exec(
ctx, ctx,
`DELETE FROM actions `DELETE FROM actions
@@ -126,7 +126,7 @@ func (r *ActionsRepo) DeleteLastActionByTeamId(ctx context.Context, teamId int)
ORDER BY created_at DESC ORDER BY created_at DESC
LIMIT 1 LIMIT 1
)`, )`,
teamId, teamID,
) )
if err != nil { if err != nil {
return err return err
+1 -1
View File
@@ -3,7 +3,7 @@ package repos
// TeamAnswer — ответ команды на вопрос дела (вопросы живут в сценарии, // TeamAnswer — ответ команды на вопрос дела (вопросы живут в сценарии,
// ответы — в таблице team_answers). // ответы — в таблице team_answers).
type TeamAnswer struct { type TeamAnswer struct {
TeamId int TeamID int
QuestionCode string QuestionCode string
Text string Text string
// Score — балл, выставленный организатором; nil — ещё не оценено. // Score — балл, выставленный организатором; nil — ещё не оценено.
+1 -1
View File
@@ -3,6 +3,6 @@ package repos
type Application struct { type Application struct {
Name string Name string
Image string Image string
TeamId int TeamID int
FileType string FileType string
} }
+11 -11
View File
@@ -24,7 +24,7 @@ func NewApplicationsRepo(pool *pgxpool.Pool) *ApplicationsRepo {
func (r *ApplicationsRepo) AddApplication( func (r *ApplicationsRepo) AddApplication(
ctx context.Context, ctx context.Context,
teamId int, teamID int,
name string, name string,
image string, image string,
fileType string, fileType string,
@@ -38,7 +38,7 @@ func (r *ApplicationsRepo) AddApplication(
name, name,
image, image,
fileType, fileType,
teamId, teamID,
).Scan(&id) ).Scan(&id)
if err != nil { if err != nil {
@@ -49,7 +49,7 @@ func (r *ApplicationsRepo) AddApplication(
func (r *ApplicationsRepo) GetApplicationsByTeamIDsAndState( func (r *ApplicationsRepo) GetApplicationsByTeamIDsAndState(
ctx context.Context, ctx context.Context,
teamIds []int, teamIDs []int,
state string, state string,
) (map[int][]*repos.Application, error) { ) (map[int][]*repos.Application, error) {
rows, err := r.pool.Query( rows, err := r.pool.Query(
@@ -61,7 +61,7 @@ func (r *ApplicationsRepo) GetApplicationsByTeamIDsAndState(
team_id team_id
FROM applications FROM applications
WHERE team_id = ANY($1) and status = $2`, WHERE team_id = ANY($1) and status = $2`,
teamIds, teamIDs,
state, state,
) )
if err != nil { if err != nil {
@@ -69,19 +69,19 @@ func (r *ApplicationsRepo) GetApplicationsByTeamIDsAndState(
} }
defer rows.Close() defer rows.Close()
res := make(map[int][]*repos.Application, len(teamIds)) res := make(map[int][]*repos.Application, len(teamIDs))
for rows.Next() { for rows.Next() {
application := &repos.Application{} application := &repos.Application{}
err := rows.Scan( err := rows.Scan(
&application.Name, &application.Name,
&application.Image, &application.Image,
&application.FileType, &application.FileType,
&application.TeamId, &application.TeamID,
) )
if err != nil { if err != nil {
return nil, err return nil, err
} }
res[application.TeamId] = append(res[application.TeamId], application) res[application.TeamID] = append(res[application.TeamID], application)
} }
if err := rows.Err(); err != nil { if err := rows.Err(); err != nil {
return nil, err return nil, err
@@ -92,7 +92,7 @@ func (r *ApplicationsRepo) GetApplicationsByTeamIDsAndState(
func (r *ApplicationsRepo) UpdateApplicationStatus( func (r *ApplicationsRepo) UpdateApplicationStatus(
ctx context.Context, ctx context.Context,
teamId int, teamID int,
name string, name string,
status string, status string,
) error { ) error {
@@ -103,7 +103,7 @@ func (r *ApplicationsRepo) UpdateApplicationStatus(
status = $1 status = $1
WHERE team_id = $2 and name = $3`, WHERE team_id = $2 and name = $3`,
status, status,
teamId, teamID,
name, name,
) )
if err != nil { if err != nil {
@@ -115,7 +115,7 @@ func (r *ApplicationsRepo) UpdateApplicationStatus(
return nil return nil
} }
func (r *ApplicationsRepo) DeleteApplicationByTeamIdAndName(ctx context.Context, teamId int, name string) error { func (r *ApplicationsRepo) DeleteApplicationByTeamIDAndName(ctx context.Context, teamID int, name string) error {
tag, err := r.pool.Exec( tag, err := r.pool.Exec(
ctx, ctx,
`DELETE FROM applications `DELETE FROM applications
@@ -126,7 +126,7 @@ func (r *ApplicationsRepo) DeleteApplicationByTeamIdAndName(ctx context.Context,
ORDER BY created_at DESC ORDER BY created_at DESC
LIMIT 1 LIMIT 1
)`, )`,
teamId, teamID,
name, name,
) )
if err != nil { if err != nil {
+1 -1
View File
@@ -12,7 +12,7 @@ type Game struct {
Location *string Location *string
StartAt time.Time StartAt time.Time
Status string Status string
ScenarioId int ScenarioID int
Scenario *Scenario Scenario *Scenario
Teams []*Team Teams []*Team
StartedAt *time.Time StartedAt *time.Time
+5 -5
View File
@@ -30,7 +30,7 @@ func (r *GamesRepo) AddGame(
description string, description string,
location *string, location *string,
startAt time.Time, startAt time.Time,
scenarioId int32, scenarioID int32,
format string, format string,
) (int, error) { ) (int, error) {
id := 0 id := 0
@@ -43,7 +43,7 @@ func (r *GamesRepo) AddGame(
description, description,
location, location,
startAt, startAt,
scenarioId, scenarioID,
format, format,
).Scan(&id) ).Scan(&id)
@@ -83,7 +83,7 @@ func (r *GamesRepo) GetGameByID(
&game.StartAt, &game.StartAt,
&game.Format, &game.Format,
&game.Status, &game.Status,
&game.ScenarioId, &game.ScenarioID,
&game.StartedAt, &game.StartedAt,
&game.EndedAt, &game.EndedAt,
) )
@@ -168,7 +168,7 @@ func (r *GamesRepo) UpdateGame(
description string, description string,
location *string, location *string,
startAt time.Time, startAt time.Time,
scenarioId int32, scenarioID int32,
format string, format string,
) error { ) error {
tag, err := r.pool.Exec( tag, err := r.pool.Exec(
@@ -187,7 +187,7 @@ func (r *GamesRepo) UpdateGame(
description, description,
location, location,
startAt, startAt,
scenarioId, scenarioID,
format, format,
id, id,
) )
+4 -4
View File
@@ -19,7 +19,7 @@ func NewRefreshTokensRepo(pool *pgxpool.Pool) *RefreshTokensRepo {
func (s *RefreshTokensRepo) AddRefreshToken( func (s *RefreshTokensRepo) AddRefreshToken(
ctx context.Context, ctx context.Context,
userId int, userID int,
expiresAt time.Time, expiresAt time.Time,
jti string, jti string,
) error { ) error {
@@ -27,7 +27,7 @@ func (s *RefreshTokensRepo) AddRefreshToken(
ctx, ctx,
`INSERT INTO refresh_tokens (user_id, expires_at, jti) `INSERT INTO refresh_tokens (user_id, expires_at, jti)
VALUES ($1, $2, $3)`, VALUES ($1, $2, $3)`,
userId, userID,
expiresAt, expiresAt,
jti, jti,
) )
@@ -36,7 +36,7 @@ func (s *RefreshTokensRepo) AddRefreshToken(
func (s *RefreshTokensRepo) ExistsRefreshToken( func (s *RefreshTokensRepo) ExistsRefreshToken(
ctx context.Context, ctx context.Context,
userId int, userID int,
jti string, jti string,
now time.Time, now time.Time,
) (bool, error) { ) (bool, error) {
@@ -51,7 +51,7 @@ func (s *RefreshTokensRepo) ExistsRefreshToken(
AND jti = $2 AND jti = $2
AND expires_at > $3 AND expires_at > $3
)`, )`,
userId, userID,
jti, jti,
now, now,
).Scan(&exists) ).Scan(&exists)
+4 -4
View File
@@ -26,7 +26,7 @@ func NewScenariosRepo(pool *pgxpool.Pool) *ScenariosRepo {
func (r *ScenariosRepo) AddScenario( func (r *ScenariosRepo) AddScenario(
ctx context.Context, ctx context.Context,
name string, name string,
authorId int, authorID int,
) (int, error) { ) (int, error) {
id := 0 id := 0
err := r.pool.QueryRow( err := r.pool.QueryRow(
@@ -35,7 +35,7 @@ func (r *ScenariosRepo) AddScenario(
VALUES ($1, $2) VALUES ($1, $2)
RETURNING id`, RETURNING id`,
name, name,
authorId, authorID,
).Scan(&id) ).Scan(&id)
if err != nil { if err != nil {
@@ -46,7 +46,7 @@ func (r *ScenariosRepo) AddScenario(
func (r *ScenariosRepo) GetScenariosByAuthorID( func (r *ScenariosRepo) GetScenariosByAuthorID(
ctx context.Context, ctx context.Context,
authorId int, authorID int,
) ([]*repos.Scenario, error) { ) ([]*repos.Scenario, error) {
rows, err := r.pool.Query( rows, err := r.pool.Query(
ctx, ctx,
@@ -66,7 +66,7 @@ func (r *ScenariosRepo) GetScenariosByAuthorID(
LEFT JOIN users on scenarios.author_id = users.id LEFT JOIN users on scenarios.author_id = users.id
WHERE scenarios.author_id = $1 and is_deleted = FALSE WHERE scenarios.author_id = $1 and is_deleted = FALSE
ORDER BY created_at DESC`, ORDER BY created_at DESC`,
authorId, authorID,
) )
if err != nil { if err != nil {
return nil, err return nil, err
+1 -1
View File
@@ -11,5 +11,5 @@ type Team struct {
Name string Name string
Status string Status string
Password string Password string
GameId int GameID int
} }
+10 -10
View File
@@ -21,7 +21,7 @@ func NewTeamAnswersRepo(pool *pgxpool.Pool) *TeamAnswersRepo {
// отсутствующие — вставляются (UNIQUE (team_id, question_code)). // отсутствующие — вставляются (UNIQUE (team_id, question_code)).
func (r *TeamAnswersRepo) UpsertAnswers( func (r *TeamAnswersRepo) UpsertAnswers(
ctx context.Context, ctx context.Context,
teamId int, teamID int,
answers []repos.TeamAnswer, answers []repos.TeamAnswer,
) error { ) error {
for _, answer := range answers { for _, answer := range answers {
@@ -33,7 +33,7 @@ func (r *TeamAnswersRepo) UpsertAnswers(
DO UPDATE SET DO UPDATE SET
answer = EXCLUDED.answer, answer = EXCLUDED.answer,
updated_at = NOW()`, updated_at = NOW()`,
teamId, teamID,
answer.QuestionCode, answer.QuestionCode,
answer.Text, answer.Text,
) )
@@ -46,7 +46,7 @@ func (r *TeamAnswersRepo) UpsertAnswers(
func (r *TeamAnswersRepo) GetAnswersByTeamID( func (r *TeamAnswersRepo) GetAnswersByTeamID(
ctx context.Context, ctx context.Context,
teamId int, teamID int,
) ([]*repos.TeamAnswer, error) { ) ([]*repos.TeamAnswer, error) {
rows, err := r.pool.Query( rows, err := r.pool.Query(
ctx, ctx,
@@ -58,7 +58,7 @@ func (r *TeamAnswersRepo) GetAnswersByTeamID(
FROM team_answers FROM team_answers
WHERE team_id = $1 WHERE team_id = $1
ORDER BY question_code ASC`, ORDER BY question_code ASC`,
teamId, teamID,
) )
if err != nil { if err != nil {
return nil, err return nil, err
@@ -69,7 +69,7 @@ func (r *TeamAnswersRepo) GetAnswersByTeamID(
for rows.Next() { for rows.Next() {
answer := &repos.TeamAnswer{} answer := &repos.TeamAnswer{}
err := rows.Scan( err := rows.Scan(
&answer.TeamId, &answer.TeamID,
&answer.QuestionCode, &answer.QuestionCode,
&answer.Text, &answer.Text,
&answer.Score, &answer.Score,
@@ -89,7 +89,7 @@ func (r *TeamAnswersRepo) GetAnswersByTeamID(
// GetAnswersByGameID возвращает ответы всех команд игры (вместе с баллами). // GetAnswersByGameID возвращает ответы всех команд игры (вместе с баллами).
func (r *TeamAnswersRepo) GetAnswersByGameID( func (r *TeamAnswersRepo) GetAnswersByGameID(
ctx context.Context, ctx context.Context,
gameId int, gameID int,
) ([]*repos.TeamAnswer, error) { ) ([]*repos.TeamAnswer, error) {
rows, err := r.pool.Query( rows, err := r.pool.Query(
ctx, ctx,
@@ -102,7 +102,7 @@ func (r *TeamAnswersRepo) GetAnswersByGameID(
JOIN teams ON teams.id = team_answers.team_id JOIN teams ON teams.id = team_answers.team_id
WHERE teams.game_id = $1 WHERE teams.game_id = $1
ORDER BY teams.id ASC, team_answers.question_code ASC`, ORDER BY teams.id ASC, team_answers.question_code ASC`,
gameId, gameID,
) )
if err != nil { if err != nil {
return nil, err return nil, err
@@ -113,7 +113,7 @@ func (r *TeamAnswersRepo) GetAnswersByGameID(
for rows.Next() { for rows.Next() {
answer := &repos.TeamAnswer{} answer := &repos.TeamAnswer{}
err := rows.Scan( err := rows.Scan(
&answer.TeamId, &answer.TeamID,
&answer.QuestionCode, &answer.QuestionCode,
&answer.Text, &answer.Text,
&answer.Score, &answer.Score,
@@ -136,7 +136,7 @@ func (r *TeamAnswersRepo) GetAnswersByGameID(
// пустым ответом и выставленным баллом. // пустым ответом и выставленным баллом.
func (r *TeamAnswersRepo) SetAnswerScore( func (r *TeamAnswersRepo) SetAnswerScore(
ctx context.Context, ctx context.Context,
teamId int, teamID int,
questionCode string, questionCode string,
score *int, score *int,
) error { ) error {
@@ -148,7 +148,7 @@ func (r *TeamAnswersRepo) SetAnswerScore(
DO UPDATE SET DO UPDATE SET
score = EXCLUDED.score, score = EXCLUDED.score,
updated_at = NOW()`, updated_at = NOW()`,
teamId, teamID,
questionCode, questionCode,
score, score,
) )
+13 -13
View File
@@ -48,7 +48,7 @@ func (r *TeamsRepo) GetTeamByID(ctx context.Context, id int) (*repos.Team, error
&team.ParticipationStatus, &team.ParticipationSource, &team.ParticipationEmailError, &team.ParticipationEmailSent, &team.ParticipationStatus, &team.ParticipationSource, &team.ParticipationEmailError, &team.ParticipationEmailSent,
&team.Status, &team.Status,
&team.Password, &team.Password,
&team.GameId, &team.GameID,
) )
if err != nil { if err != nil {
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
@@ -62,7 +62,7 @@ func (r *TeamsRepo) GetTeamByID(ctx context.Context, id int) (*repos.Team, error
func (r *TeamsRepo) GetTeamsByGameID( func (r *TeamsRepo) GetTeamsByGameID(
ctx context.Context, ctx context.Context,
gameId int, gameID int,
) ([]*repos.Team, error) { ) ([]*repos.Team, error) {
rows, err := r.pool.Query( rows, err := r.pool.Query(
ctx, ctx,
@@ -77,7 +77,7 @@ func (r *TeamsRepo) GetTeamsByGameID(
FROM teams FROM teams
WHERE game_id = $1 WHERE game_id = $1
ORDER BY created_at DESC`, ORDER BY created_at DESC`,
gameId, gameID,
) )
if err != nil { if err != nil {
return nil, err return nil, err
@@ -110,15 +110,15 @@ func (r *TeamsRepo) GetTeamsByGameID(
func (r *TeamsRepo) AddTeam( func (r *TeamsRepo) AddTeam(
ctx context.Context, ctx context.Context,
creatorId int, creatorID int,
gameId int, gameID int,
name string, name string,
password string, password string,
) (int, error) { ) (int, error) {
return r.AddTeamWithParticipation(ctx, creatorId, gameId, name, password, "", false) return r.AddTeamWithParticipation(ctx, creatorID, gameID, name, password, "", false)
} }
func (r *TeamsRepo) AddTeamWithParticipation(ctx context.Context, creatorId, gameId int, name, password, captainEmail string, autoConfirm bool) (int, error) { func (r *TeamsRepo) AddTeamWithParticipation(ctx context.Context, creatorID, gameID int, name, password, captainEmail string, autoConfirm bool) (int, error) {
id := 0 id := 0
status, source := "pending", "" status, source := "pending", ""
if autoConfirm { if autoConfirm {
@@ -130,8 +130,8 @@ func (r *TeamsRepo) AddTeamWithParticipation(ctx context.Context, creatorId, gam
VALUES ($1, $2, $3, $4, $5, $6, CASE WHEN $5 = 'confirmed' THEN NOW() ELSE NULL END, $7) VALUES ($1, $2, $3, $4, $5, $6, CASE WHEN $5 = 'confirmed' THEN NOW() ELSE NULL END, $7)
RETURNING id`, RETURNING id`,
name, name,
creatorId, creatorID,
gameId, gameID,
password, password,
status, status,
source, source,
@@ -144,7 +144,7 @@ func (r *TeamsRepo) AddTeamWithParticipation(ctx context.Context, creatorId, gam
return id, nil return id, nil
} }
func (r *TeamsRepo) UpdateTeam(ctx context.Context, teamId int, name string) error { func (r *TeamsRepo) UpdateTeam(ctx context.Context, teamID int, name string) error {
tag, err := r.pool.Exec( tag, err := r.pool.Exec(
ctx, ctx,
`UPDATE teams `UPDATE teams
@@ -152,7 +152,7 @@ func (r *TeamsRepo) UpdateTeam(ctx context.Context, teamId int, name string) err
name = $1 name = $1
WHERE id = $2`, WHERE id = $2`,
name, name,
teamId, teamID,
) )
if err != nil { if err != nil {
return err return err
@@ -163,12 +163,12 @@ func (r *TeamsRepo) UpdateTeam(ctx context.Context, teamId int, name string) err
return nil return nil
} }
func (r *TeamsRepo) DeleteTeam(ctx context.Context, teamId int) error { func (r *TeamsRepo) DeleteTeam(ctx context.Context, teamID int) error {
tag, err := r.pool.Exec( tag, err := r.pool.Exec(
ctx, ctx,
`DELETE FROM teams `DELETE FROM teams
WHERE id = $1`, WHERE id = $1`,
teamId, teamID,
) )
if err != nil { if err != nil {
return err return err
+8 -8
View File
@@ -226,7 +226,7 @@ func (s *UsersRepo) GetUsers(
func (s *UsersRepo) AddUserRole( func (s *UsersRepo) AddUserRole(
ctx context.Context, ctx context.Context,
userId int, userID int,
role string, role string,
) error { ) error {
_, err := s.pool.Exec( _, err := s.pool.Exec(
@@ -235,14 +235,14 @@ func (s *UsersRepo) AddUserRole(
SET roles = roles || $1::jsonb SET roles = roles || $1::jsonb
WHERE id = $2 AND NOT roles @> $1::jsonb`, WHERE id = $2 AND NOT roles @> $1::jsonb`,
fmt.Sprintf(`["%s"]`, role), fmt.Sprintf(`["%s"]`, role),
userId, userID,
) )
return err return err
} }
func (s *UsersRepo) DeleteUserRole( func (s *UsersRepo) DeleteUserRole(
ctx context.Context, ctx context.Context,
userId int, userID int,
role string, role string,
) error { ) error {
_, err := s.pool.Exec( _, err := s.pool.Exec(
@@ -251,7 +251,7 @@ func (s *UsersRepo) DeleteUserRole(
SET roles = roles - $1::text SET roles = roles - $1::text
WHERE id = $2`, WHERE id = $2`,
role, role,
userId, userID,
) )
return err return err
} }
@@ -264,7 +264,7 @@ func (s *UsersRepo) DeleteUserRole(
// контент остаётся в обезличенном виде. // контент остаётся в обезличенном виде.
func (s *UsersRepo) DeleteUser( func (s *UsersRepo) DeleteUser(
ctx context.Context, ctx context.Context,
userId int, userID int,
) error { ) error {
tx, err := s.pool.Begin(ctx) tx, err := s.pool.Begin(ctx)
if err != nil { if err != nil {
@@ -276,7 +276,7 @@ func (s *UsersRepo) DeleteUser(
if _, err = tx.Exec( if _, err = tx.Exec(
ctx, ctx,
`DELETE FROM refresh_tokens WHERE user_id = $1`, `DELETE FROM refresh_tokens WHERE user_id = $1`,
userId, userID,
); err != nil { ); err != nil {
return err return err
} }
@@ -293,7 +293,7 @@ func (s *UsersRepo) DeleteUser(
`UPDATE user_agreements `UPDATE user_agreements
SET user_id = NULL, ip = NULL, user_agent = NULL SET user_id = NULL, ip = NULL, user_agent = NULL
WHERE user_id = $1`, WHERE user_id = $1`,
userId, userID,
); err != nil { ); err != nil {
return err return err
} }
@@ -303,7 +303,7 @@ func (s *UsersRepo) DeleteUser(
tag, err := tx.Exec( tag, err := tx.Exec(
ctx, ctx,
`DELETE FROM users WHERE id = $1`, `DELETE FROM users WHERE id = $1`,
userId, userID,
) )
if err != nil { if err != nil {
return err return err
+40 -40
View File
@@ -50,15 +50,15 @@ var (
) )
// getTeamAndGame проверяет команду по паролю и возвращает её вместе с игрой. // getTeamAndGame проверяет команду по паролю и возвращает её вместе с игрой.
func (s *AnswerService) getTeamAndGame(ctx context.Context, teamId int, password string) (*repos.Team, *repos.Game, error) { func (s *AnswerService) getTeamAndGame(ctx context.Context, teamID int, password string) (*repos.Team, *repos.Game, error) {
team, err := s.teamsRepo.GetTeamByID(ctx, teamId) team, err := s.teamsRepo.GetTeamByID(ctx, teamID)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
if team.Password != password || team.ParticipationStatus == "cancelled" { if team.Password != password || team.ParticipationStatus == "cancelled" {
return nil, nil, teams_repo.ErrTeamNotFound return nil, nil, teams_repo.ErrTeamNotFound
} }
game, err := s.gamesRepo.GetGameByID(ctx, team.GameId) game, err := s.gamesRepo.GetGameByID(ctx, team.GameID)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@@ -66,8 +66,8 @@ func (s *AnswerService) getTeamAndGame(ctx context.Context, teamId int, password
} }
// getScenarioQuestionsByCode возвращает вопросы сценария игры с индексацией по коду. // getScenarioQuestionsByCode возвращает вопросы сценария игры с индексацией по коду.
func (s *AnswerService) getScenarioQuestionsByCode(ctx context.Context, scenarioId int) ([]*storytelling.Question, map[string]*storytelling.Question, error) { func (s *AnswerService) getScenarioQuestionsByCode(ctx context.Context, scenarioID int) ([]*storytelling.Question, map[string]*storytelling.Question, error) {
scenario, err := s.scenarioService.GetFullScenarioByID(ctx, scenarioId) scenario, err := s.scenarioService.GetFullScenarioByID(ctx, scenarioID)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@@ -81,19 +81,19 @@ func (s *AnswerService) getScenarioQuestionsByCode(ctx context.Context, scenario
// GetTeamAnswers возвращает ответы команды на вопросы дела (без баллов: // GetTeamAnswers возвращает ответы команды на вопросы дела (без баллов:
// баллы видны только организаторам). Ответы на удалённые из сценария // баллы видны только организаторам). Ответы на удалённые из сценария
// вопросы не возвращаются. // вопросы не возвращаются.
func (s *AnswerService) GetTeamAnswers(ctx context.Context, teamId int, password string) ([]Answer, error) { func (s *AnswerService) GetTeamAnswers(ctx context.Context, teamID int, password string) ([]Answer, error) {
_, game, err := s.getTeamAndGame(ctx, teamId, password) _, game, err := s.getTeamAndGame(ctx, teamID, password)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if game.Format == "offline" { if game.Format == "offline" {
return nil, nil return nil, nil
} }
_, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioId) _, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
teamAnswers, err := s.answersRepo.GetAnswersByTeamID(ctx, teamId) teamAnswers, err := s.answersRepo.GetAnswersByTeamID(ctx, teamID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -114,8 +114,8 @@ func (s *AnswerService) GetTeamAnswers(ctx context.Context, teamId int, password
// Доступно только пока игра идёт (статусы run/pause): после завершения // Доступно только пока игра идёт (статусы run/pause): после завершения
// ответы фиксируются для оценки организатором. Переданные коды должны // ответы фиксируются для оценки организатором. Переданные коды должны
// существовать в сценарии игры; пустая строка очищает ответ. // существовать в сценарии игры; пустая строка очищает ответ.
func (s *AnswerService) SubmitTeamAnswers(ctx context.Context, teamId int, password string, answers []Answer) error { func (s *AnswerService) SubmitTeamAnswers(ctx context.Context, teamID int, password string, answers []Answer) error {
_, game, err := s.getTeamAndGame(ctx, teamId, password) _, game, err := s.getTeamAndGame(ctx, teamID, password)
if err != nil { if err != nil {
return err return err
} }
@@ -131,7 +131,7 @@ func (s *AnswerService) SubmitTeamAnswers(ctx context.Context, teamId int, passw
} }
return ErrGameNotStarted return ErrGameNotStarted
} }
_, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioId) _, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioID)
if err != nil { if err != nil {
return err return err
} }
@@ -145,7 +145,7 @@ func (s *AnswerService) SubmitTeamAnswers(ctx context.Context, teamId int, passw
Text: answer.Text, Text: answer.Text,
}) })
} }
return s.answersRepo.UpsertAnswers(ctx, teamId, rows) return s.answersRepo.UpsertAnswers(ctx, teamID, rows)
} }
// GetGameAnswers возвращает полную картину для оценки организатором: // GetGameAnswers возвращает полную картину для оценки организатором:
@@ -154,28 +154,28 @@ func (s *AnswerService) SubmitTeamAnswers(ctx context.Context, teamId int, passw
// ответов команды с пустым текстом и без балла (организатор видит его и // ответов команды с пустым текстом и без балла (организатор видит его и
// может выставить балл, в т.ч. штрафной). Ответы на удалённые из сценария // может выставить балл, в т.ч. штрафной). Ответы на удалённые из сценария
// вопросы не возвращаются (как в GetTeamAnswers). // вопросы не возвращаются (как в GetTeamAnswers).
func (s *AnswerService) GetGameAnswers(ctx context.Context, gameId int) (*GameAnswers, error) { func (s *AnswerService) GetGameAnswers(ctx context.Context, gameID int) (*GameAnswers, error) {
game, err := s.gamesRepo.GetGameByID(ctx, gameId) game, err := s.gamesRepo.GetGameByID(ctx, gameID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
questions, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioId) questions, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
teams, err := s.teamsRepo.GetActiveTeamsByGameID(ctx, gameId) teams, err := s.teamsRepo.GetActiveTeamsByGameID(ctx, gameID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
teamIds := make([]int, 0, len(teams)) teamIDs := make([]int, 0, len(teams))
for _, team := range teams { for _, team := range teams {
teamIds = append(teamIds, team.ID) teamIDs = append(teamIDs, team.ID)
} }
actionsCountByTeamIDs, err := s.actionsRepo.GetActionsCountByTeamIDs(ctx, teamIds) actionsCountByTeamIDs, err := s.actionsRepo.GetActionsCountByTeamIDs(ctx, teamIDs)
if err != nil { if err != nil {
return nil, err return nil, err
} }
rows, err := s.answersRepo.GetAnswersByGameID(ctx, gameId) rows, err := s.answersRepo.GetAnswersByGameID(ctx, gameID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -185,10 +185,10 @@ func (s *AnswerService) GetGameAnswers(ctx context.Context, gameId int) (*GameAn
continue continue
} }
score := row.Score score := row.Score
if answerByTeamAndCode[row.TeamId] == nil { if answerByTeamAndCode[row.TeamID] == nil {
answerByTeamAndCode[row.TeamId] = make(map[string]AnswerScore, len(questions)) answerByTeamAndCode[row.TeamID] = make(map[string]AnswerScore, len(questions))
} }
answerByTeamAndCode[row.TeamId][row.QuestionCode] = AnswerScore{ answerByTeamAndCode[row.TeamID][row.QuestionCode] = AnswerScore{
QuestionCode: row.QuestionCode, QuestionCode: row.QuestionCode,
Text: row.Text, Text: row.Text,
Score: score, Score: score,
@@ -224,23 +224,23 @@ func (s *AnswerService) GetGameAnswers(ctx context.Context, gameId int) (*GameAn
// score == nil сбрасывает балл. Балл может быть любым целым числом // score == nil сбрасывает балл. Балл может быть любым целым числом
// (в т.ч. отрицательным — штрафные баллы). Вопрос должен существовать // (в т.ч. отрицательным — штрафные баллы). Вопрос должен существовать
// в сценарии игры. // в сценарии игры.
func (s *AnswerService) SetTeamAnswerScore(ctx context.Context, teamId int, questionCode string, score *int) error { func (s *AnswerService) SetTeamAnswerScore(ctx context.Context, teamID int, questionCode string, score *int) error {
team, err := s.teamsRepo.GetTeamByID(ctx, teamId) team, err := s.teamsRepo.GetTeamByID(ctx, teamID)
if err != nil { if err != nil {
return err return err
} }
game, err := s.gamesRepo.GetGameByID(ctx, team.GameId) game, err := s.gamesRepo.GetGameByID(ctx, team.GameID)
if err != nil { if err != nil {
return err return err
} }
_, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioId) _, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioID)
if err != nil { if err != nil {
return err return err
} }
if _, ok := byCode[questionCode]; !ok { if _, ok := byCode[questionCode]; !ok {
return ErrQuestionNotFound return ErrQuestionNotFound
} }
return s.answersRepo.SetAnswerScore(ctx, teamId, questionCode, score) return s.answersRepo.SetAnswerScore(ctx, teamID, questionCode, score)
} }
// GetGameResults возвращает итоговую таблицу игры: вопросы сценария (шапка // GetGameResults возвращает итоговую таблицу игры: вопросы сценария (шапка
@@ -248,31 +248,31 @@ func (s *AnswerService) SetTeamAnswerScore(ctx context.Context, teamId int, ques
// баллов, с баллами по каждому вопросу (в порядке сценария), числом ходов и // баллов, с баллами по каждому вопросу (в порядке сценария), числом ходов и
// местом. Доступно только после завершения игры (статус finish); неоценённые // местом. Доступно только после завершения игры (статус finish); неоценённые
// вопросы в сумме считаются как 0. // вопросы в сумме считаются как 0.
func (s *AnswerService) GetGameResults(ctx context.Context, gameId int) (*GameResults, error) { func (s *AnswerService) GetGameResults(ctx context.Context, gameID int) (*GameResults, error) {
game, err := s.gamesRepo.GetGameByID(ctx, gameId) game, err := s.gamesRepo.GetGameByID(ctx, gameID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if game.Status != "finish" { if game.Status != "finish" {
return nil, ErrGameNotFinished return nil, ErrGameNotFinished
} }
questions, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioId) questions, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
teams, err := s.teamsRepo.GetActiveTeamsByGameID(ctx, gameId) teams, err := s.teamsRepo.GetActiveTeamsByGameID(ctx, gameID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
teamIds := make([]int, 0, len(teams)) teamIDs := make([]int, 0, len(teams))
for _, team := range teams { for _, team := range teams {
teamIds = append(teamIds, team.ID) teamIDs = append(teamIDs, team.ID)
} }
actionsCountByTeamIDs, err := s.actionsRepo.GetActionsCountByTeamIDs(ctx, teamIds) actionsCountByTeamIDs, err := s.actionsRepo.GetActionsCountByTeamIDs(ctx, teamIDs)
if err != nil { if err != nil {
return nil, err return nil, err
} }
rows, err := s.answersRepo.GetAnswersByGameID(ctx, gameId) rows, err := s.answersRepo.GetAnswersByGameID(ctx, gameID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -281,10 +281,10 @@ func (s *AnswerService) GetGameResults(ctx context.Context, gameId int) (*GameRe
if _, ok := byCode[row.QuestionCode]; !ok { if _, ok := byCode[row.QuestionCode]; !ok {
continue continue
} }
if answerByTeamAndCode[row.TeamId] == nil { if answerByTeamAndCode[row.TeamID] == nil {
answerByTeamAndCode[row.TeamId] = make(map[string]AnswerScore, len(questions)) answerByTeamAndCode[row.TeamID] = make(map[string]AnswerScore, len(questions))
} }
answerByTeamAndCode[row.TeamId][row.QuestionCode] = AnswerScore{ answerByTeamAndCode[row.TeamID][row.QuestionCode] = AnswerScore{
QuestionCode: row.QuestionCode, QuestionCode: row.QuestionCode,
Text: row.Text, Text: row.Text,
Score: row.Score, Score: row.Score,
@@ -38,7 +38,7 @@ func (s *Service) Create(ctx context.Context, gameID, teamID int, password strin
return nil, ErrInvalidReview return nil, ErrInvalidReview
} }
team, err := s.teams.GetTeamByID(ctx, teamID) team, err := s.teams.GetTeamByID(ctx, teamID)
if err != nil || team.GameId != gameID || team.Password != password || team.ParticipationStatus == "cancelled" { if err != nil || team.GameID != gameID || team.Password != password || team.ParticipationStatus == "cancelled" {
return nil, teams_repo.ErrTeamNotFound return nil, teams_repo.ErrTeamNotFound
} }
game, err := s.games.GetGameByID(ctx, gameID) game, err := s.games.GetGameByID(ctx, gameID)
+10 -10
View File
@@ -49,7 +49,7 @@ func (s *GameService) AddGame(
description string, description string,
location *string, location *string,
startAt time.Time, startAt time.Time,
scenarioId int32, scenarioID int32,
format string, format string,
) (int, error) { ) (int, error) {
if format == "" { if format == "" {
@@ -58,7 +58,7 @@ func (s *GameService) AddGame(
if format != "online" && format != "offline" { if format != "online" && format != "offline" {
return 0, errors.New("Формат игры должен быть online или offline") return 0, errors.New("Формат игры должен быть online или offline")
} }
id, err := s.gamesRepo.AddGame(ctx, name, description, location, startAt, scenarioId, format) id, err := s.gamesRepo.AddGame(ctx, name, description, location, startAt, scenarioID, format)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@@ -80,7 +80,7 @@ func (s *GameService) GetGameMedia(ctx context.Context, id int) (*game_model.Gam
return nil, err return nil, err
} }
gameResult := game_model.MapGame(game, s.domain) gameResult := game_model.MapGame(game, s.domain)
gameResult.Scenario, err = s.scenarioService.GetFullScenarioByID(ctx, game.ScenarioId) gameResult.Scenario, err = s.scenarioService.GetFullScenarioByID(ctx, game.ScenarioID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -95,7 +95,7 @@ func (s *GameService) GetFullGame(
if err != nil { if err != nil {
return nil, err return nil, err
} }
scenario, err := s.scenariosRepo.GetScenarioByID(ctx, game.ScenarioId) scenario, err := s.scenariosRepo.GetScenarioByID(ctx, game.ScenarioID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -108,17 +108,17 @@ func (s *GameService) GetFullGame(
res := game_model.MapGame(game, s.domain) res := game_model.MapGame(game, s.domain)
teamIds := make([]int, 0, len(game.Teams)) teamIDs := make([]int, 0, len(game.Teams))
for _, team := range game.Teams { for _, team := range game.Teams {
teamIds = append(teamIds, team.ID) teamIDs = append(teamIDs, team.ID)
} }
actionsCountByTeamIDs, err := s.actionsRepo.GetActionsCountByTeamIDs(ctx, teamIds) actionsCountByTeamIDs, err := s.actionsRepo.GetActionsCountByTeamIDs(ctx, teamIDs)
if err != nil { if err != nil {
return nil, err return nil, err
} }
needApplicationsByTeamIDs, err := s.applicationsRepo.GetApplicationsByTeamIDsAndState(ctx, teamIds, "need") needApplicationsByTeamIDs, err := s.applicationsRepo.GetApplicationsByTeamIDsAndState(ctx, teamIDs, "need")
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -155,7 +155,7 @@ func (s *GameService) UpdateGame(
description string, description string,
location *string, location *string,
startAt time.Time, startAt time.Time,
scenarioId int32, scenarioID int32,
format string, format string,
) error { ) error {
if format == "" { if format == "" {
@@ -168,7 +168,7 @@ func (s *GameService) UpdateGame(
if format != "online" && format != "offline" { if format != "online" && format != "offline" {
return errors.New("Формат игры должен быть online или offline") return errors.New("Формат игры должен быть online или offline")
} }
return s.gamesRepo.UpdateGame(ctx, id, name, description, location, startAt, scenarioId, format) return s.gamesRepo.UpdateGame(ctx, id, name, description, location, startAt, scenarioID, format)
} }
func (s *GameService) StartGame(ctx context.Context, id int) error { func (s *GameService) StartGame(ctx context.Context, id int) error {
+22 -22
View File
@@ -45,12 +45,12 @@ func NewGameplayService(
} }
} }
func (s *GameplayService) GiveTeamApplications(ctx context.Context, teamId int, name string) error { func (s *GameplayService) GiveTeamApplications(ctx context.Context, teamID int, name string) error {
return s.applicationsRepo.UpdateApplicationStatus(ctx, teamId, name, "done") return s.applicationsRepo.UpdateApplicationStatus(ctx, teamID, name, "done")
} }
func (s *GameplayService) GetTeamActions(ctx context.Context, teamId int, password string) (*storytelling.Story, *game_model.Game, []actions_repo.Action, error) { func (s *GameplayService) GetTeamActions(ctx context.Context, teamID int, password string) (*storytelling.Story, *game_model.Game, []actions_repo.Action, error) {
team, err := s.teamsRepo.GetTeamByID(ctx, teamId) team, err := s.teamsRepo.GetTeamByID(ctx, teamID)
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, nil, err
} }
@@ -59,7 +59,7 @@ func (s *GameplayService) GetTeamActions(ctx context.Context, teamId int, passwo
return nil, nil, nil, teams_repo.ErrTeamNotFound return nil, nil, nil, teams_repo.ErrTeamNotFound
} }
game, err := s.gamesRepo.GetGameByID(ctx, team.GameId) game, err := s.gamesRepo.GetGameByID(ctx, team.GameID)
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, nil, err
} }
@@ -67,12 +67,12 @@ func (s *GameplayService) GetTeamActions(ctx context.Context, teamId int, passwo
return &storytelling.Story{}, game_model.MapGame(game, s.domain), nil, nil return &storytelling.Story{}, game_model.MapGame(game, s.domain), nil, nil
} }
actions, err := s.actionsRepo.GetActionsByTeamID(ctx, teamId) actions, err := s.actionsRepo.GetActionsByTeamID(ctx, teamID)
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, nil, err
} }
scenario, err := s.scenarioService.GetFullScenarioByID(ctx, game.ScenarioId) scenario, err := s.scenarioService.GetFullScenarioByID(ctx, game.ScenarioID)
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, nil, err
} }
@@ -86,8 +86,8 @@ func (s *GameplayService) GetTeamActions(ctx context.Context, teamId int, passwo
return story, game_model.MapGame(game, s.domain), actions, nil return story, game_model.MapGame(game, s.domain), actions, nil
} }
func (s *GameplayService) AddTeamAction(ctx context.Context, teamId int, password string, actionCode string, viaMCP bool) error { func (s *GameplayService) AddTeamAction(ctx context.Context, teamID int, password string, actionCode string, viaMCP bool) error {
team, err := s.teamsRepo.GetTeamByID(ctx, teamId) team, err := s.teamsRepo.GetTeamByID(ctx, teamID)
if err != nil { if err != nil {
return err return err
} }
@@ -96,27 +96,27 @@ func (s *GameplayService) AddTeamAction(ctx context.Context, teamId int, passwor
return teams_repo.ErrTeamNotFound return teams_repo.ErrTeamNotFound
} }
_, err = s.actionsRepo.AddAction(ctx, teamId, actionCode, viaMCP) _, err = s.actionsRepo.AddAction(ctx, teamID, actionCode, viaMCP)
if err != nil { if err != nil {
return err return err
} }
if team.ParticipationStatus == "pending" { if team.ParticipationStatus == "pending" {
if err := s.teamsRepo.ConfirmParticipationByFirstAction(ctx, teamId); err != nil { if err := s.teamsRepo.ConfirmParticipationByFirstAction(ctx, teamID); err != nil {
return err return err
} }
} }
game, err := s.gamesRepo.GetGameByID(ctx, team.GameId) game, err := s.gamesRepo.GetGameByID(ctx, team.GameID)
if err != nil { if err != nil {
return err return err
} }
actionDetails, err := s.actionsRepo.GetActionsByTeamID(ctx, teamId) actionDetails, err := s.actionsRepo.GetActionsByTeamID(ctx, teamID)
if err != nil { if err != nil {
return err return err
} }
scenario, err := s.scenarioService.GetFullScenarioByID(ctx, game.ScenarioId) scenario, err := s.scenarioService.GetFullScenarioByID(ctx, game.ScenarioID)
if err != nil { if err != nil {
return err return err
} }
@@ -132,7 +132,7 @@ func (s *GameplayService) AddTeamAction(ctx context.Context, teamId int, passwor
for _, application := range lastPlace.Applications { for _, application := range lastPlace.Applications {
app := newApplication(application, s.domain) app := newApplication(application, s.domain)
app.Name = s.cleaner.ClearText(app.Name) app.Name = s.cleaner.ClearText(app.Name)
if _, err := s.applicationsRepo.AddApplication(ctx, teamId, app.Name, app.Image, app.FileType); err != nil { if _, err := s.applicationsRepo.AddApplication(ctx, teamID, app.Name, app.Image, app.FileType); err != nil {
return err return err
} }
} }
@@ -140,23 +140,23 @@ func (s *GameplayService) AddTeamAction(ctx context.Context, teamId int, passwor
return nil return nil
} }
func (s *GameplayService) DeleteLastTeamAction(ctx context.Context, teamId int) error { func (s *GameplayService) DeleteLastTeamAction(ctx context.Context, teamID int) error {
team, err := s.teamsRepo.GetTeamByID(ctx, teamId) team, err := s.teamsRepo.GetTeamByID(ctx, teamID)
if err != nil { if err != nil {
return err return err
} }
game, err := s.gamesRepo.GetGameByID(ctx, team.GameId) game, err := s.gamesRepo.GetGameByID(ctx, team.GameID)
if err != nil { if err != nil {
return err return err
} }
actionDetails, err := s.actionsRepo.GetActionsByTeamID(ctx, teamId) actionDetails, err := s.actionsRepo.GetActionsByTeamID(ctx, teamID)
if err != nil { if err != nil {
return err return err
} }
scenario, err := s.scenarioService.GetFullScenarioByID(ctx, game.ScenarioId) scenario, err := s.scenarioService.GetFullScenarioByID(ctx, game.ScenarioID)
if err != nil { if err != nil {
return err return err
} }
@@ -170,10 +170,10 @@ func (s *GameplayService) DeleteLastTeamAction(ctx context.Context, teamId int)
lastPlace := teamStory.Places[len(teamStory.Places)-1] lastPlace := teamStory.Places[len(teamStory.Places)-1]
for _, application := range lastPlace.Applications { for _, application := range lastPlace.Applications {
if err := s.applicationsRepo.DeleteApplicationByTeamIdAndName(ctx, teamId, application.Name); err != nil { if err := s.applicationsRepo.DeleteApplicationByTeamIDAndName(ctx, teamID, application.Name); err != nil {
return err return err
} }
} }
return s.actionsRepo.DeleteLastActionByTeamId(ctx, teamId) return s.actionsRepo.DeleteLastActionByTeamID(ctx, teamID)
} }
+3 -3
View File
@@ -31,13 +31,13 @@ const defaultCallTimeout = 10 * time.Second
// *gameplay_service.GameplayService; интерфейс позволяет тестировать сервис // *gameplay_service.GameplayService; интерфейс позволяет тестировать сервис
// без БД. // без БД.
type GamePlayer interface { type GamePlayer interface {
GetTeamActions(ctx context.Context, teamId int, password string) (*storytelling.Story, *game_model.Game, []actions_repo.Action, error) GetTeamActions(ctx context.Context, teamID int, password string) (*storytelling.Story, *game_model.Game, []actions_repo.Action, error)
AddTeamAction(ctx context.Context, teamId int, password, actionCode string, viaMCP bool) error AddTeamAction(ctx context.Context, teamID int, password, actionCode string, viaMCP bool) error
} }
// AnswerSubmitter сохраняет ответы команды независимо от прохождения истории. // AnswerSubmitter сохраняет ответы команды независимо от прохождения истории.
type AnswerSubmitter interface { type AnswerSubmitter interface {
SubmitTeamAnswers(ctx context.Context, teamId int, password string, answers []answer_service.Answer) error SubmitTeamAnswers(ctx context.Context, teamID int, password string, answers []answer_service.Answer) error
} }
// MCPService собирает MCP-сервер с игровыми инструментами. Сервис не // MCPService собирает MCP-сервер с игровыми инструментами. Сервис не
+36 -36
View File
@@ -17,8 +17,8 @@ import (
// scenariosRepository — граница доступа к данным сценариев, реализуемая // scenariosRepository — граница доступа к данным сценариев, реализуемая
// *scenarios_repo.ScenariosRepo (интерфейс — для тестов без БД). // *scenarios_repo.ScenariosRepo (интерфейс — для тестов без БД).
type scenariosRepository interface { type scenariosRepository interface {
AddScenario(ctx context.Context, name string, authorId int) (int, error) AddScenario(ctx context.Context, name string, authorID int) (int, error)
GetScenariosByAuthorID(ctx context.Context, authorId int) ([]*repos.Scenario, error) GetScenariosByAuthorID(ctx context.Context, authorID int) ([]*repos.Scenario, error)
GetScenariosByStatus(ctx context.Context, status string) ([]*repos.Scenario, error) GetScenariosByStatus(ctx context.Context, status string) ([]*repos.Scenario, error)
GetScenarioByID(ctx context.Context, id int) (*repos.Scenario, error) GetScenarioByID(ctx context.Context, id int) (*repos.Scenario, error)
UpdateScenarioByID(ctx context.Context, id int, name string, description string, image string) error UpdateScenarioByID(ctx context.Context, id int, name string, description string, image string) error
@@ -55,9 +55,9 @@ func NewScenarioService(
func (s *ScenarioService) AddScenario( func (s *ScenarioService) AddScenario(
ctx context.Context, ctx context.Context,
name string, name string,
authorId int, authorID int,
) (int, error) { ) (int, error) {
id, err := s.scenariosRepo.AddScenario(ctx, name, authorId) id, err := s.scenariosRepo.AddScenario(ctx, name, authorID)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@@ -66,9 +66,9 @@ func (s *ScenarioService) AddScenario(
func (s *ScenarioService) GetScenariosByAuthorID( func (s *ScenarioService) GetScenariosByAuthorID(
ctx context.Context, ctx context.Context,
authorId int, authorID int,
) ([]*Scenario, error) { ) ([]*Scenario, error) {
scenarios, err := s.scenariosRepo.GetScenariosByAuthorID(ctx, authorId) scenarios, err := s.scenariosRepo.GetScenariosByAuthorID(ctx, authorID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -113,10 +113,10 @@ func (s *ScenarioService) UpdateScenarioByID(
name string, name string,
description string, description string,
image string, image string,
actorId int, actorID int,
isAdmin bool, isAdmin bool,
) error { ) error {
if _, err := s.getScenarioForChange(ctx, id, actorId, isAdmin); err != nil { if _, err := s.getScenarioForChange(ctx, id, actorID, isAdmin); err != nil {
return err return err
} }
return s.scenariosRepo.UpdateScenarioByID(ctx, id, name, description, image) return s.scenariosRepo.UpdateScenarioByID(ctx, id, name, description, image)
@@ -137,7 +137,7 @@ var ErrScenarioNotOwner = errors.New("Сценарий принадлежит д
func (s *ScenarioService) getScenarioForChange( func (s *ScenarioService) getScenarioForChange(
ctx context.Context, ctx context.Context,
id int, id int,
actorId int, actorID int,
isAdmin bool, isAdmin bool,
) (*repos.Scenario, error) { ) (*repos.Scenario, error) {
scenario, err := s.scenariosRepo.GetScenarioByID(ctx, id) scenario, err := s.scenariosRepo.GetScenarioByID(ctx, id)
@@ -150,7 +150,7 @@ func (s *ScenarioService) getScenarioForChange(
if isAdmin { if isAdmin {
return scenario, nil return scenario, nil
} }
if scenario.Author == nil || scenario.Author.ID != actorId { if scenario.Author == nil || scenario.Author.ID != actorID {
return nil, ErrScenarioNotOwner return nil, ErrScenarioNotOwner
} }
return scenario, nil return scenario, nil
@@ -160,10 +160,10 @@ func (s *ScenarioService) UpdateScenarioStatusByID(
ctx context.Context, ctx context.Context,
id int, id int,
status string, status string,
actorId int, actorID int,
isAdmin bool, isAdmin bool,
) error { ) error {
scenario, err := s.getScenarioForChange(ctx, id, actorId, isAdmin) scenario, err := s.getScenarioForChange(ctx, id, actorID, isAdmin)
if err != nil { if err != nil {
return err return err
} }
@@ -190,10 +190,10 @@ func (s *ScenarioService) UpdateScenarioStatusByID(
func (s *ScenarioService) DeleteScenarioByID( func (s *ScenarioService) DeleteScenarioByID(
ctx context.Context, ctx context.Context,
id int, id int,
actorId int, actorID int,
isAdmin bool, isAdmin bool,
) error { ) error {
if _, err := s.getScenarioForChange(ctx, id, actorId, isAdmin); err != nil { if _, err := s.getScenarioForChange(ctx, id, actorID, isAdmin); err != nil {
return err return err
} }
// Guard в SQL защищает от гонки «чтение статуса → запись»: не-админ не // Guard в SQL защищает от гонки «чтение статуса → запись»: не-админ не
@@ -212,10 +212,10 @@ func (s *ScenarioService) AddScenarioPlace(
ctx context.Context, ctx context.Context,
id int, id int,
place *storytelling.Place, place *storytelling.Place,
actorId int, actorID int,
isAdmin bool, isAdmin bool,
) error { ) error {
if _, err := s.getScenarioForChange(ctx, id, actorId, isAdmin); err != nil { if _, err := s.getScenarioForChange(ctx, id, actorID, isAdmin); err != nil {
return err return err
} }
story, err := s.getStory(ctx, id) story, err := s.getStory(ctx, id)
@@ -234,10 +234,10 @@ func (s *ScenarioService) UpdateScenarioPlace(
id int, id int,
code string, code string,
place *storytelling.Place, place *storytelling.Place,
actorId int, actorID int,
isAdmin bool, isAdmin bool,
) error { ) error {
if _, err := s.getScenarioForChange(ctx, id, actorId, isAdmin); err != nil { if _, err := s.getScenarioForChange(ctx, id, actorID, isAdmin); err != nil {
return err return err
} }
story, err := s.getStory(ctx, id) story, err := s.getStory(ctx, id)
@@ -257,10 +257,10 @@ func (s *ScenarioService) DeleteScenarioPlace(
ctx context.Context, ctx context.Context,
id int, id int,
code string, code string,
actorId int, actorID int,
isAdmin bool, isAdmin bool,
) error { ) error {
if _, err := s.getScenarioForChange(ctx, id, actorId, isAdmin); err != nil { if _, err := s.getScenarioForChange(ctx, id, actorID, isAdmin); err != nil {
return err return err
} }
story, err := s.getStory(ctx, id) story, err := s.getStory(ctx, id)
@@ -277,8 +277,8 @@ func (s *ScenarioService) DeleteScenarioPlace(
} }
// UpdateScenarioBackground устанавливает фон; пустое значение снимает его с дела. // UpdateScenarioBackground устанавливает фон; пустое значение снимает его с дела.
func (s *ScenarioService) UpdateScenarioBackground(ctx context.Context, id int, background string, actorId int, isAdmin bool) error { func (s *ScenarioService) UpdateScenarioBackground(ctx context.Context, id int, background string, actorID int, isAdmin bool) error {
if _, err := s.getScenarioForChange(ctx, id, actorId, isAdmin); err != nil { if _, err := s.getScenarioForChange(ctx, id, actorID, isAdmin); err != nil {
return err return err
} }
if background != "" && file_storage.FileType(background) != "image" { if background != "" && file_storage.FileType(background) != "image" {
@@ -297,10 +297,10 @@ func (s *ScenarioService) UpdateScenarioIntro(
ctx context.Context, ctx context.Context,
id int, id int,
introduction *storytelling.Introduction, introduction *storytelling.Introduction,
actorId int, actorID int,
isAdmin bool, isAdmin bool,
) error { ) error {
if _, err := s.getScenarioForChange(ctx, id, actorId, isAdmin); err != nil { if _, err := s.getScenarioForChange(ctx, id, actorID, isAdmin); err != nil {
return err return err
} }
story, err := s.getStory(ctx, id) story, err := s.getStory(ctx, id)
@@ -311,8 +311,8 @@ func (s *ScenarioService) UpdateScenarioIntro(
return s.updateStory(ctx, id, story) return s.updateStory(ctx, id, story)
} }
func (s *ScenarioService) UpdateScenarioConclusion(ctx context.Context, id int, conclusion *storytelling.Conclusion, actorId int, isAdmin bool) error { func (s *ScenarioService) UpdateScenarioConclusion(ctx context.Context, id int, conclusion *storytelling.Conclusion, actorID int, isAdmin bool) error {
if _, err := s.getScenarioForChange(ctx, id, actorId, isAdmin); err != nil { if _, err := s.getScenarioForChange(ctx, id, actorID, isAdmin); err != nil {
return err return err
} }
story, err := s.getStory(ctx, id) story, err := s.getStory(ctx, id)
@@ -328,10 +328,10 @@ func (s *ScenarioService) AddScenarioQuestion(
ctx context.Context, ctx context.Context,
id int, id int,
question *storytelling.Question, question *storytelling.Question,
actorId int, actorID int,
isAdmin bool, isAdmin bool,
) error { ) error {
if _, err := s.getScenarioForChange(ctx, id, actorId, isAdmin); err != nil { if _, err := s.getScenarioForChange(ctx, id, actorID, isAdmin); err != nil {
return err return err
} }
story, err := s.getStory(ctx, id) story, err := s.getStory(ctx, id)
@@ -349,10 +349,10 @@ func (s *ScenarioService) UpdateScenarioQuestion(
id int, id int,
code string, code string,
question *storytelling.Question, question *storytelling.Question,
actorId int, actorID int,
isAdmin bool, isAdmin bool,
) error { ) error {
if _, err := s.getScenarioForChange(ctx, id, actorId, isAdmin); err != nil { if _, err := s.getScenarioForChange(ctx, id, actorID, isAdmin); err != nil {
return err return err
} }
story, err := s.getStory(ctx, id) story, err := s.getStory(ctx, id)
@@ -373,10 +373,10 @@ func (s *ScenarioService) DeleteScenarioQuestion(
ctx context.Context, ctx context.Context,
id int, id int,
code string, code string,
actorId int, actorID int,
isAdmin bool, isAdmin bool,
) error { ) error {
if _, err := s.getScenarioForChange(ctx, id, actorId, isAdmin); err != nil { if _, err := s.getScenarioForChange(ctx, id, actorID, isAdmin); err != nil {
return err return err
} }
story, err := s.getStory(ctx, id) story, err := s.getStory(ctx, id)
@@ -404,10 +404,10 @@ func (s *ScenarioService) getStory(ctx context.Context, id int) (*storytelling.S
func (s *ScenarioService) DownloadArchive( func (s *ScenarioService) DownloadArchive(
ctx context.Context, ctx context.Context,
id int, id int,
actorId int, actorID int,
isAdmin bool, isAdmin bool,
) ([]byte, string, error) { ) ([]byte, string, error) {
scenario, err := s.getScenarioForChange(ctx, id, actorId, isAdmin) scenario, err := s.getScenarioForChange(ctx, id, actorID, isAdmin)
if err != nil { if err != nil {
return nil, "", err return nil, "", err
} }
@@ -435,7 +435,7 @@ func (s *ScenarioService) DownloadArchive(
func (s *ScenarioService) UploadArchive( func (s *ScenarioService) UploadArchive(
ctx context.Context, ctx context.Context,
data []byte, data []byte,
authorId int, authorID int,
) (int, error) { ) (int, error) {
bundle, err := s.scenarioArchive.Unpack(data) bundle, err := s.scenarioArchive.Unpack(data)
if err != nil { if err != nil {
@@ -522,7 +522,7 @@ func (s *ScenarioService) UploadArchive(
return 0, err return 0, err
} }
id, err := s.scenariosRepo.AddScenario(ctx, scenario.Name, authorId) id, err := s.scenariosRepo.AddScenario(ctx, scenario.Name, authorID)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@@ -165,7 +165,7 @@ func newFakeScenariosRepo() *fakeScenariosRepo {
} }
} }
func (r *fakeScenariosRepo) AddScenario(_ context.Context, name string, authorId int) (int, error) { func (r *fakeScenariosRepo) AddScenario(_ context.Context, name string, authorID int) (int, error) {
r.mu.Lock() r.mu.Lock()
defer r.mu.Unlock() defer r.mu.Unlock()
if r.addErr != nil { if r.addErr != nil {
@@ -177,18 +177,18 @@ func (r *fakeScenariosRepo) AddScenario(_ context.Context, name string, authorId
ID: r.nextID, ID: r.nextID,
Name: name, Name: name,
Description: &description, Description: &description,
Author: &repos.User{ID: authorId}, Author: &repos.User{ID: authorID},
Status: "draft", Status: "draft",
} }
return r.nextID, nil return r.nextID, nil
} }
func (r *fakeScenariosRepo) GetScenariosByAuthorID(_ context.Context, authorId int) ([]*repos.Scenario, error) { func (r *fakeScenariosRepo) GetScenariosByAuthorID(_ context.Context, authorID int) ([]*repos.Scenario, error) {
r.mu.Lock() r.mu.Lock()
defer r.mu.Unlock() defer r.mu.Unlock()
var res []*repos.Scenario var res []*repos.Scenario
for _, s := range r.byID { for _, s := range r.byID {
if s.Author != nil && s.Author.ID == authorId { if s.Author != nil && s.Author.ID == authorID {
res = append(res, s) res = append(res, s)
} }
} }
+8 -8
View File
@@ -43,8 +43,8 @@ func NewTeamService(
func (s *TeamService) AddTeam( func (s *TeamService) AddTeam(
ctx context.Context, ctx context.Context,
creatorId int, creatorID int,
gameId int, gameID int,
name string, name string,
captainEmail string, captainEmail string,
) (*game_model.Team, error) { ) (*game_model.Team, error) {
@@ -56,11 +56,11 @@ func (s *TeamService) AddTeam(
if err != nil { if err != nil {
return nil, err return nil, err
} }
game, err := s.gamesRepo.GetGameByID(ctx, gameId) game, err := s.gamesRepo.GetGameByID(ctx, gameID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
id, err := s.teamsRepo.AddTeamWithParticipation(ctx, creatorId, gameId, name, password, captainEmail, !time.Now().Before(game.StartAt.Add(-24*time.Hour))) id, err := s.teamsRepo.AddTeamWithParticipation(ctx, creatorID, gameID, name, password, captainEmail, !time.Now().Before(game.StartAt.Add(-24*time.Hour)))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -70,12 +70,12 @@ func (s *TeamService) AddTeam(
}, nil }, nil
} }
func (s *TeamService) UpdateTeam(ctx context.Context, teamId int, name string) error { func (s *TeamService) UpdateTeam(ctx context.Context, teamID int, name string) error {
return s.teamsRepo.UpdateTeam(ctx, teamId, name) return s.teamsRepo.UpdateTeam(ctx, teamID, name)
} }
func (s *TeamService) DeleteTeam(ctx context.Context, teamId int) error { func (s *TeamService) DeleteTeam(ctx context.Context, teamID int) error {
return s.teamsRepo.DeleteTeam(ctx, teamId) return s.teamsRepo.DeleteTeam(ctx, teamID)
} }
func (s *TeamService) RegisterTeam(ctx context.Context, gameID int, deliveryID string, registration Registration) (int, error) { func (s *TeamService) RegisterTeam(ctx context.Context, gameID int, deliveryID string, registration Registration) (int, error) {
+12 -12
View File
@@ -48,9 +48,9 @@ type usersRepository interface {
GetUserByEmail(ctx context.Context, email string) (*repos.User, error) GetUserByEmail(ctx context.Context, email string) (*repos.User, error)
GetUserByID(ctx context.Context, id int) (*repos.User, error) GetUserByID(ctx context.Context, id int) (*repos.User, error)
GetUsers(ctx context.Context) ([]*repos.User, error) GetUsers(ctx context.Context) ([]*repos.User, error)
AddUserRole(ctx context.Context, userId int, role string) error AddUserRole(ctx context.Context, userID int, role string) error
DeleteUserRole(ctx context.Context, userId int, role string) error DeleteUserRole(ctx context.Context, userID int, role string) error
DeleteUser(ctx context.Context, userId int) error DeleteUser(ctx context.Context, userID int) error
} }
type UsersService struct { type UsersService struct {
@@ -165,17 +165,17 @@ func (s *UsersService) AddUser(
// access-токена не должен мочь удалить чужой аккаунт. // access-токена не должен мочь удалить чужой аккаунт.
func (s *UsersService) DeleteAccount( func (s *UsersService) DeleteAccount(
ctx context.Context, ctx context.Context,
userId int, userID int,
password string, password string,
) error { ) error {
user, err := s.usersRepo.GetUserByID(ctx, userId) user, err := s.usersRepo.GetUserByID(ctx, userID)
if err != nil { if err != nil {
return err return err
} }
if err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil { if err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil {
return errors.New("Неверный пароль") return errors.New("Неверный пароль")
} }
return s.usersRepo.DeleteUser(ctx, userId) return s.usersRepo.DeleteUser(ctx, userID)
} }
func (s *UsersService) RefreshPassword( func (s *UsersService) RefreshPassword(
@@ -336,9 +336,9 @@ func (s *UsersService) GetUsers(
func (s *UsersService) GetUserByID( func (s *UsersService) GetUserByID(
ctx context.Context, ctx context.Context,
userId int, userID int,
) (*repos.User, error) { ) (*repos.User, error) {
user, err := s.usersRepo.GetUserByID(ctx, userId) user, err := s.usersRepo.GetUserByID(ctx, userID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -347,24 +347,24 @@ func (s *UsersService) GetUserByID(
func (s *UsersService) AddUserRole( func (s *UsersService) AddUserRole(
ctx context.Context, ctx context.Context,
userId int, userID int,
role string, role string,
) error { ) error {
if !slices.Contains(roles.AllRoles, role) { if !slices.Contains(roles.AllRoles, role) {
return fmt.Errorf("role %s not support", role) return fmt.Errorf("role %s not support", role)
} }
return s.usersRepo.AddUserRole(ctx, userId, role) return s.usersRepo.AddUserRole(ctx, userID, role)
} }
func (s *UsersService) DeleteUserRole( func (s *UsersService) DeleteUserRole(
ctx context.Context, ctx context.Context,
userId int, userID int,
role string, role string,
) error { ) error {
if !slices.Contains(roles.AllRoles, role) { if !slices.Contains(roles.AllRoles, role) {
return fmt.Errorf("role %s not support", role) return fmt.Errorf("role %s not support", role)
} }
return s.usersRepo.DeleteUserRole(ctx, userId, role) return s.usersRepo.DeleteUserRole(ctx, userID, role)
} }
var ( var (
@@ -117,14 +117,14 @@ func (r *fakeRepo) AddUserRole(_ context.Context, _ int, _ string) error { retur
func (r *fakeRepo) DeleteUserRole(_ context.Context, _ int, _ string) error { return nil } func (r *fakeRepo) DeleteUserRole(_ context.Context, _ int, _ string) error { return nil }
func (r *fakeRepo) DeleteUser(_ context.Context, userId int) error { func (r *fakeRepo) DeleteUser(_ context.Context, userID int) error {
r.mu.Lock() r.mu.Lock()
defer r.mu.Unlock() defer r.mu.Unlock()
u, ok := r.byID[userId] u, ok := r.byID[userID]
if !ok { if !ok {
return users_repo.ErrUserNotFound return users_repo.ErrUserNotFound
} }
delete(r.byID, userId) delete(r.byID, userID)
delete(r.users, u.Email) delete(r.users, u.Email)
return nil return nil
} }