Module: DashCreator::ChartHelper

Includes:
FilterHelper
Defined in:
app/helpers/dash_creator/chart_helper.rb

Instance Method Summary collapse

Methods included from FilterHelper

#encode_filter_data, #filter_boolean, #filter_data, #filter_data_count_from_redis, #filter_datetime, #filter_has, #filter_model, #filter_numeric, #filter_ref, #filter_text, #get_csv, #prepare_data, #recursive_filter_attribute, #true_string?

Instance Method Details

#boolean_chart_processing(data) ⇒ Object



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
# File 'app/helpers/dash_creator/chart_helper.rb', line 503

def boolean_chart_processing(data)
  x_data = data['x_data']
  y_data = data['y_data']

  attribute = x_data['attribute']

  sub_attribute = x_data['sub_attribute']
  unless sub_attribute.nil?
    return sub_has_boolean_chart_processing(data) if x_data['sub_attribute_from'] == 'has'
    return sub_ref_boolean_chart_processing(data)
  end

  datasets = []
  0.upto(y_data.length-1).each {datasets.push([])}
  labels = x_data['labels-corres'].blank? ? x_data['labels'] : x_data['labels-corres']

  x_data['labels'].each do |l|
    0.upto(y_data.length-1).each do |i|
      data = y_data[i].where("#{attribute}": true_string?(l))

      datasets[i].push(data.count)
    end
  end

  {labels: labels, datasets: datasets}
end

#chart_processed_data_from_redis(chart_data) ⇒ Object



780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
# File 'app/helpers/dash_creator/chart_helper.rb', line 780

def chart_processed_data_from_redis(chart_data)
  redis_data = nil
  style = chart_data.delete('style')
  redis_chart_data = encode_chart_data(chart_data)

  unless chart_data['refresh'] == 'true' || DashCreator.redis_store_variable.nil?
    redis_data = DashCreator.redis_store_variable.get(redis_chart_data)
  end

  unless redis_data.nil?
    processed_data = JSON.parse(redis_data)
  else
    chart_data_with_records = prepare_data(chart_data)
    processed_data = chart_processing(chart_data_with_records).deep_stringify_keys
    processed_data['last_updated'] = DateTime.now.strftime('%d/%m/%Y - %T')

    # Add chart data to redis
    DashCreator.redis_store_variable.set(redis_chart_data, processed_data.to_json) unless DashCreator.redis_store_variable.nil?
  end

  processed_data['style'] = style
  processed_data['style'] = processed_data['style'].to_unsafe_h unless processed_data['style'].is_a?(Hash)

  processed_data
end

#chart_processing(data) ⇒ Object

Data processing for charts Handle differently regarding x_data type



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'app/helpers/dash_creator/chart_helper.rb', line 210

def chart_processing(data)
  ActiveRecord::Base.connection.execute("SET temp_buffers = '4GB';")
  case data['x_data']['type']
    when 'datetime'
      hash = date_chart_processing(data)

    when 'numeric'
      hash = numeric_chart_processing(data)

    when 'boolean'
      hash = boolean_chart_processing(data)

    when 'text'
      hash = text_chart_processing(data)

    when 'has'
      hash = has_model_chart_processing(data)

    when 'ref'
      hash = ref_model_chart_processing(data)

    else
      hash = {}
  end
  ActiveRecord::Base.connection.execute("SET temp_buffers = '8MB';")
  hash = hash.merge({
                        datasets_labels: data['datasets_labels'],
                        types: data['types']
                    })
  hash
end

#count_hash(array) ⇒ Object



775
776
777
# File 'app/helpers/dash_creator/chart_helper.rb', line 775

def count_hash(array)
  array.group_by(&:itself).map { |k,v| [k, v.count] }.to_h
end

#count_values_in_common(model_ids, filtered_model_ids) ⇒ Object



764
765
766
767
768
769
770
771
772
773
# File 'app/helpers/dash_creator/chart_helper.rb', line 764

def count_values_in_common(model_ids, filtered_model_ids)
  values_in_common = (model_ids & filtered_model_ids)

  count_hash = count_hash(filtered_model_ids)

  count = 0
  values_in_common.each { |v| count += count_hash[v] }

  count
end

#create_plot_error_message(id, type, error_key) ⇒ Object

