Exemple #1
0
        //
        // GET: /RoomBooking/Edit/5


        public ActionResult SaveBookings()
        {
            List <CheckBoxModel> Rooms = TempData["list"] as List <CheckBoxModel>;

            foreach (var room in Rooms)
            {
                Booking     booking = dbBooking.Bookings.Find(room.BookingId);
                int         noDays  = (int)(booking.CheckOut - booking.CheckIn).TotalDays;
                Room        r       = dbRoom.Rooms.Find(room.Id);
                int         price   = r.Rate * noDays;
                RoomBooking rb      = new RoomBooking {
                    BookingId = room.BookingId, RoomId = room.Id, Price = price
                };
                db.RoomBookings.Add(rb);
            }
            db.SaveChanges();

            return(RedirectToAction("BookingDetails", "Booking", new { BookingId = Rooms.First().BookingId }));
        }
        public ActionResult RoomBookingEditByBookingID(int bookingID)
        {
            var         bookingData            = context.tbl_RoomBooking.SingleOrDefault(s => s.Booking_ID == bookingID);
            RoomBooking booking                = new RoomBooking();
            List <RoomBooking_Details> details = new List <RoomBooking_Details>();

            if (bookingData != null)
            {
                var prf = context.tbl_Profile.SingleOrDefault(b => b.ID == bookingData.UserID);

                booking.Booking_ID      = bookingID;
                booking.AdvancedPayment = bookingData.AdvancedPayment;
                booking.Amount          = bookingData.Amount;
                booking.AmtToBePaid     = bookingData.AmtToBePaid;
                booking.Bill_Number     = bookingData.Bill_Number;
                booking.Check_In        = bookingData.Check_In;
                booking.Check_Out       = bookingData.Check_Out;
                booking.Customer        = prf != null ? (prf.F_Name + " " + ((string.IsNullOrEmpty(prf.L_Name)) ? "" : prf.L_Name)) : "";
                booking.Discount        = bookingData.Discount;
                booking.GST             = bookingData.GST;
                booking.NoOfNightStays  = bookingData.NoOfNightStays;
                booking.Roombillno      = bookingData.Roombillno;
                booking.Mode_Of_Payment = bookingData.Mode_Of_Payment;
                var roomDet = context.tbl_RoomBooking_Details.Where(b => b.Booking_ID == bookingID).ToList();
                foreach (var i in roomDet)
                {
                    details.Add(new RoomBooking_Details()
                    {
                        ID                 = i.ID,
                        RoomID             = i.RoomID,
                        RoomNo             = context.tbl_Rooms.SingleOrDefault(a => a.ID == i.RoomID).RoomNo,
                        NoOfPerson         = i.NoOfPerson,
                        ExtraBed           = i.ExtraBed,
                        ComplementaryStays = i.ComplementaryStays == null?0: i.ComplementaryStays,
                        TAmtPerRoom        = i.TAmtPerRoom
                    });
                }


                booking.roomDetails = details;
            }
            return(View(booking));
        }
        public ActionResult CreateJSON(RoomBooking roomBooking)

        {
            /*
             * int RoomBookingID, int CustomerID, int Person, String RoomID,
             * string Name, string Phone, string Email, string CheckinDate, string CheckoutDate, string EmployeeID
             *
             * RoomBooking roomBooking = new RoomBooking();
             * roomBooking.RoomBookingID = RoomBookingID;
             * roomBooking.CustomerID = CustomerID;
             * roomBooking.Person = Person;
             * roomBooking.RoomID = RoomID;
             * roomBooking.Name = Name;
             * roomBooking.Phone = Phone;
             * roomBooking.Email = Email;
             * roomBooking.CheckinDate = DateTime.Parse(CheckinDate);
             * roomBooking.CheckoutDate = DateTime.Parse(CheckoutDate);
             * roomBooking.EmployeeID = EmployeeID;
             */

            System.Diagnostics.Debug.WriteLine(roomBooking.Person);
            System.Diagnostics.Debug.WriteLine(roomBooking.CheckoutDate);

            try
            {
                db.RoomBookings.Add(roomBooking);
                db.SaveChanges();
                SendMailService mailService = new SendMailService();
                mailService.toAddress = roomBooking.Email;
                mailService.body      = "ROOM BOOKING INFORMATIION\n" + "CustomerName: " + roomBooking.Name + "\n" + "Phone:" + roomBooking.Phone + "\n" + "RoomBookingID for Customer: " + roomBooking.RoomBookingID + "\n"
                                        + "Person:" + roomBooking.Person + "\n" + "CheckIn:" + roomBooking.CheckinDate + "\n" + "CheckOut:" + roomBooking.CheckoutDate;
                mailService.subject = "RoomBooking Information";
                mailService.sendMail();
                return(Json(new { status = true, roomBookingID = roomBooking.RoomBookingID }, JsonRequestBehavior.AllowGet));
            }catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());

                return(Json(new { status = false }, JsonRequestBehavior.AllowGet));
            }
        }
        //GET: RoomBookings/DeleteRoomBooking
        public ActionResult DeleteRoomBooking(int id, string hash)
        {
            RoomBooking roomBooking = db.RoomBookings.Where(x => x.RoomBookingID == id).SingleOrDefault();

            if (roomBooking != null)
            {
                HashCodeService hashCodeService = new HashCodeService();
                hash = hash.Replace(' ', '+');
                String hashCode = hashCodeService.createRoomBookingCancelCode(id, roomBooking.Email);

                if (hash.Equals(hashCode))
                {
                    roomBooking.Status          = "Canceled";
                    db.Entry(roomBooking).State = EntityState.Modified;
                    db.SaveChanges();
                    return(RedirectToAction("Search", "Home"));
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
        public static bool UpdateRB(RoomBooking rb, string reason)
        {
            HotelAPIManagementEntities hm = new HotelAPIManagementEntities();
            var item      = hm.RoomBookings.SingleOrDefault(s => s.IDRoomBook == rb.IDRoomBook);
            var idRoomOld = item.IDRoom;
            var roomOld   = item.Room.NameRoom;
            var roomNew   = hm.Rooms.SingleOrDefault(w => w.IDRoom == rb.IDRoom).NameRoom;

            item.IDRoom = rb.IDRoom;
            if (hm.SaveChanges() > 0)
            {
                var his = new HistoryBooking {
                    IDBook = rb.IDBook, NameHisBook = "Đổi phòng thành công (" + roomOld + " -> " + roomNew + ": " + reason + ")", DayCreateHisBook = DateTime.Now
                };
                HistoryBookingDAO.CreateHisBook(his);
                RoomDAO.UpdateRoomEmpty(idRoomOld);
                RoomDAO.UpdateRoomEmpty(rb.IDRoom);
                return(true);
            }
            return(false);
        }
Exemple #6
0
        public override async Task <BookGuestRoomOnAccount> HandleAsync(BookGuestRoomOnAccount command, CancellationToken cancellationToken = new CancellationToken())
        {
            Guid messageId;

            using (var uow = new BookingContext(_options))
            {
                using (var trans = uow.Database.BeginTransaction())
                {
                    var repository = new RoomBookingRepositoryAsync(new EFUnitOfWork(uow));

                    var roomBooking = new RoomBooking(
                        command.BookingId,
                        command.DateOfFirstNight,
                        command.NumberOfNights,
                        command.NumberOfGuests,
                        command.Type,
                        command.Price,
                        command.AccountId);

                    await repository.AddAsync(roomBooking, cancellationToken);

                    messageId = _messagePublisher.DepositPost(new GuestRoomBookingMade
                    {
                        BookingId        = roomBooking.RoomBookingId.ToString(),
                        DateOfFirstNight = roomBooking.DateOfFirstNight,
                        NumberOfGuests   = roomBooking.NumberOfGuests,
                        NumberOfNights   = roomBooking.NumberOfNights,
                        Type             = roomBooking.RoomType,
                        Price            = roomBooking.Price,
                        AccountId        = roomBooking.AccountId,
                    });

                    trans.Commit();
                }
            }

            _messagePublisher.ClearOutbox(messageId);

            return(await base.HandleAsync(command, cancellationToken));
        }
        //[HttpPost]
        public ActionResult Confirm(int?Id, string userid, string datefrom, string dateto, int roomId, bool payment)
        {
            //On this page user makes a booking and all information goes into the database

            // I used GET in form to generate the URL , now I know for sure what is passed
            // sample URL:localhost:44325/Room/Confirm/499f6a93-9072-47f9-af2e-898178d3c14b?fname=Ivan&lname=Bob&email=ivan%40bob.com&email=ADp9uemS4jRrtoFlyY6Slq0PBD75eJjLudcIuOv5Q63z%2F5g%2F1xa9gd3bBw3%2BwzQR5g%3D%3D&roomselected=Semi-private
            //&datefrom=2020-05-05&dateto=2020-05-10&roomId=2&payment=1

            //Creating new record of a booking with information provided
            string query = "insert into RoomBookings (RoomID, UserId, PaymentCleared, DateFrom, DateTo) values (@roomId, @userid, @payment, @datefrom, @dateto)";

            SqlParameter[] sqlparams = new SqlParameter[5];
            sqlparams[0] = new SqlParameter("@roomId", roomId);
            sqlparams[1] = new SqlParameter("@userid", userid);
            sqlparams[2] = new SqlParameter("@payment", payment);
            sqlparams[3] = new SqlParameter("@datefrom", datefrom);
            sqlparams[4] = new SqlParameter("@dateto", dateto);
            db.Database.ExecuteSqlCommand(query, sqlparams);

            //get all info about one room given the id
            Room Rooms = db.Rooms.SqlQuery("select * from Rooms where RoomID=@roomId", new SqlParameter("@roomId", roomId)).FirstOrDefault();

            //get the current user id when they logged in. Code reference Paul Tran
            string          userId      = User.Identity.GetUserId();
            ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == userId);
            //checking if  I get logged in user
            //Debug.WriteLine("User id is" + currentUser);

            //Getting information about specific booking given the user information

            RoomBooking selectedbooking = db.RoomBookings.SqlQuery("Select * from RoomBookings where UserId=@UserId", new SqlParameter("@UserId", userid)).FirstOrDefault();

            //Assigning values to the viewmodel
            RoomBookings viewmodel = new RoomBookings();

            viewmodel.User            = currentUser;
            viewmodel.Room            = Rooms;
            viewmodel.AllRoomBookings = selectedbooking;
            return(View(viewmodel));
        }
        // POST: api/RoomBookingWebApi
        public HttpResponseMessage Post([FromBody] RoomBooking roomBooking)
        {
            HttpResponseMessage response = null;

            try
            {
                if (ModelState.IsValid)
                {
                    db.RoomBookings.Add(roomBooking);
                    db.SaveChanges();

                    response         = new HttpResponseMessage(HttpStatusCode.OK);
                    response.Content = new StringContent("12345");
                    return(response);
                }

                List <string> errors = new List <string>();
                errors.Add("Insert Failed.");
                if (!ModelState.IsValidField("TotalPaid"))
                {
                    errors.Add("Total Paid must has a numeric value");
                }

                var s = string.Join("\n", errors);


                response         = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                response.Content = new StringContent(string.Join(" ", errors));

                return(response);
            }
            catch (Exception e)
            {
                response         = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                response.Content = new StringContent(e.Message);

                return(response);
            }
        }
Exemple #9
0
        // Creates a new booking
        public void CreateBooking(CreateBookingRequest request)
        {
            // Get the room
            var room = _context.Rooms.Where(rb => rb.RoomId == request.RoomId).FirstOrDefault();

            // Was the room found?
            if (room == null)
            {
                throw new NotFoundException();
            }

            // Check to see if the room capacity is sufficient
            if (request.PersonCount > room.Capacity || request.PersonCount < 1)
            {
                throw new RoomCapacityInsufficentException();
            }

            // Check to see if there are any conflicting bookings on the room
            if (_context.RoomBookings.Where(rb => rb.RoomId == request.RoomId &&
                                            rb.StartDate <= request.EndDate && rb.EndDate >= request.StartDate).ToList().Count > 0)
            {
                throw new RoomNotAvailableException();
            }

            // We are OK to insert the booking...
            var roomBooking = new RoomBooking
            {
                RoomId          = request.RoomId,
                AccountId       = request.AccountId,
                StartDate       = request.StartDate,
                EndDate         = request.EndDate,
                PersonCount     = request.PersonCount,
                CalculatedPrice = CalculateBookingPrice(request.StartDate, request.EndDate, room.Price)
            };

            _context.RoomBookings.Add(roomBooking);
            _context.SaveChanges();
        }
        public ActionResult Create([Bind(Include = "BookingId,BuildingId,RoomId,TenantEmail,RoomPrice,Status")] RoomBooking roomBooking)
        {
            var userName  = User.Identity.GetUserName();
            var roomPrice = _roomService.GetRooms().ToList().Where(p => p.RoomId == roomBooking.RoomId).Select(p => p.RoomPrice).FirstOrDefault();

            if (ModelState.IsValid)
            {
                roomBooking.TenantEmail     = userName;
                roomBooking.BuildingId      = roomBooking.GetBuildingName();
                roomBooking.DateOFBooking   = DateTime.Now.Date;
                roomBooking.RoomId          = roomBooking.RoomId;
                roomBooking.RoomPrice       = roomPrice;
                roomBooking.Status          = "Room Reserved";
                roomBooking.BuildingAddress = roomBooking.GetBuildingAddress();
                db.RoomBookings.Add(roomBooking);
                db.SaveChanges();
                return(RedirectToAction("Confirm", new { id = roomBooking.BookingId }));
            }

            ViewBag.BuildingId = new SelectList(db.buildings, "BuildingId", "BuildingName", roomBooking.BuildingId);
            ViewBag.RoomId     = new SelectList(db.Rooms, "RoomId", "RoomNumber", roomBooking.RoomId);
            return(View(roomBooking));
        }
Exemple #11
0
        public ActionResult Delete(int id = 0)
        {
            Booking booking = db.Bookings.Find(id);

            if (booking == null)
            {
                return(HttpNotFound());
            }

            var roomBookings = from t in dbRoomBooking.RoomBookings select t;

            roomBookings = roomBookings.Where(r => r.BookingId == id);
            foreach (var rB in roomBookings)
            {
                RoomBooking roomB = dbRoomBooking.RoomBookings.Find(rB.ID);
                dbRoomBooking.RoomBookings.Remove(roomB);
            }
            dbRoomBooking.SaveChanges();

            db.Bookings.Remove(booking);
            db.SaveChanges();
            return(RedirectToAction("BookingList"));
        }
Exemple #12
0
        public async Task When_mapping_a_guest_room_booking()
        {
            using (var uow = new BookingContext(_options))
            {
                //arrange
                var booking = new RoomBooking
                {
                    RoomBookingId    = Guid.NewGuid(),
                    DateOfFirstNight = new DateTime(2019, 07, 11),
                    Price            = 226,
                    RoomType         = RoomType.MasterSuite,
                    NumberOfGuests   = 3,
                    NumberOfNights   = 3,
                    AccountId        = Guid.NewGuid().ToString(),
                    LockedBy         = "SYS",
                    LockExpiresAt    = DateTime.Now.AddMilliseconds(500).Ticks.ToString()
                };

                var roomRepository = new RoomBookingRepositoryAsync(new EFUnitOfWork(uow));

                //act
                await roomRepository.AddAsync(booking);

                //assert
                await Task.Delay(50);

                var savedBooking = await roomRepository.GetAsync(booking.RoomBookingId);

                Assert.That(savedBooking.RoomBookingId, Is.EqualTo(booking.RoomBookingId));
                Assert.That(savedBooking.DateOfFirstNight, Is.EqualTo(booking.DateOfFirstNight));
                Assert.That(savedBooking.Price, Is.EqualTo(booking.Price));
                Assert.That(savedBooking.RoomType, Is.EqualTo(booking.RoomType));
                Assert.That(savedBooking.NumberOfGuests, Is.EqualTo(booking.NumberOfGuests));
                Assert.That(savedBooking.NumberOfNights, Is.EqualTo(booking.NumberOfNights));
                Assert.That(savedBooking.AccountId, Is.EqualTo(booking.AccountId));
            }
        }
        public async Task When_getting_a_booking_by_id()
        {
            using (var uow = new BookingContext(_options))
            {
                //arrange
                var booking = new RoomBooking
                {
                    RoomBookingId    = Guid.NewGuid(),
                    DateOfFirstNight = new DateTime(2019, 07, 11),
                    Price            = 226,
                    RoomType         = RoomType.MasterSuite,
                    NumberOfGuests   = 3,
                    NumberOfNights   = 3,
                    AccountId        = Guid.NewGuid().ToString(),
                    LockedBy         = "SYS",
                    LockExpiresAt    = DateTime.Now.AddMilliseconds(500).Ticks.ToString()
                };

                var repository = new RoomBookingRepositoryAsync(new EFUnitOfWork(uow));
                await repository.AddAsync(booking);

                var handler = new GetBookingByIdHandlerAsync(_options);

                //act
                var bookingResult = await handler.ExecuteAsync(new GetBookingById(booking.RoomBookingId));

                //assert
                Assert.That(bookingResult.BookingId, Is.EqualTo(booking.RoomBookingId.ToString()));
                Assert.That(bookingResult.DateOfFirstNight, Is.EqualTo(booking.DateOfFirstNight));
                Assert.That(bookingResult.Price, Is.EqualTo(booking.Price));
                Assert.That(bookingResult.RoomType, Is.EqualTo(booking.RoomType));
                Assert.That(bookingResult.NumberOfNights, Is.EqualTo(booking.NumberOfNights));
                Assert.That(bookingResult.NumberOfGuests, Is.EqualTo(booking.NumberOfGuests));
                Assert.That(bookingResult.AccountId, Is.EqualTo(booking.AccountId));
            }
        }
        public void ShouldCreateRoombooking()
        {
            var date         = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.AddDays(1).Day, 8, 0, 0, 0);
            var input        = new CreateRoomBookingInput(date, date.AddHours(1), 0, 0);
            var domain       = new RoomBooking(input.Start, input.End, input.RoomId, input.ClientId);
            var timeSlotRepo = new Mock <ITimeSlotRepository>();

            timeSlotRepo.Setup(m => m.GetAllOfPlace(0)).Returns(new List <TimeSlot> {
                new TimeSlot(date.DayOfWeek, 8, 0, 20, 0, 0)
            });

            var roomRepo = new Mock <IRoomRepository>();

            roomRepo.Setup(m => m.GetById(0)).Returns(new Room(0, "test", RoomType.Call));

            var roomBookingRepo = new Mock <IRoomBookingRepository>();

            roomBookingRepo.Setup(m => m.Create(domain)).Returns(0);

            var res =
                new CreateRoomBooking(roomBookingRepo.Object, timeSlotRepo.Object, roomRepo.Object, input).Execute();

            Assert.AreEqual(0, res);
        }
Exemple #15
0
 public static bool UpdateRB(RoomBooking rb, string reason)
 {
     return(RoomBookingDAO.UpdateRB(rb, reason));
 }
Exemple #16
0
 public static bool CreateRB(RoomBooking rb)
 {
     return(RoomBookingDAO.CreateRB(rb));
 }
Exemple #17
0
 /// <summary>
 /// Adds a new current record to the database and a version 1 record
 /// </summary>
 /// <param name="roomBooking">The roomBooking to add</param>
 /// <param name="ct">Operation cancellation</param>
 public async Task AddAsync(RoomBooking booking, CancellationToken ct = default(CancellationToken))
 {
     await _unitOfWork.AddAsync(booking, ct);
 }
Exemple #18
0
        public byte[] GeneratePDF(int BookingID)
        {
            MemoryStream memoryStream = new MemoryStream();
            Document     document     = new Document(PageSize.A5, 0, 0, 0, 0);
            PdfWriter    writer       = PdfWriter.GetInstance(document, memoryStream);

            document.Open();

            RoomBooking roomBooking = new RoomBooking();

            roomBooking = db.RoomBookings.Find(BookingID);
            var userName = User.Identity.GetUserName();
            var guest    = db.guests.Where(x => x.Email == userName).FirstOrDefault();

            iTextSharp.text.Font font_heading_3 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.RED);
            iTextSharp.text.Font font_body      = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9, iTextSharp.text.BaseColor.BLUE);

            // Create the heading paragraph with the headig font
            PdfPTable table1 = new PdfPTable(1);
            PdfPTable table2 = new PdfPTable(5);
            PdfPTable table3 = new PdfPTable(1);

            iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator();
            seperator.Offset = -6f;
            // Remove table cell
            table1.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            table3.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;

            table1.WidthPercentage = 80;
            table1.SetWidths(new float[] { 100 });
            table2.WidthPercentage = 80;
            table3.SetWidths(new float[] { 100 });
            table3.WidthPercentage = 80;

            PdfPCell cell = new PdfPCell(new Phrase(""));

            cell.Colspan = 3;
            table1.AddCell("\n");
            table1.AddCell(cell);
            table1.AddCell("\n\n");
            table1.AddCell(
                "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" +
                "Homelink \n" +
                "Email :[email protected]" + "\n" +
                "\n" + "\n");
            table1.AddCell("------------Your Details--------------!");

            table1.AddCell("Full Name : \t" + guest.FullName);
            table1.AddCell("Last Name : \t" + guest.LastName);
            table1.AddCell("Email : \t" + guest.Email);
            table1.AddCell("Phone Number : \t" + guest.Phone);
            table1.AddCell("Gender : \t" + guest.Gender);
            table1.AddCell("Address : \t" + guest.Address);

            table1.AddCell("\n------------Booking details--------------!\n");

            table1.AddCell("Booking # : \t" + roomBooking.RoomBookingId);
            table1.AddCell("Room Type : \t" + roomBooking.RoomType);
            table1.AddCell("Room Price Per Night: \t" + roomBooking.RoomPrice.ToString("C"));
            table1.AddCell("Arrival date : \t" + roomBooking.CheckInDate);
            table1.AddCell("Departure date : \t" + roomBooking.CheckOutDate);
            table1.AddCell("Number Of days : \t" + roomBooking.NumberOfDays);
            table1.AddCell("Number Of People : \t" + roomBooking.NumberOfPeople);
            table1.AddCell("Total Room Cost: \t" + roomBooking.Total.ToString("C"));

            table1.AddCell("\n");

            table3.AddCell("------------Looking forward to hear from you soon--------------!");

            //////Intergrate information into 1 document
            //var qrCode = iTextSharp.text.Image.GetInstance(reservation.QrCodeImage);
            //qrCode.ScaleToFit(200, 200);
            table1.AddCell(cell);
            document.Add(table1);
            //document.Add(qrCode);
            document.Add(table3);
            document.Close();

            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();
            return(bytes);
        }
