2020-06-07 08:28:05 +00:00
|
|
|
class Api::V1::Accounts::AgentsController < Api::V1::Accounts::BaseController
|
2019-08-14 09:48:44 +00:00
|
|
|
before_action :fetch_agent, except: [:create, :index]
|
|
|
|
before_action :check_authorization
|
2020-03-07 06:48:16 +00:00
|
|
|
before_action :find_user, only: [:create]
|
|
|
|
before_action :create_user, only: [:create]
|
|
|
|
before_action :save_account_user, only: [:create]
|
2019-08-14 09:48:44 +00:00
|
|
|
|
|
|
|
def index
|
2020-02-02 17:04:16 +00:00
|
|
|
@agents = agents
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def destroy
|
2020-05-26 17:08:48 +00:00
|
|
|
@agent.current_account_user.destroy
|
2019-08-14 09:48:44 +00:00
|
|
|
head :ok
|
|
|
|
end
|
|
|
|
|
|
|
|
def update
|
2020-03-07 06:48:16 +00:00
|
|
|
@agent.update!(agent_params.except(:role))
|
2020-05-26 17:08:48 +00:00
|
|
|
@agent.current_account_user.update!(role: agent_params[:role]) if agent_params[:role]
|
2020-05-31 17:40:20 +00:00
|
|
|
render partial: 'api/v1/models/agent.json.jbuilder', locals: { resource: @agent }
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def create
|
2020-05-31 17:40:20 +00:00
|
|
|
render partial: 'api/v1/models/agent.json.jbuilder', locals: { resource: @user }
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def check_authorization
|
|
|
|
authorize(User)
|
|
|
|
end
|
|
|
|
|
|
|
|
def fetch_agent
|
|
|
|
@agent = agents.find(params[:id])
|
|
|
|
end
|
|
|
|
|
2020-03-07 06:48:16 +00:00
|
|
|
def find_user
|
|
|
|
@user = User.find_by(email: new_agent_params[:email])
|
|
|
|
end
|
|
|
|
|
|
|
|
def create_user
|
|
|
|
return if @user
|
|
|
|
|
|
|
|
@user = User.create!(new_agent_params.slice(:email, :name, :password, :password_confirmation))
|
|
|
|
end
|
|
|
|
|
|
|
|
def save_account_user
|
|
|
|
AccountUser.create!(
|
2020-06-07 08:28:05 +00:00
|
|
|
account_id: Current.account.id,
|
2020-03-07 06:48:16 +00:00
|
|
|
user_id: @user.id,
|
|
|
|
role: new_agent_params[:role],
|
|
|
|
inviter_id: current_user.id
|
|
|
|
)
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def agent_params
|
|
|
|
params.require(:agent).permit(:email, :name, :role)
|
|
|
|
end
|
|
|
|
|
|
|
|
def new_agent_params
|
|
|
|
time = Time.now.to_i
|
2019-10-14 08:54:58 +00:00
|
|
|
params.require(:agent).permit(:email, :name, :role)
|
2019-10-20 08:47:26 +00:00
|
|
|
.merge!(password: time, password_confirmation: time, inviter: current_user)
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def agents
|
2020-08-22 16:50:22 +00:00
|
|
|
@agents ||= Current.account.users.order_by_full_name
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
end
|