Ejemplo n.º 1
0
        public void ShouldCreateBookingByCabType()
        {
            var pickupLocation       = new GeoCoordinate(12.99711, 77.61469);
            var bookingRepo          = new Mock <IBookingRepository>();
            var availableCabsService = new Mock <IAvailableCabsService>();
            var availableCab         = new Domain.Cab("3", "Toyota Etios", CabType.Pink);

            availableCabsService.Setup(a => a.GetNearestCab(pickupLocation, new[] { CabType.Pink })).Returns(availableCab);

            var bookingService       = new BookingService(bookingRepo.Object, availableCabsService.Object);
            var createBookingRequest = new CreateBookingRequest()
            {
                PickupLocation = pickupLocation,
                Destination    = new GeoCoordinate(13, 77),
                Time           = DateTime.Now,
                UserId         = "1",
                CabType        = "Pink"
            };
            var booking = bookingService.CreateBooking(createBookingRequest);

            Assert.That(booking != null);
            Assert.That(booking.CabId == availableCab.Id);
            Assert.That(booking.UserId == createBookingRequest.UserId);
            Assert.That(booking.PickupLocation.Equals(createBookingRequest.PickupLocation));
            Assert.That(booking.Destination.Equals(createBookingRequest.Destination));
            Assert.That(booking.Time.Equals(createBookingRequest.Time));

            availableCabsService.Verify(a => a.GetNearestCab(createBookingRequest.PickupLocation, new[] { CabType.Pink }));
            bookingRepo.Verify(b => b.Save(booking));
        }
Ejemplo n.º 2
0
        public void Create_WhenCorrectData_ShouldReturnSuccessfulResponseWithBookingNumber()
        {
            // Arrange
            var flight           = PrepareFlightDetails();
            var bookingPassenger = new BookingPassenger {
                Name = "Test", DateBirth = DateTime.Now.Date, Gender = Gender.Male, Address = "TestAddress", Email = "*****@*****.**"
            };
            var createBookingRequest = new CreateBookingRequest
            {
                FlightId   = 1,
                Passengers = new List <BookingPassenger> {
                    bookingPassenger
                }
            };

            Mapper.Reset();
            Mapper.Initialize(cfg => cfg.CreateMap <Booking, BookingDto>());

            var mockPersonRepository  = new Mock <IRepository <Person> >();
            var mockBookingRepository = new Mock <IRepository <Booking> >();
            var mockFlightRepository  = new Mock <IRepository <Flight> >();

            mockFlightRepository.Setup(x => x.Get(It.Is <int>(m => m == flight.Id))).Returns(flight);
            mockBookingRepository.Setup(x => x.GetAll()).Returns(new List <Booking>());
            mockPersonRepository.Setup(x => x.GetAll()).Returns(new List <Person>());

            var bookingService = new BookingService(Mapper.Instance, mockPersonRepository.Object, mockBookingRepository.Object, mockFlightRepository.Object);

            // Act
            var expectedCreateBookingResponse = bookingService.CreateBooking(createBookingRequest);

            // Assert
            Assert.IsNotNull(expectedCreateBookingResponse.BookingNumber);
        }
Ejemplo n.º 3
0
        public void Create_WhenFlightDoesNotExsit_ShouldThrowAppropriateException()
        {
            // Arrange
            var expectedErrorMessage = "Flight with specified ID does not exist.";

            var flight           = PrepareFlightDetails();
            var bookingPassenger = new BookingPassenger {
                Name = "Test", DateBirth = DateTime.Now.Date, Gender = Gender.Male, Address = "TestAddress", Email = "*****@*****.**"
            };
            var createBookingRequest = new CreateBookingRequest
            {
                FlightId   = 1,
                Passengers = new List <BookingPassenger> {
                    bookingPassenger
                }
            };

            Mapper.Reset();
            Mapper.Initialize(cfg => cfg.CreateMap <Booking, BookingDto>());

            var mockPersonRepository  = new Mock <IRepository <Person> >();
            var mockBookingRepository = new Mock <IRepository <Booking> >();
            var mockFlightRepository  = new Mock <IRepository <Flight> >();

            mockFlightRepository.Setup(x => x.GetAll()).Returns(new List <Flight>());
            mockBookingRepository.Setup(x => x.GetAll()).Returns(new List <Booking>());
            mockPersonRepository.Setup(x => x.GetAll()).Returns(new List <Person>());

            var bookingService = new BookingService(Mapper.Instance, mockPersonRepository.Object, mockBookingRepository.Object, mockFlightRepository.Object);

            // Act & Assert
            var exception = Assert.Throws <WingsOnNotFoundException>(() => bookingService.CreateBooking(createBookingRequest));

            Assert.AreEqual(exception.Message, expectedErrorMessage);
        }
Ejemplo n.º 4
0
        public ActionResult CreateBooking(int EmployeeID, string username, int escapeRoomID, TimeSpan BookTime, int AmountOfPeople, DateTime BDate)
        {
            BookingService bs = new BookingService();

            bs.CreateBooking(EmployeeID, username, escapeRoomID, BookTime, AmountOfPeople, BDate);
            return(View());
        }
