Class: Backend::InterventionsController

Inherits:
BaseController show all
Defined in:
app/controllers/backend/interventions_controller.rb

Instance Attribute Summary

Attributes inherited from ApplicationController

#current_theme

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseController

account_lettering_states_crit, accounts_range_crit, amount_range_crit, crit_params, journal_entries_states_crit, journal_letter_crit, journal_period_crit, journals_crit, search_conditions

Methods inherited from ApplicationController

#after_sign_in_path_for, #authorized?, human_action_name, #human_action_name, #session_controller?

Class Method Details

.list_conditionsObject

params:

:q Text search
:cultivable_zone_id
:campaign_id
:product_nature_id
:support_id

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'app/controllers/backend/interventions_controller.rb', line 36

def self.list_conditions
  conn = Intervention.connection
  # , productions: [:name], campaigns: [:name], activities: [:name], products: [:name]
  expressions = []
  expressions << 'CASE ' + Procedo.selection.map { |l, n| "WHEN #{Intervention.table_name}.procedure_name = #{conn.quote(n)} THEN #{conn.quote(l)}" }.join(' ') + " ELSE '' END"
  code = search_conditions({ interventions: %i[state procedure_name number] }, expressions: expressions) + " ||= []\n"
  code << "unless params[:state].blank?\n"
  code << "  c[0] << ' AND #{Intervention.table_name}.state IN (?)'\n"
  code << "  c << params[:state]\n"
  code << "end\n"

  code << "unless params[:nature].blank?\n"
  code << "  c[0] << ' AND #{Intervention.table_name}.nature IN (?)'\n"
  code << "  c << params[:nature]\n"
  code << "end\n"

  code << "c[0] << ' AND #{Intervention.table_name}.state != ?'\n"
  code << "c[0] << ' AND ((#{Intervention.table_name}.nature = ? AND I.request_intervention_id IS NULL) OR #{Intervention.table_name}.nature = ?)'\n"
  code << "c << '#{Intervention.state.rejected}'\n"
  code << "c << 'request'\n"
  code << "c << 'record'\n"

  code << "unless params[:procedure_name].blank?\n"
  code << "  c[0] << ' AND #{Intervention.table_name}.procedure_name IN (?)'\n"
  code << "  c << params[:procedure_name]\n"
  code << "end\n"

  # select the interventions according to the user current period
  code << "unless current_period_interval.blank? && current_period.blank?\n"

  code << " if current_period_interval.to_sym == :day\n"
  code << "   c[0] << ' AND EXTRACT(DAY FROM #{Intervention.table_name}.started_at) = ? AND EXTRACT(MONTH FROM #{Intervention.table_name}.started_at) = ? AND EXTRACT(YEAR FROM #{Intervention.table_name}.started_at) = ?'\n"
  code << "   c << current_period.to_date.day\n"
  code << "   c << current_period.to_date.month\n"
  code << "   c << current_period.to_date.year\n"

  code << " elsif current_period_interval.to_sym == :week\n"
  code << "   c[0] << ' AND #{Intervention.table_name}.started_at >= ? AND #{Intervention.table_name}.stopped_at <= ?'\n"
  code << "   c << current_period.to_date.at_beginning_of_week.to_time.beginning_of_day\n"
  code << "   c << current_period.to_date.at_end_of_week.to_time.end_of_day\n"

  code << " elsif current_period_interval.to_sym == :month\n"
  code << "   c[0] << ' AND EXTRACT(MONTH FROM #{Intervention.table_name}.started_at) = ? AND EXTRACT(YEAR FROM #{Intervention.table_name}.started_at) = ?'\n"
  code << "   c << current_period.to_date.month\n"
  code << "   c << current_period.to_date.year\n"

  code << " elsif current_period_interval.to_sym == :year\n"
  code << "   c[0] << ' AND EXTRACT(YEAR FROM #{Intervention.table_name}.started_at) = ?'\n"
  code << "   c << current_period.to_date.year\n"
  code << " end\n"

  # Cultivable zones
  code << "  if params[:cultivable_zone_id].to_i > 0\n"
  code << "    c[0] << ' AND #{Intervention.table_name}.id IN (SELECT intervention_id FROM activity_productions_interventions INNER JOIN #{ActivityProduction.table_name} ON #{ActivityProduction.table_name}.id = activity_production_id INNER JOIN #{CultivableZone.table_name} ON #{CultivableZone.table_name}.id = #{ActivityProduction.table_name}.cultivable_zone_id WHERE #{CultivableZone.table_name}.id = ' + params[:cultivable_zone_id] + ')'\n"
  code << "    c \n"
  code << "  end\n"

  # Current campaign
  code << "  if current_campaign\n"
  code << "    c[0] << \" AND EXTRACT(YEAR FROM #{Intervention.table_name}.started_at) = ?\"\n"
  code << "    c << current_campaign.harvest_year\n"
  code << "  end\n"
  code << "end\n"

  # Support
  code << "if params[:product_id].to_i > 0\n"
  code << "  c[0] << ' AND #{Intervention.table_name}.id IN (SELECT intervention_id FROM intervention_parameters WHERE product_id IN (?))'\n"
  code << "  c << params[:product_id].to_i\n"
  code << "end\n"

  # Label
  code << "if params[:label_id].to_i > 0\n"
  code << "  c[0] << ' AND #{Intervention.table_name}.id IN (SELECT intervention_id FROM intervention_labellings WHERE label_id IN (?))'\n"
  code << "  c << params[:label_id].to_i\n"
  code << "end\n"

  # ActivityProduction || Activity
  code << "if params[:production_id].to_i > 0\n"
  code << "  c[0] << ' AND #{Intervention.table_name}.id IN (SELECT intervention_id FROM intervention_parameters WHERE type = \\'InterventionTarget\\' AND product_id IN (SELECT target_id FROM target_distributions WHERE activity_production_id = ?))'\n"
  code << "  c << params[:production_id].to_i\n"
  code << "elsif params[:activity_id].to_i > 0\n"
  code << "  c[0] << 'AND #{Intervention.table_name}.id IN (SELECT intervention_id FROM interventions INNER JOIN activities_interventions ON activities_interventions.intervention_id = interventions.id INNER JOIN activities ON activities.id = activities_interventions.activity_id WHERE activities.id = ?)'\n"
  code << "  c << params[:activity_id].to_i\n"
  code << "end\n"

  # Worker || Driver
  code << "unless params[:driver_id].blank? \n"
  code << "   c[0] << ' AND #{Intervention.table_name}.id IN (SELECT intervention_id FROM interventions INNER JOIN #{InterventionDoer.table_name} ON #{InterventionDoer.table_name}.intervention_id = #{Intervention.table_name}.id WHERE #{InterventionDoer.table_name}.product_id = ? AND #{InterventionDoer.table_name}.reference_name = \\'driver\\')'\n"
  code << "   c << params[:driver_id].to_i\n"
  code << "end\n"

  # Intervention tool
  code << "unless params[:equipment_id].blank? \n"
  code << "   c[0] << ' AND #{Intervention.table_name}.id IN (SELECT intervention_id FROM interventions INNER JOIN #{InterventionParameter.table_name} ON #{InterventionParameter.table_name}.intervention_id = #{Intervention.table_name}.id WHERE #{InterventionParameter.table_name}.product_id = ?)'\n"
  code << "   c << params[:equipment_id].to_i\n"
  code << "end\n"

  code << "c\n "
  code.c