Returns plot failing error message



202
203
204
205
# File 'app/helpers/dash_creator/chart_helper.rb', line 202

def create_plot_error_message(id, type, error_key)
  str = error_key + " for chart-#{type}-#{id}"
  str
end

#create_update_button(id, type, text) ⇒ Object



15
16
17
# File 'app/helpers/dash_creator/chart_helper.rb', line 15

def create_update_button(id, type, text)
  button_tag text, id: "btn-#{type}-#{id}"
end

#date_chart_processing(data) ⇒ Object

Process chart data for a x timeline



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'app/helpers/dash_creator/chart_helper.rb', line 299

def date_chart_processing(data)
  date_info = data['x_data']
  y_data = data['y_data']

  sub_attribute = date_info['sub_attribute']
  unless sub_attribute.nil?
    return sub_has_date_chart_processing(data) if date_info['sub_attribute_from'] == 'has'
    return sub_ref_date_chart_processing(data)
  end

  # Gather all info
  attribute = date_info['attribute']
  format = date_info.key?('format') ? date_info['format'] : '%d.%m.%Y'
  end_date = get_start_and_end_dates(date_info)[1]
  labels = get_date_labels(date_info)

  datasets = []
  0.upto(y_data.length-1).each {datasets.push([])}
  0.upto(labels.length-1).each do |i|
    date = labels[i]
    next_date = i == (labels.length - 1) ? end_date : labels[i+1]
    0.upto(y_data.length-1).each do |k|
      count = y_data[k].where("#{attribute}": date..next_date).count
      datasets[k].push(count)
    end
  end

  labels = labels.map{ |d| d.strftime(format) }

  {labels: labels, datasets: datasets}
end

#date_label_group_size(date_info) ⇒ Object

Returns the date group size regarding date_info



723
724
725
726
727
728
729
730
731
732
# File 'app/helpers/dash_creator/chart_helper.rb', line 723

def date_label_group_size(date_info)
  case date_info['period']
    when 'day'
      1
    when 'week'
      7
    else
      30
  end
end

#encode_chart_data(chart_data) ⇒ Object



806
807
808
809
810
811
812
813
814
815
816
# File 'app/helpers/dash_creator/chart_helper.rb', line 806

def encode_chart_data(chart_data)
  # Prepare data to encode
  encoded_chart_data = chart_data.clone
  encoded_chart_data = encoded_chart_data.to_unsafe_h unless encoded_chart_data.is_a?(Hash)
  encoded_chart_data.delete('controller')
  encoded_chart_data.delete('action')
  encoded_chart_data.delete('refresh')

  # Encode
  hash_hash(encoded_chart_data)
end

#get_date_labels(date_info) ⇒ Object



734
735
736
737
738
739
740
741
742
743
744
745
746
747
# File 'app/helpers/dash_creator/chart_helper.rb', line 734

def get_date_labels(date_info)
  limit_dates = get_start_and_end_dates(date_info)
  start_date = limit_dates[0]
  end_date = limit_dates[1]
  period_length = (end_date - start_date).to_i
  group_size = date_label_group_size(date_info)

  labels = []
  (0..(period_length-1)).step(group_size).each do |i|
    date = (start_date + i.days)
    labels.push(date)
  end
  labels
end

#get_or_pluck_labels(x_data, y_data) ⇒ Object



749
750
751
752
753
754
755
756
757
758
759
760
761
762
# File 'app/helpers/dash_creator/chart_helper.rb', line 749

def get_or_pluck_labels(x_data, y_data)
  case x_data['label_type']
    when 'text-auto'
      sub_attribute = x_data['sub_attribute']
      pluck_from = sub_attribute.nil? ? y_data.first : x_data['attribute'][0..-4].classify.safe_constantize
      to_pluck = sub_attribute.nil? ? x_data['attribute'] : sub_attribute

      labels = pluck_from.pluck(:"#{to_pluck}").uniq

    when 'text'
      labels = x_data['labels']
  end
  labels
end

#get_start_and_end_dates(date_info) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'app/helpers/dash_creator/chart_helper.rb', line 242

