public async Task Should_Save_AuthorityVotes() { var model = new AuthorityPollSaveViewModel { PollId = 1, Votes = new List <AuthorityPollUserValues> { new AuthorityPollUserValues { UserId = 2.ToString(), Value = 500 }, new AuthorityPollUserValues { UserId = 3.ToString(), Value = 500 } } }; await _pollApiViewModelService.SaveAuthorityVote(model, "1"); var result = _context.Votes.Where(x => x.PollId == model.PollId); Assert.Equal(2, result.Count()); }
public async Task <IActionResult> Vote([FromBody] AuthorityPollSaveViewModel model) { if (ModelState.IsValid) { var voterId = User.ApiGetUserId(); var poll = await _pollService.GetPoll(model.PollId); if (poll == null) { ModelState.AddModelError("", _localizer["PollNotFound"]); return(BadRequest(Errors.GetErrorList(ModelState))); } if (poll.GetType() != typeof(AuthorityPoll)) { return(BadRequest(Errors.GetSingleErrorList("", _localizer["PollTypeNotAuthority"]))); } if (!poll.Active) { ModelState.AddModelError("", _localizer["PollCompleted"]); return(BadRequest(Errors.GetErrorList(ModelState))); } if (!await _pollService.UserCanVote(poll.Id, voterId)) { return(BadRequest(Errors.GetSingleErrorList("", _localizer["UserCannotVoteAfterAddedPollStart"]))); } var userVoted = await _voteService.UserVotedInPoll(voterId, model.PollId); if (userVoted) { ModelState.AddModelError("", _localizer["PollRecordExist"]); return(BadRequest(Errors.GetErrorList(ModelState))); } if (model.Votes.Any(v => v.Value < 0 || v.Value > 1000 || v.UserId == voterId)) { ModelState.AddModelError("", _localizer["AuthorityPollInvalidVoteError"]); return(BadRequest(Errors.GetErrorList(ModelState))); } if (model.Votes.Sum(v => v.Value) != 1000) { ModelState.AddModelError("", _localizer["AuthorityPollSumError"]); return(BadRequest(Errors.GetErrorList(ModelState))); } await _pollViewModelService.SaveAuthorityVote(model, voterId); var result = _mapper.Map <Poll, PollListViewModel>(poll); result.UserVoted = true; return(Ok(result)); } return(BadRequest(Errors.GetErrorList(ModelState))); }