project_team.rb 2.43 KB
Newer Older
1
class ProjectTeam
2 3 4 5
  attr_accessor :project

  def initialize(project)
    @project = project
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
  end

  # Shortcut to add users
  #
  # Use:
  #   @team << [@user, :master]
  #   @team << [@users, :master]
  #
  def << args
    users = args.first

    if users.respond_to?(:each)
      add_users(users, args.second)
    else
      add_user(users, args.second)
    end
22 23
  end

24
  def find(user_id)
25
    user = project.users.find_by_id(user_id)
26 27 28 29 30 31

    if group
      user ||= group.users.find_by_id(user_id)
    end

    user
32 33
  end

34
  def find_tm(user_id)
35 36 37 38 39 40 41 42 43
    tm = project.users_projects.find_by_user_id(user_id)

    # If user is not in project members
    # we should check for group membership
    if group && !tm
      tm = group.users_groups.find_by_user_id(user_id)
    end

    tm
44 45
  end

46 47 48 49 50 51 52 53
  def add_user(user, access)
    add_users_ids([user.id], access)
  end

  def add_users(users, access)
    add_users_ids(users.map(&:id), access)
  end

54
  def add_users_ids(user_ids, access)
55 56 57 58 59 60 61 62 63 64 65 66 67
    UsersProject.add_users_into_projects(
      [project.id],
      user_ids,
      access
    )
  end

  # Remove all users from project team
  def truncate
    UsersProject.truncate_team(project)
  end

  def members
68
    @members ||= fetch_members
69 70 71
  end

  def guests
72
    @guests ||= fetch_members(:guests)
73 74 75
  end

  def reporters
76
    @reporters ||= fetch_members(:reporters)
77 78 79
  end

  def developers
80
    @developers ||= fetch_members(:developers)
81 82 83
  end

  def masters
84
    @masters ||= fetch_members(:masters)
85
  end
86 87 88 89

  def import(source_project)
    target_project = project

skv's avatar
skv committed
90 91
    source_team = source_project.users_projects.to_a
    target_team = target_project.users_projects.to_a
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    target_user_ids = target_team.map(&:user_id)

    source_team.reject! do |tm|
      # Skip if user already present in team
      target_user_ids.include?(tm.user_id)
    end

    source_team.map! do |tm|
      new_tm = tm.dup
      new_tm.id = nil
      new_tm.project_id = target_project.id
      new_tm
    end

    UsersProject.transaction do
      source_team.each do |tm|
        tm.save
      end
    end

    true
  rescue
    false
  end
116 117 118 119 120

  private

  def fetch_members(level = nil)
    project_members = project.users_projects
121
    group_members = group ? group.users_groups : []
122 123 124

    if level
      project_members = project_members.send(level)
125
      group_members = group_members.send(level) if group
126 127 128 129
    end

    (project_members + group_members).map(&:user).uniq
  end
130 131 132 133

  def group
    project.group
  end
134
end