Exemplo n.º 1
0
        public ServiceResponse ChangeOrder(ChangeHabitsOrderRequest request)
        {
            var authResponse = _authService.GetCurrentUserId();

            if (authResponse.Failure)
            {
                return(Failure());
            }

            var habits = _dataContext
                         .Habits
                         .Where(h => h.UserId == authResponse.Payload)
                         .OrderBy(h => h.Order)
                         .ToList();

            for (int i = 0; i < habits.Count(); i++)
            {
                habits[i].Order = i;
            }

            var habit = habits
                        .FirstOrDefault(h => h.Id == request.Id);

            if (habit == null)
            {
                return(Failure());
            }

            if (request.Position < habit.Order)
            {
                var movedHabits = habits
                                  .Where(h => h.Id != request.Id)
                                  .Where(h => habit.Order >= h.Order && h.Order >= request.Position);

                foreach (var movedHabit in movedHabits)
                {
                    movedHabit.Order++;
                }
            }
            else
            {
                var movedHabits = habits
                                  .Where(h => h.Id != request.Id)
                                  .Where(h => habit.Order <= h.Order && h.Order <= request.Position);

                foreach (var movedHabit in movedHabits)
                {
                    movedHabit.Order--;
                }
            }

            habit.Order = request.Position;

            try
            { _dataContext.SaveChanges(); }
            catch (Exception)
            { return(Failure()); }

            return(Success());
        }
Exemplo n.º 2
0
        public JsonResult ChangeOrder([FromBody] ChangeHabitsOrderRequest request)
        {
            var response = _habitService.ChangeOrder(request);

            return(ServiceResponse(response));
        }