scinote-web/app/models/user_team.rb

86 lines
2.5 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
before_destroy :destroy_associations
2016-12-08 00:43:00 +08:00
after_create :create_samples_table_state
validates_uniqueness_of :user_id, scope: :team_id
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 create_samples_table_state
2016-12-08 21:41:35 +08:00
SamplesTable.create_samples_table_state(self)
2016-12-07 21:14:32 +08:00
end
2016-02-12 23:52:43 +08:00
def destroy_associations
2017-01-24 23:34:21 +08:00
# Destroy the user from all team's projects
team.projects.each do |project|
2016-02-12 23:52:43 +08:00
up2 = (project.user_projects.select { |up| up.user == self.user }).first
if up2.present?
up2.destroy
end
end
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
2017-01-24 23:34:21 +08:00
# If any project of the team has the sole owner and that
# owner is the user to be removed from the team, then we must
2016-07-21 19:11:15 +08:00
# create a new owner of the project (the provided user).
2017-01-24 23:34:21 +08:00
team.projects.find_each do |project|
2016-07-21 19:11:15 +08:00
owners = project.user_projects.where(role: 0)
if owners.count == 1 && owners.first.user == user
if project.users.exists?(new_owner.id)
# If the new owner is already assigned onto project,
# update its role
project.user_projects.find_by(user: new_owner).update(role: 0)
else
# Else, create a new association
UserProject.create(
user: new_owner,
project: project,
role: 0,
assigned_by: user
)
end
2016-07-21 19:11:15 +08:00
end
end
# 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
2016-02-12 23:52:43 +08:00
end