public IEnumerable <ReservationDTO> GetReservationsByApartment(Guid apartmentId) { IEnumerable <Reservation> MyReservations = IReservationRepository.GetReservationsByApartment(apartmentId); List <ReservationDTO> ReservationsDTO = new List <ReservationDTO>(); foreach (Reservation r in MyReservations) { ReservationDTO reservationDTO = new ReservationDTO() { id = r.id, checkIn = r.checkIn, checkOut = r.checkOut, price = r.price, review = r.review, userId = r.userId, apartmentId = r.apartmentId, numberOfPersons = r.numberOfPersons, paidWithCard = r.paidWithCard, rating = r.rating }; ReservationsDTO.Add(reservationDTO); } return(ReservationsDTO); }
public async Task <ReservationDTO> GetReservationById(Guid reservationId) { var reservation = await _context.Reservation.Where(x => x.ReservationId == reservationId) .Include(x => x.StandingReservation) .Include(x => x.User) .ThenInclude(y => y.Membership).FirstOrDefaultAsync(); if (reservation != null) { ReservationDTO reservationDTO = new ReservationDTO() { ReservationId = reservation.ReservationId, UserId = reservation.UserId, StartDate = ConvertToMountainTime(reservation.StartDate), EndDate = ConvertToMountainTime(reservation.EndDate), CreatedBy = reservation.CreatedBy, CreatedDateTime = ConvertToMountainTime(reservation.CreatedDateTime), LastModifiedBy = reservation.LastModifiedBy, LastModifiedDateTime = reservation.LastModifiedDateTime, Notes = reservation.Notes, NumberOfPlayers = reservation.NumberOfPlayers, StandingReservationId = reservation.StandingReservationId, ResevationNumber = reservation.ResevationNumber, ReservationType = reservation.StandingReservation == null ? "O" : "S", IsApproved = reservation.StandingReservation == null ? false : reservation.StandingReservation.IsApproved, User = reservation.User }; return(reservationDTO); } else { throw new Exception("Reservation not found"); } }
public ReservationDTO Add(ReservationDTO res) { RESERVATION resToAdd, addedRes; ReservationDTO retVal; retVal = null; if (CheckHelper.IsFilled(res)) { try { resToAdd = transformer.TransformFromDTO(-1, res); AddARandomSeat(resToAdd, res); addedRes = reservationRepository.Add(resToAdd); if (CheckHelper.IsFilled(addedRes)) { retVal = transformer.TransformToDTO(addedRes); } } catch (Exception) { } } return(retVal); }
public Reservation Put(int id, ReservationDTO value) { Reservation model = IReservationRepository.Get(id); if (value.review != null) { model.review = value.review; } if (value.price != 0) { model.price = value.price; } if (value.checkIn != null) { model.checkIn = value.checkIn; } if (value.checkOut != null) { model.checkOut = value.checkOut; } if (value.userId != 0) { model.userId = value.userId; } if (value.apartmentId != 0) { model.apartmentId = value.apartmentId; } if (value.numberOfPersons != 0) { model.apartmentId = value.apartmentId; } return(IReservationRepository.Update(model)); }
public async Task <ActionResult <Reservation> > Post(ReservationDTO reservationDTO) { try { Reservation reservation = new Reservation() { Id = reservationDTO.Id, Name = reservationDTO.Name, ReservationDateTime = DateTime.Parse(reservationDTO.ReservationDateTime).ToUniversalTime(), Duration = TimeSpan.Parse(reservationDTO.Duration) }; if (reservation == null) { logger.LogWarning("Request {Path} | New reservation is equal to null", this.HttpContext.Request.Path); return(StatusCode(500)); } else { logger.LogDebug("Request {Path} | Creating reservation for adding to storage is successfully", this.HttpContext.Request.Path); } return(bookingService.Add(reservation)); } catch (Exception ex) { logger.LogError(ex, "Request {Path} | Unexpected exception", this.HttpContext.Request.Path); return(StatusCode(500)); } }
public async Task <IActionResult> PostReservation([FromBody] ReservationDTO reservationDTO) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // checking if there is already a reservation at that time with the same mechanic Reservation takenReservations = _unitOfWork.Reservations.Find(res => DateTime.Compare(res.Time, reservationDTO.Time) == 0); if (takenReservations != null && reservationDTO.Mechanic.Id.Equals(takenReservations.MechanicId)) { return(BadRequest("This time is already booked at that mechanic!")); } Reservation reservation = _unitOfWork.Reservations.Add(reservationDTO); await _unitOfWork.Complete(); return(CreatedAtAction("GetReservation", new { id = reservation.Id }, reservation.Id)); } catch (Exception ex) { _logger.LogError("Unexpected error has occured during HTTP request: ", ex.Message); return(StatusCode(500, $"Unexpected error while creating reservation: {ex.Message}")); } }
public void DeleteReservation(ReservationDTO reservationDTO) { var reservation = AutoMapper.Mapper.Map <Reservation>(reservationDTO); _reservationRepository.Delete(reservation); _unitOfWork.Commit(); }
public void GetByID_WhenIdIsValid_ShouldReturnOK() { // arrange var mock = new Mock <IReservationRepository>(); var obj = new ReservationDTO( 41, DateTime.Now, new CustomerDTO(), DateTime.Now, 5, false, "TEST", new List <RestaurantTablesDTO> { new RestaurantTablesDTO(), new RestaurantTablesDTO() } ); // act mock.Setup(x => x.GetById(It.IsAny <int>())).Returns(obj); var controller = new ReservationController(mock.Object); var value = mock.Object.GetById(41); var actionResult = controller.Get(41); var okResult = actionResult as OkObjectResult; // assert Assert.IsNotNull(value); Assert.AreEqual(obj.Id, value.Id); Assert.IsNotNull(actionResult); Assert.AreEqual((int)HttpStatusCode.OK, okResult.StatusCode); }
public async Task SetOrderId(ReservationDTO model) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("gooiosapikey", "768960bff18111e79916016898e9f885"); var reqUrl = $"http://fancyservice.gooios.com/api/reservation/v1/setorderid"; var content = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json"); var res = await client.PutAsync(reqUrl, content); LogProvider.Trace(new Log { ApplicationKey = "77e960be918111e709189226c7e9f002", AppServiceName = "OrderService", BizData = res.StatusCode.ToString(), CallerApplicationKey = "", Exception = "", Level = LogLevel.INFO, LogThread = -1, LogTime = DateTime.Now, Operation = "OrderSubmittedHandler", ReturnValue = "" }); } }
public void Create_WhenReservationIsNotValid_ShouldReturnConflict() { ReservationDTO test = null; // arrange var mock = new Mock <IReservationRepository>(); var obj1 = new ReservationDTO( 0, DateTime.Now, new CustomerDTO(), DateTime.Now, 5, false, "TEST", new List <RestaurantTablesDTO> { new RestaurantTablesDTO(), new RestaurantTablesDTO() } ); // act mock.Setup(x => x.Create(obj1, true)).Returns(test); var controller = new ReservationController(mock.Object); var value = mock.Object.Create(obj1); var actionResult = controller.Post(obj1); var conflictObjectResult = actionResult as ConflictObjectResult; // assert Assert.IsNull(value); Assert.AreEqual(obj1, conflictObjectResult.Value); Assert.AreEqual((int)HttpStatusCode.Conflict, conflictObjectResult.StatusCode); }
public void Update_WhenReservationIsValidButIdNotMatching_ShouldReturnBadrequest() { // arrange var mock = new Mock <IReservationRepository>(); ReservationDTO nullObj = null; var obj1 = new ReservationDTO( 0, /// this DateTime.Now, new CustomerDTO(), DateTime.Now, 5, false, "TEST", new List <RestaurantTablesDTO> { new RestaurantTablesDTO(), new RestaurantTablesDTO() } ); // act mock.Setup(x => x.Update(obj1, true)).Returns(nullObj); var controller = new ReservationController(mock.Object); var value = mock.Object.Update(obj1); var actionResult = controller.Put(41, obj1); var badRequestObjectResult = actionResult as BadRequestObjectResult; // assert Assert.IsNull(value); Assert.AreEqual(obj1, badRequestObjectResult.Value); Assert.AreEqual((int)HttpStatusCode.BadRequest, badRequestObjectResult.StatusCode); }
public void GetByID_WhenIdIsValid_ShouldReturnNotFound() { // arrange var mock = new Mock <IReservationRepository>(); var obj = new ReservationDTO( 40, DateTime.Now, new CustomerDTO(), DateTime.Now, 5, false, "TEST", new List <RestaurantTablesDTO> { new RestaurantTablesDTO(), new RestaurantTablesDTO() } ); mock.Setup(x => x.GetById(40)).Returns(obj); var controller = new ReservationController(mock.Object); // act var value = mock.Object.GetById(41); var actionResult = controller.Get(41); var NotFound = actionResult as NotFoundObjectResult; // assert Assert.IsNull(value); Assert.AreEqual(NotFound.StatusCode, (int)HttpStatusCode.NotFound); }
public WorksheetViewModel() { _user = new UserDTO(); _reservation = new ReservationDTO(); _materials = new List <MaterialDTO>(); _totalPrice = 0; }
public async Task <ActionResult> Reserve([FromBody] ReservationDTO value) { string user_id = Request.Headers.FirstOrDefault(header => header.Key == "user_id").Value; string requestor = Request.Headers.FirstOrDefault(header => header.Key == "requestor").Value; var resul = await _repository.Reserve(user_id, requestor, value); if (resul == 200) { return(Ok()); } else if (resul == 401) { return(Unauthorized("You have no permission to perform this action")); } else if (resul == 4011) { return(Unauthorized("Your user has been deactivated by admin")); } else if (resul == 500) { return(BadRequest("Reservations longer than 6 days are not allowed")); } else if (resul == 5001) { return(BadRequest("Date range was invalid at the moment of creation. Check your dates.")); } else { return(BadRequest("You must wait " + resul + " days before making another reservation")); } }
public void CreateReservation(ReservationDTO newReservaton) { string sql = @"insert into dbo.Reservation (Date, UserId, BusinessId, TimeSlotId) values(@Date, @UserId, @BusinessId, @TimeSlotId);"; _dBManager.SaveData(sql, newReservaton); }
public void UpdateReservation() { var reservation = new ReservationDTO { Id = 1, Start = new DateTime(2012, 11, 12, 12, 0, 0), End = new DateTime(2020, 11, 12, 13, 0, 0), Title = "update" }; try { var reservationUpdate = this.Put(this.url, reservation.Id, reservation, true); } catch (Exception) { Assert.Fail("Updating chronicle via API failed!"); return; } //check if it was updated var url = this.url + this.prefix + reservation.Id; var fetched = this.Get <ReservationDTO>(url, true); Assert.NotNull(fetched); Assert.AreEqual(reservation.Title, fetched.Title); Assert.AreEqual(reservation.Start, fetched.Start); Assert.AreEqual(reservation.End, fetched.End); }
public async Task <int> PostReservation(ReservationDTO reservation, string userName, string role) { var book = await _bookRepo.GetBook((int)reservation.BookId); if (book.IsReserved) { throw new DbUpdateException(); } if (role == "Employee") { var user = await _userManager.FindByNameAsync(userName); if (user == null || book == null) { throw new DbUpdateException(); } if (book.LibraryId != user.LibraryId) { throw new UnauthorizedAccessException(); } } var id = await _repo.PostReservation(new Reservation { BookId = (int)reservation.BookId, UserId = reservation.UserId, StartDate = (DateTime)reservation.StartDate, ReturnDate = (DateTime)reservation.ReturnDate, IsReturned = false }); book.IsReserved = true; await _bookRepo.UpdateBook(book); return(id); }
public ResponseDTO AddReservation(ReservationDTO reservationDTO) { logger.LogInformation("Add reservation in progress"); try { context.Reservations.Add(mapper.Map <Reservation>(reservationDTO)); context.SaveChanges(); } catch (Exception e) { return(new ResponseDTO() { Code = 400, Message = e.Message, Status = "Error during add reservation" }); } return(new ResponseDTO() { Code = 200, Message = "Added reservation in db", Status = "Success" }); }
public IActionResult UpdateReservation(int id, [FromBody] ReservationDTO reservation) { if (reservation == null || reservation.ReservationId != id) { return(BadRequest()); } var reservationToUpdate = _manager.GetReservation(id); if (reservationToUpdate == null) { return(NotFound()); } var reservationMapped = _mapper.Map <Reservation>(reservation); try { _manager.UpdateReservation(reservationMapped); } catch (Exception) { return(BadRequest("Update reservation not allowed")); } return(Ok("Reservation updated")); }
public void ReservationCreateTest() { var roomMapper = new MapperConfiguration( cfg => { cfg.CreateMap<Room, RoomDTO>().ReverseMap(); cfg.CreateMap<PriceCategory, PriceCategoryDTO>().ReverseMap(); cfg.CreateMap<Category, CategoryDTO>().ReverseMap(); }).CreateMapper(); var clientMapper = new MapperConfiguration( cfg => cfg.CreateMap<Client, ClientDTO>()).CreateMapper(); var reservationDTO = new ReservationDTO() { ReservationID = 5, ReservationDate = DateTime.Parse("12.07.2021"), ArrivalDate = DateTime.Parse("01.08.2021"), DepartureDate = DateTime.Parse("11.08.2021"), SettledIn = false, RoomReservation = roomMapper.Map<Room, RoomDTO>(DataForTests.Rooms[0]), ClientResevation = clientMapper.Map<Client, ClientDTO>(DataForTests.Clients[2]) }; EFWorkUnitMock.Setup(x => x.Reservations.Create(fromDTOMapper.Map<ReservationDTO, Reservation>(reservationDTO))); var reservationService = new ReservationService(EFWorkUnitMock.Object); reservationService.Create(reservationDTO); EFWorkUnitMock.Verify(x => x.Reservations.Create(fromDTOMapper.Map<ReservationDTO, Reservation>(reservationDTO))); }
public void TestPostBookTableAsync() { //Arrange //var client = new RestClient("https://localhost:44349/api/Booking/Create"); // var client = new RestClient(constring); //string json = JsonConvert.SerializeObject(reservation); ////ACT //var request = new RestRequest("/post", Method.POST); //// var request = new RestRequest("/Booking/Create", Method.POST); //// request.AddJsonBody(reservation); //request.AddJsonBody(json); //var response = client.Execute(request); //Arrange BookingController _bc = new BookingController(); var reservation = new ReservationDTO( DateTime.Now, new CustomerDTO(), DateTime.Now, 4, false, "TEST", new List <RestaurantTablesDTO>()); //Act var response = _bc.PostBookingAsync(reservation, constring).Result; //Assert Assert.AreEqual(response.StatusCode, HttpStatusCode.OK); }
public ReservationDTO GetReservation(int reservationID) { bool lockWasTaken = false; ReservationDTO reservationDTO = null; using (RampUpProjectEntities dbContext = new RampUpProjectEntities(rampConnectionString)) { try { Monitor.Enter(dbContext, ref lockWasTaken); Reservation reservation = dbContext.Reservations.Where(x => x.Reservation_Id == reservationID).FirstOrDefault(); if (reservation != null) { reservationDTO = ConvertReservationToReservationDTO(reservation); } if (lockWasTaken) { Monitor.Exit(dbContext); lockWasTaken = false; } } catch (Exception) { if (lockWasTaken) { Monitor.Exit(dbContext); lockWasTaken = false; } throw; } return(reservationDTO); } }
/* * public IEnumerable<Reservation> GetReservationsByUser(int userId) * { * return IReservationRepository.GetReservationsByUser(userId); * } */ public IEnumerable <ReservationDTO> GetReservationsByUser(int userId) { IEnumerable <Reservation> MyReservations = IReservationRepository.GetReservationsByUser(userId); List <ReservationDTO> ReservationsDTO = new List <ReservationDTO>(); foreach (Reservation r in MyReservations) { ReservationDTO reservationDTO = new ReservationDTO() { id = r.id, checkIn = r.checkIn, checkOut = r.checkOut, price = r.price, review = r.review, userId = r.userId, apartmentId = r.apartmentId, numberOfPersons = r.numberOfPersons }; ReservationsDTO.Add(reservationDTO); } foreach (ReservationDTO res in ReservationsDTO) { Apartment Apartment = IApartmentRepository.Get(res.apartmentId); res.apartmentName = Apartment.apartmentName; Property Property = IPropertyRepository.Get(Apartment.propertyId); res.propertyName = Property.name; res.propertyId = Property.id; } return(ReservationsDTO); }
public List <ReservationDTO> GetallReservations() { var reservations = new List <ReservationDTO>(); using (_dbCon.Open()) { string query = "SELECT [Vehicle].[Brandname], [Vehicle].[Modelname], [Reservations].[ReservationID], [Reservations].[StartDate], [Reservations].[EndDate], [Reservations].[Email], [Reservations].[VehicleID]" + "FROM [Dbo].[Reservations]" + "INNER JOIN [Dbo].[Vehicle]" + "ON [Reservations].[VehicleID] = [Vehicle].[ID]" + "Order by [StartDate];"; using SqlCommand command = new SqlCommand(query, _dbCon.Connection); var reader = command.ExecuteReader(); while (reader.Read()) { ReservationDTO reservationDTO = new ReservationDTO { Brandname = reader.GetString(0), Modelname = reader.GetString(1), ReservationID = reader.GetInt32(2), StartDate = reader.GetDateTime(3), EndDate = reader.GetDateTime(4), Email = reader.GetString(5), VehicleID = reader.GetInt32(6) }; reservations.Add(reservationDTO); } } return(reservations); }
public async Task <ReservationDTO> CreateReservation(ReservationDTO reservation) { var mappedReservation = _mapper.Map <Reservation>(reservation); var training = await _trainingRepository.GetTraining(mappedReservation.TrainingId); mappedReservation.Date = DateTime.Now; if (training.Reservations.Count() >= training.Entries) { mappedReservation.IsReserveList = true; } var res = await _reservationRepository.CreateReservation(mappedReservation); var user = await _userService.GetUser(res.UserId); if (res.IsReserveList && user.Notification.ReserveListSignUpConfirmed) { await SendNotificationSignUpConfirmed(res.Id, res.IsReserveList); } if (!res.IsReserveList && user.Notification.SignUpConfirmed) { await SendNotificationSignUpConfirmed(res.Id, res.IsReserveList); } return(_mapper.Map <ReservationDTO>(res)); }
public async Task <Response <string> > CreateReservationAsync(ReservationDTO dto) { var response = new Response <string>(); var dateOfReservation = new DateTime(dto.Year, dto.Month, dto.Day, dto.Hour, dto.Minute, 0); var objToBD = new Reservation() { clientName = dto.clientName, clientPhone = dto.clientPhone, clientEmail = dto.clientEmail, tableNumber = dto.tableNumber, dateOfReservation = dateOfReservation, isConfirmed = false }; var result = await _db.Reservations.AddAsync(objToBD); if (result.State.ToString() == "Added") { await _db.SaveChangesAsync(); response.Data = "Reservation save succesed!"; } else { response.Error = new Error(500, "Error adding reservation!"); } return(response); }
public async Task <bool> UpdateReservation(Guid reservationId, ReservationDTO reservationDTO) { if (reservationId != reservationDTO.ReservationId) { throw new Exception("Invaild Reservation Id"); } var existingReservation = await _context.Reservation.FindAsync(reservationId); if (existingReservation == null) { throw new Exception("Reservation does not exists."); } else { existingReservation.StartDate = reservationDTO.StartDate; existingReservation.EndDate = reservationDTO.EndDate; existingReservation.NumberOfPlayers = reservationDTO.NumberOfPlayers; existingReservation.Notes = reservationDTO.Notes; existingReservation.LastModifiedBy = reservationDTO.LastModifiedBy; existingReservation.LastModifiedDateTime = DateTime.UtcNow; _context.Entry(existingReservation).State = EntityState.Modified; await _context.SaveChangesAsync(); return(true); } }
public async Task <ReservationDTO> AddReservationAsync(string userEmail, int carId, DateTime startDate, DateTime endDate) { var user = await db.UserRepository.GetUserAsync(userEmail); var car = await db.PointCarRepository.GetAsync(carId); if (car == null || car.Count == 0) { throw new Exception("This car is not available for rental"); } var reservationDTO = new ReservationDTO() { IsConfirmed = false, CreatedOn = DateTime.Now, StartDate = startDate, EndDate = endDate, RentalPointCarId = carId, UserId = user.Id }; var entity = reservationDTO.Adapt <Reservation>(); db.ReservationRepository.Add(entity); await db.Save(); reservationDTO.Id = entity.Id; return(reservationDTO); }
public ReservationDTO Update(long id, ReservationDTO res) { RESERVATION resToUpdate, updatedRes, oldRes; ReservationDTO retVal; retVal = null; oldRes = reservationRepository.GetById(id); if (CheckHelper.IsFilled(res) && CheckHelper.IsFilled(oldRes)) { try { resToUpdate = transformer.TransformFromDTO(id, res); resToUpdate.USER = oldRes.USER; resToUpdate.SEATs = oldRes.SEATs; updatedRes = reservationRepository.Update(resToUpdate); if (CheckHelper.IsFilled(updatedRes)) { retVal = transformer.TransformToDTO(updatedRes); } } catch (Exception) { } } return(retVal); }
public async Task <IActionResult> UpdateReservation(int reservationId, [FromBody] ReservationDTO reservation) { if (reservationId != reservation.ReservationId) { return(BadRequest()); } _wrapper.ReservationRepository.UpdateReservation(_mapper.Map <Reservation>(reservation)); try { await _wrapper.SaveAsync(); } catch (DbUpdateConcurrencyException e) { if (!await ReservationExists(reservationId)) { return(NotFound()); } else { return(BadRequest(e.Message)); } } return(Ok()); }