end

Instance Method Details

#change_pageObject

FIXME: Not linked directly to interventions


509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
# File 'app/controllers/backend/interventions_controller.rb', line 509

def change_page
  options = params.require(:interventions_taskboard).permit(:q, :procedure_name, :product_id, :cultivable_zone_id, :period_interval, :period, :page)
  options[:period_interval] ||= current_period_interval
  options[:period] ||= current_period

  @interventions_by_state = {
    requests:  Intervention.with_unroll(options.merge(nature: :request)),
    current:   Intervention.with_unroll(options.merge(nature: :record, state: :in_progress)),
    finished:  Intervention.with_unroll(options.merge(nature: :record, state: :done)),
    validated: Intervention.with_unroll(options.merge(nature: :record, state: :validated))
  }
  respond_to do |format|
    format.js
  end
end

#change_stateObject


425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
# File 'app/controllers/backend/interventions_controller.rb', line 425

def change_state
  unless state_change_permitted_params
    head :unprocessable_entity
    return
  end

  interventions_ids = JSON.parse(state_change_permitted_params[:interventions_ids]).to_a
  new_state = state_change_permitted_params[:state].to_sym

  @interventions = Intervention.find(interventions_ids)

  Intervention.transaction do
    @interventions.each do |intervention|
      if intervention.nature == :record && new_state == :rejected

        unless intervention.request_intervention_id.nil?
          intervention_request = Intervention.find(intervention.request_intervention_id)

          if state_change_permitted_params[:delete_option].to_sym == :delete_request
            intervention_request.destroy!
          else
            intervention_request.parameters = intervention.parameters
            intervention_request.save!
          end
        end

        intervention.destroy!
        next
      end

      if intervention.nature == :request && new_state == :rejected
        intervention.state = new_state

        next unless intervention.valid?
        intervention.save!

        next
      end

      new_intervention = intervention

      if intervention.nature == :request
        new_intervention = intervention.dup
        intervention.working_periods.each do |wp|
          new_intervention.working_periods.build(wp.dup.attributes)
        end
        intervention.parameters.each do |parameter|
          new_intervention.parameters.build(parameter.dup.attributes)
        end
        intervention.participations.includes(:working_periods).each do |participation|
          dup_participation = participation.dup.attributes.merge({state: 'in_progress'})
          new_participation = new_intervention.participations.build(dup_participation)
          participation.working_periods.each do |wp|
            new_participation.working_periods.build(wp.dup.attributes)
          end
        end
        new_intervention.request_intervention_id = intervention.id
      end


      if new_state == :validated
        new_intervention.validator = current_user
      end

      new_intervention.state = new_state
      new_intervention.nature = :record

      next unless new_intervention.valid?
      new_intervention.save!
    end
  end

  if @interventions.count == 1 && !(params[:intervention][:redirect] == 'false')
    intervention = @interventions.first
    if intervention.request? && intervention.record_interventions.any?
      record_intervention = intervention.record_interventions.first
      return redirect_to backend_intervention_path(record_intervention)
    end
  end

  redirect_to_back
