promotion.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. class Promotion < ActiveRecord::Base
  2. ##--- Llevar registro de Actividad del usuario
  3. audited
  4. belongs_to :product
  5. belongs_to :category
  6. # belongs_to :subcategory_id, class_name: "Category"
  7. enum status: [:inactive, :active]
  8. validates_presence_of :start_date, message: "Debe indicar fecha de inicio de la promoción."
  9. validates_presence_of :end_date, message: "Debe indicar fecha de término de la promoción."
  10. validates_presence_of :percent, message: "Debe indicar el porcentaje de descuento de la promoción."
  11. validates :percent, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 100 }
  12. validate :start_end_date, on: [:create]
  13. validate :start_date_greater_than_end_date, if: proc { |p| p.start_date.present? && p.end_date.present? }
  14. validate :promotion_source
  15. validate :check_for_duplicates
  16. scope :activas, -> { where(status: 1) }
  17. scope :vigentes, -> { where("? between start_date and end_date", Date.today) }
  18. def verify_promotion
  19. is_active = end_date >= Date.today
  20. unless is_active
  21. update_attribute(:status, :inactive)
  22. end
  23. end
  24. def start_end_date
  25. if end_date.present? && end_date < Date.today
  26. errors.add(:end_date, "La fecha de fin debe ser mayor a hoy.")
  27. end
  28. end
  29. def start_date_greater_than_end_date
  30. if end_date < start_date
  31. errors.add(:start_date, 'La fecha de inicio debe ser mayor a la fecha de término de la promoción.')
  32. end
  33. end
  34. def promotion_source
  35. if product_id.blank? && category_id.blank?
  36. errors.add(:base, 'Seleccione una opción entre línea o producto.')
  37. end
  38. end
  39. def check_for_duplicates
  40. source =
  41. if category_id.present?
  42. "category_id = #{category_id}"
  43. elsif subcategory_id.present? && subcategory_id != "0"
  44. "subcategory_id = #{subcategory_id}"
  45. elsif product_id.present?
  46. "product_id = #{product_id}"
  47. end
  48. if source
  49. exists_already = Promotion.activas.where(source).where("start_date < ? AND end_date > ?", end_date, start_date).any?
  50. errors.add(:base, 'Ya existe una promoción activa con los parámetros seleccionados') if exists_already
  51. end
  52. end
  53. end