Files
2020-03-06 08:35:12 -05:00

78 lines
2.3 KiB
Ruby

module Suppliers
class EmployeesController < Suppliers::ApplicationController
after_authentication only: [:show, :update, :destroy] do
@employee = current_supplier.get_employee params[:id]
render json: {}, status: 404 unless @employee.present?
end
# GET /employees
# GET /employees.json
def index
@employees = current_supplier.employees
@employees.each { |employee| employee.enrich_with_settings current_supplier.settings_for(employee) }
render json: @employees
end
def suppliers
@suppliers = current_employee.suppliers
render json: @suppliers, serializer: Suppliers::SupplierSerializer, is_collection: true
end
# GET /employees/1
# GET /employees/1.json
def show
render json: @employee
end
# POST /employees
# POST /employees.json
def create
valid = false
if existing_employee = Employee.find_by_email(employee_params[:email])
@employee = existing_employee
if valid = @employee.valid?
current_supplier.add_employee @employee
@employee.update_attributes employee_params
end
else
@employee = Employee.new(employee_params)
@employee.password = SecureRandom.hex(8)
if valid = @employee.save
current_supplier.add_employee @employee
@employee.update_attributes employee_params # needed for supplier specific settings
end
end
if valid
render json: @employee
else
render json: {errors: @employee.errors}, status: :unprocessable_entity
end
end
# PUT /employees/1
# PUT /employees/1.json
def update
#current_supplier.settings_for(@employee).update!(employee_params)
if @employee.update_attributes(employee_params)
render json: @employee
else
render json: {errors: @employee.errors}, status: :unprocessable_entity
end
end
# DELETE /employees/1
# DELETE /employees/1.json
def destroy
head :forbidden and return if @employee == current_employee # do not remove self at the moment
current_supplier.remove_employee @employee
head :no_content
end
private
def employee_params
params.require(:employee).permit(:name, :email, :active, :manager, :color)
end
end
end