def get_start_and_end_dates(date_info)
  date_range_type = date_info['date_range_type']

  case date_range_type
    when 'Today'
      start_date = DateTime.now.beginning_of_day
      end_date = DateTime.now.beginning_of_day + 1.days

    when 'Yesterday'
      start_date = DateTime.now.beginning_of_day - 1.days
      end_date = DateTime.now.beginning_of_day

    when 'Last 7 Days'
      start_date = DateTime.now.beginning_of_day - 6.days
      end_date = DateTime.now.beginning_of_day + 1.days

    when 'This Week'
      start_date = DateTime.now.beginning_of_week
      end_date = DateTime.now.beginning_of_week + 7.days

    when 'Last Week'
      start_date = DateTime.now.beginning_of_week - 7.days
      end_date = DateTime.now.beginning_of_week

    when 'Last 30 Days'
      start_date = DateTime.now.beginning_of_day - 29.days
      end_date = DateTime.now.beginning_of_day + 1.days

    when 'This Month'
      start_date = DateTime.now.beginning_of_month
      end_date = DateTime.now.beginning_of_month + 30.days

    when 'Last Month'
      start_date = DateTime.now.beginning_of_month - 30.days
      end_date = DateTime.now.beginning_of_month

    when 'Last 365 Days'
      start_date = DateTime.now.beginning_of_day - 364.days
      end_date = DateTime.now.beginning_of_day + 1.days

    when 'This Year'
      start_date = DateTime.now.beginning_of_year
      end_date = DateTime.now.beginning_of_year + 365.days

    when 'Last Year'
      start_date = DateTime.now.beginning_of_year - 365.days
      end_date = DateTime.now.beginning_of_year

    else
      start_date = DateTime.strptime(date_info['start'], '%b %d, %Y').beginning_of_day
      end_date = DateTime.strptime(date_info['end'], '%b %d, %Y').beginning_of_day + 1.days
  end

  [start_date, end_date]
end

#has_model_chart_processing(data) ⇒ Object

Has is necessarily a count : if a sub-attribute is given, then label_type becomes the one of the sub attribute and cannot be has



656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
# File 'app/helpers/dash_creator/chart_helper.rb', line 656

def has_model_chart_processing(data)
  x_data = data['x_data']
  y_data = data['y_data']

  has_models = x_data['attribute'].pluralize
  model_string = y_data.first.first.class.name.underscore
  # attribute_model = x_data['attribute'].classify.safe_constantize

  datasets = []
  # model_ids = []
  0.upto(y_data.length-1).each do |i|
    datasets.push([])
    # model_ids.push(y_data[i].pluck(:id).uniq)
  end
  # filtered_model_ids = attribute_model.pluck("#{model_string}_id")
  # count_hash = count_hash(filtered_model_ids)

  labels = x_data['labels']
  labels.each do |l|
    0.upto(y_data.length-1).each do |i|
      split = l.split('-')
      low = l[-1] == '+' ? l[0..-2] : split[0]
      high = split.length == 2 ? split[1] : low

      if l[-1] == '+'
        data = y_data[i].joins("LEFT JOIN #{has_models} ON #{has_models}.#{model_string}_id = #{model_string.pluralize}.id")
                   .group("#{model_string.pluralize}.id")
                   .having("count(#{has_models}.id) >= ?", low)
        # count = count_hash.select{ |k, v| v >= low<to_i }.count
      else
        data = y_data[i].joins("LEFT JOIN #{has_models} ON #{has_models}.#{model_string}_id = #{model_string.pluralize}.id")
                   .group("#{model_string.pluralize}.id")
                   .having("count(#{has_models}.id) BETWEEN ? AND ?", low, high)
        # count = count_hash.select{ |k, v| v >= low.to_i && v <= high.to_i }.count
      end

      # datasets[i].push(count)
      sum = 0
      data.count.each { |key, count| sum += count }
      datasets[i].push(sum)
    end
  end

  {labels: labels, datasets: datasets}
end

#hash_hash(h) ⇒ Object

This helper function is used in create_chart.js.erb to hash param hash to store it in Redis



819
820
821
822
823
# File 'app/helpers/dash_creator/chart_helper.rb', line 819

def hash_hash(h)
  require 'digest/sha1'
  str = recursive_flatten(h).sort.join
  Digest::SHA1.hexdigest(str)
end

#numeric_chart_processing(data) ⇒ Object



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'app/helpers/dash_creator/chart_helper.rb', line 406

