-
Notifications
You must be signed in to change notification settings - Fork 1
feat(users): add endpoint to update users' marketing updates by email #526
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
Open
dspachos
wants to merge
9
commits into
dev
Choose a base branch
from
feature/AI-user-receive-marketing-updates
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
1725482
feat(users): add endpoint to update users' marketing updates by email
dspachos 3b42348
refactor(api): streamline HubSpot contact update logic and improve tests
dspachos 61b2242
feat(users): add receive_marketing_updates to user creation model
dspachos 1155db5
fix(users): address HubSpot review feedback
Copilot f94fac7
refactor(api): simplify email normalization in user marketing update …
dspachos 14c9013
feat(hubspot): implement contact vid retrieval and marketing status u…
dspachos 3aad4d4
Merge remote-tracking branch 'origin/dev' into feature/AI-user-receiv…
dspachos cfb132f
refactor(api): streamline HubSpot contact creation process and error …
dspachos fa3c516
feat(hubspot): implement upsert_contact_marketing_updates method for …
dspachos 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 hidden or 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 hidden or 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 hidden or 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
32 changes: 32 additions & 0 deletions
32
app/migrations/versions/20260520_160000_add_receive_marketing_updates_to_users.py
This file contains hidden or 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,32 @@ | ||
| """add receive_marketing_updates to users | ||
|
|
||
| Revision ID: c4a9d8e1f2b3 | ||
| Revises: 2f7c9d1e4aab | ||
| Create Date: 2026-05-20 16:00:00.000000 | ||
| """ | ||
|
|
||
| from alembic import op | ||
| import sqlalchemy as sa | ||
|
|
||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision = "c4a9d8e1f2b3" | ||
| down_revision = "2f7c9d1e4aab" | ||
| branch_labels = None | ||
| depends_on = None | ||
|
|
||
|
|
||
| def upgrade() -> None: | ||
| op.add_column( | ||
| "users", | ||
| sa.Column( | ||
| "receive_marketing_updates", | ||
| sa.Boolean(), | ||
| nullable=False, | ||
| server_default=sa.text("false"), | ||
| ), | ||
| ) | ||
|
|
||
|
|
||
| def downgrade() -> None: | ||
| op.drop_column("users", "receive_marketing_updates") |
This file contains hidden or 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 hidden or 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,155 @@ | ||
| import logging | ||
| from typing import Optional | ||
|
|
||
| import httpx | ||
| from fastapi import HTTPException, status | ||
|
|
||
| from app.core.config import settings | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class HubSpotService: | ||
| BASE_URL = "https://api.hubapi.com" | ||
| CONTACTS_OBJECT_PATH = "/crm/v3/objects/contacts" | ||
| CONTACT_SEARCH_PATH = "/crm/v3/objects/contacts/search" | ||
| EMAIL_SUBSCRIPTION_PATH = "/email/public/v1/subscriptions/{email}" | ||
|
|
||
| def __init__(self, token: Optional[str] = None): | ||
| self.token = token or settings.HUBSPOT_TOKEN | ||
| self.marketing_updates_property = settings.HUBSPOT_MARKETING_UPDATES_PROPERTY | ||
| self.marketing_subscription_id = settings.HUBSPOT_MARKETING_SUBSCRIPTION_ID | ||
|
|
||
| def _headers(self) -> dict[str, str]: | ||
| if not self.token: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | ||
| detail="HubSpot token is not configured", | ||
| ) | ||
| return { | ||
| "Authorization": f"Bearer {self.token}", | ||
| "Content-Type": "application/json", | ||
| } | ||
|
|
||
| async def _get_contact_id_by_email( | ||
| self, email: str, client: httpx.AsyncClient | ||
| ) -> Optional[str]: | ||
| payload = { | ||
| "filterGroups": [ | ||
| { | ||
| "filters": [ | ||
| {"propertyName": "email", "operator": "EQ", "value": email} | ||
| ] | ||
| } | ||
| ], | ||
| "properties": ["email"], | ||
| "limit": 1, | ||
| } | ||
| response = await client.post( | ||
| f"{self.BASE_URL}{self.CONTACT_SEARCH_PATH}", | ||
| headers=self._headers(), | ||
| json=payload, | ||
| ) | ||
| if response.status_code >= 400: | ||
| request_id = response.headers.get("x-hubspot-request-id", "unknown") | ||
| logger.error( | ||
| "HubSpot contact search failed status=%s request_id=%s body=%s", | ||
| response.status_code, | ||
| request_id, | ||
| response.text[:500], | ||
| ) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_502_BAD_GATEWAY, | ||
| detail="Failed to search HubSpot contact", | ||
| ) | ||
|
|
||
| results = response.json().get("results", []) | ||
| if not results: | ||
| return None | ||
| return results[0].get("id") | ||
|
|
||
| async def _create_contact(self, email: str, client: httpx.AsyncClient) -> str: | ||
| response = await client.post( | ||
| f"{self.BASE_URL}{self.CONTACTS_OBJECT_PATH}", | ||
| headers=self._headers(), | ||
| json={"properties": {"email": email}}, | ||
| ) | ||
| if response.status_code >= 400: | ||
| request_id = response.headers.get("x-hubspot-request-id", "unknown") | ||
| logger.error( | ||
| "HubSpot contact create failed status=%s request_id=%s body=%s", | ||
| response.status_code, | ||
| request_id, | ||
| response.text[:500], | ||
| ) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_502_BAD_GATEWAY, | ||
| detail="Failed to create HubSpot contact", | ||
| ) | ||
| return str(response.json().get("id")) | ||
|
|
||
| async def _update_contact_marketing_property( | ||
| self, contact_id: str, enabled: bool, client: httpx.AsyncClient | ||
| ) -> None: | ||
| response = await client.patch( | ||
| f"{self.BASE_URL}{self.CONTACTS_OBJECT_PATH}/{contact_id}", | ||
| headers=self._headers(), | ||
| json={ | ||
| "properties": { | ||
| self.marketing_updates_property: "true" if enabled else "false" | ||
| } | ||
| }, | ||
| ) | ||
| if response.status_code >= 400: | ||
| request_id = response.headers.get("x-hubspot-request-id", "unknown") | ||
| logger.error( | ||
| "HubSpot contact property update failed status=%s request_id=%s body=%s", | ||
| response.status_code, | ||
| request_id, | ||
| response.text[:500], | ||
| ) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_502_BAD_GATEWAY, | ||
| detail="Failed to update HubSpot contact marketing property", | ||
| ) | ||
|
|
||
| async def _update_email_subscription( | ||
| self, email: str, enabled: bool, client: httpx.AsyncClient | ||
| ) -> None: | ||
| response = await client.put( | ||
| f"{self.BASE_URL}{self.EMAIL_SUBSCRIPTION_PATH.format(email=email)}", | ||
| headers=self._headers(), | ||
| json={ | ||
| "subscriptionId": self.marketing_subscription_id, | ||
| "subscribed": enabled, | ||
| }, | ||
| ) | ||
| if response.status_code >= 400: | ||
| request_id = response.headers.get("x-hubspot-request-id", "unknown") | ||
| logger.error( | ||
| "HubSpot subscription update failed status=%s request_id=%s body=%s", | ||
| response.status_code, | ||
| request_id, | ||
| response.text[:500], | ||
| ) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_502_BAD_GATEWAY, | ||
| detail="Failed to update HubSpot email subscription", | ||
| ) | ||
|
|
||
| async def upsert_contact_marketing_updates(self, email: str, enabled: bool) -> None: | ||
| """Upsert contact and sync marketing updates state. | ||
|
|
||
| - If contact exists: update custom contact property + email subscription. | ||
| - If contact does not exist: create contact first, then update both. | ||
| """ | ||
| async with httpx.AsyncClient(timeout=10.0) as client: | ||
| contact_id = await self._get_contact_id_by_email(email=email, client=client) | ||
| if not contact_id: | ||
| contact_id = await self._create_contact(email=email, client=client) | ||
| await self._update_contact_marketing_property( | ||
| contact_id=contact_id, enabled=enabled, client=client | ||
| ) | ||
| await self._update_email_subscription( | ||
| email=email, enabled=enabled, client=client | ||
| ) |
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.
Uh oh!
There was an error while loading. Please reload this page.