Exemplo n.º 1
0
 def __write_round_to_database(
     self,
     db_session: DbSession,
     election_id: str,
     votes: List[Tuple[str, int]],
     round: int,
     affected_candidate: str,
     candidate_round_action: RoundAction,
 ):
     db_session.add(Round(election_id=election_id, round_number=round))
     db_session.flush()
     db_session.add_all(
         [
             CandidateRoundResult(
                 election_id=election_id,
                 round_number=round,
                 business_id=candidate_id,
                 number_of_rank_one_votes=number_of_rank_one_votes_for_candidate,
                 round_action=None
                 if candidate_id != affected_candidate
                 else candidate_round_action,
             )
             for candidate_id, number_of_rank_one_votes_for_candidate in votes
         ]
     )
     db_session.flush()
Exemplo n.º 2
0
    def vote(self, user_id: str, election_id: str, votes: [str]):
        db_session = DbSession()
        partial_election = Election.get_election_by_id(
            db_session,
            election_id,
            query_modifier=lambda x: x.options(
                load_only(Election.id, Election.election_status)),
        )

        if partial_election is None:
            raise HttpException(
                message=f"Election with id: {election_id} not found",
                status_code=404)

        if partial_election.election_status != ElectionStatus.VOTING:
            raise InvalidElectionStateException(
                f"Cannot vote unless election is in voting status. Current status: {partial_election.election_status.name}"
            )

        candidate_ids = set([
            candidate.business_id for candidate in partial_election.candidates
        ])
        for business_id in votes:
            if business_id not in candidate_ids:
                raise HttpException(
                    message=f"Unknown or duplicate candidate id {business_id}",
                    status_code=404,
                )
            candidate_ids.remove(business_id)

        if len(candidate_ids) > 0:
            raise HttpException(
                message=
                f"Missing votes for candidates: {', '.join(candidate_ids)}",
                status_code=400,
            )

        rankings = [
            Ranking(
                user_id=user_id,
                election_id=election_id,
                business_id=business_id,
                rank=index,
            ) for index, business_id in enumerate(votes)
        ]
        Ranking.delete_users_rankings_for_election(db_session,
                                                   user_id=user_id,
                                                   election_id=election_id)
        db_session.add_all(rankings)
        db_session.commit()

        self.__queue_election_for_result_update(election=partial_election)