Example #1
0
        public async Task <IActionResult> Create(ElectionCreateViewModel electionViewModel)
        {
            var candidatesSelectedId = (string[])TempData[Configuration.CandidatesElectionCreateSelected];

            if (ModelState.IsValid)
            {
                var candidatesSelected = await _candidateService.GetCandidates().Include(c => c.Position).Where(c => candidatesSelectedId.Contains(c.Id.ToString())).ToListAsync();

                var postitionSelected = candidatesSelected.Select(c => c.Position).Distinct().ToList();

                if (postitionSelected.Count() < 4)
                {
                    ViewBag.Message = "Debe seleccionar candidatos para 4 posiciones electorales diferentes para poder iniciar un proceso electoral.";
                    var allcandidates = await _candidateService.GetCandidates().Where(c => c.IsActive == true).Include(c => c.Position).Include(c => c.PoliticParty).OrderBy(c => c.Position.Name).ToListAsync();

                    electionViewModel.ElectionCadidate = (_mapper.Map <List <Candidate>, List <CandidateElectionViewModel> >(allcandidates)).GroupBy(c => c.Position.Name).ToList();
                    return(View(electionViewModel));
                }

                var candidatesSelectedGroupByPosition = candidatesSelected.GroupBy(c => c.Position.Name).Where(c => c.Count(cc => cc.Name != "NULL") > 1 && c.Any(cn => cn.Name == "NULL"));

                if (postitionSelected.Count() != candidatesSelectedGroupByPosition.Count())
                {
                    ViewBag.Message = "Debe seleccionar almenos 2 candidatos y el candidato NULL  por cada posicion electoral para poder iniciar un proceso de eleccion.";
                    var allcandidates = await _candidateService.GetCandidates().Where(c => c.IsActive == true).Include(c => c.Position).Include(c => c.PoliticParty).OrderBy(c => c.Position.Name).ToListAsync();

                    electionViewModel.ElectionCadidate = (_mapper.Map <List <Candidate>, List <CandidateElectionViewModel> >(allcandidates)).GroupBy(c => c.Position.Name).ToList();
                    return(View(electionViewModel));
                }

                Election election = _mapper.Map <ElectionCreateViewModel, Election>(electionViewModel);
                Election result   = await _electionService.InsertElectionAsync(election, candidatesSelected, postitionSelected);

                if (result != null)
                {
                    return(RedirectToAction(nameof(ElectionsList)));
                }
                ModelState.AddModelError("", "Ocurrion un erro al insertar la eleccion.");
            }
            return(View(electionViewModel));
        }