Class: Intervention

Inherits:
Ekylibre::Record::Base show all
Includes:
CastGroupable, Customizable, PeriodicCalculable
Defined in:
app/models/intervention.rb,
app/models/intervention/recorder.rb,
app/models/intervention/recorder/cast.rb

Overview

Informations

License

Ekylibre - Simple agricultural ERP Copyright (C) 2008-2009 Brice Texier, Thibaud Merigon Copyright (C) 2010-2012 Brice Texier Copyright (C) 2012-2019 Brice Texier, David Joulin

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License along with this program. If not, see www.gnu.org/licenses.

Table: interventions

accounted_at                   :datetime
actions                        :string
auto_calculate_working_periods :boolean          default(FALSE)
costing_id                     :integer
created_at                     :datetime         not null
creator_id                     :integer
currency                       :string
custom_fields                  :jsonb
description                    :text
event_id                       :integer
id                             :integer          not null, primary key
issue_id                       :integer
journal_entry_id               :integer
lock_version                   :integer          default(0), not null
nature                         :string           not null
number                         :string
parent_id                      :integer
prescription_id                :integer
procedure_name                 :string           not null
providers                      :jsonb
purchase_id                    :integer
request_compliant              :boolean
request_intervention_id        :integer
started_at                     :datetime         not null
state                          :string           not null
stopped_at                     :datetime         not null
trouble_description            :text
trouble_encountered            :boolean          default(FALSE), not null
updated_at                     :datetime         not null
updater_id                     :integer
validator_id                   :integer
whole_duration                 :integer          not null
working_duration               :integer          not null

Defined Under Namespace

Classes: Recorder

Constant Summary collapse

PLANNED_REALISED_ACCEPTED_GAP =
{ intervention_doer: 1.2, intervention_tool: 1.2, intervention_input: 1.2 }.freeze

Constants included from PeriodicCalculable

PeriodicCalculable::PARAMETERS

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Customizable

#custom_value, #set_custom_value, #validate_custom_fields

Methods included from CastGroupable

#add_group_parameter!, #add_parameter!, #add_product_parameter!

Methods inherited from Ekylibre::Record::Base

#already_updated?, #check_if_destroyable?, #check_if_updateable?, columns_definition, #customizable?, customizable?, #customized?, #destroyable?, #editable?, has_picture, #human_attribute_name, nomenclature_reflections, #old_record, #others, refers_to, #unsuppress, #updateable?

Methods included from Userstamp::Stampable

included

Methods included from Userstamp::Stamper

included

Class Method Details

.convert_to_purchase(interventions) ⇒ Object


1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
# File 'app/models/intervention.rb', line 1111

