50 lines
1.2 KiB
Ruby
Executable File
50 lines
1.2 KiB
Ruby
Executable File
class Ticket < ApplicationRecord
|
|
# Associations
|
|
belongs_to :user
|
|
belongs_to :ticket_type
|
|
has_one :event, through: :ticket_type
|
|
|
|
# Validations
|
|
validates :qr_code, presence: true, uniqueness: true
|
|
validates :user_id, presence: true
|
|
validates :ticket_type_id, presence: true
|
|
validates :price_cents, presence: true, numericality: { greater_than: 0 }
|
|
validates :status, presence: true, inclusion: { in: %w[active used expired refunded] }
|
|
validates :first_name, presence: true, if: :requires_names?
|
|
validates :last_name, presence: true, if: :requires_names?
|
|
|
|
before_validation :set_price_from_ticket_type, on: :create
|
|
before_validation :generate_qr_code, on: :create
|
|
|
|
# Generate PDF ticket
|
|
def to_pdf
|
|
TicketPdfGenerator.new(self).generate
|
|
end
|
|
|
|
# Price in euros (formatted)
|
|
def price_euros
|
|
price_cents / 100.0
|
|
end
|
|
|
|
# Check if names are required for this ticket type
|
|
def requires_names?
|
|
ticket_type&.requires_id
|
|
end
|
|
|
|
private
|
|
|
|
def set_price_from_ticket_type
|
|
return unless ticket_type
|
|
self.price_cents = ticket_type.price_cents
|
|
end
|
|
|
|
def generate_qr_code
|
|
return if qr_code.present?
|
|
|
|
loop do
|
|
self.qr_code = SecureRandom.uuid
|
|
break unless Ticket.exists?(qr_code: qr_code)
|
|
end
|
|
end
|
|
end
|