Ejemplo n.º 5
0
        public void ShouldReturnCabToPoolIfCreateBookingFails()
        {
            var pickupLocation = new GeoCoordinate(12.99711, 77.61469);
            var bookingRepo    = new Mock <IBookingRepository>();

            bookingRepo.Setup(b => b.Save(It.IsAny <Domain.Booking>())).Throws <Exception>();
            var availableCabsService = new Mock <IAvailableCabsService>();
            var availableCab         = new Domain.Cab("3", "Toyota Etios", CabType.Pink);

            availableCabsService.Setup(a => a.GetNearestCab(pickupLocation, new CabType[] { CabType.Regular, CabType.Pink })).Returns(availableCab);

            var bookingService       = new BookingService(bookingRepo.Object, availableCabsService.Object);
            var createBookingRequest = new CreateBookingRequest()
            {
                PickupLocation = pickupLocation,
                Destination    = new GeoCoordinate(13, 77),
                Time           = DateTime.Now,
                UserId         = "1"
            };

            Assert.Throws <Exception>(() => bookingService.CreateBooking(createBookingRequest));

            availableCabsService.Verify(a => a.GetNearestCab(createBookingRequest.PickupLocation, new CabType[] { CabType.Regular, CabType.Pink }));
            availableCabsService.Verify(a => a.ReturnCabToPool(availableCab));
        }
Ejemplo n.º 6
0
        private string createBooking(HttpContext context)
        {
            BookingModel        booking = new BookingModel();
            NameValueCollection param   = context.Request.Params;

            booking.CreatedByMemberNodeId = param["create-member-id"];
            booking.ConferenceRoomNodeId  = param["create-conference-room"];
            booking.Title     = param["create-title"];
            booking.StartTime = ParseDateTime(param["create-start-date"]);
            booking.EndTime   = ParseDateTime(param["create-end-date"]);

            BookingStatusViewModel status = new BookingStatusViewModel();

            if (booking.StartTime == DateTime.MinValue || booking.EndTime == DateTime.MinValue)
            {
                status.Status  = "ERROR";
                status.Message = "Dates could not be parsed";
                return(JsonConvert.SerializeObject(status, Formatting.Indented));
            }

            BookingViewModel viewModel = BookingService.CreateBooking(booking);

            viewModel.ClassName = "booked-by-user";
            if (viewModel != null)
            {
                status.Status  = "SUCCESS";
                status.Booking = viewModel;
            }
            else
            {
                status.Status  = "EXCEPTION";
                status.Message = "Something went wrong during creation of booking.";
            }
            return(JsonConvert.SerializeObject(status, Formatting.Indented));
        }
Ejemplo n.º 7
0
        public JsonResult Action(BookingActionViewModel model, bool isDeleted = false)
        {
            JsonResult json   = new JsonResult();
            var        result = false;
            var        msg    = "";

            if (model.Id > 0 && isDeleted == false)
            {
                //edit here

                if (model.Booking != null)
                {
                    result = bookingService.UpdateBooking(model.Booking);
                    msg    = "Booking Edited Successfully";
                }
            }
            else if (model.Id > 0 && isDeleted == true)
            {
                //delete here
                //result = accomodationPackageService.DeleteAccomodationPackages(model.Id);
            }

            else
            {
                //first create object then add
                var fee = accomodationPackagesService.GetAccomodationPackageById(model.AccomodationPackageId).FeePerNight;

                var roomsTotal      = (model.Booking.NoOfAccomodation * fee) * model.Booking.Duration;
                var vatTax          = (5 * roomsTotal) / 100;
                var tourismTax      = 5 * (model.Booking.Duration * model.Booking.NoOfAccomodation);
                var breakFastTotals = 0;

                if (model.Booking.BreakFast == true)
                {
                    breakFastTotals = ((model.Booking.Adult * 7) + (model.Booking.Children * 3)) * model.Booking.Duration;
                }

                var grandTotal = roomsTotal + vatTax + tourismTax + breakFastTotals;


                model.Booking.TotalAmount = grandTotal;
                model.Booking.PaymentInfo.PaymentStatus = grandTotal - model.Booking.PaymentInfo.AmountPaid >= 0 ? "paid" : "unpaid";
                msg    = bookingService.CreateBooking(model.Booking, model.AccomodationPackageId);
                result = true;
            }

            if (result)
            {
                json.Data = new { success = true, Messag = msg };
            }
            else
            {
                json.Data = new { success = false, Messag = "Unable to Perform Operation in Accomodation Type." };
            }

            return(json);
        }
Ejemplo n.º 8
0
        public async Task CreateBooking_Failure_InvalidInputArguments(string name, int flightNumber)
        {
            BookingService service = new BookingService(_mockBookingRepository.Object, _mockFlightRepository.Object, _mockCustomerRepository.Object);

            (bool result, Exception exception) = await service.CreateBooking(name, flightNumber);

            Assert.IsFalse(result);
            Assert.IsNotNull(exception);
        }
Ejemplo n.º 9
0
        public void Pass_in_a_fake_interface([Frozen] IPaymentGateway paymentGateway, BookingService sut)
        {
            // arrange
            // not much here!!

            // act
            sut.CreateBooking();

            // assert
            A.CallTo(() => paymentGateway.CapturePayment()).MustHaveHappened();
        }
Ejemplo n.º 10
0
 public IHttpActionResult Post(BookingCreate model)
 {
     if (!ModelState.IsValid)
     {
         return(BadRequest(ModelState));
     }
     if (_service.CreateBooking(model))
     {
         return(Ok());
     }
     return(InternalServerError());
 }
