Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CSV Import File Validations #1211

Merged
merged 7 commits into from
Dec 6, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 52 additions & 25 deletions app/services/organizations/importers/google_csv_import_service.rb
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work! I like the structure.

Original file line number Diff line number Diff line change
Expand Up @@ -13,42 +13,57 @@ def initialize(file)
end

def call
CSV.foreach(@file.to_path, headers: true, skip_blanks: true).with_index(1) do |row, index|
# Using Google Form headers
email = row["Email"].downcase
csv_timestamp = Time.parse(row["Timestamp"])
catch(:halt_import) do
validate_file

person = Person.find_by(email:, organization: @organization)
previously_matched_form_submission = FormSubmission.where(person:, csv_timestamp:)
CSV.foreach(@file.to_path, headers: true, skip_blanks: true).with_index(1) do |row, index|
# Using Google Form headers
email = row["Email"].downcase
csv_timestamp = Time.parse(row["Timestamp"])

if person.nil?
@no_match << [index, email]
elsif previously_matched_form_submission.present?
next
else
latest_form_submission = person.latest_form_submission
ActiveRecord::Base.transaction do
# This checks for the empty form submission that is added when a person is created
if latest_form_submission.csv_timestamp.nil? && latest_form_submission.form_answers.empty?
latest_form_submission.update!(csv_timestamp:)
create_form_answers(latest_form_submission, row)
else
# if the person submits a new/updated form,
# i.e. an additional row in the csv with the same email / different timestamp,
# a new form_submission will be created
create_form_answers(FormSubmission.create!(person:, csv_timestamp:), row)
person = Person.find_by(email:, organization: @organization)
previously_matched_form_submission = FormSubmission.where(person:, csv_timestamp:)

if person.nil?
@no_match << [index, email]
elsif previously_matched_form_submission.present?
next
else
latest_form_submission = person.latest_form_submission
ActiveRecord::Base.transaction do
# This checks for the empty form submission that is added when a person is created
if latest_form_submission.csv_timestamp.nil? && latest_form_submission.form_answers.empty?
latest_form_submission.update!(csv_timestamp:)
create_form_answers(latest_form_submission, row)
else
# if the person submits a new/updated form,
# i.e. an additional row in the csv with the same email / different timestamp,
# a new form_submission will be created
create_form_answers(FormSubmission.create!(person:, csv_timestamp:), row)
end
@count += 1
end
@count += 1
end
rescue => e
@errors << [index, e]
end
rescue => e
@errors << [index, e]
end
Status.new(@errors.empty?, @count, @no_match, @errors)
end

private

def validate_file
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the vein of single responsibility, we could have separate validation methods for each validation. Might be something to consider if we add more validations. I am fine either way in this case.

raise FileTypeError unless @file.content_type == "text/csv"

first_row = CSV.foreach(@file.to_path).first
raise EmailColumnError if first_row.nil?
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I am understanding this correctly, we are raising EmailColumnError if the first row is empty, right? Should we have a different error class to handle this case? Something like NoDataError (I am sure there is a better name than that).

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes it is checking for an empty file as an edge case (came up during testing). I just reused the same error because technically the file does not have the "Email" column but I can add a more specific error.

raise EmailColumnError unless first_row.include?("Email")
Copy link
Collaborator

@kasugaijin kasugaijin Dec 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shall we add lowercase email here as well just in case the user doesn't adhere to case requirement?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I'm confused on what you are asking. If the header row doesn't include "Email"(capitalized) the error is raised. The service is currently using "Email". Do you want "email" to work as well?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry yeh that’s right. We may as well allow Email and email as valid because users won’t adhere to case rules half the time.

rescue EmailColumnError, FileTypeError => e
@errors << e
throw :halt_import
end

def create_form_answers(form_submission, row)
row.each do |col|
next if col[0] == "Email" || col[0] == "Timestamp"
Expand All @@ -61,6 +76,18 @@ def create_form_answers(form_submission, row)
)
end
end

class EmailColumnError < StandardError
def message
'The column header "Email" was not found in the attached csv'
end
end

class FileTypeError < StandardError
def message
"Invalid File Type: File type must be CSV"
end
end
end
end
end
30 changes: 30 additions & 0 deletions test/services/organizations/csv_import_service_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ class CsvImportServiceTest < ActiveSupport::TestCase
Current.organization = adopter.organization

@file = Tempfile.new(["test", ".csv"])
@file.stubs(:content_type).returns("text/csv")

headers = ["Timestamp", "First name", "Last name", "Email", "Address", "Phone number", *Faker::Lorem.questions]

@data = [
Expand Down Expand Up @@ -110,5 +112,33 @@ class CsvImportServiceTest < ActiveSupport::TestCase
refute import.success?
assert_equal "mon out of range", import.errors[0][1].message
end

should "validate file type" do
file = Tempfile.new(["test", ".png"])
file.stubs(:content_type).returns("image/png")
import = Organizations::Importers::GoogleCsvImportService.new(file).call

assert_equal "Invalid File Type: File type must be CSV", import.errors.first.message
end

should "validate empty header" do
file = Tempfile.new(["test", ".csv"])
file.stubs(:content_type).returns("text/csv")
import = Organizations::Importers::GoogleCsvImportService.new(file).call

assert_equal 'The column header "Email" was not found in the attached csv', import.errors.first.message
end

should "validate email header" do
file = Tempfile.new(["test", ".csv"])
headers = ["Timestamp", "First name", "Last name", "Address", "Phone number", *Faker::Lorem.questions]
CSV.open(@file.path, "wb") do |csv|
csv << headers
end
file.stubs(:content_type).returns("text/csv")
import = Organizations::Importers::GoogleCsvImportService.new(file).call

assert_equal 'The column header "Email" was not found in the attached csv', import.errors.first.message
end
end
end
Loading