Ejemplo n.º 1
0
        public ActionResult CreatingRoom(Room room)
        {
            IRepository repository = new CommunicationWithDataBase();

            logger.Debug($"Обращение к базе данных, получение комнат");
            Room existedRoom = repository.GetRoomByNumber(room.Numder);

            if (existedRoom != null)
            {
                ModelState.AddModelError(nameof(room.Numder), "Комната с таким номером уже существует");
            }

            if (ModelState.IsValid)
            {
                logger.Debug($"Обращение к базе данных, для добавления новой комнаты");
                logger.Info($"В базу данных добавлена новая комната");
                repository.CreateRoom(room.Numder, room.ClassRoomId, room.CountOfPlaces);
                return(RedirectToAction("AdminMainPage"));
            }

            IEnumerable <SelectListItem> roomCountOfPlacesItems = FormingSelectItems.GetRoomCountOfPlacesItems();
            IEnumerable <SelectListItem> classRoomItems         = FormingSelectItems.GetClassRoomItems();

            ViewData["RoomCountOfPlacesItems"] = roomCountOfPlacesItems;
            ViewData["ClassRoomItems"]         = classRoomItems;

            logger.Info($"Отказ в добавлении новой комнаты");
            return(View());
        }
Ejemplo n.º 2
0
        public ActionResult BookingRoomByUser(int roomNumber)
        {
            IRepository repository = new CommunicationWithDataBase();

            DateTime startDate = new DateTime();
            DateTime endDate   = new DateTime();

            HttpCookie cookie = HttpContext.Request.Cookies["accommodation date"];

            if (cookie == null)
            {
                logger.Error($"Ошибка. Значение куки было null");
            }

            try
            {
                startDate = Convert.ToDateTime(cookie.Values["start"]);
                endDate   = Convert.ToDateTime(cookie.Values["end"]);
            }
            catch
            {
                logger.Error($"Ошибка. Невозможно конвертировать дату");
                ModelState.AddModelError("DateValidationError", "Даты указаны некорректно");
            }

            string userLogin = User.Identity.Name;

            logger.Info($"Обращение к базе данных для создания нового бронирования");
            repository.CreateBooking(userLogin, roomNumber, startDate, endDate);
            logger.Info($"Бронирование комнаты {roomNumber} пользователем {userLogin}");
            return(JavaScript($"window.location = 'https://localhost:44399/Home/UserBookings'"));
        }
Ejemplo n.º 3
0
        public ActionResult DeleteBooking(int id)
        {
            IRepository repository = new CommunicationWithDataBase();

            logger.Debug($"Обращение к базе данных, для изменения статуса бронирования");
            repository.DeleteBooking(id);
            logger.Info($"Бронирование снято");
            return(JavaScript($"window.location = 'https://localhost:44399/Home/ActuallyBookings'"));
        }
Ejemplo n.º 4
0
        public ActionResult ConfirmPayment(int id)
        {
            IRepository repository = new CommunicationWithDataBase();

            logger.Debug($"Обращение к базе данных, для изменения статуса бронирования");
            repository.ConfirmPayment(id);
            logger.Debug($"Оплата подтверждена");
            return(JavaScript($"window.location = 'https://localhost:44399/Home/ActuallyBookings'"));
        }
Ejemplo n.º 5
0
        public ActionResult UpdateRoomStatus()
        {
            IRepository repository = new CommunicationWithDataBase();

            logger.Debug($"Обращение к базе данных, получение комнат");
            List <Room> rooms = repository.GetAllRooms();

            return(View(rooms));
        }
Ejemplo n.º 6
0
        public ActionResult ProcessingOfRoomStatusUpdating(Room room)
        {
            IRepository repository = new CommunicationWithDataBase();

            logger.Debug($"Обращение к базе данных, для обновления статуса комнаты");
            logger.Info($"Стату комнаты {room.Numder} обновлен");
            repository.UpdateRoomAvailability(room.Numder, room.Availability);
            return(RedirectToAction("UpdateRoomStatus"));
        }
Ejemplo n.º 7
0
        public ActionResult ProcessingRequest(Booking booking)
        {
            IRepository repository = new CommunicationWithDataBase();

            logger.Debug($"Обращение к базе данных, обновление бронирования комнаты");
            repository.UpdateRoomInBooking(booking.Id, Convert.ToInt32(booking.RoomNumber));
            logger.Info($"Обновление бронирование с {booking.Id} выполнено успешно");
            return(RedirectToAction("NotProcessedRequests"));
        }
Ejemplo n.º 8
0
        public ActionResult RoomReservation()
        {
            IRepository repository = new CommunicationWithDataBase();

            logger.Debug($"Обращение к базе данных, получение комнат");
            List <Room> rooms = repository.GetAllRooms();

            ViewData["RoomClassItems"]     = FormingSelectItems.GetRoomClassRoomItems(rooms);
            ViewData["CountOfPlacesItems"] = FormingSelectItems.GetCurrentRoomCountOfPlacesItems(rooms);

            return(View(rooms));
        }
Ejemplo n.º 9
0
        public ActionResult ActuallyBookings()
        {
            IRepository repository = new CommunicationWithDataBase();

            logger.Debug($"Обращение к базе данных, обновление статуса бронирований");
            repository.UpdateAllOverdueBookings();

            logger.Debug($"Обращение к базе данных, получение обработанных запросов");
            List <Booking> currentBookings = repository.GetBookings()
                                             .Where(b => b.BookingStatusId != 1 && b.DateEnd.AddDays(7) > DateTime.Now).ToList();

            return(View(currentBookings));
        }
Ejemplo n.º 10
0
        public static IEnumerable <SelectListItem> GetClassRoomItems()
        {
            IRepository repository = new CommunicationWithDataBase();

            List <ClassRoom> classRooms = repository.GetRoomClasses();

            IEnumerable <SelectListItem> roomClassItems = classRooms.Select(
                rc => new SelectListItem()
            {
                Text  = rc.Name,
                Value = rc.Id.ToString()
            }
                );

            return(roomClassItems);
        }
Ejemplo n.º 11
0
        public ActionResult RoomReservation(FormCollection form)
        {
            IRepository repository = new CommunicationWithDataBase();

            int      roomClassId   = Convert.ToInt32(form["RoomClass"]);
            int      countOfPlaces = Convert.ToInt32(form["CountOfPlaces"]);
            DateTime startDate     = new DateTime();
            DateTime endDate       = new DateTime();

            try
            {
                startDate = Convert.ToDateTime(form["StartDate"]);
                endDate   = Convert.ToDateTime(form["EndDate"]);
            }
            catch
            {
                ModelState.AddModelError("DateValidationError", "Даты указаны некорректно");
                logger.Error($"Ошибка. Невозможно конвертировать дату");
            }

            if (startDate < DateTime.Now || startDate >= endDate)
            {
                ModelState.AddModelError("DateValidationError", "Даты указаны некорректно");
            }

            if (startDate.AddDays(14) < endDate)
            {
                ModelState.AddModelError("DateValidationError", "Проживание в отеле допустимо не более 2х недель");
            }

            if (ModelState.IsValid)
            {
                logger.Debug($"Обращение к базе данных, создание запроса на поселение");
                string userLogin = User.Identity.Name;
                repository.CreateRequest(userLogin, roomClassId, countOfPlaces, startDate, endDate);
                logger.Info($"Пользователем создан новый запрос на поселение");
                return(RedirectToAction("Index"));
            }

            logger.Debug($"Обращение к базе данных, получение комнат");
            List <Room> rooms = repository.GetAllRooms();

            ViewData["RoomClassItems"]     = FormingSelectItems.GetRoomClassRoomItems(rooms);
            ViewData["CountOfPlacesItems"] = FormingSelectItems.GetCurrentRoomCountOfPlacesItems(rooms);

            return(View());
        }
Ejemplo n.º 12
0
        public ActionResult NotProcessedRequests()
        {
            IRepository repository = new CommunicationWithDataBase();

            logger.Debug($"Обращение к базе данных, получение комнат");
            List <Room> rooms = repository.GetAllRooms();

            IEnumerable <SelectListItem> roomNumberItems = FormingSelectItems.GetRoomNumberItems(rooms);

            ViewData["RoomNumberItems"] = roomNumberItems;

            logger.Debug($"Обращение к базе данных, получение запросов на проживание");
            List <Booking> bookings             = repository.GetBookingRequests();
            var            notProcessedBookings = bookings.Where(b => b.BookingStatusId == 1);

            return(View(notProcessedBookings));
        }
Ejemplo n.º 13
0
        public ActionResult ReportUser(int id)
        {
            IRepository repository = new CommunicationWithDataBase();

            User user = repository.GetUserById(id);

            if (user == null)
            {
                logger.Error($"Пользователя с id {id} не сущестувует");
            }

            logger.Debug($"Обращение к базе данных, жалоба на пользователя");
            repository.ReportUser(id);
            logger.Debug($"Жалоба на пользователя была оставлена");

            return(View());
        }