def numeric_chart_processing(data)
  x_data = data['x_data']
  y_data = data['y_data']

  attribute = x_data['attribute']

  sub_attribute = x_data['sub_attribute']
  unless sub_attribute.nil?
    return sub_has_numeric_chart_processing(data) if x_data['sub_attribute_from'] == 'has'
    return sub_ref_numeric_chart_processing(data)
  end

  datasets = []
  0.upto(y_data.length-1).each {datasets.push([])}
  labels = x_data['labels-corres'].blank? ? x_data['labels'] : x_data['labels-corres']

  x_data['labels'].each do |l|
    0.upto(y_data.length-1).each do |i|
      split = l.split('-')
      low = l[-1] == '+' ? l[0..-2] : split[0]
      high = split.length == 2 ? split[1] : low
      data = y_data[i].where("#{attribute}" + ' >= ?', low)
      data = data.where("#{attribute}" + ' <= ?', high) unless l[-1] == '+'

      datasets[i].push(data.count)
    end
  end

  {labels: labels, datasets: datasets}
end

#plot_bar_chart(id, data, options = {}) ⇒ Object



167
168
169
# File 'app/helpers/dash_creator/chart_helper.rb', line 167

def plot_bar_chart(id, data, options = {})
  plot_type_1_chart(id, 'bar', data, options)
end

#plot_chart(id, type, plot_data, options = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
# File 'app/helpers/dash_creator/chart_helper.rb', line 3

def plot_chart(id, type, plot_data, options = {})
  default_options = {
      tooltips: {
          mode: 'nearest',
          intersect: false
      },
      responsive: true
  }
  options = options.merge(default_options)
  render 'dash_creator/chart/plot_chart', {id: id, type: type, data: plot_data, options: options}
end

#plot_doughnut_chart(id, data, options = {}) ⇒ Object



181
182
183
# File 'app/helpers/dash_creator/chart_helper.rb', line 181

def plot_doughnut_chart(id, data, options = {})
  plot_type_2_chart(id, 'doughnut', data, options)
end

#plot_line_chart(id, data, options = {}) ⇒ Object

 Type 1 charts & mixed bar/line



163
164
165
# File 'app/helpers/dash_creator/chart_helper.rb', line 163

def plot_line_chart(id, data, options = {})
  plot_type_1_chart(id, 'line', data, options)
end

#plot_mixed_chart(id, data, options = {}) ⇒ Object



171
172
173
# File 'app/helpers/dash_creator/chart_helper.rb', line 171

def plot_mixed_chart(id, data, options = {})
  plot_type_1_chart(id, 'mixed', data, options)
end

#plot_pie_chart(id, data, options = {}) ⇒ Object

 Type 2 charts



177
178
179
# File 'app/helpers/dash_creator/chart_helper.rb', line 177

def plot_pie_chart(id, data, options = {})
  plot_type_2_chart(id, 'pie', data, options)
end

#plot_polar_chart(id, data, options = {}) ⇒ Object



185
186
187
# File 'app/helpers/dash_creator/chart_helper.rb', line 185

def plot_polar_chart(id, data, options = {})
  plot_type_2_chart(id, 'polarArea', data, options)
end

#plot_radar_chart(id, data, options = {}) ⇒ Object



189
190
191
# File 'app/helpers/dash_creator/chart_helper.rb', line 189

def plot_radar_chart(id, data, options = {})
  plot_type_2_chart(id, 'radar', data, options)
end

#plot_type_1_chart(id, type, data, options = {}) ⇒ Object

Data formatting (hash) :labels is array of labels :datasets_labels is array of datasets labels :datasets is array of arrays containing the datasets data for a mixed chart, :types is array of datasets types :style contains chart styling



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'app/helpers/dash_creator/chart_helper.rb', line 29

def plot_type_1_chart(id, type, data, options = {})
  begin
    raise ArgumentError, 'datasets_key_missing' unless data.key?('datasets')
    raise ArgumentError, 'labels_key_missing' unless data.key?('labels')
    raise ArgumentError, 'types_key_missing' if (type == 'mixed' && !data.key?('types'))

    plot_data = type_1_data_to_plot(data)
  rescue Exception => e
    return render html: create_plot_error_message(id, type, e.message).to_s
  end
  plot_data_with_options = type_1_add_style(plot_data, data['style'])
  plot_data_with_options[:options] = plot_data_with_options[:options].merge(options)

  plot_chart(id, type, plot_data_with_options[:plot_data], plot_data_with_options[:options])
