Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
goals_helper.rb 7.36 KiB
module GoalsHelper
  # Returns number of habits user currently has
  def getHabitsAmount(current_user)
    amount = 0
    current_user.habits.each do |habit|
      amount = amount + 1
    end
    return amount
  end

  def updateHabitAmountGoals
    @goals = Goals.where(goaltype: "habitAmount")
    amount = getHabitsAmount(current_user)

    @goals.each do |goal|
      if goal.counter != amount
        goal.counter = amount
      end
      if goal.counter >= goal.target
        goal.completed = "true"
      end
      goal.save
    end
  end

  # Updates streaks for goals
  def updateHabitStreakGoals
    @goals = Goals.where(goaltype: "habitStreak").or(Goals.where(goaltype: "monthlyHabitStreak"))

    @goals.each do |goal|
      if Habit.exists?(goal.habit_id)
        @habit = Habit.find(goal.habit_id)
        currentStreak = @habit.streak

        if goal.counter != currentStreak
          goal.counter = currentStreak
        end
        if goal.counter >= goal.target
          goal.completed = "true"
        end
        goal.save
      else
        goal.destroy
      end
    end
  end

  # Calls update methods
  def updateAllGoals
    updateHabitAmountGoals
    updateHabitStreakGoals
  end

  def generateHabitAmountGoals
    #I know very messy but gets job done
    @completedgoals = Goals.where(user_id: current_user.id, completed: "true")
    @allgoals = Goals.where(user_id: current_user.id)

    if @completedgoals.exists?(title: "First")
      if @completedgoals.exists?(title: "Second")
        if @completedgoals.exists?(title: "Third")
          if @completedgoals.exists?(title: "Forth")
            if @completedgoals.exists?(title: "Fifth")
            elsif @allgoals.exists?(title: "Fifth")
            else
              @goal = Goals.new(:title => "Fifth", :description => "Create your fifth habit", :counter => "0", :target => "5", :user_id => current_user.id,
                                :goaltype => "habitAmount", :completed => "false")
              @goal.save
            end
          elsif @allgoals.exists?(title: "Forth")
          else
            @goal = Goals.new(:title => "Forth", :description => "Create your forth habit", :counter => "0", :target => "4", :user_id => current_user.id,
                              :goaltype => "habitAmount", :completed => "false")
            @goal.save
          end
        elsif @allgoals.exists?(title: "Third")
        else
          @goal = Goals.new(:title => "Third", :description => "Create your third habit", :counter => "0", :target => "3", :user_id => current_user.id,
                            :goaltype => "habitAmount", :completed => "false")
          @goal.save
        end
      elsif @allgoals.exists?(title: "Second")
      else
        @goal = Goals.new(:title => "Second", :description => "Create your second habit", :counter => "0", :target => "2", :user_id => current_user.id,
                          :goaltype => "habitAmount", :completed => "false")
        @goal.save
      end
    elsif @allgoals.exists?(title: "First")
    else
      @goal = Goals.new(:title => "First", :description => "Create your first habit", :counter => "0", :target => "1", :user_id => current_user.id,
                        :goaltype => "habitAmount", :completed => "false")
      @goal.save
    end
    updateHabitAmountGoals
  end

  def generateHabitStreakGoals
    @habits = Habit.where(user_id: current_user.id)
    @goals = Goals.where(user_id: current_user.id)
    @habits.each do |habit|
      if @goals.exists?(title: habit.title)
      else
        @goal = Goals.new(:title => habit.title, :description => "Reach Target", :counter => habit.streak, :target => habit.target,
                          :user_id => current_user.id, :goaltype => "habitStreak", :completed => "false", :habit_id => habit.id)
        @goal.save
      end
    end
    updateHabitStreakGoals
  end

  def deleteLastMonthsGoals
    @goals = Goals.where(user_id: current_user.id, goaltype: "monthlyHabitStreak", completed: "false")
    if @goals.length > 0
      @goals.each do |goal|
        goal.destroy
      end
    end
  end

  def generateMonthlyGoals
    if Date.today == Date.today.beginning_of_month

      deleteLastMonthsGoals
      pushGoalNotification("New Goals generated!")

      @goals = Goals.where(user_id: current_user.id, goaltype: "monthlyHabitStreak")
      monthlyHabitsCreated = "false"

      if @goals.size > 0
        monthlyHabitsCreated = "true"
      end

      if monthlyHabitsCreated == "false"
        @habits = Habit.all
        @myhabits = Habit.where(user_id: current_user.id)

        @emptyhabits = Habit.where(user_id: current_user.id, streak: 0)
        if @emptyhabits.length > 0
          @habit = @emptyhabits.order("RANDOM()").first()
          @goal = Goals.new(:title => "Start tracking " + @habit.title, :description => "Reach a streak of 10 for " + @habit.title, :counter => @habit.streak, :target => 10,
                            :user_id => current_user.id, :goaltype => "monthlyHabitStreak", :completed => "false", :habit_id => @habit.id)
          @goal.save
        end

        allstreaks = Array.new
        allstreaks = @habits.pluck(:streak)
        allstreaks = allstreaks.sort
        higheststreak = @myhabits.maximum("streak")

        @myhabits.each do |habit|
          if habit.streak == higheststreak
            @maxhabit = habit
          end
        end

        position = allstreaks.length - allstreaks.find_index(@maxhabit.streak)
        percentile = ((position.to_f / allstreaks.length) * 100).ceil
        if percentile == 0
          percentile = 1
        end

        @goal = Goals.new(:title => "Increase " + @maxhabit.title + " streak", :description => "Your " + @maxhabit.title + " streak is in the top " + percentile.to_s + "% for highest ongoing streak, keep this going this month",
                          :counter => @maxhabit.streak, :target => @maxhabit.streak + 25,
                          :user_id => current_user.id, :goaltype => "monthlyHabitStreak", :completed => "false", :habit_id => @maxhabit.id)
        @goal.save

        @streakhabits = Habit.where("(max_streak - streak) < 30").where("(max_streak - streak) >= 0").where(user_id: current_user.id)
        @habit = @streakhabits.order("RANDOM()").first()

        @goal = Goals.new(:title => "Streak Beater", :description => "Beat your maximum streak for " + @habit.title, :counter => @habit.streak, :target => @habit.max_streak,
                          :user_id => current_user.id, :goaltype => "monthlyHabitStreak", :completed => "false", :habit_id => @habit.id)
        @goal.save
      end
    end
  end

  def pushGoalNotification(message)
    current_user.push_subscriptions.each do |subscription| begin
      Webpush.payload_send(
        message: message,
        endpoint: subscription.endpoint,
        p256dh: subscription.p256dh,
        auth: subscription.auth,
        vapid: {
          subject: "mailto:sender@example.com",
          public_key: ENV['VAPID_PUBLIC_KEY'],
          private_key: ENV['VAPID_PRIVATE_KEY'],
          expiration: 60*59*24
        },
        ssl_timeout: 5, # value for Net::HTTP#ssl_timeout=, optional
        open_timeout: 5, # value for Net::HTTP#open_timeout=, optional
        read_timeout: 5 # value for Net::HTTP#read_timeout=, optional
      )
      rescue Webpush::InvalidSubscription => exception
        subscription.destroy
      rescue Webpush::ExpiredSubscription => exception
        subscription.destroy
      end
    end
  end
end