Ejemplo n.º 11
0
        public async Task CreateBooking_Failure_FlightNotInDatabase()
        {
            _mockFlightRepository.Setup(repository => repository.GetFlightByFlightNumber(1))
            .Throws(new FlightNotFoundException());

            BookingService service = new BookingService(_mockBookingRepository.Object, _mockFlightRepository.Object, _mockCustomerRepository.Object);

            (bool result, Exception exception) = await service.CreateBooking("Maurits Escher", 1);

            Assert.IsFalse(result);
            Assert.IsNotNull(exception);
            Assert.IsInstanceOfType(exception, typeof(CouldNotAddBookingToDatabaseException));
        }
Ejemplo n.º 12
0
        public async Task CreateBooking_Success_CustomerNotInDatabase()
        {
            _mockBookingRepository.Setup(repository => repository.CreateBooking(0, 0)).Returns(Task.CompletedTask);
            _mockCustomerRepository.Setup(repository => repository.GetCustomerByName("Konrad Zuse"))
            .Throws(new CustomerNotFoundException());

            BookingService service = new BookingService(_mockBookingRepository.Object, _mockFlightRepository.Object, _mockCustomerRepository.Object);

            (bool result, Exception exception) = await service.CreateBooking("Konrad Zuse", 0);

            Assert.IsFalse(result);
            Assert.IsNotNull(exception);
            Assert.IsInstanceOfType(exception, typeof(CustomerNotFoundException));
        }
Ejemplo n.º 13
0
        public async Task CreateBooking_Success()
        {
            _mockBookingRepository.Setup(repository => repository.CreateBooking(0, 0)).Returns(Task.CompletedTask);
            _mockCustomerRepository.Setup(repository => repository.GetCustomerByName("Leo Tolstoy"))
            .Returns(Task.FromResult(new Customer("Leo Tolstoy")));
            _mockFlightRepository.Setup(repository => repository.GetFlightByFlightNumber(0))
            .Returns(Task.FromResult(new Flight()));

            BookingService service = new BookingService(_mockBookingRepository.Object, _mockFlightRepository.Object, _mockCustomerRepository.Object);

            (bool result, Exception exception) = await service.CreateBooking("Leo Tolstoy", 0);

            Assert.IsTrue(result);
            Assert.IsNull(exception);
        }
Ejemplo n.º 14
0
        public void CheckBookingInputPartyUnderMinTest()
        {
            BookingService lRSMSSERVICE = new BookingService();

            Booking lBooking = new Booking
            {
                ContactName     = "Luke",
                BookingDateTime = DateTime.Now,
                PartyNumber     = -20,
                SpecialOccasion = true,
                OtherDetails    = "N/A"
            };

            Assert.ThrowsException <Exception>(() => lRSMSSERVICE.CreateBooking(lBooking));
        }
Ejemplo n.º 15
0
        public async Task CreateBooking_Failure_CustomerNotInDatabase_RepositoryFailure()
        {
            _mockBookingRepository.Setup(repository => repository.CreateBooking(0, 0)).Throws(new CouldNotAddBookingToDatabaseException());
            _mockFlightRepository.Setup(repository => repository.GetFlightByFlightNumber(0))
            .ReturnsAsync(new Flight());
            _mockCustomerRepository.Setup(repository => repository.GetCustomerByName("Bill Gates")).Returns(Task.FromResult(new Customer("Bill Gates")));

            BookingService service = new BookingService(_mockBookingRepository.Object, _mockFlightRepository.Object, _mockCustomerRepository.Object);

            (bool result, Exception exception) = await service.CreateBooking("Bill Gates", 0);

            Assert.IsFalse(result);
            Assert.IsNotNull(exception);
            Assert.IsInstanceOfType(exception, typeof(CouldNotAddBookingToDatabaseException));
        }
        public async Task CreateBooking_Success()
        {
            Mock <BookingRepository>  mockBookingRepository  = new Mock <BookingRepository>();
            Mock <CustomerRepository> mockCustomerRepository = new Mock <CustomerRepository>();

            mockBookingRepository.Setup(repository => repository.CreateBooking(0, 0)).Returns(Task.CompletedTask);
            mockCustomerRepository.Setup(repository => repository.GetCustomerByName("Leo Tolstoy"))
            .Returns(Task.FromResult(new Customer("Leo Tolstoy")));

            BookingService service = new BookingService(mockBookingRepository.Object, mockCustomerRepository.Object);

            (bool result, Exception exception) = await service.CreateBooking("Leo Tolstoy", 0);

            Assert.IsTrue(result);
            Assert.IsNull(exception);
        }
Ejemplo n.º 17
0
        public void Successful_booking_captures_payment()
        {
            // arrange
            var sut       = new BookingService();
            var startTime = DateTime.Now;

            // act
            sut.CreateBooking(new CreateBookingRequest(startTime: startTime,
                                                       durationMinutes: 10,
                                                       bookingUser: new User {
                Id = 1
            },
                                                       paymentMethod: CreateBookingRequest.BookingPaymentMethod.Swish));

            // assert
            Assert.Equal(10, sut.PaymentGateway.TotalPayments);
        }
Ejemplo n.º 18
0
        public async Task CreateBooking_Failure_CouldNotAddBookingToDatabaseException()
        {
            _mockBookingRepository.Setup(repository => repository.CreateBooking(1, 2)).Throws(new CouldNotAddBookingToDatabaseException());

            _mockCustomerRepository.Setup(repository => repository.GetCustomerByName("Eise Eisinga"))
            .Returns(Task.FromResult(new Customer("Eise Eisinga")
            {
                CustomerId = 1
            }));

            BookingService service = new BookingService(_mockBookingRepository.Object, _mockFlightRepository.Object, _mockCustomerRepository.Object);

            (bool result, Exception exception) = await service.CreateBooking("Eise Eisinga", 2);

            Assert.IsFalse(result);
            Assert.IsNotNull(exception);
            Assert.IsInstanceOfType(exception, typeof(CouldNotAddBookingToDatabaseException));
        }