Ejemplo n.º 14
0
        public ActionResult UserBookings()
        {
            IRepository repository = new CommunicationWithDataBase();

            logger.Debug($"Обращение к базе данных, получение пользователя по логину");
            User user = repository.GetUserByLogin(User.Identity.Name);

            if (user == null)
            {
                logger.Debug($"Ошибка. не возможно получить пользователя");
            }
            logger.Debug($"Обращение к базе данных, получение комнат забронированых пользователем {user.Login}");
            List <Booking> bookings        = repository.GetUserBookings(user.Id);
            List <Booking> currentBookings = bookings.Where(b => b.BookingStatusId == 2).ToList();

            logger.Info($"Возвращение забронированных пользователем комнат");
            return(View(currentBookings));
        }
Ejemplo n.º 15
0
        public ActionResult PartialRooms(FormCollection form)
        {
            IRepository repository = new CommunicationWithDataBase();

            logger.Debug($"Обращение к базе данных, получение комнат");
            List <Room> rooms          = repository.GetAllRooms();
            List <Room> currentRooms   = new List <Room>();
            int         roomTypeNumber = 0;

            logger.Debug($"Выборка нужных комнат из всех доступных");
            switch (form["RoomItems"])
            {
            case "1":
                roomTypeNumber = 1;
                currentRooms   = rooms.Where(r =>
                                             r.Bookings.Where(b => b.DateStart <= DateTime.Now && b.DateEnd > DateTime.Now)
                                             .Select(rn => rn.RoomNumber).ToList().Contains(r.Numder) == false && r.Availability)
                                 .ToList();
                break;

            case "2":
                roomTypeNumber = 2;
                currentRooms   = rooms.Where(r =>
                                             r.Bookings.Where(b => b.DateStart <= DateTime.Now && b.DateEnd > DateTime.Now)
                                             .Select(rn => rn.RoomNumber).ToList().Contains(r.Numder) && r.Availability).ToList();
                break;

            case "3":
                roomTypeNumber = 3;
                currentRooms   = rooms.Where(r =>
                                             r.Bookings.Where(b => b.DateStart > DateTime.Now)
                                             .Select(rn => rn.RoomNumber).ToList().Contains(r.Numder) && r.Availability).ToList();
                break;

            case "4":
                roomTypeNumber = 4;
                currentRooms   = rooms.Where(r => r.Availability == false).ToList();
                break;
            }

            ViewData["RoomTypeNumber"] = roomTypeNumber;
            return(View(currentRooms));
        }
Ejemplo n.º 16
0
        public ActionResult Authorization(UserAuthorization model)
        {
            IRepository repository = new CommunicationWithDataBase();

            logger.Debug("Обращение к базе данных для получения данных о пользователе");
            User user = repository.GetUserByLogin(model.Login?.ToLower());

            if (user?.BlockDate > DateTime.Now)
            {
                logger.Debug($"Ошибка входа, пользователь {user.Login} заблокирован в системе");
                ModelState.AddModelError("AuthorizationValidationError",
                                         $"Вы заблокированы в системе до {user.BlockDate.ToString("d")}.");
            }
            else if (model.Password == null)
            {
                ModelState.AddModelError("AuthorizationValidationError", "Логин или пароль некорректен");
            }
            else if (repository.CheckUserAuthorization(model.Login?.ToLower(), model?.Password))
            {
                logger.Debug($"Обращение к базе данных для проверки подлиности данных авторизации");
                if (model.Login == null)
                {
                    logger.Error("Ошибка. Логин пользователя был null");
                }

                FormsAuthentication.SetAuthCookie(model.Login.ToLower(), true);
                logger.Info($"Пользователь {user.Login} выполнил вход на сайт");
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                ModelState.AddModelError("AuthorizationValidationError", "Логин или пароль некорректен");
            }

            logger.Info($"Отказ входа. некорректные данные");
            return(View(model));
        }
Ejemplo n.º 17
0
        public ActionResult AllRooms()
        {
            IRepository repository = new CommunicationWithDataBase();

            List <SelectListItem> roomItems = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text  = "Свободны",
                    Value = "1"
                },
                new SelectListItem()
                {
                    Text  = "Заняты",
                    Value = "2"
                },
                new SelectListItem()
                {
                    Text  = "Забронированы",
                    Value = "3"
                },
                new SelectListItem()
                {
                    Text  = "Недоступны",
                    Value = "4"
                },
            };

            ViewData["RoomItems"] = roomItems;

            logger.Debug($"Обращение к базе данных, получение комнат");
            List <Room> rooms = repository.GetAllRooms();

            ViewData["RoomClassItems"] = FormingSelectItems.GetRoomClassRoomItems(rooms);

            return(View(rooms));
        }
