class PreSale < ActiveRecord::Base belongs_to :customer belongs_to :user belongs_to :open_cash_register belongs_to :product belongs_to :special_price has_one :cash_register, through: :open_cash_register has_one :pointsale, through: :cash_register enum sale_type: [:credit, :cash, :reserved] validates :customer_id, presence: { message: "Debe seleccionar cliente para la venta." }, on: [:create, :update] validates :open_cash_register_id, presence: { message: "Debe seleccionar caja registradora." }, on: [:create, :update] validates :sale_type, presence: { message: "Debe seleccionar tipo de venta." }, on: [:create, :update] # before_save :get_totals def get_totals promotion = product.get_promotion special_price = SpecialPrice.find_by(customer_id: customer_id, product_id: product_id) discount_per_unit = if promotion.present? self.promotion_id = promotion.id (promotion.percent / 100) * unit_price elsif special_price.present? self.special_price_id = special_price.id special_price.get_unit_discount(unit_price) else 0 end self.unit_price_w_discount = (unit_price - discount_per_unit).round(2) self.discount = (discount_per_unit * quantity).round(2) self.amount = (quantity * unit_price_w_discount) self.tax = 0.0 if product.include_sale_tax? self.tax = ((PosConfig.first.tax_percent / 100) * amount).round(2) end haggle_discount = if haggle > 0 haggle.round(2) elsif haggle_percent > 0 ((haggle_percent.to_f / 100) * amount).round(2) else 0 end self.amount -= haggle_discount if haggle_discount.present? self.total = amount + tax true end end