end

#compare_realised_with_plannedObject


558
559
560
561
562
563
564
# File 'app/controllers/backend/interventions_controller.rb', line 558

def compare_realised_with_planned
  @intervention = Intervention.find(params[:intervention_id])
  @request_intervention = @intervention.request_intervention
  respond_to do |format|
    format.js
  end
end

#computeObject

Computes impacts of a updated value in an intervention input context


360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# File 'app/controllers/backend/interventions_controller.rb', line 360

def compute
  unless params[:intervention]
    head(:unprocessable_entity)
    return
  end
  intervention_params = params[:intervention].deep_symbolize_keys
  procedure = Procedo.find(intervention_params[:procedure_name])
  unless procedure
    head(:not_found)
    return
  end

  unless intervention_params[:tools_attributes].nil?
    intervention_params[:tools_attributes]
      .values
      .each { |tool_attributes| tool_attributes.except!(:readings_attributes) }
  end

  intervention = Procedo::Engine.new_intervention(intervention_params)
  begin
    intervention.impact_with!(params[:updater])
    updater_id = 'intervention_' + params[:updater].gsub('[', '_attributes_').tr(']', '_')
    # raise intervention.to_hash.inspect
    respond_to do |format|
      # format.xml  { render xml: intervention.to_xml }
      format.json { render json: { updater_id: updater_id, intervention: intervention, handlers: intervention.handlers_states, procedure_states: intervention.procedure_states }.to_json }
    end
  rescue Procedo::Error => e
    respond_to do |format|
      # format.xml  { render xml:  { errors: e.message }, status: 500 }
      format.json { render json: { errors: e.message }, status: 500 }
    end
  end