Exemple #19
0
        public static BookRequest prepareSearchObj(ConfirmData data, string city)
        {
            //2019-07-27
            BookRequest Request = new BookRequest();

            Request.BookingDetails.ArrivalDate               = data.fromDate;
            Request.BookingDetails.CCAmount                  = "0";
            Request.BookingDetails.CCCardTypeID              = "0";
            Request.BookingDetails.CCIssueNumber             = "0";
            Request.BookingDetails.ContractArrangementID     = "0";
            Request.BookingDetails.ContractSpecialOfferID    = "0";
            Request.BookingDetails.Duration                  = data.Dur;
            Request.BookingDetails.LeadGuestAddress1         = "";
            Request.BookingDetails.LeadGuestBookingCountryID = "0";
            Request.BookingDetails.LeadGuestEmail            = "";
            var holder = data.hotelsBooking.Pax_Name.Split(' ');

            Request.BookingDetails.LeadGuestFirstName = holder[0];
            Request.BookingDetails.LeadGuestLastName  = holder[1];
            Request.BookingDetails.LeadGuestPhone     = "0";
            Request.BookingDetails.LeadGuestPostcode  = "0";
            Request.BookingDetails.LeadGuestTitle     = "Mr";

            Request.BookingDetails.PropertyID     = data.PropertyTS;
            Request.BookingDetails.Request        = "";
            Request.BookingDetails.TradeReference = data.hotelsBooking.Booking_No;
            var availRooms  = data.Rooms.Select(a => a.roomResult).ToList();
            var availReqobj = AvailabiltyManager.prepareAvailabilityObj(availRooms, data.PropertyTS, data.fromDate, data.Dur);
            var availResp   = CheckAvailability.GetTSAvailability(availReqobj, data.hotelsBooking.SessionId);

            if (availResp == null)
            {
                return(null);
            }
            Request.BookingDetails.PreBookingToken = availResp.PreBookingToken;
            foreach (var item in data.Rooms)
            {
                RoomBooking roomBooking = new RoomBooking();
                roomBooking.Adults              = item.roomResult.Adults.Value.ToString();
                roomBooking.Children            = item.roomResult.Childern.Value.ToString();
                roomBooking.Infants             = "0";
                roomBooking.MealBasisID         = item.roomResult.MealId;
                roomBooking.OptionalSupplements = "";
                roomBooking.PropertyRoomTypeID  = item.roomResult.RoomReference;

                if (item.roomResult.RoomReference == "0")
                {
                    roomBooking.BookingToken = item.roomResult.ProviderBookingKey;
                }
                foreach (var pax in item.bookingPaxes)
                {
                    Guest guest = new Guest();
                    guest.Age         = "0";
                    guest.DateOfBirth = "0001-01-01T00:00:00";
                    guest.Nationality = "";
                    guest.FirstName   = pax.First_name;
                    guest.LastName    = pax.Last_Name;
                    guest.Title       = pax.Salutations;
                    guest.Type        = pax.Pax_Type;
                    roomBooking.Guests.Guest.Add(guest);
                }

                Request.BookingDetails.RoomBookings.RoomBooking.Add(roomBooking);
            }
            return(Request);
        }
