2019-10-16 06:52:30 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2019-08-14 09:48:44 +00:00
|
|
|
class AccountBuilder
|
|
|
|
include CustomExceptions::Account
|
2022-01-26 00:58:49 +00:00
|
|
|
pattr_initialize [:account_name!, :email!, :confirmed, :user, :user_full_name, :user_password, :super_admin]
|
2019-08-14 09:48:44 +00:00
|
|
|
|
|
|
|
def perform
|
2020-07-26 07:24:50 +00:00
|
|
|
if @user.nil?
|
|
|
|
validate_email
|
|
|
|
validate_user
|
|
|
|
end
|
2019-10-20 08:47:26 +00:00
|
|
|
ActiveRecord::Base.transaction do
|
|
|
|
@account = create_account
|
|
|
|
@user = create_and_link_user
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
2020-07-26 07:24:50 +00:00
|
|
|
[@user, @account]
|
2019-10-20 08:47:26 +00:00
|
|
|
rescue StandardError => e
|
|
|
|
puts e.inspect
|
|
|
|
raise e
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def validate_email
|
|
|
|
address = ValidEmail2::Address.new(@email)
|
2019-10-20 08:47:26 +00:00
|
|
|
if address.valid? # && !address.disposable?
|
2019-08-14 09:48:44 +00:00
|
|
|
true
|
|
|
|
else
|
2021-01-17 08:37:18 +00:00
|
|
|
raise InvalidEmail.new(valid: address.valid?)
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def validate_user
|
|
|
|
if User.exists?(email: @email)
|
2019-10-20 08:47:26 +00:00
|
|
|
raise UserExists.new(email: @email)
|
2019-08-14 09:48:44 +00:00
|
|
|
else
|
|
|
|
true
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def create_account
|
2020-11-24 13:04:31 +00:00
|
|
|
@account = Account.create!(name: @account_name, locale: I18n.locale)
|
2020-05-26 17:08:48 +00:00
|
|
|
Current.account = @account
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def create_and_link_user
|
2020-07-26 07:24:50 +00:00
|
|
|
if @user.present? || create_user
|
2020-03-07 06:48:16 +00:00
|
|
|
link_user_to_account(@user, @account)
|
2019-08-14 09:48:44 +00:00
|
|
|
@user
|
|
|
|
else
|
2019-10-20 08:47:26 +00:00
|
|
|
raise UserErrors.new(errors: @user.errors)
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-03-07 06:48:16 +00:00
|
|
|
def link_user_to_account(user, account)
|
|
|
|
AccountUser.create!(
|
|
|
|
account_id: account.id,
|
|
|
|
user_id: user.id,
|
|
|
|
role: AccountUser.roles['administrator']
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
2020-07-26 07:24:50 +00:00
|
|
|
def create_user
|
|
|
|
@user = User.new(email: @email,
|
2021-06-07 11:56:08 +00:00
|
|
|
password: user_password,
|
|
|
|
password_confirmation: user_password,
|
2020-12-21 08:35:19 +00:00
|
|
|
name: @user_full_name)
|
2022-01-26 00:58:49 +00:00
|
|
|
@user.type = 'SuperAdmin' if @super_admin
|
2020-07-26 07:24:50 +00:00
|
|
|
@user.confirm if @confirmed
|
|
|
|
@user.save!
|
|
|
|
end
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|