- Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathmarketing.rake
88 lines (75 loc) · 2.88 KB
/
marketing.rake
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
namespace:marketingdo
defsendgrid_client
Excon.new(
'https://api.sendgrid.com',
headers: {
"Authorization"=>"Bearer #{ENV.fetch('SENDGRID_KEY')}",
"Content-Type"=>"application/json"
},
)
end
defsendgrid(method,path,body=nil,options={})
params={method: method,path: "v3/#{path}"}
params[:body]=body.to_jsonifbody
response=sendgrid_client.request(params)
ifoptions[:check_status] != false && ![200,201,204].include?(response.status)
putsresponse.body
putsresponse.headers
raise"sendgrid #{path}#{response.status}"
end
JSON.parse(response.body)unlessresponse.body.blank?
end
defupsert_list(name)
resp=sendgrid('GET','contactdb/lists')
resp['lists'].find{|l| l['name'] == name} ||
sendgrid('POST','contactdb/lists',{name: name})
end
task:sync_lists=>:environmentdo
list_name=ENV.fetch('MARKETING_LIST')
list=upsert_list(list_name)
%w(usernamefull_name).eachdo |field|
sendgrid('POST','contactdb/custom_fields',{name: field,type: 'text'},check_status: false)
end
# add users to marketing list
User.where(marketing_list: nil,email_invalid_at: nil,receive_newsletter: true).find_in_batches(batch_size: 1000)do |group|
entries=group.mapdo |u|
{
email: u.email,
username: u.username,
full_name: u.name,
}
end
puts"creating #{entries.size} recipients"
response=sendgrid('POST','contactdb/recipients',entries)
putsresponse.slice('new_count','updated_count')
(response['errors'] || []).eachdo |error|
putserror['message']
puts(error['error_indices'] || []).map{|i| putsentries[i]}
iferror['message'] =~ /email.*is invalid/i
error['error_indices'].map{|i| group[i]}.eachdo |u|
u.update!email_invalid_at: Time.now
end
end
end
recipients=response['persisted_recipients']
puts"adding #{recipients.size} recipients to list #{list}"
sendgrid('POST',"contactdb/lists/#{list['id']}/recipients",recipients)
persisted_users=group.select.with_index{ |u,idx|
!response['error_indices'].include?(idx)
}.map.with_index{|u,idx| [u,recipients[idx]]}
persisted_users.eachdo |user,recipient_id|
user.update!(marketing_list: list['id'])
end
sleep1# sendgrid rate limits
end
# remove users from marketing list
User.where.not(marketing_list: nil).where(receive_newsletter: false).find_eachdo |u|
response=sendgrid('GET',"contactdb/recipients/search?email=#{u.email}")
response['recipients'].eachdo |r|
sendgrid("DELETE","contactdb/lists/#{list['id']}/recipients/#{r['id']}")
u.update!(marketing_list: nil)
puts"unsubscribed #{r['email']}"
end
end
end
end