Chatwoot/app/builders/account_builder.rb

70 lines
1.5 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
class AccountBuilder
include CustomExceptions::Account
pattr_initialize [:account_name!, :email!]
def perform
2019-10-20 08:47:26 +00:00
validate_email
validate_user
ActiveRecord::Base.transaction do
@account = create_account
@user = create_and_link_user
end
2019-10-20 08:47:26 +00:00
rescue StandardError => e
@account&.destroy
puts e.inspect
raise e
end
private
def validate_email
address = ValidEmail2::Address.new(@email)
2019-10-20 08:47:26 +00:00
if address.valid? # && !address.disposable?
true
else
2019-10-20 08:47:26 +00:00
raise InvalidEmail.new(valid: address.valid?) # , disposable: address.disposable?})
end
end
def validate_user
if User.exists?(email: @email)
2019-10-20 08:47:26 +00:00
raise UserExists.new(email: @email)
else
true
end
end
def create_account
@account = Account.create!(name: @account_name)
end
def create_and_link_user
password = Time.now.to_i
@user = User.new(email: @email,
password: password,
password_confirmation: password,
name: email_to_name(@email))
if @user.save!
link_user_to_account(@user, @account)
@user
else
2019-10-20 08:47:26 +00:00
raise UserErrors.new(errors: @user.errors)
end
end
def link_user_to_account(user, account)
AccountUser.create!(
account_id: account.id,
user_id: user.id,
role: AccountUser.roles['administrator']
)
end
def email_to_name(email)
name = email[/[^@]+/]
2019-10-20 08:47:26 +00:00
name.split('.').map(&:capitalize).join(' ')
end
end