Exemple #20
0
        public ActionResult Reservation(ReservationViewModel details)
        {
            ReservationViewModel RVM = new ReservationViewModel();

            RVM = ((ReservationViewModel)Session["RVM"]);

            Guest_Details Guest = new Guest_Details();

            Guest = ((Guest_Details)Session["logindetails"]);



            if (ModelState.IsValid)
            {
                DateTime date = DateTime.Today;
                if (date <= details.reseravation.Check_In)
                {
                    if (details.reseravation.Check_In <= details.reseravation.Check_Out)
                    {
                        Reservation resrved  = new Reservation();
                        RoomBooking bookings = new RoomBooking();
                        Bill        bill     = new Bill();


                        int  No  = Convert.ToInt32(Session["RoomNo"]);
                        Room det = db.Rooms.Where(m => m.Room_Number == No).FirstOrDefault();
                        // IEnumerable<RoomBooking> reservedRooms = db.RoomBookings.Where(m => m.RoomNo == No).ToList().Where(a => (a.ArivalDate >= details.reseravation.Check_In) && a.DepartureDate <= details.reseravation.Check_Out);
                        var reservedRooms = db.RoomBookings.Where(r => !(r.ArivalDate >= details.reseravation.Check_Out) && !(r.DepartureDate <= details.reseravation.Check_In)).Distinct().ToList().Where(w => w.RoomNo == No).SingleOrDefault();

                        int packageid    = details.reseravation.Package_Id;
                        int?packageprice = db.Packages.Where(y => y.Package_ID == packageid).Select(p => p.Package_Price).SingleOrDefault();


                        int cap      = details.reseravation.Childrens + details.reseravation.Adults;
                        int capacity = Convert.ToInt32(Session["capasity"]);
                        if (cap <= capacity)
                        {
                            if (reservedRooms == null)
                            {
                                resrved.Guest_Id    = Guest.Guest_Id;
                                resrved.Package_Id  = details.reseravation.Package_Id;
                                resrved.Room_Number = No;
                                resrved.Check_In    = details.reseravation.Check_In;
                                resrved.Check_Out   = details.reseravation.Check_Out;
                                resrved.Adults      = details.reseravation.Adults;
                                resrved.Childrens   = details.reseravation.Childrens;
                                db.Reservations.Add(resrved);
                                db.SaveChanges();
                                Reservation lastRow = (from r in db.Reservations orderby r.Reservation_Id descending select r).FirstOrDefault();

                                bookings.ReservationId = lastRow.Reservation_Id;
                                bookings.ArivalDate    = details.reseravation.Check_In;
                                bookings.DepartureDate = details.reseravation.Check_Out;
                                bookings.RoomNo        = No;
                                bookings.CategoryId    = det.Room_Category_Id;
                                db.RoomBookings.Add(bookings);
                                db.SaveChanges();


                                bill.Reservation_ID = lastRow.Reservation_Id;
                                bill.Total_Charge   = packageprice;
                                db.Bills.Add(bill);
                                db.SaveChanges();

                                Session["lastReservation"] = lastRow;
                                // Session["RoomNo"]
                                //Session["capasity"]
                            }
                            else
                            {
                                ViewBag.Error = "Sorry," + Guest.Guest_Title + "." + Guest.Guest_First_Name + ".This Room is already Booked for the selected days.Please look for another room or select a different date";
                                return(View(RVM));
                            }
                        }
                        else
                        {
                            ViewBag.cap = "Sorry you can not select No.of heads more than capacity of the room ";
                            return(View(RVM));
                        }
                    }
                    else
                    {
                        ViewBag.date = "Check In Cannot be greater than Check Out";
                        return(View(RVM));
                    }
                }
                else
                {
                    ViewBag.date = "You Cannot reserve for past dates.select a valid date";
                    return(View(RVM));
                }
            }
            else
            {
                ModelState.AddModelError("E1", "invalid");
                return(View(RVM));
            }

            return(RedirectToAction("Email"));
        }