end

#plot_type_2_chart(id, type, data, options = {}) ⇒ Object

Data formatting (hash) :labels is array of labels :datasets is array of arrays containing the datasets data :style contains chart styling



116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'app/helpers/dash_creator/chart_helper.rb', line 116

def plot_type_2_chart(id, type, data, options = {})
  begin
    raise ArgumentError, 'datasets_key_missing' unless data.key?('datasets')
    raise ArgumentError, 'labels_key_missing' unless data.key?('labels')

    plot_data = type_2_data_to_plot(data)
  rescue Exception => e
    return render html: create_plot_error_message(id, type, e.message).to_s
  end
  plot_data_with_options = type_2_add_style(plot_data, data['style'])
  plot_data_with_options = plot_data_with_options.merge(options)

  plot_chart(id, type, plot_data_with_options[:plot_data], plot_data_with_options[:options])
end

#recursive_flatten(h) ⇒ Object



825
826
827
# File 'app/helpers/dash_creator/chart_helper.rb', line 825

def recursive_flatten(h)
  h.flatten(-1).map{|el| el.is_a?(Hash) ? recursive_flatten(el) : el}.flatten
end

#ref_model_chart_processing(data) ⇒ Object



702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
# File 'app/helpers/dash_creator/chart_helper.rb', line 702

def ref_model_chart_processing(data)
  x_data = data['x_data']
  y_data = data['y_data']

  ref_model = x_data['attribute']

  datasets = []
  0.upto(y_data.length-1).each {datasets.push([])}

  labels = ['Having', 'Not having']
  0.upto(y_data.length-1).each do |i|
    tot_count = y_data[i].count
    having_count = y_data[i].where.not("#{ref_model}": nil).count
    datasets[0].push(having_count).push(tot_count - having_count)
  end

  {labels: labels, datasets: datasets}
end

#set_transparency(colors, transparencies) ⇒ Object

From rgb to rgba with given colors and transparencies



195
196
197
198
199
# File 'app/helpers/dash_creator/chart_helper.rb', line 195

def set_transparency(colors, transparencies)
  colors_with_transparency = []
  0.upto(colors.length - 1).each { |i| colors_with_transparency.push('rgba' + colors[i][3..-2] + ', ' + (1-(transparencies[i].to_f/100)).to_s + ')') }
  colors_with_transparency
end

#sub_has_boolean_chart_processing(data) ⇒ Object



530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
# File 'app/helpers/dash_creator/chart_helper.rb', line 530

def sub_has_boolean_chart_processing(data)
  x_data = data['x_data']
  y_data = data['y_data']

  model_string = y_data.first.first.class.name.underscore
  attribute_model = x_data['attribute'].classify.safe_constantize
  sub_attribute = x_data['sub_attribute']

  datasets = []
  model_ids = []
  0.upto(y_data.length-1).each do |i|
    datasets.push([])
    model_ids.push(y_data[i].pluck(:id).uniq)
  end

  labels = x_data['labels-corres'].blank? ? x_data['labels'] : x_data['labels-corres']

  x_data['labels'].each do |l|
    0.upto(y_data.length-1).each do |i|
      filtered_model_ids = attribute_model.where("#{sub_attribute}": true_string?(l)).pluck("#{model_string}_id")

      datasets[i].push(count_values_in_common(model_ids[i], filtered_model_ids))
    end
  end

  {labels: labels, datasets: datasets}
end

#sub_has_date_chart_processing(data) ⇒ Object



331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# File 'app/helpers/dash_creator/chart_helper.rb', line 331

