summaryrefslogtreecommitdiff
path: root/app/services/alert_management/http_integrations/create_service.rb
blob: 1abe0548c453de23d31e8552f89b24d8f74a8ee9 (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
64
65
66
67
68
69
# frozen_string_literal: true

module AlertManagement
  module HttpIntegrations
    class CreateService
      # @param project [Project]
      # @param current_user [User]
      # @param params [Hash]
      def initialize(project, current_user, params)
        @project = project
        @current_user = current_user
        @params = params.with_indifferent_access
      end

      def execute
        return error_no_permissions unless allowed?
        return error_multiple_integrations unless creation_allowed?

        integration = project.alert_management_http_integrations.create(permitted_params)
        return error_in_create(integration) unless integration.valid?

        success(integration)
      end

      private

      attr_reader :project, :current_user, :params

      def allowed?
        current_user&.can?(:admin_operations, project)
      end

      def creation_allowed?
        project.alert_management_http_integrations.empty?
      end

      def permitted_params
        params.slice(*permitted_params_keys)
      end

      # overriden in EE
      def permitted_params_keys
        %i[name active]
      end

      def error(message)
        ServiceResponse.error(message: message)
      end

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

      def error_no_permissions
        error(_('You have insufficient permissions to create an HTTP integration for this project'))
      end

      def error_multiple_integrations
        error(_('Multiple HTTP integrations are not supported for this project'))
      end

      def error_in_create(integration)
        error(integration.errors.full_messages.to_sentence)
      end
    end
  end
end

::AlertManagement::HttpIntegrations::CreateService.prepend_mod_with('AlertManagement::HttpIntegrations::CreateService')