Exemple #1
0
        public IActionResult ProcessBookingSelection(Inquiry inquiry, long cartID, long cartItemID, int resourceTypeID, int rateCompositionID, int numberOfUnits, int numberOfGuests, decimal pricePerUnit)
        {
            inquiry.DateOfInquiry = System.DateTime.Now;
            inquiry.ChannelID     = 100;
            string userID = "system";
            Cart   cCart  = (shopRepository.GetCart(cartID) ?? shopRepository.CreateCart(inquiry, userID));

            CartItem cCartItem = shopRepository.GetCartItem(cartItemID);

            if (cCartItem == null)
            {
                cCart = shopRepository.AddCartItemToCart(cCart, resourceTypeID, rateCompositionID, inquiry.DateOfArrival, inquiry.DateOfDeparture, numberOfUnits, pricePerUnit);
            }
            else
            {
                cCart = shopRepository.UpdateCartItemInCart(cCartItem, rateCompositionID, numberOfUnits, numberOfGuests, pricePerUnit);
            }

            CreateBookingViewModel cBVM = new CreateBookingViewModel()
            {
                Inquiry              = inquiry,
                Cart                 = cCart,
                Channels             = bookingRepository.GetChannels(),
                OfferedResourceTypes = availabilityRepsository.GetOfferedResourceTypes(inquiry),
                ResourceTypes        = bookingRepository.GetResourceTypes(inquiry.CompanyID),
                RateCompositions     = bookingRepository.GetRateCompositions(inquiry.CompanyID)
            };

            return(View(nameof(CreateBooking), cBVM));
        }
        public async Task <IActionResult> AttachBooking([Bind] CreateBookingViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    model.TheBooking.StartDateTime  = DateTime.Parse(model.dt1);
                    model.TheBooking.EndDateTime    = DateTime.Parse(model.dt2);
                    model.TheTimeslot.StartDateTime = DateTime.Parse(model.dt1);
                    model.TheTimeslot.EndDateTime   = DateTime.Parse(model.dt2);

                    await bookTimeslot.TryBookTimeslot(model.TheTimeslot, model.TheBooking);

                    return(StatusCode(200));
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    return(BadRequest(new { Message = ex.Message }));
                }
                catch (Exception ex)
                {
                    return(BadRequest(new { Message = ex.Message }));
                }
            }
            return(BadRequest(new { Message = "State not valid" }));
        }
        private bool ValidateBooking(Booking booking)
        {
            bool isValid = true;

            // Check if from date is after To date
            if (booking.From > booking.To)
            {
                ModelState.AddModelError("Booking.From", "Start date cannot be after end date");
                var createBookingViewModel = new CreateBookingViewModel()
                {
                    Tracks = DbContext.Tracks, Booking = booking
                };
                isValid = false;
            }

            //1. Hämta ut alla bokning som har samma roomId som den nya bokningen
            List <Booking> bookingsFromDb = DbContext.Bookings.Where(b => b.TrackId == booking.TrackId).ToList();

            //2. Kolla om något av dessa bokningar har överlappande datum
            foreach (var oldBooking in bookingsFromDb)
            {
                if (DateHelpers.HasSharedDateIntervals(booking.From, booking.To, oldBooking.From, oldBooking.To))
                {
                    ModelState.AddModelError("Booking.From", "Date already occupied.");
                    var createBookingViewModel = new CreateBookingViewModel()
                    {
                        Tracks = DbContext.Tracks, Booking = booking
                    };
                    isValid = false;
                }
            }

            return(isValid);
        }
Exemple #4
0
        private bool ValidateBooking(Booking booking)
        {
            bool isValid = true;

            //Check if From date is after To date
            if (booking.From > booking.To)
            {
                ModelState.AddModelError("Booking.From", "Start date cannot be after end date");
                var CreateBookingViewModel = new CreateBookingViewModel()
                {
                    Giraffes = DbContext.Giraffes, Booking = booking
                };
                isValid = false;
            }
            //1. Fetch all bookings with the same GiraffeID as the new one

            List <Booking> oldBookings = DbContext.Bookings.Where(b => b.GiraffeId == booking.GiraffeId).ToList();

            //2. Check if any of the dates in the bookings overlap
            foreach (var oldBooking in oldBookings)
            {
                if (DateHelpers.HasSharedDateInterval(booking.From, booking.To, oldBooking.From, oldBooking.To))
                {
                    ModelState.AddModelError("Booking.From", "Date already occupied.");
                    var createBookingViewModel = new CreateBookingViewModel()
                    {
                        Giraffes = DbContext.Giraffes, Booking = booking
                    };
                    isValid = false;
                }
            }
            return(isValid);
        }
        public IActionResult CreateBooking(CreateBookingViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }


            var user = this._context.Users.FirstOrDefault(u => u.Id == model.CostumerId);

            if (user != null)
            {
                Booking booking = new Booking()
                {
                    Id             = Guid.NewGuid(),
                    Time           = model.Time,
                    BookingAddress = model.BookingAddress,
                    UserId         = model.CostumerId,
                    ServiceType    = model.ServiceType,
                    Title          = model.Vehicle,
                    CreatedAt      = DateTime.UtcNow,
                    UpdatedAt      = DateTime.UtcNow,
                };
                this._context.Bookings.Add(booking);
                this._context.SaveChanges();
            }



            return(RedirectToAction("Index"));
        }
        public ActionResult CreateForm()
        {
            HomeDepotContext _context  = new HomeDepotContext();
            var createBookingViewModel = new CreateBookingViewModel();

            return(View(createBookingViewModel));
        }