def sub_has_date_chart_processing(data)
  date_info = data['x_data']
  y_data = data['y_data']

  # Gather all info
  # has_models = date_info['attribute'].pluralize
  model_string = y_data.first.first.class.name.underscore
  attribute_model = date_info['attribute'].classify.safe_constantize
  sub_attribute = date_info['sub_attribute']

  format = date_info.key?('format') ? date_info['format'] : '%d.%m.%Y'
  end_date = get_start_and_end_dates(date_info)[1]
  labels = get_date_labels(date_info)

  datasets = []
  model_ids = []
  0.upto(y_data.length-1).each do |i|
    datasets.push([])
    model_ids.push(y_data[i].pluck(:id).uniq)
  end

  0.upto(labels.length-1).each do |i|
    date = labels[i]
    next_date = i == (labels.length - 1) ? end_date : labels[i+1]
    0.upto(y_data.length-1).each do |k|
      # data = y_data[k].joins("LEFT JOIN #{has_models} ON #{has_models}.#{model_string}_id = #{model_string.pluralize}.id")
      #            .group("#{model_string.pluralize}.id")
      #            .having("#{has_models}.#{sub_attribute}": date..next_date)

      # total_count = 0
      # data.count.each { |key, count| total_count += count }
      # datasets[k].push(total_count)

      filtered_model_ids = attribute_model.where("#{sub_attribute}": date..next_date).pluck("#{model_string}_id")

      datasets[i].push(count_values_in_common(model_ids[i], filtered_model_ids))
    end
  end

  labels = labels.map { |d| d.strftime(format) }

  {labels: labels, datasets: datasets}
end

#sub_has_numeric_chart_processing(data) ⇒ Object



437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'app/helpers/dash_creator/chart_helper.rb', line 437

def sub_has_numeric_chart_processing(data)
  x_data = data['x_data']
  y_data = data['y_data']

  model_string = y_data.first.first.class.name.underscore
  attribute_model = x_data['attribute'].classify.safe_constantize
  sub_attribute = x_data['sub_attribute']

  datasets = []
  model_ids = []
  0.upto(y_data.length-1).each do |i|
      datasets.push([])
      model_ids.push(y_data[i].pluck(:id).uniq)
  end

  labels = x_data['labels-corres'].blank? ? x_data['labels'] : x_data['labels-corres']

  x_data['labels'].each do |l|
    0.upto(y_data.length-1).each do |i|
      split = l.split('-')
      low = l[-1] == '+' ? l[0..-2] : split[0]
      high = split.length == 2 ? split[1] : low

      if l[-1] == '+'
        filtered_model_ids = attribute_model.where("#{sub_attribute} >= ?", low).pluck("#{model_string}_id")
      else
        filtered_model_ids = attribute_model.where("#{sub_attribute}": low..high).pluck("#{model_string}_id")
      end

      datasets[i].push(count_values_in_common(model_ids[i], filtered_model_ids))
    end
  end

  {labels: labels, datasets: datasets}
end

#sub_has_text_chart_processing(data) ⇒ Object



606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# File 'app/helpers/dash_creator/chart_helper.rb', line 606

def sub_has_text_chart_processing(data)
  x_data = data['x_data']
  y_data = data['y_data']

  model_string = y_data.first.first.class.name.underscore
  attribute_model = x_data['attribute'].classify.safe_constantize
  sub_attribute = x_data['sub_attribute']

  datasets = []
  model_ids = []
  0.upto(y_data.length-1).each do |i|
    datasets.push([])
    model_ids.push(y_data[i].pluck(:id).uniq)
  end

  labels = get_or_pluck_labels(x_data, y_data)

  labels.each do |l|
    0.upto(y_data.length-1).each do |i|
      filtered_model_ids = attribute_model.where("#{sub_attribute}": l).pluck("#{model_string}_id")

      datasets[i].push(count_values_in_common(model_ids[i], filtered_model_ids))
    end
  end

  {labels: labels, datasets: datasets}
end

#sub_ref_boolean_chart_processing(data) ⇒ Object



558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
# File 'app/helpers/dash_creator/chart_helper.rb', line 558

def sub_ref_boolean_chart_processing(data)
  x_data = data['x_data']
  y_data = data['y_data']

  ref_model = x_data['attribute'][0..-4]
  sub_attribute = x_data['sub_attribute']

  datasets = []
  0.upto(y_data.length-1).each {datasets.push([])}
  labels = x_data['labels-corres'].blank? ? x_data['labels'] : x_data['labels-corres']

  x_data['labels'].each do |l|
    0.upto(y_data.length-1).each do |i|
      data = y_data[i].joins(:"#{ref_model}").where("#{ref_model.pluralize}.#{sub_attribute}": true_string?(l))

      datasets[i].push(data.count)
    end
  end

  {labels: labels, datasets: datasets}
