generated from VLADIMIR/template
fix
This commit is contained in:
@@ -470,6 +470,16 @@ service EveningDetectiveServer {
|
||||
};
|
||||
}
|
||||
|
||||
rpc GetGameResults(GetGameResultsReq) returns (GetGameResultsRsp) {
|
||||
option (google.api.http) = {
|
||||
get: "/api/games/{gameId}/results"
|
||||
};
|
||||
option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_operation) = {
|
||||
tags : "Игры";
|
||||
summary: "Получить итоговую таблицу игры (после завершения)";
|
||||
};
|
||||
}
|
||||
|
||||
rpc UpdateGame(UpdateGameReq) returns (UpdateGameRsp) {
|
||||
option (google.api.http) = {
|
||||
put : "/api/games/{id}"
|
||||
@@ -1115,6 +1125,37 @@ message GetGameAnswersRsp {
|
||||
repeated TeamAnswers teams = 3;
|
||||
}
|
||||
|
||||
message GetGameResultsReq {
|
||||
int32 gameId = 1;
|
||||
}
|
||||
|
||||
// Вопрос в шапке итоговой таблицы: правильный ответ (поле answer сообщения
|
||||
// Question) командам/таблице не передаётся — он виден только в панели оценки.
|
||||
message ResultsQuestion {
|
||||
string code = 1;
|
||||
string text = 2;
|
||||
}
|
||||
|
||||
// Строка итоговой таблицы: команда, баллы по вопросам, сумма и место.
|
||||
message TeamResult {
|
||||
Team team = 1;
|
||||
repeated AnswerScore answers = 2;
|
||||
// Сумма баллов по всем вопросам сценария (неоценённые считаются как 0)
|
||||
int32 total_score = 3;
|
||||
// Место в итоговой таблице: команды с одинаковой суммой баллов и
|
||||
// одинаковым числом ходов занимают одно место (следующее пропускается)
|
||||
int32 place = 4;
|
||||
// Количество ходов команды (дублирует team.actions_count для удобства
|
||||
// таблицы; участвует в тай-брейке при равенстве суммы баллов)
|
||||
int32 actions_count = 5;
|
||||
}
|
||||
|
||||
message GetGameResultsRsp {
|
||||
string error = 1;
|
||||
repeated ResultsQuestion questions = 2;
|
||||
repeated TeamResult teams = 3;
|
||||
}
|
||||
|
||||
message UpdateGameReq {
|
||||
int32 id = 1;
|
||||
string name = 2;
|
||||
|
||||
Binary file not shown.
@@ -388,6 +388,38 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/games/{gameId}/results": {
|
||||
"get": {
|
||||
"summary": "Получить итоговую таблицу игры (после завершения)",
|
||||
"operationId": "EveningDetectiveServer_GetGameResults",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "A successful response.",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/evening_detective_serverGetGameResultsRsp"
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"description": "An unexpected error response.",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/rpcStatus"
|
||||
}
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "gameId",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"type": "integer",
|
||||
"format": "int32"
|
||||
}
|
||||
],
|
||||
"tags": [
|
||||
"Игры"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/games/{id}": {
|
||||
"get": {
|
||||
"summary": "Получить игру",
|
||||
@@ -2514,6 +2546,28 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"evening_detective_serverGetGameResultsRsp": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"error": {
|
||||
"type": "string"
|
||||
},
|
||||
"questions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"$ref": "#/definitions/evening_detective_serverResultsQuestion"
|
||||
}
|
||||
},
|
||||
"teams": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"$ref": "#/definitions/evening_detective_serverTeamResult"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"evening_detective_serverGetGameRsp": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -2867,6 +2921,18 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"evening_detective_serverResultsQuestion": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": {
|
||||
"type": "string"
|
||||
},
|
||||
"text": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"description": "Вопрос в шапке итоговой таблицы: правильный ответ (поле answer сообщения\nQuestion) командам/таблице не передаётся — он виден только в панели оценки."
|
||||
},
|
||||
"evening_detective_serverScenario": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -3022,6 +3088,37 @@
|
||||
},
|
||||
"title": "Ответы одной команды на вопросы дела"
|
||||
},
|
||||
"evening_detective_serverTeamResult": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"team": {
|
||||
"$ref": "#/definitions/evening_detective_serverTeam"
|
||||
},
|
||||
"answers": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"$ref": "#/definitions/evening_detective_serverAnswerScore"
|
||||
}
|
||||
},
|
||||
"totalScore": {
|
||||
"type": "integer",
|
||||
"format": "int32",
|
||||
"title": "Сумма баллов по всем вопросам сценария (неоценённые считаются как 0)"
|
||||
},
|
||||
"place": {
|
||||
"type": "integer",
|
||||
"format": "int32",
|
||||
"title": "Место в итоговой таблице: команды с одинаковой суммой баллов и\nодинаковым числом ходов занимают одно место (следующее пропускается)"
|
||||
},
|
||||
"actionsCount": {
|
||||
"type": "integer",
|
||||
"format": "int32",
|
||||
"title": "Количество ходов команды (дублирует team.actions_count для удобства\nтаблицы; участвует в тай-брейке при равенстве суммы баллов)"
|
||||
}
|
||||
},
|
||||
"description": "Строка итоговой таблицы: команда, баллы по вопросам, сумма и место."
|
||||
},
|
||||
"evening_detective_serverUpdateGameRsp": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"evening_detective_server/internal/modules/storytelling"
|
||||
"evening_detective_server/internal/services/game_service"
|
||||
proto "evening_detective_server/proto"
|
||||
)
|
||||
|
||||
// mapResultsQuestions мапит вопросы сценария в шапку итоговой таблицы:
|
||||
// правильный ответ (поле Answer) не передаётся — он виден только в панели
|
||||
// оценки (GetGameAnswers).
|
||||
func mapResultsQuestions(o []*storytelling.Question) []*proto.ResultsQuestion {
|
||||
res := make([]*proto.ResultsQuestion, 0, len(o))
|
||||
for _, item := range o {
|
||||
res = append(res, &proto.ResultsQuestion{
|
||||
Code: item.Code,
|
||||
Text: item.Text,
|
||||
})
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// mapTeamResults мапит строки итоговой таблицы. Команда мапится целиком
|
||||
// (включая password/applications — аудитория та же, что у GetGameAnswers:
|
||||
// организатор/автор); actionsCount продублирован на уровне строки таблицы.
|
||||
func mapTeamResults(o []game_service.TeamResult) []*proto.TeamResult {
|
||||
res := make([]*proto.TeamResult, 0, len(o))
|
||||
for _, item := range o {
|
||||
res = append(res, &proto.TeamResult{
|
||||
Team: mapTeam(item.Team),
|
||||
Answers: mapAnswerScores(item.Answers),
|
||||
TotalScore: int32(item.TotalScore),
|
||||
Place: int32(item.Place),
|
||||
ActionsCount: int32(item.Team.ActionsCount),
|
||||
})
|
||||
}
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"evening_detective_server/internal/services/game_service"
|
||||
)
|
||||
|
||||
func TestMapTeamResults(t *testing.T) {
|
||||
sc := 5
|
||||
results := []game_service.TeamResult{
|
||||
{
|
||||
Team: &game_service.Team{
|
||||
ID: 1,
|
||||
Name: "Команда А",
|
||||
Status: "play",
|
||||
ActionsCount: 7,
|
||||
},
|
||||
Answers: []game_service.AnswerScore{
|
||||
{QuestionCode: "q1", Text: "ответ", Score: &sc},
|
||||
},
|
||||
TotalScore: 5,
|
||||
Place: 1,
|
||||
},
|
||||
}
|
||||
|
||||
got := mapTeamResults(results)
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("len(mapTeamResults) = %d, want 1", len(got))
|
||||
}
|
||||
row := got[0]
|
||||
if row.Team == nil || row.Team.Id != 1 || row.Team.Name != "Команда А" {
|
||||
t.Fatalf("row.Team = %+v, want id 1, name Команда А", row.Team)
|
||||
}
|
||||
// actionsCount продублирован на уровне строки таблицы.
|
||||
if row.ActionsCount != 7 {
|
||||
t.Fatalf("row.ActionsCount = %d, want 7", row.ActionsCount)
|
||||
}
|
||||
if row.TotalScore != 5 || row.Place != 1 {
|
||||
t.Fatalf("row.TotalScore = %d, row.Place = %d; want 5 и 1", row.TotalScore, row.Place)
|
||||
}
|
||||
if len(row.Answers) != 1 || row.Answers[0].QuestionCode != "q1" {
|
||||
t.Fatalf("row.Answers = %+v, want один ответ q1", row.Answers)
|
||||
}
|
||||
}
|
||||
@@ -848,6 +848,25 @@ func (s *server) GetGameAnswers(ctx context.Context, req *proto.GetGameAnswersRe
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *server) GetGameResults(ctx context.Context, req *proto.GetGameResultsReq) (*proto.GetGameResultsRsp, error) {
|
||||
claims := ctx.Value("claims").(*processor_jwt.JWTClaims)
|
||||
if !roles.HasRole(claims, roles.Organizer) && !roles.HasRole(claims, roles.Author) {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
||||
}
|
||||
|
||||
results, err := s.gameService.GetGameResults(ctx, int(req.GameId))
|
||||
if err != nil {
|
||||
return &proto.GetGameResultsRsp{
|
||||
Error: err.Error(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &proto.GetGameResultsRsp{
|
||||
Questions: mapResultsQuestions(results.Questions),
|
||||
Teams: mapTeamResults(results.Teams),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *server) GetGames(ctx context.Context, req *proto.GetGamesReq) (*proto.GetGamesRsp, error) {
|
||||
claims := ctx.Value("claims").(*processor_jwt.JWTClaims)
|
||||
if !roles.HasRole(claims, roles.Organizer) && !roles.HasRole(claims, roles.Author) {
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
package game_service
|
||||
|
||||
import (
|
||||
"sort"
|
||||
|
||||
"evening_detective_server/internal/modules/storytelling"
|
||||
)
|
||||
|
||||
// TeamResult — строка итоговой таблицы: команда, баллы по вопросам (в порядке
|
||||
// сценария), сумма баллов и место.
|
||||
type TeamResult struct {
|
||||
Team *Team
|
||||
Answers []AnswerScore
|
||||
// TotalScore — сумма баллов по всем вопросам сценария; неоценённые
|
||||
// вопросы считаются как 0.
|
||||
TotalScore int
|
||||
// Place — место в итоговой таблице. Команды с одинаковой суммой баллов
|
||||
// и одинаковым числом ходов занимают одно место (следующее место
|
||||
// пропускается); проставляется функцией rankTeams.
|
||||
Place int
|
||||
}
|
||||
|
||||
// GameResults — итоговая таблица игры: вопросы сценария (шапка таблицы) и
|
||||
// результаты команд, отсортированные по сумме баллов.
|
||||
type GameResults struct {
|
||||
Questions []*storytelling.Question
|
||||
Teams []TeamResult
|
||||
}
|
||||
|
||||
// buildTeamResults собирает строки итоговой таблицы по командам: баллы в
|
||||
// порядке вопросов сценария (неотвеченный/неоценённый вопрос — с пустым
|
||||
// текстом и Score=nil), сумма баллов (nil считается как 0). Команды в
|
||||
// результате — в порядке переданного списка; сортировку и места делает
|
||||
// rankTeams.
|
||||
func buildTeamResults(
|
||||
questions []*storytelling.Question,
|
||||
teams []*Team,
|
||||
answerByTeamAndCode map[int]map[string]AnswerScore,
|
||||
) []TeamResult {
|
||||
res := make([]TeamResult, 0, len(teams))
|
||||
for _, team := range teams {
|
||||
byCode := answerByTeamAndCode[team.ID]
|
||||
answers := make([]AnswerScore, 0, len(questions))
|
||||
total := 0
|
||||
for _, question := range questions {
|
||||
answer, ok := byCode[question.Code]
|
||||
if !ok {
|
||||
answers = append(answers, AnswerScore{QuestionCode: question.Code})
|
||||
continue
|
||||
}
|
||||
answers = append(answers, answer)
|
||||
if answer.Score != nil {
|
||||
total += *answer.Score
|
||||
}
|
||||
}
|
||||
res = append(res, TeamResult{
|
||||
Team: team,
|
||||
Answers: answers,
|
||||
TotalScore: total,
|
||||
})
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// rankTeams сортирует строки итоговой таблицы по сумме баллов (убывание);
|
||||
// при равенстве суммы выше команда с меньшим числом ходов. Команды с
|
||||
// одинаковой суммой баллов И одинаковым числом ходов занимают одно место
|
||||
// (следующее место пропускается — схема 1,2,2,4 по ключу (сумма, ходы)).
|
||||
// id команды влияет только на порядок показа внутри группы (меньший id
|
||||
// первым), не на место. Входной срез не изменяется.
|
||||
func rankTeams(rows []TeamResult) []TeamResult {
|
||||
sorted := make([]TeamResult, len(rows))
|
||||
copy(sorted, rows)
|
||||
sort.SliceStable(sorted, func(i, j int) bool {
|
||||
a, b := sorted[i], sorted[j]
|
||||
if a.TotalScore != b.TotalScore {
|
||||
return a.TotalScore > b.TotalScore
|
||||
}
|
||||
if a.Team.ActionsCount != b.Team.ActionsCount {
|
||||
return a.Team.ActionsCount < b.Team.ActionsCount
|
||||
}
|
||||
return a.Team.ID < b.Team.ID
|
||||
})
|
||||
place := 0
|
||||
for i := range sorted {
|
||||
row := sorted[i]
|
||||
if i == 0 || row.TotalScore != sorted[i-1].TotalScore || row.Team.ActionsCount != sorted[i-1].Team.ActionsCount {
|
||||
place = i + 1
|
||||
}
|
||||
sorted[i].Place = place
|
||||
}
|
||||
return sorted
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package game_service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"evening_detective_server/internal/modules/storytelling"
|
||||
)
|
||||
|
||||
func intPtr(v int) *int { return &v }
|
||||
|
||||
func teamResult(id, actions, total int) TeamResult {
|
||||
return TeamResult{
|
||||
Team: &Team{ID: id, ActionsCount: actions},
|
||||
TotalScore: total,
|
||||
}
|
||||
}
|
||||
|
||||
func TestRankTeamsSortsByTotalThenActions(t *testing.T) {
|
||||
// У всех команд разный ключ (сумма, ходы) — места идут подряд 1..N.
|
||||
rows := []TeamResult{
|
||||
teamResult(3, 5, 10),
|
||||
teamResult(1, 3, 10),
|
||||
teamResult(2, 1, 12),
|
||||
teamResult(4, 7, 8),
|
||||
}
|
||||
got := rankTeams(rows)
|
||||
|
||||
wantIDs := []int{2, 1, 3, 4}
|
||||
wantPlaces := []int{1, 2, 3, 4}
|
||||
for i, id := range wantIDs {
|
||||
if got[i].Team.ID != id {
|
||||
t.Fatalf("rankTeams[%d].Team.ID = %d, want %d (порядок: total desc, actions asc)", i, got[i].Team.ID, id)
|
||||
}
|
||||
if got[i].Place != wantPlaces[i] {
|
||||
t.Fatalf("rankTeams[%d].Place = %d, want %d", i, got[i].Place, wantPlaces[i])
|
||||
}
|
||||
}
|
||||
// Команды 1 и 3 имеют одинаковую сумму (10), но разные ходы — разные места.
|
||||
if got[1].Place == got[2].Place {
|
||||
t.Fatalf("равные суммы при разных ходах должны давать разные места: places = %d, %d", got[1].Place, got[2].Place)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRankTeamsSharesPlaceOnEqualTotalAndActions(t *testing.T) {
|
||||
// Одинаковая сумма И одинаковое число ходов — одно место у всех трёх.
|
||||
rows := []TeamResult{
|
||||
teamResult(5, 4, 9),
|
||||
teamResult(2, 4, 9),
|
||||
teamResult(7, 4, 9),
|
||||
}
|
||||
got := rankTeams(rows)
|
||||
|
||||
// Внутри группы порядок показа — по id asc (детерминированный).
|
||||
wantIDs := []int{2, 5, 7}
|
||||
for i, id := range wantIDs {
|
||||
if got[i].Team.ID != id {
|
||||
t.Fatalf("rankTeams[%d].Team.ID = %d, want %d (порядок показа внутри группы — id asc)", i, got[i].Team.ID, id)
|
||||
}
|
||||
if got[i].Place != 1 {
|
||||
t.Fatalf("rankTeams[%d].Place = %d, want 1 (одно место у равных по сумме и ходам)", i, got[i].Place)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRankTeamsSkipsPlaceAfterSharedTie(t *testing.T) {
|
||||
// Две команды делят 1-е место, следующая получает 3-е (схема 1,1,3).
|
||||
rows := []TeamResult{
|
||||
teamResult(3, 2, 7),
|
||||
teamResult(1, 5, 10),
|
||||
teamResult(2, 5, 10),
|
||||
teamResult(4, 9, 5),
|
||||
}
|
||||
got := rankTeams(rows)
|
||||
|
||||
wantIDs := []int{1, 2, 3, 4}
|
||||
wantPlaces := []int{1, 1, 3, 4}
|
||||
for i := range wantIDs {
|
||||
if got[i].Team.ID != wantIDs[i] {
|
||||
t.Fatalf("rankTeams[%d].Team.ID = %d, want %d", i, got[i].Team.ID, wantIDs[i])
|
||||
}
|
||||
if got[i].Place != wantPlaces[i] {
|
||||
t.Fatalf("rankTeams[%d].Place = %d, want %d (места 1,1,3,4)", i, got[i].Place, wantPlaces[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRankTeamsDoesNotMutateInput(t *testing.T) {
|
||||
rows := []TeamResult{
|
||||
teamResult(1, 1, 5),
|
||||
teamResult(2, 1, 5),
|
||||
}
|
||||
rankTeams(rows)
|
||||
|
||||
if rows[0].Place != 0 || rows[1].Place != 0 {
|
||||
t.Fatalf("rankTeams изменил входной срез: places = %d, %d; want 0, 0", rows[0].Place, rows[1].Place)
|
||||
}
|
||||
if rows[0].Team.ID != 1 || rows[1].Team.ID != 2 {
|
||||
t.Fatalf("rankTeams изменил порядок входного среза: ids = %d, %d; want 1, 2", rows[0].Team.ID, rows[1].Team.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildTeamResultsScenarioOrderAndNilScores(t *testing.T) {
|
||||
questions := []*storytelling.Question{
|
||||
{Code: "q1", Text: "Вопрос 1"},
|
||||
{Code: "q2", Text: "Вопрос 2"},
|
||||
{Code: "q3", Text: "Вопрос 3"},
|
||||
}
|
||||
teams := []*Team{
|
||||
{ID: 1, Name: "А", ActionsCount: 4},
|
||||
{ID: 2, Name: "Б", ActionsCount: 2},
|
||||
}
|
||||
answerByTeamAndCode := map[int]map[string]AnswerScore{
|
||||
1: {
|
||||
"q1": {QuestionCode: "q1", Text: "ответ 1", Score: intPtr(5)},
|
||||
"q3": {QuestionCode: "q3", Text: "ответ 3", Score: intPtr(-1)},
|
||||
},
|
||||
2: {
|
||||
"q2": {QuestionCode: "q2", Text: "ответ 2"}, // балл не выставлен
|
||||
},
|
||||
}
|
||||
|
||||
got := buildTeamResults(questions, teams, answerByTeamAndCode)
|
||||
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("len(buildTeamResults) = %d, want 2", len(got))
|
||||
}
|
||||
|
||||
// Команда 1: q1(5), q2 не отвечен, q3(-1) → сумма 4.
|
||||
first := got[0]
|
||||
if first.Team.ID != 1 || first.TotalScore != 4 {
|
||||
t.Fatalf("команда 1: Team.ID = %d, TotalScore = %d; want ID 1, Total 4", first.Team.ID, first.TotalScore)
|
||||
}
|
||||
if len(first.Answers) != 3 {
|
||||
t.Fatalf("команда 1: len(Answers) = %d, want 3 (порядок сценария)", len(first.Answers))
|
||||
}
|
||||
for i, wantCode := range []string{"q1", "q2", "q3"} {
|
||||
if first.Answers[i].QuestionCode != wantCode {
|
||||
t.Fatalf("команда 1: Answers[%d].QuestionCode = %q, want %q", i, first.Answers[i].QuestionCode, wantCode)
|
||||
}
|
||||
}
|
||||
if first.Answers[1].Score != nil || first.Answers[1].Text != "" {
|
||||
t.Fatalf("команда 1: неотвеченный q2 = %+v, want Score=nil и Text=\"\"", first.Answers[1])
|
||||
}
|
||||
|
||||
// Команда 2: все не оценены → сумма 0.
|
||||
second := got[1]
|
||||
if second.Team.ID != 2 || second.TotalScore != 0 {
|
||||
t.Fatalf("команда 2: Team.ID = %d, TotalScore = %d; want ID 2, Total 0", second.Team.ID, second.TotalScore)
|
||||
}
|
||||
if second.Answers[1].Score != nil {
|
||||
t.Fatalf("команда 2: неоценённый q2: Score = %v, want nil", second.Answers[1].Score)
|
||||
}
|
||||
}
|
||||
@@ -321,6 +321,8 @@ var (
|
||||
ErrGameNotStarted = errors.New("Игра не начата, отвечать на вопросы нельзя")
|
||||
// ErrQuestionNotFound — вопрос с таким кодом отсутствует в сценарии игры.
|
||||
ErrQuestionNotFound = errors.New("Вопрос не найден")
|
||||
// ErrGameNotFinished — итоги игры доступны только после её завершения.
|
||||
ErrGameNotFinished = errors.New("Итоги доступны после завершения игры")
|
||||
)
|
||||
|
||||
// getTeamAndGame проверяет команду по паролю и возвращает её вместе с игрой.
|
||||
@@ -500,3 +502,62 @@ func (s *GameService) SetTeamAnswerScore(ctx context.Context, teamId int, questi
|
||||
}
|
||||
return s.answersRepo.SetAnswerScore(ctx, teamId, questionCode, score)
|
||||
}
|
||||
|
||||
// GetGameResults возвращает итоговую таблицу игры: вопросы сценария (шапка
|
||||
// таблицы, без правильных ответов) и команды, отсортированные по сумме
|
||||
// баллов, с баллами по каждому вопросу (в порядке сценария), числом ходов и
|
||||
// местом. Доступно только после завершения игры (статус finish); неоценённые
|
||||
// вопросы в сумме считаются как 0.
|
||||
func (s *GameService) GetGameResults(ctx context.Context, gameId int) (*GameResults, error) {
|
||||
game, err := s.gamesRepo.GetGameByID(ctx, gameId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if game.Status != "finish" {
|
||||
return nil, ErrGameNotFinished
|
||||
}
|
||||
questions, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
teams, err := s.teamsRepo.GetTeamsByGameID(ctx, gameId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
teamIds := make([]int, 0, len(teams))
|
||||
for _, team := range teams {
|
||||
teamIds = append(teamIds, team.ID)
|
||||
}
|
||||
actionsCountByTeamIDs, err := s.actionsRepo.GetActionsCountByTeamIDs(ctx, teamIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := s.answersRepo.GetAnswersByGameID(ctx, gameId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
answerByTeamAndCode := make(map[int]map[string]AnswerScore, len(teams))
|
||||
for _, row := range rows {
|
||||
if _, ok := byCode[row.QuestionCode]; !ok {
|
||||
continue
|
||||
}
|
||||
if answerByTeamAndCode[row.TeamId] == nil {
|
||||
answerByTeamAndCode[row.TeamId] = make(map[string]AnswerScore, len(questions))
|
||||
}
|
||||
answerByTeamAndCode[row.TeamId][row.QuestionCode] = AnswerScore{
|
||||
QuestionCode: row.QuestionCode,
|
||||
Text: row.Text,
|
||||
Score: row.Score,
|
||||
}
|
||||
}
|
||||
mappedTeams := make([]*Team, 0, len(teams))
|
||||
for _, team := range teams {
|
||||
mapped := mapTeam(team)
|
||||
mapped.ActionsCount = actionsCountByTeamIDs[team.ID]
|
||||
mappedTeams = append(mappedTeams, mapped)
|
||||
}
|
||||
return &GameResults{
|
||||
Questions: questions,
|
||||
Teams: rankTeams(buildTeamResults(questions, mappedTeams, answerByTeamAndCode)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
+545
-276
File diff suppressed because it is too large
Load Diff
@@ -1422,6 +1422,45 @@ func local_request_EveningDetectiveServer_GetGameAnswers_0(ctx context.Context,
|
||||
return msg, metadata, err
|
||||
}
|
||||
|
||||
func request_EveningDetectiveServer_GetGameResults_0(ctx context.Context, marshaler runtime.Marshaler, client EveningDetectiveServerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
|
||||
var (
|
||||
protoReq GetGameResultsReq
|
||||
metadata runtime.ServerMetadata
|
||||
err error
|
||||
)
|
||||
if req.Body != nil {
|
||||
_, _ = io.Copy(io.Discard, req.Body)
|
||||
}
|
||||
val, ok := pathParams["gameId"]
|
||||
if !ok {
|
||||
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "gameId")
|
||||
}
|
||||
protoReq.GameId, err = runtime.Int32(val)
|
||||
if err != nil {
|
||||
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "gameId", err)
|
||||
}
|
||||
msg, err := client.GetGameResults(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
|
||||
return msg, metadata, err
|
||||
}
|
||||
|
||||
func local_request_EveningDetectiveServer_GetGameResults_0(ctx context.Context, marshaler runtime.Marshaler, server EveningDetectiveServerServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
|
||||
var (
|
||||
protoReq GetGameResultsReq
|
||||
metadata runtime.ServerMetadata
|
||||
err error
|
||||
)
|
||||
val, ok := pathParams["gameId"]
|
||||
if !ok {
|
||||
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "gameId")
|
||||
}
|
||||
protoReq.GameId, err = runtime.Int32(val)
|
||||
if err != nil {
|
||||
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "gameId", err)
|
||||
}
|
||||
msg, err := server.GetGameResults(ctx, &protoReq)
|
||||
return msg, metadata, err
|
||||
}
|
||||
|
||||
func request_EveningDetectiveServer_UpdateGame_0(ctx context.Context, marshaler runtime.Marshaler, client EveningDetectiveServerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
|
||||
var (
|
||||
protoReq UpdateGameReq
|
||||
@@ -2989,6 +3028,26 @@ func RegisterEveningDetectiveServerHandlerServer(ctx context.Context, mux *runti
|
||||
}
|
||||
forward_EveningDetectiveServer_GetGameAnswers_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
|
||||
})
|
||||
mux.Handle(http.MethodGet, pattern_EveningDetectiveServer_GetGameResults_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
|
||||
ctx, cancel := context.WithCancel(req.Context())
|
||||
defer cancel()
|
||||
var stream runtime.ServerTransportStream
|
||||
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
|
||||
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
|
||||
annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/crabs.evening_detective_server.EveningDetectiveServer/GetGameResults", runtime.WithHTTPPathPattern("/api/games/{gameId}/results"))
|
||||
if err != nil {
|
||||
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
|
||||
return
|
||||
}
|
||||
resp, md, err := local_request_EveningDetectiveServer_GetGameResults_0(annotatedContext, inboundMarshaler, server, req, pathParams)
|
||||
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
|
||||
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
|
||||
if err != nil {
|
||||
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
|
||||
return
|
||||
}
|
||||
forward_EveningDetectiveServer_GetGameResults_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
|
||||
})
|
||||
mux.Handle(http.MethodPut, pattern_EveningDetectiveServer_UpdateGame_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
|
||||
ctx, cancel := context.WithCancel(req.Context())
|
||||
defer cancel()
|
||||
@@ -4049,6 +4108,23 @@ func RegisterEveningDetectiveServerHandlerClient(ctx context.Context, mux *runti
|
||||
}
|
||||
forward_EveningDetectiveServer_GetGameAnswers_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
|
||||
})
|
||||
mux.Handle(http.MethodGet, pattern_EveningDetectiveServer_GetGameResults_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
|
||||
ctx, cancel := context.WithCancel(req.Context())
|
||||
defer cancel()
|
||||
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
|
||||
annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/crabs.evening_detective_server.EveningDetectiveServer/GetGameResults", runtime.WithHTTPPathPattern("/api/games/{gameId}/results"))
|
||||
if err != nil {
|
||||
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
|
||||
return
|
||||
}
|
||||
resp, md, err := request_EveningDetectiveServer_GetGameResults_0(annotatedContext, inboundMarshaler, client, req, pathParams)
|
||||
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
|
||||
if err != nil {
|
||||
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
|
||||
return
|
||||
}
|
||||
forward_EveningDetectiveServer_GetGameResults_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
|
||||
})
|
||||
mux.Handle(http.MethodPut, pattern_EveningDetectiveServer_UpdateGame_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
|
||||
ctx, cancel := context.WithCancel(req.Context())
|
||||
defer cancel()
|
||||
@@ -4382,6 +4458,7 @@ var (
|
||||
pattern_EveningDetectiveServer_GetGames_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"api", "games"}, ""))
|
||||
pattern_EveningDetectiveServer_GetGame_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"api", "games", "id"}, ""))
|
||||
pattern_EveningDetectiveServer_GetGameAnswers_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"api", "games", "gameId", "answers"}, ""))
|
||||
pattern_EveningDetectiveServer_GetGameResults_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"api", "games", "gameId", "results"}, ""))
|
||||
pattern_EveningDetectiveServer_UpdateGame_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"api", "games", "id"}, ""))
|
||||
pattern_EveningDetectiveServer_StartGame_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"api", "games", "id", "start"}, ""))
|
||||
pattern_EveningDetectiveServer_PauseGame_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"api", "games", "id", "pause"}, ""))
|
||||
@@ -4442,6 +4519,7 @@ var (
|
||||
forward_EveningDetectiveServer_GetGames_0 = runtime.ForwardResponseMessage
|
||||
forward_EveningDetectiveServer_GetGame_0 = runtime.ForwardResponseMessage
|
||||
forward_EveningDetectiveServer_GetGameAnswers_0 = runtime.ForwardResponseMessage
|
||||
forward_EveningDetectiveServer_GetGameResults_0 = runtime.ForwardResponseMessage
|
||||
forward_EveningDetectiveServer_UpdateGame_0 = runtime.ForwardResponseMessage
|
||||
forward_EveningDetectiveServer_StartGame_0 = runtime.ForwardResponseMessage
|
||||
forward_EveningDetectiveServer_PauseGame_0 = runtime.ForwardResponseMessage
|
||||
|
||||
@@ -60,6 +60,7 @@ const (
|
||||
EveningDetectiveServer_GetGames_FullMethodName = "/crabs.evening_detective_server.EveningDetectiveServer/GetGames"
|
||||
EveningDetectiveServer_GetGame_FullMethodName = "/crabs.evening_detective_server.EveningDetectiveServer/GetGame"
|
||||
EveningDetectiveServer_GetGameAnswers_FullMethodName = "/crabs.evening_detective_server.EveningDetectiveServer/GetGameAnswers"
|
||||
EveningDetectiveServer_GetGameResults_FullMethodName = "/crabs.evening_detective_server.EveningDetectiveServer/GetGameResults"
|
||||
EveningDetectiveServer_UpdateGame_FullMethodName = "/crabs.evening_detective_server.EveningDetectiveServer/UpdateGame"
|
||||
EveningDetectiveServer_StartGame_FullMethodName = "/crabs.evening_detective_server.EveningDetectiveServer/StartGame"
|
||||
EveningDetectiveServer_PauseGame_FullMethodName = "/crabs.evening_detective_server.EveningDetectiveServer/PauseGame"
|
||||
@@ -123,6 +124,7 @@ type EveningDetectiveServerClient interface {
|
||||
GetGames(ctx context.Context, in *GetGamesReq, opts ...grpc.CallOption) (*GetGamesRsp, error)
|
||||
GetGame(ctx context.Context, in *GetGameReq, opts ...grpc.CallOption) (*GetGameRsp, error)
|
||||
GetGameAnswers(ctx context.Context, in *GetGameAnswersReq, opts ...grpc.CallOption) (*GetGameAnswersRsp, error)
|
||||
GetGameResults(ctx context.Context, in *GetGameResultsReq, opts ...grpc.CallOption) (*GetGameResultsRsp, error)
|
||||
UpdateGame(ctx context.Context, in *UpdateGameReq, opts ...grpc.CallOption) (*UpdateGameRsp, error)
|
||||
StartGame(ctx context.Context, in *StartGameReq, opts ...grpc.CallOption) (*StartGameRsp, error)
|
||||
PauseGame(ctx context.Context, in *PauseGameReq, opts ...grpc.CallOption) (*PauseGameRsp, error)
|
||||
@@ -550,6 +552,16 @@ func (c *eveningDetectiveServerClient) GetGameAnswers(ctx context.Context, in *G
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *eveningDetectiveServerClient) GetGameResults(ctx context.Context, in *GetGameResultsReq, opts ...grpc.CallOption) (*GetGameResultsRsp, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetGameResultsRsp)
|
||||
err := c.cc.Invoke(ctx, EveningDetectiveServer_GetGameResults_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *eveningDetectiveServerClient) UpdateGame(ctx context.Context, in *UpdateGameReq, opts ...grpc.CallOption) (*UpdateGameRsp, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(UpdateGameRsp)
|
||||
@@ -764,6 +776,7 @@ type EveningDetectiveServerServer interface {
|
||||
GetGames(context.Context, *GetGamesReq) (*GetGamesRsp, error)
|
||||
GetGame(context.Context, *GetGameReq) (*GetGameRsp, error)
|
||||
GetGameAnswers(context.Context, *GetGameAnswersReq) (*GetGameAnswersRsp, error)
|
||||
GetGameResults(context.Context, *GetGameResultsReq) (*GetGameResultsRsp, error)
|
||||
UpdateGame(context.Context, *UpdateGameReq) (*UpdateGameRsp, error)
|
||||
StartGame(context.Context, *StartGameReq) (*StartGameRsp, error)
|
||||
PauseGame(context.Context, *PauseGameReq) (*PauseGameRsp, error)
|
||||
@@ -911,6 +924,9 @@ func (UnimplementedEveningDetectiveServerServer) GetGame(context.Context, *GetGa
|
||||
func (UnimplementedEveningDetectiveServerServer) GetGameAnswers(context.Context, *GetGameAnswersReq) (*GetGameAnswersRsp, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method GetGameAnswers not implemented")
|
||||
}
|
||||
func (UnimplementedEveningDetectiveServerServer) GetGameResults(context.Context, *GetGameResultsReq) (*GetGameResultsRsp, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method GetGameResults not implemented")
|
||||
}
|
||||
func (UnimplementedEveningDetectiveServerServer) UpdateGame(context.Context, *UpdateGameReq) (*UpdateGameRsp, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method UpdateGame not implemented")
|
||||
}
|
||||
@@ -1704,6 +1720,24 @@ func _EveningDetectiveServer_GetGameAnswers_Handler(srv interface{}, ctx context
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _EveningDetectiveServer_GetGameResults_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetGameResultsReq)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(EveningDetectiveServerServer).GetGameResults(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: EveningDetectiveServer_GetGameResults_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(EveningDetectiveServerServer).GetGameResults(ctx, req.(*GetGameResultsReq))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _EveningDetectiveServer_UpdateGame_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(UpdateGameReq)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -2177,6 +2211,10 @@ var EveningDetectiveServer_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "GetGameAnswers",
|
||||
Handler: _EveningDetectiveServer_GetGameAnswers_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetGameResults",
|
||||
Handler: _EveningDetectiveServer_GetGameResults_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "UpdateGame",
|
||||
Handler: _EveningDetectiveServer_UpdateGame_Handler,
|
||||
|
||||
Reference in New Issue
Block a user