2017-06-19 20:05:37 +08:00
|
|
|
module ImportRepository
|
|
|
|
class ParseRepository
|
|
|
|
include ActionView::Helpers::TextHelper
|
|
|
|
def initialize(options)
|
|
|
|
@file = options.fetch(:file)
|
|
|
|
@repository = options.fetch(:repository)
|
|
|
|
@session = options.fetch(:session)
|
|
|
|
@sheet = @repository.open_spreadsheet(@file)
|
|
|
|
end
|
|
|
|
|
|
|
|
def data
|
|
|
|
# Get data (it will trigger any errors as well)
|
2017-10-12 20:43:25 +08:00
|
|
|
if @sheet.is_a?(Roo::CSV)
|
|
|
|
header = @sheet.row(1)
|
|
|
|
columns = @sheet.row(2)
|
|
|
|
elsif @sheet.is_a?(Roo::Excelx)
|
|
|
|
i = 1
|
|
|
|
@sheet.each_row_streaming do |row|
|
|
|
|
header = row.map(&:cell_value) if i == 1
|
|
|
|
columns = row.map(&:cell_value) if i == 2
|
|
|
|
i += 1
|
|
|
|
break if i > 2
|
|
|
|
end
|
|
|
|
else
|
|
|
|
i = 1
|
|
|
|
@sheet.rows.each do |row|
|
|
|
|
header = row.values if i == 1
|
|
|
|
columns = row.values if i == 2
|
|
|
|
i += 1
|
|
|
|
break if i > 2
|
|
|
|
end
|
|
|
|
end
|
2017-06-19 20:05:37 +08:00
|
|
|
# Fill in fields for dropdown
|
|
|
|
@repository.available_repository_fields.transform_values! do |name|
|
|
|
|
truncate(name, length: Constants::NAME_TRUNCATION_LENGTH_DROPDOWN)
|
|
|
|
end
|
2017-10-12 20:43:25 +08:00
|
|
|
header ||= []
|
|
|
|
columns ||= []
|
2017-06-19 20:05:37 +08:00
|
|
|
Data.new(header,
|
2017-07-18 20:54:35 +08:00
|
|
|
columns,
|
2017-06-19 20:05:37 +08:00
|
|
|
@repository.available_repository_fields,
|
2017-10-12 20:43:25 +08:00
|
|
|
@repository)
|
2017-06-19 20:05:37 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def too_large?
|
|
|
|
@file.size > Constants::FILE_MAX_SIZE_MB.megabytes
|
|
|
|
end
|
|
|
|
|
2017-10-12 20:43:25 +08:00
|
|
|
def generate_temp_file
|
2017-06-19 20:05:37 +08:00
|
|
|
# Save file for next step (importing)
|
2017-10-12 20:43:25 +08:00
|
|
|
temp_file = TempFile.new(
|
2017-06-19 20:05:37 +08:00
|
|
|
session_id: @session.id,
|
|
|
|
file: @file
|
|
|
|
)
|
|
|
|
|
2017-10-12 20:43:25 +08:00
|
|
|
if temp_file.save
|
|
|
|
temp_file.destroy_obsolete
|
|
|
|
return temp_file
|
2017-06-19 20:05:37 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
Data = Struct.new(
|
2017-10-12 20:43:25 +08:00
|
|
|
:header, :columns, :available_fields, :repository
|
2017-06-19 20:05:37 +08:00
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|