示例#1
0
        public GenericObjectResponse <List <WorkingHoursPayload> > ChangeWorkingHoursForRoom(long roomId, List <WorkingHoursPayload> workingHours, bool shouldValidate = true)
        {
            if (shouldValidate)
            {
                WorkingHoursValidationService workingHoursValidationService = new WorkingHoursValidationService();
                GenericStatusMessage          validationMessage             = workingHoursValidationService.ValidateWorkingHoursData(workingHours);
                if (!validationMessage.Success)
                {
                    return(new GenericObjectResponse <List <WorkingHoursPayload> >(validationMessage.Message));
                }
            }

            try
            {
                using (ReservationDataContext context = new ReservationDataContext())
                {
                    List <WorkingHours> workingHoursToRemove = context.WorkingHours.Where(x => x.RoomId == roomId).ToList();
                    context.WorkingHours.RemoveRange(workingHoursToRemove);
                    List <WorkingHours> workingHoursToAdd = workingHours.Select(x => ConvertWorkingHoursFromPayload(roomId, x)).ToList();
                    context.WorkingHours.AddRange(workingHoursToAdd);
                    context.SaveChanges();
                    List <WorkingHoursPayload> savedWorkingHours = context.WorkingHours
                                                                   .Where(x => x.RoomId == roomId)
                                                                   .Select(ConvertWorkingHoursToPayload)
                                                                   .ToList();
                    return(new GenericObjectResponse <List <WorkingHoursPayload> >(savedWorkingHours));
                }
            }
            catch (DbEntityValidationException e)
            {
                string exceptionMessage = e.EntityValidationErrors.FirstOrDefault()?.ValidationErrors.FirstOrDefault()?.ErrorMessage;
                Logger.Error($"Failed to create working hours. Error: '{exceptionMessage}'");
                return(new GenericObjectResponse <List <WorkingHoursPayload> >("Failed to add working hours, please contact support."));
            }
        }
        public GenericObjectResponse <UserResponse> ChangeUserData(ChangeUserDataPayload payload, long userId)
        {
            UserValidationService service            = new UserValidationService();
            GenericStatusMessage  validationResponse = service.ValidateUserData(payload, false);

            if (validationResponse.Success)
            {
                using (ReservationDataContext context = new ReservationDataContext())
                {
                    User user = context.Users.Single(x => x.Id == userId);
                    user.FirstName      = payload.FirstName ?? user.FirstName;
                    user.LastName       = payload.LastName ?? user.LastName;
                    user.Country        = payload.Country ?? user.Country;
                    user.City           = payload.City ?? user.City;
                    user.Street         = payload.Street ?? user.Street;
                    user.BuildingNumber = payload.BuildingNumber ?? user.BuildingNumber;
                    context.SaveChanges();
                    return(new GenericObjectResponse <UserResponse>(ConvertUserToUserResponse(user)));
                }
            }
            else
            {
                return(new GenericObjectResponse <UserResponse>(validationResponse.Message));
            }
        }
        public GenericObjectResponse <List <WorkingHoursPayload> > ChangeWorkingHours(long roomId, [FromBody] List <WorkingHoursPayload> payload)
        {
            long?userId = AuthenticationService.IsAuthorized(Request, UserRole.RoomOwner);

            if (userId == null)
            {
                Response.StatusCode = 401;
                return(new GenericObjectResponse <List <WorkingHoursPayload> >(""));
            }

            RoomValidationService roomValidationService = new RoomValidationService();
            GenericStatusMessage  roomExistsValidation  = roomValidationService.ValidateRoomExistsAndOwnedByUser(roomId, userId.Value);

            if (!roomExistsValidation.Success)
            {
                Response.StatusCode = 404;
                return(new GenericObjectResponse <List <WorkingHoursPayload> >("Not found."));
            }

            WorkingHoursManipulationService service = new WorkingHoursManipulationService();
            GenericObjectResponse <List <WorkingHoursPayload> > response = service.ChangeWorkingHoursForRoom(roomId, payload);

            if (!response.Status.Success)
            {
                Response.StatusCode = 400;
            }

            return(response);
        }
        public GenericListResponse <ReservationRequestResponse> GetReservationsByDate(long roomId, [FromQuery] DateTime?startDate, [FromQuery] DateTime?endDate,
                                                                                      [FromQuery] int skip = 0, [FromQuery] int take = 10)
        {
            long?userId = AuthenticationService.IsAuthorized(Request, UserRole.Coach, UserRole.RoomOwner);

            if (userId == null)
            {
                Response.StatusCode = 401;
                return(new GenericListResponse <ReservationRequestResponse>(""));
            }

            RoomValidationService roomValidationService = new RoomValidationService();
            GenericStatusMessage  roomExistsValidation  = roomValidationService.ValidateRoomExists(roomId);

            if (!roomExistsValidation.Success)
            {
                Response.StatusCode = 404;
                return(new GenericListResponse <ReservationRequestResponse>("Not found."));
            }

            DateTime defaultStartDate            = startDate ?? DateTime.Today;
            DateTime defaultEndDate              = endDate ?? defaultStartDate + TimeSpan.FromDays(180);
            ReservationQueryService queryService = new ReservationQueryService();

            return(queryService.GetReservationsByDate(roomId, defaultStartDate, defaultEndDate, userId.Value, skip, take));
        }
        public GenericObjectResponse <ReservationRequestResponse> RequestReservation(long roomId, [FromBody] ReservationRequestPayload payload)
        {
            long?userId = AuthenticationService.IsAuthorized(Request, UserRole.RoomOwner, UserRole.Coach);

            if (userId == null)
            {
                Response.StatusCode = 401;
                return(new GenericObjectResponse <ReservationRequestResponse>(""));
            }

            ReservationRequestPayload trimmedPayload = new ReservationRequestPayload()
            {
                Description = payload.Description,
                RentStart   = payload.RentStart.TrimDate(DateTimePrecision.Minute).ToLocalDate(),
                RentEnd     = payload.RentEnd.TrimDate(DateTimePrecision.Minute).ToLocalDate()
            };
            ReservationValidationService reservationValidationService = new ReservationValidationService();
            GenericStatusMessage         roomAvailabilityValidation   = reservationValidationService.ValidateRoomAvailability(roomId, trimmedPayload);

            if (!roomAvailabilityValidation.Success)
            {
                Response.StatusCode = 400;
                return(new GenericObjectResponse <ReservationRequestResponse>(roomAvailabilityValidation.Message));
            }

            ReservationManipulationService reservationManipulationService = new ReservationManipulationService();

            return(reservationManipulationService.AddReservation(roomId, userId.Value, trimmedPayload));
        }
        public GenericListResponse <AvailableReservationTime> GetRoomAvailableTimes(long roomId, DateTime?startDate, int duration, int take)
        {
            using (ReservationDataContext context = new ReservationDataContext())
            {
                if (duration <= 0)
                {
                    return(new GenericListResponse <AvailableReservationTime>("Invalid duration."));
                }

                var roomQuery = context.Rooms.Include(x => x.WorkingHours).Include(x => x.Reservations);
                var room      = roomQuery.SingleOrDefault(x => x.Id == roomId);
                if (room == null)
                {
                    return(new GenericListResponse <AvailableReservationTime>("Room not found."));
                }

                List <AvailableReservationTime> availableTimes = new List <AvailableReservationTime>();
                DateTime now             = DateTime.Now;
                DateTime currentDateTemp = (startDate != null && startDate > now ? startDate.Value.ToLocalDate() : now);
                DateTime currentDate     = currentDateTemp.Date;
                int      limit           = 1440 - duration;
                ReservationValidationService reservationValidationService = new ReservationValidationService();
                while (availableTimes.Count < take)
                {
                    for (int i = 0; i < limit && availableTimes.Count < take; i += 30)
                    {
                        DateTime rentStart = currentDate + TimeSpan.FromMinutes(i);
                        if (rentStart < now)
                        {
                            continue;
                        }

                        ReservationRequestPayload payload = new ReservationRequestPayload
                        {
                            RentStart = rentStart,
                            RentEnd   = rentStart + TimeSpan.FromMinutes(duration)
                        };

                        GenericStatusMessage availability = reservationValidationService.ValidateRoomAvailability(context, room, payload);
                        if (availability.Success)
                        {
                            var matchedWorkingHours = reservationValidationService.GetMatchingWorkingHours(payload, room);
                            availableTimes.Add(new AvailableReservationTime
                            {
                                RentStart = rentStart,
                                Price     = PriceHelper.CalculatePrice(matchedWorkingHours.PriceForHour, rentStart, payload.RentEnd)
                            });
                        }
                    }

                    currentDate += TimeSpan.FromDays(1);
                }
                return(new GenericListResponse <AvailableReservationTime>(availableTimes, availableTimes.Count));
            }
        }
        public async Task <GenericObjectResponse <RoomResponse> > AddRoom(CreateRoomPayload payload, long?userId)
        {
            try
            {
                Logger.Debug($"Attempting to create new room for user {userId}");
                RoomResponse          roomResponse     = null;
                RoomValidationService service          = new RoomValidationService();
                GenericStatusMessage  validationResult = service.ValidateRoomData(payload);
                if (!validationResult.Success)
                {
                    return(new GenericObjectResponse <RoomResponse>(validationResult.Message));
                }

                using (ReservationDataContext context = new ReservationDataContext())
                {
                    Room room = ConvertRoomFromPayload(payload, userId);
                    context.Rooms.Add(room);
                    context.SaveChanges();
                    roomResponse = ConvertRoomToResponse(room, userId);
                }

                Logger.Debug($"Attempting to create working hours for room {roomResponse.Id}");
                WorkingHoursManipulationService workingHoursService = new WorkingHoursManipulationService();
                GenericObjectResponse <List <WorkingHoursPayload> > workingHours = workingHoursService.ChangeWorkingHoursForRoom(roomResponse.Id, payload.WorkingHours);
                if (!workingHours.Status.Success)
                {
                    Logger.Error($"failed to create working hours for room {roomResponse.Id}, Deleting created room.");
                    using (ReservationDataContext context = new ReservationDataContext())
                    {
                        Room room = context.Rooms.Single(x => x.Id == roomResponse.Id);
                        context.Rooms.Remove(room);
                        context.SaveChanges();
                    }
                    return(new GenericObjectResponse <RoomResponse>($"Failed to add room due to faulty working hours: {workingHours.Status.Message}"));
                }
                roomResponse.WorkingHours = workingHours.Object;
                Logger.Debug($"Room created for user {userId}.");
                LatLon latLon = await AddLatLonForRoom(roomResponse.Id);

                if (latLon != null)
                {
                    roomResponse.Lat = latLon.Lat;
                    roomResponse.Lon = latLon.Lon;
                }
                return(new GenericObjectResponse <RoomResponse>(roomResponse));
            }
            catch (DbEntityValidationException e)
            {
                string exceptionMessage = e.EntityValidationErrors.FirstOrDefault()?.ValidationErrors.FirstOrDefault()?.ErrorMessage;
                Logger.Error($"Failed to create room. Error: '{exceptionMessage}'");
                return(new GenericObjectResponse <RoomResponse>("Failed to add the room, please contact support."));
            }
        }
