public async Task <RateResponse> AddRatingForDishAsync(AddRatingDto addRatingDto, int userId)
        {
            var rating = await _unitOfWork.Ratings.FindAsync((userId, addRatingDto.DishId));

            double oldRate = 0;

            if (rating != null)
            {
                oldRate     = rating.Rate;
                rating.Rate = addRatingDto.Rate;
            }
            else
            {
                var newRating = _mapper.Map <Rating>(addRatingDto);

                newRating.UserId = userId;
                _unitOfWork.Ratings.Add(newRating);
            }

            await _unitOfWork.CommitAsync();

            return(new RateResponse()
            {
                IsNewRate = rating == null,
                OldRate = oldRate
            });
        }
Ejemplo n.º 2
0
        public async Task <ActionResult <RatingDto> > AddRating(AddRatingDto addRatingDto, CancellationToken token = default)
        {
            var userId = RetrieveUserId().ToString();

            var user = await userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(BadRequest("No such user."));
            }

            var movie = await Context.Movies.Include(x => x.Ratings)
                        .FirstOrDefaultAsync(x => x.Id == addRatingDto.MovieId, token);

            if (movie == null)
            {
                return(NotFound("Movie not found."));
            }

            var rating = await Context.Ratings
                         .SingleOrDefaultAsync(x => x.User == user && x.Movie == movie, token);

            // If user is trying to add a rating that he has already added
            if (rating != null)
            {
                return(Conflict("User has already rated the movie."));
            }

            movie.AverageRating = (movie.Ratings.Sum(x => x.Rate) + addRatingDto.Rate) / (movie.Ratings.Count + 1);
            rating = new Rating {
                Movie = movie, User = user, Rate = addRatingDto.Rate, Review = addRatingDto.Review
            };

            Context.Ratings.Add(rating);

            await Context.SaveChangesAsync(token);

            return(CreatedAtAction(nameof(GetRating), new { id = rating.Id }, Mapper.Map <Rating, RatingDto>(rating)));
        }
 public async Task <IActionResult> AddRating(AddRatingDto addRatingDto)
 {
     return(Ok(await _ratingService.AddRatingForDishAsync(addRatingDto, this.GetContactId())));
 }