예제 #1
0
 internal object AddBookingRequest(BookingRequestModel requestModel)
 {
     try
     {
         Booking new_request = new Booking
         {
             BookingById        = requestModel.BookingById,
             BookingToId        = requestModel.BookingToId,
             ServiceType        = requestModel.ServiceType,
             BookingDate        = DateTime.Now,
             ServiceDate        = Convert.ToDateTime(requestModel.ServiceDate),
             CustomerAddress    = requestModel.CustomerAddress,
             ProblemDescription = requestModel.ProblemDescription,
             VendorAcceptance   = false,
             CompletedStatus    = false,
         };
         _dbContext.Bookings.Add(new_request);
         _dbContext.SaveChanges();
         return("{Success: true}");
     }
     catch (Exception ex)
     {
         return("{ Success:  " + ex.Message + "}");
     }
 }
예제 #2
0
        public async Task <BookingResponseModel> UpdateBooking(BookingRequestModel bookingRequest)
        {
            var booking  = _mapper.Map <Booking>(bookingRequest);
            var response = await _bookingRepository.UpdateAsync(booking);

            return(_mapper.Map <BookingResponseModel>(response));
        }
예제 #3
0
        public async Task <IActionResult> CreateNewBooking([FromBody] BookingRequestModel bookingRequestModel)
        {
            var          loggedIn   = User.Claims.FirstOrDefault(c => c.Type == "sub").Value;
            Guid         LoggedInID = new Guid(loggedIn);
            List <Order> orders     = new List <Order>();

            foreach (var order in bookingRequestModel.Orders)
            {
                orders.Add(new Order
                {
                    BookingId      = order.bookingId,
                    CustomerNumber = order.customerNumber,
                    WareNumber     = order.wareNumber,
                    OrderNumber    = order.orderNumber,
                    InOut          = order.InOut,
                    TotalPallets   = order.TotalPallets,
                    ExternalId     = order.ExternalId,
                    Comment        = order.Comment,
                    BottomPallets  = order.BottomPallets,
                    SupplierName   = order.SupplierName
                });
            }

            var result = await CommandRouter.RouteAsync <CreateBookingCommand, IdResponse>(
                new CreateBookingCommand(bookingRequestModel.totalPallets, bookingRequestModel.bookingTime,
                                         bookingRequestModel.transporterName, bookingRequestModel.port, bookingRequestModel.actualArrival,
                                         bookingRequestModel.startLoading, bookingRequestModel.endLoading, bookingRequestModel.email, orders, LoggedInID, bookingRequestModel.ExternalId, LoggedInID ));

            return(!result.IsSuccessful ? Conflict(result) : new ObjectResult(result));
        }
        public IHttpActionResult PutOccupacy(BookingRequestModel booking)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            Occupacy    _OC = new Occupacy();
            RoomBooking _RB = db.RoomBookings.FirstOrDefault(m => m.IdBooking == booking.IdBooking);
            Room        _R  = db.Rooms.FirstOrDefault(m => m.IdRoom == booking.IdRoom);

            _OC.IdCustomer     = _RB.IdCustomer;
            _OC.IdRoom         = _R.IdRoom;
            _OC.DateOccupacied = _RB.DateCheckin;
            _OC.RateApplied    = _R.Rate;
            _OC.IsPaid         = false;

            db.Occupacies.Add(_OC);
            db.RoomBookings.FirstOrDefault(m => m.IdBooking == booking.IdBooking).IsApproved = true;

            DateTime checkinDate = _RB.DateCheckin.GetValueOrDefault(DateTime.Now);

            db.Rooms.FirstOrDefault(m => m.IdRoom == booking.IdRoom).Status = checkinDate.ToString("MM/dd/yyyy");

            db.SaveChanges();

            return(Ok(_OC));
        }
예제 #5
0
        public JsonResult AddCommonAreaBooking(BookingRequestModel model)
        {
            string strMsg = "NotOk";
            int    val    = -1;

            if (model.CommonAreaId == 0)
            {
                strMsg = "Common area required.";
            }
            else
            {
                StrataOwnerHelper strataOwnerHelper = new StrataOwnerHelper();
                model.Status      = "1";
                model.AdminStatus = 1; // As area is booked by admin then no need for approval
                int result = strataOwnerHelper.AddStrataAdminBookingRequest(model);
                if (result == 1)
                {
                    val    = 0;
                    strMsg = "Booking request has been created successfully.";
                }
                else if (result == -1)
                {
                    strMsg = "Booking request already exists in these dates.";
                }
                else
                {
                    strMsg = "Booking request creation failed.";
                }
            }


            return(Json(new { Msg = strMsg, Result = val }, JsonRequestBehavior.AllowGet));
        }
