scinote-web/app/services/client_api/user_team_service.rb

88 lines
2.6 KiB
Ruby
Raw Normal View History

2017-08-31 21:56:55 +08:00
module ClientApi
class UserTeamService
include NotificationsHelper
include InputSanitizeHelper
2017-09-01 23:10:43 +08:00
def initialize(args)
2017-08-31 21:56:55 +08:00
parsed_args = validate_params(args)
@team = Team.find_by_id(parsed_args.fetch(:team_id))
@user = parsed_args.fetch(:user)
2017-09-01 23:10:43 +08:00
@user_team = UserTeam.find_by_id(parsed_args.fetch(:user_team_id).to_i)
@role = args.fetch(:role) { false }
2017-08-31 21:56:55 +08:00
end
def destroy_user_team_and_assign_new_team_owner!
2017-09-14 19:11:19 +08:00
raise ClientApi::CustomUserTeamError if user_cant_leave?
2017-08-31 21:56:55 +08:00
new_owner = @team.user_teams
.where(role: 2)
.where.not(id: @user_team.id)
.first.user
new_owner ||= @user
reset_user_current_team(@user_team)
@user_team.destroy(new_owner)
generate_new_notification
end
def update_role!
2017-09-14 19:11:19 +08:00
raise ClientApi::CustomUserTeamError if user_cant_leave?
unless @role
raise ClientApi::CustomUserTeamError,
I18n.t('client_api.generic_error_message')
end
return if @user_team.update_attribute(:role, @role)
raise ClientApi::CustomUserTeamError, @user_team.errors.full_messages
end
def team_users_data
team_users = UserTeam.includes(:user)
.references(:user)
.where(team: @team)
.distinct
{ team_users: team_users }
end
2017-08-31 21:56:55 +08:00
def teams_data
{
teams: @user.teams_data,
flash_message: I18n.t('client_api.user_teams.leave_flash',
team: @team.name)
2017-08-31 21:56:55 +08:00
}
end
2017-09-01 23:10:43 +08:00
2017-08-31 21:56:55 +08:00
private
def reset_user_current_team(user_team)
ids = user_team.user.teams_ids
ids -= [user_team.team.id]
user_team.user.current_team_id = ids.first
user_team.user.save
end
def user_cant_leave?
2017-09-14 19:11:19 +08:00
@user.teams.include?(@team) &&
2017-09-01 23:10:43 +08:00
@user_team.admin? &&
@team.user_teams.where(role: 2).count <= 1
2017-08-31 21:56:55 +08:00
end
def generate_new_notification
user = @user_team.user
generate_notification(user,
user,
@user_team.team,
false,
false)
end
def validate_params(args)
2017-09-14 19:11:19 +08:00
keys = %i(team_id user_team_id user)
raise ClientApi::CustomUserTeamError unless keys.all? { |s| args.key? s }
raise ClientApi::CustomUserTeamError if args.values.any? &:nil?
2017-09-01 23:10:43 +08:00
team_id = args.fetch(:team_id)
user_team_id = args.fetch(:user_team_id)
user = args.fetch(:user)
{ user: user, user_team_id: user_team_id, team_id: team_id }
2017-08-31 21:56:55 +08:00
end
end
CustomUserTeamError = Class.new(StandardError)
end