-
Notifications
You must be signed in to change notification settings - Fork 429
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Track leads to Hubspot #3473
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
f1d6bb5
Add hubspot client
zachaysan 6cb25e5
Add hubspot access token
zachaysan 4b91e2c
WIP commit
zachaysan e30d69f
Add stub test
zachaysan 17b3397
Create HubspotOrganisation and enable post create hook for lead tracking
zachaysan 8991dde
Create hubspot API client methods
zachaysan 75aafa8
Create Hubspot settings constants
zachaysan ab8e64f
Create HubspotLeadTracker
zachaysan 33c1e0b
Create hubspot lead tracking task
zachaysan 9f0f171
Create hubspot tracking tests
zachaysan 23b223b
Change to more accurate test module name
zachaysan 933ef5f
Fix conflicts, update migrations, and merge branch 'main' into feat/h…
zachaysan aa0631d
Fix poetry.lock
zachaysan 95cb9a4
Update api/integrations/lead_tracking/hubspot/client.py
zachaysan 91a2116
Merge branch 'main' into feat/hubspot
zachaysan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
import logging | ||
|
||
import hubspot | ||
from django.conf import settings | ||
from hubspot.crm.companies import SimplePublicObjectInputForCreate | ||
from hubspot.crm.contacts import BatchReadInputSimplePublicObjectId | ||
|
||
from users.models import FFAdminUser | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
class HubspotClient: | ||
def __init__(self) -> None: | ||
access_token = settings.HUBSPOT_ACCESS_TOKEN | ||
self.client = hubspot.Client.create(access_token=access_token) | ||
|
||
def get_contact(self, user: FFAdminUser) -> None | dict: | ||
public_object_id = BatchReadInputSimplePublicObjectId( | ||
id_property="email", | ||
inputs=[{"id": user.email}], | ||
properties=["email", "firstname", "lastname"], | ||
) | ||
|
||
response = self.client.crm.contacts.batch_api.read( | ||
batch_read_input_simple_public_object_id=public_object_id, | ||
archived=False, | ||
) | ||
|
||
results = response.to_dict()["results"] | ||
if not results: | ||
return None | ||
|
||
if len(results) > 1: | ||
logger.warning( | ||
"Hubspot contact endpoint is non-unique which should not be possible" | ||
) | ||
|
||
return results[0] | ||
|
||
def create_contact(self, user: FFAdminUser, hubspot_company_id: str) -> dict: | ||
properties = { | ||
"email": user.email, | ||
"firstname": user.first_name, | ||
"lastname": user.last_name, | ||
"hs_marketable_status": user.marketing_consent_given, | ||
} | ||
|
||
response = self.client.crm.contacts.basic_api.create( | ||
simple_public_object_input_for_create=SimplePublicObjectInputForCreate( | ||
properties=properties, | ||
associations=[ | ||
{ | ||
"types": [ | ||
{ | ||
"associationCategory": "HUBSPOT_DEFINED", | ||
"associationTypeId": 1, | ||
} | ||
], | ||
"to": {"id": hubspot_company_id}, | ||
} | ||
], | ||
) | ||
) | ||
return response.to_dict() | ||
|
||
def create_company(self, name: str) -> dict: | ||
properties = {"name": name} | ||
simple_public_object_input_for_create = SimplePublicObjectInputForCreate( | ||
properties=properties, | ||
) | ||
|
||
response = self.client.crm.companies.basic_api.create( | ||
simple_public_object_input_for_create=simple_public_object_input_for_create, | ||
) | ||
|
||
return response.to_dict() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
import logging | ||
|
||
from django.conf import settings | ||
|
||
from integrations.lead_tracking.lead_tracking import LeadTracker | ||
from organisations.models import HubspotOrganisation, Organisation | ||
from users.models import FFAdminUser | ||
|
||
from .client import HubspotClient | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
try: | ||
import re2 as re | ||
|
||
logger.info("Using re2 library for regex.") | ||
except ImportError: | ||
logger.warning("Unable to import re2. Falling back to re.") | ||
import re | ||
|
||
|
||
class HubspotLeadTracker(LeadTracker): | ||
@staticmethod | ||
def should_track(user: FFAdminUser) -> bool: | ||
if not settings.ENABLE_HUBSPOT_LEAD_TRACKING: | ||
return False | ||
|
||
domain = user.email_domain | ||
|
||
if settings.HUBSPOT_IGNORE_DOMAINS_REGEX and re.match( | ||
settings.HUBSPOT_IGNORE_DOMAINS_REGEX, domain | ||
): | ||
return False | ||
|
||
if ( | ||
settings.HUBSPOT_IGNORE_DOMAINS | ||
and domain in settings.HUBSPOT_IGNORE_DOMAINS | ||
): | ||
return False | ||
|
||
if any( | ||
org.is_paid | ||
for org in user.organisations.select_related("subscription").all() | ||
): | ||
return False | ||
|
||
return True | ||
|
||
def create_lead(self, user: FFAdminUser, organisation: Organisation) -> None: | ||
contact_data = self.client.get_contact(user) | ||
|
||
if contact_data: | ||
# The user is already present in the system as a lead | ||
# for an existing organisation, so return early. | ||
return | ||
|
||
hubspot_id = self.get_or_create_organisation_hubspot_id(organisation) | ||
|
||
self.client.create_contact(user, hubspot_id) | ||
|
||
def get_or_create_organisation_hubspot_id(self, organisation: Organisation) -> str: | ||
""" | ||
Return the Hubspot API's id for an organisation. | ||
""" | ||
if getattr(organisation, "hubspot_organisation", None): | ||
return organisation.hubspot_organisation.hubspot_id | ||
|
||
response = self.client.create_company(name=organisation.name) | ||
# Store the organisation data in the database since we are | ||
# unable to look them up via a unique identifier. | ||
HubspotOrganisation.objects.create( | ||
organisation=organisation, | ||
hubspot_id=response["id"], | ||
) | ||
return response["id"] | ||
|
||
def _get_client(self) -> HubspotClient: | ||
return HubspotClient() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
from django.conf import settings | ||
|
||
from task_processor.decorators import register_task_handler | ||
|
||
|
||
@register_task_handler() | ||
def track_hubspot_lead(user_id: int, organisation_id: int) -> None: | ||
assert settings.ENABLE_HUBSPOT_LEAD_TRACKING | ||
|
||
# Avoid circular imports. | ||
from organisations.models import Organisation | ||
from users.models import FFAdminUser | ||
|
||
from .lead_tracker import HubspotLeadTracker | ||
|
||
user = FFAdminUser.objects.get(id=user_id) | ||
|
||
if not HubspotLeadTracker.should_track(user): | ||
return | ||
|
||
organisation = Organisation.objects.get(id=organisation_id) | ||
|
||
hubspot_lead_tracker = HubspotLeadTracker() | ||
hubspot_lead_tracker.create_lead(user=user, organisation=organisation) |
24 changes: 24 additions & 0 deletions
24
api/organisations/migrations/0052_create_hubspot_organisation.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
# Generated by Django 3.2.24 on 2024-02-26 19:04 | ||
|
||
from django.db import migrations, models | ||
import django.db.models.deletion | ||
|
||
|
||
class Migration(migrations.Migration): | ||
|
||
dependencies = [ | ||
('organisations', '0051_create_org_api_usage_notification'), | ||
] | ||
|
||
operations = [ | ||
migrations.CreateModel( | ||
name='HubspotOrganisation', | ||
fields=[ | ||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), | ||
('hubspot_id', models.CharField(max_length=100)), | ||
('created_at', models.DateTimeField(auto_now_add=True)), | ||
('updated_at', models.DateTimeField(auto_now=True)), | ||
('organisation', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='hubspot_organisation', to='organisations.organisation')), | ||
], | ||
), | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This import logic was to mirror the functionality of the existing pipedrive code which had this way of importing
re
.