end

#createObject


293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'app/controllers/backend/interventions_controller.rb', line 293

def create
  unless permitted_params[:participations_attributes].nil?
    participations = permitted_params[:participations_attributes]

    participations.each_pair do |key, value|
      participations[key] = JSON.parse(value)
    end

    permitted_params[:participations_attributes] = participations
  end

  # binding.pry
  @intervention = Intervention.new(permitted_params)
  url = if params[:create_and_continue]
          { action: :new, continue: true }
        elsif URI(request.referer).path == '/backend/schedulings/new_detailed_intervention'
          backend_schedulings_path
        else
          params[:redirect] || { action: :show, id: 'id'.c }
        end
  @intervention.save
  reconcile_receptions
  return if save_and_redirect(@intervention, url: url, notify: :record_x_created, identifier: :number)
  render(locals: { cancel_url: { action: :index }, with_continue: true })
end

#create_duplicate_interventionObject


547
548
549
550
551
552
553
554
555
556
# File 'app/controllers/backend/interventions_controller.rb', line 547

def create_duplicate_intervention
  find_intervention
  new_intervention
  if @new_intervention.save
    params[:interventions].delete(params[:intervention])
    duplicate_interventions
  else
    render json: { errors: @new_intervention.errors.full_messages.join(', ') }
  end
end

#duplicate_interventionsObject


537
538
539
540
541
542
543
544
545
# File 'app/controllers/backend/interventions_controller.rb', line 537

def duplicate_interventions
  get_interventions
  if interventions_validations
    render json: nil
  else
    render partial: 'duplicate_modal',
    locals: { intervention: @interventions.first }
  end
end

#generate_buttonsObject


525
526
527
528
529
530
531
532
533
534
535
# File 'app/controllers/backend/interventions_controller.rb', line 525

def generate_buttons
  get_interventions

  if interventions_validations
    render json: nil
  elsif params[:icon_btn] == 'true'
    render json: { translation: :duplicate_x_selected_interventions.tl(count: @interventions.count) }
  else
    render partial: 'generate_buttons'
  end
end

408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'app/controllers/backend/interventions_controller.rb', line 408

def modal
  if params[:intervention_id]
    @intervention = Intervention.find(params[:intervention_id])
    render partial: 'backend/interventions/details_modal', locals: { intervention: @intervention }
  end

  if params[:interventions_ids]
    @interventions = Intervention.find(params[:interventions_ids].split(','))

    if params[:modal_type] == 'delete'
      render partial: 'backend/interventions/delete_modal', locals: { interventions: @interventions }
    else
      render partial: 'backend/interventions/change_state_modal', locals: { interventions: @interventions }
    end
  end
end

#newObject


222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'app/controllers/backend/interventions_controller.rb', line 222

