Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor(customer-analytics): Move account CRUD presentation behind facade (#64982)

Arthur Moreira de Deus01b016ad6a36
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index c591aa61d39c..26401ba3b080 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -15,15 +15,18 @@ Do NOT:
- Import DRF, serializers, or HTTP concerns
"""
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any, Optional, cast
from django.core.exceptions import ValidationError
-from django.db import transaction
-from django.db.models import Q
+from django.db import IntegrityError, transaction
+from django.db.models import Prefetch, Q
+
+from pydantic import ValidationError as PydanticValidationError
from posthog.api.tagged_item import set_tags_on_object
from posthog.exceptions_capture import capture_exception
from posthog.models import OrganizationMembership, Tag
+from posthog.models.activity_logging.activity_log import AuditableScope, Detail, changes_between, log_activity
from posthog.models.tag import tagify
from posthog.models.tagged_item import TaggedItem
@@ -32,13 +35,14 @@ from products.customer_analytics.backend.constants import ACCOUNT_ASSIGNMENT_ROL
from products.customer_analytics.backend.logic.usage_spike_notifications import (
notify_managers_of_usage_spike as notify_managers_of_usage_spike,
)
-from products.customer_analytics.backend.models import Account
+from products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfig
from products.customer_analytics.backend.models.account import AccountProperties as _ModelAccountProperties
from products.notebooks.backend.models import Notebook, ResourceNotebook
from . import contracts
if TYPE_CHECKING:
+ from posthog.models.user import User
from posthog.rbac.user_access_control import UserAccessControl
@@ -334,3 +338,788 @@ def update_external_account(
account.refresh_from_db()
return contracts.ExternalAccountUpdateResult(account=_to_external_account(account))
+
+
+# ---------------------------------------------------------------------------
+# Presentation wave: account / customer-journey / profile-config CRUD.
+#
+# The four DRF viewsets that back the Accounts UI reach their models exclusively
+# through the functions below. Everything HTTP — request validation, status
+# codes, pagination wiring, permission-mixin gating — stays in the view; the data
+# access, transactions, conflict handling, pydantic-error formatting, and the
+# activity logging that used to live in ``presentation/views/utils.py`` and the
+# ViewSets' ``perform_*`` hooks all live here.
+# ---------------------------------------------------------------------------
+
+
+class AccountConflictError(Exception):
+ """Raised when an account write violates the per-team unique external_id constraint."""
+
+
+class AccountPropertiesValidationError(Exception):
+ """Raised when account properties fail the pydantic schema. ``messages`` mirrors the
+ field-error list the old serializer produced from ``PydanticValidationError``."""
+
+ def __init__(self, messages: list[str]) -> None:
+ super().__init__("; ".join(messages))
+ self.messages = messages
+
+
+class CustomerJourneyConflictError(Exception):
+ """Raised when a customer journey already exists for the given insight (per team)."""
+
+
+class ResourceForbiddenError(Exception):
+ """Raised when the caller passes resource/object access checks at the team level but
+ lacks the object-level access required for the action — the view maps this to 403,
+ matching the ``AccessControlPermission.has_object_permission`` path it replaces."""
+
+
+# Re-export the "not found" exceptions so the view can branch to 404 without importing the
+# models. They are model ``DoesNotExist`` subclasses raised by the team-scoped detail fetches.
+Account_DoesNotExist = Account.DoesNotExist
+CustomerJourney_DoesNotExist = CustomerJourney.DoesNotExist
+
+
+def _format_pydantic_errors(exc: PydanticValidationError) -> list[str]:
+ messages = []
+ for err in exc.errors():
+ loc = ".".join(str(part) for part in err["loc"])
+ messages.append(f"{loc}: {err['msg']}" if loc else err["msg"])
+ return messages
+
+
+def _set_tags(tags: list[str] | None, obj) -> None:
+ """Replace ``obj``'s tags, creating/deleting ``TaggedItem`` rows individually so each
+ change emits its own activity-log entry (the account activity stream depends on this).
+
+ Mirrors ``posthog.api.tagged_item.set_tags_on_object`` + ``cleanup_orphan_tags`` but
+ stays on pure-model imports so the facade keeps DRF off its import path. ``None`` means
+ "tags not supplied" — leave them untouched (matches the serializer mixin).
+
+ Sets ``obj.prefetched_tags`` to the resulting rows so a freshly-written account renders
+ its new tags without re-reading a stale prefetch (the mixin did the same)."""
+ if tags is None:
+ return
+ deduped_tags = list({tagify(t) for t in tags})
+ tagged_item_objects = []
+ for tag in deduped_tags:
+ tag_instance, _ = Tag.objects.get_or_create(name=tag, team_id=obj.team_id)
+ tagged_item_instance, _ = obj.tagged_items.get_or_create(tag_id=tag_instance.id)
+ tagged_item_instance.tag = tag_instance
+ tagged_item_objects.append(tagged_item_instance)
+ for tagged_item in obj.tagged_items.exclude(tag__name__in=deduped_tags):
+ tagged_item.delete()
+ Tag.objects.filter(Q(team_id=obj.team_id) & Q(tagged_items__isnull=True)).delete()
+ obj.prefetched_tags = tagged_item_objects
+
+
+def _log_activity_swallowing(
+ *,
+ instance,
+ scope: str,
+ activity: str,
+ name: str,
+ organization_id,
+ team_id: int,
+ user: "User",
+ was_impersonated: bool,
+ previous=None,
+) -> None:
+ """Replicates ``posthog.api.utils.log_activity_from_viewset`` — including its blanket
+ ``except: pass`` — for the account / customer-journey write paths."""
+ try:
+ detail_kwargs: dict[str, Any] = {"name": name}
+ if previous is not None:
+ detail_kwargs["changes"] = changes_between(cast(AuditableScope, scope), previous=previous, current=instance)
+ log_activity(
+ organization_id=organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=str(instance.id),
+ scope=scope,
+ activity=activity,
+ detail=Detail(**detail_kwargs),
+ )
+ except Exception:
+ pass
+
+
+# --- CustomerProfileConfig ---
+
+
+def _to_customer_profile_config_view(config: CustomerProfileConfig) -> contracts.CustomerProfileConfigView:
+ return contracts.CustomerProfileConfigView(
+ id=config.id,
+ scope=config.scope,
+ content=config.content,
+ sidebar=config.sidebar,
+ created_at=config.created_at,
+ updated_at=config.updated_at,
+ )
+
+
+def _log_customer_profile_config_activity(
+ *,
+ instance: CustomerProfileConfig,
+ activity: str,
+ organization_id,
+ team_id: int,
+ user: "User",
+ was_impersonated: bool,
+ previous: Optional[CustomerProfileConfig] = None,
+) -> None:
+ """Folds in ``presentation/views/utils.log_customer_profile_config_activity`` verbatim
+ (note: unlike the account/journey path, this one does NOT swallow exceptions)."""
+ name = f"{instance.scope} profile"
+ changes = changes_between("CustomerProfileConfig", previous=previous, current=instance)
+ log_activity(
+ organization_id=organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=str(instance.id),
+ scope="CustomerProfileConfig",
+ activity=activity,
+ detail=Detail(name=name, changes=changes),
+ )
+
+
+def list_customer_profile_configs(
+ team_id: int, offset: int, limit: int
+) -> tuple[list[contracts.CustomerProfileConfigView], int]:
+ """Profile configs for the team. Returns ``(page, total_count)``."""
+ queryset = CustomerProfileConfig.objects.filter(team_id=team_id)
+ total_count = queryset.count()
+ page = queryset[offset : offset + limit]
+ return [_to_customer_profile_config_view(c) for c in page], total_count
+
+
+def get_customer_profile_config(team_id: int, config_id: str) -> contracts.CustomerProfileConfigView | None:
+ config = _get_team_scoped(CustomerProfileConfig, team_id, config_id)
+ return _to_customer_profile_config_view(config) if config is not None else None
+
+
+def create_customer_profile_config(
+ *,
+ team_id: int,
+ scope: str,
+ content: Any,
+ sidebar: Any,
+ organization_id,
+ user: "User",
+ was_impersonated: bool,
+) -> contracts.CustomerProfileConfigView:
+ config = CustomerProfileConfig.objects.create(
+ team_id=team_id, created_by=user, scope=scope, content=content, sidebar=sidebar
+ )
+ _log_customer_profile_config_activity(
+ instance=config,
+ activity="created",
+ organization_id=organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ )
+ return _to_customer_profile_config_view(config)
+
+
+def update_customer_profile_config(
+ *,
+ team_id: int,
+ config_id: str,
+ fields: dict[str, Any],
+ organization_id,
+ user: "User",
+ was_impersonated: bool,
+) -> contracts.CustomerProfileConfigView | None:
+ """Apply ``fields`` (only the keys the caller sent) to a team-scoped config. Returns the
+ updated view, or None when no config matches the id for this team (→ 404 in the view)."""
+ config = _get_team_scoped(CustomerProfileConfig, team_id, config_id)
+ if config is None:
+ return None
+ previous = CustomerProfileConfig.objects.get(pk=config.pk)
+ for attr, value in fields.items():
+ setattr(config, attr, value)
+ config.save()
+ _log_customer_profile_config_activity(
+ instance=config,
+ activity="updated",
+ organization_id=organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ previous=previous,
+ )
+ return _to_customer_profile_config_view(config)
+
+
+def delete_customer_profile_config(
+ *,
+ team_id: int,
+ config_id: str,
+ organization_id,
+ user: "User",
+ was_impersonated: bool,
+) -> bool:
+ """Delete a team-scoped config. Returns False when none matched (→ 404)."""
+ config = _get_team_scoped(CustomerProfileConfig, team_id, config_id)
+ if config is None:
+ return False
+ instance_id = config.id
+ instance_scope = config.scope
+ config.delete()
+ # Mirror the old viewset: log against a transient instance carrying the deleted id/scope.
+ _log_customer_profile_config_activity(
+ instance=CustomerProfileConfig(id=instance_id, scope=instance_scope),
+ activity="deleted",
+ organization_id=organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ )
+ return True
+
+
+# --- CustomerJourney ---
+
+
+def _to_customer_journey_view(journey: CustomerJourney) -> contracts.CustomerJourneyView:
+ return contracts.CustomerJourneyView(
+ id=journey.id,
+ insight=journey.insight_id,
+ name=journey.name,
+ description=journey.description,
+ created_at=journey.created_at,
+ created_by=journey.created_by_id,
+ updated_at=journey.updated_at,
+ )
+
+
+def _customer_journeys_queryset(team_id: int):
+ """Team-scoped customer journeys, ordered by creation. Object-level access filtering is
+ applied by the caller (list applies it; detail relies on the per-object check)."""
+ return CustomerJourney.objects.order_by("created_at").filter(team_id=team_id)
+
+
+def insight_belongs_to_team(team_id: int, insight_id: int) -> bool:
+ """Whether the given insight is in the team — backs the journey serializer's
+ ``validate_insight`` (kept as a cheap existence probe so the model stays hidden)."""
+ from products.product_analytics.backend.models.insight import Insight
+
+ return Insight.objects.filter(pk=insight_id, team_id=team_id).exists()
+
+
+def list_customer_journeys(
+ team_id: int, offset: int, limit: int, user_access_control: "UserAccessControl"
+) -> tuple[list[contracts.CustomerJourneyView], int]:
+ queryset = user_access_control.filter_queryset_by_access_level(_customer_journeys_queryset(team_id))
+ total_count = queryset.count()
+ page = queryset[offset : offset + limit]
+ return [_to_customer_journey_view(j) for j in page], total_count
+
+
+def get_customer_journey(
+ team_id: int, journey_id: str, user_access_control: "UserAccessControl", required_level: str | None
+) -> contracts.CustomerJourneyView:
+ """Fetch one team-scoped journey, enforcing object-level access. Raises
+ ``CustomerJourney.DoesNotExist`` (→ 404) when absent and ``ResourceForbiddenError``
+ (→ 403) when the caller lacks object access — mirroring the old viewset."""
+ journey = _get_object_or_raise(_customer_journeys_queryset(team_id), journey_id, CustomerJourney)
+ _enforce_object_access(journey, user_access_control, required_level)
+ return _to_customer_journey_view(journey)
+
+
+def create_customer_journey(
+ *,
+ team_id: int,
+ insight_id: int,
+ name: str,
+ description: str | None,
+ organization_id,
+ user: "User",
+ was_impersonated: bool,
+) -> contracts.CustomerJourneyView:
+ try:
+ journey = CustomerJourney.objects.create(
+ team_id=team_id, created_by=user, insight_id=insight_id, name=name, description=description
+ )
+ except IntegrityError:
+ raise CustomerJourneyConflictError("A customer journey already exists for this insight.")
+ _log_activity_swallowing(
+ instance=journey,
+ scope="CustomerJourney",
+ activity="created",
+ name=journey.name,
+ organization_id=organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ )
+ return _to_customer_journey_view(journey)
+
+
+def update_customer_journey(
+ *,
+ team_id: int,
+ journey_id: str,
+ fields: dict[str, Any],
+ user_access_control: "UserAccessControl",
+ required_level: str | None,
+ organization_id,
+ user: "User",
+ was_impersonated: bool,
+) -> contracts.CustomerJourneyView:
+ journey = _get_object_or_raise(_customer_journeys_queryset(team_id), journey_id, CustomerJourney)
+ _enforce_object_access(journey, user_access_control, required_level)
+ previous = CustomerJourney.objects.get(pk=journey.pk)
+ for attr, value in fields.items():
+ setattr(journey, attr, value)
+ journey.save()
+ _log_activity_swallowing(
+ instance=journey,
+ scope="CustomerJourney",
+ activity="updated",
+ name=journey.name,
+ organization_id=organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ previous=previous,
+ )
+ return _to_customer_journey_view(journey)
+
+
+def delete_customer_journey(
+ *,
+ team_id: int,
+ journey_id: str,
+ user_access_control: "UserAccessControl",
+ required_level: str | None,
+ organization_id,
+ user: "User",
+ was_impersonated: bool,
+) -> None:
+ journey = _get_object_or_raise(_customer_journeys_queryset(team_id), journey_id, CustomerJourney)
+ _enforce_object_access(journey, user_access_control, required_level)
+ _log_activity_swallowing(
+ instance=journey,
+ scope="CustomerJourney",
+ activity="deleted",
+ name=journey.name,
+ organization_id=organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ )
+ journey.delete()
+
+
+# --- Account (full CRUD view) ---
+
+
+def _account_view_tags(account: Account) -> list[str]:
+ """Tags for an account, preferring the prefetched list when present (list path) so
+ the query budget stays flat — matching the old ``TaggedItemSerializerMixin``."""
+ if hasattr(account, "prefetched_tags"):
+ return [p.tag.name for p in account.prefetched_tags]
+ return list(account.tagged_items.values_list("tag__name", flat=True)) if account.pk else []
+
+
+def _account_view_notebooks(account: Account) -> list[str]:
+ return [link.notebook.short_id for link in account.notebooks.all()]
+
+
+def _to_account_view(account: Account) -> contracts.AccountView:
+ return contracts.AccountView(
+ id=account.id,
+ name=account.name,
+ external_id=account.external_id,
+ # Raw stored JSON (already ``exclude_unset`` from the manager), so an account with
+ # no assignments serializes ``properties`` as ``{}`` exactly as before.
+ properties=account._properties or {},
+ # Unsorted, matching the old ``TaggedItemSerializerMixin.to_representation`` output.
+ tags=_account_view_tags(account),
+ notebooks=_account_view_notebooks(account),
+ created_at=account.created_at,
+ created_by=account.created_by_id,
+ updated_at=account.updated_at,
+ )
+
+
+def list_accounts_for_view(
+ *,
+ team_id: int,
+ user_access_control: "UserAccessControl",
+ offset: int,
+ limit: int,
+ search: str | None = None,
+ tags: list[str] | None = None,
+ csm: str | None = None,
+ account_executive: str | None = None,
+ account_owner: str | None = None,
+ all_roles_unassigned: bool = False,
+ ordering: str | None = None,
+) -> tuple[list[contracts.AccountView], int]:
+ """The accounts list endpoint, behind the facade: team + object-level access filtering,
+ the search / tags / role / ordering query filters, notebook + tag prefetching, and
+ pagination. Returns ``(page, total_count)``. ``tags``/``ordering`` are pre-validated by
+ the view; an empty ``tags`` list is treated as "no tag filter" (matches old behavior)."""
+ queryset = _accounts_queryset(team_id, user_access_control).prefetch_related(
+ Prefetch("notebooks", queryset=ResourceNotebook.objects.select_related("notebook")),
+ Prefetch("tagged_items", queryset=TaggedItem.objects.select_related("tag"), to_attr="prefetched_tags"),
+ )
+
+ if search:
+ queryset = queryset.filter(Q(name__icontains=search) | Q(external_id__icontains=search))
+
+ if tags:
+ queryset = queryset.filter(tagged_items__tag__name__in=tags).distinct()
+
+ # An unset role serializes as JSON null, which ``_properties__role__isnull`` does not
+ # match; probing the nested ``id`` matches every unassigned shape (missing key, null
+ # value, or empty object).
+ if all_roles_unassigned:
+ queryset = queryset.filter(
+ _properties__csm__id__isnull=True,
+ _properties__account_executive__id__isnull=True,
+ _properties__account_owner__id__isnull=True,
+ )
+
+ if csm == "unassigned":
+ queryset = queryset.filter(_properties__csm__id__isnull=True)
+ elif csm:
+ try:
+ queryset = queryset.filter(_properties__csm__id=int(csm))
+ except ValueError:
+ # Malformed user id is a no-op (return all), not "match nothing" — old behavior.
+ pass
+
+ if account_executive == "unassigned":
+ queryset = queryset.filter(_properties__account_executive__id__isnull=True)
+ elif account_executive:
+ try:
+ queryset = queryset.filter(_properties__account_executive__id=int(account_executive))
+ except ValueError:
+ pass
+
+ if account_owner == "unassigned":
+ queryset = queryset.filter(_properties__account_owner__id__isnull=True)
+ elif account_owner:
+ try:
+ queryset = queryset.filter(_properties__account_owner__id=int(account_owner))
+ except ValueError:
+ pass
+
+ queryset = queryset.order_by(ordering) if ordering else queryset.order_by("-created_at")
+
+ total_count = queryset.count()
+ page = list(queryset[offset : offset + limit])
+ return [_to_account_view(a) for a in page], total_count
+
+
+def get_account_for_view(
+ *, team_id: int, account_id: str, user_access_control: "UserAccessControl", required_level: str | None
+) -> contracts.AccountView:
+ """Fetch one team-scoped account with tags + notebooks, enforcing object-level access.
+ Raises ``Account.DoesNotExist`` (→ 404) / ``ResourceForbiddenError`` (→ 403)."""
+ account = _get_account_for_detail(team_id, account_id)
+ _enforce_object_access(account, user_access_control, required_level)
+ return _to_account_view(account)
+
+
+def create_account_for_view(
+ *,
+ team_id: int,
+ team,
+ input: contracts.CreateAccountInput,
+ organization_id,
+ user: "User",
+ was_impersonated: bool,
+) -> contracts.AccountView:
+ try:
+ with transaction.atomic():
+ account = Account.objects.create_account(
+ team=team,
+ created_by=user,
+ name=input.name,
+ external_id=input.external_id,
+ properties=input.properties,
+ )
+ _set_tags(input.tags, account)
+ except PydanticValidationError as exc:
+ raise AccountPropertiesValidationError(_format_pydantic_errors(exc))
+ except IntegrityError:
+ raise AccountConflictError("An account with this external_id already exists for this team.")
+ _log_activity_swallowing(
+ instance=account,
+ scope="Account",
+ activity="created",
+ name=account.name,
+ organization_id=organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ )
+ return _to_account_view(account)
+
+
+def update_account_for_view(
+ *,
+ team_id: int,
+ account_id: str,
+ input: contracts.UpdateAccountInput,
+ user_access_control: "UserAccessControl",
+ required_level: str | None,
+ organization_id,
+ user: "User",
+ was_impersonated: bool,
+) -> contracts.AccountView:
+ account = _get_account_for_detail(team_id, account_id)
+ _enforce_object_access(account, user_access_control, required_level)
+ previous = Account.objects.unscoped().get(pk=account.pk)
+
+ update_kwargs: dict[str, Any] = {}
+ if input.name is not None:
+ update_kwargs["name"] = input.name
+ if input.external_id_provided:
+ update_kwargs["external_id"] = input.external_id
+ if input.properties_provided:
+ update_kwargs["properties"] = input.properties if input.properties is not None else {}
+
+ try:
+ with transaction.atomic():
+ account = Account.objects.update_account(account, **update_kwargs)
+ _set_tags(input.tags, account)
+ except PydanticValidationError as exc:
+ raise AccountPropertiesValidationError(_format_pydantic_errors(exc))
+ except IntegrityError:
+ raise AccountConflictError("An account with this external_id already exists for this team.")
+ _log_activity_swallowing(
+ instance=account,
+ scope="Account",
+ activity="updated",
+ name=account.name,
+ organization_id=organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ previous=previous,
+ )
+ return _to_account_view(account)
+
+
+def delete_account_for_view(
+ *,
+ team_id: int,
+ account_id: str,
+ user_access_control: "UserAccessControl",
+ required_level: str | None,
+ organization_id,
+ user: "User",
+ was_impersonated: bool,
+) -> None:
+ account = _get_account_for_detail(team_id, account_id)
+ _enforce_object_access(account, user_access_control, required_level)
+ _log_activity_swallowing(
+ instance=account,
+ scope="Account",
+ activity="deleted",
+ name=account.name,
+ organization_id=organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ )
+ account.delete()
+
+
+def _get_account_for_detail(team_id: int, account_id: str) -> Account:
+ """Team-scoped account fetch for detail/write paths (object-level access is enforced
+ separately). Prefetches notebooks + tags so the returned view renders without extra
+ queries, matching the old viewset's ``safely_get_queryset`` + tag-mixin prefetch.
+ Raises ``Account.DoesNotExist`` when not found in the team."""
+ queryset = (
+ Account.objects.unscoped()
+ .filter(team_id=team_id)
+ .prefetch_related(
+ Prefetch("notebooks", queryset=ResourceNotebook.objects.select_related("notebook")),
+ Prefetch("tagged_items", queryset=TaggedItem.objects.select_related("tag"), to_attr="prefetched_tags"),
+ )
+ )
+ return _get_object_or_raise(queryset, account_id, Account)
+
+
+# --- AccountNotebook (nested under an account) ---
+
+
+def _to_user_basic_info(user: "User | None") -> contracts.UserBasicInfo | None:
+ # None when the notebook has no creator/modifier — the old nested
+ # ``UserBasicSerializer`` rendered ``null`` for a null FK, so preserve that.
+ if user is None:
+ return None
+ return contracts.UserBasicInfo(
+ id=user.id,
+ uuid=user.uuid,
+ distinct_id=user.distinct_id,
+ first_name=user.first_name,
+ last_name=user.last_name,
+ email=user.email,
+ is_email_verified=user.is_email_verified,
+ hedgehog_config=user.hedgehog_config,
+ role_at_organization=user.role_at_organization,
+ )
+
+
+def _to_account_notebook_view(notebook: Notebook) -> contracts.AccountNotebookView:
+ return contracts.AccountNotebookView(
+ id=notebook.id,
+ short_id=notebook.short_id,
+ title=notebook.title,
+ content=notebook.content,
+ text_content=notebook.text_content,
+ created_at=notebook.created_at,
+ created_by=_to_user_basic_info(notebook.created_by),
+ last_modified_at=notebook.last_modified_at,
+ last_modified_by=_to_user_basic_info(notebook.last_modified_by),
+ )
+
+
+def get_accessible_account_id(team_id: int, account_id: str, user_access_control: "UserAccessControl") -> str | None:
+ """The account_id when the caller has object-level access to that team-scoped account,
+ else None — backs the notebook viewset's parent-account gate (object denial → 404,
+ via filtering rather than a permission check)."""
+ queryset = user_access_control.filter_queryset_by_access_level(Account.objects.unscoped().filter(team_id=team_id))
+ try:
+ account = queryset.filter(id=account_id).first()
+ except (ValidationError, ValueError):
+ return None
+ return str(account.id) if account is not None else None
+
+
+def list_account_notebooks(
+ team_id: int, account_id: str, user_access_control: "UserAccessControl"
+) -> list[contracts.AccountNotebookView] | None:
+ """Internal notebooks linked to an accessible account, newest first. None when the
+ parent account isn't accessible (→ 404)."""
+ if get_accessible_account_id(team_id, account_id, user_access_control) is None:
+ return None
+ notebooks = (
+ Notebook.objects.filter(
+ deleted=False,
+ visibility=Notebook.Visibility.INTERNAL,
+ resources__account_id=account_id,
+ )
+ .select_related("created_by", "last_modified_by")
+ .order_by("-last_modified_at")
+ )
+ return [_to_account_notebook_view(n) for n in notebooks]
+
+
+def get_account_notebook(
+ team_id: int, account_id: str, short_id: str, user_access_control: "UserAccessControl"
+) -> contracts.AccountNotebookView | None:
+ """One internal notebook linked to an accessible account. None when the account isn't
+ accessible or no such linked notebook exists (→ 404)."""
+ if get_accessible_account_id(team_id, account_id, user_access_control) is None:
+ return None
+ notebook = (
+ Notebook.objects.filter(
+ deleted=False,
+ visibility=Notebook.Visibility.INTERNAL,
+ resources__account_id=account_id,
+ short_id=short_id,
+ )
+ .select_related("created_by", "last_modified_by")
+ .first()
+ )
+ return _to_account_notebook_view(notebook) if notebook is not None else None
+
+
+def create_account_notebook(
+ *,
+ team_id: int,
+ team,
+ account_id: str,
+ input: contracts.CreateAccountNotebookInput,
+ user: "User",
+ user_access_control: "UserAccessControl",
+) -> contracts.AccountNotebookView | None:
+ """Create an internal notebook and link it to an accessible account. None when the
+ parent account isn't accessible (→ 404). The view supplies ``synthesized_content``
+ (markdown→tiptap) so the ``ee.hogai`` helper stays off the facade import path."""
+ if get_accessible_account_id(team_id, account_id, user_access_control) is None:
+ return None
+ save_kwargs: dict[str, Any] = {
+ "team": team,
+ "created_by": user,
+ "last_modified_by": user,
+ "visibility": Notebook.Visibility.INTERNAL,
+ "title": input.title,
+ "text_content": input.text_content,
+ }
+ if input.synthesized_content is not None:
+ save_kwargs["content"] = input.synthesized_content
+ elif input.content is not None:
+ save_kwargs["content"] = input.content
+ with transaction.atomic():
+ notebook = Notebook.objects.create(**save_kwargs)
+ ResourceNotebook.objects.create(notebook=notebook, account_id=account_id)
+ return _to_account_notebook_view(notebook)
+
+
+def delete_account_notebook(
+ *, team_id: int, account_id: str, short_id: str, user_access_control: "UserAccessControl"
+) -> bool:
+ """Delete an internal notebook linked to an accessible account. False when the account
+ isn't accessible or no such notebook exists (→ 404)."""
+ if get_accessible_account_id(team_id, account_id, user_access_control) is None:
+ return False
+ notebook = Notebook.objects.filter(
+ deleted=False,
+ visibility=Notebook.Visibility.INTERNAL,
+ resources__account_id=account_id,
+ short_id=short_id,
+ ).first()
+ if notebook is None:
+ return False
+ with transaction.atomic():
+ notebook.delete()
+ return True
+
+
+# --- shared resolution / access helpers for the CRUD paths ---
+
+
+def _get_team_scoped(model, team_id: int, pk: str):
+ """Fetch a team-scoped row by pk, or None (malformed/absent). Used by the
+ profile-config path, whose old viewset returned 404 for both."""
+ try:
+ return model.objects.filter(team_id=team_id).get(pk=pk)
+ except (model.DoesNotExist, ValidationError, ValueError):
+ return None
+
+
+def _get_object_or_raise(queryset, pk: str, model):
+ """Fetch by pk from an already-scoped queryset, raising ``model.DoesNotExist`` for
+ absent/malformed ids (the view maps that to 404)."""
+ try:
+ obj = queryset.filter(pk=pk).first()
+ except (ValidationError, ValueError):
+ raise model.DoesNotExist()
+ if obj is None:
+ raise model.DoesNotExist()
+ return obj
+
+
+def _enforce_object_access(obj, user_access_control: "UserAccessControl", required_level: str | None) -> None:
+ """Object-level access gate matching ``AccessControlPermission.has_object_permission``:
+ raise ``ResourceForbiddenError`` (→ 403) when the caller lacks ``required_level`` on the
+ object. The view computes ``required_level`` from the HTTP method (viewer / editor), and
+ passes ``None`` when the permission layer would skip the object check (service auth) — in
+ which case the gate is a no-op, exactly like ``has_object_permission`` returning early."""
+ if required_level is None:
+ return
+ if not user_access_control.check_access_level_for_object(obj, required_level=required_level): # type: ignore[arg-type]
+ raise ResourceForbiddenError()
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 16bb7057f001..6a70d2149047 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -10,9 +10,13 @@ construction, so structural mistakes from mappers surface at the facade boundary
instead of producing a malformed payload deeper in a caller.
"""
-from dataclasses import field
+from dataclasses import (
+ dataclass as stdlib_dataclass,
+ field,
+)
from datetime import datetime
from enum import Enum
+from typing import Any
from uuid import UUID
from pydantic.dataclasses import dataclass
@@ -137,3 +141,169 @@ class ExternalAccountUpdateResult:
account: ExternalAccount | None = None
error: ExternalAccountUpdateError | None = None
error_field: str | None = None
+
+
+# --- Presentation wave: views that back the Accounts CRUD endpoints ---
+#
+# These contracts shape the DRF responses for the account/customer-journey/
+# customer-profile-config viewsets. They are wire-faithful to the pre-isolation
+# ``ModelSerializer`` output so the OpenAPI schema (and every downstream generated
+# type / MCP tool) stays byte-identical. ``Any`` is used for free-form JSON values
+# (account properties, notebook content) so pydantic passes them through verbatim
+# rather than coercing.
+
+
+@stdlib_dataclass(frozen=True)
+class UserBasicInfo:
+ """Mirror of ``posthog.api.shared.UserBasicSerializer`` output, field-for-field.
+
+ Carries the raw user values (not the rendered representation) so the presentation
+ layer can serialize it through the core ``UserBasicSerializer`` — keeping the
+ generated ``UserBasic`` OpenAPI component identical. ``hedgehog_config`` stays the
+ raw stored value; ``UserBasicSerializer.get_hedgehog_config`` shapes it at render
+ time exactly as before.
+ """
+
+ id: int
+ uuid: UUID
+ distinct_id: str | None
+ first_name: str
+ last_name: str
+ email: str
+ is_email_verified: bool | None
+ hedgehog_config: Any
+ role_at_organization: str | None
+
+
+@stdlib_dataclass(frozen=True)
+class AccountView:
+ """An account as returned by the accounts list/detail endpoints.
+
+ ``properties`` is the raw stored JSON dict (``Account._properties``), not the
+ typed :class:`AccountProperties`, so ``exclude_unset`` semantics are preserved —
+ an account with no assignments serializes ``properties`` as ``{}`` rather than a
+ full object of nulls. ``created_by`` is the creator's user id (or ``None``),
+ matching the model serializer's ``PrimaryKeyRelatedField`` output.
+
+ The serializer that wraps this contract is reused as the viewset's
+ ``serializer_class`` for both request and response (keeping the OpenAPI ``Account``
+ / ``PatchedAccount`` components byte-identical to the old ``ModelSerializer``). To
+ let that serializer instantiate the contract from a partial PATCH body, every field
+ carries a default — those defaults never reach output (the facade always supplies
+ real values) and never relax validation (the serializer pins ``required`` /
+ ``read_only`` explicitly).
+ """
+
+ id: UUID | None = None
+ name: str = ""
+ external_id: str | None = None
+ properties: dict = field(default_factory=dict)
+ tags: list[str] = field(default_factory=list)
+ notebooks: list[str] = field(default_factory=list)
+ created_at: datetime | None = None
+ created_by: int | None = None
+ updated_at: datetime | None = None
+
+
+@stdlib_dataclass(frozen=True)
+class CustomerJourneyView:
+ """A customer journey as returned by the customer-journey endpoints.
+
+ Defaults exist for the same reason as :class:`AccountView` — the wrapping serializer
+ doubles as request + response so the OpenAPI components stay identical.
+ """
+
+ id: UUID | None = None
+ insight: int = 0
+ name: str = ""
+ description: str | None = None
+ created_at: datetime | None = None
+ created_by: int | None = None
+ updated_at: datetime | None = None
+
+
+@stdlib_dataclass(frozen=True)
+class CustomerProfileConfigView:
+ """A customer profile config as returned by the profile-config endpoints.
+
+ Defaults exist so the wrapping serializer can parse partial request bodies (see
+ :class:`AccountView`).
+ """
+
+ id: UUID | None = None
+ scope: str = ""
+ content: Any = None
+ sidebar: Any = None
+ created_at: datetime | None = None
+ updated_at: datetime | None = None
+
+
+@stdlib_dataclass(frozen=True)
+class AccountNotebookView:
+ """An account notebook as returned by the nested account-notebooks endpoints.
+
+ Defaults exist so the wrapping serializer can parse partial request bodies (see
+ :class:`AccountView`).
+ """
+
+ id: UUID | None = None
+ short_id: str = ""
+ title: str | None = None
+ content: Any = None
+ text_content: str | None = None
+ created_at: datetime | None = None
+ created_by: UserBasicInfo | None = None
+ last_modified_at: datetime | None = None
+ last_modified_by: UserBasicInfo | None = None
+
+
+# --- Presentation wave: input contracts for the CRUD write paths ---
+
+
+@dataclass(frozen=True)
+class CreateAccountInput:
+ """Validated body for creating an account.
+
+ ``properties`` is the raw client dict; the facade hands it to the model manager,
+ which validates it against the pydantic ``AccountProperties`` schema (rejecting
+ unknown keys and malformed assignments).
+ """
+
+ name: str
+ external_id: str | None = None
+ properties: dict = field(default_factory=dict)
+ tags: list[str] | None = None
+
+
+@dataclass(frozen=True)
+class UpdateAccountInput:
+ """Validated partial body for updating an account.
+
+ Each field is optional; only the keys the caller supplied are applied, so a PATCH
+ that omits ``name`` leaves the name unchanged. ``tags`` of ``None`` means "tags
+ not provided" (left untouched), distinct from ``[]`` (clear all tags).
+ """
+
+ name: str | None = None
+ external_id: str | None = None
+ properties: dict | None = None
+ tags: list[str] | None = None
+ # Distinguishes "external_id omitted" from "external_id explicitly set to null".
+ external_id_provided: bool = False
+ properties_provided: bool = False
+
+
+@dataclass(frozen=True)
+class CreateAccountNotebookInput:
+ """Validated body for creating an account notebook.
+
+ ``content`` is the ProseMirror document the caller supplied (or ``None``);
+ ``synthesized_content`` is the markdown-derived document the view built when the
+ caller passed only ``text_content`` — the view owns that normalization so the
+ ``ee.hogai`` tiptap helper stays off the facade import path.
+ """
+
+ title: str | None
+ content: Any
+ text_content: str | None
+ synthesized_content: Any = None
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 9009c7abaf34..9ae907ad61aa 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -1,19 +1,53 @@
-import json
+"""DRF serializers for the customer_analytics account CRUD presentation layer.
+
+The model-backed viewsets used to bind ``ModelSerializer``s straight to ``Account`` /
+``CustomerJourney`` / ``CustomerProfileConfig``. They now serialize the facade's frozen
+contracts via ``DataclassSerializer`` instead, so this module no longer imports product
+models. Every field is declared explicitly to keep the generated OpenAPI components
+(``Account``, ``PatchedAccount``, ``CustomerJourney``, ``CustomerProfileConfig``,
+``AccountNotebook``, ``UserBasic`` …) byte-identical to the pre-isolation output.
+
+Each serializer doubles as the viewset's ``serializer_class`` for both request and
+response — drf-spectacular derives the request component (and its ``Patched`` variant)
+from it exactly as it did for the ``ModelSerializer``s. The contracts carry field
+defaults purely so these serializers can instantiate them from partial request bodies;
+``required`` / ``read_only`` are pinned here, not by the dataclass.
+
+``AccountOrganizationMemberSerializer`` stays a ``ModelSerializer`` — it is bound to the
+core ``OrganizationMembership`` model (no customer_analytics dependency) and is imported
+by the sibling ``organization_members`` module.
+"""
-from django.db import IntegrityError, transaction
+import json
from drf_spectacular.utils import extend_schema_field
-from pydantic import ValidationError as PydanticValidationError
from rest_framework import serializers
+from rest_framework_dataclasses.serializers import DataclassSerializer
from posthog.api.shared import UserBasicSerializer
-from posthog.api.tagged_item import TaggedItemSerializerMixin
-from posthog.exceptions import Conflict
from posthog.models import OrganizationMembership
-from products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfig
-from products.notebooks.backend.models import Notebook
-
+from products.customer_analytics.backend.facade.contracts import (
+ AccountNotebookView,
+ AccountView,
+ CustomerJourneyView,
+ CustomerProfileConfigView,
+)
+
+# Scope (value, label) pairs, kept in sync with ``CustomerProfileConfig.Scope``. Declared
+# here rather than read off the model so this module imports no product models — the
+# generated ``CustomerProfileConfigScopeEnum`` stays identical to the model-derived one.
+_PROFILE_CONFIG_SCOPE_CHOICES = [
+ ("person", "Person"),
+ ("group_0", "Group 0"),
+ ("group_1", "Group 1"),
+ ("group_2", "Group 2"),
+ ("group_3", "Group 3"),
+ ("group_4", "Group 4"),
+]
+
+# JSON schema for the account ``properties`` field. Kept verbatim from the pre-isolation
+# serializer so the generated ``AccountApiProperties`` component is unchanged.
_ACCOUNT_ASSIGNMENT_SCHEMA = {
"type": "object",
"nullable": True,
@@ -47,33 +81,20 @@ class AccountPropertiesField(serializers.JSONField):
pass
-class CustomerProfileConfigSerializer(serializers.ModelSerializer):
+class CustomerProfileConfigSerializer(DataclassSerializer):
+ id = serializers.UUIDField(read_only=True)
+ scope = serializers.ChoiceField(choices=_PROFILE_CONFIG_SCOPE_CHOICES)
content = serializers.JSONField(required=False, allow_null=True, default=dict)
sidebar = serializers.JSONField(required=False, allow_null=True, default=dict)
+ created_at = serializers.DateTimeField(read_only=True)
+ updated_at = serializers.DateTimeField(read_only=True, allow_null=True)
class Meta:
- model = CustomerProfileConfig
- fields = [
- "id",
- "scope",
- "content",
- "sidebar",
- "created_at",
- "updated_at",
- ]
- read_only_fields = [
- "id",
- "created_at",
- "updated_at",
- ]
-
- @staticmethod
- def validate_scope(value):
- if value not in dict(CustomerProfileConfig.Scope.choices):
- raise serializers.ValidationError(
- f"Invalid scope '{value}'. Must be one of: {', '.join(dict(CustomerProfileConfig.Scope.choices).keys())}"
- )
- return value
+ dataclass = CustomerProfileConfigView
+ # Pin the OpenAPI component name to the pre-isolation one (DataclassSerializer would
+ # otherwise name it after the wrapped dataclass, ``CustomerProfileConfigView``).
+ ref_name = "CustomerProfileConfig"
+ fields = ["id", "scope", "content", "sidebar", "created_at", "updated_at"]
def validate_content(self, value):
return self._validate_json(field="content", value=value)
@@ -97,40 +118,26 @@ class CustomerProfileConfigSerializer(serializers.ModelSerializer):
return value
- def create(self, validated_data):
- request = self.context["request"]
- validated_data["created_by"] = request.user
- validated_data["team_id"] = self.context["team_id"]
- return super().create(validated_data)
+class CustomerJourneySerializer(DataclassSerializer):
+ id = serializers.UUIDField(read_only=True)
+ insight = serializers.IntegerField()
+ name = serializers.CharField(max_length=400)
+ description = serializers.CharField(required=False, allow_null=True)
+ created_at = serializers.DateTimeField(read_only=True)
+ created_by = serializers.IntegerField(read_only=True, allow_null=True)
+ updated_at = serializers.DateTimeField(read_only=True, allow_null=True)
-class CustomerJourneySerializer(serializers.ModelSerializer):
class Meta:
- model = CustomerJourney
+ dataclass = CustomerJourneyView
+ ref_name = "CustomerJourney"
fields = ["id", "insight", "name", "description", "created_at", "created_by", "updated_at"]
- read_only_fields = ["id", "created_at", "created_by", "updated_at"]
-
- def validate_insight(self, value):
- if value.team_id != self.context["team_id"]:
- raise serializers.ValidationError("The insight does not belong to this team.")
- return value
- def create(self, validated_data):
- from django.db import IntegrityError
- from posthog.exceptions import Conflict
-
- validated_data["created_by"] = self.context["request"].user
- validated_data["team_id"] = self.context["team_id"]
- try:
- return super().create(validated_data)
- except IntegrityError:
- raise Conflict("A customer journey already exists for this insight.")
-
-
-class AccountSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):
+class AccountSerializer(DataclassSerializer):
"""A Customer Analytics account — a logical grouping used to assign customer-success ownership."""
+ id = serializers.UUIDField(read_only=True)
name = serializers.CharField(
max_length=400,
help_text="Human-readable name of the account.",
@@ -146,7 +153,6 @@ class AccountSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):
),
)
properties = AccountPropertiesField(
- source="_properties",
required=False,
allow_null=True,
help_text=(
@@ -161,15 +167,21 @@ class AccountSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):
required=False,
help_text="Tag names attached to the account. Pass a list to replace existing tags.",
)
- notebooks = serializers.SerializerMethodField(
+ notebooks = serializers.ListField(
+ child=serializers.CharField(),
+ read_only=True,
help_text=(
"Short IDs of the internal notebooks linked to this account, used to persist investigations, "
"call notes, and other free-form context. Empty list if no notebooks have been created for the account."
- )
+ ),
)
+ created_at = serializers.DateTimeField(read_only=True)
+ created_by = serializers.IntegerField(read_only=True, allow_null=True)
+ updated_at = serializers.DateTimeField(read_only=True, allow_null=True)
class Meta:
- model = Account
+ dataclass = AccountView
+ ref_name = "Account"
fields = [
"id",
"name",
@@ -181,17 +193,6 @@ class AccountSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):
"created_by",
"updated_at",
]
- read_only_fields = [
- "id",
- "notebooks",
- "created_at",
- "created_by",
- "updated_at",
- ]
-
- @extend_schema_field({"type": "array", "items": {"type": "string"}})
- def get_notebooks(self, obj: Account) -> list[str]:
- return [link.notebook.short_id for link in obj.notebooks.all()]
def validate_properties(self, value):
if value is None:
@@ -204,52 +205,6 @@ class AccountSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):
raise serializers.ValidationError("properties must be JSON-serializable.")
return value
- def create(self, validated_data):
- properties = validated_data.pop("_properties", {})
- validated_data.pop("tags", None)
- try:
- with transaction.atomic():
- account = Account.objects.create_account(
- team=self.context["get_team"](),
- created_by=self.context["request"].user,
- name=validated_data["name"],
- external_id=validated_data.get("external_id"),
- properties=properties,
- )
- self._attempt_set_tags(self.initial_data.get("tags"), account)
- except PydanticValidationError as exc:
- raise serializers.ValidationError({"properties": _format_pydantic_errors(exc)})
- except IntegrityError:
- raise Conflict("An account with this external_id already exists for this team.")
- return account
-
- def update(self, instance, validated_data):
- update_kwargs: dict = {}
- if "name" in validated_data:
- update_kwargs["name"] = validated_data["name"]
- if "external_id" in validated_data:
- update_kwargs["external_id"] = validated_data["external_id"]
- if "_properties" in validated_data:
- update_kwargs["properties"] = validated_data["_properties"]
-
- try:
- with transaction.atomic():
- account = Account.objects.update_account(instance, **update_kwargs)
- self._attempt_set_tags(self.initial_data.get("tags"), account)
- except PydanticValidationError as exc:
- raise serializers.ValidationError({"properties": _format_pydantic_errors(exc)})
- except IntegrityError:
- raise Conflict("An account with this external_id already exists for this team.")
- return account
-
-
-def _format_pydantic_errors(exc: PydanticValidationError) -> list[str]:
- messages = []
- for err in exc.errors():
- loc = ".".join(str(part) for part in err["loc"])
- messages.append(f"{loc}: {err['msg']}" if loc else err["msg"])
- return messages
-
class AccountOrganizationMemberSerializer(serializers.ModelSerializer):
"""Slim organization-member representation for Customer analytics account rows."""
@@ -266,7 +221,9 @@ class AccountOrganizationMemberSerializer(serializers.ModelSerializer):
extra_kwargs = {"id": {"help_text": "Organization membership ID."}}
-class AccountNotebookSerializer(serializers.ModelSerializer):
+class AccountNotebookSerializer(DataclassSerializer):
+ id = serializers.UUIDField(read_only=True)
+ short_id = serializers.CharField(read_only=True)
created_by = UserBasicSerializer(read_only=True)
last_modified_by = UserBasicSerializer(read_only=True)
title = serializers.CharField(
@@ -287,9 +244,12 @@ class AccountNotebookSerializer(serializers.ModelSerializer):
allow_null=True,
help_text="Plain text representation of the notebook content for search.",
)
+ created_at = serializers.DateTimeField(read_only=True)
+ last_modified_at = serializers.DateTimeField(read_only=True)
class Meta:
- model = Notebook
+ dataclass = AccountNotebookView
+ ref_name = "AccountNotebook"
fields = [
"id",
"short_id",
@@ -301,11 +261,3 @@ class AccountNotebookSerializer(serializers.ModelSerializer):
"last_modified_at",
"last_modified_by",
]
- read_only_fields = [
- "id",
- "short_id",
- "created_at",
- "created_by",
- "last_modified_at",
- "last_modified_by",
- ]
diff --git a/products/customer_analytics/backend/presentation/views/utils.py b/products/customer_analytics/backend/presentation/views/utils.py
deleted file mode 100644
index d6ce94a85d23..000000000000
--- a/products/customer_analytics/backend/presentation/views/utils.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from typing import Optional, cast
-
-from loginas.utils import is_impersonated_session
-
-from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity
-from posthog.models.user import User
-
-from products.customer_analytics.backend.models import CustomerProfileConfig
-
-
-def log_customer_profile_config_activity(
- viewset,
- instance: CustomerProfileConfig,
- activity: str,
- previous: Optional[CustomerProfileConfig] = None,
-) -> None:
- name = f"{instance.scope} profile"
- changes = changes_between("CustomerProfileConfig", previous=previous, current=instance)
- detail = Detail(name=name, changes=changes)
- log_activity(
- organization_id=viewset.organization.id,
- team_id=viewset.team.id,
- user=cast(User, viewset.request.user),
- was_impersonated=is_impersonated_session(viewset.request),
- item_id=str(instance.id),
- scope="CustomerProfileConfig",
- activity=activity,
- detail=detail,
- )
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index c95b2dd13b35..16a28e65b21a 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -1,84 +1,326 @@
-import json
+"""DRF views for the customer_analytics account CRUD endpoints.
+
+Thin HTTP layer: these viewsets validate requests, gate access through the standard
+mixins, and shape responses, but reach all product data through the facade — no product
+models are imported here. Request validation, status codes, ``@extend_schema`` parameter
+declarations, pagination wiring, and the markdown→tiptap normalization for account
+notebooks stay here; team/object access filtering, transactions, conflict handling,
+pydantic-error formatting, and activity logging live behind the facade.
+"""
-from django.db import transaction
-from django.db.models import Prefetch, Q
-from django.shortcuts import get_object_or_404
+# Lazy annotations: each ViewSet defines a ``list`` method, which would otherwise shadow the
+# ``list`` builtin for any ``list[...]`` annotation evaluated later in the same class body.
+from __future__ import annotations
+
+import json
+from typing import cast
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema
-from rest_framework import mixins, viewsets
-from rest_framework.exceptions import ValidationError
+from loginas.utils import is_impersonated_session
+from rest_framework import mixins, status, viewsets
+from rest_framework.exceptions import PermissionDenied, ValidationError
+from rest_framework.request import Request
+from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.tagged_item import TaggedItemViewSetMixin
-from posthog.api.utils import log_activity_from_viewset
+from posthog.exceptions import Conflict
+from posthog.models.user import User
+from posthog.permissions import is_service_auth
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
-from products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfig
+from products.customer_analytics.backend.facade import api, contracts
from products.customer_analytics.backend.presentation.views.serializers import (
AccountNotebookSerializer,
AccountSerializer,
CustomerJourneySerializer,
CustomerProfileConfigSerializer,
)
-from products.customer_analytics.backend.presentation.views.utils import log_customer_profile_config_activity
-from products.notebooks.backend.models import Notebook, ResourceNotebook
from ee.hogai.tools.create_notebook.tiptap import markdown_to_tiptap_nodes
+# Object-level access levels for the resource ViewSets, matching what
+# ``AccessControlPermission._get_required_access_level`` derives for these scope objects:
+# reads need "viewer", writes need "editor".
+_OBJECT_READ_LEVEL = "viewer"
+_OBJECT_WRITE_LEVEL = "editor"
+
+# drf-spectacular auto-describes the pk path param for a model-backed viewset as
+# "A UUID string identifying this <model>.". These viewsets reach the model through the
+# facade (no ``queryset``), so the description is declared explicitly to keep the generated
+# OpenAPI (and MCP) path params byte-identical.
+_ACCOUNT_ID_PARAM = OpenApiParameter(
+ "id",
+ OpenApiTypes.STR,
+ OpenApiParameter.PATH,
+ description="A UUID string identifying this account.",
+)
+
-class CustomerProfileConfigViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+# NOTE: deliberately no class docstring — a docstring here is inherited as the ViewSets'
+# ``__doc__`` and drf-spectacular would surface it as every operation's description (the
+# model-backed viewsets had none), drifting the generated clients.
+class _FacadePaginationMixin:
+ # Drives the standard ``LimitOffsetPagination`` envelope from a facade ``(page, count)``
+ # result. The facade does the slicing (offset/limit), so we set the paginator's state
+ # directly rather than handing it a queryset — keeping the param names (``limit`` /
+ # ``offset``), default page size, and ``count`` / ``next`` / ``previous`` shape identical
+ # to the model-backed viewsets.
+ def _paginate_via_facade(self, request: Request, fetch, serializer_class) -> Response:
+ paginator = self.paginator # type: ignore[attr-defined]
+ limit = paginator.get_limit(request)
+ offset = paginator.get_offset(request)
+ page, count = fetch(offset=offset, limit=limit)
+ paginator.request = request
+ paginator.limit = limit
+ paginator.offset = offset
+ paginator.count = count
+ serializer = serializer_class(instance=page, many=True)
+ return paginator.get_paginated_response(serializer.data)
+
+
+def _object_required_level(request: Request, write: bool) -> str | None:
+ """The object-level access level to enforce for this request, or ``None`` when the
+ permission layer would skip the object check (service auth) — mirroring
+ ``AccessControlPermission.has_object_permission``."""
+ if is_service_auth(request):
+ return None
+ return _OBJECT_WRITE_LEVEL if write else _OBJECT_READ_LEVEL
+
+
+class CustomerProfileConfigViewSet(
+ TeamAndOrgViewSetMixin,
+ _FacadePaginationMixin,
+ mixins.CreateModelMixin,
+ mixins.RetrieveModelMixin,
+ mixins.UpdateModelMixin,
+ mixins.DestroyModelMixin,
+ mixins.ListModelMixin,
+ viewsets.GenericViewSet,
+):
scope_object = "customer_profile_config"
- queryset = CustomerProfileConfig.objects.all()
serializer_class = CustomerProfileConfigSerializer
+ queryset = None # data is reached through the facade; declared for router/schema only
- def perform_create(self, serializer):
- instance = serializer.save()
- log_customer_profile_config_activity(viewset=self, instance=instance, activity="created")
-
- def perform_update(self, serializer):
- previous_instance = CustomerProfileConfig.objects.get(pk=serializer.instance.pk)
- instance = serializer.save()
- log_customer_profile_config_activity(
- viewset=self, instance=instance, activity="updated", previous=previous_instance
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ return self._paginate_via_facade(
+ request,
+ lambda offset, limit: api.list_customer_profile_configs(self.team_id, offset=offset, limit=limit),
+ CustomerProfileConfigSerializer,
)
- def perform_destroy(self, instance):
- instance_id = instance.id
- instance_scope = instance.scope
-
- super().perform_destroy(instance)
-
- temp_instance = CustomerProfileConfig(id=instance_id, scope=instance_scope)
- log_customer_profile_config_activity(viewset=self, instance=temp_instance, activity="deleted")
-
-
-class CustomerJourneyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):
+ def retrieve(self, request: Request, *args, **kwargs) -> Response:
+ config = api.get_customer_profile_config(self.team_id, self.kwargs["pk"])
+ if config is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(CustomerProfileConfigSerializer(instance=config).data)
+
+ def create(self, request: Request, *args, **kwargs) -> Response:
+ serializer = CustomerProfileConfigSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+ config = api.create_customer_profile_config(
+ team_id=self.team_id,
+ scope=data.scope,
+ content=data.content,
+ sidebar=data.sidebar,
+ organization_id=self.organization.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ )
+ return Response(CustomerProfileConfigSerializer(instance=config).data, status=status.HTTP_201_CREATED)
+
+ def update(self, request: Request, *args, **kwargs) -> Response:
+ partial = kwargs.pop("partial", False)
+ serializer = CustomerProfileConfigSerializer(data=request.data, partial=partial)
+ serializer.is_valid(raise_exception=True)
+ config = api.update_customer_profile_config(
+ team_id=self.team_id,
+ config_id=self.kwargs["pk"],
+ fields=_profile_config_write_fields(serializer.validated_data, request.data),
+ organization_id=self.organization.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ )
+ if config is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(CustomerProfileConfigSerializer(instance=config).data)
+
+ def partial_update(self, request: Request, *args, **kwargs) -> Response:
+ kwargs["partial"] = True
+ return self.update(request, *args, **kwargs)
+
+ def destroy(self, request: Request, *args, **kwargs) -> Response:
+ deleted = api.delete_customer_profile_config(
+ team_id=self.team_id,
+ config_id=self.kwargs["pk"],
+ organization_id=self.organization.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ )
+ if not deleted:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+
+def _profile_config_write_fields(validated, raw_data: dict) -> dict:
+ """The profile-config columns the caller actually sent (scope/content/sidebar). ``content``
+ and ``sidebar`` default to ``{}`` in the serializer, so only forward them when present in
+ the raw body — matching the model serializer's partial-update behavior."""
+ fields: dict = {}
+ if "scope" in raw_data:
+ fields["scope"] = validated.scope
+ if "content" in raw_data:
+ fields["content"] = validated.content
+ if "sidebar" in raw_data:
+ fields["sidebar"] = validated.sidebar
+ return fields
+
+
+class CustomerJourneyViewSet(
+ TeamAndOrgViewSetMixin,
+ AccessControlViewSetMixin,
+ _FacadePaginationMixin,
+ mixins.CreateModelMixin,
+ mixins.RetrieveModelMixin,
+ mixins.UpdateModelMixin,
+ mixins.DestroyModelMixin,
+ mixins.ListModelMixin,
+ viewsets.GenericViewSet,
+):
scope_object = "customer_journey"
- queryset = CustomerJourney.objects.order_by("created_at").all()
serializer_class = CustomerJourneySerializer
+ queryset = None
- def safely_get_queryset(self, queryset):
- return queryset.filter(team_id=self.team.id)
-
- def perform_create(self, serializer):
- serializer.save()
- log_activity_from_viewset(self, serializer.instance, name=serializer.instance.name)
-
- def perform_update(self, serializer):
- previous = self.get_object()
- serializer.save()
- log_activity_from_viewset(self, serializer.instance, name=serializer.instance.name, previous=previous)
-
- def perform_destroy(self, instance):
- log_activity_from_viewset(self, instance, activity="deleted", name=instance.name)
- super().perform_destroy(instance)
-
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ return self._paginate_via_facade(
+ request,
+ lambda offset, limit: api.list_customer_journeys(
+ self.team_id, offset=offset, limit=limit, user_access_control=self.user_access_control
+ ),
+ CustomerJourneySerializer,
+ )
-class AccountViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):
+ def retrieve(self, request: Request, *args, **kwargs) -> Response:
+ try:
+ journey = api.get_customer_journey(
+ self.team_id,
+ self.kwargs["pk"],
+ user_access_control=self.user_access_control,
+ required_level=_object_required_level(request, write=False),
+ )
+ except api.CustomerJourney_DoesNotExist:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ except api.ResourceForbiddenError:
+ raise PermissionDenied()
+ return Response(CustomerJourneySerializer(instance=journey).data)
+
+ def create(self, request: Request, *args, **kwargs) -> Response:
+ serializer = CustomerJourneySerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+ if not api.insight_belongs_to_team(self.team_id, data.insight):
+ raise ValidationError({"insight": "The insight does not belong to this team."})
+ try:
+ journey = api.create_customer_journey(
+ team_id=self.team_id,
+ insight_id=data.insight,
+ name=data.name,
+ description=data.description,
+ organization_id=self.organization.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ )
+ except api.CustomerJourneyConflictError as e:
+ raise Conflict(str(e))
+ return Response(CustomerJourneySerializer(instance=journey).data, status=status.HTTP_201_CREATED)
+
+ def update(self, request: Request, *args, **kwargs) -> Response:
+ partial = kwargs.pop("partial", False)
+ serializer = CustomerJourneySerializer(data=request.data, partial=partial)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+ if "insight" in request.data and not api.insight_belongs_to_team(self.team_id, data.insight):
+ raise ValidationError({"insight": "The insight does not belong to this team."})
+ try:
+ journey = api.update_customer_journey(
+ team_id=self.team_id,
+ journey_id=self.kwargs["pk"],
+ fields=_journey_write_fields(data, request.data),
+ user_access_control=self.user_access_control,
+ required_level=_object_required_level(request, write=True),
+ organization_id=self.organization.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ )
+ except api.CustomerJourney_DoesNotExist:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ except api.ResourceForbiddenError:
+ raise PermissionDenied()
+ return Response(CustomerJourneySerializer(instance=journey).data)
+
+ def partial_update(self, request: Request, *args, **kwargs) -> Response:
+ kwargs["partial"] = True
+ return self.update(request, *args, **kwargs)
+
+ def destroy(self, request: Request, *args, **kwargs) -> Response:
+ try:
+ api.delete_customer_journey(
+ team_id=self.team_id,
+ journey_id=self.kwargs["pk"],
+ user_access_control=self.user_access_control,
+ required_level=_object_required_level(request, write=True),
+ organization_id=self.organization.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ )
+ except api.CustomerJourney_DoesNotExist:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ except api.ResourceForbiddenError:
+ raise PermissionDenied()
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+
+def _journey_write_fields(validated, raw_data: dict) -> dict:
+ fields: dict = {}
+ if "name" in raw_data:
+ fields["name"] = validated.name
+ if "description" in raw_data:
+ fields["description"] = validated.description
+ if "insight" in raw_data:
+ fields["insight_id"] = validated.insight
+ return fields
+
+
+def _parse_tags_param(request: Request) -> list[str] | None:
+ tags_param = request.query_params.get("tags")
+ if not tags_param:
+ return None
+ try:
+ tags_list = json.loads(tags_param)
+ except json.JSONDecodeError:
+ raise ValidationError({"tags": "Must be a JSON-encoded list of strings."})
+ if not isinstance(tags_list, list) or not all(isinstance(t, str) for t in tags_list):
+ raise ValidationError({"tags": "Must be a JSON-encoded list of strings."})
+ return tags_list
+
+
+class AccountViewSet(
+ TaggedItemViewSetMixin,
+ TeamAndOrgViewSetMixin,
+ AccessControlViewSetMixin,
+ _FacadePaginationMixin,
+ mixins.CreateModelMixin,
+ mixins.RetrieveModelMixin,
+ mixins.UpdateModelMixin,
+ mixins.DestroyModelMixin,
+ mixins.ListModelMixin,
+ viewsets.GenericViewSet,
+):
scope_object = "account"
- queryset = Account.objects.unscoped().order_by("-created_at")
serializer_class = AccountSerializer
+ queryset = None
bulk_update_tags = None # Mixin action assumes integer PKs; Account uses UUIDs.
ALLOWED_ORDERING = frozenset({"name", "-name", "created_at", "-created_at", "updated_at", "-updated_at"})
@@ -143,84 +385,129 @@ class AccountViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContr
),
],
)
- def list(self, request, *args, **kwargs):
- return super().list(request, *args, **kwargs)
-
- def safely_get_queryset(self, queryset):
- queryset = queryset.filter(team_id=self.team.id).prefetch_related(
- Prefetch("notebooks", queryset=ResourceNotebook.objects.select_related("notebook"))
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ tags = _parse_tags_param(self.request)
+ ordering = request.query_params.get("ordering")
+ ordering = ordering if ordering in self.ALLOWED_ORDERING else None
+ return self._paginate_via_facade(
+ request,
+ lambda offset, limit: api.list_accounts_for_view(
+ team_id=self.team_id,
+ user_access_control=self.user_access_control,
+ offset=offset,
+ limit=limit,
+ search=request.query_params.get("search", "").strip() or None,
+ tags=tags,
+ csm=request.query_params.get("csm"),
+ account_executive=request.query_params.get("account_executive"),
+ account_owner=request.query_params.get("account_owner"),
+ all_roles_unassigned=request.query_params.get("all_roles_unassigned", "").lower() == "true",
+ ordering=ordering,
+ ),
+ AccountSerializer,
)
- search = self.request.query_params.get("search", "").strip()
- if search:
- queryset = queryset.filter(Q(name__icontains=search) | Q(external_id__icontains=search))
-
- tags_param = self.request.query_params.get("tags")
- if tags_param:
- try:
- tags_list = json.loads(tags_param)
- except json.JSONDecodeError:
- raise ValidationError({"tags": "Must be a JSON-encoded list of strings."})
- if not isinstance(tags_list, list) or not all(isinstance(t, str) for t in tags_list):
- raise ValidationError({"tags": "Must be a JSON-encoded list of strings."})
- if tags_list:
- queryset = queryset.filter(tagged_items__tag__name__in=tags_list).distinct()
-
- # An unset role is serialized as JSON null, which `_properties__role__isnull`
- # does not match; probing the nested `id` matches every unassigned
- # representation (missing key, null value, or empty object).
- if self.request.query_params.get("all_roles_unassigned", "").lower() == "true":
- queryset = queryset.filter(
- _properties__csm__id__isnull=True,
- _properties__account_executive__id__isnull=True,
- _properties__account_owner__id__isnull=True,
+ @extend_schema(parameters=[_ACCOUNT_ID_PARAM])
+ def retrieve(self, request: Request, *args, **kwargs) -> Response:
+ try:
+ account = api.get_account_for_view(
+ team_id=self.team_id,
+ account_id=self.kwargs["pk"],
+ user_access_control=self.user_access_control,
+ required_level=_object_required_level(request, write=False),
+ )
+ except api.Account_DoesNotExist:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ except api.ResourceForbiddenError:
+ raise PermissionDenied()
+ return Response(AccountSerializer(instance=account).data)
+
+ def create(self, request: Request, *args, **kwargs) -> Response:
+ serializer = AccountSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+ try:
+ account = api.create_account_for_view(
+ team_id=self.team_id,
+ team=self.team,
+ input=contracts.CreateAccountInput(
+ name=data.name,
+ external_id=data.external_id,
+ properties=data.properties or {},
+ tags=_account_tags_input(serializer),
+ ),
+ organization_id=self.organization.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ )
+ except api.AccountPropertiesValidationError as e:
+ raise ValidationError({"properties": e.messages})
+ except api.AccountConflictError as e:
+ raise Conflict(str(e))
+ return Response(AccountSerializer(instance=account).data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(parameters=[_ACCOUNT_ID_PARAM])
+ def update(self, request: Request, *args, **kwargs) -> Response:
+ partial = kwargs.pop("partial", False)
+ serializer = AccountSerializer(data=request.data, partial=partial)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+ try:
+ account = api.update_account_for_view(
+ team_id=self.team_id,
+ account_id=self.kwargs["pk"],
+ input=contracts.UpdateAccountInput(
+ name=data.name if "name" in request.data else None,
+ external_id=data.external_id if "external_id" in request.data else None,
+ external_id_provided="external_id" in request.data,
+ properties=data.properties if "properties" in request.data else None,
+ properties_provided="properties" in request.data,
+ tags=_account_tags_input(serializer),
+ ),
+ user_access_control=self.user_access_control,
+ required_level=_object_required_level(request, write=True),
+ organization_id=self.organization.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ )
+ except api.Account_DoesNotExist:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ except api.ResourceForbiddenError:
+ raise PermissionDenied()
+ except api.AccountPropertiesValidationError as e:
+ raise ValidationError({"properties": e.messages})
+ except api.AccountConflictError as e:
+ raise Conflict(str(e))
+ return Response(AccountSerializer(instance=account).data)
+
+ @extend_schema(parameters=[_ACCOUNT_ID_PARAM])
+ def partial_update(self, request: Request, *args, **kwargs) -> Response:
+ kwargs["partial"] = True
+ return self.update(request, *args, **kwargs)
+
+ @extend_schema(parameters=[_ACCOUNT_ID_PARAM])
+ def destroy(self, request: Request, *args, **kwargs) -> Response:
+ try:
+ api.delete_account_for_view(
+ team_id=self.team_id,
+ account_id=self.kwargs["pk"],
+ user_access_control=self.user_access_control,
+ required_level=_object_required_level(request, write=True),
+ organization_id=self.organization.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
)
+ except api.Account_DoesNotExist:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ except api.ResourceForbiddenError:
+ raise PermissionDenied()
+ return Response(status=status.HTTP_204_NO_CONTENT)
- csm_value = self.request.query_params.get("csm")
- if csm_value == "unassigned":
- queryset = queryset.filter(_properties__csm__id__isnull=True)
- elif csm_value:
- try:
- queryset = queryset.filter(_properties__csm__id=int(csm_value))
- except ValueError:
- pass
-
- ae_value = self.request.query_params.get("account_executive")
- if ae_value == "unassigned":
- queryset = queryset.filter(_properties__account_executive__id__isnull=True)
- elif ae_value:
- try:
- queryset = queryset.filter(_properties__account_executive__id=int(ae_value))
- except ValueError:
- pass
-
- owner_value = self.request.query_params.get("account_owner")
- if owner_value == "unassigned":
- queryset = queryset.filter(_properties__account_owner__id__isnull=True)
- elif owner_value:
- try:
- queryset = queryset.filter(_properties__account_owner__id=int(owner_value))
- except ValueError:
- pass
-
- ordering = self.request.query_params.get("ordering")
- if ordering in self.ALLOWED_ORDERING:
- queryset = queryset.order_by(ordering)
-
- return queryset
-
- def perform_create(self, serializer):
- serializer.save()
- log_activity_from_viewset(self, serializer.instance, name=serializer.instance.name)
-
- def perform_update(self, serializer):
- previous = self.get_object()
- serializer.save()
- log_activity_from_viewset(self, serializer.instance, name=serializer.instance.name, previous=previous)
-
- def perform_destroy(self, instance):
- log_activity_from_viewset(self, instance, activity="deleted", name=instance.name)
- super().perform_destroy(instance)
+
+def _account_tags_input(serializer) -> list[str] | None:
+ """Tags exactly as the client supplied them (raw initial data), so ``None`` (omitted)
+ is distinguished from ``[]`` (clear) — matching ``TaggedItemSerializerMixin``."""
+ return serializer.initial_data.get("tags")
@extend_schema(
@@ -245,55 +532,76 @@ class AccountNotebookViewSet(
):
scope_object = "account"
serializer_class = AccountNotebookSerializer
- queryset = Notebook.objects.all()
+ queryset = None
lookup_field = "short_id"
- filter_rewrite_rules = {"account_id": "resources__account_id"}
- def _get_account(self) -> Account:
- queryset = self.user_access_control.filter_queryset_by_access_level(
- Account.objects.unscoped().filter(team_id=self.team.id),
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ notebooks = api.list_account_notebooks(
+ self.team_id, self.parents_query_dict["account_id"], user_access_control=self.user_access_control
)
- return get_object_or_404(queryset, id=self.parents_query_dict["account_id"])
-
- def safely_get_queryset(self, queryset):
- self._get_account()
- return (
- queryset.filter(deleted=False, visibility=Notebook.Visibility.INTERNAL)
- .select_related("created_by", "last_modified_by")
- .order_by("-last_modified_at")
+ if notebooks is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ page = self.paginate_queryset(notebooks)
+ if page is not None:
+ return self.get_paginated_response(AccountNotebookSerializer(instance=page, many=True).data)
+ return Response(AccountNotebookSerializer(instance=notebooks, many=True).data)
+
+ def retrieve(self, request: Request, *args, **kwargs) -> Response:
+ notebook = api.get_account_notebook(
+ self.team_id,
+ self.parents_query_dict["account_id"],
+ self.kwargs["short_id"],
+ user_access_control=self.user_access_control,
)
-
- @transaction.atomic
- def perform_create(self, serializer):
- account = self._get_account()
- save_kwargs: dict = {
- "team": self.team,
- "created_by": self.request.user,
- "last_modified_by": self.request.user,
- "visibility": Notebook.Visibility.INTERNAL,
- }
-
- # Agents calling the MCP `accounts-notebooks-create` tool typically pass `text_content`
- # (Markdown) without a ProseMirror `content` tree, since hand-writing ProseMirror is
- # awkward. NotebookScene only renders `content`, so the result is a blank page. Treat
- # `text_content` as Markdown and synthesize `content` from it when the caller hasn't.
- validated = serializer.validated_data
- text_content = validated.get("text_content")
- existing_content = validated.get("content")
- has_usable_content = (
- isinstance(existing_content, dict)
- and existing_content.get("type") == "doc"
- and isinstance(existing_content.get("content"), list)
+ if notebook is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(AccountNotebookSerializer(instance=notebook).data)
+
+ def create(self, request: Request, *args, **kwargs) -> Response:
+ serializer = AccountNotebookSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+ notebook = api.create_account_notebook(
+ team_id=self.team_id,
+ team=self.team,
+ account_id=self.parents_query_dict["account_id"],
+ input=contracts.CreateAccountNotebookInput(
+ title=data.title,
+ content=data.content,
+ text_content=data.text_content,
+ synthesized_content=_synthesize_notebook_content(data.text_content, data.content),
+ ),
+ user=cast(User, request.user),
+ user_access_control=self.user_access_control,
+ )
+ if notebook is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(AccountNotebookSerializer(instance=notebook).data, status=status.HTTP_201_CREATED)
+
+ def destroy(self, request: Request, *args, **kwargs) -> Response:
+ deleted = api.delete_account_notebook(
+ team_id=self.team_id,
+ account_id=self.parents_query_dict["account_id"],
+ short_id=self.kwargs["short_id"],
+ user_access_control=self.user_access_control,
)
- if text_content and not has_usable_content:
- save_kwargs["content"] = {
- "type": "doc",
- "content": markdown_to_tiptap_nodes(text_content) or [{"type": "paragraph"}],
- }
-
- notebook = serializer.save(**save_kwargs)
- ResourceNotebook.objects.create(notebook=notebook, account=account)
-
- @transaction.atomic
- def perform_destroy(self, instance: Notebook):
- instance.delete()
+ if not deleted:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+
+def _synthesize_notebook_content(text_content, existing_content):
+ """When the caller passed Markdown ``text_content`` but no usable ProseMirror ``content``
+ tree, build one from the Markdown. Agents calling the MCP notebook-create tool typically
+ send ``text_content`` only (hand-writing ProseMirror is awkward), and NotebookScene only
+ renders ``content`` — so without this the result is a blank page. The tiptap helper lives
+ in ``ee.hogai`` and stays in the view so it never reaches the facade import path. Returns
+ ``None`` when the caller already supplied usable content (or no markdown)."""
+ has_usable_content = (
+ isinstance(existing_content, dict)
+ and existing_content.get("type") == "doc"
+ and isinstance(existing_content.get("content"), list)
+ )
+ if text_content and not has_usable_content:
+ return {"type": "doc", "content": markdown_to_tiptap_nodes(text_content) or [{"type": "paragraph"}]}
+ return None
diff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.py
index 49628f716dd9..a2768ab5f01b 100644
--- a/products/customer_analytics/backend/test/test_facade.py
+++ b/products/customer_analytics/backend/test/test_facade.py
@@ -2,6 +2,7 @@ from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from posthog.models import Organization, User
+from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.tag import Tag
from posthog.models.tagged_item import TaggedItem
from posthog.rbac.user_access_control import UserAccessControl
@@ -10,9 +11,11 @@ from products.customer_analytics.backend.facade import (
api as facade,
contracts,
)
+from products.customer_analytics.backend.models import Account
from products.customer_analytics.backend.models.account import AccountAssignment, AccountProperties
from products.customer_analytics.backend.test.factories import create_account
from products.notebooks.backend.models import Notebook, ResourceNotebook
+from products.product_analytics.backend.models.insight import Insight
class TestCustomerAnalyticsFacade(BaseTest):
@@ -271,3 +274,214 @@ class TestCustomerAnalyticsFacade(BaseTest):
assert result.error == contracts.ExternalAccountUpdateError.UPDATE_FAILED
account.refresh_from_db()
assert account.properties.csm is None
+
+
+class TestCustomerAnalyticsCRUDFacade(BaseTest):
+ """Parity coverage for the presentation-wave CRUD functions the account/journey/
+ profile-config viewsets call."""
+
+ def _uac(self) -> UserAccessControl:
+ return UserAccessControl(user=self.user, team=self.team)
+
+ def _create_account_input(self, **kwargs) -> contracts.CreateAccountInput:
+ kwargs.setdefault("name", "Acme Corp")
+ return contracts.CreateAccountInput(**kwargs)
+
+ def _create(self, **kwargs) -> contracts.AccountView:
+ return facade.create_account_for_view(
+ team_id=self.team.id,
+ team=self.team,
+ input=self._create_account_input(**kwargs),
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ )
+
+ # --- Account create/update/delete ---
+
+ def test_create_account_returns_view_and_persists(self):
+ view = self._create(name="Acme", external_id="acme-1", properties={"stripe_customer_id": "cus_1"})
+
+ assert isinstance(view, contracts.AccountView)
+ assert view.name == "Acme"
+ assert view.external_id == "acme-1"
+ assert view.properties == {"stripe_customer_id": "cus_1"}
+ assert view.created_by == self.user.id
+ stored = Account.objects.unscoped().get(id=str(view.id))
+ assert stored.team_id == self.team.id
+ assert stored.created_by_id == self.user.id
+
+ def test_create_account_empty_properties_serializes_as_empty_dict(self):
+ view = self._create(name="Bare")
+ assert view.properties == {}
+
+ def test_create_account_sets_tags(self):
+ view = self._create(name="Tagged", tags=["enterprise", "priority"])
+ account = Account.objects.unscoped().get(id=str(view.id))
+ assert sorted(TaggedItem.objects.filter(account=account).values_list("tag__name", flat=True)) == [
+ "enterprise",
+ "priority",
+ ]
+
+ def test_create_account_duplicate_external_id_raises_conflict(self):
+ self._create(name="First", external_id="dup")
+ with self.assertRaises(facade.AccountConflictError):
+ self._create(name="Second", external_id="dup")
+
+ def test_create_account_invalid_properties_raises_validation_error(self):
+ with self.assertRaises(facade.AccountPropertiesValidationError) as ctx:
+ self._create(name="Bad", properties={"unknown_field": "x"})
+ assert ctx.exception.messages # non-empty field-error list
+
+ def test_create_account_logs_activity(self):
+ view = self._create(name="Logged")
+ log = ActivityLog.objects.get(team_id=self.team.id, scope="Account", activity="created")
+ assert log.item_id == str(view.id)
+
+ def test_update_account_changes_name_and_tags(self):
+ view = self._create(name="Before", tags=["old"])
+ updated = facade.update_account_for_view(
+ team_id=self.team.id,
+ account_id=str(view.id),
+ input=contracts.UpdateAccountInput(name="After", tags=["new"]),
+ user_access_control=self._uac(),
+ required_level="editor",
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ )
+ assert updated.name == "After"
+ assert updated.tags == ["new"]
+
+ def test_update_account_unknown_raises_does_not_exist(self):
+ with self.assertRaises(facade.Account_DoesNotExist):
+ facade.update_account_for_view(
+ team_id=self.team.id,
+ account_id="00000000-0000-0000-0000-000000000000",
+ input=contracts.UpdateAccountInput(name="x"),
+ user_access_control=self._uac(),
+ required_level="editor",
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ )
+
+ def test_delete_account_removes_row(self):
+ view = self._create(name="Doomed")
+ facade.delete_account_for_view(
+ team_id=self.team.id,
+ account_id=str(view.id),
+ user_access_control=self._uac(),
+ required_level="editor",
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ )
+ assert not Account.objects.unscoped().filter(id=str(view.id)).exists()
+
+ def test_get_account_for_view_unknown_raises(self):
+ with self.assertRaises(facade.Account_DoesNotExist):
+ facade.get_account_for_view(
+ team_id=self.team.id,
+ account_id="00000000-0000-0000-0000-000000000000",
+ user_access_control=self._uac(),
+ required_level="viewer",
+ )
+
+ def test_list_accounts_for_view_filters_by_search(self):
+ self._create(name="Acme Corp", external_id="acme-1")
+ self._create(name="Globex", external_id="glx-9")
+ page, count = facade.list_accounts_for_view(
+ team_id=self.team.id, user_access_control=self._uac(), offset=0, limit=10, search="acme"
+ )
+ assert count == 1
+ assert [a.name for a in page] == ["Acme Corp"]
+
+ # --- CustomerJourney ---
+
+ def test_create_journey_returns_view_and_logs(self):
+ insight = Insight.objects.create(team=self.team)
+ view = facade.create_customer_journey(
+ team_id=self.team.id,
+ insight_id=insight.id,
+ name="Onboarding",
+ description="desc",
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ )
+ assert isinstance(view, contracts.CustomerJourneyView)
+ assert view.insight == insight.id
+ assert view.created_by == self.user.id
+ assert ActivityLog.objects.filter(team_id=self.team.id, scope="CustomerJourney", activity="created").exists()
+
+ def test_create_journey_duplicate_insight_raises_conflict(self):
+ insight = Insight.objects.create(team=self.team)
+ kwargs = {
+ "team_id": self.team.id,
+ "insight_id": insight.id,
+ "description": None,
+ "organization_id": self.organization.id,
+ "user": self.user,
+ "was_impersonated": False,
+ }
+ facade.create_customer_journey(name="First", **kwargs)
+ with self.assertRaises(facade.CustomerJourneyConflictError):
+ facade.create_customer_journey(name="Second", **kwargs)
+
+ def test_insight_belongs_to_team(self):
+ insight = Insight.objects.create(team=self.team)
+ assert facade.insight_belongs_to_team(self.team.id, insight.id)
+ assert not facade.insight_belongs_to_team(self.team.id, insight.id + 9999)
+
+ # --- CustomerProfileConfig ---
+
+ def test_profile_config_create_update_delete_with_activity(self):
+ created = facade.create_customer_profile_config(
+ team_id=self.team.id,
+ scope="person",
+ content={"a": 1},
+ sidebar={},
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ )
+ assert isinstance(created, contracts.CustomerProfileConfigView)
+ assert created.scope == "person"
+ assert ActivityLog.objects.filter(
+ team_id=self.team.id, scope="CustomerProfileConfig", activity="created"
+ ).exists()
+
+ updated = facade.update_customer_profile_config(
+ team_id=self.team.id,
+ config_id=str(created.id),
+ fields={"content": {"a": 2}},
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ )
+ assert updated is not None and updated.content == {"a": 2}
+
+ assert facade.delete_customer_profile_config(
+ team_id=self.team.id,
+ config_id=str(created.id),
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ )
+ assert ActivityLog.objects.filter(
+ team_id=self.team.id, scope="CustomerProfileConfig", activity="deleted"
+ ).exists()
+
+ def test_profile_config_update_unknown_returns_none(self):
+ assert (
+ facade.update_customer_profile_config(
+ team_id=self.team.id,
+ config_id="00000000-0000-0000-0000-000000000000",
+ fields={"scope": "person"},
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ )
+ is None
+ )
diff --git a/pyproject.toml b/pyproject.toml
index a9d06aed003d..2dff60f4a8e3 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -573,9 +573,6 @@ ignore_imports = [
# Thin each view to parse -> facade -> serialize and delete its entry. backend:contract-check
# stays off until this list is empty.
"products.customer_analytics.backend.presentation.views.organization_members -> products.customer_analytics.backend.constants",
- "products.customer_analytics.backend.presentation.views.serializers -> products.customer_analytics.backend.models",
- "products.customer_analytics.backend.presentation.views.utils -> products.customer_analytics.backend.models",
- "products.customer_analytics.backend.presentation.views.views -> products.customer_analytics.backend.models",
]
[tool.ty.rules]