Update Hubpost tracking form submission (#3261)

* Update Hubpost tracking form submission

* minor cleanup

* validated

* validate

* nit

* k
This commit is contained in:
pablonyx 2024-12-16 18:31:09 -08:00 committed by GitHub
parent ed9014f03d
commit 48be6338ec
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 57 additions and 12 deletions

View File

@ -53,3 +53,5 @@ OAUTH_GOOGLE_DRIVE_CLIENT_SECRET = os.environ.get(
# when the capture is called. These defaults prevent Posthog issues from breaking the Onyx app # when the capture is called. These defaults prevent Posthog issues from breaking the Onyx app
POSTHOG_API_KEY = os.environ.get("POSTHOG_API_KEY") or "FooBar" POSTHOG_API_KEY = os.environ.get("POSTHOG_API_KEY") or "FooBar"
POSTHOG_HOST = os.environ.get("POSTHOG_HOST") or "https://us.i.posthog.com" POSTHOG_HOST = os.environ.get("POSTHOG_HOST") or "https://us.i.posthog.com"
HUBSPOT_TRACKING_URL = os.environ.get("HUBSPOT_TRACKING_URL")

View File

@ -3,12 +3,15 @@ import logging
import uuid import uuid
import aiohttp # Async HTTP client import aiohttp # Async HTTP client
import httpx
from fastapi import HTTPException from fastapi import HTTPException
from fastapi import Request
from sqlalchemy import select from sqlalchemy import select
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from ee.onyx.configs.app_configs import ANTHROPIC_DEFAULT_API_KEY from ee.onyx.configs.app_configs import ANTHROPIC_DEFAULT_API_KEY
from ee.onyx.configs.app_configs import COHERE_DEFAULT_API_KEY from ee.onyx.configs.app_configs import COHERE_DEFAULT_API_KEY
from ee.onyx.configs.app_configs import HUBSPOT_TRACKING_URL
from ee.onyx.configs.app_configs import OPENAI_DEFAULT_API_KEY from ee.onyx.configs.app_configs import OPENAI_DEFAULT_API_KEY
from ee.onyx.server.tenants.access import generate_data_plane_token from ee.onyx.server.tenants.access import generate_data_plane_token
from ee.onyx.server.tenants.models import TenantCreationPayload from ee.onyx.server.tenants.models import TenantCreationPayload
@ -47,13 +50,16 @@ from shared_configs.enums import EmbeddingProvider
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
async def get_or_create_tenant_id( async def get_or_provision_tenant(
email: str, referral_source: str | None = None email: str, referral_source: str | None = None, request: Request | None = None
) -> str: ) -> str:
"""Get existing tenant ID for an email or create a new tenant if none exists.""" """Get existing tenant ID for an email or create a new tenant if none exists."""
if not MULTI_TENANT: if not MULTI_TENANT:
return POSTGRES_DEFAULT_SCHEMA return POSTGRES_DEFAULT_SCHEMA
if referral_source and request:
await submit_to_hubspot(email, referral_source, request)
try: try:
tenant_id = get_tenant_id_for_email(email) tenant_id = get_tenant_id_for_email(email)
except exceptions.UserNotExists: except exceptions.UserNotExists:
@ -281,3 +287,36 @@ def configure_default_api_keys(db_session: Session) -> None:
logger.info( logger.info(
"COHERE_DEFAULT_API_KEY not set, skipping Cohere embedding provider configuration" "COHERE_DEFAULT_API_KEY not set, skipping Cohere embedding provider configuration"
) )
async def submit_to_hubspot(
email: str, referral_source: str | None, request: Request
) -> None:
if not HUBSPOT_TRACKING_URL:
logger.info("HUBSPOT_TRACKING_URL not set, skipping HubSpot submission")
return
# HubSpot tracking cookie
hubspot_cookie = request.cookies.get("hubspotutk")
# IP address
ip_address = request.client.host if request.client else None
data = {
"fields": [
{"name": "email", "value": email},
{"name": "referral_source", "value": referral_source or ""},
],
"context": {
"hutk": hubspot_cookie,
"ipAddress": ip_address,
"pageUri": str(request.url),
"pageName": "User Registration",
},
}
async with httpx.AsyncClient() as client:
response = await client.post(HUBSPOT_TRACKING_URL, json=data)
if response.status_code != 200:
logger.error(f"Failed to submit to HubSpot: {response.text}")

View File

@ -229,17 +229,20 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
request: Optional[Request] = None, request: Optional[Request] = None,
) -> User: ) -> User:
user_count: int | None = None user_count: int | None = None
referral_source = None referral_source = (
if request is not None: request.cookies.get("referral_source", None)
referral_source = request.cookies.get("referral_source", None) if request is not None
else None
)
tenant_id = await fetch_ee_implementation_or_noop( tenant_id = await fetch_ee_implementation_or_noop(
"onyx.server.tenants.provisioning", "onyx.server.tenants.provisioning",
"get_or_create_tenant_id", "get_or_provision_tenant",
async_return_default_schema, async_return_default_schema,
)( )(
email=user_create.email, email=user_create.email,
referral_source=referral_source, referral_source=referral_source,
request=request,
) )
async with get_async_session_with_tenant(tenant_id) as db_session: async with get_async_session_with_tenant(tenant_id) as db_session:
@ -346,17 +349,18 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
associate_by_email: bool = False, associate_by_email: bool = False,
is_verified_by_default: bool = False, is_verified_by_default: bool = False,
) -> User: ) -> User:
referral_source = None referral_source = (
if request: getattr(request.state, "referral_source", None) if request else None
referral_source = getattr(request.state, "referral_source", None) )
tenant_id = await fetch_ee_implementation_or_noop( tenant_id = await fetch_ee_implementation_or_noop(
"onyx.server.tenants.provisioning", "onyx.server.tenants.provisioning",
"get_or_create_tenant_id", "get_or_provision_tenant",
async_return_default_schema, async_return_default_schema,
)( )(
email=account_email, email=account_email,
referral_source=referral_source, referral_source=referral_source,
request=request,
) )
if not tenant_id: if not tenant_id:
@ -502,7 +506,7 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
# Get tenant_id from mapping table # Get tenant_id from mapping table
tenant_id = await fetch_ee_implementation_or_noop( tenant_id = await fetch_ee_implementation_or_noop(
"onyx.server.tenants.provisioning", "onyx.server.tenants.provisioning",
"get_or_create_tenant_id", "get_or_provision_tenant",
async_return_default_schema, async_return_default_schema,
)( )(
email=email, email=email,
@ -563,7 +567,7 @@ class TenantAwareJWTStrategy(JWTStrategy):
async def _create_token_data(self, user: User, impersonate: bool = False) -> dict: async def _create_token_data(self, user: User, impersonate: bool = False) -> dict:
tenant_id = await fetch_ee_implementation_or_noop( tenant_id = await fetch_ee_implementation_or_noop(
"onyx.server.tenants.provisioning", "onyx.server.tenants.provisioning",
"get_or_create_tenant_id", "get_or_provision_tenant",
async_return_default_schema, async_return_default_schema,
)( )(
email=user.email, email=user.email,