Skip to content

Instantly share code, notes, and snippets.

@FSevaistre
Created October 9, 2019 12:20
Show Gist options
  • Save FSevaistre/4d3af314f6a5638fac9fe8011e9ad123 to your computer and use it in GitHub Desktop.
Save FSevaistre/4d3af314f6a5638fac9fe8011e9ad123 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
namespace :competition do
desc "Insert all competition"
task insert: :environment do
if ARGV.length <= 1
puts "Please specify csv path competition:insert <path>"
puts "The CSV must have the following header :"
puts "ID, OPPORTUNITY__C, OPPORTUNITY__R.ID_PRETTO__C, ACCOUNT__C, ACCOUNT__R.SLUG__C, BANQUE_CLIENT__C, DERNIER_CONTACT__C, DURATION__C, RATE_OBTAINED__C, ACTION_PRETTO__C"
exit(1)
end
brokers = %w[
meilleurtauxcom
meilleurtaux
cafpi
empruntis
vousfinancer
ace
artemis
cyberpret
hellopret
creditadvisor
centraledefinancement
monemprunt
lesfurets
abc
boursedescredits
lowtaux
credixia
immopret
other
]
banks_query = "UPDATE projects AS p SET solicited_banks = v.solicited_banks FROM (VALUES "
brokers_query = "UPDATE projects AS p SET solicited_brokers = v.solicited_brokers FROM (VALUES "
banks_hash = {}
brokers_hash = {}
CSV.read(ARGV[1]).each do |line|
next if line.first == "ID" # skip first line
next if line[2].nil? || line[2].empty? # skip if pretto id is empty
if(brokers.include?(line[4]))
b = {
name: line[4] == "" ? nil : line[4],
last_contact_date: line[6] == "" ? nil : line[6],
duration: line[7] == "" ? nil : line[7].to_i / 12,
rate: line[8] == "" ? nil : line[8].to_f
}.compact
next if b == {}
brokers_hash[line[2]] = (brokers_hash[line[2]] ? brokers_hash[line[2]] : []) + [b]
else
b = {
bank_slug: line[4] == "" ? nil : line[4],
last_contact_date: line[6] == "" ? nil : line[6],
duration: line[7] == "" ? nil : line[7].to_i / 12,
rate: line[8] == "" ? nil : line[8].to_f
}.compact
next if b == {}
banks_hash[line[2]] = (banks_hash[line[2]] ? banks_hash[line[2]] : []) + [b]
end
end
brokers_hash.each do |project_id, solicited_brokers|
brokers_query += "('#{project_id}', '#{solicited_brokers.to_json}'::jsonb),"
end
banks_hash.each do |project_id, solicited_banks|
banks_query += "('#{project_id}', '#{solicited_banks.to_json}'::jsonb),"
end
banks_query = banks_query.delete_suffix!(",") + ") AS v(project_id, solicited_banks) WHERE v.project_id = p.id::text"
brokers_query = brokers_query.delete_suffix!(",") + ") AS v(project_id, solicited_brokers) WHERE v.project_id = p.id::text"
ActiveRecord::Base.connection.execute(banks_query)
ActiveRecord::Base.connection.execute(brokers_query)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment