require 'subj_models/concerns/comprising_external_id' require 'subj_models/services/values_checker' module SubjModels module OrderItemModule include SubjModels::TypesSupport::ItemTypes include SubjModels::ValuesChecker def self.included(including_class) including_class.class_eval do include SubjModels::ComprisingExternalId before_destroy :decrease_nomenclature_popularity after_create :increase_nomenclature_popularity enum item_type: ITEM_TYPES belongs_to :order belongs_to :event belongs_to :nomenclature_variety belongs_to :nomenclature validates :item_type, presence: true, inclusion: { in: item_types.keys } validates :item_price, :item_count, presence: true scope :order_id, -> (order_id) { parent_id_scope("order", order_id) } end end def to_s id.to_s # TODO end def item_type=(value) super(check_string_for_int(value)) end private def increase_nomenclature_popularity if nomenclature current_popularity = (nomenclature.popularity && nomenclature.popularity > 0) ? nomenclature.popularity : 0 nomenclature.update(popularity: current_popularity + item_count) end end def decrease_nomenclature_popularity if nomenclature current_popularity = (nomenclature.popularity && nomenclature.popularity > item_count) ? nomenclature.popularity : item_count nomenclature.update(popularity: current_popularity - item_count) end end def update_nomenclature_popularity if nomenclature current_popularity = (nomenclature.popularity && nomenclature.popularity > 0) ? nomenclature.popularity : 0 method = transaction_include_any_action?([:create]) ? :+ : :- new_popularity = current_popularity.send(method, self.item_count) nomenclature.update(popularity: new_popularity) end end def add_nomenclature_quality founded_quality_id = if nomenclature_variety nomenclature_variety.nomenclature_price.try(:quality_id) else nomenclature.nomenclature_prices.try(:last).try(:quality_id) end self.quality_id = founded_quality_id if founded_quality_id end end end