Search in sources :

Example 6 with VotingChoice

use of com.faforever.api.data.domain.VotingChoice in project faf-java-api by FAForever.

the class VotingServiceTest method notSaveVoteIfAlternativeOrdinalWrong.

@Test
public void notSaveVoteIfAlternativeOrdinalWrong() {
    VotingSubject votingSubject = new VotingSubject();
    votingSubject.setId(1);
    votingSubject.setBeginOfVoteTime(OffsetDateTime.now());
    votingSubject.setEndOfVoteTime(OffsetDateTime.MAX);
    VotingQuestion votingQuestion = new VotingQuestion();
    votingQuestion.setAlternativeQuestion(true);
    votingSubject.setVotingQuestions(Collections.singleton(votingQuestion));
    votingQuestion.setMaxAnswers(2);
    Vote vote = new Vote();
    VotingAnswer votingAnswer = new VotingAnswer();
    VotingChoice votingChoice = new VotingChoice();
    votingChoice.setId(1);
    votingChoice.setVotingQuestion(votingQuestion);
    votingAnswer.setVotingChoice(votingChoice);
    votingAnswer.setAlternativeOrdinal(1);
    VotingAnswer votingAnswer2 = new VotingAnswer();
    VotingChoice votingChoice2 = new VotingChoice();
    votingChoice2.setId(2);
    votingChoice2.setVotingQuestion(votingQuestion);
    votingAnswer2.setVotingChoice(votingChoice2);
    votingAnswer2.setAlternativeOrdinal(1);
    vote.setVotingAnswers(new HashSet<>(Arrays.asList(votingAnswer, votingAnswer2)));
    vote.setVotingSubject(votingSubject);
    Player player = new Player();
    when(voteRepository.findByPlayerAndVotingSubjectId(player, votingSubject.getId())).thenReturn(Optional.empty());
    when(votingSubjectRepository.findById(votingSubject.getId())).thenReturn(Optional.of(votingSubject));
    when(votingChoiceRepository.findById(votingChoice.getId())).thenReturn(Optional.of(votingChoice));
    when(votingChoiceRepository.findById(votingChoice2.getId())).thenReturn(Optional.of(votingChoice2));
    try {
        instance.saveVote(vote, player);
    } catch (ApiException e) {
        assertTrue(Arrays.stream(e.getErrors()).anyMatch(error -> error.getErrorCode().equals(ErrorCode.MALFORMATTED_ALTERNATIVE_ORDINALS)));
    }
    verify(voteRepository, never()).save(vote);
}
Also used : Vote(com.faforever.api.data.domain.Vote) Player(com.faforever.api.data.domain.Player) VotingAnswer(com.faforever.api.data.domain.VotingAnswer) VotingSubject(com.faforever.api.data.domain.VotingSubject) VotingQuestion(com.faforever.api.data.domain.VotingQuestion) VotingChoice(com.faforever.api.data.domain.VotingChoice) ApiException(com.faforever.api.error.ApiException) Test(org.junit.Test)

Example 7 with VotingChoice

use of com.faforever.api.data.domain.VotingChoice in project faf-java-api by FAForever.

the class VotingElideTest method testRevealWinnerOnEndedSubjectWorks.

@Test
@WithUserDetails(AUTH_MODERATOR)
public void testRevealWinnerOnEndedSubjectWorks() throws Exception {
    mockMvc.perform(patch("/data/votingSubject/2").header(HttpHeaders.CONTENT_TYPE, DataController.JSON_API_MEDIA_TYPE).content(PATCH_VOTING_SUBJECT_REVEAL_ID_2)).andExpect(status().isNoContent());
    VotingQuestion question = votingQuestionRepository.getOne(2);
    List<VotingChoice> winners = question.getWinners();
    assertThat(winners, hasSize(1));
    assertThat(winners.get(0).getId(), is(3));
}
Also used : VotingQuestion(com.faforever.api.data.domain.VotingQuestion) VotingChoice(com.faforever.api.data.domain.VotingChoice) AbstractIntegrationTest(com.faforever.api.AbstractIntegrationTest) Test(org.junit.Test) WithUserDetails(org.springframework.security.test.context.support.WithUserDetails)

Example 8 with VotingChoice

use of com.faforever.api.data.domain.VotingChoice in project faf-java-api by FAForever.

the class VotingService method saveVote.