Exemple #7
0
        public async Task <IActionResult> Book(CreateBookingViewModel model)
        {
            if (ModelState.IsValid)
            {
                Table   table   = _db.Tables.FirstOrDefault(t => t.Id == model.TableId);
                Booking booking = new Booking()
                {
                    ClientName   = model.ClientName,
                    BookFrom     = model.BookFrom,
                    BookTo       = model.BookTo,
                    Comment      = model.Comment,
                    RestaurantId = table.RestaurantId,
                    Pax          = model.Pax,
                    PhoneNumber  = model.PhoneNumber,
                    Email        = model.Email,
                };
                if (model.Date == "today")
                {
                    booking.Date = DateTime.Today.ToShortDateString();
                }
                else if (model.Date == "tomorrow")
                {
                    booking.Date = DateTime.Today.AddDays(1).ToShortDateString();
                }
                else if (model.Date == "custom")
                {
                    booking.Date = model.CustomDate;
                }
                else
                {
                    return(PartialView("PartialViews/BookTableModalPartialView", model));
                }

                if (SessionHelper.GetObjectFromJson <List <Item> >(HttpContext.Session, "booking") == null)
                {
                    List <Booking> items = new List <Booking>();
                    items.Add(booking);
                    SessionHelper.SetObjectAsJson(HttpContext.Session, "booking", items);
                }
                else
                {
                    List <Booking> items = SessionHelper.GetObjectFromJson <List <Booking> >(HttpContext.Session, "booking");
                    items.Add(booking);
                    SessionHelper.SetObjectAsJson(HttpContext.Session, "booking", items);
                }
                _db.Entry(booking).State = EntityState.Added;
                BookingTable bookingTable = new BookingTable()
                {
                    BookingId = booking.Id,
                    TableId   = model.TableId
                };
                _db.Entry(bookingTable).State = EntityState.Added;
                await _db.SaveChangesAsync();

                return(Json(new{ status = "success" }));
            }

            return(PartialView("PartialViews/BookTableModalPartialView", model));
        }
        // GET: Bookings/Create
        public IActionResult Create()
        {
            var createBookingViewModel = new CreateBookingViewModel()
            {
                Tracks = DbContext.Tracks
            };

            return(View(createBookingViewModel));
        }
Exemple #9
0
        public IActionResult Create()
        {
            var CreateBookingViewModel = new CreateBookingViewModel()
            {
                Giraffes = DbContext.Giraffes
            };

            return(View(CreateBookingViewModel));
        }
        // GET: Bookings/Create
        public IActionResult Create()
        {
            var createBookingViewModel = new CreateBookingViewModel()
            {
                Rooms = DbContextLista.Rooms
            };

            return(View(createBookingViewModel));
        }
Exemple #11
0
 public CreateBookingDTO CreateBookingDto(CreateBookingViewModel createBookingViewModel)
 {
     return(new CreateBookingDTO
     {
         Name = createBookingViewModel.Name,
         BookingDateTime = createBookingViewModel.BookingDateTime,
         Flexibility = (Flexibility)createBookingViewModel.Flexibility,
         VehicleSize = (VehicleSize)createBookingViewModel.VehicleSize,
         ContactNumber = createBookingViewModel.ContactNumber,
         EmailAddress = createBookingViewModel.EmailAddress
     });
 }
Exemple #12
0
        // GET: Booking
        public ActionResult Index()
        {
            var roomtypes       = _roomrepo.FindAll().ToList();
            var mappedRoomTypes = _mapper.Map <List <RoomType>, List <RoomTypeViewModel> >(roomtypes);
            var model           = new CreateBookingViewModel
            {
                RoomTypes     = mappedRoomTypes,
                NumberUpdated = 0
            };

            return(View(model));
        }
Exemple #13
0
        public async Task <ActionResult> Index(CreateBookingViewModel createBookingViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(createBookingViewModel));
            }

            var bookingDto = _bookingFactory.CreateBookingDto(createBookingViewModel);

            await _bookingService.CreateBookingAsync(bookingDto);

            return(View("CreateSuccess"));
        }
Exemple #14
0
        public IActionResult Book(int id, string date, string customDate, string timeFrom, string timeTo)
        {
            CreateBookingViewModel bookingTable = new CreateBookingViewModel()
            {
                TableId    = id,
                BookFrom   = timeFrom,
                BookTo     = timeTo,
                Date       = date,
                CustomDate = customDate
            };

            return(PartialView("PartialViews/BookTableModalPartialView", bookingTable));
        }
