2014-08-28 15:21:05 +02:00
|
|
|
class TicketPurchase < ActiveRecord::Base
|
|
|
|
|
belongs_to :ticket
|
|
|
|
|
belongs_to :user
|
|
|
|
|
belongs_to :conference
|
|
|
|
|
|
|
|
|
|
validates :ticket_id, :user_id, :conference_id, :quantity, presence: true
|
|
|
|
|
|
|
|
|
|
validates_numericality_of :quantity, greater_than: 0
|
|
|
|
|
|
2014-12-05 16:04:34 +01:00
|
|
|
delegate :title, to: :ticket
|
|
|
|
|
delegate :description, to: :ticket
|
|
|
|
|
delegate :price, to: :ticket
|
|
|
|
|
delegate :price_cents, to: :ticket
|
|
|
|
|
delegate :price_currency, to: :ticket
|
|
|
|
|
|
2016-07-27 19:41:42 +05:30
|
|
|
scope :paid, -> { where(paid: true) }
|
|
|
|
|
scope :unpaid, -> { where(paid: false) }
|
|
|
|
|
scope :by_conference, -> (conference) { where(conference_id: conference.id) }
|
|
|
|
|
scope :by_user, -> (user) { where(user_id: user.id) }
|
|
|
|
|
|
2014-08-28 15:21:05 +02:00
|
|
|
def self.purchase(conference, user, purchases)
|
|
|
|
|
errors = []
|
|
|
|
|
ActiveRecord::Base.transaction do
|
|
|
|
|
conference.tickets.each do |ticket|
|
|
|
|
|
quantity = purchases[ticket.id.to_s].to_i
|
2016-08-02 01:37:55 +05:30
|
|
|
# if the user bought the ticket and is still unpaid, just update the quantity
|
2016-07-27 19:41:42 +05:30
|
|
|
if ticket.bought?(user) && ticket.unpaid?(user)
|
2014-08-28 15:21:05 +02:00
|
|
|
purchase = update_quantity(conference, quantity, ticket, user)
|
|
|
|
|
else
|
|
|
|
|
purchase = purchase_ticket(conference, quantity, ticket, user)
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
if purchase && !purchase.save
|
|
|
|
|
errors.push(purchase.errors.full_messages)
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
errors.join('. ')
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
def self.purchase_ticket(conference, quantity, ticket, user)
|
2016-08-02 01:37:55 +05:30
|
|
|
if quantity > 0
|
|
|
|
|
if ticket.price_cents.zero?
|
|
|
|
|
purchase = new(ticket_id: ticket.id,
|
|
|
|
|
conference_id: conference.id,
|
|
|
|
|
user_id: user.id,
|
|
|
|
|
quantity: quantity,
|
|
|
|
|
paid: true)
|
|
|
|
|
else
|
|
|
|
|
purchase = new(ticket_id: ticket.id,
|
|
|
|
|
conference_id: conference.id,
|
|
|
|
|
user_id: user.id,
|
|
|
|
|
quantity: quantity)
|
|
|
|
|
end
|
|
|
|
|
end
|
2014-08-28 15:21:05 +02:00
|
|
|
purchase
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
def self.update_quantity(conference, quantity, ticket, user)
|
|
|
|
|
purchase = TicketPurchase.where(ticket_id: ticket.id,
|
|
|
|
|
conference_id: conference.id,
|
2016-07-27 19:41:42 +05:30
|
|
|
user_id: user.id,
|
|
|
|
|
paid: false).first
|
2014-08-28 15:21:05 +02:00
|
|
|
|
|
|
|
|
purchase.quantity = quantity if quantity > 0
|
|
|
|
|
purchase
|
|
|
|
|
end
|
|
|
|
|
end
|