@Transactional
public void saveVote(Vote vote, Player player) {
    vote.setPlayer(player);
    Assert.notNull(vote.getVotingSubject(), "You must specify a subject");
    List<Error> errors = ableToVote(player, vote.getVotingSubject().getId());
    if (vote.getVotingAnswers() == null) {
        vote.setVotingAnswers(Collections.emptySet());
    }
    VotingSubject subject = votingSubjectRepository.findById(vote.getVotingSubject().getId()).orElseThrow(() -> new IllegalArgumentException("Subject of vote not found"));
    vote.getVotingAnswers().forEach(votingAnswer -> {
        VotingChoice votingChoice = votingAnswer.getVotingChoice();
        VotingChoice one = votingChoiceRepository.findById(votingChoice.getId()).orElseThrow(() -> new ApiException(new Error(ErrorCode.VOTING_CHOICE_DOES_NOT_EXIST, votingChoice.getId())));
        votingAnswer.setVotingChoice(one);
        votingAnswer.setVote(vote);
    });
    subject.getVotingQuestions().forEach(votingQuestion -> {
        List<VotingAnswer> votingAnswers = vote.getVotingAnswers().stream().filter(votingAnswer -> votingAnswer.getVotingChoice().getVotingQuestion().equals(votingQuestion)).collect(Collectors.toList());
        long countOfAnswers = votingAnswers.size();
        int maxAnswers = votingQuestion.getMaxAnswers();
        if (maxAnswers < countOfAnswers) {
            errors.add(new Error(ErrorCode.TOO_MANY_ANSWERS, countOfAnswers, maxAnswers));
        }
        if (votingQuestion.isAlternativeQuestion()) {
            for (int i = 0; i < countOfAnswers; i++) {
                int finalI = i;
                long answersWithOrdinal = votingAnswers.stream().filter(votingAnswer -> Objects.equals(votingAnswer.getAlternativeOrdinal(), finalI)).count();
                if (answersWithOrdinal == 1) {
                    continue;
                }
                errors.add(new Error(ErrorCode.MALFORMATTED_ALTERNATIVE_ORDINALS));
            }
        }
    });
    if (!errors.isEmpty()) {
        throw new ApiException(errors.toArray(new Error[0]));
    }
    voteRepository.save(vote);
}
Also used : Error(com.faforever.api.error.Error) ErrorCode(com.faforever.api.error.ErrorCode) VotingAnswer(com.faforever.api.data.domain.VotingAnswer) Transactional(javax.transaction.Transactional) ApiException(com.faforever.api.error.ApiException) GamePlayerStatsRepository(com.faforever.api.game.GamePlayerStatsRepository) Vote(com.faforever.api.data.domain.Vote) Player(com.faforever.api.data.domain.Player) Collectors(java.util.stream.Collectors) VotingChoice(com.faforever.api.data.domain.VotingChoice) ArrayList(java.util.ArrayList) Objects(java.util.Objects) List(java.util.List) OffsetDateTime(java.time.OffsetDateTime) Validity(com.faforever.api.data.domain.Validity) Service(org.springframework.stereotype.Service) Optional(java.util.Optional) VotingSubject(com.faforever.api.data.domain.VotingSubject) Collections(java.util.Collections) Assert(org.springframework.util.Assert) VotingAnswer(com.faforever.api.data.domain.VotingAnswer) Error(com.faforever.api.error.Error) VotingSubject(com.faforever.api.data.domain.VotingSubject) VotingChoice(com.faforever.api.data.domain.VotingChoice) ApiException(com.faforever.api.error.ApiException) Transactional(javax.transaction.Transactional)

Example 9 with VotingChoice

use of com.faforever.api.data.domain.VotingChoice in project faf-java-api by FAForever.

the class VotingSubjectEnricher method getWinners.