Exemple #15
0
        public ActionResult Create(string id)
        {
            if (id is null)
            {
                throw new ArgumentNullException(nameof(id));
            }

            if (ModelState.IsValid)
            {
                try
                {
                    List <Bike>        bikes    = context.Bikes.Where(b => b.CustomerId == id).ToList();
                    List <BikeService> services = context.BikeServices.ToList();

                    List <SelectListItem> bikesSelectList = new List <SelectListItem>();
                    foreach (Bike bike in bikes)
                    {
                        bikesSelectList.Add(new SelectListItem()
                        {
                            Value = bike.Id.ToString(),
                            Text  = bike.Model
                        });
                    }

                    List <SelectListItem> servicesSelectList = new List <SelectListItem>();
                    foreach (BikeService service in services)
                    {
                        servicesSelectList.Add(new SelectListItem()
                        {
                            Value = service.Id.ToString(),
                            Text  = service.Name
                        });
                    }

                    CreateBookingViewModel viewModel = new CreateBookingViewModel
                    {
                        Date         = DateTime.Now.AddHours(2), // Default value
                        Bikes        = bikesSelectList,
                        BikeServices = servicesSelectList
                    };

                    return(View(viewModel));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: " + ex.Message);
                    return(RedirectToAction("Index", "Home"));
                }
            }
            return(RedirectToAction("Index", "Home"));
        }
        public async Task <ActionResult> Create()
        {
            var customers = (await _customerService.GetCustomer()).Items;
            var products  = (await _productService.GetProduct()).Items;

            var model = new CreateBookingViewModel
            {
                Customers         = customers,
                Products          = products,
                LoginInformations = await _sessionAppService.GetCurrentLoginInformations(),
            };

            return(View("Create", model));
        }
