Files
sx-fc/app/models/menu_category.rb
2018-03-16 17:41:30 +06:30

102 lines
3.0 KiB
Ruby
Executable File

class MenuCategory < ApplicationRecord
# before_create :generate_menu_category_code
belongs_to :menu , counter_cache: true
has_many :children, :class_name => "MenuCategory", foreign_key: "menu_category_id"
belongs_to :parent, :class_name => "MenuCategory", foreign_key: "menu_category_id", optional: true
has_many :menu_items
validates_presence_of :code, :name, :menu, :order_by
validates_uniqueness_of :code
default_scope { order('order_by asc') }
scope :active, -> {where("is_available = 1")}
def self.destroyCategory(menu_category)
# find the sub menu item of current item
sub_menu_cat = MenuCategory.where("menu_category_id=?",menu_category.id)
if sub_menu_cat.length != 0
sub_menu_cat.each do |sub|
if destroyCategory(sub)
end
end
# find the items of current menu item
items = MenuItem.where("menu_category_id=?",menu_category.id)
items.each do |item|
abc = MenuItem.deleteRecursive(item)
end
menu_category.destroy
return true
else
items = MenuItem.where("menu_category_id=?",menu_category.id)
items.each do |item|
abc = MenuItem.deleteRecursive(item)
end
menu_category.destroy
return false
end
end
def valid_time
menu_category = MenuCategory.find(self.id)
menu = Menu.find(menu_category.menu_id)
from_t = Time.parse(menu.valid_time_from.strftime("%H:%M:%S"))
to_t = Time.parse(menu.valid_time_to.strftime("%H:%M:%S"))
current_t = Time.parse(Time.now.utc.getlocal.strftime("%H:%M:%S"))
from = from_t.hour * 3600 + from_t.min*60 + from_t.sec
to = to_t.hour * 3600 + to_t.min* 60 + to_t.sec
current = current_t.hour * 3600 + current_t.min*60+current_t.sec
if from > to
h = to_t.hour
if h < 12 # before noon
if h == 0
to = 24
to = to * 3600 + to_t.min* 60 + to_t.sec
end
else # (after) noon
if h > 12
to -= 12
to = to * 3600 + to_t.min* 60 + to_t.sec
end
end
end
# from = from.split(':').map { |a| a.to_i }.inject(0) { |a, b| a * 60 + b}
# to = to.split(':').map { |a| a.to_i }.inject(0) { |a, b| a * 60 + b}
# current = current.split(':').map { |a| a.to_i }.inject(0) { |a, b| a * 60 + b}
day = Date.today.wday
dayresult = menu.valid_days.include?(day.to_s)
if current.between?(from, to) && menu.valid_days.include?(day.to_s)
return true
else
return nil
end
end
private
# def generate_menu_category_code
# self.code = SeedGenerator.generate_code(self.class.name, "C")
# end
def self.to_csv
mc_attributes = %w{id menu_id code name alt_name order_by created_by menu_category_id is_available created_at updated_at}
CSV.generate(headers: true) do |csv|
csv << mc_attributes
csv << mc_attributes
MenuCategory.all.each do |user|
puts user
csv << mc_attributes.map{ |attr| user.send(attr)}
end
end
end
end