summaryrefslogtreecommitdiff
path: root/app/controllers/targets_controller.rb
blob: a11ddd7a374f7be4f69cd83a84821e5731741fef (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
class TargetsController < ApplicationController
  before_action :set_target, only: %i[show edit update destroy]

  def index
    @targets = Target.order(:name)
  end

  def new
    @target = Target.new(name: "Cible #{Date.today + 1.month}")
    seed_allocations
  end

  def create
    @target = Target.new(target_params)
    if @target.save
      redirect_to @target, notice: "Cible enregistrée."
    else
      seed_allocations if @target.target_allocations.blank?
      render :new, status: :unprocessable_entity
    end
  end

  def edit
  end

  def update
    if @target.update(target_params)
      redirect_to @target, notice: "Cible mise à jour."
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def show
    @weighted = @target.weighted_requirements # => { "nno3"=>..., "p"=>..., ... }

    last = NutrientMeasurement.order(measured_on: :desc, created_at: :desc).first
    @latest_measurements = {}

    if last
      # Use the same keys as NutrientProfile to keep naming consistent.
      keys = (NutrientProfile::NUTRIENT_KEYS rescue []).map(&:to_s)
      keys.each do |k|
        @latest_measurements[k] = last.send(k) if last.respond_to?(k)
      end
    end
  end

  private

  def set_target
    @target = Target.find(params[:id])
  end

  def seed_allocations
    existing_ids = @target.target_allocations.map(&:nutrient_profile_id).compact
    (NutrientProfile.order(:name).pluck(:id) - existing_ids).each do |np_id|
      @target.target_allocations.build(nutrient_profile_id: np_id, percentage: 12.5)
    end
  end

  def target_params
    params.require(:target).permit(
      :name,
      target_allocations_attributes: [ :id, :nutrient_profile_id, :percentage, :_destroy ]
    )
  end
end
Copyright 2019--2025 Marius PETER