scinote-web/app/models/user_team.rb

68 lines
1.9 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
2017-06-23 21:19:08 +08:00
class UserTeam < ApplicationRecord
2016-02-12 23:52:43 +08:00
enum role: { guest: 0, normal_user: 1, admin: 2 }
validates :role, :user, :team, presence: true
2016-02-12 23:52:43 +08:00
belongs_to :user, inverse_of: :user_teams, touch: true
belongs_to :assigned_by, foreign_key: 'assigned_by_id', class_name: 'User', optional: true
belongs_to :team, inverse_of: :user_teams
2016-02-12 23:52:43 +08:00
after_create :assign_user_to_visible_projects
before_destroy :destroy_associations
2016-02-12 23:52:43 +08:00
def role_str
2017-01-31 20:33:55 +08:00
I18n.t("user_teams.enums.role.#{role}")
2016-02-12 23:52:43 +08:00
end
def destroy_associations
2017-01-24 23:34:21 +08:00
# Destroy the user from all team's projects
user.user_projects.joins(:project).where(project: team.projects).destroy_all
# destroy all assignments
UserAssignments::RemoveUserAssignmentJob.perform_now(user, team)
2016-02-12 23:52:43 +08:00
end
2017-01-24 23:34:21 +08:00
# returns user_teams where the user is in team
def self.user_in_team(user, team)
where(user: user, team: team)
end
2016-07-21 19:11:15 +08:00
def destroy(new_owner)
return super() unless new_owner
2016-07-21 19:11:15 +08:00
# Also, make new owner author of all protocols that belong
# to the departing user and belong to this team.
p_ids = user.added_protocols.where(team: team).pluck(:id)
2016-07-21 19:11:15 +08:00
Protocol.find(p_ids).each do |protocol|
protocol.record_timestamps = false
protocol.added_by = new_owner
if protocol.archived_by != nil
protocol.archived_by = new_owner
end
if protocol.restored_by != nil
protocol.restored_by = new_owner
end
protocol.save
end
# Make new owner author of all inventory items that were added
# by departing user and belong to this team.
RepositoryRow.change_owner(team, user, new_owner)
2016-07-21 19:11:15 +08:00
super()
end
private
def assign_user_to_visible_projects
team.projects.visible.each do |project|
UserAssignments::ProjectGroupAssignmentJob.perform_later(
team,
project,
assigned_by
)
end
end
2016-02-12 23:52:43 +08:00
end