def new
  options = {}
  %i[actions custom_fields description event_id issue_id
     nature number prescription_id procedure_name
     request_intervention_id started_at state
     stopped_at trouble_description trouble_encountered
     whole_duration working_duration].each do |param|
    options[param] = params[param]
  end

  # , :doers, :inputs, :outputs, :tools
  %i[group_parameters targets].each do |param|
    next unless params.include? :intervention
    options[:"#{param}_attributes"] = permitted_params["#{param}_attributes"] || []

    next unless options[:targets_attributes]

    next if permitted_params.include? :working_periods
    targets = if options[:targets_attributes].is_a? Array
                options[:targets_attributes].collect { |k, _| k[:product_id] }
              else
                options[:targets_attributes].collect { |_, v| v[:product_id] }
              end
    availables = Product.where(id: targets).at(Time.zone.now - 1.hour).collect(&:id)

    options[:targets_attributes].select! do |k, v|
      obj = k.is_a?(Hash) ? k : v
      obj.include?(:product_id) && availables.include?(obj[:product_id].to_i)
    end
  end

  %i[doers inputs outputs tools participations working_periods].each do |param|
    next unless params.include? :intervention
    options[:"#{param}_attributes"] = permitted_params["#{param}_attributes"] || []
  end

  # consume preference and erase
  if params[:keeper_id] && (p = current_user.preferences.get(params[:keeper_id])) && p.value.present?

    options[:targets_attributes] = p.value.split(',').collect do |v|
      hash = {}

      hash[:product_id] = v if Product.find_by(id: v)

      if params[:reference_name]
        next unless params[:reference_name] == 'animal'
        hash[:reference_name] = params[:reference_name]
      end

      if params[:new_group] && (g = Product.find_by(id: params[:new_group]))
        hash[:new_group_id] = g.id
      end

      if params[:new_container] && (c = Product.find_by(id: params[:new_container]))
        hash[:new_container_id] = c.id
      end

      hash
    end.compact

    p.set! nil
  end

  @intervention = Intervention.new(options)

  from_request = Intervention.find_by(id: params[:request_intervention_id])
  @intervention = from_request.initialize_record if from_request

  render(locals: { cancel_url: { action: :index }, with_continue: true })
end

#purchaseObject


350
351
352
353
354
355
356
357
# File 'app/controllers/backend/interventions_controller.rb', line 350

def purchase
  interventions = params[:id].split(',')
  if interventions
    redirect_to new_backend_purchase_path(intervention_ids: interventions)
  else
    redirect_to action: :index
  end
end

#purchase_order_itemsObject


395
396
397
398
399
400
401
402
403
404
405
406
# File 'app/controllers/backend/interventions_controller.rb', line 395

def purchase_order_items
  purchase_order = Purchase.find(params[:purchase_order_id])
  reception = Intervention.find(params[:intervention_id]).receptions.first if params[:intervention_id].present?
  order_hash = if reception.present? && reception.purchase_id == purchase_order.id
                 find_items(reception.id, reception.pretax_amount, reception.items)
               else
                 find_items(purchase_order.id, purchase_order.pretax_amount, purchase_order.items)
               end
  respond_to do |format|
    format.json { render json: order_hash }
  end
end

#sellObject


340
341
342
343
344
345
346
347
348
# File 'app/controllers/backend/interventions_controller.rb', line 340

def sell
  interventions = params[:id].split(',')
  return unless interventions
  if interventions
    redirect_to new_backend_sale_path(intervention_ids: interventions)
  else
    redirect_to action: :index
  end
end

#showObject

Show one intervention with params_id


201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'app/controllers/backend/interventions_controller.rb', line 201

def show
  return unless @intervention = find_and_check
  t3e @intervention, procedure_name: @intervention.procedure.human_name, nature: @intervention.request? ? :planning_of.tl : nil
  respond_with(@intervention, methods: %i[cost earn status name duration human_working_zone_area human_actions_names],
                              include: [
                                { leaves_parameters: {
                                  methods: %i[reference_name default_name working_zone_svg human_quantity human_working_zone_area],
                                  include: {
                                    product: {
                                      methods: %i[picture_path nature_name unit_name]
                                    }
                                  }
                                } }, {
                                  prescription: {
                                    include: %i[prescriptor attachments]
                                  }
                                }
                              ],
                              procs: proc { |options| options[:builder].tag!(:url, backend_intervention_url(@intervention)) })
end

#updateObject


319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'app/controllers/backend/interventions_controller.rb', line 319

def update
  @intervention = find_and_check

  unless permitted_params[:participations_attributes].nil?
    participations = permitted_params[:participations_attributes]
    participations.each_pair do |key, value|
      participations[key] = JSON.parse(value)
    end

    permitted_params[:participations_attributes] = participations

    delete_working_periods(participations)
  end
  if @intervention.update_attributes(permitted_params)
    reconcile_receptions
    redirect_to action: :show
  else
    render :edit
  end
end