summaryrefslogtreecommitdiff
path: root/app/controllers/dashboard_controller.rb
blob: 4e9d5606d98c35e70da22916627e597b0a508bc5 (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
class DashboardController < ApplicationController
  def index
    # Raft allocation by crop type
    @raft_data = raft_data_series

    # Nutrient target table
    @latest_measurement = NutrientMeasurement.order(measured_on: :desc, created_at: :desc).first
    @target = TargetNutrientCalculator.call

    # Measurement history table
    @measurements = NutrientMeasurement.order(measured_on: :desc).limit(10)

    @npk_measurement_data = measurement_data_series(:nno3, :p, :k)
    @ammonium_measurement_data = measurement_data_series(:nnh4)
  end

  private

  def raft_data_series
    data_series = []

    counts = Raft.left_outer_joins(:crop)
               .group("crops.name", "crops.crop_type")
               .count

    counts.each do |(crop_name, crop_type), count|
      name = (crop_name || "unassigned").titleize
      type = (crop_type || "unassigned").titleize
      data = { type => count }
      data_series << { name:, data: }
    end

    unassigned, assigned = data_series.partition { |s| s[:name].casecmp("unassigned").zero? }
    assigned + unassigned
  end

  def measurement_data_series(*nutrients)
    nutrients.map do |formula|
      { name: Nutrient.find_by!(formula:).name,
        data: NutrientMeasurement
          .order(:measured_on)
          .pluck(:measured_on, formula) }
    end
  end
end
Copyright 2019--2025 Marius PETER