Class: FlashSale

Inherits:
ApplicationRecord show all
Defined in:
app/models/flash_sale.rb

Overview

Schema Information

Table name: flash_sales

id         :bigint           not null, primary key
end_at     :datetime
slot_date  :date
start_at   :datetime
created_at :datetime         not null
updated_at :datetime         not null
outlet1_id :integer
outlet2_id :integer
outlet3_id :integer

Indexes

index_flash_sales_on_outlet1_id  (outlet1_id)
index_flash_sales_on_outlet2_id  (outlet2_id)
index_flash_sales_on_outlet3_id  (outlet3_id)
index_flash_sales_on_slot_date   (slot_date) UNIQUE

Foreign Keys

fk_rails_...  (outlet1_id => restaurants.id)
fk_rails_...  (outlet2_id => restaurants.id)
fk_rails_...  (outlet3_id => restaurants.id)

Constant Summary collapse

TIMEZONE =
'Asia/Bangkok'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from ApplicationRecord

sync_carrierwave_url

Class Method Details

.active_scopeObject



43
44
45
46
47
48
# File 'app/models/flash_sale.rb', line 43

def self.active_scope
  now = Time.use_zone(FlashSale::TIMEZONE) { Time.zone.now }
  current_time = now.strftime('%Y-%m-%d %H:%M').to_datetime

  where('start_at <= ? AND end_at >= ?', current_time, current_time).first
end

.flash_sale_outlet_idsObject



50
51
52
# File 'app/models/flash_sale.rb', line 50

def self.flash_sale_outlet_ids
  [active_scope&.outlet1_id, active_scope&.outlet2_id, active_scope&.outlet3_id].compact
end

Instance Method Details

#statusObject



54
55
56
57
58
59
60
61
62
63
64
# File 'app/models/flash_sale.rb', line 54

def status
  now = Time.thai_time.to_datetime
  timezone = ActiveSupport::TimeZone.new(FlashSale::TIMEZONE)

  start_at_in_tz = timezone.strptime("#{slot_date} 09:00", '%Y-%m-%d %H:%M')
  end_at_in_tz = timezone.strptime("#{slot_date + 1.day} 08:59", '%Y-%m-%d %H:%M')
  return 'active' if start_at_in_tz <= now && end_at_in_tz >= now
  return 'upcoming' if slot_date > now

  'past'
end