2018-07-18 12:03:33 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-06-13 05:32:21 -04:00
|
|
|
module Users
|
|
|
|
class UpdateService < BaseService
|
2017-08-25 19:15:43 -04:00
|
|
|
include NewUserNotifier
|
|
|
|
|
2017-09-27 05:48:33 -04:00
|
|
|
def initialize(current_user, params = {})
|
2017-09-20 06:00:33 -04:00
|
|
|
@current_user = current_user
|
2017-09-27 06:08:10 -04:00
|
|
|
@user = params.delete(:user)
|
2018-07-13 11:52:31 -04:00
|
|
|
@status_params = params.delete(:status)
|
2017-06-13 05:32:21 -04:00
|
|
|
@params = params.dup
|
|
|
|
end
|
|
|
|
|
2017-06-23 05:34:07 -04:00
|
|
|
def execute(validate: true, &block)
|
2017-06-23 11:11:31 -04:00
|
|
|
yield(@user) if block_given?
|
|
|
|
|
2017-09-20 06:31:35 -04:00
|
|
|
user_exists = @user.persisted?
|
|
|
|
|
2018-12-14 17:58:57 -05:00
|
|
|
assign_attributes
|
2017-06-13 05:32:21 -04:00
|
|
|
|
2018-07-13 11:52:31 -04:00
|
|
|
if @user.save(validate: validate) && update_status
|
2017-09-20 06:31:35 -04:00
|
|
|
notify_success(user_exists)
|
2017-06-13 05:32:21 -04:00
|
|
|
else
|
2018-07-13 11:52:31 -04:00
|
|
|
messages = @user.errors.full_messages + Array(@user.status&.errors&.full_messages)
|
|
|
|
error(messages.uniq.join('. '))
|
2017-06-13 05:32:21 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-06-22 06:10:28 -04:00
|
|
|
def execute!(*args, &block)
|
2017-06-22 05:27:37 -04:00
|
|
|
result = execute(*args, &block)
|
2017-06-14 05:35:58 -04:00
|
|
|
|
2017-06-23 05:34:07 -04:00
|
|
|
raise ActiveRecord::RecordInvalid.new(@user) unless result[:status] == :success
|
2017-06-22 06:10:28 -04:00
|
|
|
|
|
|
|
true
|
2017-06-14 05:35:58 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2018-07-13 11:52:31 -04:00
|
|
|
def update_status
|
|
|
|
return true unless @status_params
|
|
|
|
|
|
|
|
Users::SetStatusService.new(current_user, @status_params.merge(user: @user)).execute
|
|
|
|
end
|
|
|
|
|
2017-09-20 06:31:35 -04:00
|
|
|
def notify_success(user_exists)
|
|
|
|
notify_new_user(@user, nil) unless user_exists
|
2017-09-20 05:00:06 -04:00
|
|
|
|
|
|
|
success
|
|
|
|
end
|
|
|
|
|
2018-12-14 17:58:57 -05:00
|
|
|
def assign_attributes
|
|
|
|
if (metadata = @user.user_synced_attributes_metadata)
|
|
|
|
read_only = metadata.read_only_attributes
|
|
|
|
|
|
|
|
params.reject! { |key, _| read_only.include?(key.to_sym) }
|
2017-08-29 04:57:41 -04:00
|
|
|
end
|
|
|
|
|
2017-06-14 05:35:58 -04:00
|
|
|
@user.assign_attributes(params) if params.any?
|
|
|
|
end
|
2017-06-13 05:32:21 -04:00
|
|
|
end
|
|
|
|
end
|