summaryrefslogtreecommitdiff
path: root/app/services/issues/import_csv_service.rb
blob: 60790ba35475d5958244c1d74fab19539ba0968f (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
# frozen_string_literal: true

module Issues
  class ImportCsvService
    def initialize(user, project, csv_io)
      @user = user
      @project = project
      @csv_io = csv_io
      @results = { success: 0, error_lines: [], parse_error: false }
    end

    def execute
      process_csv
      email_results_to_user

      @results
    end

    private

    def process_csv
      csv_data = @csv_io.open(&:read).force_encoding(Encoding::UTF_8)

      csv_parsing_params = {
        col_sep: detect_col_sep(csv_data.lines.first),
        headers: true,
        header_converters: :symbol
      }

      CSV.new(csv_data, csv_parsing_params).each.with_index(2) do |row, line_no|
        issue_attributes = {
          title:       row[:title],
          description: row[:description]
        }

        issue = Issues::CreateService.new(@project, @user, issue_attributes).execute

        if issue.persisted?
          @results[:success] += 1
        else
          @results[:error_lines].push(line_no)
        end
      end
    rescue ArgumentError, CSV::MalformedCSVError
      @results[:parse_error] = true
    end

    def email_results_to_user
      Notify.import_issues_csv_email(@user.id, @project.id, @results).deliver_later
    end

    def detect_col_sep(header)
      if header.include?(",")
        ","
      elsif header.include?(";")
        ";"
      elsif header.include?("\t")
        "\t"
      else
        raise CSV::MalformedCSVError
      end
    end
  end
end