: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): add private account view API (#107159)
Arthur Moreira de Deusaa10f37fdca0
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex bd9828e781c1..d0f2fdbc3a86 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -61,6 +61,7 @@ rules:|AccountRelationshipControl|AccountRelationshipDefinition|AccountTrackRuleRun+ |AccountView|Action|AEOCitationCheck|AEOPrompt@@ -501,6 +502,7 @@ rules:|AccountRelationshipControl|AccountRelationshipDefinition|AccountTrackRuleRun+ |AccountView|Action|AgentApplication|AgentArtifactdiff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 429155cfb034..f637e2b15972 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -6172,6 +6172,7 @@ export type PromptFlag = {export enum ActivityScope {DATA_QUALITY_CHECK_SCHEDULE = 'DataQualityCheckSchedule',ACTION = 'Action',+ ACCOUNT_VIEW = 'AccountView',ALERT_CONFIGURATION = 'AlertConfiguration',ANNOTATION = 'Annotation',BATCH_EXPORT = 'BatchExport',diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex b18f56a24478..630a2f3ea38a 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -92,6 +92,7 @@ ActivityScope = Literal["OAuthApplication","User","Action",+ "AccountView","AlertConfiguration","Threshold","AlertSubscription",@@ -294,6 +295,7 @@ common_field_exclusions = [field_with_masked_contents: dict[AuditableScope, list[str]] = {+ "AccountView": ["name", "content", "text_content"],"HogFunction": [# Encrypted secret inputs (Fernet ciphertext) — a diff would be noise at best and# leak-adjacent at worst; record that they changed, never the values.@@ -530,6 +532,14 @@ signal_exclusions: dict[ActivityScope, list[str]] = {# Activity visibility restrictions - controls which users can see certain activity logs# Used to hide sensitive activities (e.g., impersonated logins, user account changes) from non-staff usersactivity_visibility_restrictions: list[dict[str, Any]] = [+ {+ # Account views are private to their creator, so even their IDs and timestamps stay out of+ # the team and org feeds.+ "scope": "AccountView",+ "activities": ["created", "updated", "deleted"],+ "exclude_when": {},+ "allow_staff": True,+ },{"scope": "Integration", "activities": ["github_diagnostic"], "allow_staff": True},{"scope": "User",@@ -601,6 +611,7 @@ activity_visibility_restrictions: list[dict[str, Any]] = []field_exclusions: dict[AuditableScope, list[str]] = {+ "AccountView": ["version"],# The reverse relations are listed because the diff reads each one in full; a scanner's# observations run to millions of rows, and its alerts carry their own audit trail."ReplayScanner": [*replay_scanner_machine_fields, "observations", "backfills", "prompt_suggestions", "alerts"],diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex d1618537ed12..bd844b55cd1c 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -27,6 +27,7 @@ model_activity:products.alerts.backend.activity_logging.handle_threshold_changemodel_activity:products.annotations.backend.activity_logging.handle_annotation_changemodel_activity:products.batch_exports.backend.activity_logging.handle_batch_export_changemodel_activity:products.business_knowledge.backend.signals.handle_knowledge_source_change+model_activity:products.customer_analytics.backend.activity_logging.handle_account_view_changemodel_activity:products.dashboards.backend.activity_logging.handle_dashboard_changemodel_activity:products.dashboards.backend.activity_logging.handle_dashboard_widget_changemodel_activity:products.data_catalog.backend.activity_logging.handle_metric_activity@@ -260,6 +261,7 @@ pre_delete:posthog.storage.team_llm_gateway_policy_signal_handlers._clear_cache_pre_delete:products.alerts.backend.activity_logging.cleanup_alert_hog_functionspre_delete:products.alerts.backend.activity_logging.handle_alert_subscription_deletepre_delete:products.billing_alerts.backend.team_lifecycle.rehome_billing_alerts_before_team_delete+pre_delete:products.customer_analytics.backend.signals.delete_private_account_views_for_deleted_userpre_delete:products.managed_migrations.backend.activity_logging.handle_batch_import_deletepre_delete:products.tasks.backend.models.clear_channel_repositories_on_github_integration_deletepre_delete:products.tasks.backend.team_deletion.cancel_task_workflows_on_team_deletediff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.pyindex ff0eb95546ad..3029609ef49f 100644--- a/posthog/test/repo_invariants/test_pagination_contract.py+++ b/posthog/test/repo_invariants/test_pagination_contract.py@@ -125,6 +125,7 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {"products.customer_analytics.backend.presentation.views.views.AccountRelationshipViewSet","products.customer_analytics.backend.presentation.views.views.AccountTrackRuleViewSet","products.customer_analytics.backend.presentation.views.views.AccountViewSet",+ "products.customer_analytics.backend.presentation.views.views.AccountViewTemplateViewSet","products.customer_analytics.backend.presentation.views.views.CalendarSyncViewSet","products.customer_analytics.backend.presentation.views.views.CustomPropertyDefinitionViewSet","products.customer_analytics.backend.presentation.views.views.CustomPropertySourceViewSet",diff --git a/products/customer_analytics/backend/activity_logging.py b/products/customer_analytics/backend/activity_logging.pynew file mode 100644index 000000000000..49cbfb5d4479--- /dev/null+++ b/products/customer_analytics/backend/activity_logging.py@@ -0,0 +1,41 @@+from typing import TYPE_CHECKING, Any++from posthog.models.activity_logging.activity_log import ActivityScope, Detail, changes_between, log_activity+from posthog.models.signals import model_activity_signal, mutable_receiver++from products.customer_analytics.backend.models.account_view import AccountView++if TYPE_CHECKING:+ from posthog.models import User+++@mutable_receiver(model_activity_signal, sender=AccountView)+def handle_account_view_change(+ sender: type[AccountView],+ scope: ActivityScope,+ before_update: AccountView | None,+ after_update: AccountView | None,+ activity: str,+ user: "User | None",+ was_impersonated: bool = False,+ **kwargs: Any,+) -> None:+ instance = after_update or before_update+ if instance is None:+ return+ changes = changes_between(scope, previous=before_update, current=after_update)+ resolved_activity = activity+ deleted_change = next((change for change in changes if change.field == "deleted_at"), None)+ if deleted_change and deleted_change.after:+ resolved_activity = "deleted"++ log_activity(+ organization_id=instance.team.organization_id,+ team_id=instance.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=instance.id,+ scope=scope,+ activity=resolved_activity,+ detail=Detail(changes=changes),+ )diff --git a/products/customer_analytics/backend/apps.py b/products/customer_analytics/backend/apps.pyindex db6e082aa4a9..081da8eebc6c 100644--- a/products/customer_analytics/backend/apps.py+++ b/products/customer_analytics/backend/apps.py@@ -7,6 +7,9 @@ class CustomerAnalyticsConfig(AppConfig):label = "customer_analytics"def ready(self) -> None:+ # The receivers must connect in every process because account views can change outside web requests.+ from products.customer_analytics.backend import activity_logging, signals # noqa: F401, PLC0415+self._register_person_property_hooks()self._register_account_property_hooks()self._register_workflows_account_audience()diff --git a/products/customer_analytics/backend/constants.py b/products/customer_analytics/backend/constants.pyindex 0c9c9614a893..1943431af268 100644--- a/products/customer_analytics/backend/constants.py+++ b/products/customer_analytics/backend/constants.py@@ -12,6 +12,7 @@ CUSTOMER_ANALYTICS_CSP_FLAG = "customer-analytics-csp"CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG = "customer-analytics-feature-requests"CUSTOMER_ANALYTICS_TRACK_RULES_FLAG = "customer-analytics-track-rules"CUSTOMER_ANALYTICS_CUSTOMER_TASKS_FLAG = "customer-analytics-customer-tasks"+CUSTOMER_ANALYTICS_ACCOUNT_VIEWS_FLAG = "customer-analytics-account-views"# Mirrors frontend `FEATURE_FLAGS.WAREHOUSE_PERSON_PROPERTIES`. Gates the whole warehouse -> person# properties feature: creating person-target custom property sources (API + UI), staging rows duringdiff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 15d23fea7044..a199717f1430 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -19,7 +19,7 @@ import asynciofrom collections.abc import Iterablefrom datetime import UTC, date, datetime, time, timedeltafrom enum import Enum-from typing import TYPE_CHECKING, Any, Optional, cast+from typing import TYPE_CHECKING, Any, Literal, Optional, castfrom uuid import UUIDfrom django.apps import apps@@ -105,6 +105,7 @@ from products.customer_analytics.backend.facade.enums import (from products.customer_analytics.backend.logic import (account_presence as _account_presence_logic,account_track_rules as _account_track_rules_logic,+ account_views as _account_views_logic,announcements as _announcements_logic,channel_summaries as _channel_summaries_logic,custom_property_values as _custom_property_values_logic,@@ -147,6 +148,7 @@ from products.customer_analytics.backend.models import (AccountRelationship,AccountRelationshipControl,AccountRelationshipDefinition,+ AccountView as AccountViewModel,Announcement,CustomerJourney,CustomerProfileConfig,@@ -1213,6 +1215,74 @@ def delete_customer_profile_config(return True+# --- AccountView ---+++InvalidAccountViewContent = _account_views_logic.InvalidAccountViewContent+AccountViewVersionConflict = _account_views_logic.AccountViewVersionConflict+++def _to_account_view(view: AccountViewModel) -> contracts.AccountView:+ return contracts.AccountView(+ id=view.id,+ name=view.name,+ visibility=cast(Literal["private"], view.visibility),+ content=view.content,+ text_content=view.text_content,+ version=view.version,+ created_by=view.created_by_id,+ last_modified_by=view.last_modified_by_id,+ created_at=view.created_at,+ updated_at=view.updated_at,+ )+++def list_account_views(*, team_id: int, user_id: int) -> list[contracts.AccountView]:+ return [+ _to_account_view(view) for view in _account_views_logic.list_account_views(team_id=team_id, user_id=user_id)+ ]+++def get_account_view(*, team_id: int, user_id: int, view_id: UUID) -> contracts.AccountView | None:+ view = _account_views_logic.get_account_view(team_id=team_id, user_id=user_id, view_id=view_id)+ return _to_account_view(view) if view is not None else None+++def create_account_view(*, team_id: int, user_id: int, name: str, content: dict[str, Any]) -> contracts.AccountView:+ return _to_account_view(+ _account_views_logic.create_account_view(team_id=team_id, user_id=user_id, name=name, content=content)+ )+++def update_account_view(+ *,+ team_id: int,+ user_id: int,+ view_id: UUID,+ expected_version: int,+ name: str | None = None,+ content: dict[str, Any] | None = None,+) -> contracts.AccountView | None:+ view = _account_views_logic.update_account_view(+ team_id=team_id,+ user_id=user_id,+ view_id=view_id,+ expected_version=expected_version,+ name=name,+ content=content,+ )+ return _to_account_view(view) if view is not None else None+++def delete_account_view(*, team_id: int, user_id: int, view_id: UUID, expected_version: int) -> bool:+ return _account_views_logic.delete_account_view(+ team_id=team_id,+ user_id=user_id,+ view_id=view_id,+ expected_version=expected_version,+ )++# --- UserCustomerAnalyticsConfig ---@@ -2981,8 +3051,8 @@ 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(+def _to_account_details(account: Account) -> contracts.AccountDetails:+ return contracts.AccountDetails(id=account.id,name=account.name,external_id=account.external_id,@@ -3497,7 +3567,7 @@ def list_accounts_for_view(include_churned: bool = False,include_ignored: bool = False,ordering: str | None = None,-) -> tuple[list[contracts.AccountView], int]:+) -> tuple[list[contracts.AccountDetails], int]:"""The accounts list endpoint, behind the facade: team + object-level access filtering,the search / tags / unassigned / ordering query filters, notebook + tag prefetching, andpagination. Returns ``(page, total_count)``. ``tags``/``ordering`` are pre-validated by@@ -3531,25 +3601,25 @@ def list_accounts_for_view(total_count = queryset.count()page = list(queryset[offset : offset + limit])- return [_to_account_view(a) for a in page], total_count+ return [_to_account_details(a) for a in page], total_countdef get_account_for_view(*, team_id: int, account_id: str, user_access_control: "UserAccessControl", required_level: str | None-) -> contracts.AccountView:+) -> contracts.AccountDetails:"""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)+ return _to_account_details(account)def get_account_for_view_by_external_id(*, team_id: int, external_id: str, user_access_control: "UserAccessControl", required_level: str | None-) -> contracts.AccountView:+) -> contracts.AccountDetails:account = _account_detail_queryset(team_id).get(external_id=external_id)_enforce_object_access(account, user_access_control, required_level)- return _to_account_view(account)+ return _to_account_details(account)class _Unset(Enum):@@ -3677,7 +3747,7 @@ def create_account_for_view(input: contracts.CreateAccountInput,user: "User",was_impersonated: bool,-) -> contracts.AccountView:+) -> contracts.AccountDetails:account = create_account(team=team,created_by=user,@@ -3689,7 +3759,7 @@ def create_account_for_view(churned_at=input.churned_at,was_impersonated=was_impersonated,)- return _to_account_view(account)+ return _to_account_details(account)def update_account_for_view(@@ -3703,7 +3773,7 @@ def update_account_for_view(user: "User",was_impersonated: bool,allow_matching_updates: bool = False,-) -> contracts.AccountView:+) -> contracts.AccountDetails: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)@@ -3749,7 +3819,7 @@ def update_account_for_view(# and one backfill per switch is LLM spend nobody asked for.if not previous.slack_summary_cadence and account.slack_summary_cadence:_dispatch_initial_channel_summary(account)- return _to_account_view(account)+ return _to_account_details(account)# Roughly 70 accounts opting into a daily cadence in one day, far above real use.diff --git a/products/customer_analytics/backend/facade/constants.py b/products/customer_analytics/backend/facade/constants.pyindex 6f314ae6ce11..7776e3344384 100644--- a/products/customer_analytics/backend/facade/constants.py+++ b/products/customer_analytics/backend/facade/constants.py@@ -10,6 +10,7 @@ from products.customer_analytics.backend.constants import (BILLING_USAGE_INSIGHT_SHORT_IDS,CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES,CUSTOM_PROPERTY_OPTION_COLORS,+ CUSTOMER_ANALYTICS_ACCOUNT_VIEWS_FLAG,CUSTOMER_ANALYTICS_CSP_FLAG,CUSTOMER_ANALYTICS_CUSTOMER_TASKS_FLAG,CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG,@@ -27,6 +28,7 @@ __all__ = ["CUSTOM_PROPERTY_OPTION_COLORS","CUSTOMER_ANALYTICS_CSP_FLAG","CUSTOMER_ANALYTICS_CUSTOMER_TASKS_FLAG",+ "CUSTOMER_ANALYTICS_ACCOUNT_VIEWS_FLAG","CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG","CUSTOMER_ANALYTICS_TRACK_RULES_FLAG","DEFAULT_ACTIVITY_EVENT",diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 17bd41090569..72025604234b 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -769,7 +769,7 @@ class UserBasicInfo:@stdlib_dataclass(frozen=True)-class AccountView:+class AccountDetails:"""An account as returned by the accounts list/detail endpoints.``properties`` is the raw stored JSON dict (``Account._properties``), not the@@ -801,11 +801,25 @@ class AccountView:updated_at: datetime | None = None+@dataclass(frozen=True)+class AccountView:+ id: UUID+ name: str+ visibility: Literal["private"]+ content: dict[str, Any]+ text_content: str+ version: int+ created_by: int | None+ last_modified_by: int | None+ created_at: datetime+ updated_at: datetime++@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+ Defaults exist for the same reason as :class:`AccountDetails` — the wrapping serializerdoubles as request + response so the OpenAPI components stay identical."""@@ -1021,7 +1035,7 @@ 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`).+ :class:`AccountDetails`)."""id: UUID | None = None@@ -1059,7 +1073,7 @@ class CustomPropertyDefinitionView:custom-property-definitions endpoints.Defaults exist so the wrapping serializer can parse partial request bodies (see- :class:`AccountView`). ``created_by`` is the creator's user id (or ``None``), matching+ :class:`AccountDetails`). ``created_by`` is the creator's user id (or ``None``), matchingthe old model serializer's ``PrimaryKeyRelatedField`` output. ``references`` lists where theproperty is used (workflows), resolved by definition id. ``source`` is the read-onlyview-sync binding when one is configured for this definition, else ``None``.@@ -1093,7 +1107,7 @@ class CustomPropertySourceView:run. Account-target sources set ``saved_query`` + ``source_column``; person- and group-targetsources set ``column_property_map`` plus exactly one of ``external_data_schema`` (an importedtable) and ``saved_query`` (a materialized view). Defaults exist so the wrapping serializer can- parse partial request bodies (see :class:`AccountView`).+ parse partial request bodies (see :class:`AccountDetails`)."""id: UUID | None = None@@ -1157,7 +1171,7 @@ 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`).+ :class:`AccountDetails`)."""id: UUID | None = None@@ -1175,7 +1189,7 @@ class AccountNotebookView:class AccountNoteView:"""A row of the team-wide account-notes list: an internal notebook plus the account it'slinked to. Read-only (the wrapping serializer never parses request bodies), so fields are- strict — no serializer-instantiation defaults like :class:`AccountView` needs."""+ strict — no serializer-instantiation defaults like :class:`AccountDetails` needs."""short_id: strtitle: str | None@@ -1290,7 +1304,7 @@ class EventStreamView:(``event_names``), the owner's Slack delivery target, and the member accounts(``account_ids``) whose users' events are streamed.Defaults exist so the wrapping serializer can parse partial request bodies (see- :class:`AccountView`).+ :class:`AccountDetails`)."""id: UUID | None = Nonediff --git a/products/customer_analytics/backend/facade/enums.py b/products/customer_analytics/backend/facade/enums.pyindex 3f5be33d7111..dbf775a40477 100644--- a/products/customer_analytics/backend/facade/enums.py+++ b/products/customer_analytics/backend/facade/enums.py@@ -8,6 +8,11 @@ class AccountPropertyPinKind(str, Enum):RELATIONSHIP = "relationship"+class AccountViewVisibility(models.TextChoices):+ PRIVATE = "private", "Personal"+ TEAM = "team", "Team"++class TaskDigestCadence(models.TextChoices):"""How often a user's customer task digest email is sent."""@@ -47,6 +52,7 @@ class OwnershipRoleDiagnostic(models.TextChoices):__all__ = ["AccountPropertyPinKind",+ "AccountViewVisibility","AccountRelationshipSource","OwnershipRoleDiagnostic","OwnershipRoleState",diff --git a/products/customer_analytics/backend/logic/account_views.py b/products/customer_analytics/backend/logic/account_views.pynew file mode 100644index 000000000000..d12ede347a72--- /dev/null+++ b/products/customer_analytics/backend/logic/account_views.py@@ -0,0 +1,220 @@+import re+import json+from typing import Any+from uuid import UUID++from django.db import transaction+from django.utils import timezone++from products.customer_analytics.backend.facade.enums import AccountViewVisibility+from products.customer_analytics.backend.models.account_view import AccountView+from products.notebooks.backend.facade import content as notebook_content+from products.notebooks.backend.facade.contracts import NotebookMarkdownContentInvalid++ACCOUNT_VIEW_COMPONENT_LABELS = {+ "Notes": "Notes",+ "Tasks": "Tasks",+ "Users": "Users",+ "Relationships": "Relationships",+ "FeatureRequests": "Feature requests",+ "Usage": "Usage",+ "Spend": "Spend",+ "Opportunities": "Opportunities",+ "Conversations": "Conversations",+ "Meetings": "Meetings",+ "EventStream": "Event stream",+}+ACCOUNT_VIEW_ALLOWED_PROPS = {"config", "nodeId", "title"}+ACCOUNT_VIEW_COMPONENT_TITLE_MAX_LENGTH = 400+ACCOUNT_VIEW_CONFIG_MAX_BYTES = 16_384+ACCOUNT_VIEW_IDENTITY_PROPS = {+ "accountId",+ "account_id",+ "externalId",+ "external_id",+ "projectId",+ "project_id",+ "teamId",+ "team_id",+}+ACCOUNT_VIEW_NODE_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9:_-]{0,127}$")+++class InvalidAccountViewContent(ValueError):+ def __init__(self, errors: list[str]) -> None:+ super().__init__("; ".join(errors))+ self.errors = errors+++class AccountViewVersionConflict(Exception):+ pass+++def get_account_identity_props(value: object) -> set[str]:+ if isinstance(value, dict):+ return ACCOUNT_VIEW_IDENTITY_PROPS.intersection(value) | set().union(+ *(get_account_identity_props(item) for item in value.values())+ )+ if isinstance(value, list):+ return set().union(*(get_account_identity_props(item) for item in value))+ return set()+++def list_account_views(*, team_id: int, user_id: int) -> list[AccountView]:+ return list(+ AccountView.objects.for_team(team_id)+ .filter(created_by_id=user_id, deleted_at__isnull=True, visibility=AccountViewVisibility.PRIVATE)+ .order_by("name", "created_at")+ )+++def get_account_view(*, team_id: int, user_id: int, view_id: UUID) -> AccountView | None:+ return (+ AccountView.objects.for_team(team_id)+ .filter(+ id=view_id,+ created_by_id=user_id,+ deleted_at__isnull=True,+ visibility=AccountViewVisibility.PRIVATE,+ )+ .first()+ )+++def validate_account_view_content(content: dict[str, Any]) -> tuple[dict[str, Any], str]:+ try:+ components = notebook_content.parse_markdown_component_document(content)+ except NotebookMarkdownContentInvalid as error:+ raise InvalidAccountViewContent([str(error)]) from error++ if not components:+ raise InvalidAccountViewContent(["Add at least one component."])++ errors: list[str] = []+ node_ids: set[str] = set()+ labels: list[str] = []+ for index, component in enumerate(components, start=1):+ label = ACCOUNT_VIEW_COMPONENT_LABELS.get(component.tag_name)+ if label is None:+ errors.append(f"Component {index} uses unknown type {component.tag_name}.")+ continue+ title = component.props.get("title")+ if title is None:+ labels.append(label)+ elif not isinstance(title, str) or not title.strip() or len(title) > ACCOUNT_VIEW_COMPONENT_TITLE_MAX_LENGTH:+ errors.append(f"Component {index} title must be a non-empty string up to 400 characters.")+ else:+ labels.append(title.strip())++ identity_props = ACCOUNT_VIEW_IDENTITY_PROPS.intersection(component.props)+ if identity_props:+ errors.append(f"Component {index} cannot set account identity.")++ unknown_props = set(component.props).difference(ACCOUNT_VIEW_ALLOWED_PROPS)+ if unknown_props:+ errors.append(f"Component {index} has unsupported properties: {', '.join(sorted(unknown_props))}.")++ node_id = component.props.get("nodeId")+ if not isinstance(node_id, str) or not ACCOUNT_VIEW_NODE_ID.fullmatch(node_id):+ errors.append(f"Component {index} needs a valid nodeId.")+ elif node_id in node_ids:+ errors.append(f"Component {index} duplicates nodeId {node_id}.")+ else:+ node_ids.add(node_id)++ config = component.props.get("config")+ if config is not None:+ if not isinstance(config, dict):+ errors.append(f"Component {index} config must be an object.")+ elif identity_props := get_account_identity_props(config):+ errors.append(+ f"Component {index} config cannot set account identity: {', '.join(sorted(identity_props))}."+ )+ elif len(json.dumps(config, separators=(",", ":")).encode()) > ACCOUNT_VIEW_CONFIG_MAX_BYTES:+ errors.append(f"Component {index} config is too large.")++ if errors:+ raise InvalidAccountViewContent(errors)++ return content, "\n".join(labels)+++def create_account_view(*, team_id: int, user_id: int, name: str, content: dict[str, Any]) -> AccountView:+ validated_content, text_content = validate_account_view_content(content)+ return AccountView.objects.for_team(team_id).create(+ team_id=team_id,+ name=name,+ visibility=AccountViewVisibility.PRIVATE,+ content=validated_content,+ text_content=text_content,+ created_by_id=user_id,+ last_modified_by_id=user_id,+ )+++def update_account_view(+ *,+ team_id: int,+ user_id: int,+ view_id: UUID,+ expected_version: int,+ name: str | None = None,+ content: dict[str, Any] | None = None,+) -> AccountView | None:+ view = (+ AccountView.objects.for_team(team_id)+ .select_for_update()+ .filter(+ id=view_id,+ created_by_id=user_id,+ deleted_at__isnull=True,+ visibility=AccountViewVisibility.PRIVATE,+ )+ .first()+ )+ if view is None:+ return None+ if view.version != expected_version:+ raise AccountViewVersionConflict("This view changed since you opened it.")+ if name is None and content is None:+ return view++ update_fields = ["last_modified_by", "version", "updated_at"]+ if name is not None:+ view.name = name+ update_fields.append("name")+ if content is not None:+ view.content, view.text_content = validate_account_view_content(content)+ update_fields.extend(["content", "text_content"])++ view.last_modified_by_id = user_id+ view.version += 1+ view.save(update_fields=update_fields)+ return view+++def delete_account_view(*, team_id: int, user_id: int, view_id: UUID, expected_version: int) -> bool:+ view = (+ AccountView.objects.for_team(team_id)+ .select_for_update()+ .filter(+ id=view_id,+ created_by_id=user_id,+ deleted_at__isnull=True,+ visibility=AccountViewVisibility.PRIVATE,+ )+ .first()+ )+ if view is None:+ return False+ if view.version != expected_version:+ raise AccountViewVersionConflict("This view changed since you opened it.")++ view.deleted_at = timezone.now()+ view.last_modified_by_id = user_id+ view.version += 1+ view.save(update_fields=["deleted_at", "last_modified_by", "version", "updated_at"])+ return Truediff --git a/products/customer_analytics/backend/migrations/0059_account_view.py b/products/customer_analytics/backend/migrations/0059_account_view.pynew file mode 100644index 000000000000..eee07af92104--- /dev/null+++ b/products/customer_analytics/backend/migrations/0059_account_view.py@@ -0,0 +1,93 @@+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ (+ "customer_analytics",+ "0058_accountrelationshipdefinition_claim_saved_query_sha256",+ ),+ ("posthog", "1385_add_data_deletion_submission_id_constraint"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="AccountView",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("name", models.CharField(max_length=400)),+ (+ "visibility",+ models.CharField(+ choices=[("private", "Personal"), ("team", "Team")],+ default="private",+ max_length=16,+ ),+ ),+ ("content", models.JSONField()),+ ("text_content", models.TextField(db_default="", default="")),+ ("version", models.PositiveIntegerField(db_default=1, default=1)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ ("deleted_at", models.DateTimeField(blank=True, null=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ db_index=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "last_modified_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ db_index=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "indexes": [+ models.Index(+ fields=["team", "deleted_at", "visibility"],+ name="ca_account_view_list_idx",+ ),+ models.Index(+ fields=["team", "created_by", "deleted_at"],+ name="ca_account_view_owner_idx",+ ),+ ],+ },+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txtindex 590fa37f332c..e0d47da63581 100644--- a/products/customer_analytics/backend/migrations/max_migration.txt+++ b/products/customer_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0058_accountrelationshipdefinition_claim_saved_query_sha256+0059_account_viewdiff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.pyindex eea7e80e70da..22433f7a450f 100644--- a/products/customer_analytics/backend/models/__init__.py+++ b/products/customer_analytics/backend/models/__init__.py@@ -1,6 +1,7 @@from .account import Accountfrom .account_channel_summary import AccountChannelSummary, SlackSummaryCadencefrom .account_track_rule_run import AccountTrackRuleRun, AccountTrackRuleRunStatus, AccountTrackRuleRunTrigger+from .account_view import AccountViewfrom .announcement import Announcementfrom .announcement_delivery import AnnouncementDeliveryfrom .custom_property_definition import (@@ -41,6 +42,7 @@ __all__ = ["CANONICAL_LAST_SLACK_MESSAGE_AT","DATA_TYPE_BY_DISPLAY_TYPE","Account",+ "AccountView","AccountChannelSummary","AccountTrackRuleRun","AccountTrackRuleRunStatus",diff --git a/products/customer_analytics/backend/models/account_view.py b/products/customer_analytics/backend/models/account_view.pynew file mode 100644index 000000000000..0f1bdfc49f81--- /dev/null+++ b/products/customer_analytics/backend/models/account_view.py@@ -0,0 +1,53 @@+from django.db import models++from posthog.models.activity_logging.model_activity import ModelActivityMixin+from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel++from products.customer_analytics.backend.facade.enums import AccountViewVisibility+++class AccountView(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")+ name = models.CharField(max_length=400)+ visibility = models.CharField(+ max_length=16,+ choices=AccountViewVisibility.choices,+ default=AccountViewVisibility.PRIVATE,+ )+ content = models.JSONField()+ text_content = models.TextField(default="", db_default="")+ version = models.PositiveIntegerField(default=1, db_default=1)+ created_by = models.ForeignKey(+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ db_constraint=False,+ db_index=False,+ related_name="+",+ )+ last_modified_by = models.ForeignKey(+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ db_constraint=False,+ db_index=False,+ related_name="+",+ )+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)+ deleted_at = models.DateTimeField(null=True, blank=True)++ class Meta:+ indexes = [+ models.Index(+ fields=["team", "deleted_at", "visibility"],+ name="ca_account_view_list_idx",+ ),+ models.Index(+ fields=["team", "created_by", "deleted_at"],+ name="ca_account_view_owner_idx",+ ),+ ]diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex 2a5c5ccb2863..fcf488d65b92 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -50,6 +50,7 @@ from products.customer_analytics.backend.facade.contracts import (TASK_DIGEST_SEND_TIME_FORMAT,AccountAssignment,AccountChannelSummaryView,+ AccountDetails,AccountNotebookView,AccountNoteView,AccountPresence,@@ -84,6 +85,7 @@ from products.customer_analytics.backend.facade.contracts import (from products.customer_analytics.backend.facade.enums import (AccountPropertyPinKind,AccountRelationshipSource,+ AccountViewVisibility,TaskDigestCadence,)@@ -960,6 +962,111 @@ class CustomerProfileConfigSerializer(DataclassSerializer):return value+class AccountViewMarkdownAttributesSerializer(serializers.Serializer):+ nodeId = serializers.CharField(help_text="Stable identifier for this document.")+ markdown = serializers.CharField(+ max_length=256 * 1024, help_text="Component-only Markdown stored by the account view editor."+ )+++class AccountViewMarkdownNodeSerializer(serializers.Serializer):+ type = serializers.ChoiceField(+ choices=["ph-markdown-notebook"],+ help_text="Markdown notebook node type.",+ )+ attrs = AccountViewMarkdownAttributesSerializer(help_text="Markdown notebook attributes.")+++class AccountViewContentSerializer(serializers.Serializer):+ type = serializers.ChoiceField(choices=["doc"], help_text="Document root type.")+ content = serializers.ListField(+ child=AccountViewMarkdownNodeSerializer(),+ min_length=1,+ max_length=1,+ help_text="The single Markdown notebook node containing the account view components.",+ )+++class AccountViewSerializer(DataclassSerializer):+ id = serializers.UUIDField(read_only=True, help_text="Stable account view identifier.")+ name = serializers.CharField(read_only=True, help_text="Name shown in the account view.")+ visibility = serializers.CharField(read_only=True, help_text="Account views created through this API are private.")+ content = AccountViewContentSerializer(read_only=True, help_text="Validated Markdown notebook document.")+ text_content = serializers.CharField(+ read_only=True, help_text="Searchable component labels extracted from content."+ )+ version = serializers.IntegerField(read_only=True, help_text="Optimistic concurrency version.")+ created_by = serializers.IntegerField(read_only=True, allow_null=True, help_text="Creator user ID.")+ last_modified_by = serializers.IntegerField(+ read_only=True,+ allow_null=True,+ help_text="User ID that last changed the view.",+ )+ created_at = serializers.DateTimeField(read_only=True, help_text="When the view was created.")+ updated_at = serializers.DateTimeField(read_only=True, help_text="When the view was last changed.")++ class Meta:+ dataclass = AccountView+ ref_name = "AccountView"+ fields = [+ "id",+ "name",+ "visibility",+ "content",+ "text_content",+ "version",+ "created_by",+ "last_modified_by",+ "created_at",+ "updated_at",+ ]+++class AccountViewCreateSerializer(serializers.Serializer):+ name = serializers.CharField(max_length=400, allow_blank=False, trim_whitespace=True, help_text="View name.")+ content = AccountViewContentSerializer(help_text="Initial account view components.")+++class AccountViewUpdateSerializer(serializers.Serializer):+ name = serializers.CharField(+ max_length=400,+ allow_blank=False,+ trim_whitespace=True,+ required=False,+ help_text="New view name. Omit to keep the current name.",+ )+ content = AccountViewContentSerializer(+ required=False,+ help_text="Replacement account view components. Omit to keep current content.",+ )+ visibility = serializers.ChoiceField(+ choices=[(AccountViewVisibility.PRIVATE, "Personal")],+ required=False,+ write_only=True,+ help_text="Views can only be private.",+ )+ version = serializers.IntegerField(min_value=1, help_text="Version returned by the last read.")++ def validate_visibility(self, value: str) -> str:+ if value != AccountViewVisibility.PRIVATE:+ raise serializers.ValidationError("Views can only be private.")+ return value++ # The endpoint is a PATCH, so the schema generator marks every field optional. Every update needs+ # `version`, and the generated types and MCP tool must say so.+ @property+ def partial(self) -> bool:+ return False++ @partial.setter+ def partial(self, _value: bool) -> None:+ pass+++class AccountViewDeleteQuerySerializer(serializers.Serializer):+ version = serializers.IntegerField(min_value=1, help_text="Version returned by the last read.")++class CustomerJourneySerializer(DataclassSerializer):id = serializers.UUIDField(read_only=True)insight = serializers.IntegerField()@@ -1052,7 +1159,7 @@ class AccountSerializer(DataclassSerializer):updated_at = serializers.DateTimeField(read_only=True, allow_null=True)class Meta:- dataclass = AccountView+ dataclass = AccountDetailsref_name = "Account"fields = ["id",diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 0bb9c8a9c671..20a248f33272 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -61,6 +61,7 @@ from products.access_control.backend.facade.user_access_control import UserAccesfrom products.access_control.backend.presentation.access_control import AccessControlViewSetMixinfrom products.customer_analytics.backend.facade import api, contractsfrom products.customer_analytics.backend.facade.constants import (+ CUSTOMER_ANALYTICS_ACCOUNT_VIEWS_FLAG,CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG,CUSTOMER_ANALYTICS_TRACK_RULES_FLAG,)@@ -82,6 +83,10 @@ from products.customer_analytics.backend.presentation.views.serializers import (AccountTrackRuleRunRequestSerializer,AccountTrackRuleRunSerializer,AccountTrackRulesConfigSerializer,+ AccountViewCreateSerializer,+ AccountViewDeleteQuerySerializer,+ AccountViewSerializer,+ AccountViewUpdateSerializer,CalendarSyncBackfillSerializer,CalendarSyncIntervalSerializer,CalendarSyncStatusSerializer,@@ -867,6 +872,106 @@ class FeatureRequestViewSet(return Response(FeatureRequestStatusHistorySerializer(instance=history, many=True).data)+class AccountViewTemplateViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.GenericViewSet):+ scope_object = "account"+ serializer_class = AccountViewSerializer+ lookup_value_regex = r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"+ queryset = None+ pagination_class = None+ permission_classes = [PostHogFeatureFlagPermission]+ posthog_feature_flag = CUSTOMER_ANALYTICS_ACCOUNT_VIEWS_FLAG++ @extend_schema(responses={200: AccountViewSerializer(many=True)}, summary="List account views")+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ views = api.list_account_views(team_id=self.team_id, user_id=cast(User, request.user).id)+ return Response(AccountViewSerializer(instance=views, many=True).data)++ @extend_schema(responses={200: AccountViewSerializer}, summary="Get an account view")+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ view = api.get_account_view(+ team_id=self.team_id,+ user_id=cast(User, request.user).id,+ view_id=UUID(self.kwargs["pk"]),+ )+ if view is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(AccountViewSerializer(instance=view).data)++ @validated_request(+ request_serializer=AccountViewCreateSerializer,+ responses={201: AccountViewSerializer, 400: OpenApiResponse(description="The content is invalid.")},+ summary="Create a private account view",+ )+ def create(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:+ try:+ view = api.create_account_view(+ team_id=self.team_id,+ user_id=cast(User, request.user).id,+ name=request.validated_data["name"],+ content=request.validated_data["content"],+ )+ except api.InvalidAccountViewContent as error:+ raise ValidationError({"content": error.errors})+ return Response(AccountViewSerializer(instance=view).data, status=status.HTTP_201_CREATED)++ @validated_request(+ request_serializer=AccountViewUpdateSerializer,+ responses={+ 200: AccountViewSerializer,+ 400: OpenApiResponse(description="The request is invalid."),+ 404: OpenApiResponse(description="The view was not found."),+ 409: OpenApiResponse(description="The view changed since the supplied version."),+ },+ summary="Update an account view",+ )+ def partial_update(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:+ try:+ view = api.update_account_view(+ team_id=self.team_id,+ user_id=cast(User, request.user).id,+ view_id=UUID(self.kwargs["pk"]),+ expected_version=request.validated_data["version"],+ name=request.validated_data.get("name"),+ content=request.validated_data.get("content"),+ )+ except api.InvalidAccountViewContent as error:+ raise ValidationError({"content": error.errors})+ except api.AccountViewVersionConflict as error:+ raise Conflict(str(error))+ if view is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(AccountViewSerializer(instance=view).data)++ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="version",+ type=OpenApiTypes.INT,+ location=OpenApiParameter.QUERY,+ required=True,+ description="Version returned by the last read.",+ )+ ],+ responses={204: None, 404: OpenApiResponse(), 409: OpenApiResponse()},+ summary="Delete an account view",+ )+ def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ query = AccountViewDeleteQuerySerializer(data=request.query_params)+ query.is_valid(raise_exception=True)+ try:+ deleted = api.delete_account_view(+ team_id=self.team_id,+ user_id=cast(User, request.user).id,+ view_id=UUID(self.kwargs["pk"]),+ expected_version=query.validated_data["version"],+ )+ except api.AccountViewVersionConflict as error:+ raise Conflict(str(error))+ if not deleted:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(status=status.HTTP_204_NO_CONTENT)++class UserConfigCanonicalTeamAccessPermission(BasePermission):message = "You don't have access to the project."diff --git a/products/customer_analytics/backend/routes.py b/products/customer_analytics/backend/routes.pyindex c0bef85b6f95..c4ad1a860609 100644--- a/products/customer_analytics/backend/routes.py+++ b/products/customer_analytics/backend/routes.py@@ -14,6 +14,7 @@ from products.customer_analytics.backend.presentation.views.views import (AccountRelationshipViewSet,AccountTrackRuleViewSet,AccountViewSet,+ AccountViewTemplateViewSet,CalendarSyncViewSet,CustomerJourneyViewSet,CustomerProfileConfigViewSet,@@ -116,6 +117,12 @@ def register_routes(routers: RouterRegistry) -> None:"project_user_customer_analytics_config",["team_id"],)+ routers.projects.register(+ r"account_views",+ AccountViewTemplateViewSet,+ "project_account_views",+ ["team_id"],+ )project_accounts_router = routers.projects.register(r"accounts", AccountViewSet, "project_accounts", ["team_id"])project_accounts_router.register(r"notebooks", AccountNotebookViewSet, "project_account_notebooks", ["team_id", "account_id"]diff --git a/products/customer_analytics/backend/signals.py b/products/customer_analytics/backend/signals.pynew file mode 100644index 000000000000..418b10029caa--- /dev/null+++ b/products/customer_analytics/backend/signals.py@@ -0,0 +1,19 @@+from typing import Any++from django.db.models.signals import pre_delete+from django.dispatch import receiver++from posthog.models.user import User++from products.customer_analytics.backend.facade.enums import AccountViewVisibility+from products.customer_analytics.backend.models.account_view import AccountView+++@receiver(pre_delete, sender=User)+def delete_private_account_views_for_deleted_user(+ sender: type[User], instance: User, using: str, **kwargs: Any+) -> None:+ AccountView.objects.unscoped().filter(+ created_by_id=instance.id,+ visibility=AccountViewVisibility.PRIVATE,+ ).delete()diff --git a/products/customer_analytics/backend/test/test_account_views.py b/products/customer_analytics/backend/test/test_account_views.pynew file mode 100644index 000000000000..46e54f357561--- /dev/null+++ b/products/customer_analytics/backend/test/test_account_views.py@@ -0,0 +1,159 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from rest_framework import status++from posthog.constants import AvailableFeature+from posthog.models import OrganizationMembership, User+from posthog.models.activity_logging.activity_log import ActivityLog++from products.access_control.backend.models.access_control import AccessControl+from products.customer_analytics.backend.models import AccountView+++def account_view_content(*components: str) -> dict:+ return {+ "type": "doc",+ "content": [+ {+ "type": "ph-markdown-notebook",+ "attrs": {"nodeId": "markdown-notebook-v2", "markdown": "\n\n".join(components)},+ }+ ],+ }+++class TestAccountViews(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.enterContext(patch("posthoganalytics.feature_enabled", return_value=True))+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ {"key": AvailableFeature.AUDIT_LOGS, "name": AvailableFeature.AUDIT_LOGS},+ ]+ self.organization.save()+ self.endpoint = f"/api/projects/{self.team.id}/account_views/"+ self.viewer = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ membership = OrganizationMembership.objects.get(user=self.viewer, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="account",+ access_level="viewer",+ organization_member=membership,+ )++ def _create(self) -> dict:+ response = self.client.post(+ self.endpoint,+ {+ "name": "Account workspace",+ "content": account_view_content('<Usage nodeId="usage-one" title="Product usage" />'),+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ self.assertEqual(response.json()["visibility"], "private")+ return response.json()++ def test_private_view_is_not_readable_or_editable_by_another_user(self) -> None:+ view = self._create()++ self.client.force_login(self.viewer)+ self.assertEqual(self.client.get(self.endpoint).json(), [])+ self.assertEqual(self.client.get(f"{self.endpoint}{view['id']}/").status_code, status.HTTP_404_NOT_FOUND)+ self.assertEqual(+ self.client.patch(+ f"{self.endpoint}{view['id']}/",+ {"name": "Changed", "version": view["version"]},+ format="json",+ ).status_code,+ status.HTTP_404_NOT_FOUND,+ )++ def test_malformed_view_id_returns_not_found(self) -> None:+ malformed_id = "zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz"+ self.assertEqual(self.client.get(f"{self.endpoint}{malformed_id}/").status_code, status.HTTP_404_NOT_FOUND)+ self.assertEqual(+ self.client.patch(f"{self.endpoint}{malformed_id}/", {"version": 1}, format="json").status_code,+ status.HTTP_404_NOT_FOUND,+ )++ def test_patch_rejects_team_visibility(self) -> None:+ view = self._create()++ response = self.client.patch(+ f"{self.endpoint}{view['id']}/",+ {"visibility": "team", "version": view["version"]},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ self.assertEqual(AccountView.objects.for_team(self.team.id).get(id=view["id"]).visibility, "private")++ def test_stale_update_does_not_overwrite_newer_content(self) -> None:+ view = self._create()+ first = self.client.patch(+ f"{self.endpoint}{view['id']}/",+ {"name": "First save", "version": view["version"]},+ format="json",+ )+ self.assertEqual(first.status_code, status.HTTP_200_OK, first.json())+ unchanged = self.client.patch(+ f"{self.endpoint}{view['id']}/",+ {"version": first.json()["version"]},+ format="json",+ )+ self.assertEqual(unchanged.status_code, status.HTTP_200_OK, unchanged.json())+ self.assertEqual(unchanged.json()["version"], first.json()["version"])++ stale = self.client.patch(+ f"{self.endpoint}{view['id']}/",+ {"name": "Stale save", "version": view["version"]},+ format="json",+ )++ self.assertEqual(stale.status_code, status.HTTP_409_CONFLICT)+ self.assertEqual(AccountView.objects.for_team(self.team.id).get(id=view["id"]).name, "First save")++ def test_invalid_content_is_not_persisted(self) -> None:+ response = self.client.post(+ self.endpoint,+ {+ "name": "Invalid",+ "content": account_view_content('<Usage nodeId="same" accountId="customer-1" />'),+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertFalse(AccountView.objects.for_team(self.team.id).exists())++ def test_create_update_and_delete_are_audited_without_content(self) -> None:+ view = self._create()+ updated = self.client.patch(+ f"{self.endpoint}{view['id']}/",+ {+ "name": "Updated private view",+ "content": account_view_content('<Usage nodeId="usage-one" title="Renewal details" />'),+ "version": view["version"],+ },+ format="json",+ )+ self.assertEqual(updated.status_code, status.HTTP_200_OK, updated.json())+ deleted = self.client.delete(f"{self.endpoint}{view['id']}/?version={updated.json()['version']}")+ self.assertEqual(deleted.status_code, status.HTTP_204_NO_CONTENT)++ activities = ActivityLog.objects.filter(scope="AccountView", item_id=view["id"]).order_by("created_at")+ self.assertEqual([activity.activity for activity in activities], ["created", "updated", "deleted"])+ for activity in activities:+ self.assertNotIn("Account workspace", str(activity.detail))+ self.assertNotIn("Updated private view", str(activity.detail))+ self.assertNotIn("Product usage", str(activity.detail))+ self.assertNotIn("Renewal details", str(activity.detail))++ for user in (self.user, self.viewer):+ self.client.force_login(user)+ feed = self.client.get(f"/api/projects/{self.team.id}/activity_log/?scope=AccountView")+ self.assertEqual(feed.status_code, status.HTTP_200_OK, feed.json())+ self.assertEqual(feed.json()["results"], [])diff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.pyindex ebf4bec9ff41..638312fd02c4 100644--- a/products/customer_analytics/backend/test/test_facade.py+++ b/products/customer_analytics/backend/test/test_facade.py@@ -415,7 +415,7 @@ class TestCustomerAnalyticsCRUDFacade(BaseTest):kwargs.setdefault("name", "Acme Corp")return contracts.CreateAccountInput(**kwargs)- def _create(self, **kwargs) -> contracts.AccountView:+ def _create(self, **kwargs) -> contracts.AccountDetails:return facade.create_account_for_view(team=self.team,input=self._create_account_input(**kwargs),@@ -428,7 +428,7 @@ class TestCustomerAnalyticsCRUDFacade(BaseTest):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 isinstance(view, contracts.AccountDetails)assert view.name == "Acme"assert view.external_id == "acme-1"assert view.properties == {"stripe_customer_id": "cus_1"}diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 2a9288716c88..a5e71ac94d38 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -566,6 +566,126 @@ export interface PaginatedAccountTrackRuleRunViewListApi {results: AccountTrackRuleRunViewApi[]}+/**+ * * `doc` - doc+ */+export type AccountViewContentTypeEnumApi =+ (typeof AccountViewContentTypeEnumApi)[keyof typeof AccountViewContentTypeEnumApi]++export const AccountViewContentTypeEnumApi = {+ Doc: 'doc',+} as const++/**+ * * `ph-markdown-notebook` - ph-markdown-notebook+ */+export type AccountViewMarkdownNodeTypeEnumApi =+ (typeof AccountViewMarkdownNodeTypeEnumApi)[keyof typeof AccountViewMarkdownNodeTypeEnumApi]++export const AccountViewMarkdownNodeTypeEnumApi = {+ PhMarkdownNotebook: 'ph-markdown-notebook',+} as const++export interface AccountViewMarkdownAttributesApi {+ /** Stable identifier for this document. */+ nodeId: string+ /**+ * Component-only Markdown stored by the account view editor.+ * @maxLength 262144+ */+ markdown: string+}++export interface AccountViewMarkdownNodeApi {+ /** Markdown notebook node type.+ *+ * * `ph-markdown-notebook` - ph-markdown-notebook */+ type: AccountViewMarkdownNodeTypeEnumApi+ /** Markdown notebook attributes. */+ attrs: AccountViewMarkdownAttributesApi+}++export interface AccountViewContentApi {+ /** Document root type.+ *+ * * `doc` - doc */+ type: AccountViewContentTypeEnumApi+ /**+ * The single Markdown notebook node containing the account view components.+ * @minItems 1+ * @maxItems 1+ */+ content: AccountViewMarkdownNodeApi[]+}++export interface AccountViewApi {+ /** Stable account view identifier. */+ readonly id: string+ /** Name shown in the account view. */+ readonly name: string+ /** Account views created through this API are private. */+ readonly visibility: string+ /** Validated Markdown notebook document. */+ readonly content: AccountViewContentApi+ /** Searchable component labels extracted from content. */+ readonly text_content: string+ /** Optimistic concurrency version. */+ readonly version: number+ /**+ * Creator user ID.+ * @nullable+ */+ readonly created_by: number | null+ /**+ * User ID that last changed the view.+ * @nullable+ */+ readonly last_modified_by: number | null+ /** When the view was created. */+ readonly created_at: string+ /** When the view was last changed. */+ readonly updated_at: string+}++export interface AccountViewCreateApi {+ /**+ * View name.+ * @maxLength 400+ */+ name: string+ /** Initial account view components. */+ content: AccountViewContentApi+}++/**+ * * `private` - Personal+ */+export type AccountViewUpdateVisibilityEnumApi =+ (typeof AccountViewUpdateVisibilityEnumApi)[keyof typeof AccountViewUpdateVisibilityEnumApi]++export const AccountViewUpdateVisibilityEnumApi = {+ Private: 'private',+} as const++export interface AccountViewUpdateApi {+ /**+ * New view name. Omit to keep the current name.+ * @maxLength 400+ */+ name?: string+ /** Replacement account view components. Omit to keep current content. */+ content?: AccountViewContentApi+ /** Views can only be private.+ *+ * * `private` - Personal */+ visibility?: AccountViewUpdateVisibilityEnumApi+ /**+ * Version returned by the last read.+ * @minimum 1+ */+ version: number+}+/*** * `daily` - daily* * `weekly` - weekly@@ -4549,6 +4669,13 @@ export type AccountTrackRulesRunsListParams = {offset?: number}+export type AccountViewsDestroyParams = {+ /**+ * Version returned by the last read.+ */+ version: number+}+export type AccountsListParams = {/*** When true, returns only accounts where no user actively holds any relationship.diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex 8eae47934c7e..61ad311c6ace 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -24,6 +24,10 @@ import type {AccountTrackRuleRunViewApi,AccountTrackRulesConfigApi,AccountTrackRulesRunsListParams,+ AccountViewApi,+ AccountViewCreateApi,+ AccountViewUpdateApi,+ AccountViewsDestroyParams,AccountsByExternalIdRetrieveParams,AccountsEmailThreadMessagesListParams,AccountsEmailThreadsListParams,@@ -463,6 +467,110 @@ export const accountTrackRulesRunsList = async (})}+export const getAccountViewsListUrl = (projectId: string) => {+ return `/api/projects/${projectId}/account_views/`+}++/**+ * @summary List account views+ */+export const accountViewsList = async (projectId: string, options?: RequestInit): Promise<AccountViewApi[]> => {+ return apiMutator<AccountViewApi[]>(getAccountViewsListUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getAccountViewsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/account_views/`+}++/**+ * @summary Create a private account view+ */+export const accountViewsCreate = async (+ projectId: string,+ accountViewCreateApi: AccountViewCreateApi,+ options?: RequestInit+): Promise<AccountViewApi> => {+ return apiMutator<AccountViewApi>(getAccountViewsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(accountViewCreateApi),+ })+}++export const getAccountViewsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/account_views/${id}/`+}++/**+ * @summary Get an account view+ */+export const accountViewsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<AccountViewApi> => {+ return apiMutator<AccountViewApi>(getAccountViewsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getAccountViewsPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/account_views/${id}/`+}++/**+ * @summary Update an account view+ */+export const accountViewsPartialUpdate = async (+ projectId: string,+ id: string,+ accountViewUpdateApi: AccountViewUpdateApi,+ options?: RequestInit+): Promise<AccountViewApi> => {+ return apiMutator<AccountViewApi>(getAccountViewsPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(accountViewUpdateApi),+ })+}++export const getAccountViewsDestroyUrl = (projectId: string, id: string, params: AccountViewsDestroyParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/account_views/${id}/?${stringifiedParams}`+ : `/api/projects/${projectId}/account_views/${id}/`+}++/**+ * @summary Delete an account view+ */+export const accountViewsDestroy = async (+ projectId: string,+ id: string,+ params: AccountViewsDestroyParams,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getAccountViewsDestroyUrl(projectId, id, params), {+ ...options,+ method: 'DELETE',+ })+}+export const getAccountsListUrl = (projectId: string, params?: AccountsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex 12707a9bb2b3..202240adcaa5 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -233,6 +233,99 @@ export const AccountTrackRulesRunCreateBody = /* @__PURE__ */ zod.object({confirmed: zod.boolean(),})+/**+ * @summary Create a private account view+ */+export const accountViewsCreateBodyNameMax = 400++export const accountViewsCreateBodyContentOneContentItemAttrsOneMarkdownMax = 262144++export const accountViewsCreateBodyContentOneContentMax = 1++export const AccountViewsCreateBody = /* @__PURE__ */ zod.object({+ name: zod.string().max(accountViewsCreateBodyNameMax).describe('View name.'),+ content: zod+ .object({+ type: zod.enum(['doc']).describe('\* `doc` - doc').describe('Document root type.\n\n\* `doc` - doc'),+ content: zod+ .array(+ zod.object({+ type: zod+ .enum(['ph-markdown-notebook'])+ .describe('\* `ph-markdown-notebook` - ph-markdown-notebook')+ .describe(+ 'Markdown notebook node type.\n\n\* `ph-markdown-notebook` - ph-markdown-notebook'+ ),+ attrs: zod+ .object({+ nodeId: zod.string().describe('Stable identifier for this document.'),+ markdown: zod+ .string()+ .max(accountViewsCreateBodyContentOneContentItemAttrsOneMarkdownMax)+ .describe('Component-only Markdown stored by the account view editor.'),+ })+ .describe('Markdown notebook attributes.'),+ })+ )+ .min(1)+ .max(accountViewsCreateBodyContentOneContentMax)+ .describe('The single Markdown notebook node containing the account view components.'),+ })+ .describe('Initial account view components.'),+})++/**+ * @summary Update an account view+ */+export const accountViewsPartialUpdateBodyNameMax = 400++export const accountViewsPartialUpdateBodyContentOneContentItemAttrsOneMarkdownMax = 262144++export const accountViewsPartialUpdateBodyContentOneContentMax = 1++export const AccountViewsPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(accountViewsPartialUpdateBodyNameMax)+ .optional()+ .describe('New view name. Omit to keep the current name.'),+ content: zod+ .object({+ type: zod.enum(['doc']).describe('\* `doc` - doc').describe('Document root type.\n\n\* `doc` - doc'),+ content: zod+ .array(+ zod.object({+ type: zod+ .enum(['ph-markdown-notebook'])+ .describe('\* `ph-markdown-notebook` - ph-markdown-notebook')+ .describe(+ 'Markdown notebook node type.\n\n\* `ph-markdown-notebook` - ph-markdown-notebook'+ ),+ attrs: zod+ .object({+ nodeId: zod.string().describe('Stable identifier for this document.'),+ markdown: zod+ .string()+ .max(accountViewsPartialUpdateBodyContentOneContentItemAttrsOneMarkdownMax)+ .describe('Component-only Markdown stored by the account view editor.'),+ })+ .describe('Markdown notebook attributes.'),+ })+ )+ .min(1)+ .max(accountViewsPartialUpdateBodyContentOneContentMax)+ .describe('The single Markdown notebook node containing the account view components.'),+ })+ .optional()+ .describe('Replacement account view components. Omit to keep current content.'),+ visibility: zod+ .enum(['private'])+ .describe('\* `private` - Personal')+ .optional()+ .describe('Views can only be private.\n\n\* `private` - Personal'),+ version: zod.number().min(1).describe('Version returned by the last read.'),+})+export const accountsCreateBodyNameMax = 400export const accountsCreateBodyExternalIdMax = 400diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex 6aa50c830d40..e1478bed49d8 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -114,6 +114,21 @@ tools:account-track-rules-update:operation: account_track_rules_updateenabled: false+ account-views-create:+ operation: account_views_create+ enabled: false+ account-views-destroy:+ operation: account_views_destroy+ enabled: false+ account-views-list:+ operation: account_views_list+ enabled: false+ account-views-partial-update:+ operation: account_views_partial_update+ enabled: false+ account-views-retrieve:+ operation: account_views_retrieve+ enabled: falseaccounts-by-external-id-retrieve:operation: accounts_by_external_id_retrieveenabled: falsediff --git a/products/notebooks/backend/facade/content.py b/products/notebooks/backend/facade/content.pyindex 07bfd36a910f..14e4c388f31a 100644--- a/products/notebooks/backend/facade/content.py+++ b/products/notebooks/backend/facade/content.py@@ -6,6 +6,8 @@ so cross-product callers that build or sanitize notebook content import them frohere rather than reaching into ``backend.util``."""+from typing import Any+from ..markdown_conversion import (build_markdown_notebook_content as build_markdown_notebook_content,convert_notebook_content_to_markdown as convert_notebook_content_to_markdown,@@ -17,6 +19,7 @@ from ..util import (SHARED_NOTEBOOK_SUPPORTED_NODE_TYPES as SHARED_NOTEBOOK_SUPPORTED_NODE_TYPES,TipTapContent as TipTapContent,TipTapNode as TipTapNode,+ _parse_markdown_component_props,create_bullet_list as create_bullet_list,create_empty_paragraph as create_empty_paragraph,create_heading_with_text as create_heading_with_text,@@ -27,6 +30,27 @@ from ..util import (extract_inline_query_nodes as extract_inline_query_nodes,extract_referenced_insight_short_ids as extract_referenced_insight_short_ids,filter_notebook_content_for_sharing as filter_notebook_content_for_sharing,+ iter_markdown_blocks,iter_prosemirror_nodes as iter_prosemirror_nodes,sanitize_text_content as sanitize_text_content,)+from . import contracts+++def parse_markdown_component_document(content: Any) -> list[contracts.NotebookMarkdownComponent]:+ if not is_markdown_notebook_content(content):+ raise contracts.NotebookMarkdownContentInvalid("Content must use the Markdown notebook document format.")++ markdown = convert_notebook_content_to_markdown(content)+ components: list[contracts.NotebookMarkdownComponent] = []+ for block in iter_markdown_blocks(markdown):+ if block.kind != "component" or block.tag_name is None:+ raise contracts.NotebookMarkdownContentInvalid("Account views can contain components only.")+ components.append(+ contracts.NotebookMarkdownComponent(+ tag_name=block.tag_name,+ node_id=block.node_id,+ props=_parse_markdown_component_props(block.source),+ )+ )+ return componentsdiff --git a/products/notebooks/backend/facade/contracts.py b/products/notebooks/backend/facade/contracts.pyindex 4407bd39f05b..f3ab843b79b6 100644--- a/products/notebooks/backend/facade/contracts.py+++ b/products/notebooks/backend/facade/contracts.py@@ -53,6 +53,17 @@ class NotebookContentNotConvertible(Exception):"""+class NotebookMarkdownContentInvalid(Exception):+ pass+++@dataclass(frozen=True)+class NotebookMarkdownComponent:+ tag_name: str+ node_id: str+ props: dict[str, Any]++@dataclass(frozen=True)class NotebookData:"""A notebook's persisted state, as other products read it."""diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex 69ba7b42fb9c..8fd2d8e66fb8 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -1359,6 +1359,7 @@ export type ActivityLogListParams = {* * `OAuthApplication` - OAuthApplication* * `User` - User* * `Action` - Action+ * * `AccountView` - AccountView* * `AlertConfiguration` - AlertConfiguration* * `Threshold` - Threshold* * `AlertSubscription` - AlertSubscription@@ -1461,6 +1462,7 @@ export const ActivityLogListScope = {OAuthApplication: 'OAuthApplication',User: 'User',Action: 'Action',+ AccountView: 'AccountView',AlertConfiguration: 'AlertConfiguration',Threshold: 'Threshold',AlertSubscription: 'AlertSubscription',@@ -1550,6 +1552,7 @@ export const ActivityLogListScope = {* * `OAuthApplication` - OAuthApplication* * `User` - User* * `Action` - Action+ * * `AccountView` - AccountView* * `AlertConfiguration` - AlertConfiguration* * `Threshold` - Threshold* * `AlertSubscription` - AlertSubscription@@ -1640,6 +1643,7 @@ export const ActivityLogListScopesItem = {OAuthApplication: 'OAuthApplication',User: 'User',Action: 'Action',+ AccountView: 'AccountView',AlertConfiguration: 'AlertConfiguration',Threshold: 'Threshold',AlertSubscription: 'AlertSubscription',diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 95da4748d209..3411617aed48 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -1506,6 +1506,126 @@ export namespace Schemas {groups: AccountTrackRuleGroup[];}+ /**+ * * `doc` - doc+ */+ export type AccountViewContentTypeEnum = typeof AccountViewContentTypeEnum[keyof typeof AccountViewContentTypeEnum];+++ export const AccountViewContentTypeEnum = {+ Doc: 'doc',+ } as const;++ /**+ * * `ph-markdown-notebook` - ph-markdown-notebook+ */+ export type AccountViewMarkdownNodeTypeEnum = typeof AccountViewMarkdownNodeTypeEnum[keyof typeof AccountViewMarkdownNodeTypeEnum];+++ export const AccountViewMarkdownNodeTypeEnum = {+ PhMarkdownNotebook: 'ph-markdown-notebook',+ } as const;++ export interface AccountViewMarkdownAttributes {+ /** Stable identifier for this document. */+ nodeId: string;+ /**+ * Component-only Markdown stored by the account view editor.+ * @maxLength 262144+ */+ markdown: string;+ }++ export interface AccountViewMarkdownNode {+ /** Markdown notebook node type.+ *+ * * `ph-markdown-notebook` - ph-markdown-notebook */+ type: AccountViewMarkdownNodeTypeEnum;+ /** Markdown notebook attributes. */+ attrs: AccountViewMarkdownAttributes;+ }++ export interface AccountViewContent {+ /** Document root type.+ *+ * * `doc` - doc */+ type: AccountViewContentTypeEnum;+ /**+ * The single Markdown notebook node containing the account view components.+ * @minItems 1+ * @maxItems 1+ */+ content: AccountViewMarkdownNode[];+ }++ export interface AccountView {+ /** Stable account view identifier. */+ readonly id: string;+ /** Name shown in the account view. */+ readonly name: string;+ /** Account views created through this API are private. */+ readonly visibility: string;+ /** Validated Markdown notebook document. */+ readonly content: AccountViewContent;+ /** Searchable component labels extracted from content. */+ readonly text_content: string;+ /** Optimistic concurrency version. */+ readonly version: number;+ /**+ * Creator user ID.+ * @nullable+ */+ readonly created_by: number | null;+ /**+ * User ID that last changed the view.+ * @nullable+ */+ readonly last_modified_by: number | null;+ /** When the view was created. */+ readonly created_at: string;+ /** When the view was last changed. */+ readonly updated_at: string;+ }++ export interface AccountViewCreate {+ /**+ * View name.+ * @maxLength 400+ */+ name: string;+ /** Initial account view components. */+ content: AccountViewContent;+ }++ /**+ * * `private` - Personal+ */+ export type AccountViewUpdateVisibilityEnum = typeof AccountViewUpdateVisibilityEnum[keyof typeof AccountViewUpdateVisibilityEnum];+++ export const AccountViewUpdateVisibilityEnum = {+ Private: 'private',+ } as const;++ export interface AccountViewUpdate {+ /**+ * New view name. Omit to keep the current name.+ * @maxLength 400+ */+ name?: string;+ /** Replacement account view components. Omit to keep current content. */+ content?: AccountViewContent;+ /** Views can only be private.+ *+ * * `private` - Personal */+ visibility?: AccountViewUpdateVisibilityEnum;+ /**+ * Version returned by the last read.+ * @minimum 1+ */+ version: number;+ }+export type BounceRatePageViewMode = typeof BounceRatePageViewMode[keyof typeof BounceRatePageViewMode];@@ -108446,6 +108566,13 @@ export namespace Schemas {offset?: number;};+ export type AccountViewsDestroyParams = {+ /**+ * Version returned by the last read.+ */+ version: number;+ };+export type AccountsListParams = {/*** When true, returns only accounts where no user actively holds any relationship.@@ -108776,6 +108903,7 @@ export namespace Schemas {* * `OAuthApplication` - OAuthApplication* * `User` - User* * `Action` - Action+ * * `AccountView` - AccountView* * `AlertConfiguration` - AlertConfiguration* * `Threshold` - Threshold* * `AlertSubscription` - AlertSubscription@@ -108879,6 +109007,7 @@ export namespace Schemas {OAuthApplication: 'OAuthApplication',User: 'User',Action: 'Action',+ AccountView: 'AccountView',AlertConfiguration: 'AlertConfiguration',Threshold: 'Threshold',AlertSubscription: 'AlertSubscription',@@ -108968,6 +109097,7 @@ export namespace Schemas {* * `OAuthApplication` - OAuthApplication* * `User` - User* * `Action` - Action+ * * `AccountView` - AccountView* * `AlertConfiguration` - AlertConfiguration* * `Threshold` - Threshold* * `AlertSubscription` - AlertSubscription@@ -109059,6 +109189,7 @@ export namespace Schemas {OAuthApplication: 'OAuthApplication',User: 'User',Action: 'Action',+ AccountView: 'AccountView',AlertConfiguration: 'AlertConfiguration',Threshold: 'Threshold',AlertSubscription: 'AlertSubscription',