class Section include SimplyStored::Couch property :title property :path, type: Array, default: [] belongs_to :supplier has_many :tables has_many :lists has_many :orders attr_protected :supplier_id validates :supplier_id, presence: true # Probably faster to directly retreive the document and return nil # if the supplier does not match def self.find_by_supplier_and_id(supplier, id) section = find(id) return nil unless section.supplier_id == supplier.id section end def occupied_tables return @occupied_tables if @occupied_tables.present? @active_lists = List.active_for_section(self.id) @active_lists.include_relation(:table) @occupied_tables = @active_lists.map(&:table) end def active_lists return @active_lists if @active_lists.present? @active_lists = List.active_for_section(self.id) end def width self.path.last.try(:first).to_f - self.path.first.try(:first).to_f end def height self.path.last.try(:last).to_f - self.path.first.try(:last).to_f end def width=(val) val = val.to_f self.path[0] ||= [0.0, 0.0] self.path[1] ||= [0.0, 0.0] unless path[1][0] == val self.path[1][0] = val path_will_change! end end def height=(val) val = val.to_f self.path[0] ||= [0.0, 0.0] self.path[1] ||= [0.0, 0.0] unless path[1][1] == val self.path[1][1] = val path_will_change! end end def as_json super.merge(width: width, height: height) end def for_tables_as_json return @for_tables_as_json if @for_tables_as_json.present? h = as_json h[:tables] = [] for table in tables ht = table.as_json ht[:occupied] = occupied_tables.include?(table) ht[:needs_help] = ht[:occupied] ? active_lists.find{|l| l.table_id == table.id}.try(:needs_help).present? : false ht[:needs_payment] = ht[:occupied] ? active_lists.find{|l| l.table_id == table.id}.try(:needs_payment).present? : false h[:tables] << ht end @for_tables_as_json = h end end