diff options
Diffstat (limited to 'app/controllers/targets_controller.rb')
-rw-r--r-- | app/controllers/targets_controller.rb | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/app/controllers/targets_controller.rb b/app/controllers/targets_controller.rb new file mode 100644 index 0000000..60d3523 --- /dev/null +++ b/app/controllers/targets_controller.rb @@ -0,0 +1,68 @@ +class TargetsController < ApplicationController + before_action :set_target, only: %i[show edit update] + + 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 |