public async Task <IActionResult> CastVote(AddVoteVM vote) { if (vote == null || !ModelState.IsValid) { return(BadRequest()); } try { //if voter is valid and he/she does not cast vote for same catergory before var isVoteAlreadyCasted = await this._voteService.IsVoteCastForCategoryByVoter(vote.VoterId, vote.CandidateCategoryId); if (isVoteAlreadyCasted) { return(UnprocessableEntity("You already cast vote for this category")); } var IsValidUser = await this._voteService.IsVoterAndCandidateIsValid(vote.VoterId, vote.CandidateId, vote.CandidateCategoryId); if (!IsValidUser.VoterExist) // voter is not a valid { return(StatusCode(StatusCodes.Status404NotFound, "Voter does not associate with VoterSystem application, please register to cast vote")); } if (!IsValidUser.CandidateExist) // candidate is not a valid { return(StatusCode(StatusCodes.Status404NotFound, "Candidate selected is not valid, please recheck and try again")); } // now candidate and voter both are valid. var IsVoteCasted = await this._voteService.CastAVote(vote.ToVote()); var status = IsVoteCasted == true ? "Thanks for voting. Your vote is succcessfully cast!" : "Unexpected error in voting system, please retry after 1 minute time"; return(CreatedAtAction(nameof(CastVote), status)); } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message)); } }
public static Vote ToVote(this AddVoteVM viewModel) => new Vote { CandidateCategoryId = viewModel.CandidateCategoryId, CandidateId = viewModel.CandidateId, VoterId = viewModel.VoterId };