-
Notifications
You must be signed in to change notification settings - Fork 200
/
Copy pathfreshsales3.py
448 lines (355 loc) · 13.7 KB
/
freshsales3.py
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright _!_
#
# License _!_
import pprint
import sys
import time
from os.path import abspath, dirname
from os.path import join as pjoin
from urllib.parse import urlparse
import requests
from icecream import ic
_corePath = abspath(pjoin(dirname(__file__), '../'))
if _corePath not in sys.path:
sys.path.append(_corePath)
from common.utils import lget, stripStringStart
DEFAULT_FIRST_NAME = 'there'
DEFAULT_LAST_NAME = '-'
FRESH_SALES_API_KEY = 'P3bYheaquAHH1_hNxhMUDQ'
FS_API_URL = 'https://arcindustriesinc.freshsales.io/api'
FS_AUTH_HEADERS = {'Authorization': 'Token token=P3bYheaquAHH1_hNxhMUDQ'}
#
# FreshSales' Contact field magic values looked up with
#
# curl -H "Authorization: Token token=P3bYheaquAHH1_hNxhMUDQ" -H "Content-Type: application/json" -X GET "https://arcindustriesinc.freshsales.io/api/settings/contacts/fields"
#
#
# FreshSales' Lead field magic values looked up with
#
# curl -H "Authorization: Token token=P3bYheaquAHH1_hNxhMUDQ" -H "Content-Type: application/json" -X GET "https://arcindustriesinc.freshsales.io/api/settings/leads/fields"
#
# FreshSales' Company field magic values looked up with
#
# curl -H "Authorization: Token token=P3bYheaquAHH1_hNxhMUDQ" -H "Content-Type: application/json" -X GET "https://arcindustriesinc.freshsales.io/api/settings/sales_accounts/fields"
#
def splitName(name):
# Intelligently split <name> into first and last name, if provided.
# '' -> firstName: '', lastName: '-'
# 'Susan' -> firstName: 'Susan', lastName: '-'
# 'Greg Borp' -> firstName: 'Greg', lastName: 'Borp'
# 'Freddy van der Field' -> firstName: 'Freddy', lastName: 'van der Field'
toks = name.split(None, 1)
firstName = lget(toks, 0, DEFAULT_FIRST_NAME)
lastName = lget(toks, 1, DEFAULT_LAST_NAME)
return firstName, lastName
def lookupFullContact(contact):
contactId = contact['id']
resp = requests.get(
f'{FS_API_URL}/contacts/{contactId}?include=sales_accounts',
headers=FS_AUTH_HEADERS)
contact = (resp.json() or {}).get('contact')
return contact
def findFirstContactWithEmail(emailAddr):
contacts = _findEntitiesWith('contact', 'email', emailAddr)
return lget(contacts, 0)
def findFirstCompanyWithWebsite(websiteUrl):
ic('before', websiteUrl)
if ic(urlparse(websiteUrl).scheme) is None:
websiteUrl = f'http://{websiteUrl}'
ic('after', websiteUrl)
# FreshSales' API returns unrelated companies. For example, searching for
# companies with website 'http://blockchainexamples.com', ie
#
# ?f=website&entities=sales_account&q=http%3A%2F%2Fblockchainexamples.com
#
# returns https://arcindustriesinc.freshsales.io/accounts/9001963743 with
# name 'http://culturetv.club' and website
# 'http://104.225.221.170:8082'. Why? Who knows.
#
# As a workaround, filter all returned companies to verify that the domains
# match.
hostNoWww = lambda url: stripStringStart(urlparse(url).hostname, 'www.')
allCompanies = _findEntitiesWith('sales_account', 'website', websiteUrl)
ic(allCompanies)
ic(websiteUrl)
companies = [
c for c in _findEntitiesWith('sales_account', 'website', websiteUrl)
if hostNoWww(c.get('website')) == hostNoWww(websiteUrl)]
ic(companies)
firstCompany = lget(companies, 0)
return firstCompany
def _findEntitiesWith(entityType, query, queryValue):
resp = requests.get(
f'{FS_API_URL}/lookup?f={query}&entities={entityType}',
params={'q': queryValue}, headers=FS_AUTH_HEADERS)
entities = (
resp.json() or {}).get(f'{entityType}s', {}).get(f'{entityType}s', [])
return entities
def createNote(entityType, entityId, message):
data = {
'note': {
'description': message,
'targetable_id': entityId,
'targetable_type': entityType,
}
}
resp = requests.post(
f'{FS_API_URL}/notes', json=data, headers=FS_AUTH_HEADERS)
if resp.status_code != 201:
err = f'Failed to create {entityType} note for id {entityId}.'
raise RuntimeError(err)
def createLead(data):
return _createEntity('lead', data)
def createContact(data):
ANSGAR_GRUNSEID = 9000013180
data.setdefault('owner_id', ANSGAR_GRUNSEID)
return _createEntity('contact', data)
def createCompany(data):
return _createEntity('sales_account', data)
def _createEntity(entityType, data):
wrapped = {entityType: data}
url = f'{FS_API_URL}/{entityType}s'
resp = requests.post(url, json=wrapped, headers=FS_AUTH_HEADERS)
if resp.status_code not in [200, 201]:
raise RuntimeError(f'Failed to create new {entityType}.')
entity = (resp.json() or {}).get(entityType)
return entity
def updateLead(leadId, data):
return _updateEntity('lead', leadId, data)
def updateContact(contactId, data):
return _updateEntity('contact', contactId, data)
def updateCompany(companyId, data):
return _updateEntity('sales_account', companyId, data)
def _updateEntity(entityType, entityId, data):
wrapped = {entityType: data}
url = f'{FS_API_URL}/{entityType.lower()}s/{entityId}'
resp = requests.put(url, json=wrapped, headers=FS_AUTH_HEADERS)
if resp.status_code != 200:
err = f'Failed to update {entityType.title()} with id {entityId}.'
raise RuntimeError(err)
entity = (resp.json() or {}).get(entityType)
return entity
def lookupContactsInView(viewId):
return _lookupEntitiesInView('contact', viewId)
def _lookupEntitiesInView(entityType, viewId):
entities = []
url = f'{FS_API_URL}/{entityType.lower()}s/view/{viewId}'
def pageUrl(pageNo):
return url + f'?page={pageNo}'
resp = requests.get(url, headers=FS_AUTH_HEADERS)
js = resp.json()
entities += js.get(f'{entityType}s')
totalPages = js.get('meta', {}).get('total_pages')
for pageNo in range(2, totalPages + 1):
resp = requests.get(pageUrl(pageNo), headers=FS_AUTH_HEADERS)
entities += (resp.json() or {}).get(f'{entityType}s')
return entities
def unsubscribeContact(contact, reasons):
UNSUBSCRIBED = 9000159966
updateContact(contact['id'], {
'do_not_disturb': True,
'contact_status_id': UNSUBSCRIBED,
})
dateStr = time.ctime()
reasonsStr = pprint.pformat(reasons)
note = (
f'This Contact unsubscribed on arc.io/unsubscribe at [{dateStr}] '
'because:\n'
'\n'
f'{reasonsStr}\n'
'\n')
createNote('Contact', contact['id'], note)
def optContactIn(contact):
OPTED_IN = 9000159976
updateContact(contact['id'], {
'contact_status_id': OPTED_IN,
})
def createAndOrAssociateCompanyWithContact(websiteUrl, contact):
if 'sales_accounts' not in contact:
contact = lookupFullContact(contact)
companyToAdd = None
companies = contact.get('sales_accounts', [])
company = findFirstCompanyWithWebsite(websiteUrl)
if company:
companyId = company['id']
alreadyRelated = any(companyId == c['id'] for c in companies)
if not alreadyRelated:
companyToAdd = company
else:
companyToAdd = createCompany({
'name': websiteUrl,
'website': websiteUrl,
})
if companyToAdd:
companyData = {
'id': companyToAdd['id'],
# There can only be one primary Company associated with a
# Contact. See https://www.freshsales.io/api/#create_contact.
'is_primary': not companies,
}
companies.append(companyData)
updateContact(contact['id'], { 'sales_accounts': companies })
return company or companyToAdd
def upgradeContactWhoSubmittedSplashPage(contact, websiteUrl):
createAndOrAssociateCompanyWithContact(websiteUrl, contact)
SUBMITTED_ARC_IO_SIGN_UP_FORM = 9000159955
updateContact(contact['id'], {
'contact_status_id': SUBMITTED_ARC_IO_SIGN_UP_FORM,
})
dateStr = time.ctime()
emailAddr = contact['email']
note = (
f'This Contact submitted the sign up form on arc.io at [{dateStr}] '
f'with email address [{emailAddr}] and website [{websiteUrl}].')
createNote('Contact', contact['id'], note)
def noteContactSubmittedPepSplashPage(contact, websiteUrl):
createAndOrAssociateCompanyWithContact(websiteUrl, contact)
PEP = 9000004543
updateContact(contact['id'], {
'custom_field': {
'cf_product': 'Pep',
},
})
dateStr = time.ctime()
emailAddr = contact['email']
note = (
f"This Contact submitted Pep's sign up form on pep.dev at [{dateStr}] "
f'with email address [{emailAddr}] and website [{websiteUrl}].')
createNote('Contact', contact['id'], note)
def createCrawledIndieHackersContact(name, emailAddr, websiteUrl, noteData):
INDIE_HACKERS = 9000321821
_createCrawledContact(name, emailAddr, websiteUrl, INDIE_HACKERS, noteData)
def _createCrawledContact(name, emailAddr, websiteUrl, leadSourceId, noteData):
firstName, lastName = splitName(name)
SUSPECT = 9000073090
contact = createContact({
'email': emailAddr,
'first_name': firstName,
'last_name': lastName,
'contact_status_id': SUSPECT,
'lead_source_id': leadSourceId,
})
createAndOrAssociateCompanyWithContact(websiteUrl, contact)
dateStr = time.ctime()
reasonsStr = pprint.pformat(noteData)
note = (
f'This Contact was crawled and created on [{dateStr}]. '
'Other data:'
'\n'
f'{reasonsStr}\n'
'\n')
createNote('Contact', contact['id'], note)
def createSplashPageLead(name, emailAddr, websiteUrl):
firstName, lastName = splitName(name)
INTERESTED = 9000057526
ARC_IO_SIGN_UP_FORM = 9000315608
lead = createLead({
'first_name': firstName,
'last_name': lastName,
'email': emailAddr,
'company': {
'website': websiteUrl,
},
'lead_stage_id': INTERESTED,
'lead_source_id': ARC_IO_SIGN_UP_FORM,
})
dateStr = time.ctime()
note = (
f'This Lead was created on [{dateStr}] because they submitted '
f'the sign up form on arc.io with email address [{emailAddr}] '
f'and website [{websiteUrl}].')
createNote('Lead', lead['id'], note)
def createPepSplashPageLead(emailAddr, websiteUrl):
PEP = 9000004543
INTERESTED = 9000057526
PEP_SIGN_UP_FORM = 9000321929
lead = createLead({
'first_name': DEFAULT_FIRST_NAME,
'last_name': DEFAULT_LAST_NAME,
'email': emailAddr,
'company': {
'website': websiteUrl,
},
'deal': {
'deal_product_id': PEP,
},
'lead_stage_id': INTERESTED,
'lead_source_id': PEP_SIGN_UP_FORM,
})
dateStr = time.ctime()
note = (
f'This Lead was created on [{dateStr}] because they submitted '
f'the sign up form on pep.dev with email address [{emailAddr}] '
f'and website [{websiteUrl}].')
createNote('Lead', lead['id'], note)
def noteACustomersFirstWidgetReport(emailAddr, seenOnUrl):
raise NotImplementedError
# TODO(grun): Finish me.
contact = findFirstContactWithEmail(emailAddr)
if contact:
note = (
f'The widget for Arc account with email {emailAddr} was just seen '
f'live for the first seen for the first time live on {seenOnUrl}.')
createNote('Contact', contact['id'], note)
else:
# TODO(grun): Log this scenario, which means someone added Arc's widget
# to someone
ic()
# TODO(grun): Refactor and/or rename the below handleWordPressPlugin*()
# functions, like how the above handle*() functions were refactored.
def handleWordPressPluginInstall(emailAddr, websiteUrl):
WORDPRESS = 9000321857
ALPHA_CODE = 9000124404
contact = findFirstContactWithEmail(emailAddr)
if contact:
updateContact(contact['id'], {
'lead_source_id': WORDPRESS,
'contact_status_id': ALPHA_CODE,
})
else:
contact = createContact({
'email': emailAddr,
'first_name': 'there',
'last_name': websiteUrl,
'lead_source_id': WORDPRESS,
'contact_status_id': ALPHA_CODE,
})
CUSTOMER = 9000095000
company = createAndOrAssociateCompanyWithContact(websiteUrl, contact)
updateCompany(company['id'], {
'business_type_id': CUSTOMER,
'custom_field': {
'cf_source': 'Wordpress',
},
})
dateStr = time.ctime()
note = (
f"This Contact installed Arc's WordPress plugin at [{dateStr}] on "
"website [{websiteUrl}].")
createNote('Contact', contact['id'], note)
def handleWordPressPluginCreatedArcAccount(emailAddr):
contact = findFirstContactWithEmail(emailAddr)
if not contact:
return
CUSTOMER = 9000066454
updateContact(contact['id'], { 'contact_status_id': CUSTOMER })
dateStr = time.ctime()
note = (
f'This WordPress Contact created their Arc account at [{dateStr}].')
createNote('Contact', contact['id'], note)
def handleWordPressPluginUninstall(emailAddr):
contact = findFirstContactWithEmail(emailAddr)
if not contact:
return
FORMER_CUSTOMER = 9000124405
updateContact(contact['id'], { 'contact_status_id': FORMER_CUSTOMER })
dateStr = time.ctime()
note = (
f'This Contact uninstalled their WordPress plugin at [{dateStr}].')
createNote('Contact', contact['id'], note)
if __name__ == '__main__': # For development only.
#ic(findFirstCompanyWithWebsite('http://www.blockchainexamples.com'))
#ic(findFirstCompanyWithWebsite('http://www.culturetv.club'))
ic(findFirstCompanyWithWebsite('www.realizeventures.com'))