def convert_to_purchase(interventions)
  purchase = nil
  transaction do
    interventions = interventions
                      .collect { |intv| (intv.is_a?(self) ? intv : find(intv)) }
                      .sort_by(&:stopped_at)
    planned_at = interventions.last.stopped_at
    owners = interventions.map(&:doers).map { |t| t.map(&:product).map(&:owner).compact }.flatten.uniq
    supplier = owners.first if owners.second.blank?
    unless nature = PurchaseNature.actives.first
      unless journal = Journal.purchases.opened_at(planned_at).first
        raise 'No purchase journal'
      end
      nature = PurchaseNature.new(
        active: true,
        currency: Preference[:currency],
        with_accounting: true,
        journal: journal,
        by_default: true,
        name: PurchaseNature.tc('default.name', default: PurchaseNature.model_name.human)
      )
    end
    purchase = nature.purchases.new(
      supplier: supplier,
      planned_at: planned_at,
      delivery_address: supplier && supplier.default_mail_address,
      description: %(#{Intervention.model_name.plural.tl}:
\t- #{interventions.map(&:name).join("\n\t - ")})
    )

    # Adds items
    interventions.each do |intervention|
      hourly_params = {
        catalog: Catalog.by_default!(:cost),
        quantity_method: ->(_item) { intervention.duration.in_second.in_hour }
      }
      components = {
        doers: hourly_params,
        tools: hourly_params,
        inputs: {
          catalog: Catalog.by_default!(:purchase),
          quantity_method: ->(item) { item.quantity }
        }
      }

      components.each do |component, cost_params|
        intervention.send(component).each do |item|
          catalog_item = Maybe(cost_params[:catalog].items.find_by(variant_id: item.variant))
          quantity = cost_params[:quantity_method].call(item).round(3)
          purchase.items.new(
            variant: item.variant,
            unit_pretax_amount: catalog_item.pretax_amount.or_else(nil),
            tax: catalog_item.reference_tax.or_else(nil),
            quantity: quantity.value.to_f,
            annotation: %(#{Intervention.model_name.human} '#{intervention.name}' > \
            #{Intervention.human_attribute_name(component).capitalize}
            \t- #{item.product.name} x #{quantity.l(precision: 2)})
          )
        end
      end
    end
  end
  purchase
end

.convert_to_sale(interventions) ⇒ Object


1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
# File 'app/models/intervention.rb', line 1176

def convert_to_sale(interventions)
  sale = nil
  transaction do
    interventions = interventions
                      .collect { |intv| (intv.is_a?(self) ? intv : find(intv)) }
                      .sort_by(&:stopped_at)
    planned_at = interventions.last.stopped_at

    owners = interventions.map do |intervention|
      intervention.targets.map do |target|
        if target.product.is_a?(LandParcel)
          prod = target.activity_production
          owner = prod && prod.cultivable_zone && prod.cultivable_zone.farmer
        elsif target.product.is_a?(Equipment)
          owner = target.product.owner
        end
        owner
      end
    end
    owners = owners.flatten.uniq
    client = owners.first unless owners.count > 1
    unless nature = SaleNature.actives.first
      unless journal = Journal.sales.opened_at(planned_at).first
        raise 'No sale journal'
      end
      nature = SaleNature.new(
        active: true,
        currency: Preference[:currency],
        journal: journal,
        by_default: true,
        name: SaleNature.tc('default.name', default: SaleNature.model_name.human)
      )
    end
    sale = nature.sales.new(
      client: client,
      address: client && client.default_mail_address,
      description: %(#{Intervention.model_name.plural.tl}:
\t- #{interventions.map(&:name).join("\n\t - ")})
    )
    # Adds items
    interventions.each do |intervention|
      hourly_params = {
        catalog: Catalog.by_default!(:cost),
        quantity_method: ->(_item) { intervention.duration.in_second.in_hour }
      }
      components = {
        doers: hourly_params,
        tools: hourly_params,
        inputs: {
          catalog: Catalog.by_default!(:sale),
          quantity_method: ->(item) { item.quantity }
        }
      }

      components.each do |component, cost_params|
        intervention.send(component).each do |item|
          catalog_item = Maybe(cost_params[:catalog].items.find_by(variant_id: item.variant))
          quantity = cost_params[:quantity_method].call(item).round(3)
          sale.items.new(
            variant: item.variant,
            unit_pretax_amount: catalog_item.pretax_amount.or_else(nil),
            tax: catalog_item.reference_tax.or_else(nil),
            quantity: quantity.value.to_f,
            annotation: %(#{Intervention.model_name.human} '#{intervention.name}' > \
            #{Intervention.human_attribute_name(component).capitalize}
            \t- #{item.product.name} x #{quantity.l(precision: 2)})
          )
        end
      end
    end
  end
  sale
end

.find_products(model, options = {}) ⇒ Object

Find a product with given options

- started_at
- work_number
- can
- variety
- derivative_of
- filter: WSQL expression

Options for product creation only:

- default_storage

Special options for worker creation only:

- first_name
- last_name
- born_at
- default_storage

1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
# File 'app/models/intervention.rb', line 1030

def find_products(model, options = {})
  relation = model
  relation = relation.where('COALESCE(born_at, ?) <= ? ', options[:started_at], options[:started_at]) if options[:started_at]
  relation = relation.of_expression(options[:filter]) if options[:filter]
  relation = relation.of_work_numbers(options[:work_number]) if options[:work_number]
  relation = relation.can(options[:can]) if options[:can]
  relation = relation.of_variety(options[:variety]) if options[:variety]
  relation = relation.derivative_of(options[:derivative_of]) if options[:derivative_of]
  return relation.all if relation.any?
end

.match(actors, options = {}) ⇒ Object

Returns an array of procedures matching the given actors ordered by relevance whose structure is [[procedure, relevance, arity], [procedure, relevance, arity], …] where 'procedure' is a Procedo::Procedure object, 'relevance' is a float, 'arity' is the number of actors matched in the procedure

parameters:

- actors, an array of actors identified for a given procedure

options:

- relevance: sets the relevance threshold above which results are wished.
  A float number between 0 and 1 is expected. Default value: 0.
- limit: sets the number of wanted results. By default all results are returned
- history: sets the use of actors history to calculate relevance.
  A boolean is expected. Default: false,since checking through history is slower
- provisional: sets the use of actors provisional to calculate relevance.
  A boolean is expected. Default: false, since it's slower.
- max_arity: limits results to procedures matching most actors.
  A boolean is expected. Default: false

1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
# File 'app/models/intervention.rb', line 1057

def match(actors, options = {})
  actors = [actors].flatten
  limit = options[:limit].to_i - 1
  relevance_threshold = options[:relevance].to_f
  maximum_arity = 0

  # Creating coefficients for relevance calculation for each procedure
  # coefficients depend on provisional, actors history and actors presence in procedures
  history = Hash.new(0)
  provisional = []
  actors_id = []
  actors_id = actors.map(&:id) if options[:history] || options[:provisional]

  # Select interventions from all actors history
  if options[:history]
    # history is considered relevant on 1 year
    history.merge!(Intervention.joins(:product_parameters)
                     .where("intervention_parameters.actor_id IN (#{actors_id.join(', ')})")
                     .where(started_at: (Time.zone.now.midnight - 1.year)..(Time.zone.now))
                     .group('interventions.procedure_name')
                     .count('interventions.procedure_name'))
  end

  if options[:provisional]
    provisional.concat(Intervention.distinct
                         .joins(:product_parameters)
                         .where("intervention_parameters.actor_id IN (#{actors_id.join(', ')})")
                         .where(started_at: (Time.zone.now.midnight - 1.day)..(Time.zone.now + 3.days))
                         .pluck('interventions.procedure_name')).uniq!
  end

  coeff = {}

  history_size = 1.0 # prevents division by zero
  history_size = history.values.reduce(:+).to_f if history.count >= 1

  denominator = 1.0
  denominator += 2.0 if options[:history] && history.present?
  denominator += 3.0 if provisional.present? # if provisional is empty, it's pointless using it for relevance calculation

  result = []
  Procedo.procedures do |procedure_key, procedure|
    coeff[procedure_key] = 1.0 + 2.0 * (history[procedure_key].to_f / history_size) + 3.0 * provisional.count(procedure_key).to_f
    matched_parameters = procedure.matching_parameters_for(actors)
    if matched_parameters.any?
      result << [procedure, (((matched_parameters.values.count.to_f / actors.count) * coeff[procedure_key]) / denominator), matched_parameters.values.count]
      maximum_arity = matched_parameters.values.count if maximum_arity < matched_parameters.values.count
    end
  end
  result.delete_if { |_procedure, relevance, _arity| relevance < relevance_threshold }
  result.delete_if { |_procedure, _relevance, arity| arity < maximum_arity } if options[:max_arity]
  result.sort_by { |_procedure, relevance, _arity| -relevance }[0..limit]
end

.run!(*args) ⇒ Object

Create and run intervention


990
991
992
993
994
995
996
997
998
999
# File 'app/models/intervention.rb', line 990

def run!(*args)
  attributes = args.extract_options!
  attributes[:procedure_name] ||= args.shift
  intervention = transaction do
    intervention = Intervention.create!(attributes)
    yield intervention if block_given?
    intervention.run!
  end
  intervention
end

.used_proceduresObject


983
984
985
986
987
# File 'app/models/intervention.rb', line 983

def used_procedures
  select(:procedure_name).distinct.pluck(:procedure_name).map do |name|
    Procedo.find(name)
  end.compact
end

.write(*args) ⇒ Object

Registers and runs an intervention directly


1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
# File 'app/models/intervention.rb', line 1002

def write(*args)
  options = args.extract_options!
  procedure_name = args.shift || options[:procedure_name]

  transaction do
    attrs = options.slice(:procedure_name, :description, :issue_id, :prescription_id)
    recorder = Intervention::Recorder.new(attrs)

    yield recorder

    recorder.write!
  end
end

Instance Method Details

#activity_imputation(activity) ⇒ Object


796
797
798
799
800
801
802
803
804
805
806
807
# File 'app/models/intervention.rb', line 796

def activity_imputation(activity)
  if activity.size_indicator == :net_surface_area
    unit = :hectare
    precision = 2
    if targets.any?
      at = targets.of_activity(activity).with_working_zone.map(&:working_zone_area).sum.in(unit)
      coeff = (at.to_d / working_zone_area.to_d) if working_zone_area.to_d != 0.0
      return nil unless coeff
      coeff.round(precision)
    end
  end
end

#activity_production_zone_area(*args) ⇒ Object

return all initial area of supports of targets


773
774
775
776
777
778
779
780
781
782
# File 'app/models/intervention.rb', line 773

def activity_production_zone_area(*args)
  options = args.extract_options!
  unit = args.shift || options[:unit] || :hectare
  if targets.any?
    ap = ActivityProduction.where(support_id: targets.pluck(:product_id))
    area = ap.map(&:support_shape_area).sum.in(:square_meter).convert(unit)
  end
  area ||= 0.0.in(unit)
  area
end

#add_activity_production_to_outputObject


831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
# File 'app/models/intervention.rb', line 831

def add_activity_production_to_output
  parameters = group_parameters

  group_parameters.each do |group_parameter|
    activity_production_id = group_parameter
                               .targets
                               .map(&:product)
                               .flatten
                               .map(&:activity_production_id)
                               .uniq
                               .first

    products_to_update = group_parameter
                           .outputs
                           .map(&:product)
                           .flatten
                           .uniq

    products_to_update.each do |product|
      product.update(activity_production_id: activity_production_id)
    end
  end
end

#add_working_period!(started_at, stopped_at) ⇒ Object


870
871
872
# File 'app/models/intervention.rb', line 870

def add_working_period!(started_at, stopped_at)
  working_periods.create!(started_at: started_at, stopped_at: stopped_at)
end

#area_cost_coefficientObject


739
740
741
742
743
744
745
746
747
748
# File 'app/models/intervention.rb', line 739

def area_cost_coefficient
  zone_area = working_zone_area(:hectare).to_f.round(2)
  global_area = activity_production_zone_area(:hectare).to_f.round(2)
  coef = 1.0
  # build coef for area's
  if zone_area && global_area && global_area > 0.0
    coef = zone_area / global_area
  end
  coef
end

#build_duplicate_intervention_attributesObject


928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
# File 'app/models/intervention.rb', line 928

def build_duplicate_intervention_attributes
  associations_parameters = { intervention: {} }
  %w[targets tools inputs doers outputs participations working_periods].each do |product_parameter|
    next unless self.send(product_parameter).any?
    key = (product_parameter + '_attributes').to_sym
    associations_parameters[:intervention][key] = {}
    self.send(product_parameter).each_with_index do |parameter, parameter_index|
      parameter_attributes = build_has_many_association(product_parameter, parameter)
      associations_parameters[:intervention][key][parameter_index] = parameter_attributes
    end
  end

  if self.group_parameters.any?
    associations_group_parameters = { intervention: { group_parameters_attributes: {} } }
    self.group_parameters.each_with_index do |gp, gp_index|
      associations_group_parameters[:intervention][:group_parameters_attributes][gp_index] = { reference_name: gp.reference_name }
      %w[targets tools inputs doers outputs participations working_periods].each do |product_parameter|
        next unless gp.send(product_parameter).any?
        key = (product_parameter + '_attributes').to_sym
        associations_group_parameters[:intervention][:group_parameters_attributes][gp_index][key] = {}
        gp.send(product_parameter).each_with_index do |parameter, parameter_index|
          parameter_attributes = build_has_many_association(product_parameter, parameter)
          associations_group_parameters[:intervention][:group_parameters_attributes][gp_index][key][parameter_index] = parameter_attributes
        end
      end
    end
    associations_parameters.deep_merge!(associations_group_parameters)
  end

  parameters = self.attributes.merge(associations_parameters)
  parameters
end

#build_has_many_association(product_parameter, parameter) ⇒ Object


961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
# File 'app/models/intervention.rb', line 961

def build_has_many_association(product_parameter, parameter)
  if product_parameter == 'inputs'
    parameter_attributes = { product_id: parameter.product_id.to_s, reference_name: parameter.reference_name, quantity_value: parameter.quantity_value, quantity_handler: parameter.quantity_handler, quantity_population: parameter.quantity_population }
  elsif product_parameter == 'outputs'
    parameter_attributes = { variant_id: parameter.variant_id.to_s, reference_name: parameter.reference_name, quantity_value: parameter.quantity_value, quantity_handler: parameter.quantity_handler, quantity_population: parameter.quantity_population }
  elsif product_parameter == 'participations'
    parameter_attributes = { product_id: parameter.product_id, state: parameter.state, working_periods_attributes: [] }
    parameter.working_periods.each_with_index do |wp, wp_index|
      wp_attributes = { nature: wp.nature, started_at: wp.started_at, stopped_at: wp.stopped_at }
      parameter_attributes[:working_periods_attributes][wp_index] = wp_attributes
    end
  elsif product_parameter == 'working_periods'
    parameter_attributes = { started_at: parameter.started_at, stopped_at: parameter.stopped_at }
  elsif product_parameter == 'targets'
    parameter_attributes = { product_id: parameter.product_id.to_s, reference_name: parameter.reference_name, working_zone: parameter.working_zone }
  else
    parameter_attributes = { product_id: parameter.product_id.to_s, reference_name: parameter.reference_name }
  end
  parameter_attributes
end

#calculate_cost_amount_computation(product_parameter) ⇒ Object


485
486
487
488
489
490
491
492
493
494
# File 'app/models/intervention.rb', line 485

def calculate_cost_amount_computation(product_parameter)
  if product_parameter.product.is_a?(Worker)
    computation = product_parameter.cost_amount_computation
  elsif product_parameter.product.try(:tractor?) && product_parameter.try(:participation) && product_parameter.participation.present?
    computation = product_parameter.cost_amount_computation(natures: %i[travel intervention])
  else
    computation = product_parameter.cost_amount_computation(natures: %i[intervention])
  end
  computation
end

#compare_planned_and_realisedObject


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
# File 'app/models/intervention.rb', line 425

def compare_planned_and_realised
  return :no_request if request_intervention.nil? || request_intervention.parameters.blank?
  return false if request_intervention.duration != self.duration
  accepted_error = PLANNED_REALISED_ACCEPTED_GAP
  params_result = true

  associations = %i[doers tools inputs targets]
  associations.each do |association|
    self_parameters = send(association)
    request_parameters = request_intervention.send(association)
    if (self_parameters.empty? && request_parameters.any?) || (self_parameters.any? && request_parameters.empty?)
      params_result = false
      break false
    end
    unless self_parameters.empty? && request_parameters.empty?
      if self_parameters.group_by(&:product_id).count != request_parameters.group_by(&:product_id).count
        params_result = false
        break false
      end
      request_parameters.group_by(&:product_id).each do |product_id, request_param|
        self_param = product_parameters.where(product_id: product_id)

        return false if self_param.empty?

        # For InterventionDoer and InterventionTool
        request_duration = 0
        request_param.each { |param| request_duration += calculate_cost_amount_computation(param).quantity }

        self_duration = 0
        self_param.each { |param| self_duration += calculate_cost_amount_computation(param).quantity }

        percent = accepted_error[request_param.first.type.underscore.to_sym] || 1.2
        intervals = (request_duration / percent..request_duration * percent)

        unless intervals.include?(self_duration)
          params_result = false
          break false
        end
        # For InterventionTarget
        if self_param.map(&:working_zone).compact.sum != request_param.map(&:working_zone).compact.sum
          params_result = false
          break false
        end

        # For InterventionInput
        request_quantity = request_param.map(&:quantity_population).compact.sum
        self_quantity = self_param.map(&:quantity_population).compact.sum

        percent = accepted_error[request_param.first.type.underscore.to_sym] || 1.2
        intervals = (request_quantity / percent..request_quantity * percent)
        unless intervals.include?(self_quantity)
          params_result = false
          break false
        end
      end
    end
  end
  params_result
end

#completely_filled?Boolean

Returns:

  • (Boolean)

623
624
625
626
627
628
629
630
# File 'app/models/intervention.rb', line 623

def completely_filled?
  reference_names = parameters.pluck(:reference_name).uniq
  reference_names = reference_names.map(&:to_sym)
  parameters_names = procedure.parameters.map(&:name).uniq

  result = parameters_names - reference_names | reference_names - parameters_names
  result.empty?
end

#cost(role = :input) ⇒ Object

Sums all intervention product parameter total_cost of a particular role


687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
# File 'app/models/intervention.rb', line 687

def cost(role = :input)
  params = product_parameters.of_generic_role(role)

  if params.any?
    return params.map(&:cost).compact.sum if participations.empty?

    return params.map do |param|
      natures = {}
      if param.product.is_a?(Equipment)
        natures = %i[travel intervention] if param.product.try(:tractor?)
        natures = %i[intervention] unless param.product.try(:tractor?)
      end

      param.cost(natures: natures)
    end.compact.sum
  end

  nil
end

#cost_per_area(role = :input, area_unit = :hectare) ⇒ Object


711
712
713
714
715
716
717
718
719
720
# File 'app/models/intervention.rb', line 711

def cost_per_area(role = :input, area_unit = :hectare)
  zone_area = working_zone_area(area_unit).to_f.round(2)
  if zone_area > 0.0
    params = product_parameters.of_generic_role(role)
    costs = params.map(&:cost).compact
    return (costs.sum / zone_area) * area_cost_coefficient if costs.any?
    nil
  end
  nil
end

#create_missing_costingObject


496
497
498
# File 'app/models/intervention.rb', line 496

def create_missing_costing
  update_costing if costing.blank?
end

#currencyObject


750
751
752
# File 'app/models/intervention.rb', line 750

def currency
  Preference[:currency]
end

#drivers_times(nature: nil, not_nature: nil) ⇒ Object


909
910
911
912
913
# File 'app/models/intervention.rb', line 909

def drivers_times(nature: nil, not_nature: nil)
  worker_working_periods(nature: nature, not_nature: not_nature)
    .map(&:duration)
    .reduce(0, :+)
end

#duration_from_catalogObject

compute stopped_at and duration if not present and if duration <


920
921
922
923
924
925
926
# File 'app/models/intervention.rb', line 920

def duration_from_catalog
  flow = MasterEquipmentFlow.find_by(procedure_name: procedure_name)
  if flow && working_zone_area.to_f > 0.0
    real_stop = started_at + (flow.intervention_flow.to_d * working_zone_area.to_d * 3600)
    catalog_duration = (real_stop - started_at).in(:second).convert(:hour)
  end
end

#earn(role = :output) ⇒ Object


754
755
756
757
758
# File 'app/models/intervention.rb', line 754

def earn(role = :output)
  params = product_parameters.of_generic_role(role)
  return params.map(&:earn).compact.sum if params.any?
  nil
end

#first_worker_working_period(nature: nil, not_nature: nil) ⇒ Object


915
916
917
# File 'app/models/intervention.rb', line 915

def first_worker_working_period(nature: nil, not_nature: nil)
  test = worker_working_periods(nature: nature, not_nature: not_nature)
end

#human_actions_namesObject

Returns human actions names


601
602
603
604
# File 'app/models/intervention.rb', line 601

def human_actions_names
  actions.map { |action| Nomen::ProcedureAction.find(action).human_name }
    .to_sentence
end

#human_activities_namesObject

Returns human activity names


556
557
558
# File 'app/models/intervention.rb', line 556

def human_activities_names
  activities.map(&:name).to_sentence
end

#human_doer_namesObject

Returns human doer names


582
583
584
# File 'app/models/intervention.rb', line 582

def human_doer_names
  doers.map(&:product).compact.map(&:work_name).sort.to_sentence
end

#human_input_quantity_namesObject

Returns human inputs names and quantity


592
593
594
595
596
597
598
# File 'app/models/intervention.rb', line 592

def human_input_quantity_names
  names = []
  inputs.each do |input|
    names << "#{input.name} : #{input.human_quantity}"
  end
  names.sort.to_sentence
end

#human_target_namesObject

Returns human target names


577
578
579
# File 'app/models/intervention.rb', line 577

def human_target_names
  targets_list.to_sentence
end

#human_tool_namesObject

Returns human tool names


587
588
589
# File 'app/models/intervention.rb', line 587

def human_tool_names
  tools.map(&:product).compact.map(&:work_name).sort.to_sentence
end

#human_total_costObject


728
729
730
731
732
# File 'app/models/intervention.rb', line 728

def human_total_cost
  %i[input tool doer].map do |type|
    (cost(type) || 0.0).to_d
  end.sum.round(Nomen::Currency.find(currency).precision)
end

#human_working_duration(unit = :hour) ⇒ Object


615
616
617
# File 'app/models/intervention.rb', line 615

def human_working_duration(unit = :hour)
  working_duration.in(:second).convert(unit).round(2).l
end

#human_working_zone_area(*args) ⇒ Object


784
785
786
787
788
789
# File 'app/models/intervention.rb', line 784

def human_working_zone_area(*args)
  options = args.extract_options!
  unit = args.shift || options[:unit] || :hectare
  precision = args.shift || options[:precision] || 2
  working_zone_area(unit: unit).round(precision).l(precision: precision)
end

#initialize_record(state: :done) ⇒ Object


500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# File 'app/models/intervention.rb', line 500

def initialize_record(state: :done)
  raise 'Can only generate record for an intervention request' unless request?
  return record_interventions.first if record_interventions.any?
  new_record = deep_clone(
    only: %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],
    include:
      [
        { group_parameters: %i[
          parameters
          group_parameters
          doers
          inputs
          outputs
          targets
          tools
        ] },
        { root_parameters: :group },
        { parameters: :group },
        { product_parameters: %i[readings group] },
        { doers: :group },
        { inputs: :group },
        { outputs: :group },
        { targets: :group },
        { tools: :group },
        :working_periods
      ],
    use_dictionary: true
  ) do |original, kopy|
    kopy.intervention_id = nil if original.respond_to? :intervention_id
  end
  new_record.request_intervention_id = id
  new_record.nature = :record
  new_record.state = state
  new_record
end

#nameObject


606
607
608
609
# File 'app/models/intervention.rb', line 606

def name
  # raise self.inspect if self.procedure_name.blank?
  tc(:name, intervention: (procedure ? procedure.human_name : "procedures.#{procedure_name}".t(default: procedure_name.humanize)), number: number)
end

#participation(product) ⇒ Object


890
891
892
# File 'app/models/intervention.rb', line 890

def participation(product)
  InterventionParticipation.of_intervention(self).of_product(product).first
end

#printed_atObject


540
541
542
# File 'app/models/intervention.rb', line 540

def printed_at
  (stopped_at? ? stopped_at : created_at? ? created_at : Time.zone.now)
end

#printed_onObject


544
545
546
# File 'app/models/intervention.rb', line 544

def printed_on
  printed_at.to_date
end

#procedureObject

The Procedo::Procedure behind intervention


561
562
563
# File 'app/models/intervention.rb', line 561

def procedure
  Procedo.find(procedure_name)
end

#receptions_costObject


707
708
709
# File 'app/models/intervention.rb', line 707

def receptions_cost
  receptions.any? ? receptions.sum(:pretax_amount) : 0
end

#receptions_is_given?Boolean

Returns:

  • (Boolean)

855
856
857
858
# File 'app/models/intervention.rb', line 855

def receptions_is_given?
  return receptions.first.given? if receptions.any?
  false
end

#referenceObject

Deprecated method to return procedure


566
567
568
569
570
# File 'app/models/intervention.rb', line 566

def reference
  ActiveSupport::Deprecation.warn 'Intervention#reference is deprecated.' \
                                  'Please use Intervention#procedure instead.'
  procedure
end

#run!Object

Run the intervention ie. the state is marked as done Returns intervention DEPRECATED Will be removed in 3.0


863
864
865
866
867
868
# File 'app/models/intervention.rb', line 863

def run!
  ActiveSupport::Deprecation.warn 'Intervention#run! is deprecated, because it never works. Use classical AR methods instead to create interventions'
  raise 'Cannot run intervention without procedure' unless runnable?
  update_attributes(state: :done)
  self
end

#run_sequenceObject


132
133
134
# File 'app/models/intervention.rb', line 132

def run_sequence
  request_intervention.present?
end

#runnable?Boolean

Returns:

  • (Boolean)

815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
# File 'app/models/intervention.rb', line 815

def runnable?
  return false unless record? && procedure
  valid = true
  # Check cardinality and runnability
  procedure.parameters.each do |parameter|
    all_parameters = parameters.where(reference_name: parameter.name)
    # unless parameter.cardinality.include?(parameters.count)
    #   valid = false
    # end
    all_parameters.each do |parameter|
      valid = false unless parameter.runnable?
    end
  end
  valid
end

#set_numberObject


128
129
130
# File 'app/models/intervention.rb', line 128

def set_number
  self.number = request_intervention.number if request_intervention.present?
end

#start_timeObject


611
612
613
# File 'app/models/intervention.rb', line 611

def start_time
  started_at
end

#statusObject


809
810
811
812
813
# File 'app/models/intervention.rb', line 809

def status
  return :go if done? || validated?
  return :caution if in_progress?
  return :stop if rejected?
end

#targets_listObject


572
573
574
# File 'app/models/intervention.rb', line 572

def targets_list
  targets.includes(:product).map(&:product).compact.map(&:work_name).sort
end

#total_costObject


722
723
724
725
726
# File 'app/models/intervention.rb', line 722

def total_cost
  %i[input tool doer].map do |type|
    (cost(type) || 0.0).to_d
  end.sum + receptions_cost
end

#total_cost_per_area(area_unit = :hectare) ⇒ Object


734
735
736
737
# File 'app/models/intervention.rb', line 734

def total_cost_per_area(area_unit = :hectare)
  zone_area = working_zone_area(area_unit).to_f
  (total_cost / zone_area) * area_cost_coefficient if zone_area > 0.0
end

#update_compliance(modifier = {}) ⇒ Object


882
883
884
885
886
887
888
# File 'app/models/intervention.rb', line 882

def update_compliance(modifier = {})
  return unless participations.any? || !modifier.nil?
  compliances = participations.pluck(:id, :request_compliant).to_h
  compliances[modifier.keys.first] = modifier.values.first
  update(request_compliant: false) if compliances.values.index(false)
  update(request_compliant: true) if (compliances.values - [true]).empty?
end

#update_costingObject


410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'app/models/intervention.rb', line 410

def update_costing
  attributes = {}

  %i[input tool doer].each do |type|
    attributes["#{type.to_s.pluralize}_cost"] = cost(type) || 0
  end
  attributes[:receptions_cost] = receptions_cost.to_f.round(2)

  if costing
    costing.update(attributes)
  else
    update_columns(costing_id: InterventionCosting.create!(attributes))
  end
end

#update_state(modifier = {}) ⇒ Object


874
875
876
877
878
879
880
# File 'app/models/intervention.rb', line 874

def update_state(modifier = {})
  return unless participations.any? || modifier.present?
  states = participations.pluck(:id, :state).to_h
  states[modifier.keys.first] = modifier.values.first
  update(state: :in_progress) if states.values.map(&:to_sym).index(:in_progress)
  update(state: :done) if (states.values.map(&:to_sym) - [:done]).empty?
end

#update_temporalityObject

Update temporality informations in intervention


633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
# File 'app/models/intervention.rb', line 633

def update_temporality
  reload unless new_record? || destroyed?

  if working_periods.any?
    started_at = working_periods.minimum(:started_at)
    stopped_at = working_periods.maximum(:stopped_at)
    update_columns(
      started_at: started_at,
      stopped_at: stopped_at,
      working_duration: working_periods.sum(:duration),
      whole_duration: (stopped_at && started_at ? (stopped_at - started_at).to_i : 0)
    )
  end

  if event
    event.update_columns(
      started_at: self.started_at,
      stopped_at: self.stopped_at
    )
  end

  outputs.find_each do |output|
    product = output.product
    next unless product
    product.born_at = self.started_at
    product.initial_born_at = product.born_at
    product.save!

    reading = product.initial_reading(:shape)
    unless reading.nil?
      reading.read_at = product.born_at
      reading.save!
    end

    movement = output.product_movement
    next unless movement
    movement.started_at = self.started_at
    movement.stopped_at = self.stopped_at
    movement.save!
  end

  inputs.find_each do |input|
    product = input.product
    next unless product

    movement = input.product_movement
    next unless movement
    movement.started_at = self.started_at
    movement.stopped_at = self.stopped_at
    movement.save!
  end
end

#with_undestroyable_products?Boolean

Returns:

  • (Boolean)

548
549
550
551
552
553
# File 'app/models/intervention.rb', line 548

def with_undestroyable_products?
  outputs.includes(:product).map(&:product).detect do |product|
    next unless product
    InterventionProductParameter.of_actor(product).where.not(type: 'InterventionOutput').any?
  end
end

#worker_working_periods(nature: nil, not_nature: nil) ⇒ Object


894
895
896
897
898
899
900
901
902
903
904
905
906
907
# File 'app/models/intervention.rb', line 894

def worker_working_periods(nature: nil, not_nature: nil)
  workers_participations = participations.select { |participation| participation.product.is_a?(Worker) }
  working_periods = nil

  if nature.nil? && not_nature.nil?
    working_periods = workers_participations.map(&:working_periods)
  elsif !nature.nil?
    working_periods = workers_participations.map { |participation| participation.working_periods.where(nature: nature) }
  elsif !not_nature.nil?
    working_periods = workers_participations.map { |participation| participation.working_periods.where.not(nature: not_nature) }
  end

  working_periods.flatten
end

#working_area(unit = :hectare) ⇒ Object


791
792
793
794
# File 'app/models/intervention.rb', line 791

def working_area(unit = :hectare)
  ActiveSupport::Deprecation.warn 'Intervention#working_area is deprecated. Please use Intervention#working_zone_area instead.'
  working_zone_area(unit)
end

#working_duration_of_nature(nature = :intervention) ⇒ Object


619
620
621
# File 'app/models/intervention.rb', line 619

def working_duration_of_nature(nature = :intervention)
  InterventionWorkingPeriod.of_intervention_participations(InterventionParticipation.of_intervention(self)).of_nature(nature).sum(:duration)
end

#working_zone_area(*args) ⇒ Object

return all working zone area of targets


761
762
763
764
765
766
767
768
769
770
# File 'app/models/intervention.rb', line 761

def working_zone_area(*args)
  options = args.extract_options!
  unit = args.shift || options[:unit] || :hectare
  area = if targets.any?
           targets.with_working_zone.map(&:working_zone_area).sum.in(unit)
         else
           0.0.in(unit)
         end
  area
end