summaryrefslogtreecommitdiff
path: root/app/controllers/targets_controller.rb
diff options
context:
space:
mode:
authorMarius Peter <dev@marius-peter.com>2025-09-08 21:21:56 +0200
committerMarius Peter <dev@marius-peter.com>2025-09-08 21:21:56 +0200
commit7116826b854188604e21e2a613ac6672b6fd81f3 (patch)
tree33150bf2e04e69b8e1fa7d37901d2643b1955534 /app/controllers/targets_controller.rb
parent8ba568ae0ebe715b5da453681eb141886f1977a8 (diff)
Create Target and nutrient target table on dashboard.
Diffstat (limited to 'app/controllers/targets_controller.rb')
-rw-r--r--app/controllers/targets_controller.rb68
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
Copyright 2019--2025 Marius PETER