Sha256: 9385f008333b3b07f5c6c9edc943c7e34b3efb74c3215e2668df66a32bd3b1d6

Contents?: true

Size: 1.77 KB

Versions: 1

Compression:

Stored size: 1.77 KB

Contents

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

    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 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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
subj_models-0.6.0 lib/subj_models/order_item.rb