예제 #6
0
        /// <summary>
        /// Get the booking listing on stratasboard admin dashboard..
        /// </summary>
        /// <param name="stratasBoardId"></param>
        /// <returns></returns>
        public List <BookingRequestModel> GetAdminDashboardNewBookingListing(long stratasBoardId)
        {
            var bookingList = context.vw_GetBookingList.Where(x => x.StratasBoardId == stratasBoardId && x.STATUS == 1 && x.AdminStatus == 0 && x.RequestType == "bookingrequest").OrderByDescending(x => x.CreatedOn).ToList();
            List <BookingRequestModel> objProjListingModel = new List <BookingRequestModel>();

            foreach (var item in bookingList)
            {
                BookingRequestModel objBookingList = new BookingRequestModel
                {
                    BookingRequestId = item.BookingRequestId,
                    UserClientId     = item.UserClientId,
                    CommonAreaId     = item.CommonAreaId.Value,
                    CommonAreaName   = item.CommonAreaName,
                    Subject          = item.Subject,
                    FromDate         = item.FromDate.ToString(),
                    ToDate           = item.ToDate.Value.ToString(),
                    Reason           = item.Reason,
                    Status           = item.STATUS.ToString(),
                    AdminStatus      = item.AdminStatus.Value,
                    AdminRemark      = item.AdminRemark,
                    AdminUserId      = item.AdminUserId.Value,
                    CreatedOn        = item.CreatedOn.Value,
                    ModifiedOn       = item.ModifiedOn.Value,
                    StratasBoardId   = item.StratasBoardId.Value,
                    NoOfDay          = item.NoOfDay.Value,
                    AdminStatusText  = item.AdminStatusText,
                    RequestType      = item.RequestType
                };
                objProjListingModel.Add(objBookingList);
            }
            return(objProjListingModel);
        }
예제 #7
0
        // POST api/book
        public async Task <IHttpActionResult> Post(BookingRequestModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (model.BookingRequestId == Guid.Empty)
            {
                model.BookingRequestId = NewId.NextGuid();
            }

            var address = ConfigurationManager.AppSettings["BookMeetingAddress"];

            var endpoint = await WebApiApplication.Bus.GetSendEndpoint(new Uri(address));

            var request = new BookMeetingCommand(model);

            await endpoint.Send(request);

            return(Accepted(new BookingRequestResult
            {
                BookingRequestId = model.BookingRequestId,
                Timestamp = request.Timestamp
            }));
        }
예제 #8
0
                public async void EditTable_ChangeBookingFrom2to3_ReturnsFalse()
                {
                    var tablesGetAll      = FakeTables.GetAll3x2Tables();
                    var bookingsGetByDate = FakeBookings.Get3Bookings();

                    _bookingRepository.GetByDate(Arg.Any <DateTime>()).Returns(bookingsGetByDate);
                    _tableRepository.GetAll().Returns(tablesGetAll);
                    var booking1 = bookingsGetByDate.Where(b => b.CustomerName == "Jane").First();

                    _bookingRepository.GetByID(Arg.Any <Guid>()).Returns(booking1);

                    var bookingService = new BookingService(_bookingRepository, _tableRepository);

                    var bookingRequest = new BookingRequestModel()
                    {
                        Seats        = 4,
                        Email        = "*****@*****.**",
                        CustomerName = "Jane",
                        Time         = DateTime.Now,
                        PhoneNumber  = "133337"
                    };

                    Guid guid = new Guid("3BFD706B-869A-40DE-910A-4D0CDB0FA095");

                    var actual = await bookingService.EditBooking(bookingRequest, guid);

                    actual.Success.Should().BeFalse();
                }
예제 #9
0
            public async void BookTable_WithNullBookingRequest_ReturnsFalse()
            {
                BookingRequestModel bookingRequest = null;

                var actual = await _service.ClientBookTable(bookingRequest);

                actual.Success.Should().BeFalse();
            }
 public async Task <IActionResult> Create([FromBody] BookingRequestModel booking)
 {
     try {
         return(Ok(await this.bookingService.Create(booking, int.Parse(User.Identity.Name))));
     } catch {
         return(BadRequest());
     }
 }