Exemple #21
0
 /// <summary>
 /// Update an roomBooking
 /// </summary>
 /// <param name="newBookingVersion">The new roomBooking version</param>
 /// <param name="aggregateLock">A pessimistic lock, retrieved from a Lock call, that allows us to update this guest roomBooking</param>
 /// <param name="ct">A token for operation cancellation</param>
 public async Task UpdateAsync(RoomBooking newBookingVersion, AggregateLock aggregateLock, CancellationToken ct = default(CancellationToken))
 {
     //find the next version to use
     await _unitOfWork.UpdateAsync(ct);
 }
Exemple #22
0
 private void btnCheckGuestOut_Click(object sender, EventArgs e)
 {
     RoomBooking.CheckGuestOut();
     RefreshDataSources();
 }
Exemple #23
0
        public int Add()
        {
            string   cusID = HttpContext.Session.GetString("CusID") ?? string.Empty;
            DateTime sDate = DateTime.ParseExact(HttpContext.Session.GetString("sDate"), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
            DateTime eDate = DateTime.ParseExact(HttpContext.Session.GetString("eDate"), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);

            if (cusID == null)
            {
                return(0);
            }

            double discount = 0;

            if (HttpContext.Session.GetInt32("Voucher") != null)
            {
                discount = (double)HttpContext.Session.GetInt32("Voucher");
            }
            double grandtotal = (double)(HttpContext.Session.GetInt32("GrandTotal") ?? 0);
            Bill   bill       = new Bill
            {
                Emp_ID            = "admin",
                Cus_ID            = cusID,
                Bill_Status       = 1,
                Bill_CheckInDate  = sDate,
                Bill_CheckOutDate = eDate,
                Bill_CusNum       = HttpContext.Session.GetInt32("numC") ?? 0,
                Bill_BookCost     = grandtotal * (double)((100 - discount) / 100),
                Bill_ExtraCost    = 0,
                Bill_Total        = grandtotal * ((100 - discount) / 100)
            };

            _context.Add(bill);
            _context.SaveChanges();
            int billid = bill.Bill_ID;


            string cartStr = HttpContext.Session.GetString("cart") ?? "";

            if (cartStr == "")
            {
                return(0);
            }
            JObject json = null;

            if (cartStr != "")
            {
                json = JObject.Parse(cartStr);
            }
            if (!json.HasValues)
            {
                return(0);
            }


            foreach (var item in json)
            {
                int roomid = (int)item.Value.SelectToken("Room");
                for (var day = sDate.Date; day < eDate.Date; day = day.AddDays(1))
                {
                    RoomBooking roomBooking = new RoomBooking
                    {
                        Bill_ID      = billid,
                        Room_ID      = roomid,
                        Booking_Date = day.Year * 10000 + day.Month * 100 + day.Day
                    };
                    _context.Add(roomBooking);
                }
            }
            _context.SaveChanges();



            //Mail
            var    message  = new MimeMessage();
            string cusEmail = HttpContext.Session.GetString("cusEmail");

            message.From.Add(new MailboxAddress("Royal HS", "*****@*****.**"));
            message.To.Add(new MailboxAddress("Mr. Luong Do", $"{cusEmail}"));

            string billID       = "#" + billid.ToString();
            string currDateTime = DateTime.Now.ToString(new CultureInfo("vi-vn"));


            string cusName    = HttpContext.Session.GetString("cusName");
            string cusPhone   = HttpContext.Session.GetString("cusPhone");
            string cusAddress = HttpContext.Session.GetString("cusAddress");

            string billCheckinDate  = sDate.ToString(new CultureInfo("vi-vn"));
            string billCheckoutDate = eDate.ToString(new CultureInfo("vi-vn"));
            string grandTotal       = (grandtotal * ((100 - discount) / 100)).ToString("C0", new CultureInfo("vi-vn"));

            message.Subject = $"Chi tiết hoá đơn đặt phòng {billID}";
            message.Body    = new TextPart("html")
            {
                Text = $"<table align=\"center\" bgcolor=\"#dcf0f8\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"margin:0;padding:0;background-color:#f2f2f2;width:100%!important;font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#444;line-height:18px\" width=\"100%\">	<tbody>		<tr>			<td align=\"center\" style=\"font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#444;line-height:18px;font-weight:normal\" valign=\"top\">			<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"margin-top:15px\" width=\"600\">				<tbody>					<tr style=\"background:#fff\">						<td align=\"left\" height=\"auto\" style=\"padding:15px\" width=\"600\">						<table>							<tbody>																<tr>									<td>									<h1 style=\"font-size:17px;font-weight:bold;color:#444;padding:0 0 5px 0;margin:0\">Cảm ơn quý khách {cusName} đã đặt hàng tại Royal HS,</h1>																		<p style=\"margin:4px 0;font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#444;line-height:18px;font-weight:normal\">Royal HS rất vui thông báo đơn hàng {billID} của quý khách đã được tiếp nhận và lưu trữ trên hệ thống.</p>																		<h3 style=\"font-size:13px;font-weight:bold;color:#02acea;text-transform:uppercase;margin:20px 0 0 0;border-bottom:1px solid #ddd\">Thông tin đơn hàng {billID} <span style=\"font-size:12px;color:#777;text-transform:none;font-weight:normal\">{currDateTime}</span></h3>									</td>								</tr>								<tr>									<td style=\"font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#444;line-height:18px\">									<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">										<thead>											<tr>												<th align=\"left\" style=\"padding:6px 9px 0px 9px;font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#444;font-weight:bold\" width=\"50%\">Thông tin thanh toán</th>												<th align=\"left\" style=\"padding:6px 9px 0px 9px;font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#444;font-weight:bold\" width=\"50%\"> Thời gian nhận phòng </th>											</tr>										</thead>										<tbody>											<tr>												<td style=\"padding:3px 9px 9px 9px;border-top:0;font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#444;line-height:18px;font-weight:normal\" valign=\"top\"><span style=\"text-transform:capitalize\">{cusName}</span><br>												<a href=\"mailto:{cusEmail}\" target=\"_blank\">{cusEmail}</a><br>												{cusPhone}<br>												{cusAddress}												</td>												<td style=\"padding:3px 9px 9px 9px;border-top:0;border-left:0;font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#444;line-height:18px;font-weight:normal\" valign=\"top\"><span style=\"text-transform:capitalize\">{billCheckinDate}</span><br>												 <br>												{billCheckoutDate}</td>											</tr>											<tr>											</tr>																																</tbody>									</table>									</td>								</tr>								<tr>									<td>									<p style=\"margin:4px 0;font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#444;line-height:18px;font-weight:normal\"><i>Lưu ý: Khi đến nhận phòng Homestay, nhân viên lễ tân có thể yêu cầu người nhận phòng cung cấp CMND / giấy phép lái xe để chụp ảnh hoặc ghi lại thông tin.</i></p>									</td>								</tr>																<tr>									<td>									<h2 style=\"text-align:left;margin:10px 0;border-bottom:1px solid #ddd;padding-bottom:5px;font-size:13px;color:#02acea\">CHI TIẾT ĐƠN HÀNG</h2>									<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:#f5f5f5\" width=\"100%\">										<thead>											<tr>												<th align=\"left\" bgcolor=\"#02acea\" style=\"padding:6px 9px;color:#fff;font-family:Arial,Helvetica,sans-serif;font-size:12px;line-height:14px\">STT</th>												<th align=\"left\" bgcolor=\"#02acea\" style=\"padding:6px 9px;color:#fff;font-family:Arial,Helvetica,sans-serif;font-size:12px;line-height:14px\">Nội dung</th>												<th align=\"right\" bgcolor=\"#02acea\" style=\"padding:6px 9px;color:#fff;font-family:Arial,Helvetica,sans-serif;font-size:12px;line-height:14px\">Thành tiền</th>											</tr>										</thead>										<tbody bgcolor=\"#eee\" style=\"font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#444;line-height:18px\">											<tr>												<td align=\"left\" style=\"padding:3px 9px\" valign=\"top\"><span>1</span><br>												</td>												<td align=\"left\" style=\"padding:3px 9px\" valign=\"top\"><span>Tiền thu thanh toán đặt phòng</span></td>												<td align=\"right\" style=\"padding:3px 9px\" valign=\"top\"><span>{grandTotal}</span></td>											</tr>											 										</tbody>																						<tr bgcolor=\"#eee\">												<td align=\"right\" colspan=\"2\" style=\"padding:7px 9px\"><strong><big>Tổng tiền thu</big> </strong></td>												<td align=\"right\" style=\"padding:7px 9px\"><strong><big><span>{grandTotal}</span> </big> </strong></td>											</tr>										</tfoot>									</table>									<div style=\"margin:auto\"><a href=\"\" style=\"display:inline-block;text-decoration:none;background-color:#00b7f1!important;margin-right:30px;text-align:center;border-radius:3px;color:#fff;padding:5px 10px;font-size:12px;font-weight:bold;margin-left:35%;margin-top:5px\" target=\"_blank\" data-saferedirecturl=\"https://www.google.com/url?q=https://tiki.vn/sales/order/trackingDetail?code%3D746504874&amp;source=gmail&amp;ust=1594303783242000&amp;usg=AFQjCNGrZAnCVbnSON_VTkwd8buaWR8Okw\">Chi tiết đơn hàng tại Royal HS</a></div>									</td>								</tr>																<tr>									<td>&nbsp;									<p style=\"margin:0;font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#444;line-height:18px;font-weight:normal\">Trường hợp quý khách có những băn khoăn về đơn hàng, có thể xem thêm mục <a href=\"\" title=\"Các câu hỏi thường gặp\" target=\"_blank\" data-saferedirecturl=\"https://www.google.com/url?q=http://hotro.Royal HS.vn/hc/vi/?utm_source%3Dtransactional%2Bemail%26utm_medium%3Demail%26utm_term%3Dlogo%26utm_campaign%3Dnew%2Border&amp;source=gmail&amp;ust=1594303783242000&amp;usg=AFQjCNGmdmxJvF88Zd8x_1a2R67nUyDO1Q\"> <strong>các câu hỏi thường gặp</strong>.</a></p>																		<p style=\"font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#444;line-height:18px;font-weight:normal;border:1px #14ade5 dashed;padding:5px;list-style-type:none\">Từ ngày 14/2/2015, Royal HS sẽ không gởi tin nhắn SMS khi đơn hàng của bạn được xác nhận thành công.</p>																		<p style=\"margin:10px 0 0 0;font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#444;line-height:18px;font-weight:normal\">Bạn cần được hỗ trợ ngay? Chỉ cần email <a href=\"mailto:hotro@Royal HS.vn\" style=\"color:#099202;text-decoration:none\" target=\"_blank\"> <strong>[email protected]</strong> </a>, hoặc gọi số điện thoại <strong style=\"color:#099202\">1900-6035</strong> (8-21h cả T7,CN). Đội ngũ Royal HS Care luôn sẵn sàng hỗ trợ bạn bất kì lúc nào.</p>									</td>								</tr>								<tr>									<td>&nbsp;									<p style=\"font-family:Arial,Helvetica,sans-serif;font-size:12px;margin:0;padding:0;line-height:18px;color:#444;font-weight:bold\">Một lần nữa Royal HS cảm ơn quý khách.</p>									<p style=\"font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#444;line-height:18px;font-weight:normal;text-align:right\"><strong><a  style=\"color:#00a3dd;text-decoration:none;font-size:14px\" target=\"_blank\" data-saferedirecturl=\"https://www.google.com/url?q=http://Royal HS.vn?utm_source%3Dtransactional%2Bemail%26utm_medium%3Demail%26utm_term%3Dlogo%26utm_campaign%3Dnew%2Border&amp;source=gmail&amp;ust=1594303783242000&amp;usg=AFQjCNEVrS3Bg5SZP6XsOKPbP6hMIB_CdA\">Royal HS</a> </strong></p>									</td>								</tr>							</tbody>						</table>						</td>					</tr>				</tbody>			</table>			</td>		</tr>		<tr>			<td align=\"center\">			<table width=\"600\">				<tbody>					<tr>						<td>						<p align=\"left\" style=\"font-family:Arial,Helvetica,sans-serif;font-size:11px;line-height:18px;color:#4b8da5;padding:10px 0;margin:0px;font-weight:normal\">Quý khách nhận được email này vì đã đặt phòng tại Royal HS.<br>						Để chắc chắn luôn nhận được email thông báo, xác nhận đặt phòng từ Royal HS, quý khách vui lòng thêm địa chỉ <strong><a href=\"mailto:hotro@Royal HS.vn\" target=\"_blank\">[email protected]</a></strong> vào số địa chỉ (Address Book, Contacts) của hộp email.<br>						<b>Văn phòng Royal HS:</b> 52 Út Tịch, phường 4, quận Tân Bình, thành phố Hồ Chí Minh, Việt Nam<br>						Bạn không muốn nhận email từ Royal HS? Hủy đăng ký tại <a>đây</a>.</p>						</td>					</tr>				</tbody>			</table>			</td>		</tr>	</tbody></table>"
            };

            using (var client = new SmtpClient())
            {
                client.Connect("smtp.gmail.com", 587);

                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                client.Authenticate("*****@*****.**", "**********");

                client.Send(message);
                client.Disconnect(true);
            }


            HttpContext.Session.Clear();

            return(1);
        }
Exemple #24
0
        //TODO BookingDocument

        protected override Booking DoPostPutDto(Client currentClient, BookingDTO dto, Booking entity, string path, object param)
        {
            if (entity == null)
            {
                entity = new Booking();
            }
            GetMapper.Map <BookingDTO, Booking>(dto, entity);

            HomeConfig hc = HomeConfigRepository.GetHomeConfigById(entity.HomeId, currentClient.Id);

            if (hc != null)
            {
                if (hc.DefaultHourCheckIn != null)
                {
                    entity.DateArrival = ((DateTime)entity.DateArrival).Date.Add(hc.DefaultHourCheckInToTimeSpan);
                }
                if (hc.DefaultHourCheckOut != null)
                {
                    entity.DateDeparture = ((DateTime)entity.DateDeparture).Date.Add(hc.DefaultHourCheckOutToTimeSpan);
                }
            }
            if (dto.People != null)
            {
                entity.People = PeopleService.PreProcessDTOPostPut(validationDictionnary, dto.HomeId, dto.People, currentClient, path);
            }
            if (dto.AdditionalBookings != null)
            {
                AdditionalBookingRepository.DeleteRange(entity.AdditionalBookings.Where(d => !dto.AdditionalBookings.Any(x => x.Id == d.Id)));
                dto.AdditionalBookings.ForEach(additionalBooking =>
                {
                    if (entity.AdditionalBookings.Count != 0 && additionalBooking.Id != 0 &&
                        entity.AdditionalBookings.Find(p => p.Id == additionalBooking.Id) != null)
                    {
                        return;
                    }
                    AdditionalBooking toAdd = AdditionalBookingService.PreProcessDTOPostPut(validationDictionnary, dto.HomeId, additionalBooking, currentClient, path);

                    if (toAdd != null)
                    {
                        entity.AdditionalBookings.Add(toAdd);
                    }
                });
            }
            if (dto.BookingStepBooking != null)
            {
                entity.BookingStepBooking = BookingStepBookingService.PreProcessDTOPostPut(validationDictionnary, dto.HomeId, dto.BookingStepBooking, currentClient, path);
            }
            if (dto.Deposits != null)
            {
                DepositRepository.DeleteRange(entity.Deposits.Where(d => !dto.Deposits.Any(x => x.Id == d.Id)));
                dto.Deposits.ForEach(deposit =>
                {
                    if (entity.Deposits.Count != 0 && deposit.Id != 0 &&
                        entity.Deposits.Find(p => p.Id == deposit.Id) != null)
                    {
                        return;
                    }
                    Deposit toAdd = DepositService.PreProcessDTOPostPut(validationDictionnary, dto.HomeId, deposit, currentClient, path);

                    if (toAdd != null)
                    {
                        entity.Deposits.Add(toAdd);
                    }
                });
            }
            if (dto.DinnerBookings != null)
            {
                DinnerBookingRepository.DeleteRange(entity.DinnerBookings.Where(d => !dto.DinnerBookings.Any(x => x.Id == d.Id)));
                dto.DinnerBookings.ForEach(dinnerBooking =>
                {
                    if (entity.DinnerBookings.Count != 0 && dinnerBooking.Id != 0 &&
                        entity.DinnerBookings.Find(p => p.Id == dinnerBooking.Id) != null)
                    {
                        return;
                    }
                    DinnerBooking toAdd = DinnerBookingService.PreProcessDTOPostPut(validationDictionnary, dto.HomeId, dinnerBooking, currentClient, path);

                    if (toAdd != null)
                    {
                        entity.DinnerBookings.Add(toAdd);
                    }
                });
            }
            if (dto.ProductBookings != null)
            {
                ProductBookingRepository.DeleteRange(entity.ProductBookings.Where(d => !dto.ProductBookings.Any(x => x.Id == d.Id)));
                dto.ProductBookings.ForEach(productBooking =>
                {
                    if (entity.ProductBookings.Count != 0 && productBooking.Id != 0 &&
                        entity.ProductBookings.Find(p => p.Id == productBooking.Id) != null)
                    {
                        return;
                    }
                    ProductBooking toAdd = ProductBookingService.PreProcessDTOPostPut(validationDictionnary, dto.HomeId, productBooking, currentClient, path);

                    if (toAdd != null)
                    {
                        entity.ProductBookings.Add(toAdd);
                    }
                });
            }
            if (dto.RoomBookings != null)
            {
                RoomBokingRepository.DeleteRange(entity.RoomBookings.Where(d => !dto.RoomBookings.Any(x => x.Id == d.Id)));
                dto.RoomBookings.ForEach(roomBooking =>
                {
                    if (entity.RoomBookings.Count != 0 && roomBooking.Id != 0 &&
                        entity.RoomBookings.Find(p => p.Id == roomBooking.Id) != null)
                    {
                        return;
                    }
                    RoomBooking toAdd = RoomBookingService.PreProcessDTOPostPut(validationDictionnary, dto.HomeId, roomBooking, currentClient, path);

                    if (toAdd != null)
                    {
                        entity.RoomBookings.Add(toAdd);
                    }
                });
            }
            entity.DateCreation = DateTime.UtcNow;
            return(entity);
        }
Exemple #25
0
        public ActionResult BookingRoomDateView(BookingRoomDateViewModles model)
        {
            using (var context = HttpContext.GetOwinContext().Get <ApplicationDbContext>())
            {
                var DepartureDate = model.DateArrival.AddDays(model.NoOfDaysStayed);
                var query         =
                    //(
                    from Room in context.Rooms
                    join Booking in context.Bookings
                    on Room.RoomId equals Booking.Room.RoomId into RoomBooking
                    from Booking in RoomBooking.DefaultIfEmpty()
                    select new
                {
                    FoundRoom    = Room,
                    FoundBooking = Booking
                };
                //).FirstOrDefault();

                Room foundRoom = null;

                foreach (var rom in query)
                {
                    if (rom.FoundRoom.Bookings == null)
                    {
                        foundRoom = rom.FoundRoom;
                        break;
                    }
                    if (rom.FoundBooking.ArrivalDate > model.DateArrival.AddDays(model.NoOfDaysStayed) ||
                        rom.FoundBooking.DepartureDate < model.DateArrival)
                    {
                        foundRoom = rom.FoundRoom;
                        break;
                    }
                }

                if (foundRoom == null)
                {
                    return(RedirectToAction("NoRoomFound"));
                }

                var newBooking = new Booking
                {
                    Price         = foundRoom.Price,
                    Payed         = false,
                    ArrivalDate   = model.DateArrival,
                    DepartureDate = model.DateArrival.AddDays(model.NoOfDaysStayed),
                    AadOns        = "",
                    ChechIn       = 0,
                    ChechOut      = 0,

                    ApplicationUser = UserManager.FindById(User.Identity.GetUserId()),
                    Room            = foundRoom
                };

                var             pay        = new BasePayment(newBooking);
                LoyaltyDiscount decorator1 = new LoyaltyDiscount(pay);

                if (foundRoom.Bookings == null)
                {
                    foundRoom.Bookings = new List <Booking>
                    {
                        newBooking
                    };

                    context.SaveChanges();
                }
                else
                {
                    foundRoom.Bookings.Add(newBooking);
                }


                context.SaveChanges();
            }

            return(RedirectToAction("Index"));
        }
Exemple #26
0
        public void Create(RoomBooking roomBookingToCreate)
        {
            var newBookingRow = MapToRoomBookingRow(roomBookingToCreate);

            _database.RoomBookingRows.Add(newBookingRow.Id, newBookingRow);
        }
Exemple #27
0
 public static decimal calcTotalRoomCost(RoomBooking roomBooking)
 {
     return(GetRoomPrice(roomBooking.RoomId) * GetNumberDays(roomBooking.CheckInDate, roomBooking.CheckOutDate));
 }