Exemple #1
0
        public IHttpActionResult CreateRental(MovieRentalDto movieRental)
        {
            var customer = db.Customers.Find(movieRental.CustomerId);

            foreach (var movieId in movieRental.MovieId)
            {
                var movie = db.Movies.Find(movieId);
                if (movie == null)
                {
                    throw new Exception(HttpStatusCode.BadRequest.ToString());
                }

                var movieRentalObj = new MovieRental();
                movieRentalObj.Customers        = customer;
                movieRentalObj.Movies           = movie;
                movieRentalObj.Movies.Available = movieRentalObj.Movies.Available - 1;
                movieRentalObj.RentalDate       = DateTime.Now;

                db.MovieRentals.Add(movieRentalObj);
            }

            db.SaveChanges();

            return(Ok());
        }
Exemple #2
0
        public IHttpActionResult CreateNewRental(MovieRentalDto newRental)
        {
            var customer = _context.Customers.Single(c => c.Id == newRental.CustomerId);
            var movies   = _context.Movies.Where(m => newRental.MovieIds.Contains(m.Id)).ToList();

            foreach (var movie in movies)
            {
                if (movie.NumberAvailable == 0)
                {
                    return(BadRequest("Movie is not available"));
                }

                movie.NumberAvailable--;

                var rental = new MovieRental
                {
                    Customers = customer,
                    Movies    = movie,
                    DateAdded = DateTime.Now
                };
                _context.MovieRental.Add(rental);
            }
            _context.SaveChanges();

            return(Ok());
        }
        public RentResponse RentMovie(Customer customer, Movie movie)
        {
            if (customer.MovieRentals.FirstOrDefault(r => r.MovieId == movie.Id && r.EndDate > DateTime.Now) != null)
            {
                throw new MovieAlreadyRentedException("Movie already rented.");
            }

            if (customer.MoviePurchases.Select(r => r.MovieId).Contains(movie.Id))
            {
                throw new MovieAlreadyPurchasedException("Movie already purchased.");
            }

            if (!paymentService.Rent(customer))
            {
                InvalidateCustomerCreditCard(customer);

                throw new PaymentFailedException(
                          $"Payment failed for customer {customer.FullName.ToString()}. " +
                          "Please check and update your credit card details."
                          );
            }

            var movieRental = MovieRental.Create(customer, movie, DateTime.Now.AddDays(RentalDays));

            customersRepository.AddMovieRental(movieRental);

            var movieStream = streamingService.GetMovieStream(movie);

            return(new RentResponse(movieRental, movieStream));
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,UserId,MovieId,RentDate,EndDate,Duration,TotalPrice")] MovieRental movieRental)
        {
            if (id != movieRental.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(movieRental);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!MovieRentalExists(movieRental.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["MovieId"] = new SelectList(_context.Movies, "Id", "Title", movieRental.MovieId);
            ViewData["UserId"]  = new SelectList(_context.Users, "Id", "FullName", movieRental.UserId);
            return(View(movieRental));
        }
        public async Task <IActionResult> Create([Bind("Id,UserId,MovieId,RentDate,EndDate,Duration,TotalPrice")] MovieRental movieRental)
        {
            // xử lý logic đầu vào


            if (movieRental.Duration != TimeSpan.Zero)                              // Từ Duration tính EndDate
            {
                movieRental.EndDate = movieRental.RentDate + movieRental.Duration;
            }
            else if (movieRental.EndDate != default(DateTime) && movieRental.EndDate != null)                      // Từ EndDate tính Duration
            {
                movieRental.Duration = (TimeSpan)(movieRental.EndDate - movieRental.RentDate);
            }
            var tMovie = _context.Movies.Where(m => m.Id == movieRental.MovieId).First();

            movieRental.TotalPrice = tMovie.Price * movieRental.Duration.Days; // Duration.Days : chuyển Duration về dạng int số ngày


            if (ModelState.IsValid && (movieRental.Duration != TimeSpan.Zero || (movieRental.EndDate != default(DateTime) && movieRental.EndDate != null)))
            {
                _context.Add(movieRental);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["MovieId"] = new SelectList(_context.Movies, "Id", "Title", movieRental.MovieId);
            ViewData["UserId"]  = new SelectList(_context.Users, "Id", "FullName", movieRental.UserId);
            return(View(movieRental));
        }
        // POST api/<controller>
        public IHttpActionResult Post(MovieRentalsDto movieRentalDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }



            if (movieRentalDto.MoviesId.Count == 0)
            {
                return(BadRequest("List of movies is empty"));
            }

            var customer = _context.Customers.SingleOrDefault(c => c.Id == movieRentalDto.CustomerId);

            if (customer == null)
            {
                return(BadRequest("Customer ID is invalid"));
            }

            var movies = _context.Movies.Where(m => movieRentalDto.MoviesId.Contains(m.Id)).ToList();

            if (movies.Count != movieRentalDto.MoviesId.Count)
            {
                return(BadRequest("One or more movies are invalid"));
            }

            var customerRentalLimit    = customer.MaxRentMoviesAtOnce;
            var moviesRentedByCustomer = _context.MovieRentals
                                         .Where(m => m.Customer.Id == customer.Id &&
                                                m.DateReturned == null).Count();

            if (movieRentalDto.MoviesId.Count + moviesRentedByCustomer > customerRentalLimit)
            {
                return(BadRequest("Customer Movies Rented is Up to Limit"));
            }


            MovieRental movieRental;

            foreach (Movie movie in movies)
            {
                if (movie.Avaliable == 0)
                {
                    return(BadRequest("Movie is not avaliable."));
                }

                movie.Avaliable--;
                movieRental            = new MovieRental();
                movieRental.Customer   = customer;
                movieRental.Movie      = movie;
                movieRental.DateRented = DateTime.Now;
                _context.MovieRentals.Add(movieRental);
            }
            _context.SaveChanges();

            return(Ok());
        }
            public void Setup()
            {
                OurCustomer = new SecretShopperCustomer();
                Context();

                TheRental = new MovieRental(RentalPeriod, PriceCode);

                Because();
            }
        public Customer AddMovieRental(MovieRental movieRental)
        {
            var customer = context.Customers.Find(movieRental.CustomerId);

            customer.AddMovieRental(movieRental);

            context.Add(movieRental);
            context.SaveChanges();

            return(customer);
        }
Exemple #9
0
        public ActionResult Index()
        {
            var username = (string)Session["Username"];

            if (username == null || (bool)Session["LoggedIn"] != true)
            {
                return(RedirectToRoute(new
                {
                    controller = "Home",
                    action = "LogInModal"
                }));
            }

            try
            {
                var result   = _movieOrdersLogic.GetUserMovieOrders(username);
                var myMovies = new List <MovieRental>();

                foreach (var entry in result)
                {
                    var movieRental = new MovieRental()
                    {
                        RentedMovieId = entry.RentedMovieId
                    };

                    var movie = _moviesLogic.GetMovie(movieRental.RentedMovieId);

                    var newRentedMovie = new Movie()
                    {
                        Title      = movie.Title,
                        Year       = movie.Year,
                        Rated      = movie.Rated,
                        Runtime    = movie.Runtime,
                        Genre      = movie.Genre,
                        Director   = movie.Director,
                        Plot       = movie.Plot,
                        Poster     = movie.Poster,
                        ImdbRating = movie.ImdbRating,
                        ScreenShot = movie.ScreenShot
                    };

                    movieRental.RentedMovie = newRentedMovie;

                    myMovies.Add(movieRental);
                }

                return(View(myMovies));
            }
            catch (Exception)
            {
                return(View("ErrorPage"));
            }
        }
        public void MovieRentalGetsThreeDayLaterDueDate()
        {
            MovieRental r = new MovieRental();

            r.movieTitle = "Die HArd";
            r.dueDate    = DateTime.Now.AddDays(3);
            testCustomer.SocialSecurityNumber = "123";

            sut.AddRental(r.movieTitle, testCustomer.SocialSecurityNumber);

            Assert.AreEqual(DateTime.Now.AddDays(3).Date, r.dueDate.Date);
        }
Exemple #11
0
        // GET: Movies
        public ActionResult Random()
        {
            MovieRental model = new MovieRental(movie, clients);

            /*MovieRental model = new MovieRental()
             * {
             *  Movie =  movie,
             *  Clients = clients
             * };*/
//            model.Movie = movie;
//            model.Clients = clients;
            return(View(model));
        }
        public IHttpActionResult CreateNewMovieRentals(NewRentalDto newRental)
        {
            if (newRental.MovieIds.Count == 0)
            {
                return(BadRequest("No Movie Ids have been given"));
            }

            Customer customer = _context.Customers.SingleOrDefault(
                c => c.Id == newRental.CustomerId);

            if (customer == null)
            {
                return(BadRequest("Customer Id is not valid"));
            }



            var movies = _context.Movies.Where(
                m => newRental.MovieIds.Contains(m.Id)).ToList();

            if (movies.Count != newRental.MovieIds.Count)
            {
                return(BadRequest("One or more Movie Ids are invalid."));
            }


            foreach (Movie movie in movies)
            {
                if (movie.NumberAvailable == 0)
                {
                    return(BadRequest("Movie is not available."));
                }

                movie.NumberAvailable--;

                MovieRental rental = new MovieRental
                {
                    Customer   = customer,
                    Movie      = movie,
                    DateRented = DateTime.Now
                };
                _context.MovieRentals.Add(rental);
            }

            _context.SaveChanges();
            return(Ok());
        }
Exemple #13
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            MovieRental = await _context.MovieRental
                          .Include(m => m.customer)
                          .Include(m => m.movie).FirstOrDefaultAsync(m => m.Id == id);

            if (MovieRental == null)
            {
                return(NotFound());
            }
            return(Page());
        }
Exemple #14
0
        public async Task <IActionResult> OnPostAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            MovieRental = await _context.MovieRental.FindAsync(id);

            if (MovieRental != null)
            {
                _context.MovieRental.Remove(MovieRental);
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("./Index"));
        }
        public void FinishRental(MovieRental movieRental)
        {
            var customer = context.Customers
                           .Include(c => c.MovieRentals)
                           .Where(c => c.Id == movieRental.CustomerId)
                           .First();

            customer.MovieRentals = customer.MovieRentals.Select(r =>
            {
                if (r == movieRental)
                {
                    r.EndDate = DateTime.Now;
                }
                return(r);
            }).ToList();

            context.SaveChanges();
        }
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            MovieRental = await _context.MovieRental
                          .Include(m => m.customer)
                          .Include(m => m.movie).FirstOrDefaultAsync(m => m.Id == id);

            if (MovieRental == null)
            {
                return(NotFound());
            }
            // replace ID value with FullName and Title to be display in the dropdown menu
            ViewData["CustomerFK"] = new SelectList(_context.Customer, "Id", "FullName");
            ViewData["MovieFK"]    = new SelectList(_context.Movie, "Id", "Title");
            return(Page());
        }
        public async Task <MovieRentalDTO> CreateMovieRentalAsync(CreateMovieRentalInputModel inputModel, CancellationToken cancellationToken = default)
        {
            inputModel.EnsureIsValid();

            var movie = await _repository.Query <Movie>().FirstOrDefaultAsync(c => c.Id == inputModel.MovieId, cancellationToken);

            if (movie is null)
            {
                throw new BusinessException("Movie sented not exist");
            }

            var customer = await _repository.Query <Customer>().FirstOrDefaultAsync(c => c.Id == inputModel.CustomerId, cancellationToken);

            if (customer is null)
            {
                throw new BusinessException("Customer sented not exist");
            }

            var movieRental = await _repository.Query <MovieRental>().FirstOrDefaultAsync(c => c.MovieId == inputModel.MovieId && c.ReturnedAt == null, cancellationToken);

            if (movieRental != null)
            {
                throw new BusinessException("Movie not available to rent.");
            }

            movieRental = new MovieRental(inputModel.DaysInRental, inputModel.MovieId, inputModel.CustomerId)
            {
                DaysInRental = inputModel.DaysInRental
            };

            await _repository.AddAsync(movieRental, cancellationToken);

            return(new MovieRentalDTO()
            {
                Id = movieRental.Id,
                MovieId = movieRental.MovieId,
                CustomerId = movieRental.CustomerId,
                ReturnedAt = movieRental.ReturnedAt,
                DaysInRental = movieRental.DaysInRental
            });
        }