예제 #11
0
        public async Task <BookingResponseModel> NewBooking(BookingRequestModel request)
        {
            BookingResponseModel response = new BookingResponseModel();

            response.BookingReference = 12345;

            return(response);
        }
예제 #12
0
        public async Task <BookingResponseModel> AddBooking(BookingRequestModel bookingRequest)
        {
            var booking = _mapper.Map <Booking>(bookingRequest);

            booking.Status = "pending";
            var response = await _bookingRepository.AddAsync(booking);

            return(_mapper.Map <BookingResponseModel>(response));
        }
예제 #13
0
        public async Task <BookingResponseModel> AddBooking(BookingRequestModel model)
        {
            // check customer exist

            // add booking
            var bookingGuid             = Guid.NewGuid();
            var bookingDateLocationInfo = model.BookingDetail;
            var booking = new Booking
            {
                BookingCarPriceGuid = model.CarPrice.PriceRateId,
                BookingStatus       = BookingStatusEnum.Submitted.ToString(),
                CarId             = model.CarPrice.Car.Id,
                PickupDate        = bookingDateLocationInfo.PickupDate,
                ReturnDate        = bookingDateLocationInfo.ReturnDate,
                PickupLocation    = bookingDateLocationInfo.PickupLocation.Name,
                ReturnLocation    = bookingDateLocationInfo.ReturnLocation.Name,
                CustomerGuid      = model.CustomerGuid,
                CarName           = model.CarPrice.Car.Name,
                DriverAge         = model.DriverAge,
                DriverName        = model.DriverName,
                RowKey            = bookingGuid.ToString(),
                PartitionKey      = Constants.DefaultPartitionKey,
                CustomerFirstName = model.CustomerFirstName,
                CustomerLastName  = model.CustomerLastName,
                CustomerEmail     = model.CustomerEmail
                                    //SupplierId = model.CarPrice.Supplier.Id,
            };
            await _bookingTable.Insert(booking);

            // add carPrice
            var bookingPrice = new BookingCarPrice {
                RowKey       = bookingGuid.ToString(),
                PartitionKey = Constants.DefaultPartitionKey,
                CarId        = model.CarPrice.Car.Id,
                CarName      = model.CarPrice.Car.Name,
                CurrencyCode = model.CarPrice.CurrencyCode,
                Price        = model.CarPrice.Price,
                CarPriceRate = model.CarPrice.PriceRateId
                               //SupplierBasePrice = model.CarPrice.SupplierPrice
            };
            await _bookingCarPriceTable.Insert(bookingPrice);

            return(new BookingResponseModel {
                BookingGuid = bookingGuid, BookingStatus = booking.BookingStatus,
                CustomerEmail = booking.CustomerEmail,
                CustomerFirstName = booking.CustomerFirstName,
                CustomerLastName = booking.CustomerLastName,
                DriverName = booking.DriverName,
                PickupDate = booking.PickupDate,
                ReturnDate = booking.ReturnDate,
                PickupLocation = booking.PickupLocation,
                ReturnLocation = booking.ReturnLocation,
                CarPrice = model.CarPrice.Price,
                CarName = model.CarPrice.Car.Name
            });
        }