Ejemplo n.º 18
0
        public ActionResult Registration(UserRegistration user)
        {
            IRepository repository = new CommunicationWithDataBase();

            logger.Debug("Попытка создания нового пользователя");

            if (user.Password != null)
            {
                if (user.Password.Length < 6 || user.Password.Length > 15)
                {
                    ModelState.AddModelError(nameof(user.Password), "Пароль должен содержать от 6 до 15 символов");
                }

                if (!Regex.IsMatch(user.Password, "^[a-zA-ZА-Яа-я0-9_\\.\\-]+$"))
                {
                    ModelState.AddModelError(nameof(user.Password), "Пароль содержит некорректные символы");
                }

                if (user.ConfirmPassword != user.Password)
                {
                    ModelState.AddModelError(nameof(user.ConfirmPassword), "Пароли не совпадают");
                }
            }

            if (!(user.DateOfBirth > DateTime.Now.AddYears(-110) &&
                  user.DateOfBirth < DateTime.Now.AddYears(-16)))
            {
                ModelState.AddModelError(nameof(user.DateOfBirth),
                                         "Некорректная дата рождения. Наши пользователи должны быть старше 16 и моложе 110 лет");
            }

            if (user.Login != null)
            {
                if (!Regex.IsMatch(user.Login, "^[A-Za-z]+"))
                {
                    ModelState.AddModelError(nameof(user.Login),
                                             "В логине должны присутствовать буквы английского алфавита");
                }

                logger.Debug($"Обращение к базе данных для проврки уникальности логина {user.Login}");
                if (repository.GetUserByLogin(user.Login.ToLower()) != null)
                {
                    ModelState.AddModelError(nameof(user.Login), "Пользователь с таким логином уже существует");
                }
            }

            if (user.Email != null)
            {
                logger.Debug($"Обращение к базе данных для проврки уникальности email {user.Email}");
                if (repository.GetUserByEmail(user.Email) != null)
                {
                    ModelState.AddModelError(nameof(user.Email), "Email используется в системе");
                }
            }

            if (ModelState.IsValid)
            {
                try
                {
                    repository.CreateUser(user.FirstName.ToLower(), user.SecondName.ToLower(),
                                          user.Login.ToLower(), user.Email, user.Password, user.DateOfBirth);
                }
                catch
                {
                    logger.Error("Ошибка. пользователь не был создан");
                }

                logger.Info("В систему добавлен новый пользователь");

                FormsAuthentication.SetAuthCookie(user.Login.ToLower(), true);

                return(RedirectToAction("Index", "Home"));
            }

            return(View(user));
        }
Ejemplo n.º 19
0
        public ActionResult FreeRoomsForBooking(Booking booking)
        {
            IRepository repository = new CommunicationWithDataBase();

            DateTime startDate = new DateTime();
            DateTime endDate   = new DateTime();

            try
            {
                startDate = Convert.ToDateTime(booking.DateStart);
                endDate   = Convert.ToDateTime(booking.DateEnd);
            }
            catch
            {
                logger.Error($"Ошибка. Невозможно конвертировать дату");
                ModelState.AddModelError("WrongDateMessage", "Даты указаны некорректно");
                return(View());
            }

            if (startDate > DateTime.Now.AddMonths(3))
            {
                ModelState.AddModelError("WrongDateMessage", "Комнаты нельзя бронировать позже чем за 3 месяца");
            }

            if (startDate < DateTime.Now || startDate >= endDate)
            {
                ModelState.AddModelError("WrongDateMessage", "Даты указаны некорректно");
            }

            if (startDate.AddDays(14) < endDate)
            {
                ModelState.AddModelError("WrongDateMessage", "Проживание в отеле допустимо не более 2х недель");
            }

            if (ModelState.IsValid)
            {
                logger.Debug($"Обращение к базе данных, получение комнат сводных с {startDate} по {endDate} число");
                List <Room> freeRooms           = repository.GetFreeRooms(startDate, endDate);
                HttpCookie  accommodationCookie = new HttpCookie("accommodation date");

                try
                {
                    accommodationCookie["start"] = startDate.ToString();
                    accommodationCookie["end"]   = endDate.ToString();
                }
                catch
                {
                    logger.Error("Ошибка. некорректная дата");
                }

                ViewData["StartDate"] = startDate;
                ViewData["EndDate"]   = endDate;

                HttpContext.Response.Cookies.Add(accommodationCookie);
                logger.Debug($"Установка куки даты проживания пользователя");

                return(View(freeRooms));
            }

            return(View());
        }