summaryrefslogtreecommitdiff
path: root/app/models/target.rb
blob: 2efd3b2599eea56fd4eb9e37e74bf2ecfcbed450 (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
class Target < ApplicationRecord
  include NutrientVector

  has_many :target_allocations, inverse_of: :target, dependent: :destroy

  after_initialize :set_defaults, if: :new_record?

  validate :allocations_sum_to_100

  # Recompute when allocations change; keep it simple (memoized per instance)
  def recompute_nutrients!
    @nutrient_values = nil
    nutrient_values
  end

  private

  def nutrient_values
    @nutrient_values ||= get_nutrient_values
  end

  def get_nutrient_values
    sums = Hash.new(0.0)
    allocs = target_allocations.includes(:nutrient_profile)

    allocs.each do |alloc|
      weight = alloc.percentage.to_f / 100.0
      profile = alloc.nutrient_profile
      NutrientVector::NUTRIENT_KEYS.each do |k|
        sums[k] += profile.public_send(k).to_f * weight
      end
    end

    # Ensure all keys exist, even when there are no allocations
    NutrientVector::NUTRIENT_KEYS.each { |k| sums[k] ||= 0.0 }
    sums.freeze
  end

  def set_defaults
    self.name ||= "Cible #{Date.today + 1.month}"
    if target_allocations.empty?
      nutrient_profiles = NutrientProfile.limit(3)
      nutrient_profiles.each do |profile|
        target_allocations.build(nutrient_profile: profile, percentage: 0)
      end
    end
  end

  def allocations_sum_to_100
    sum = target_allocations.reject(&:marked_for_destruction?).sum { |a| a.percentage.to_f }
    errors.add(:base, "La somme des pourcentages doit être 100%") unless (sum - 100).abs < 0.01
  end
end
Copyright 2019--2026 Marius PETER