private List<VotingChoice> getWinners(VotingQuestion votingQuestion) {
    if (!votingQuestion.isAlternativeQuestion()) {
        OptionalInt max = votingQuestion.getVotingChoices().stream().mapToInt(value -> value.getVotingAnswers().size()).max();
        if (max.isPresent()) {
            return votingQuestion.getVotingChoices().stream().filter(votingChoice -> votingChoice.getVotingAnswers().size() == max.getAsInt()).collect(toList());
        }
        return Collections.emptyList();
    }
    // All the answers sorted by their choice, but only those that are the 1st choice
    Map<VotingChoice, List<VotingAnswer>> votersByChoice = votingQuestion.getVotingChoices().stream().collect(Collectors.toMap(Function.identity(), choice -> new ArrayList<>(choice.getVotingAnswers().stream().filter(votingAnswer -> votingAnswer.getAlternativeOrdinal() == 0).collect(toList()))));
    while (votersByChoice.size() > 1) {
        OptionalInt min = votersByChoice.values().stream().mapToInt(List::size).min();
        List<VotingChoice> candidatesToEliminate = votersByChoice.entrySet().stream().filter(votingChoiceListEntry -> votingChoiceListEntry.getValue().size() == min.getAsInt()).map(Entry::getKey).collect(toList());
        if (candidatesToEliminate.size() == votersByChoice.size()) {
            // We got a problem here, we would eliminate all the candidates if we went on normally
            return candidatesToEliminate;
        }
        candidatesToEliminate.forEach(candidate -> {
            List<VotingAnswer> votingAnswersForCandidate = votersByChoice.get(candidate);
            // Lets distribute the answers of the candidate that is eliminated
            votingAnswersForCandidate.forEach(votingAnswer -> {
                int newAlternativeOrdinal = votingAnswer.getAlternativeOrdinal() + 1;
                votingAnswer.getVote().getVotingAnswers().stream().filter(votingAnswer1 -> votingAnswer1.getVotingChoice().getVotingQuestion().equals(votingAnswer.getVotingChoice().getVotingQuestion()) && votingAnswer1.getAlternativeOrdinal() == newAlternativeOrdinal).findFirst().ifPresent(votingAnswer1 -> {
                    VotingChoice votingChoice1 = votingAnswer1.getVotingChoice();
                    votersByChoice.get(votingChoice1).add(votingAnswer1);
                });
            });
            votersByChoice.remove(candidate);
        });
    }
    Optional<Entry<VotingChoice, List<VotingAnswer>>> first = votersByChoice.entrySet().stream().findFirst();
    return first.map(votingChoiceListEntry -> Collections.singletonList(votingChoiceListEntry.getKey())).orElse(Collections.emptyList());
}
Also used : PreUpdate(javax.persistence.PreUpdate) VotingAnswer(com.faforever.api.data.domain.VotingAnswer) VotingQuestion(com.faforever.api.data.domain.VotingQuestion) OptionalInt(java.util.OptionalInt) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) VotingChoice(com.faforever.api.data.domain.VotingChoice) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) Component(org.springframework.stereotype.Component) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) OffsetDateTime(java.time.OffsetDateTime) PostLoad(javax.persistence.PostLoad) Map(java.util.Map) MessageSourceAccessor(org.springframework.context.support.MessageSourceAccessor) Entry(java.util.Map.Entry) Optional(java.util.Optional) VotingSubject(com.faforever.api.data.domain.VotingSubject) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) Entry(java.util.Map.Entry) VotingAnswer(com.faforever.api.data.domain.VotingAnswer) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) OptionalInt(java.util.OptionalInt) VotingChoice(com.faforever.api.data.domain.VotingChoice)

Example 10 with VotingChoice

use of com.faforever.api.data.domain.VotingChoice in project faf-java-api by FAForever.

the class VotingSubjectEnricher method calculateWinners.

@VisibleForTesting
void calculateWinners(VotingQuestion votingQuestion) {
    VotingSubject votingSubject = votingQuestion.getVotingSubject();
    boolean ended = votingSubject.getEndOfVoteTime().isBefore(OffsetDateTime.now());
    List<VotingChoice> winners = votingQuestion.getWinners();
    if ((winners == null || winners.isEmpty()) && ended && votingSubject.getRevealWinner()) {
        votingQuestion.setWinners(getWinners(votingQuestion));
    } else {
        votingQuestion.setWinners(Collections.emptyList());
    }
}
Also used : VotingSubject(com.faforever.api.data.domain.VotingSubject) VotingChoice(com.faforever.api.data.domain.VotingChoice) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

VotingChoice (com.faforever.api.data.domain.VotingChoice)10 VotingSubject (com.faforever.api.data.domain.VotingSubject)9 VotingQuestion (com.faforever.api.data.domain.VotingQuestion)8 Player (com.faforever.api.data.domain.Player)7 Vote (com.faforever.api.data.domain.Vote)7 Test (org.junit.Test)7 VotingAnswer (com.faforever.api.data.domain.VotingAnswer)6 ApiException (com.faforever.api.error.ApiException)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 OffsetDateTime (java.time.OffsetDateTime)2 ArrayList (java.util.ArrayList)2 Collections (java.util.Collections)2 List (java.util.List)2 Optional (java.util.Optional)2 Collectors (java.util.stream.Collectors)2 AbstractIntegrationTest (com.faforever.api.AbstractIntegrationTest)1 Validity (com.faforever.api.data.domain.Validity)1 Error (com.faforever.api.error.Error)1 ErrorCode (com.faforever.api.error.ErrorCode)1 GamePlayerStatsRepository (com.faforever.api.game.GamePlayerStatsRepository)1