cyri113 / shiny-rails

0 stars 1 forks source link

Discounts feature #74

Open cyri113 opened 7 years ago

cyri113 commented 7 years ago

Use Cases:

  1. Frequency: Depending on the frequency selected, a discount should be applied
  2. Coupon: When a valid coupon is entered, the discount should be applied
  3. Product: When a product is selected, any associated Discounts should be applied
  4. User: When a given user is ordering, any associated Discounts should be applied

Rules:

Models:

Frequency


@weekly = Discount.create(name: 'Weekly', description: 'A professional will clean once a week', discount_type: :percentage, amount: 0.3, category: :frequency)
@weekly.update_attributes(locale: :de, name: 'Wöchentlich', description: 'Ein Profi wird einmal wöchentlich reinigen')
@2weeks = Discount.create(name: 'Every 2 Weeks', description: 'A professional will clean every 2 weeks', discount_type: :percentage, amount: 0.3, category: :frequency)
@2weeks.update_attributes(locale: :de, name: 'Alle 2 Wochen', description: 'Ein Profi wird alle 2 Wochen reinigen')
cyri113 commented 7 years ago

Models:


class Cart
  has_many :discount_items, dependent: :destroy
  has_many :discounts, through: :discount_items

  def total_discount
    total_discount = discounts.sum(&total_discount)
    total_discount = total_price if discount > total_price
    total_discount
  end

end

class Discount
  has_many :discount_items
  has_many :carts, through: :discount_items

  before_destroy :ensure_not_referenced_by_any_discount_item

  private

  # ensure that there are not discount items referencing this product
  def ensure_not_referenced_by_any_discount_item
    unless discount_items.empty?
      errors.add(:base, 'Discount Items present')
      throw :abort
    end
  end
end

class DiscountItem
  belongs_to :discount
  belongs_to :cart
  def total_discount
    total_discount = discount.amount
    total_discount = discount.amount * cart.total_price if discount.discount_type == :percentage
    total_discount
  end

end
cyri113 commented 7 years ago

Tests

cyri113 commented 7 years ago

Future: