1 # frozen_string_literal: true
 
   3 # == Schema Information
 
   7 #  id          :bigint           not null, primary key
 
   8 #  latitude    :integer          not null
 
   9 #  longitude   :integer          not null
 
  10 #  tile        :bigint           not null
 
  11 #  updated_at  :datetime         not null
 
  12 #  created_at  :datetime         not null
 
  13 #  status      :enum             not null
 
  15 #  description :text             default(""), not null
 
  21 #  index_notes_on_description             (to_tsvector('english'::regconfig, description)) USING gin
 
  22 #  index_notes_on_user_id_and_created_at  (user_id,created_at) WHERE (user_id IS NOT NULL)
 
  23 #  notes_created_at_idx                   (created_at)
 
  24 #  notes_tile_status_idx                  (tile,status)
 
  25 #  notes_updated_at_idx                   (updated_at)
 
  29 #  notes_user_id_fkey  (user_id => users.id)
 
  32 class Note < ApplicationRecord
 
  35   belongs_to :author, :class_name => "User", :foreign_key => "user_id", :optional => true
 
  37   has_many :comments, -> { left_joins(:author).where(:visible => true, :users => { :status => [nil, "active", "confirmed"] }).order(:created_at) }, :class_name => "NoteComment", :foreign_key => :note_id
 
  38   has_many :all_comments, -> { left_joins(:author).order(:created_at) }, :class_name => "NoteComment", :foreign_key => :note_id, :inverse_of => :note
 
  39   has_many :subscriptions, :class_name => "NoteSubscription"
 
  40   has_many :subscribers, :through => :subscriptions, :source => :user
 
  42   validates :id, :uniqueness => true, :presence => { :on => :update },
 
  43                  :numericality => { :on => :update, :only_integer => true }
 
  44   validates :latitude, :longitude, :numericality => { :only_integer => true }
 
  45   validates :closed_at, :presence => true, :if => proc { :status == "closed" }
 
  46   validates :status, :inclusion => %w[open closed hidden]
 
  48   validate :validate_position
 
  50   scope :visible, -> { where.not(:status => "hidden") }
 
  51   scope :invisible, -> { where(:status => "hidden") }
 
  53   after_initialize :set_defaults
 
  55   DEFAULT_FRESHLY_CLOSED_LIMIT = 7.days
 
  57   # Sanity check the latitude and longitude and add an error if it's broken
 
  59     errors.add(:base, "Note is not in the world") unless in_world?
 
  64     self.status = "closed"
 
  65     self.closed_at = Time.now.utc
 
  76   # Check if a note is visible
 
  81   # Check if a note is closed
 
  87     return false unless closed?
 
  89     Time.now.utc < freshly_closed_until
 
  92   def freshly_closed_until
 
  93     return nil unless closed?
 
  95     closed_at + DEFAULT_FRESHLY_CLOSED_LIMIT
 
  98   # Return the note's description
 
 100     RichText.new("text", super)
 
 105   # Fill in default values for new notes
 
 107     self.status = "open" unless attribute_present?(:status)