task_service.rb 1.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
# TaskService class
#
# Used for creating tasks on task queue after certain user action
#
# Ex.
#   TaskService.new.new_issue(issue, current_user)
#
class TaskService
  # When create an issue we should:
  #
  #  * creates a pending task for assignee if issue is assigned
  #
  def new_issue(issue, current_user)
14
    if issue.is_assigned? && issue.assignee != current_user
15 16 17 18
      create_task(issue.project, issue, current_user, issue.assignee, Task::ASSIGNED)
    end
  end

19 20 21 22 23 24 25 26
  # When close an issue we should:
  #
  #  * mark all pending tasks related to the target for the current user as done
  #
  def close_issue(issue, current_user)
    mark_as_done(issue, current_user)
  end

27 28 29 30 31 32 33 34 35 36
  # When we reassign an issue we should:
  #
  #  * creates a pending task for new assignee if issue is assigned
  #
  def reassigned_issue(issue, current_user)
    if issue.is_assigned?
      create_task(issue.project, issue, current_user, issue.assignee, Task::ASSIGNED)
    end
  end

37 38 39 40 41 42 43 44 45
  # When we mark a task as done we should:
  #
  #  * mark all pending tasks related to the target for the user as done
  #
  def mark_as_done(target, user)
    pending_tasks = pending_tasks_for(user, target.project, target)
    pending_tasks.update_all(state: :done)
  end

46 47 48 49 50 51 52 53 54 55 56 57 58 59
  private

  def create_task(project, target, author, user, action)
    attributes = {
      project: project,
      user_id: user.id,
      author_id: author.id,
      target_id: target.id,
      target_type: target.class.name,
      action: action
    }

    Task.create(attributes)
  end
60 61 62 63

  def pending_tasks_for(user, project, target)
    user.tasks.pending.where(project: project, target: target)
  end
64
end