summaryrefslogtreecommitdiff
path: root/app/services/alert_management/update_alert_status_service.rb
blob: a7ebddb82e05d6dc46a275ab296d547389b4fe12 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# frozen_string_literal: true

module AlertManagement
  class UpdateAlertStatusService
    include Gitlab::Utils::StrongMemoize

    # @param alert [AlertManagement::Alert]
    # @param user [User]
    # @param status [Integer] Must match a value from AlertManagement::Alert::STATUSES
    def initialize(alert, user, status)
      @alert = alert
      @user = user
      @status = status
    end

    def execute
      return error_no_permissions unless allowed?
      return error_invalid_status unless status_key

      if alert.update(status_event: status_event)
        success
      else
        error(alert.errors.full_messages.to_sentence)
      end
    end

    private

    attr_reader :alert, :user, :status

    delegate :project, to: :alert

    def allowed?
      user.can?(:update_alert_management_alert, project)
    end

    def status_key
      strong_memoize(:status_key) do
        AlertManagement::Alert::STATUSES.key(status)
      end
    end

    def status_event
      AlertManagement::Alert::STATUS_EVENTS[status_key]
    end

    def success
      ServiceResponse.success(payload: { alert: alert })
    end

    def error_no_permissions
      error(_('You have no permissions'))
    end

    def error_invalid_status
      error(_('Invalid status'))
    end

    def error(message)
      ServiceResponse.error(payload: { alert: alert }, message: message)
    end
  end
end