BigW Consortium Gitlab

notification_setting.rb 1.99 KB
Newer Older
1
class NotificationSetting < ActiveRecord::Base
2
  enum level: { global: 3, watch: 2, mention: 4, participating: 1, disabled: 0, custom: 5 }
3 4 5

  default_value_for :level, NotificationSetting.levels[:global]

6 7
  belongs_to :user
  belongs_to :source, polymorphic: true
8
  belongs_to :project, foreign_key: 'source_id'
9 10 11 12 13 14

  validates :user, presence: true
  validates :level, presence: true
  validates :user_id, uniqueness: { scope: [:source_type, :source_id],
                                    message: "already exists in source",
                                    allow_nil: true }
15 16

  scope :for_groups, -> { where(source_type: 'Namespace') }
17 18 19 20 21 22 23

  # Exclude projects not included by the Project model's default scope (those that are
  # pending delete).
  #
  scope :for_projects, -> do
    includes(:project).references(:projects).where(source_type: 'Project').where.not(projects: { id: nil })
  end
24

25 26 27 28 29 30 31 32 33 34
  EMAIL_EVENTS = [
    :new_note,
    :new_issue,
    :reopen_issue,
    :close_issue,
    :reassign_issue,
    :new_merge_request,
    :reopen_merge_request,
    :close_merge_request,
    :reassign_merge_request,
35 36 37
    :merge_merge_request,
    :failed_pipeline,
    :success_pipeline
38 39
  ]

40 41 42 43
  EXCLUDED_WATCHER_EVENTS = [
    :success_pipeline
  ]

44 45 46 47 48
  store :events, accessors: EMAIL_EVENTS, coder: JSON

  before_create :set_events
  before_save :events_to_boolean

49 50 51 52 53 54 55 56 57
  def self.find_or_create_for(source)
    setting = find_or_initialize_by(source: source)

    unless setting.persisted?
      setting.save
    end

    setting
  end
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

  # Set all event attributes to false when level is not custom or being initialized for UX reasons
  def set_events
    return if custom?

    EMAIL_EVENTS.each do |event|
      events[event] = false
    end
  end

  # Validates store accessors values as boolean
  # It is a text field so it does not cast correct boolean values in JSON
  def events_to_boolean
    EMAIL_EVENTS.each do |event|
      events[event] = ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES.include?(events[event])
    end
  end
75
end