示例#8
0
        public GenericStatusMessage CreateUser([FromBody] CreateUserPayload payload, UserRole role)
        {
            UserValidationService userValidationService = new UserValidationService();
            GenericStatusMessage  genericStatusMessage  = userValidationService.ValidateCreateUserData(payload);

            if (!genericStatusMessage.Success)
            {
                Response.StatusCode = 400;
                return(genericStatusMessage);
            }

            UserManipulationService userManipulationService = new UserManipulationService();

            return(userManipulationService.AddUser(payload, role));
        }
示例#9
0
        public GenericStatusMessage ValidateWorkingHoursData(List <WorkingHoursPayload> list, bool required = true)
        {
            for (int i = 0; i < list.Count; i++)
            {
                WorkingHoursPayload  current = list[i];
                GenericStatusMessage status  = ValidateWorkingHoursData(current, required);
                if (!status.Success)
                {
                    status.Message = $"Working hours [{i}]: {status.Message}";
                    return(status);
                }
            }

            List <GenericStatusMessage> overlapsValidations = list.GroupBy(x => x.Day).Select(x => CheckOverlapsForDay(x)).ToList();

            return(overlapsValidations.FirstOrDefault(x => !x.Success) ?? new GenericStatusMessage(true));
        }
示例#10
0
        public GenericStatusMessage ChangePassword([FromBody] PasswordChangePayload payload)
        {
            long?userId = AuthenticationService.IsAuthorized(Request, UserRole.Coach, UserRole.RoomOwner);

            if (userId == null)
            {
                Response.StatusCode = 401;
                return(new GenericStatusMessage(false));
            }
            else
            {
                UserManipulationService userManipulationService = new UserManipulationService();
                GenericStatusMessage    message = userManipulationService.ChangePassword(payload, userId.Value);
                Response.StatusCode = message.Success ? 200 : 401;
                return(message);
            }
        }
        public async Task <GenericObjectResponse <RoomResponse> > ChangeRoomData([FromBody] CreateRoomPayload payload, long roomId)
        {
            long?userId = AuthenticationService.IsAuthorized(Request, UserRole.RoomOwner);

            if (userId == null)
            {
                Response.StatusCode = 401;
                return(new GenericObjectResponse <RoomResponse>(""));
            }

            RoomValidationService roomValidationService = new RoomValidationService();
            GenericStatusMessage  roomExistsValidation  = roomValidationService.ValidateRoomExistsAndOwnedByUser(roomId, userId.Value);

            if (!roomExistsValidation.Success)
            {
                Response.StatusCode = 404;
                return(new GenericObjectResponse <RoomResponse>("Not found."));
            }

            RoomManipulationService roomManipulationService = new RoomManipulationService();

            return(await roomManipulationService.ChangeRoomData(payload, roomId));
        }
        private GenericStatusMessage ChangeRoomActivation(long roomId, bool activate, bool force = false)
        {
            long?userId = AuthenticationService.IsAuthorized(Request, UserRole.RoomOwner);

            if (userId == null)
            {
                Response.StatusCode = 401;
                return(new GenericStatusMessage(false, ""));
            }

            RoomValidationService roomValidationService = new RoomValidationService();
            GenericStatusMessage  roomExistsValidation  = roomValidationService.ValidateRoomExistsAndOwnedByUser(roomId, userId.Value);

            if (!roomExistsValidation.Success)
            {
                Response.StatusCode = 404;
                return(new GenericStatusMessage(false, "Not found."));
            }

            RoomManipulationService roomManipulationService = new RoomManipulationService();

            return(roomManipulationService.ChangeRoomActivation(roomId, activate, force));
        }
        public GenericStatusMessage RejectReservation(long roomId, long requestId)
        {
            long?userId = AuthenticationService.IsAuthorized(Request, UserRole.RoomOwner);

            if (userId == null)
            {
                Response.StatusCode = 401;
                return(new GenericStatusMessage(false, ""));
            }

            ReservationValidationService reservationValidationService = new ReservationValidationService();
            GenericStatusMessage         requestExistsValidation      = reservationValidationService.ValidateRequest(roomId, requestId, userId.Value);

            if (!requestExistsValidation.Success)
            {
                Response.StatusCode = 400;
                return(new GenericStatusMessage(false, requestExistsValidation.Message));
            }

            ReservationManipulationService reservationManipulationService = new ReservationManipulationService();

            return(reservationManipulationService.ChangeReservationApproval(requestId, ReservationStatus.Rejected));
        }
        public async Task <GenericObjectResponse <RoomResponse> > ChangeRoomData(CreateRoomPayload payload, long roomId)
        {
            RoomValidationService service            = new RoomValidationService();
            GenericStatusMessage  validationResponse = service.ValidateRoomData(payload, false);
            RoomResponse          roomResponse       = null;

            if (validationResponse.Success)
            {
                using (ReservationDataContext context = new ReservationDataContext())
                {
                    Room room = context.Rooms.Include(x => x.WorkingHours).Single(x => x.Id == roomId);
                    room.Name = payload.Name ?? room.Name;
                    room.Size = payload.Size ?? room.Size;
                    room.MaxNumberOfPeople = payload.MaxNumberOfPeople ?? room.MaxNumberOfPeople;
                    room.Country           = payload.Country ?? room.Country;
                    room.City           = payload.City ?? room.City;
                    room.Street         = payload.Street ?? room.Street;
                    room.BuildingNumber = payload.BuildingNumber ?? room.BuildingNumber;
                    context.SaveChanges();
                    roomResponse = ConvertRoomToResponse(room, room.OwnerId);
                }

                LatLon latLon = await AddLatLonForRoom(roomResponse.Id);

                if (latLon != null)
                {
                    roomResponse.Lat = latLon.Lat;
                    roomResponse.Lon = latLon.Lon;
                }

                return(new GenericObjectResponse <RoomResponse>(roomResponse));
            }
            else
            {
                return(new GenericObjectResponse <RoomResponse>(validationResponse.Message));
            }
        }