2018-12-05 19:51:30 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Issues
|
|
|
|
class ImportCsvService
|
2019-01-03 00:17:07 -05:00
|
|
|
def initialize(user, project, csv_io)
|
2018-12-05 19:51:30 -05:00
|
|
|
@user = user
|
|
|
|
@project = project
|
2019-01-03 00:17:07 -05:00
|
|
|
@csv_io = csv_io
|
2018-12-31 03:39:43 -05:00
|
|
|
@results = { success: 0, error_lines: [], parse_error: false }
|
2018-12-05 19:51:30 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def execute
|
|
|
|
process_csv
|
|
|
|
email_results_to_user
|
|
|
|
|
|
|
|
@results
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def process_csv
|
2019-01-03 00:17:07 -05:00
|
|
|
csv_data = @csv_io.open(&:read).force_encoding(Encoding::UTF_8)
|
|
|
|
|
|
|
|
CSV.new(csv_data, col_sep: detect_col_sep(csv_data.lines.first), headers: true).each.with_index(2) do |row, line_no|
|
2018-12-05 19:51:30 -05:00
|
|
|
issue = Issues::CreateService.new(@project, @user, title: row[0], description: row[1]).execute
|
|
|
|
|
|
|
|
if issue.persisted?
|
|
|
|
@results[:success] += 1
|
|
|
|
else
|
2018-12-31 03:39:43 -05:00
|
|
|
@results[:error_lines].push(line_no)
|
2018-12-05 19:51:30 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
rescue ArgumentError, CSV::MalformedCSVError
|
2018-12-31 03:39:43 -05:00
|
|
|
@results[:parse_error] = true
|
2018-12-05 19:51:30 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def email_results_to_user
|
|
|
|
Notify.import_issues_csv_email(@user.id, @project.id, @results).deliver_now
|
|
|
|
end
|
|
|
|
|
2019-01-03 00:17:07 -05:00
|
|
|
def detect_col_sep(header)
|
2018-12-05 19:51:30 -05:00
|
|
|
if header.include?(",")
|
|
|
|
","
|
|
|
|
elsif header.include?(";")
|
|
|
|
";"
|
|
|
|
elsif header.include?("\t")
|
|
|
|
"\t"
|
|
|
|
else
|
|
|
|
raise CSV::MalformedCSVError
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|