public async Task <ActionResult <List <LocationData> > > GetCountries([FromQuery] int?ballotId) { try { var result = await _territoryRepository.GetCountries(ballotId); if (result.IsSuccess) { return(result.Value.Select(c => new LocationData { Id = c.Id, Name = c.Name }).ToList()); } return(StatusCode(500, result.Error)); } catch (Exception e) { return(StatusCode(500, e.Message)); } }
public async Task <Result <List <ElectionMapWinner> > > GetCountryWinners(int ballotId) { var parties = await _partiesRepository.GetAllParties(); var dbWinners = await GetWinners(ballotId, null, ElectionDivision.Diaspora_Country); if (dbWinners.Count > 0) { return(dbWinners.Select(winner => WinnerToElectionMapWinner(winner, parties.ToList())).ToList()); } _appCache.Remove(MemoryCache.CreateWinnersKey(ballotId, null, ElectionDivision.Diaspora_Country)); var winners = new List <ElectionMapWinner>(); var countries = await _territoryRepository.GetCountries(null); if (countries.IsFailure) { return(Result.Failure <List <ElectionMapWinner> >(countries.Error)); } var ballot = await _dbContext.Ballots .Include(b => b.Election) .FirstOrDefaultAsync(b => b.BallotId == ballotId); var candidateResultsByCountries = await _dbContext.CandidateResults .Include(c => c.Party) .Where(c => c.BallotId == ballotId && c.Division == ElectionDivision.Diaspora_Country) .ToListAsync(); var turnouts = await _dbContext.Turnouts .Where(c => c.BallotId == ballotId && c.Division == ElectionDivision.Diaspora_Country) .ToListAsync(); List <Winner> winningCandidates = new List <Winner>(); foreach (var country in countries.Value) { var countryWinner = candidateResultsByCountries .Where(c => c.CountryId == country.Id) .OrderByDescending(c => c.Votes) .FirstOrDefault(); var turnoutForCountry = turnouts .FirstOrDefault(c => c.CountryId == country.Id); if (countryWinner == null || turnoutForCountry == null) { continue; } var electionMapWinner = CreateElectionMapWinner(country.Id, ballot, countryWinner, turnoutForCountry); if (electionMapWinner.Winner.PartyColor.IsEmpty()) { electionMapWinner.Winner.PartyColor = parties.ToList().GetMatchingParty(countryWinner.ShortName)?.Color ?? Consts.IndependentCandidateColor; } winners.Add(electionMapWinner); winningCandidates.Add(CreateWinner(ballot, countryWinner, electionMapWinner, turnoutForCountry.Id, country.Id, ElectionDivision.Diaspora_Country)); } await SaveWinners(winningCandidates); return(Result.Success(winners)); }