class PrePurchase < ActiveRecord::Base
  belongs_to :supplier
  belongs_to :user
  belongs_to :pointsale
  belongs_to :product
  belongs_to :warehouse

  validates :supplier_id, presence: { message: "Debe seleccionar proveedor para la compra." }, on: [:create, :update]
  validates :product_id, presence: { message: "Debe seleccionar producto para la compra." }, on: [:create, :update]
  validates :pointsale_id, presence: { message: "Debe seleccionar un almacén o un punto de venta." }, if: Proc.new { |c| c.warehouse_id.blank? }, on: [:create, :update]
  validates :warehouse_id, presence: { message: "Debe seleccionar un almacén o un punto de venta." }, if: Proc.new { |c| c.pointsale_id.blank? }, on: [:create, :update]

  def get_totals
    self.price_base =
      if exchange.present?
        product.price_base_dollars
      else
        product.price_base
      end
    self.price_base = 0 if price_base.nil?

    self.amount = quantity * price_base
    self.tax = 0.0
    if product.include_purchase_tax? && exchange.blank?
      tax_percent = PosConfig.first.tax_percent
      self.tax = (((tax_percent / 100)  * amount) / ((100 + tax_percent) / 100)).round(2)
    end
    self.total = tax + amount
    true
  end
end
