module Comee module Core class MasterPrice < Price before_save :set_default_currency enum :price_status, {draft: 0, approved: 1} belongs_to :supplier belongs_to :previous_price, class_name: "Comee::Core::MasterPrice", optional: true belongs_to :next_price, class_name: "Comee::Core::MasterPrice", optional: true belongs_to :country_of_origin, -> { where(lookup_type: :country) }, class_name: "Comee::Core::Lookup", optional: true belongs_to :product_lookup, optional: true belongs_to :currency, optional: true validates :purchase_price, :selling_price, presence: true validates :margin, presence: true, numericality: {greater_than_or_equal_to: 0, less_than_or_equal_to: 100} validates :product_id, uniqueness: {scope: %i[supplier_id previous_price_id next_price_id status]} validate :validate_primary_price, :validate_product_lookup scope :current_primary, -> { where(primary: true).current } scope :unapplied, -> { where(propagated_to_client: false).current_primary } def self.product_price(product_id) MasterPrice.find_by( product_id: product_id, primary: true, status: Price.statuses[:current] ) end def validate_primary_price return unless product && primary price = MasterPrice.find_by(product: product, primary: true, status: Price.statuses[:current]) return unless price && price.id != id && status == price.status errors.add(:base, "There is already a primary price entry for item '#{product.code}'") end def validate_product_lookup return unless product_lookup && product && supplier if product_lookup.itemable_id != supplier_id || product_lookup.itemable_type != "Comee::Core::Supplier" || product_lookup.product_id != product_id errors.add(:product_lookup, "contains wrong supplier or product.") end end def set_default_currency return if currency self.currency = Comee::Core::Currency.find_by(code: "EUR") end def self.ransackable_attributes(_auth_object = nil) %w[ id valid_from valid_to purchase_price selling_price status product_id supplier_id previous_price_id next_price_id ] end def self.ransackable_associations(_auth_object = nil) %w[product supplier product_lookup] end end end end