Ejemplo n.º 19
0
        [Fact] // behavioural or communication (white box)
        public void Successful_booking_should_capture_payment()
        {
            // arrange
            var id = Guid.NewGuid().ToString();
            // managed dependency - concrete instance
            var bookingRepository = new BookingRepositoryMongoDB(this.mongoClient);
            // unmanaged dependency - interface
            var priceCalculator = A.Fake <IPriceCalculator>();
            var paymentGateway  = A.Fake <IPaymentGateway>();

            var sut = new BookingService(bookingRepository, paymentGateway, priceCalculator);

            // act
            sut.CreateBooking(new BookingService.CreateBookingRequest(id, "jason"));

            // assert
            A.CallTo(() => paymentGateway.CapturePayment(A <decimal> .Ignored)).MustHaveHappened();
        }
Ejemplo n.º 20
0
        public void Successful_booking_captures_payment()
        {
            // arrange
            var paymentGateway = A.Fake <IPaymentGateway>();
            var sut            = new BookingService(paymentGateway);
            var startTime      = DateTime.Now;

            // act
            sut.CreateBooking(new CreateBookingRequest(startTime: startTime,
                                                       durationMinutes: 10,
                                                       bookingUser: new User {
                Id = 1
            },
                                                       paymentMethod: CreateBookingRequest.BookingPaymentMethod.Swish));

            // assert
            A.CallTo(() => paymentGateway.CapturePayment(10)).MustHaveHappenedOnceExactly();
        }
Ejemplo n.º 21
0
        public void CreateBookingTest()
        {
            bool lIsCompleted = false;

            BookingService lRSMSSERVICE = new BookingService();

            Booking lBooking = new Booking
            {
                ContactName     = "Test",
                BookingDateTime = DateTime.Now,
                PartyNumber     = 4,
                SpecialOccasion = true,
                OtherDetails    = "N/A"
            };

            lIsCompleted = lRSMSSERVICE.CreateBooking(lBooking);

            Assert.IsTrue(lIsCompleted);
        }
Ejemplo n.º 22
0
        public async Task <IActionResult> CreateBooking([FromBody] BookingData body, int flightNumber)
        {
            if (ModelState.IsValid && flightNumber.IsPositiveInteger())
            {
                string name = $"{body.FirstName} {body.LastName}";
                (bool result, Exception exception) = await _bookingService.CreateBooking(name, flightNumber);

                if (result && exception == null)
                {
                    return(StatusCode((int)HttpStatusCode.Created));
                }

                return(exception is CouldNotAddBookingToDatabaseException
                    ? StatusCode((int)HttpStatusCode.NotFound)
                    : StatusCode((int)HttpStatusCode.InternalServerError, exception.Message));
            }

            return(StatusCode((int)HttpStatusCode.InternalServerError, ModelState.Root.Errors.First().ErrorMessage));
        }
Ejemplo n.º 23
0
        public void CreateBookingReturnsNull()
        {
            var fakeBooking = new BookingResource {
                Id = 1, Number = "XYZ"
            };

            var mockedMapper            = GetMockedMapper();
            var mockedPersonRepository  = GetMockedPersonRepository();
            var mockedBookingRepository = GetMockedBookingRepository();
            var mockedFlightRepository  = GetMockedFlightRepository();

            var bookingService = new BookingService(mockedBookingRepository.Object,
                                                    mockedFlightRepository.Object,
                                                    mockedPersonRepository.Object,
                                                    mockedMapper.Object);

            var result = bookingService.CreateBooking(fakeBooking, nonExistingFlightId, nonExistingPassengerId);

            Assert.Null(result);
        }
Ejemplo n.º 24
0
        public void ShouldThrowExceptionIfCabsAreNotAvailable()
        {
            var pickupLocation       = new GeoCoordinate(12.99711, 77.61469);
            var bookingRepo          = new Mock <IBookingRepository>();
            var availableCabsService = new Mock <IAvailableCabsService>();

            availableCabsService.Setup(a => a.GetNearestCab(pickupLocation, new CabType[] { CabType.Regular, CabType.Pink })).Returns(() => { return(null); });

            var bookingService       = new BookingService(bookingRepo.Object, availableCabsService.Object);
            var createBookingRequest = new CreateBookingRequest()
            {
                PickupLocation = pickupLocation,
                Destination    = new GeoCoordinate(13, 77),
                Time           = DateTime.Now,
                UserId         = "1"
            };

            Assert.Throws <Exception>(() => bookingService.CreateBooking(createBookingRequest));

            availableCabsService.Verify(a => a.GetNearestCab(createBookingRequest.PickupLocation, new CabType[] { CabType.Regular, CabType.Pink }));
        }
