From a6753b832ce5ef5383e9cefa9df2d55c753e50d4 Mon Sep 17 00:00:00 2001 From: Maikel Linke Date: Tue, 8 Sep 2020 14:30:00 +1000 Subject: [PATCH] Add example script for importing customers --- script/import-customers.rb | 51 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 script/import-customers.rb diff --git a/script/import-customers.rb b/script/import-customers.rb new file mode 100644 index 0000000000..2ec349afd3 --- /dev/null +++ b/script/import-customers.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +# Read customer entries in CSV format from STDIN and create those records in +# the database. Example: +# +# rails runner script/import-customers.rb 3359 < FND-customers-Emails.csv +# +# This script was written for a once-off import. If we want to perform this +# task more often, we can make it more flexible and eventually add a +# feature to the user interface. +require 'csv' + +enterprise_id = ARGV.first + +def check_enterprise_exists(id) + enterprise = Enterprise.find(id) + puts "Importing customers for #{enterprise.name}:" +end + +def import_customer(row, enterprise_id) + email = row["Email"].downcase + tag = row["Tag"] + + print email + customer = find_or_create_customer(email, enterprise_id) + add_tag(customer, tag) + puts "" +end + +def find_or_create_customer(email, enterprise_id) + Customer.find_or_create_by( + email: email, + enterprise_id: enterprise_id, + ) { print " - newly imported" } + print " - user exists" if Spree::User.where(email: email).exists? +end + +def add_tag(customer, tag) + return if tag.blank? + + customer.tag_list.add(tag) + customer.save! +end + +check_enterprise_exists(enterprise_id) + +CSV($stdin, headers: true, row_sep: "\r\n") do |csv| + csv.each do |row| + import_customer(row, enterprise_id) + end +end