Sha256: 6288328625ffc8fe84c623cdfa6b0c89d1ffc9515470a89a9d03c79d0b4bbec4

Contents?: true

Size: 1.82 KB

Versions: 1

Compression:

Stored size: 1.82 KB

Contents

module Comee
  module Core
    class MasterPrice < Price
      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

      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

      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])
        Rails.logger.info("Existing price: ")
        Rails.logger.info(price)
        Rails.logger.info("Current price:")
        Rails.logger.info(self)
        return unless price && price.id != id

        Rails.logger.info("RAISING ERROR ...")
        errors.add(:base, "There is already a primary price entry for item '#{product.code}'")
      end

      def self.ransackable_attributes(_auth_object = nil)
        %w[
          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]
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
comee_core-0.1.45.pre2 app/models/comee/core/master_price.rb