Ejemplo n.º 25
0
        [Fact] // state based (black box)
        public void Successful_booking_should_be_persisted()
        {
            // arrange
            var id = Guid.NewGuid().ToString();
            var bookingRepository = new BookingRepositoryMongoDB(this.mongoClient);
            // unmanaged dependency - interface
            var paymentGateway  = A.Fake <IPaymentGateway>();
            var priceCalculator = A.Fake <IPriceCalculator>();
            var sut             = new BookingService(bookingRepository, paymentGateway, priceCalculator);

            // simulate that the payment fails
            A.CallTo(() => paymentGateway.CapturePayment(A <decimal> .Ignored)).Returns(true);

            // act
            sut.CreateBooking(new BookingService.CreateBookingRequest(id, "jason"));

            var booking = bookingRepository.GetById(id);

            // assert
            booking.Id.Should().Be(id);
        }
Ejemplo n.º 26
0
        public ActionResult CreateBookingDone(int EmployeeID, string username, int escapeRoomID, TimeSpan BookTime, int AmountOfPeople, DateTime BDate)
        {
            EscapeRoomService escs = new EscapeRoomService();

            EscRef.EscapeRoom es = escs.GetEscapeRoom(escapeRoomID);
            ViewBag.EscapeRoom = es;
            List <TimeSpan> freetime = escs.FreeTimes(escapeRoomID, BDate);

            ViewBag.freetimes = freetime;
            BookingService bs     = new BookingService();
            HttpCookie     cookie = Request.Cookies["User"];

            cookie.Value = username;

            int c = bs.CreateBooking(EmployeeID, username, escapeRoomID, BookTime, AmountOfPeople, BDate);

            if (c == 0)
            {
                TempData["message"] = "Den tid du prøvede at booke er desværre blevet taget ";
                return(RedirectToAction("CreateBooking", new { id = escapeRoomID }));
            }
            return(View());
        }
Ejemplo n.º 27
0
        [Fact] // behavioural or communication (white box)
        public void Should_use_total_price_from_price_service()
        {
            // arrange
            var id = Guid.NewGuid().ToString();
            // managed dependency - concrete instance
            var bookingRepository = new BookingRepositoryMongoDB(this.mongoClient);
            // unmanaged dependency - interface
            var priceCalculator = A.Fake <IPriceCalculator>();
            var paymentGateway  = A.Fake <IPaymentGateway>();

            var sut = new BookingService(bookingRepository, paymentGateway, priceCalculator);

            // use price calculator as stub
            A.CallTo(() => priceCalculator
                     .GetPriceForBookingWith(A <int> .Ignored, A <int> .Ignored))
            .Returns(100);


            // act
            sut.CreateBooking(new BookingService.CreateBookingRequest(id, "jason"));

            // assert
            A.CallTo(() => paymentGateway.CapturePayment(100)).MustHaveHappened();
        }
        public void Create_booking_efcore()
        {
            // arrange
            var id              = Guid.NewGuid().ToString();
            var repository      = new BookingRepositoryEFCore(context);
            var paymentGateway  = A.Fake <IPaymentGateway>();
            var priceCalculator = A.Fake <IPriceCalculator>();

            var sut = new BookingService(repository, paymentGateway, priceCalculator);

            // stub, set expectation of success
            A.CallTo(() => paymentGateway.CapturePayment(A <decimal> .Ignored)).Returns(true);

            // act
            sut.CreateBooking(new BookingService.CreateBookingRequest(
                                  id: id,
                                  requestedBy: "a.user",
                                  date: DateTime.Now));

            var newBooking = repository.GetById(id);

            // assert
            newBooking.Should().NotBeNull();
        }
