feat: Add promotion code functionality to ticket orders
This commit is contained in:
@@ -7,6 +7,8 @@ class Order < ApplicationRecord
|
||||
belongs_to :user
|
||||
belongs_to :event
|
||||
has_many :tickets, dependent: :destroy
|
||||
has_many :order_promotion_codes, dependent: :destroy
|
||||
has_many :promotion_codes, through: :order_promotion_codes
|
||||
|
||||
# === Validations ===
|
||||
validates :user_id, presence: true
|
||||
|
||||
26
app/models/order_promotion_code.rb
Normal file
26
app/models/order_promotion_code.rb
Normal file
@@ -0,0 +1,26 @@
|
||||
class OrderPromotionCode < ApplicationRecord
|
||||
# Associations
|
||||
belongs_to :order
|
||||
belongs_to :promotion_code
|
||||
|
||||
# Validations
|
||||
validates :order, presence: true
|
||||
validates :promotion_code, presence: true
|
||||
|
||||
# Callbacks
|
||||
after_create :apply_discount
|
||||
after_create :increment_promotion_code_uses
|
||||
|
||||
private
|
||||
|
||||
def apply_discount
|
||||
# Apply the discount to the order
|
||||
discount_amount = promotion_code.discount_amount_cents
|
||||
order.update!(total_amount_cents: [ order.total_amount_cents - discount_amount, 0 ].max)
|
||||
end
|
||||
|
||||
def increment_promotion_code_uses
|
||||
# Increment the uses count on the promotion code
|
||||
promotion_code.increment!(:uses_count)
|
||||
end
|
||||
end
|
||||
23
app/models/promotion_code.rb
Normal file
23
app/models/promotion_code.rb
Normal file
@@ -0,0 +1,23 @@
|
||||
class PromotionCode < ApplicationRecord
|
||||
# Validations
|
||||
validates :code, presence: true, uniqueness: true
|
||||
validates :discount_amount_cents, numericality: { greater_than_or_equal_to: 0 }
|
||||
|
||||
# Scopes
|
||||
scope :active, -> { where(active: true) }
|
||||
scope :expired, -> { where("expires_at < ? OR active = ?", Time.current, false) }
|
||||
scope :valid, -> { active.where("expires_at > ? OR expires_at IS NULL", Time.current) }
|
||||
|
||||
# Callbacks
|
||||
before_create :increment_uses_count
|
||||
|
||||
# Associations
|
||||
has_many :order_promotion_codes
|
||||
has_many :orders, through: :order_promotion_codes
|
||||
|
||||
private
|
||||
|
||||
def increment_uses_count
|
||||
self.uses_count ||= 0
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user