aboutsummaryrefslogtreecommitdiffstats
path: root/app/controllers/companies_controller.rb
blob: 2c32ed3a5fdc62b253be2f238d26a3e61ce63e5b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class CompaniesController < ChouetteController
  include ApplicationHelper
  include PolicyChecker
  defaults :resource_class => Chouette::Company
  respond_to :html
  respond_to :xml
  respond_to :json
  respond_to :js, :only => :index

  belongs_to :line_referential

  def index
    index! do |format|
      format.html {
        if collection.out_of_bounds?
          redirect_to params.merge(:page => 1)
        end

        @companies = decorate_companies(@companies)
      }

      format.json {
        @companies = decorate_companies(@companies)
      }
    end
  end

  def new
    authorize resource_class
    super
  end

  def create
    authorize resource_class
    super
  end


  protected

  def collection
    scope = line_referential.companies
    @q = scope.search(params[:q])
    ids = @q.result(:distinct => true).pluck(:id)
    scope = scope.where(id: ids)
    if sort_column && sort_direction
      @companies ||= scope.order(sort_column + ' ' + sort_direction).paginate(:page => params[:page])
    else
      @companies ||= scope.order(:name).paginate(:page => params[:page])
    end
  end

  def resource
    super.decorate(context: { referential: line_referential })
  end

  def resource_url(company = nil)
    line_referential_company_path(line_referential, company || resource)
  end

  def collection_url
    line_referential_companies_path(line_referential)
  end

  alias_method :line_referential, :parent

  alias_method :current_referential, :line_referential
  helper_method :current_referential

  def begin_of_association_chain
    current_organisation
  end

  def company_params
    fields = [:objectid, :object_version, :name, :short_name, :organizational_unit, :operating_department_name, :code, :phone, :fax, :email, :registration_number, :url, :time_zone]
    fields += permitted_custom_fields_params(Chouette::Company.custom_fields(line_referential.workgroup))
    params.require(:company).permit( fields )
  end

  private

  def sort_column
    line_referential.companies.column_names.include?(params[:sort]) ? params[:sort] : 'name'
  end
  def sort_direction
    %w[asc desc].include?(params[:direction]) ?  params[:direction] : 'asc'
  end

  def decorate_companies(companies)
    CompanyDecorator.decorate(
      companies,
      context: {
        referential: line_referential
      }
    )
  end

end