Ejemplo n.º 29
0
        public static void Main(string[] args)
        {
            UserService         UserService         = new UserService();
            BookingService      BookingService      = new BookingService();
            OfferService        OfferService        = new OfferService();
            OfferRequestService OfferRequestService = new OfferRequestService();
            PaymentService      PaymentService      = new PaymentService();
            LocationService     LocationService     = new LocationService();

            while (true)
            {
Login:
                Console.WriteLine("1 -> SignUp\n2 -> SignIn\n0 -> Exit");

                IEnums.CarPoolOptions Option = (IEnums.CarPoolOptions)Convert.ToInt32(Console.ReadLine());
                switch (Option)
                {
                case IEnums.CarPoolOptions.SignUp:
                {
                    Console.WriteLine("enter name:");
                    string Name = Console.ReadLine();
                    Console.WriteLine("enter Password:"******"Name: " + NewUser.Name);
                    Console.WriteLine("UserId: " + NewUser.UserId);
                    Console.WriteLine("Account Created Successfully!!");
                    break;
                }

                case IEnums.CarPoolOptions.SignIn:
                {
                    Console.WriteLine("enter UserId:");
                    string UserId = Console.ReadLine();
                    Console.WriteLine("enter Password:"******"Your Booking Status: " + Booking.Status);
                                if (Booking.Status.Equals(IEnums.BookingStatus.Confirmed))
                                {
                                    Offer Offer = OfferService.GetDriverDetails(Booking.RiderId);
                                    Console.WriteLine("Drivername: " + Offer.DriverName + ", VehicleNumber: " + Offer.VehicleRegNumber + ", VehicleModel: " + Offer.VehicleModel);
                                }
                                Console.ReadKey();
                                Console.WriteLine("1 -> Book a Ride\n5 -> Display bookings history\n6 -> Display created offers history\n7 -> Cancel Ride\n10 -> Pay\n11 -> Add money to wallet\n" +
                                                  "13 -> wallet Balance\n14 -> display payment History\n0 -> Logout");
                            }
                            else if (OfferService.AnyActiveOffer(UserId))
                            {
                                Console.WriteLine("4 -> Display Offer requests\n5 -> Display bookings history\n" +
                                                  "6 -> Display offers history\n8 -> Cancel Offer\n9 -> End Ride\n15 -> End Offer\n10 -> Pay\n11 -> Add money to wallet\n" +
                                                  "13 -> wallet Balance\n14 -> display payment History\n0 -> Logout");
                            }
                            else
                            {
                                Console.WriteLine("1 -> Book a Ride\n2 -> Offer a Ride\n5 -> Display booking history\n" +
                                                  "6 -> Display offers history\n10 -> Pay\n11 -> Add money to wallet\n" +
                                                  "13 -> wallet Balance\n14 -> display payment History\n0 -> Logout");
                            }

                            IEnums.UserOptions UserOption = (IEnums.UserOptions)Convert.ToInt32(Console.ReadLine());
                            switch (UserOption)
                            {
                            case IEnums.UserOptions.BookARide:
                            {
                                if (PaymentService.IsEligibleToBook(UserId))
                                {
                                    Console.WriteLine("enter pick-up location:");
                                    string   PickUpLocation = Console.ReadLine();
                                    Location FromLocation   = LocationService.GetLocation(PickUpLocation.ToUpper());
                                    if (FromLocation != null)
                                    {
                                        Console.WriteLine("enter Destination:");
                                        string   Destination = Console.ReadLine();
                                        Location ToLocation  = LocationService.GetLocation(Destination.ToUpper());
                                        if (ToLocation != null)
                                        {
                                            Console.WriteLine("number of passengers:");
                                            int          NumberOfPassengers = Convert.ToInt32(Console.ReadLine());
                                            List <Offer> ActiveOffers       = OfferService.DisplayActiveOffers(PickUpLocation.ToUpper(), Destination.ToUpper(), NumberOfPassengers);
                                            if (ActiveOffers.Count == 0)
                                            {
                                                Console.WriteLine("no active offers");
                                            }
                                            else
                                            {
                                                foreach (var offer in ActiveOffers)
                                                {
                                                    Console.WriteLine("Drivername: " + offer.DriverName + " RiderId " + offer.RiderId + " Vehicle Number: " + offer.VehicleRegNumber + " Vehicle Model: " + offer.VehicleModel + " Phone Number: " + offer.PhoneNumber);
                                                }
                                                Console.WriteLine("enter Riders userId to select the offer\nRider UserId:");
                                                string RiderId = Console.ReadLine();
                                                OfferRequestService.SendRideRequest(FromLocation, ToLocation, NumberOfPassengers, RiderId.ToUpper(), UserId.ToUpper());
                                                Booking NewBooking = BookingService.CreateBooking(RiderId, UserId, FromLocation, ToLocation, NumberOfPassengers);
                                            }
                                        }
                                        else
                                        {
                                            Console.WriteLine(Destination + " not found");
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine(PickUpLocation + " not found");
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("pay your pending dues to book for next ride");
                                    Console.WriteLine("do you want to pay now?");
                                    Console.WriteLine("1 -> paynow\n2 -> later");
                                    IEnums.PaymentDecision Decision = (IEnums.PaymentDecision)Convert.ToInt32(Console.ReadLine());
                                    if (Decision.Equals(IEnums.PaymentDecision.Now))
                                    {
                                        List <Payment> PaymentDues = PaymentService.DisplayPendingDues(UserId);
                                        foreach (var payment in PaymentDues)
                                        {
                                            Console.WriteLine("BookingId: " + payment.PaymentID + ", amount to be paid: " + payment.Fair);
                                        }
                                        Console.WriteLine("enter paymentId: ");
                                        string PaymentId = Console.ReadLine();
                                        if (PaymentService.Pay(PaymentId))
                                        {
                                            Console.WriteLine("payment done successfully!!");
                                        }
                                        else
                                        {
                                            Console.WriteLine("insufficient wallet balance");
                                            Console.WriteLine("Do you want to add money to the wallet?");
                                            Console.WriteLine("1 -> yes\n2 -> no");
                                            IEnums.YesOrNo Choice = (IEnums.YesOrNo)Convert.ToInt32(Console.ReadLine());
                                            if (Choice.Equals(IEnums.YesOrNo.Yes))
                                            {
                                                Console.WriteLine("enter amount: ");
                                                double Amount = Convert.ToDouble(Console.ReadLine());
                                                UserService.AddMoneyToWallet(Amount, UserId);
                                                Console.WriteLine("Money added successfully!!");
                                            }
                                        }
                                    }
                                }
                                break;
                            }

                            case IEnums.UserOptions.OfferARide:
                            {
                                Console.WriteLine("enter name:");
                                string Name = Console.ReadLine();
                                Console.WriteLine("enter From location:");
                                string   FromLocation = Console.ReadLine();
                                Location StartPoint   = LocationService.GetLocation(FromLocation.ToUpper());
                                if (StartPoint != null)
                                {
                                    Console.WriteLine("enter To location:");
                                    string   ToLocation = Console.ReadLine();
                                    Location EndPoint   = LocationService.GetLocation(ToLocation.ToUpper());
                                    if (EndPoint != null)
                                    {
                                        Console.WriteLine("enter Availability");
                                        int Availability = Convert.ToInt32(Console.ReadLine());
                                        Console.WriteLine("enter Vehicle Number");
                                        string VehicleNumber = Console.ReadLine();
                                        Console.WriteLine("enter Vehicle Model");
                                        string VehicleModel = Console.ReadLine();
                                        if (OfferService.VehicleVerification(VehicleNumber))
                                        {
                                            Offer           Offer     = OfferService.CreateOffer(Name.ToUpper(), UserId, StartPoint, EndPoint, Availability, VehicleNumber.ToUpper(), VehicleModel.ToUpper());
                                            List <Location> ViaPoints = LocationService.GetViaPoints(StartPoint, EndPoint);
                                            if (ViaPoints.Count != 0)
                                            {
                                                int SelectViaPoint = 0;
                                                do
                                                {
                                                    Console.WriteLine("you might touch these locations: ");
                                                    foreach (var location in ViaPoints)
                                                    {
                                                        Console.WriteLine(location.Index + " -> " + location.Name);
                                                    }
                                                    Console.WriteLine("0 -> end");
                                                    Console.WriteLine("selects the locations: ");
                                                    SelectViaPoint = Convert.ToInt32(Console.ReadLine());
                                                    IEnums.LocationIndex LocationIndex = (IEnums.LocationIndex)SelectViaPoint;
                                                    OfferService.AddViaPoint(Offer, LocationIndex);
                                                } while (SelectViaPoint != 0);

                                                Console.WriteLine("offer created successfully!!");
                                            }
                                            else
                                            {
                                                Console.WriteLine("Cannot use same vehicle for two offers");
                                            }
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine(ToLocation + " not found");
                                    }
                                }
                                else
                                {
                                    Console.WriteLine(FromLocation + " not found");
                                }
                                break;
                            }

                            case IEnums.UserOptions.DisplayCurrentBookingStatus:
                            {
                                Booking Booking = BookingService.ViewBookingStatus(UserId);
                                if (Booking != null)
                                {
                                    Console.WriteLine("Rider: " + Booking.RiderId + " From " + Booking.FromLocation + " To " + Booking.ToLocation + " Status " + Booking.Status);
                                }
                                else
                                {
                                    Console.WriteLine("you have no current bookings");
                                }
                                break;
                            }

                            case IEnums.UserOptions.DisplayOfferRequests:
                            {
                                if (OfferRequestService.AnyOfferRequest(UserId))
                                {
                                    List <OfferRequest> OfferRequests = OfferRequestService.DisplayOfferRequests(UserId);
                                    foreach (var offerRequest in OfferRequests)
                                    {
                                        Console.WriteLine("RequestId: " + offerRequest.RequestId + " from " + offerRequest.FromLocation + " to " + offerRequest.ToLocation);
                                    }
                                    Console.WriteLine("enter the RequestId to accept or reject offer request");
                                    string RequestId = Console.ReadLine();
                                    Console.WriteLine("1 -> Accept offer\n2 -> reject offer");
                                    IEnums.Decisions Decision = (IEnums.Decisions)Convert.ToInt32(Console.ReadLine());
                                    OfferRequestService.OfferRequestApproval(RequestId.ToUpper(), Decision);
                                }
                                else
                                {
                                    Console.WriteLine("no offers requests to display");
                                }
                                break;
                            }

                            case IEnums.UserOptions.DisplayBookingHistory:
                            {
                                List <Booking> AllBookings = BookingService.DisplayBookingsHistory(UserId);
                                if (AllBookings != null)
                                {
                                    foreach (var booking in AllBookings)
                                    {
                                        Console.WriteLine("From: " + booking.FromLocation.Name + " to " + booking.ToLocation.Name + " Status: " + booking.Status);
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("no bookings to display");
                                }
                                break;
                            }

                            case IEnums.UserOptions.DisplayOfferHistory:
                            {
                                List <Offer> AllOffers = OfferService.DisplayOffersHistory(UserId);
                                if (AllOffers != null)
                                {
                                    foreach (var offer in AllOffers)
                                    {
                                        Console.WriteLine("From: " + offer.FromLocation.Name + " to " + offer.ToLocation.Name + " Status: " + offer.Status);
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("no offers to display");
                                }
                                break;
                            }

                            case IEnums.UserOptions.CancelRide:
                            {
                                List <Booking> ActiveBookings = BookingService.DisplayActiveBookings(UserId);
                                if (ActiveBookings != null)
                                {
                                    foreach (var booking in ActiveBookings)
                                    {
                                        Console.WriteLine("RiderId: " + booking.RiderId + " From " + booking.FromLocation.Name + " to " + booking.ToLocation.Name + " Status: " + booking.Status);
                                    }
                                    Console.WriteLine("enter RiderId to cancel: ");
                                    string RiderId = Console.ReadLine();
                                    BookingService.CancelRide(RiderId);
                                    Console.WriteLine("Ride Cancelled");
                                }
                                else
                                {
                                    Console.WriteLine("no active bookings to cancel");
                                }
                                break;
                            }

                            case IEnums.UserOptions.CancelOffer:
                            {
                                OfferService.CancelOffer(UserId);
                                Console.WriteLine("Offer Cancelled");
                                break;
                            }

                            case IEnums.UserOptions.EndRide:
                            {
                                List <string> PassengersInVehicle = BookingService.DisplayPassengersInVehicle(UserId);
                                foreach (var Passenger in PassengersInVehicle)
                                {
                                    Console.WriteLine("RideeId: " + Passenger);
                                }
                                Console.WriteLine("enter ridee Id");
                                string RideeId = Console.ReadLine();
                                BookingService.EndRide(UserId, RideeId);
                                break;
                            }

                            case IEnums.UserOptions.Pay:
                            {
                                List <Payment> PendingPayments = PaymentService.DisplayPendingDues(UserId);
                                if (PendingPayments.Count != 0)
                                {
                                    foreach (var payment in PendingPayments)
                                    {
                                        Console.WriteLine("PaymentId: " + payment.PaymentID + ", Fair: " + payment.Fair);
                                    }
                                    Console.WriteLine("enter paymentId: ");
                                    string PaymentId = Console.ReadLine();
                                    if (PaymentService.Pay(PaymentId))
                                    {
                                        Console.WriteLine("payment done successfully!!");
                                    }
                                    else
                                    {
                                        Console.WriteLine("insufficient wallet balance");
                                        Console.WriteLine("Do you want to add money to the wallet?");
                                        Console.WriteLine("1 -> yes\n2 -> no");
                                        IEnums.YesOrNo Choice = (IEnums.YesOrNo)Convert.ToInt32(Console.ReadLine());
                                        if (Choice.Equals(IEnums.YesOrNo.Yes))
                                        {
                                            Console.WriteLine("enter amount: ");
                                            double Amount = Convert.ToDouble(Console.ReadLine());
                                            UserService.AddMoneyToWallet(Amount, UserId);
                                            Console.WriteLine("Money added successfully!!");
                                        }
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("no pending dues");
                                }
                                break;
                            }

                            case IEnums.UserOptions.AddMoneyToWallet:
                            {
                                Console.WriteLine("enter amount: ");
                                double Amount = Convert.ToDouble(Console.ReadLine());
                                UserService.AddMoneyToWallet(Amount, UserId);
                                Console.WriteLine("Money added successfully!!");
                                break;
                            }

                            case IEnums.UserOptions.WalletBalance:
                            {
                                Console.WriteLine("your wallet balance: " + UserService.DisplayWalletBalance(UserId));
                                break;
                            }

                            case IEnums.UserOptions.DisplayPaymentHistory:
                            {
                                List <Payment> AllPayments = PaymentService.DisplayPaymentHistory(UserId);
                                if (AllPayments.Count != 0)
                                {
                                    foreach (var payment in AllPayments)
                                    {
                                        if (payment.RideeId.Equals(UserId))
                                        {
                                            Console.WriteLine("PaymentId: " + payment.PaymentID + " to " + payment.RiderId + " Status: " + payment.Status);
                                        }
                                        else if (payment.RiderId.Equals(UserId))
                                        {
                                            Console.WriteLine("PaymentId: " + payment.PaymentID + " from " + payment.RideeId + " Status: " + payment.Status);
                                        }
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("you have no payments to display");
                                }
                                break;
                            }

                            case IEnums.UserOptions.Logout:
                            {
                                goto Login;
                            }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Incorrect userId or password");
                    }
                    break;
                }

                case IEnums.CarPoolOptions.Exit:
                {
                    System.Environment.Exit(0);
                    break;
                }
                }
            }
        }
Ejemplo n.º 30
0
        public void CreateNewBookingTest( )
        {
            //Arrange
            BookingService    bs  = new BookingService();
            CustomerService   cs  = new CustomerService();
            EscapeRoomService es  = new EscapeRoomService();
            EmployeeService   ems = new EmployeeService();

            MAPMA_WebClient.CusRef.Customer   cus = cs.GetCustomer("Anorak");
            MAPMA_WebClient.EmpRef.Employee   em  = ems.GetEmployee(1);
            MAPMA_WebClient.EscRef.EscapeRoom er  = es.GetEscapeRoom(1);
            Customer customer = new Customer()
            {
                customerNo = cus.customerNo,
                firstName  = cus.firstName,
                lastName   = cus.lastName,
                mail       = cus.mail,
                password   = cus.password,
                phone      = cus.phone,
                username   = cus.username
            };
            Employee employee = new Employee()
            {
                address    = em.address,
                cityName   = em.cityName,
                employeeID = em.employeeID,
                firstName  = em.firstName,
                lastName   = em.lastName,
                mail       = em.mail,
                phone      = em.phone,
                region     = em.region,
                zipcode    = em.zipcode
            };
            EscapeRoom escapeRoom = new EscapeRoom()
            {
                cleanTime    = er.cleanTime,
                description  = er.description,
                escapeRoomID = er.escapeRoomID,
                maxClearTime = er.maxClearTime,
                name         = er.name,
                price        = er.price,
                rating       = er.rating
            };
            Booking hostBook;
            Booking book = new Booking()
            {
                amountOfPeople = 22,
                bookingTime    = DateTime.Now.TimeOfDay,
                cus            = customer,
                date           = DateTime.Now.AddDays(7.0).Date,
                emp            = employee,
                er             = escapeRoom
            };


            //Act
            bs.CreateBooking(book.emp.employeeID, book.cus.username, book.er.escapeRoomID, book.bookingTime, book.amountOfPeople, book.date);
            hostBook = bs.GetBooking(book.er.escapeRoomID, book.cus.username, book.date);

            //Assert
            Assert.AreEqual(book.date, hostBook.date);
            Assert.AreEqual(book.emp.employeeID, hostBook.emp.employeeID);
            Assert.AreEqual(book.cus.username, hostBook.cus.username);

            bs.DeleteBooking(book.emp.employeeID, book.cus.username, book.er.escapeRoomID, book.bookingTime, book.amountOfPeople, book.date);
        }