Sha256: b75433b317b0b602475fe370d8365eedea621ffbba81247d9a999a2efe110536

Contents?: true

Size: 1.41 KB

Versions: 2

Compression:

Stored size: 1.41 KB

Contents

module Comee
  module Core
    class MasterPrice < ApplicationRecord
      belongs_to :supplier
      belongs_to :product
      belongs_to :previous_price, class_name: "Comee::Core::MasterPrice", optional: true

      validates :purchase_price, :selling_price, :pp_valid_from, :pp_valid_to, :sp_valid_from, :sp_valid_to, presence: true
      validates :margin, presence: true, numericality: {greater_than_or_equal_to: 0, less_than_or_equal_to: 100}
      validates :product_id, uniqueness: {scope: :supplier_id}
      validate :validate_primary_price, :validate_purchase_price_validity_dates, :validate_selling_price_validity_dates

      def validate_primary_price
        return unless product && primary

        count = MasterPrice.where(product:, primary: true).count
        errors.add(:base, "There is already a primary supplier for item '#{product.code}'") if count.positive?
      end

      def validate_purchase_price_validity_dates
        return unless pp_valid_from && pp_valid_to

        period = Period.new(pp_valid_from, pp_valid_to)
        errors.add(:base, "Purchase price validity date range is not correct.") unless period.valid?
      end

      def validate_selling_price_validity_dates
        return unless sp_valid_from && sp_valid_to

        period = Period.new(sp_valid_from, sp_valid_to)
        errors.add(:base, "Selling price validity date range is not correct.") unless period.valid?
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
comee_core-0.1.15 app/models/comee/core/master_price.rb
comee_core-0.1.14 app/models/comee/core/master_price.rb