aboutsummaryrefslogtreecommitdiffstats
path: root/app/controllers/calendars_controller.rb
blob: c33aa9373def27de20a6b999926d28481647f6f9 (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
class CalendarsController < BreadcrumbController
  include PolicyChecker
  defaults resource_class: Calendar
  before_action :ransack_contains_date, only: [:index]
  respond_to :html
  respond_to :js, only: :index

  private
  def calendar_params
    permitted_params = [:id, :name, :short_name, periods_attributes: [:id, :begin, :end, :_destroy], date_values_attributes: [:id, :value, :_destroy]]
    permitted_params << :shared if policy(Calendar).share?
    params.require(:calendar).permit(*permitted_params)
  end

  def sort_column
    Calendar.column_names.include?(params[:sort]) ? params[:sort] : 'short_name'
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ?  params[:direction] : 'asc'
  end

  protected
  def resource
    @calendar = Calendar.where('organisation_id = ? OR shared = true', current_organisation.id).find_by_id(params[:id])
  end

  def build_resource
    super.tap do |calendar|
      calendar.organisation = current_organisation
    end
  end

  def collection
    return @calendars if @calendars

    @q = Calendar.where('organisation_id = ? OR shared = true', current_organisation.id).search(params[:q])
    calendars = @q.result
    calendars = calendars.order(sort_column + ' ' + sort_direction) if sort_column && sort_direction
    @calendars = calendars.paginate(page: params[:page])
  end

  def ransack_contains_date
    # 3 parts to date object, in order to use in ransackable_scopes
    if params[:q] && !params[:q]['contains_date(1i)'].empty?
      date =[]
      ['contains_date(1i)', 'contains_date(2i)', 'contains_date(3i)'].each do |key|
        date << params[:q][key]
        params[:q].delete(key)
      end
      params[:q]['contains_date'] = Date.parse(date.join('-'))
    end
  end
end