Skip to content

Instantly share code, notes, and snippets.

@steveburkett
Forked from timlinquist/gist:1019588
Created June 10, 2011 19:31
Show Gist options
  • Save steveburkett/1019592 to your computer and use it in GitHub Desktop.
Save steveburkett/1019592 to your computer and use it in GitHub Desktop.
SAVE THE WORLD REMIX!!!
namespace :gts do
desc "get source of lead for client"
#target output
#client id 1003, from date 2001-01-01
# coupon
# www.google.com 13
# www.yahoo.com 7
# quotes
# www.google.com 7
# www.yahoo.com 4
#
task(:source_for_client_lead => :environment) do
start_date = ENV['start_date'] || Date.parse('2011-01-01')
client_id = ENV['client_id'] || 1003
lead_types = LeadType.all(:select=>'id, name')
lead_types_by_id = {}
lead_types.each{|lead| lead_types_by_id[lead.id] = lead_types_by_id.name }
#this makes an assumption that a lead type is 1:1 to a session
leads = Lead.all(:select=>'DISTINCT(session_id), lead_type_id', :conditions=>["client_id=? AND session_id IS NOT NULL AND DATE(created_at) >= ?", client_id, start_date])
lead_sources = {}
leads.each do |lead|
first_source_in_session = G5PageView::PageView.collection.find({:session_id => lead.session_id}, :fields => ["source"]).sort([['created_at', -1]]).first["source"]
lead_type_name = lead_types_by_id[lead.lead_type_id]
sources_for_lead_type = lead_sources[lead_type_name] || {}
num_leads = sources_for_lead_type.fetch(first_source_in_session, 0)
num_leads += 1
sources_for_lead_type[first_source_in_session] = num_leads
lead_sources[lead_type_name] = sources_for_lead_type
end
puts "Client id #{client_id}, from date #{start_date}"
lead_sources.each { |lead_type_name, sources|
puts "\t#{lead_type_name}"
sources.each {|source, num|
puts "\t\t#{source}\tnum"
}
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment