summaryrefslogtreecommitdiff
path: root/app/services/jira_connect_installations/update_service.rb
blob: b2b6f2a91f26fd7b7855df571b07e4ab11d9aa1b (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
# frozen_string_literal: true

module JiraConnectInstallations
  class UpdateService
    def self.execute(installation, update_params)
      new(installation, update_params).execute
    end

    def initialize(installation, update_params)
      @installation = installation
      @update_params = update_params
    end

    def execute
      return update_error unless @installation.update(@update_params)

      if @installation.instance_url?
        hook_result = ProxyLifecycleEventService.execute(@installation, :installed, @installation.instance_url)

        if instance_url_changed? && hook_result.error?
          @installation.update!(instance_url: @installation.instance_url_before_last_save)

          return instance_installation_creation_error(hook_result.message)
        end
      end

      send_uninstalled_hook if instance_url_changed?

      ServiceResponse.new(status: :success)
    end

    private

    def instance_url_changed?
      @installation.instance_url_before_last_save != @installation.instance_url
    end

    def send_uninstalled_hook
      return if @installation.instance_url_before_last_save.blank?

      JiraConnect::SendUninstalledHookWorker.perform_async(
        @installation.id,
        @installation.instance_url_before_last_save
      )
    end

    def instance_installation_creation_error(error_message)
      message = if error_message[:type] == :response_error
                  "Could not be installed on the instance. Error response code #{error_message[:code]}"
                else
                  'Could not be installed on the instance. Network error'
                end

      ServiceResponse.error(message: { instance_url: [message] })
    end

    def update_error
      ServiceResponse.error(message: @installation.errors)
    end
  end
end