예제 #14
0
        public async Task <IActionResult> CreateReservation([FromBody] BookingRequestModel model)
        {
            try
            {
                var response = await _bookingService.CreateReservation(model);

                return(Ok(response));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
        public async Task <IActionResult> Post([FromBody] BookingRequestModel request)
        {
            var bookingRequest = new BookingRequest()
            {
                PropertyId = request.PropertyId,
                CustomerId = request.CustomerId,
                From       = request.Dates.From,
                To         = request.Dates.To
            };
            var requestId = await _bookingService.BookProperty(bookingRequest);

            return(Ok(requestId));
        }
예제 #16
0
        public async Task <IActionResult> UpdateBooking([FromBody] BookingRequestModel bookingRequestModel, Guid id)
        {
            var booking = await QueryRouter.QueryAsync <GetBookingById, Booking>(new GetBookingById(id));

            if (booking != null)
            {
                if (bookingRequestModel.totalPallets == 0)
                {
                    bookingRequestModel.totalPallets = booking.TotalPallets;
                }
                if (DateTimeEmpty(bookingRequestModel.bookingTime))
                {
                    bookingRequestModel.bookingTime = booking.BookingTime;
                }
                if (String.IsNullOrEmpty(bookingRequestModel.transporterName))
                {
                    bookingRequestModel.transporterName = booking.TransporterName;
                }
                if (bookingRequestModel.port == 0)
                {
                    bookingRequestModel.port = booking.Port;
                }
                if (DateTimeEmpty(bookingRequestModel.actualArrival))
                {
                    bookingRequestModel.actualArrival = booking.ActualArrival;
                }
                if (DateTimeEmpty(bookingRequestModel.startLoading))
                {
                    bookingRequestModel.startLoading = booking.StartLoading;
                }
                if (DateTimeEmpty(bookingRequestModel.endLoading))
                {
                    bookingRequestModel.endLoading = booking.EndLoading;
                }
                if (String.IsNullOrEmpty(bookingRequestModel.email))
                {
                    bookingRequestModel.email = booking.Email;
                }
                if (bookingRequestModel.ExternalId == 0)
                {
                    bookingRequestModel.ExternalId = booking.ExternalId;
                }
            }

            var result = await CommandRouter.RouteAsync <UpdateBookingCommand, IdResponse>(
                new UpdateBookingCommand(bookingRequestModel.totalPallets, bookingRequestModel.bookingTime,
                                         bookingRequestModel.transporterName, bookingRequestModel.port, bookingRequestModel.actualArrival,
                                         bookingRequestModel.startLoading, bookingRequestModel.endLoading, bookingRequestModel.email, id, bookingRequestModel.ExternalId));

            return(!result.IsSuccessful ? Conflict(result) : new ObjectResult(result));
        }
예제 #17
0
        public int AddStrataAdminBookingRequest(BookingRequestModel strataOwnerBookingRequestModel)
        {
            int result = 0;

            try
            {
                tblUserBookingRequest tblUserBookingRequestDb = new tblUserBookingRequest();
                tblUserBookingRequestDb.UserClientId   = ClientSessionData.UserClientId;
                tblUserBookingRequestDb.Subject        = strataOwnerBookingRequestModel.Subject;
                tblUserBookingRequestDb.FromDate       = !string.IsNullOrEmpty(strataOwnerBookingRequestModel.FromDate) ? Convert.ToDateTime(strataOwnerBookingRequestModel.FromDate) : (DateTime?)null;
                tblUserBookingRequestDb.ToDate         = !string.IsNullOrEmpty(strataOwnerBookingRequestModel.ToDate) ? Convert.ToDateTime(strataOwnerBookingRequestModel.ToDate) : (DateTime?)null;
                tblUserBookingRequestDb.Reason         = strataOwnerBookingRequestModel.Reason;
                tblUserBookingRequestDb.Status         = int.Parse(strataOwnerBookingRequestModel.Status);
                tblUserBookingRequestDb.AdminStatus    = strataOwnerBookingRequestModel.AdminStatus;
                tblUserBookingRequestDb.CommonAreaId   = strataOwnerBookingRequestModel.CommonAreaId;
                tblUserBookingRequestDb.CreatedOn      = DateTime.UtcNow;
                tblUserBookingRequestDb.ModifiedOn     = DateTime.UtcNow;
                tblUserBookingRequestDb.StratasBoardId = ClientSessionData.ClientStrataBoardId;

                // Get all the records related to that particular strataboard
                var UserRequests = _context.tblUserBookingRequests.Where(x => x.StratasBoardId == ClientSessionData.ClientStrataBoardId && x.CommonAreaId == strataOwnerBookingRequestModel.CommonAreaId && x.Status != 2).ToList();
                if (UserRequests != null && UserRequests.Count > 0)
                {
                    foreach (var item in UserRequests)
                    {
                        // Check any other booking is not there in the requested time slot
                        if ((Convert.ToDateTime(strataOwnerBookingRequestModel.FromDate) >= item.FromDate && Convert.ToDateTime(strataOwnerBookingRequestModel.FromDate) <= item.ToDate) ||
                            (Convert.ToDateTime(strataOwnerBookingRequestModel.ToDate) >= item.FromDate && Convert.ToDateTime(strataOwnerBookingRequestModel.ToDate) <= item.ToDate) ||
                            (Convert.ToDateTime(strataOwnerBookingRequestModel.FromDate) <= item.FromDate && Convert.ToDateTime(strataOwnerBookingRequestModel.ToDate) >= item.ToDate))
                        {
                            result = -1;
                            break;
                        }
                    }
                }


                if (result == 0)
                {
                    _context.tblUserBookingRequests.Add(tblUserBookingRequestDb);
                    result = _context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                new AppError().LogMe(ex);
                result = -2;
            }
            return(result);
        }
예제 #18
0
        public async Task <IActionResult> Initiate([FromBody] BookingRequestModel bookingRequest)
        {
            try
            {
                var trip = await this._tripRepository.GetByTripReferenceAsync(bookingRequest.TripReference);

                if (trip == null)
                {
                    return(NotFound(bookingRequest.TripReference));
                }

                // Verify if opted seats are available for booking
                foreach (var seat in bookingRequest.Seats)
                {
                    if (trip.Seats.Any(s => s.SeatNumber == seat && s.Status != SeatStatus.Available))
                    {
                        return(StatusCode(ErrorCodes.SEAT_NOT_AVAILABLE, nameof(ErrorCodes.SEAT_NOT_AVAILABLE)));
                    }
                }

                // Initiate booking for this trip
                var booking = new Booking
                {
                    BookingReference = StringHelper.RandomString(6),
                    TripReference    = bookingRequest.TripReference,
                    BookedSeats      = bookingRequest.Seats.ToArray()
                };

                var bookingRef = await this._bookingRepository.AddAsync(booking);

                // Update trip seat status for this booking to blocked
                foreach (var bookedSeat in booking.BookedSeats)
                {
                    var tripSeat = trip.Seats.FirstOrDefault(s => s.SeatNumber == bookedSeat);
                    if (tripSeat != null)
                    {
                        tripSeat.Status = SeatStatus.Blocked;
                    }
                }

                await this._tripRepository.UpdateAsync(trip);

                return(Ok(bookingRef));
            }
            catch (Exception ex)
            {
                _logger.LogError("{0}", ex);
                throw;
            }
        }
예제 #19
0
            public async void ClientBookTable_WithEmptyName_ReturnsFalse()
            {
                var bookingRequest = new BookingRequestModel()
                {
                    Seats        = 2,
                    Email        = "*****@*****.**",
                    CustomerName = "",
                    Time         = DateTime.Now.AddHours(2),
                    PhoneNumber  = "3758374"
                };

                var actual = await _service.ClientBookTable(bookingRequest);

                actual.Success.Should().BeFalse();
            }
예제 #20
0
                public async void TableAvailable_TableBookedAfter_ReturnsTrue()
                {
                    var tablesGetAll      = FakeTables.GetAll3x2Tables();
                    var bookingsGetByDate = FakeBookings.Get3Bookings1Late();

                    _bookingRepository.GetByDate(Arg.Any <DateTime>()).Returns(bookingsGetByDate);
                    _tableRepository.GetAll().Returns(tablesGetAll);

                    var bookingService = new BookingService(_bookingRepository, _tableRepository);

                    BookingRequestModel bookingRequest = ValidBooking(0);

                    var actual = await bookingService.AdminBookTable(bookingRequest);

                    actual.Success.Should().BeTrue();
                }
        public PartialViewResult LoadBookingList(string commonAreaId, string requestDate, string adminStatus, string pageNo, string pageSize = "10")
        {
            BookingRequestHelper helper = new BookingRequestHelper();
            BookingRequestModel  model  = new BookingRequestModel();

            model.StratasBoardId = ClientSessionData.ClientStrataBoardId;
            var bookingList = helper.GetBookingListing(model);


            if (!string.IsNullOrEmpty(commonAreaId))
            {
                bookingList = bookingList.Where(x => x.CommonAreaId == int.Parse(commonAreaId)).ToList();
            }

            if (!string.IsNullOrEmpty(requestDate))
            {
                bookingList = bookingList.Where(x => x.CreatedOn.ToShortDateString() == DateTime.Parse(requestDate).ToShortDateString()).ToList();
            }

            if (!string.IsNullOrEmpty(adminStatus))
            {
                bookingList = bookingList.Where(x => x.AdminStatus == int.Parse(adminStatus)).ToList();
            }


            int totalRecords = bookingList.Count;

            BookingRequestModelView bookingRequestModel = new BookingRequestModelView();

            bookingRequestModel.TotalPages = totalRecords / Convert.ToInt32(pageSize);
            if (totalRecords % Convert.ToInt32(pageSize) > 0)
            {
                bookingRequestModel.TotalPages++;
            }

            var skip = Convert.ToInt32(pageSize) * (Convert.ToInt32(pageNo) - 1);

            bookingRequestModel.ListBooking = bookingList.Skip(skip).Take(Convert.ToInt32(pageSize)).ToList();

            return(PartialView("_AdminBookingListPartial", bookingRequestModel));
        }
예제 #22
0
        public async Task <BookingModel> Create(BookingRequestModel model, long userId)
        {
            var validator = new BookingModelValidator().Validate(model);

            if (!validator.IsValid)
            {
                var error = validator.Errors;
                throw new TaskSchedulerException();
            }

            var vehicle = this.mapper.Map <Vehicle, VehicleModel>(await this.vehicleRepository.GetSingle(model.VehicleId));

            var rental = this.mapper.Map <BookingRequestModel, Booking>(model);

            rental.RentalAmount = vehicle.SimulateCost(model.NumberOfHours);
            rental.UserId       = userId;

            var query = this.bookingRepository.InsertIntoDatabase(rental);

            return(this.mapper.Map <Booking, BookingModel>(rental));
        }
예제 #23
0
        // POST api/book
        public async Task<IHttpActionResult> Post(BookingRequestModel model)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            if (model.BookingRequestId == Guid.Empty)
                model.BookingRequestId = NewId.NextGuid();

            var address = ConfigurationManager.AppSettings["BookMeetingAddress"];

            var endpoint = await WebApiApplication.Bus.GetSendEndpoint(new Uri(address));

            var request = new BookMeetingCommand(model);

            await endpoint.Send(request);

            return Accepted(new BookingRequestResult
            {
                BookingRequestId = model.BookingRequestId,
                Timestamp = request.Timestamp
            });
        }
예제 #24
0
        /// <summary>
        /// Update the booking status from StratasBoard Admin
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateAdminBookingStatus(BookingRequestModel model)
        {
            try
            {
                tblUserBookingRequest objModel = new tblUserBookingRequest();
                objModel             = context.tblUserBookingRequests.Where(x => x.BookingRequestId == model.BookingRequestId && x.Status == 1).FirstOrDefault();
                objModel.AdminUserId = ClientSessionData.UserClientId;
                objModel.ModifiedOn  = DateTime.UtcNow;
                objModel.AdminRemark = model.AdminRemark;
                objModel.AdminStatus = model.AdminStatus;

                context.tblUserBookingRequests.Attach(objModel);
                context.Entry(objModel).Property(x => x.AdminUserId).IsModified = true;
                context.Entry(objModel).Property(x => x.ModifiedOn).IsModified  = true;
                context.Entry(objModel).Property(x => x.AdminRemark).IsModified = true;
                context.Entry(objModel).Property(x => x.AdminStatus).IsModified = true;
                return(context.SaveChanges());
            }
            catch
            {
                return(-1);
            }
        }
예제 #25
0
            public async void Booking_AvailableTableTooSmall_ReturnsFalse()
            {
                var tablesGetAll      = FakeTables.GetAll4x2Tables();
                var bookingsGetByDate = FakeBookings.Get3Bookings();

                _bookingRepository.GetByDate(Arg.Any <DateTime>()).Returns(bookingsGetByDate);
                _tableRepository.GetAll().Returns(tablesGetAll);

                var bookingService = new BookingService(_bookingRepository, _tableRepository);

                var bookingRequest = new BookingRequestModel()
                {
                    Seats        = 4,
                    Email        = "*****@*****.**",
                    CustomerName = "notCoolguy",
                    Time         = DateTime.Now,
                    PhoneNumber  = "3758374"
                };

                var actual = await bookingService.ClientBookTable(bookingRequest);

                actual.Success.Should().BeFalse();
            }
예제 #26
0
        public Occupacy addOccupy(long IdBooking, long IdRoom)
        {
            try
            {
                BookingRequestModel booking = new BookingRequestModel();
                booking.IdBooking = IdBooking;
                booking.IdRoom    = IdRoom;

                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(tools.Constants.Base_URL);
                client.DefaultRequestHeaders.Add("API_KEY", "12354678");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
                HttpResponseMessage response = client.PutAsJsonAsync("Occupacies/PutOccupacy/", booking).Result;
                if (response.IsSuccessStatusCode)
                {
                    return(response.Content.ReadAsAsync <Occupacy>().Result);
                }
                return(null);
            }
            catch
            {
                return(null);
            }
        }
예제 #27
0
            public BookMeetingCommand(BookingRequestModel model)
            {
                _model = model;

                Timestamp = DateTime.UtcNow;
            }
 public IActionResult Post(BookingRequestModel requestModel)
 {
     return(Ok(bookingRequest.AddBookingRequest(requestModel)));
 }
예제 #29
0
        //*****modified by hoangle 10-10-2019
        //*****next modified by
        public IActionResult GetCartTotalFee(BookingRequestModel requestModel)
        {
            var result = _yachtService.GetRedisCartStorageTotalFee(requestModel);

            return(Ok(result));
        }
예제 #30
0
        public async Task <BookingResponseModel> EditBooking(BookingRequestModel bookingRequest, Guid bookingId)
        {
            if (bookingRequest == null)
            {
                return(new BookingResponseModel {
                    Success = false, ErrorMessage = "Bad request"
                });
            }

            if (bookingRequest.Seats <= 0 || bookingRequest.Seats > 6)
            {
                return(new BookingResponseModel {
                    Success = false, ErrorMessage = "Bad number of seats"
                });
            }

            var nameGreaterThan1     = bookingRequest.CustomerName.Length <= 1 ? true : false;
            var nameNotLongerThan50  = bookingRequest.CustomerName.Length > 50 ? true : false;
            var phoneNotShorterThan6 = bookingRequest.PhoneNumber.Length < 6 ? true : false;
            var phoneNotLongerThan25 = bookingRequest.PhoneNumber.Length > 25 ? true : false;

            if (nameGreaterThan1 || nameNotLongerThan50 || phoneNotShorterThan6 || phoneNotLongerThan25)
            {
                return(new BookingResponseModel {
                    Success = false, ErrorMessage = "Invalid name or phone number"
                });
            }

            bookingRequest.Time = bookingRequest.Time.AddMilliseconds(-bookingRequest.Time.Millisecond);
            bookingRequest.Time = bookingRequest.Time.AddSeconds(-bookingRequest.Time.Second);

            var now = DateTime.Now.AddMinutes(-5);

            now = now.AddMilliseconds(-now.Millisecond);
            now = now.AddSeconds(-now.Second - 1);

            //if (bookingRequest.Time < now)
            //{
            //    return new BookingResponseModel { Success = false, ErrorMessage = "Can't make a booking in the past" };
            //}

            List <Booking> bookingsOnDate;
            List <Table>   tables;

            try
            {
                bookingsOnDate = await _bookingRepository.GetByDate(bookingRequest.Time);

                tables = await _tableRepository.GetAll();
            }
            catch (Exception)
            {
                // logg error
                return(new BookingResponseModel {
                    Success = false, ErrorMessage = "Error connecting to database"
                });
            }

            List <Table> freeTables = new List <Table>();

            List <Booking> bookingsDuring2hInterval = new List <Booking>();

            foreach (var oldBooking in bookingsOnDate)
            {
                var newBookingStart = bookingRequest.Time.AddMinutes(1);
                var newBookingEnd   = bookingRequest.Time.AddHours(2).AddMinutes(-1);

                var oldBookingStart = oldBooking.Time.AddMinutes(1);
                var oldBookingEnd   = oldBooking.Time.AddHours(2).AddMinutes(-1);

                // if these are true add to interval
                var overlapOldBookingFirst = newBookingStart <oldBookingEnd && newBookingStart> oldBookingStart;
                var overlapNewBookingFirst = newBookingEnd > oldBookingStart && newBookingEnd < oldBookingEnd;


                if (overlapNewBookingFirst || overlapOldBookingFirst)
                {
                    bookingsDuring2hInterval.Add(oldBooking);
                }
            }

            var oldBookingToChange = await _bookingRepository.GetByID(bookingId);

            foreach (var table in tables)
            {
                if (oldBookingToChange.Table.Id == table.Id)
                {
                    freeTables.Add(table);
                }
                else if (!bookingsOnDate.Any(b => b.Table.Id == table.Id))
                {
                    freeTables.Add(table);
                }
            }

            freeTables.Sort((x, y) => x.Seats.CompareTo(y.Seats));
            Table selectedTable = new Table();

            foreach (var table in freeTables)
            {
                if (bookingRequest.Seats <= table.Seats)
                {
                    selectedTable = table;
                }
            }

            if (selectedTable == null || (selectedTable.Seats <= 0))
            {
                return(new BookingResponseModel {
                    Success = false, ErrorMessage = "No table available"
                });
            }

            oldBookingToChange.Seats        = bookingRequest.Seats;
            oldBookingToChange.PhoneNumber  = bookingRequest.PhoneNumber;
            oldBookingToChange.CustomerName = bookingRequest.CustomerName;
            oldBookingToChange.Time         = bookingRequest.Time;
            oldBookingToChange.Email        = bookingRequest.Email;
            oldBookingToChange.Table        = selectedTable;

            try
            {
                await _bookingRepository.EditAsync(bookingId, oldBookingToChange);
            }
            catch (Exception)
            {
                // log error
                return(new BookingResponseModel {
                    Success = false, ErrorMessage = "Error connecting to database"
                });
            }

            return(new BookingResponseModel {
                Success = true
            });
        }
예제 #31
0
        public JsonResult Post([FromBody] BookingRequestModel bookRQ)
        {
            BookingResponseModel bookRS = new BookingResponseModel();

            Website.Instance.logger.Info($"Gateway Router Start! KKday PkgOid:{bookRQ.order.packageOid},OrderMid:{bookRQ.order.orderMid}");

            string result = "";

            //https不需驗證
            HttpClientHandler handler = new HttpClientHandler();

            handler.ClientCertificateOptions = ClientCertificateOption.Manual;
            handler.ServerCertificateCustomValidationCallback =
                (httpRequestMessage, cert, cetChain, policyErrors) =>
            {
                return(true);
            };

            HttpClient client = new HttpClient(handler);

            client.DefaultRequestHeaders.Accept.Add(
                new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            try
            {
                //套餐與供應上API分流
                var xdoc = XDocument.Load(System.AppDomain.CurrentDomain.BaseDirectory + "//App_Data//RouteMapping.xml");
                if (xdoc.Descendants("item").Where(x => x.Element("kkday_pkg_oid").Value.Contains(bookRQ.order.packageOid)).Count() <= 0)
                {
                    Metadata metadata = new Metadata();
                    metadata.status      = "JTR-10002";
                    metadata.description = $"此套餐編號找不到串接的供應商,且不再即訂即付的商品項目中";
                    bookRS.metadata      = metadata;

                    return(Json(bookRS));
                }

                string sup = xdoc.Descendants("item").Where(x => x.Element("kkday_pkg_oid").Value.Contains(bookRQ.order.packageOid)).
                             Select(x => x.Element("sup").Value).FirstOrDefault().ToString();
                string sup_url = Website.Instance.Configuration[$"{sup}:BOOK_URL"];
                string sup_id  = Website.Instance.Configuration[$"{sup}:SUP_ID"];
                string sup_key = Website.Instance.Configuration[$"{sup}:SUP_KEY"];


                bookRQ.sup_id  = sup_id;
                bookRQ.sup_key = sup_key;

                string json = JsonConvert.SerializeObject(bookRQ);

                var contentData = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
                HttpResponseMessage response = client.PostAsync(sup_url, contentData).Result;

                Website.Instance.logger.Info($"Supplier:{sup},Booking URL:{sup_url},URL Response StatusCode:{response.StatusCode}");

                //與API串接失敗
                if (response.StatusCode.ToString() != "OK")
                {
                    throw new Exception(response.Content.ReadAsStringAsync().Result);
                }

                result = response.Content.ReadAsStringAsync().Result;
                bookRS = JsonConvert.DeserializeObject <BookingResponseModel>(result);
            }
            catch (Exception ex)
            {
                Metadata metadata = new Metadata();
                metadata.status      = "JTR-10002";
                metadata.description = $"Gateway Error :{ex.Message}";
                bookRS.metadata      = metadata;

                Website.Instance.logger.Fatal($"Gateway Error :{ex.Message},{ex.StackTrace}");
            }

            //回傳真正的JSON格式
            return(Json(bookRS));
        }
예제 #32
0
        public async Task <IActionResult> EditBooking(BookingRequestModel bookingRequest)
        {
            var booking = await _bookingService.UpdateBooking(bookingRequest);

            return(Ok(booking));
        }