end

#sub_ref_date_chart_processing(data) ⇒ Object



375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# File 'app/helpers/dash_creator/chart_helper.rb', line 375

def sub_ref_date_chart_processing(data)
  date_info = data['x_data']
  y_data = data['y_data']

  # Gather all info
  ref_model = date_info['attribute'][0..-4]
  sub_attribute = date_info['sub_attribute']

  format = date_info.key?('format') ? date_info['format'] : '%d.%m.%Y'
  end_date = get_start_and_end_dates(date_info)[1]
  labels = get_date_labels(date_info)

  datasets = []
  0.upto(y_data.length-1).each {datasets.push([])}
  0.upto(labels.length-1).each do |i|
    date = labels[i]
    next_date = i == (labels.length - 1) ? end_date : labels[i+1]
    0.upto(y_data.length-1).each do |k|
      count = y_data[k].joins(:"#{ref_model}")
                  .where("#{ref_model.pluralize}.#{sub_attribute}": date..next_date)
                  .count

      datasets[k].push(count)
    end
  end

  labels = labels.map { |d| d.strftime(format) }

  {labels: labels, datasets: datasets}
end

#sub_ref_numeric_chart_processing(data) ⇒ Object



473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# File 'app/helpers/dash_creator/chart_helper.rb', line 473

def sub_ref_numeric_chart_processing(data)
  x_data = data['x_data']
  y_data = data['y_data']

  ref_model = x_data['attribute'][0..-4]
  sub_attribute = x_data['sub_attribute']

  datasets = []
  0.upto(y_data.length-1).each {datasets.push([])}
  labels = x_data['labels-corres'].blank? ? x_data['labels'] : x_data['labels-corres']

  x_data['labels'].each do |l|
    0.upto(y_data.length-1).each do |i|
      split = l.split('-')
      low = l[-1] == '+' ? l[0..-2] : split[0]
      high = split.length == 2 ? split[1] : low

      if l[-1] == '+'
        data = y_data[i].joins(:"#{ref_model}").where("#{ref_model.pluralize}.#{sub_attribute} >= ?", low)
      else
        data = y_data[i].joins(:"#{ref_model}").where("#{ref_model.pluralize}.#{sub_attribute}": low..high)
      end

      datasets[i].push(data.count)
    end
  end

  {labels: labels, datasets: datasets}
end

#sub_ref_text_chart_processing(data) ⇒ Object



634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
# File 'app/helpers/dash_creator/chart_helper.rb', line 634

def sub_ref_text_chart_processing(data)
  x_data = data['x_data']
  y_data = data['y_data']

  ref_model = x_data['attribute'][0..-4]
  sub_attribute = x_data['sub_attribute']

  datasets = []
  0.upto(y_data.length-1).each {datasets.push([])}

  labels = get_or_pluck_labels(x_data, y_data)

  labels.each do |l|
    0.upto(y_data.length-1).each do |i|
      datasets[i].push(y_data[i].joins(:"#{ref_model}").where("#{ref_model.pluralize}.#{sub_attribute} = '#{l}'").count)
    end
  end

  {labels: labels, datasets: datasets}
end

#text_chart_processing(data) ⇒ Object



580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
# File 'app/helpers/dash_creator/chart_helper.rb', line 580

def text_chart_processing(data)
  x_data = data['x_data']
  y_data = data['y_data']

  sub_attribute = x_data['sub_attribute']
  unless sub_attribute.nil?
    return sub_has_text_chart_processing(data) if x_data['sub_attribute_from'] == 'has'
    return sub_ref_text_chart_processing(data)
  end

  attribute = x_data['attribute']

  datasets = []
  0.upto(y_data.length-1).each {datasets.push([])}

  labels = get_or_pluck_labels(x_data, y_data)

  labels.each do |l|
    0.upto(y_data.length-1).each do |i|
      datasets[i].push(y_data[i].where("#{attribute}": l).count)
    end
  end

  {labels: labels, datasets: datasets}
end

#type_1_add_style(plot_data, style_options) ⇒ Object



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
99
100
101
102
103
104
105
106
107
108
# File 'app/helpers/dash_creator/chart_helper.rb', line 59

