summaryrefslogtreecommitdiff
path: root/app/services/work_items/create_and_link_service.rb
blob: 351ebc145646a44d855f02273229208bf132315f (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
# frozen_string_literal: true

module WorkItems
  # Create and link operations are not run inside a transaction in this class
  # because CreateFromTaskService also creates a transaction.
  # This class should always be run inside a transaction as we could end up with
  # new work items that were never associated with other work items as expected.
  class CreateAndLinkService
    def initialize(project:, spam_params:, current_user: nil, params: {}, link_params: {})
      @project = project
      @current_user = current_user
      @params = params
      @link_params = link_params
      @spam_params = spam_params
    end

    def execute
      create_result = CreateService.new(
        project: @project,
        current_user: @current_user,
        params: @params.merge(title: @params[:title].strip).reverse_merge(confidential: confidential_parent),
        spam_params: @spam_params
      ).execute
      return create_result if create_result.error?

      work_item = create_result[:work_item]
      return ::ServiceResponse.success(payload: payload(work_item)) if @link_params.blank?

      result = WorkItems::ParentLinks::CreateService.new(
        @link_params[:parent_work_item],
        @current_user,
        { target_issuable: work_item }
      ).execute

      if result[:status] == :success
        ::ServiceResponse.success(payload: payload(work_item))
      else
        ::ServiceResponse.error(message: result[:message], http_status: 404)
      end
    end

    private

    def confidential_parent
      !!@link_params[:parent_work_item]&.confidential
    end

    def payload(work_item)
      { work_item: work_item }
    end
  end
end