Exemple #18
0
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Movie Rental Input System");
                MovieRental rental = new MovieRental();
                rental.MovieInput();

                Console.WriteLine("How many returns will be entered?");
                int customerReturns = Convert.ToInt32(Console.ReadLine());

                for (int i = 1; i <= customerReturns; i++)
                {
                    MovieRental rental2 = new MovieRental();
                    rental2.ReturnedMovies();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadLine();
            }
        }
Exemple #19
0
 public RentResponse(MovieRental movieRental, string movieStream)
 {
     MovieRental = movieRental;
     MovieStream = movieStream;
 }
        public void SaveNewRental(int memberCode, List <int> movieCodes)
        {
            // Validate max number of movies:
            if (movieCodes.Count > 4)
            {
                throw new Exception("User can't rent more than 4 movies");
            }

            using (var db = new VideoClubDbContext())
            {
                // Validate if user has movies to be returned
                if (db.MovieRentals.Any(rental => rental.MemberCode == memberCode && rental.Returned == null))
                {
                    throw new Exception("User can't rent more movies because has movies to be returned");
                }

                // Check if user has already rented any of the movies
                var userPreviousRentals =
                    db.MovieRentals
                    .Where(rental => rental.MemberCode == memberCode && movieCodes.Contains(rental.MovieCode))
                    .Select(rental => rental.Movie);

                if (userPreviousRentals.Any())
                {
                    var friendlyMessage = "User already rent the following movies in the past and can't rent them again:";
                    foreach (var movie in userPreviousRentals)
                    {
                        friendlyMessage += Environment.NewLine + movie.Name;
                    }
                    throw new Exception(friendlyMessage);
                }

                // Check stock
                var movies = db.Movies.Where(movie => movieCodes.Contains(movie.Code)).ToList();

                if (movies.Any(movie => movie.Copies <= 0))
                {
                    var friendlyMessage = "The following movies can't be rented because they have no stock:";
                    foreach (var movie in movies)
                    {
                        friendlyMessage += Environment.NewLine + movie.Name;
                    }
                    throw new Exception(friendlyMessage);
                }

                // Calculate deadline date
                var daysToReturn = 2; // Default for 1 movie;
                if (movieCodes.Count > 3)
                {
                    daysToReturn = 6;
                }
                else if (movieCodes.Count > 1)
                {
                    daysToReturn = 4;
                }

                // Rent the movies
                foreach (var movie in movies)
                {
                    var newRental = new MovieRental();
                    newRental.MemberCode = memberCode;
                    newRental.MovieCode  = movie.Code;
                    newRental.Rented     = DateTime.Now;
                    newRental.Deadline   = DateTime.Now.AddDays(daysToReturn);
                    db.MovieRentals.Add(newRental);

                    // Fix movie stock
                    movie.Copies--;
                }

                // Save all changes both on rentals and movies
                db.SaveChanges();
            }
        }