def type_1_add_style(plot_data, style_options)
  colors = style_options['colors'].nil? ? nil : set_transparency(style_options['colors'], style_options['transparencies'])

  0.upto(plot_data[:datasets].length-1) do |i|
    set = plot_data[:datasets][i]
    set[:backgroundColor] = colors[i] unless colors.nil? || colors[i].nil?
    set[:borderColor] = style_options['colors'][i] unless style_options['colors'].nil? || style_options['colors'][i].nil?
  end

  # Initialize options
  options = {}
  scales = options['scales'] = {}
  scales['xAxes'] = [{}]
  scales['yAxes'] = [{}]
  scales['xAxes'][0]['gridLines'] = {}
  scales['xAxes'][0]['ticks'] = {}
  scales['yAxes'][0]['gridLines'] = {}
  scales['yAxes'][0]['ticks'] = {}

  # Grid options
  grid_options = style_options['grid']
  scales['xAxes'][0]['gridLines']['display'] = false if grid_options['x'] == 'false'
  scales['yAxes'][0]['gridLines']['display'] = false if grid_options['y'] == 'false'

  # Y Axis options
  y_axis_options = style_options['y-axis']
  scales['yAxes'][0]['ticks']['min'] = y_axis_options['min'].to_i if y_axis_options['min'] != ''
  scales['yAxes'][0]['ticks']['max'] = y_axis_options['max'].to_i if y_axis_options['max'] != ''
  scales['yAxes'][0]['ticks']['stepSize'] = y_axis_options['step'].to_i if y_axis_options['step'] != ''

  # Stacked
  if style_options['stacked'] == 'true'
    scales['xAxes'][0]['stacked'] = true
    scales['yAxes'][0]['stacked'] = true
  end

  # Labeling step
  scales['xAxes'][0]['ticks']['callback'] = style_options['labeling-step'] if style_options['labeling-step'] != ''

  # Legend
  legend_options = style_options['legend']
  legend = options['legend'] = {}
  legend['display'] = false if legend_options['display'] == 'false'
  legend['position'] = legend_options['position']

  # Title
  options['title'] = {display: true, text: style_options['title']} if style_options['title'] != ''

  {plot_data: plot_data, options: options}
end

#type_1_data_to_plot(data) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'app/helpers/dash_creator/chart_helper.rb', line 45

def type_1_data_to_plot(data)
  datasets = []
  0.upto(data['datasets'].length-1) do |i|
    set = {data: data['datasets'][i]}
    unless data['labels'][i].nil?
      set[:label] = data['datasets_labels'][i] unless data['datasets_labels'].nil?
    end
    set[:type] = data['types'][i]
    datasets.push(set)
  end

  {labels: data['labels'], datasets: datasets}
end

#type_2_add_style(plot_data, style_options) ⇒ Object



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'app/helpers/dash_creator/chart_helper.rb', line 143

def type_2_add_style(plot_data, style_options)
  0.upto(plot_data[:datasets].length-1) do |i|
    set = plot_data[:datasets][i]
    set[:backgroundColor] = set_transparency(style_options['colors'], style_options['transparencies']) unless style_options['colors'].nil?
  end

  options = {}

  legend_options = style_options['legend']
  legend = options['legend'] = {}
  legend['display'] = false if legend_options['display'] == 'false'
  legend['position'] = legend_options['position']

  options['title'] = {display: true, text: style_options['title']} if style_options['title'] != ''

  {plot_data: plot_data, options: options}
end

#type_2_data_to_plot(data) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
# File 'app/helpers/dash_creator/chart_helper.rb', line 131

def type_2_data_to_plot(data)
  datasets = []
  0.upto(data['datasets'].length-1) do |i|
    set = {
        data: data['datasets'][i]
    }
    datasets.push(set)
  end

  {labels: data['labels'], datasets: datasets}
end

#update_chart_script(id, type, action_path, action_params = {}) ⇒ Object



19
20
21
# File 'app/helpers/dash_creator/chart_helper.rb', line 19

def update_chart_script(id, type, action_path, action_params = {})
  render 'dash_creator/chart/update_chart', {id: id, type: type, action_path: action_path, action_params: action_params}
end