Exemple #17
0
        public ActionResult Create(CreateBookingViewModel model)
        {
            if (ModelState.IsValid)
            {
                model.TotalPrice = 50;
                db.Bookings.Add(new Booking()
                {
                    StartTime = model.StartTime, EndTime = model.EndTime, TotalPrice = model.TotalPrice, UserId = model.UserId, ComputerId = model.ComputerId
                });
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
Exemple #18
0
        //[HttpPost]
        //public IActionResult CreateNewBooking(string companyID, int channelID, int resourceTypeID, int rateCompositionID,
        //    DateTime dateOfArrival, DateTime dateOfDeparture, int numberOfUnits, int numberOfGuests, string guestNames, string userID)
        //{
        //    string sCompanyID = companyID ?? "B68162";

        //    Cart newCart = new Cart();
        //    newCart = shopRepository.CreateCart(inquiry, userID);

        //    newBooking = bookingRepository.AddBookingItem(newBooking, resourceTypeID, rateCompositionID, numberOfUnits, numberOfGuests, guestNames, dateOfArrival, dateOfDeparture);

        //    CreateBookingViewModel cBVM = new CreateBookingViewModel()
        //    {
        //        Booking = newBooking,
        //        ResourceTypes = bookingRepository.GetResourceTypes(companyID),
        //        Channels = bookingRepository.GetChannels(),
        //        RateCompositions = bookingRepository.GetRateCompositions(companyID),
        //    };
        //    return View(nameof(CreateBooking), cBVM);
        //}

        public IActionResult GetAvailabilities(string companyID, DateTime dateOfArrival, DateTime dateOfDeparture)
        {
            Inquiry inquiry = new Inquiry()
            {
                CompanyID       = "B68162",
                DateOfArrival   = dateOfArrival,
                DateOfDeparture = dateOfDeparture,
                DateOfInquiry   = DateTime.Now
            };

            CreateBookingViewModel cBVM = new CreateBookingViewModel()
            {
                Inquiry = inquiry,
                ResourceTypeUnitsAvailableForSale = availabilityRepsository.GetResourceTypesNumberOfUnitsAvailable(inquiry),
                OfferedResourceTypes = availabilityRepsository.GetOfferedResourceTypes(inquiry)
            };

            return(View(nameof(CreateBooking), cBVM));
        }
Exemple #19
0
        public IActionResult CreateBooking()
        {
            Inquiry inquiryDefault = new Inquiry()
            {
                CompanyID       = "B68162",
                DateOfArrival   = System.DateTime.Now,
                DateOfDeparture = System.DateTime.Now.AddDays(1)
            };

            CreateBookingViewModel cBVM = new CreateBookingViewModel()
            {
                Inquiry          = inquiryDefault,
                ResourceTypes    = bookingRepository.GetResourceTypes(inquiryDefault.CompanyID),
                Channels         = bookingRepository.GetChannels(),
                RateCompositions = bookingRepository.GetRateCompositions(inquiryDefault.CompanyID),
            };

            return(View(cBVM));
        }
        public async Task <IActionResult> TimeslotAjaxGet(int id)
        {
            try
            {
                var obj = await timeslotCrud.GetFromId(id);

                var dto = new CreateBookingViewModel {
                    SelectedCalender = obj.Calendar, ThePerson = obj.Teacher, TheTimeslot = obj
                };
                dto.TheTimeslot.Booking  = null;
                dto.TheTimeslot.Calendar = null;
                dto.TheTimeslot.Teacher  = null;
                return(StatusCode(200, dto));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
        public string AddBooking(CreateBookingViewModel bookingVM)
        {
            //try {
            if (ModelState.IsValid)
            {
                var config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap <CreateBookingViewModel, Booking>();
                });

                IMapper mapper  = config.CreateMapper();
                Booking booking = mapper.Map <CreateBookingViewModel, Booking>(bookingVM);

                //booking.ServiceID = ViewBag.ServiceID;
                db.Bookings.Add(booking);
                db.SaveChanges();


                MailMessage mail   = new MailMessage("", booking.Email);
                SmtpClient  client = new SmtpClient();
                client.EnableSsl             = true;
                client.Port                  = 25;
                client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials           = new NetworkCredential("", "");
                client.Host                  = "smtp.gmail.com";
                mail.Subject                 = "Service booking";
                mail.Body = "Your booking has been saved. Time" + booking.BookingTime;
                client.Send(mail);


                return("Success");
            }
            else
            {
                return("Invalid data");
            }


            //}
            //catch(Exception e) { return e.Message; }
        }
        public ActionResult Create(Guid?cloneBookingId = null)
        {
            CreateBookingViewModel vm;

            if (cloneBookingId.HasValue)
            {
                var originalBooking = _context.Bookings
                                      .FirstOrDefault(b => b.Id == cloneBookingId);
                if (originalBooking == null)
                {
                    return(NotFound());
                }

                vm = new CreateBookingViewModel
                {
                    Date                     = originalBooking.BookingDate,
                    Email                    = originalBooking.PassengerEmail,
                    PhoneNumber              = originalBooking.PassengerPhone.AsPhoneNumber(),
                    Name                     = originalBooking.PassengerName + " +1",
                    Weight                   = originalBooking.PassengerWeight,
                    Comment                  = originalBooking.Comment,
                    PrimaryBookingId         = originalBooking.Id,
                    NotifyPassenger          = false,
                    NotifyPilot              = true,
                    NofityBookingCoordinator = true,
                    PassengerFee             = (int)originalBooking.PassengerFee,
                };
            }
            else
            {
                vm = new CreateBookingViewModel
                {
                    Date                     = DateTime.Today,
                    PilotId                  = User.IsAdmin() ? "-1" : _userManager.GetUserId(User),
                    NotifyPassenger          = false,
                    NotifyPilot              = false,
                    NofityBookingCoordinator = false,
                };
            }

            return(View(vm));
        }
        public async Task <IActionResult> CreateAsync(int carid)
        {
            // Viewmodel =>calander avec les dates et heurres -> les dates et heures deja present dans banque de données pour voiture x => viewmodel calender et dropdown heures soit grisés.
            {
                var car         = _carRepository.GetCar(carid);
                var currentuser = await _userManager.GetUserAsync(HttpContext.User);

                {
                    CreateBookingViewModel createBookingViewModel = new CreateBookingViewModel()
                    {
                        BrandName        = car.CarModel.Brand.BrandName,
                        ModelName        = car.CarModel.ModelName,
                        Prijs            = car.Prijs,
                        MinLeeftijd      = car.CarModel.MinLeeftijd,
                        Kw               = car.CarModel.Kw,
                        ExistingPhotoCar = car.PhotoCar
                    };
                    return(View(createBookingViewModel));
                }
            }
        }
        // från vyn till metoden i controllen
        public IActionResult Create(Booking booking)
        {
            if (!ValidateBooking(booking))
            {
                var createBookingViewModel = new CreateBookingViewModel()
                {
                    Tracks = DbContext.Tracks, Booking = booking
                };
                return(View(createBookingViewModel));
            }

            // vi hämtar ut det valda rummets namn
            var trackName = DbContext.Tracks.FirstOrDefault(r => r.Id == booking.TrackId).Name;

            booking.Id        = Guid.NewGuid();
            booking.TrackName = trackName;


            DbContext.Bookings.Add(booking);

            return(RedirectToAction("Index"));
        }
        public async Task <IActionResult> CreateAsync(CreateBookingViewModel formulaire) //  Method(class nom de l'object)
        {
            // Post de booking -> model qui contient les valuers du formuliare
            //

            {
                if (ModelState.IsValid)                                                  // si model est valide alors
                {
                    var LoggedIn    = User.IsInRole("Admin, User");                      // false / true
                    var currentuser = await _userManager.GetUserAsync(HttpContext.User); // class ApplicationUser -> USER QUI EST logged in.

                    //if (LoggedIn) // if statement sont des check sur valuers (pas sur properties
                    // -> Gargae 1 et garage 3 => admin de garage 1 , rajouter une voiture dans garage 1 , que il est bien admin de garage 1.
                    // -> naviger vers http/local/garage2


                    BookingVehicule nouveaubookingquidoitallerdansbanquededonnees = new BookingVehicule
                    {
                        ApplicationUserId = currentuser.Id, // Class -> template (only properties) Class avec values -> object de la classe -> currentuser est un object de la classe applicationuser.
                        CarId             = formulaire.CarId,
                        StartDate         = formulaire.StartDate,
                        EndDate           = formulaire.EndDate,
                        CreateBy          = currentuser.Email,
                    };



                    var response = _bookingRepository.Create(nouveaubookingquidoitallerdansbanquededonnees);

                    if (response != null && response.BookingId != 0)
                    {
                        return(RedirectToAction("details", "Booking", new { id = nouveaubookingquidoitallerdansbanquededonnees.BookingId }));
                    }

                    return(View("NotAuthorized"));
                }
                return(View(formulaire));
            }
        }
Exemple #26
0
        public async Task <IActionResult> Create(CreateBookingViewModel booking)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var details = mapper.MapFrom(booking);
                    await bookingService.BookAsync(booking.FacilityId, booking.AccommodationId, details);

                    return(RedirectToAction("Index"));
                }

                var accommodation = await accommodationService.FindAsync(booking.AccommodationId);

                ViewBag.AccommodationId   = accommodation.Id;
                ViewBag.AccommodationName = accommodation.Details.Name;
                return(View(booking));
            }
            catch (AccommodationNotFoundException)
            {
                return(View("NotFound"));
            }
        }
        public ActionResult Create(CreateBookingViewModel createBookingViewModel)
        {
            HomeDepotContext _context = new HomeDepotContext();
            Customer         customer = Session["user"] as Customer;

            if (customer != null)
            {
                Tool    tool    = _context.Tools.Find(createBookingViewModel.SelectedValue);
                Booking booking = new Booking();
                booking.Status     = "Booked";
                booking.PickUpDate = createBookingViewModel.PickUpDate;
                booking.Days       = createBookingViewModel.Days;
                booking.ToolID     = tool.Id;
                booking.CustomerID = customer.Id;
                _context.Bookings.Add(booking);
                _context.SaveChanges();
                return(Redirect("/booking/viewbooking"));
            }
            else
            {
                return(Redirect("/login/login"));
            }
        }
        public async Task <IActionResult> Edit(int id, [Bind("ID,SurgeryStartingTime,SurgeryEndingTime,SurgeryRoomId,PatientFullName,PatientDateOfBirth,PatientGender,PatientMRNnumber,SurgeryName,SurgerySite,SurgicalDepartmentId,SurgeonID,BloodRequested,RequestedPostOperativeCare,SurgeryPosition,FrozenSection,SpecialThingsLikeSutures,SpecialThingsLikeSuturesText,Consumables,AnesthesiaTechniqueId,SpecialDevices,Turniquet,CArm,Harmonic,Ligasure,Microscope,Others,AppointmentStatus,PatientStatus,BookedItemsList,BloodRequestedText,ConsumablesText,SpecialDevicesText,SurgeryPositionText,AnestheticsId")] CreateBookingViewModel booking)
        {
            if (id != booking.ID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var itemsBooked = booking.BookedItemsList?.Split(',').Where(x => int.TryParse(x, out _))
                                      .Select(int.Parse)
                                      .ToList();


                    booking.ItemsBooked = _context.ItemsBooked.Where(x => x.BookingId == booking.ID).Include(x => x.Item).ToList();

                    //delete extra items in itemsbooked
                    List <ItemsBooked> collection = new List <ItemsBooked>();
                    if (booking.ItemsBooked.Any())
                    {
                        if (itemsBooked != null)
                        {
                            collection = booking.ItemsBooked
                                         .Where(x => itemsBooked.All(c => c != x.ItemId)).ToList();
                        }
                        else
                        {
                            collection = booking.ItemsBooked;
                        }
                        if (collection.Any())
                        {
                            _context.ItemsBooked.RemoveRange(collection);
                        }
                    }

                    //add new items
                    if (itemsBooked != null)
                    {
                        foreach (var i in itemsBooked)
                        {
                            var booked = new ItemsBooked()
                            {
                                Booking  = booking,
                                Item     = _context.Item.FirstOrDefault(x => x.Id == i),
                                Quantity = 1
                            };
                            if (booking.ItemsBooked.All(x => x.ItemId != booked.Item.Id))
                            {
                                booking.ItemsBooked.Add(booked);
                            }
                        }
                    }

                    var bookingId       = booking.ID;
                    var overlapBookings = _bookingRepository.GetAllBookings().Where(x =>
                                                                                    x.SurgeryStartingTime <booking.SurgeryEndingTime &&
                                                                                                           x.SurgeryEndingTime> booking.SurgeryStartingTime && x.ID != bookingId).ToList();

                    if (User.IsInRole("StatusUpdate") && booking.AnestheticsId == null)
                    {
                        ModelState.AddModelError("AnestheticsId", $"Anesthetics is required.");
                    }

                    var overLapRoom = overlapBookings.FirstOrDefault(x => x.SurgeryRoomId == booking.SurgeryRoomId);
                    if (overLapRoom != null)
                    {
                        ModelState.AddModelError("SurgeryRoomId", $"Room {overLapRoom.SurgeryRoom.SurgeryRoomDescription} booked in this hour since someone booked it just now. Please select other time or room.");
                    }

                    var totalItems = _context.Item.AsNoTracking().ToList();

                    foreach (var i in totalItems.Where(i => overlapBookings.Any(x => x.ItemsBooked.Any(c => c.Item.Id == i.Id))))
                    {
                        i.Quantity--;
                    }

                    foreach (var i in totalItems.Where(x => booking.ItemsBooked.Any(c => c.Item.Id == x.Id && x.Quantity < 1)))
                    {
                        ModelState.AddModelError("", $"'{i.Description}' is not available in this time since someone booked it just now. Please select other time.");
                    }

                    if (ModelState.ErrorCount == 0)
                    {
                        _bookingRepository.Update(booking);
                    }
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!BookingExists(booking.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                if (ModelState.ErrorCount == 0)
                {
                    return(RedirectToAction(nameof(Index)));
                }
            }
            ViewData["Rooms"] = JsonConvert.SerializeObject(_context.SurgeryRoom.OrderBy(x => x.SurgeryRoomDescription).Select(x => new
            {
                id          = x.Id,
                description = x.SurgeryRoomDescription.Trim()
            }));
            var items     = _context.Item.ToArray();
            var listItems = items.Select(i => new { id = i.Id, description = i.Description }).Distinct().OrderBy(x => x.description);

            ViewData["Item"] = JsonConvert.SerializeObject(listItems);

            ViewData["AnesthesiaTechniqueId"] = new SelectList(_context.AnesthesiaTechnique, "Id", "Text", booking.AnesthesiaTechniqueId);
            ViewData["SurgeryRoomId"]         = new SelectList(_context.SurgeryRoom, "Id", "SurgeryRoomDescription", booking.SurgeryRoomId);
            ViewData["SurgicalDepartmentId"]  = new SelectList(_context.Set <SurgicalDepartment>(), "Id", "SurgicalDepartmentDescription", booking.SurgicalDepartmentId);
            ViewData["Anesthetics"]           = new SelectList(_context.Anesthetics, "Id", "Name", booking.AnestheticsId);
            var allBookings = _bookingRepository.GetAllBookings();

            ViewData["Appointments"] = JsonConvert.SerializeObject(allBookings.Where(x => x.ID != id).Select(x => new
            {
                startTime   = x.SurgeryStartingTime,
                endTime     = x.SurgeryEndingTime,
                roomId      = x.SurgeryRoomId,
                itemsBooked = x.ItemsBooked?.Where(p => p.Quantity > 0)
                              .SelectMany(p => Enumerable.Range(0, p.Quantity)
                                          .Select(i => new
                {
                    itemId   = p.ItemId,
                    quantity = p.Quantity
                }))
            }));


            ViewData["bookedItems"] = JsonConvert.SerializeObject(booking.ItemsBooked.Select(x => x.Item.Id).ToArray());
            var userModel = new List <UserRoleViewModel>();

            foreach (var user in _userManager.Users)
            {
                if (await _userManager.IsInRoleAsync(user, "Surgeon"))
                {
                    var userRoleViewModel = new UserRoleViewModel
                    {
                        UserID   = user.Id,
                        UserName = user.UserName,
                    };
                    userModel.Add(userRoleViewModel);
                }
            }

            ViewData["SurgeonId"] = new SelectList(userModel, "UserID", "UserName", booking.SurgeonID);

            var originalBooking = _bookingRepository.GetBooking((int)id);

            booking.CreatedBy  = originalBooking.CreatedBy;
            booking.ModifiedBy = originalBooking.ModifiedBy;


            return(View(booking));
        }
        // GET: Booking/Edit/5
        public async Task <IActionResult> Edit(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var booking = _bookingRepository.GetBooking((int)id);

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

            //check if user is allowed to edit
            if (!(User.IsInRole("Administrator") || User.IsInRole("StatusUpdate") || (booking.CreatedBy == User.FindFirst(ClaimTypes.NameIdentifier).Value&& booking.AppointmentStatus == AppointmentStatus.Pending)))
            {
                return(View("Index"));
            }

            booking.ItemsBooked = _context.ItemsBooked.Where(x => x.BookingId == booking.ID).Include(x => x.Item).AsNoTracking().ToList();

            ViewData["AnesthesiaTechniqueId"] = new SelectList(_context.AnesthesiaTechnique, "Id", "Text", booking.AnesthesiaTechniqueId);
            ViewData["Rooms"] = JsonConvert.SerializeObject(_context.SurgeryRoom.OrderBy(x => x.SurgeryRoomDescription).Select(x => new
            {
                id          = x.Id,
                description = x.SurgeryRoomDescription.Trim()
            }));
            var allBookings = _bookingRepository.GetAllBookings();

            ViewData["Appointments"] = JsonConvert.SerializeObject(allBookings.Where(x => x.ID != id).Select(x => new
            {
                startTime   = x.SurgeryStartingTime,
                endTime     = x.SurgeryEndingTime,
                roomId      = x.SurgeryRoomId,
                itemsBooked = x.ItemsBooked?.Where(p => p.Quantity > 0)
                              .SelectMany(p => Enumerable.Range(0, p.Quantity)
                                          .Select(i => new
                {
                    itemId   = p.ItemId,
                    quantity = p.Quantity
                }))
            }));


            ViewData["SurgicalDepartmentId"] = new SelectList(_context.SurgicalDepartment, "Id", "SurgicalDepartmentDescription", booking.SurgicalDepartmentId);

            var items     = _context.Item.AsNoTracking().ToArray();
            var listItems = items.Select(i => new { id = i.Id, description = i.Description }).Distinct().OrderBy(x => x.description);

            ViewData["Item"] = JsonConvert.SerializeObject(listItems);

            var userModel = new List <UserRoleViewModel>();

            foreach (var user in _userManager.Users)
            {
                if (await _userManager.IsInRoleAsync(user, "Surgeon"))
                {
                    var userRoleViewModel = new UserRoleViewModel
                    {
                        UserID   = user.Id,
                        UserName = user.DisplayName,
                    };
                    userModel.Add(userRoleViewModel);
                }
            }



            ViewData["bookedItems"] = JsonConvert.SerializeObject(booking.ItemsBooked?.Select(x => x.Item.Id).ToArray());


            ViewData["CurrentUserName"] = (await _userManager.FindByIdAsync(_userManager.GetUserId(User)).ConfigureAwait(false)).DisplayName;
            ViewData["SurgeonId"]       = new SelectList(userModel, "UserID", "UserName", booking.SurgeonID);
            ViewData["Anesthetics"]     = new SelectList(_context.Anesthetics, "Id", "Name", booking.AnestheticsId);

            if (booking.SMS != null)
            {
                ViewData["SMS"] = JsonConvert.SerializeObject(booking.SMS.Select(x => new
                {
                    phoneNumber = x.PhoneNumber,
                    message     = x.Message,
                    sentBy      = _userManager.FindByIdAsync(x.CreatedBy).Result.DisplayName,
                    sentOn      = ((DateTime)x.CreatedDate).ToString("dd/MM/yyyy")
                }));
            }

            var bookingModel = new CreateBookingViewModel()
            {
                ID = booking.ID,
                SurgeryStartingTime          = booking.SurgeryStartingTime,
                SurgeryEndingTime            = booking.SurgeryEndingTime,
                SurgeryRoomId                = booking.SurgeryRoomId,
                PatientFullName              = booking.PatientFullName,
                PatientDateOfBirth           = booking.PatientDateOfBirth,
                PatientGender                = booking.PatientGender,
                PatientMRNnumber             = booking.PatientMRNnumber,
                SurgeryName                  = booking.SurgeryName,
                SurgerySite                  = booking.SurgerySite,
                SurgicalDepartmentId         = booking.SurgicalDepartmentId,
                SurgeonID                    = booking.SurgeonID,
                BloodRequested               = booking.BloodRequested,
                BloodRequestedText           = booking.BloodRequestedText,
                RequestedPostOperativeCare   = booking.RequestedPostOperativeCare,
                SurgeryPosition              = booking.SurgeryPosition,
                SurgeryPositionText          = booking.SurgeryPositionText,
                FrozenSection                = booking.FrozenSection,
                SpecialThingsLikeSutures     = booking.SpecialThingsLikeSutures,
                SpecialThingsLikeSuturesText = booking.SpecialThingsLikeSuturesText,
                Consumables                  = booking.Consumables,
                ConsumablesText              = booking.ConsumablesText,
                AnesthesiaTechniqueId        = booking.AnesthesiaTechniqueId,
                SpecialDevices               = booking.SpecialDevices,
                SpecialDevicesText           = booking.SpecialDevicesText,
                Turniquet                    = booking.Turniquet,
                CArm              = booking.CArm,
                Harmonic          = booking.Harmonic,
                Ligasure          = booking.Ligasure,
                Microscope        = booking.Microscope,
                Others            = booking.Others,
                ItemsBooked       = booking.ItemsBooked,
                AppointmentStatus = booking.AppointmentStatus,
                PatientStatus     = booking.PatientStatus,
                CreatedDate       = booking.CreatedDate,
                ModifiedDate      = booking.ModifiedDate,
                CreatedBy         = booking.CreatedBy,
                ModifiedBy        = booking.ModifiedBy,
            };

            return(View(bookingModel));
        }
        public async Task <IActionResult> Create([Bind("ID,SurgeryStartingTime,SurgeryEndingTime,SurgeryRoomId,PatientFullName,PatientDateOfBirth,PatientGender,PatientMRNnumber,SurgeryName,SurgerySite,SurgicalDepartmentId,SurgeonID,BloodRequested,RequestedPostOperativeCare,SurgeryPosition,FrozenSection,SpecialThingsLikeSutures,SpecialThingsLikeSuturesText,Consumables,AnesthesiaTechniqueId,SpecialDevices,Turniquet,CArm,Harmonic,Ligasure,Microscope,Others,BookedItemsList,AppointmentStatus,BloodRequestedText,ConsumablesText,SpecialDevicesText,SurgeryPositionText")] CreateBookingViewModel booking)
        {
            if (ModelState.IsValid)
            {
                var itemsBooked = booking.BookedItemsList?.Split(',');
                booking.ItemsBooked = new List <ItemsBooked>();

                if (itemsBooked != null)
                {
                    foreach (var i in itemsBooked)
                    {
                        var booked = new ItemsBooked()
                        {
                            Booking  = booking,
                            Item     = _context.Item.FirstOrDefault(x => x.Id == int.Parse(i)),
                            Quantity = 1
                        };
                        booking.ItemsBooked.Add(booked);
                    }
                }

                var overlapBookings = _bookingRepository.GetAllBookings().Where(x =>
                                                                                x.SurgeryStartingTime <booking.SurgeryEndingTime &&
                                                                                                       x.SurgeryEndingTime> booking.SurgeryStartingTime).ToList();

                var overLapRoom = overlapBookings.FirstOrDefault(x => x.SurgeryRoomId == booking.SurgeryRoomId);
                if (overLapRoom != null)
                {
                    ModelState.AddModelError("SurgeryRoomId", $"Room {overLapRoom.SurgeryRoom.SurgeryRoomDescription} booked in this hour since someone booked it just now. Please select other time or room.");
                }

                var totalItems = _context.Item.AsNoTracking().ToList();

                foreach (var i in totalItems.Where(i => overlapBookings.Any(x => x.ItemsBooked.Any(c => c.Item.Id == i.Id))))
                {
                    i.Quantity--;
                }

                foreach (var i in totalItems.Where(x => booking.ItemsBooked.Any(c => c.Item.Id == x.Id && x.Quantity < 1)))
                {
                    ModelState.AddModelError("", $"'{i.Description}' is not available in this time since someone booked it just now. Please select other time.");
                }

                if (ModelState.ErrorCount == 0)
                {
                    _bookingRepository.Add(booking);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }

            ViewData["AnesthesiaTechniqueId"] = new SelectList(_context.AnesthesiaTechnique, "Id", "Text", booking.AnesthesiaTechniqueId);
            ViewData["Rooms"] = JsonConvert.SerializeObject(_context.SurgeryRoom.OrderBy(x => x.SurgeryRoomDescription).Select(x => new
            {
                id          = x.Id,
                description = x.SurgeryRoomDescription.Trim()
            }));
            ViewData["Appointments"] = JsonConvert.SerializeObject(_bookingRepository.GetAllBookings().Select(x => new
            {
                startTime   = x.SurgeryStartingTime,
                endTime     = x.SurgeryEndingTime,
                roomId      = x.SurgeryRoomId,
                itemsBooked = x.ItemsBooked?.Where(p => p.Quantity > 0)
                              .SelectMany(p => Enumerable.Range(0, p.Quantity)
                                          .Select(i => new
                {
                    itemId   = p.ItemId,
                    quantity = p.Quantity
                }))
            }));


            ViewData["SurgicalDepartmentId"] = new SelectList(_context.SurgicalDepartment, "Id", "SurgicalDepartmentDescription", booking.SurgicalDepartmentId);

            var items     = _context.Item.AsNoTracking().ToArray();
            var listItems = items.Select(i => new { id = i.Id, description = i.Description }).Distinct().OrderBy(x => x.description);

            ViewData["Item"] = JsonConvert.SerializeObject(listItems);

            var userModel = new List <UserRoleViewModel>();

            foreach (var user in _userManager.Users)
            {
                if (await _userManager.IsInRoleAsync(user, "Surgeon"))
                {
                    var userRoleViewModel = new UserRoleViewModel
                    {
                        UserID   = user.Id,
                        UserName = user.DisplayName,
                    };
                    userModel.Add(userRoleViewModel);
                }
            }

            ViewData["CurrentUserName"] = (await _userManager.FindByIdAsync(_userManager.GetUserId(User)).ConfigureAwait(false)).DisplayName;
            ViewData["SurgeonId"]       = new SelectList(userModel, "UserID", "UserName", booking.SurgeonID);


            return(View(booking));
        }