: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 multi-account request evidence (#83975)
Arthur Moreira de Deus82638de180fa
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 1b1750d78764..7df06a1c74fc 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -182,6 +182,7 @@ rules:|FeatureFlag|FeatureRequest|FeatureRequestAccountLink+ |FeatureRequestEvidence|FeatureRequestHistory|FeatureRequestProductArea|FeatureRequestProductAreaLink@@ -553,6 +554,7 @@ rules:|FeatureFlag|FeatureRequest|FeatureRequestAccountLink+ |FeatureRequestEvidence|FeatureRequestHistory|FeatureRequestProductArea|FeatureRequestProductAreaLinkdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 513ce11fd2c0..2826ba602b29 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5752,6 +5752,10 @@ snapshots:hash: v1.k794b7964.89995158723a826e4604ddfcf9681dc0c9b50f33219cfccd06ccce637fe1b65b.i40Oi8tI3Ey-wqAdh3EekF8ti9WEdjq6dx-6JQPSvA0scenes-app-customer-analytics-accounts--row-expanded-empty--light:hash: v1.k794b7964.9e34cdbfa99277db4e17ef52314317b9523ac737c8285b972460baa2b993e8ea.EQ8z6F2X7fhbbuoIctopbwQcd2nqhfDcwzEmlLgEAlM+ scenes-app-customer-analytics-accounts--row-expanded-feature-requests--dark:+ hash: v1.k794b7964.3550178b721e91fc806f841754bba3a3fdd2e0fdd2a8674cb2af773fd7ddad49.zXeWz2rgJxGeGlCJpmfj7fgjIGOw3P7UEZsRf7iaoGs+ scenes-app-customer-analytics-accounts--row-expanded-feature-requests--light:+ hash: v1.k794b7964.7834a6d05cb251553b3862de12152cb10f46e39ae247f3aea8790c4b8f32390c.ZgnlU9dDtcjD2PYGpqDfxi66rARzxeG18fNFn0_dpysscenes-app-customer-analytics-accounts--row-expanded-links-disabled--dark:hash: v1.k794b7964.385a63b277ab9041131f99759cf602d06443de6cc4e41333603d1187d64b6954.sQ8rSdSRp6Hbyvu_itGLdKOfbKjxjMSO_rxHaY4nP_0scenes-app-customer-analytics-accounts--row-expanded-links-disabled--light:@@ -5777,13 +5781,13 @@ snapshots:scenes-app-customer-analytics-dashboard--b-2-c-mode--light:hash: v1.k794b7964.ff25e11868464e00df352180254dbe0a1017cd1d8c7c4f4c7d6995068e80e2dc.m0XFOZVPCdSaCLaPQ6XTePvkZJ1I11QI2KARZi9QpWsscenes-app-customer-analytics-dashboard--feature-request-details--dark:- hash: v1.k794b7964.0d7ce44316c47882f56a1d1c7db14e241e03b92074985091f9c4b1ca069be524.PCx-z4FTlYvQqiqToglKwU2ILV0-ud1zzz8m9l-_xNc+ hash: v1.k794b7964.3b8a1d3f0725f7e80cb22182dbffd2669477fb0d7252e23a2f8600d255089d23.qT77Df8D6q02ZQhcSqw_bdueZW8sycJgDSJoC-t-Vl8scenes-app-customer-analytics-dashboard--feature-request-details--light:- hash: v1.k794b7964.a9f4788e8209cdd8b65d6cf83b53876cb5bd08486b337082d0a6267223c13868.GU1Yb6cnmrGF8WksLhk3ftl1zahAK0lUzGuNgqa8clY+ hash: v1.k794b7964.177e3c8ca3cdb3a1cde3fd4f3a53fa980da80c266828666b83f69120e203b2ce.SIQx9fwqD0gfUYUZhn2qfHrCPQCpNw44lP9tnE1j99Escenes-app-customer-analytics-dashboard--feature-requests--dark:- hash: v1.k794b7964.4a644f2b24bd9975a6c13537802a90de304fbbb0fe5c3175074a1254f7607a14.b2oNSFOpeVeb2UK_z8ITtLpwgmoqZWuBPkm_V_RVHb8+ hash: v1.k794b7964.678601de25c8530baa9bd4e94dc67731a7844beae1e6b59a47662824cba7a3e6.EjmdN0pXmKKifMocgNRlncMyliK4qEZlj2AqJ3LhclMscenes-app-customer-analytics-dashboard--feature-requests--light:- hash: v1.k794b7964.167bfebacfdc4de1bd7297ee4ed1c02d706664f3faf599cdcba0daa0d5016482.3zruynD8LR3q8WO3WzA9GE-5dJNbs0hKpdGa5o_ULnc+ hash: v1.k794b7964.87acabcc5f63d80410f42f07ed172a86f4113743b89949eea8436994216a674a.Oc_4HP6VqrlgLwYSOjuJjJp-MgKBKDLHUx-wCjL9vwQscenes-app-customer-analytics-dashboard--gated-with-feature-toggle--dark:hash: v1.k794b7964.731394bccab76141d6dc494f99dd56cc85e18b3f787977f8edd5c1a50c5564c8.9z2bNOo-dAM0tEyxcqStccQSV7X6iHbKnJdqAgvNapUscenes-app-customer-analytics-dashboard--gated-with-feature-toggle--light:diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 9ab817a24a92..a86d40b8bb40 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -2309,6 +2309,74 @@ def update_feature_request()+def add_feature_request_account(+ *,+ team_id: int,+ feature_request_id: UUID,+ input: contracts.AddFeatureRequestAccountInput,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestView | None:+ return _feature_requests_logic.add_feature_request_account(+ team_id=team_id,+ feature_request_id=feature_request_id,+ input=input,+ actor_id=actor_id,+ user_access_control=user_access_control,+ )+++def create_feature_request_evidence(+ *,+ team_id: int,+ feature_request_id: UUID,+ input: contracts.CreateFeatureRequestEvidenceInput,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestView | None:+ return _feature_requests_logic.create_feature_request_evidence(+ team_id=team_id,+ feature_request_id=feature_request_id,+ input=input,+ actor_id=actor_id,+ user_access_control=user_access_control,+ )+++def update_feature_request_evidence(+ *,+ team_id: int,+ feature_request_id: UUID,+ input: contracts.UpdateFeatureRequestEvidenceInput,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestView | None:+ return _feature_requests_logic.update_feature_request_evidence(+ team_id=team_id,+ feature_request_id=feature_request_id,+ input=input,+ actor_id=actor_id,+ user_access_control=user_access_control,+ )+++def delete_feature_request_evidence(+ *,+ team_id: int,+ feature_request_id: UUID,+ input: contracts.DeleteFeatureRequestEvidenceInput,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestView | None:+ return _feature_requests_logic.delete_feature_request_evidence(+ team_id=team_id,+ feature_request_id=feature_request_id,+ input=input,+ actor_id=actor_id,+ user_access_control=user_access_control,+ )++def set_feature_request_archived(*,team_id: int,diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex b2dbb0387dc3..312fdd47b4f6 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -14,7 +14,7 @@ from dataclasses import (dataclass as stdlib_dataclass,field,)-from datetime import datetime+from datetime import date, datetimefrom enum import Enumfrom typing import Any, TypedDictfrom uuid import UUID@@ -571,6 +571,30 @@ class FeatureRequestAccountView:name: str = ""+@stdlib_dataclass(frozen=True)+class FeatureRequestEvidenceView:+ id: UUID | None = None+ summary: str = ""+ customer_quote: str = ""+ evidence_source: str = "conversation"+ source_url: str = ""+ requested_on: date | None = None+ created_by: int | None = None+ updated_by: int | None = None+ created_at: datetime | None = None+ updated_at: datetime | None = None+++@stdlib_dataclass(frozen=True)+class FeatureRequestAccountLinkView:+ id: UUID | None = None+ account: FeatureRequestAccountView | None = None+ evidence: list[FeatureRequestEvidenceView] = field(default_factory=list)+ evidence_count: int = 0+ created_at: datetime | None = None+ updated_at: datetime | None = None++@stdlib_dataclass(frozen=True)class FeatureRequestView:id: UUID | None = None@@ -582,7 +606,9 @@ class FeatureRequestView:archived_at: datetime | None = Nonearchived_by: int | None = Noneversion: int = 1+ can_update: bool = Falseaccount: FeatureRequestAccountView | None = None+ account_links: list[FeatureRequestAccountLinkView] = field(default_factory=list)product_areas: list[FeatureRequestProductAreaView] = field(default_factory=list)created_by: int | None = Noneupdated_by: int | None = None@@ -649,13 +675,57 @@ class UpdateFeatureRequestInput:expected_version: inttitle: str | None = Nonedescription: str | None = None- account_id: UUID | None = None+ account_ids: tuple[UUID, ...] | None = Noneproduct_area_ids: tuple[UUID, ...] | None = Nonerequest_status: str | None = Nonerequest_priority: str | None = Nonerequest_priority_is_set: bool = False+@dataclass(frozen=True)+class FeatureRequestEvidenceInput:+ summary: str+ customer_quote: str+ evidence_source: str+ source_url: str+ requested_on: date | None+++@dataclass(frozen=True)+class AddFeatureRequestAccountInput:+ expected_version: int+ account_id: UUID+ evidence: FeatureRequestEvidenceInput | None = None+++@dataclass(frozen=True)+class CreateFeatureRequestEvidenceInput:+ expected_version: int+ account_link_id: UUID+ summary: str+ customer_quote: str+ evidence_source: str+ source_url: str+ requested_on: date | None+++@dataclass(frozen=True)+class UpdateFeatureRequestEvidenceInput:+ expected_version: int+ evidence_id: UUID+ summary: str+ customer_quote: str+ evidence_source: str+ source_url: str+ requested_on: date | None+++@dataclass(frozen=True)+class DeleteFeatureRequestEvidenceInput:+ expected_version: int+ evidence_id: UUID++@stdlib_dataclass(frozen=True)class CustomerProfileConfigView:"""A customer profile config as returned by the profile-config endpoints.diff --git a/products/customer_analytics/backend/logic/feature_requests.py b/products/customer_analytics/backend/logic/feature_requests.pyindex 79bfae89a9b0..499fd9f9b117 100644--- a/products/customer_analytics/backend/logic/feature_requests.py+++ b/products/customer_analytics/backend/logic/feature_requests.py@@ -1,11 +1,14 @@-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Protocol, cast+from urllib.parse import urlparsefrom uuid import UUID+from django.core.exceptions import PermissionDeniedfrom django.db import IntegrityError, transaction-from django.db.models import Case, IntegerField, Q, QuerySet, Value, When+from django.db.models import Case, Count, IntegerField, Prefetch, Q, QuerySet, Value, Whenfrom django.db.models.functions import Lowerfrom django.utils import timezone+from posthog.dataclasses import frozenfrom posthog.models import Userfrom products.customer_analytics.backend.facade import contracts@@ -13,6 +16,7 @@ from products.customer_analytics.backend.models import (Account,FeatureRequest,FeatureRequestAccountLink,+ FeatureRequestEvidence,FeatureRequestHistory,FeatureRequestHistorySource,FeatureRequestPriority,@@ -24,6 +28,10 @@ if TYPE_CHECKING:from posthog.rbac.user_access_control import UserAccessControl+class _FeatureRequestWithPermissionLinks(Protocol):+ _permission_account_links: list[FeatureRequestAccountLink]++class FeatureRequestValidationError(ValueError):def __init__(self, field: str, message: str) -> None:super().__init__(message)@@ -39,6 +47,14 @@ class FeatureRequestConflictError(ValueError):pass+@frozen+class _ValidatedEvidence:+ summary: str+ customer_quote: str+ source: str+ source_url: str++def _to_product_area_view(product_area: FeatureRequestProductArea) -> contracts.FeatureRequestProductAreaView:return contracts.FeatureRequestProductAreaView(id=product_area.id,@@ -50,8 +66,65 @@ def _to_product_area_view(product_area: FeatureRequestProductArea) -> contracts.)-def _to_feature_request_view(feature_request: FeatureRequest) -> contracts.FeatureRequestView:- account_link = next(iter(feature_request.account_links.all()))+def _to_evidence_view(evidence: FeatureRequestEvidence) -> contracts.FeatureRequestEvidenceView:+ return contracts.FeatureRequestEvidenceView(+ id=evidence.id,+ summary=evidence.summary,+ customer_quote=evidence.customer_quote,+ evidence_source=evidence.source,+ source_url=evidence.source_url,+ requested_on=evidence.requested_on,+ created_by=evidence.created_by_id,+ updated_by=evidence.updated_by_id,+ created_at=evidence.created_at,+ updated_at=evidence.updated_at,+ )+++def _to_account_link_view(+ account_link: FeatureRequestAccountLink, *, include_evidence: bool+) -> contracts.FeatureRequestAccountLinkView:+ evidence = [_to_evidence_view(item) for item in account_link.evidence.all()] if include_evidence else []+ evidence_count = getattr(account_link, "evidence_count", len(evidence))+ return contracts.FeatureRequestAccountLinkView(+ id=account_link.id,+ account=contracts.FeatureRequestAccountView(id=account_link.account.id, name=account_link.account.name),+ evidence=evidence,+ evidence_count=evidence_count,+ created_at=account_link.created_at,+ updated_at=account_link.updated_at,+ )+++def _get_feature_request_can_update(feature_request: FeatureRequest, user_access_control: "UserAccessControl") -> bool:+ account_links = cast(_FeatureRequestWithPermissionLinks, feature_request)._permission_account_links+ return (+ user_access_control.check_access_level_for_resource("customer_analytics", required_level="editor")+ and bool(account_links)+ and all(+ user_access_control.check_access_level_for_object(link.account, required_level="editor")+ for link in account_links+ )+ )+++def _to_feature_request_view(+ feature_request: FeatureRequest,+ *,+ user_access_control: "UserAccessControl",+ include_evidence: bool = True,+) -> contracts.FeatureRequestView:+ account_links = [+ _to_account_link_view(link, include_evidence=include_evidence) for link in feature_request.account_links.all()+ ]+ legacy_account = account_links[0].account if account_links else None+ account_links.sort(+ key=lambda link: (+ -link.evidence_count,+ link.account.name.casefold() if link.account else "",+ str(link.id),+ )+ )return contracts.FeatureRequestView(id=feature_request.id,title=feature_request.title,@@ -62,7 +135,9 @@ def _to_feature_request_view(feature_request: FeatureRequest) -> contracts.Featuarchived_at=feature_request.archived_at,archived_by=feature_request.archived_by_id,version=feature_request.version,- account=contracts.FeatureRequestAccountView(id=account_link.account.id, name=account_link.account.name),+ can_update=_get_feature_request_can_update(feature_request, user_access_control),+ account=legacy_account,+ account_links=account_links,product_areas=[_to_product_area_view(area) for area in feature_request.product_areas.all()],created_by=feature_request.created_by_id,updated_by=feature_request.updated_by_id,@@ -71,16 +146,35 @@ def _to_feature_request_view(feature_request: FeatureRequest) -> contracts.Featu)-def _feature_request_queryset(team_id: int, user_access_control: "UserAccessControl") -> QuerySet[FeatureRequest]:+def _feature_request_queryset(+ team_id: int,+ user_access_control: "UserAccessControl",+ *,+ include_evidence: bool = True,+) -> QuerySet[FeatureRequest]:accessible_account_ids = user_access_control.filter_queryset_by_access_level(Account.objects.for_team(team_id)).values("id")- return (+ visible_links = (+ FeatureRequestAccountLink.objects.for_team(team_id)+ .filter(account_id__in=accessible_account_ids, unlinked_at__isnull=True)+ .select_related("account")+ .annotate(evidence_count=Count("evidence"))+ .order_by("account__name", "id")+ )+ if include_evidence:+ visible_links = visible_links.prefetch_related("evidence")+ permission_links = (+ FeatureRequestAccountLink.objects.for_team(team_id).filter(unlinked_at__isnull=True).select_related("account")+ )+ queryset = (FeatureRequest.objects.for_team(team_id)- .filter(account_links__account_id__in=accessible_account_ids)- .prefetch_related("product_areas", "account_links__account")- .distinct()+ .filter(account_links__account_id__in=accessible_account_ids, account_links__unlinked_at__isnull=True)+ .prefetch_related("product_areas", Prefetch("account_links", queryset=visible_links)))+ return queryset.prefetch_related(+ Prefetch("account_links", queryset=permission_links, to_attr="_permission_account_links")+ ).distinct()def _apply_priority_ordering(queryset: QuerySet[FeatureRequest], ordering: str) -> QuerySet[FeatureRequest]:@@ -118,7 +212,9 @@ def _apply_ordering(queryset: QuerySet[FeatureRequest], ordering: str) -> QuerySdef _apply_filters(- queryset: QuerySet[FeatureRequest], filters: contracts.FeatureRequestListFilters+ queryset: QuerySet[FeatureRequest],+ filters: contracts.FeatureRequestListFilters,+ account_filter_ids: tuple[UUID, ...],) -> QuerySet[FeatureRequest]:search = filters.search.strip()if search:@@ -135,7 +231,10 @@ def _apply_filters(if filters.product_area_ids:queryset = queryset.filter(product_area_links__product_area_id__in=filters.product_area_ids)if filters.account_ids:- queryset = queryset.filter(account_links__account_id__in=filters.account_ids)+ queryset = queryset.filter(+ account_links__account_id__in=account_filter_ids,+ account_links__unlinked_at__isnull=True,+ )if filters.archive_state == "active":queryset = queryset.filter(archived_at__isnull=True)elif filters.archive_state == "archived":@@ -149,17 +248,25 @@ def _get_accessible_feature_request_for_update(feature_request = FeatureRequest.objects.for_team(team_id).select_for_update().filter(id=feature_request_id).first()if feature_request is None:return None- linked_account_ids = set(+ account_links = list(FeatureRequestAccountLink.objects.for_team(team_id)- .filter(feature_request=feature_request)- .values_list("account_id", flat=True)+ .filter(feature_request=feature_request, unlinked_at__isnull=True)+ .select_related("account"))+ linked_account_ids = {link.account_id for link in account_links}accessible_account_ids = set(user_access_control.filter_queryset_by_access_level(Account.objects.for_team(team_id)).filter(id__in=linked_account_ids).values_list("id", flat=True))- return feature_request if linked_account_ids == accessible_account_ids else None+ if linked_account_ids != accessible_account_ids:+ return None+ if any(+ not user_access_control.check_access_level_for_object(link.account, required_level="editor")+ for link in account_links+ ):+ raise PermissionDenied+ return feature_requestdef _get_accessible_account(*, team_id: int, account_id: UUID, user_access_control: "UserAccessControl") -> Account:@@ -170,9 +277,29 @@ def _get_accessible_account(*, team_id: int, account_id: UUID, user_access_contr)if account is None:raise FeatureRequestValidationError("account_id", "Select an account you can access.")+ if not user_access_control.check_access_level_for_object(account, required_level="editor"):+ raise PermissionDeniedreturn account+def _get_accessible_accounts(+ *, team_id: int, account_ids: tuple[UUID, ...], user_access_control: "UserAccessControl"+) -> list[Account]:+ unique_ids = tuple(dict.fromkeys(account_ids))+ if not unique_ids:+ raise FeatureRequestValidationError("account_ids", "Select at least one account.")+ accounts = list(+ user_access_control.filter_queryset_by_access_level(Account.objects.for_team(team_id)).filter(id__in=unique_ids)+ )+ if len(accounts) != len(unique_ids):+ raise FeatureRequestValidationError("account_ids", "Select accounts you can access.")+ if any(+ not user_access_control.check_access_level_for_object(account, required_level="editor") for account in accounts+ ):+ raise PermissionDenied+ return accounts++def _get_valid_product_areas(*, team_id: int, feature_request: FeatureRequest, product_area_ids: tuple[UUID, ...]) -> list[FeatureRequestProductArea]:@@ -196,6 +323,26 @@ def _account_snapshot(account: Account) -> dict[str, str]:return {"id": str(account.id), "name": account.name}+def _account_snapshots(accounts: list[Account]) -> list[dict[str, str]]:+ return [+ _account_snapshot(account)+ for account in sorted(accounts, key=lambda account: (account.name.lower(), str(account.id)))+ ]+++def _evidence_snapshot(evidence: FeatureRequestEvidence, *, account: Account | None = None) -> dict[str, object]:+ evidence_account = account or evidence.account_link.account+ return {+ "id": str(evidence.id),+ "account": _account_snapshot(evidence_account),+ "summary": evidence.summary,+ "customer_quote": evidence.customer_quote,+ "source": evidence.source,+ "source_url": evidence.source_url,+ "requested_on": evidence.requested_on.isoformat() if evidence.requested_on else None,+ }++def _history_account_id(value: object) -> UUID | None:if not isinstance(value, dict) or not isinstance(value.get("id"), str):return None@@ -214,22 +361,49 @@ def _redact_history_account(value: object, accessible_account_ids: set[UUID]) ->return {"id": None, "name": "Restricted account"}+def _filter_history_accounts(value: object, accessible_account_ids: set[UUID]) -> object:+ if not isinstance(value, list):+ return []+ return [item for item in value if _history_account_id(item) in accessible_account_ids]+++def _evidence_history_account_id(value: object) -> UUID | None:+ if not isinstance(value, dict):+ return None+ return _history_account_id(value.get("account"))++def _redact_inaccessible_history_accounts(changes: list[contracts.FeatureRequestHistoryChange], accessible_account_ids: set[UUID]) -> list[contracts.FeatureRequestHistoryChange]:- redacted_changes: list[contracts.FeatureRequestHistoryChange] = []+ visible_changes: list[contracts.FeatureRequestHistoryChange] = []for change in changes:if change["field"] == "account":- redacted_changes.append(+ visible_changes.append(contracts.FeatureRequestHistoryChange(field=change["field"],before=_redact_history_account(change["before"], accessible_account_ids),after=_redact_history_account(change["after"], accessible_account_ids),))+ elif change["field"] == "accounts":+ before = _filter_history_accounts(change["before"], accessible_account_ids)+ after = _filter_history_accounts(change["after"], accessible_account_ids)+ if before != after:+ visible_changes.append(+ contracts.FeatureRequestHistoryChange(+ field=change["field"],+ before=before,+ after=after,+ )+ )+ elif change["field"] == "evidence":+ account_id = _evidence_history_account_id(change["after"]) or _evidence_history_account_id(change["before"])+ if account_id in accessible_account_ids:+ visible_changes.append(change)else:- redacted_changes.append(change)- return redacted_changes+ visible_changes.append(change)+ return visible_changesdef _product_area_snapshots(product_areas: list[FeatureRequestProductArea]) -> list[dict[str, str]]:@@ -242,15 +416,15 @@ def _product_area_snapshots(product_areas: list[FeatureRequestProductArea]) -> ldef _ensure_initial_history(feature_request: FeatureRequest,*,- account: Account | None = None,+ accounts: list[Account] | None = None,product_areas: list[FeatureRequestProductArea] | None = None,) -> None:- if account is None:- account = (- FeatureRequestAccountLink.objects.for_team(feature_request.team_id)- .select_related("account")- .get(feature_request=feature_request)- .account+ if accounts is None:+ accounts = list(+ Account.objects.for_team(feature_request.team_id).filter(+ feature_request_links__feature_request=feature_request,+ feature_request_links__unlinked_at__isnull=True,+ ))if product_areas is None:product_areas = list(@@ -266,7 +440,7 @@ def _ensure_initial_history("changes": [{"field": "status", "before": None, "after": feature_request.status},{"field": "priority", "before": None, "after": feature_request.priority},- {"field": "account", "before": None, "after": _account_snapshot(account)},+ {"field": "accounts", "before": [], "after": _account_snapshots(accounts)},{"field": "product_areas","before": [],@@ -286,7 +460,7 @@ def _refresh_feature_request(refreshed = _feature_request_queryset(team_id, user_access_control).filter(id=feature_request_id).first()if refreshed is None:raise FeatureRequestValidationError("feature_request_id", "This feature request is no longer available.")- return _to_feature_request_view(refreshed)+ return _to_feature_request_view(refreshed, user_access_control=user_access_control)def list_product_areas(@@ -354,17 +528,35 @@ def list_feature_requests(offset: int,limit: int,) -> tuple[list[contracts.FeatureRequestView], int]:- queryset = _apply_filters(_feature_request_queryset(team_id, user_access_control), filters)+ account_filter_ids: tuple[UUID, ...] = ()+ if filters.account_ids:+ account_filter_ids = tuple(+ user_access_control.filter_queryset_by_access_level(Account.objects.for_team(team_id))+ .filter(id__in=filters.account_ids)+ .values_list("id", flat=True)+ )+ queryset = _apply_filters(+ _feature_request_queryset(team_id, user_access_control, include_evidence=False),+ filters,+ account_filter_ids,+ )queryset = _apply_ordering(queryset, filters.ordering)total_count = queryset.count()- return [_to_feature_request_view(item) for item in queryset[offset : offset + limit]], total_count+ return [+ _to_feature_request_view(item, user_access_control=user_access_control, include_evidence=False)+ for item in queryset[offset : offset + limit]+ ], total_countdef get_feature_request(*, team_id: int, feature_request_id: UUID, user_access_control: "UserAccessControl") -> contracts.FeatureRequestView | None:feature_request = _feature_request_queryset(team_id, user_access_control).filter(id=feature_request_id).first()- return _to_feature_request_view(feature_request) if feature_request is not None else None+ return (+ _to_feature_request_view(feature_request, user_access_control=user_access_control)+ if feature_request is not None+ else None+ )def create_feature_request(@@ -387,7 +579,7 @@ def create_feature_request(if accessible_existing is None:raise FeatureRequestValidationError("idempotency_key", "This idempotency key is already in use.")return contracts.FeatureRequestCreateOutcome(- request=_to_feature_request_view(accessible_existing),+ request=_to_feature_request_view(accessible_existing, user_access_control=user_access_control),created=False,)@@ -435,7 +627,7 @@ def create_feature_request()_ensure_initial_history(feature_request,- account=accessible_account,+ accounts=[accessible_account],product_areas=product_areas,)@@ -497,27 +689,43 @@ def update_feature_request(update_fields.add("priority")relations_changed = False- if input.account_id is not None:- account = _get_accessible_account(+ if input.account_ids is not None:+ accounts = _get_accessible_accounts(team_id=team_id,- account_id=input.account_id,+ account_ids=input.account_ids,user_access_control=user_access_control,)- account_link = (+ requested_ids = {account.id for account in accounts}+ active_links = list(FeatureRequestAccountLink.objects.for_team(team_id)+ .filter(feature_request=feature_request, unlinked_at__isnull=True).select_related("account")- .get(feature_request=feature_request))- if account_link.account_id != account.id:+ active_ids = {link.account_id for link in active_links}+ if requested_ids != active_ids:+ changed_at = timezone.now()history_changes.append({- "field": "account",- "before": _account_snapshot(account_link.account),- "after": _account_snapshot(account),+ "field": "accounts",+ "before": _account_snapshots([link.account for link in active_links]),+ "after": _account_snapshots(accounts),})- account_link.account = account- account_link.save(update_fields=["account"])+ FeatureRequestAccountLink.objects.for_team(team_id).filter(+ feature_request=feature_request,+ account_id__in=active_ids - requested_ids,+ ).update(unlinked_at=changed_at, unlinked_by_id=actor_id, updated_at=changed_at)+ for account in accounts:+ link, created = FeatureRequestAccountLink.objects.for_team(team_id).get_or_create(+ team_id=team_id,+ feature_request=feature_request,+ account=account,+ )+ if not created and link.unlinked_at is not None:+ link.unlinked_at = None+ link.unlinked_by_id = None+ link.updated_at = changed_at+ link.save(update_fields=["unlinked_at", "unlinked_by_id", "updated_at"])relations_changed = Trueif input.product_area_ids is not None:@@ -582,6 +790,337 @@ def update_feature_request()+def _validate_evidence(+ input: (+ contracts.FeatureRequestEvidenceInput+ | contracts.CreateFeatureRequestEvidenceInput+ | contracts.UpdateFeatureRequestEvidenceInput+ ),+) -> _ValidatedEvidence:+ summary = input.summary.strip()+ customer_quote = input.customer_quote.strip()+ source_url = input.source_url.strip()+ if not summary and not customer_quote and not source_url:+ raise FeatureRequestValidationError("evidence", "Enter a summary, customer quote, or source URL.")+ if source_url:+ parsed_url = urlparse(source_url)+ if parsed_url.scheme not in {"http", "https"} or not parsed_url.netloc:+ raise FeatureRequestValidationError("source_url", "Enter a valid HTTP or HTTPS URL.")+ if input.requested_on is not None and input.requested_on > timezone.localdate():+ raise FeatureRequestValidationError("requested_on", "The request date cannot be in the future.")+ return _ValidatedEvidence(+ summary=summary,+ customer_quote=customer_quote,+ source=input.evidence_source,+ source_url=source_url,+ )+++def _get_evidence_account_link(+ *,+ team_id: int,+ feature_request_id: UUID,+ account_link_id: UUID,+ expected_version: int,+ user_access_control: "UserAccessControl",+) -> tuple[FeatureRequest, FeatureRequestAccountLink] | None:+ feature_request = FeatureRequest.objects.for_team(team_id).select_for_update().filter(id=feature_request_id).first()+ if feature_request is None:+ return None+ account_link = (+ FeatureRequestAccountLink.objects.for_team(team_id)+ .select_related("account")+ .filter(+ id=account_link_id,+ feature_request=feature_request,+ unlinked_at__isnull=True,+ )+ .first()+ )+ if account_link is None:+ return None+ _get_accessible_account(+ team_id=team_id,+ account_id=account_link.account_id,+ user_access_control=user_access_control,+ )+ if feature_request.archived_at is not None:+ raise FeatureRequestValidationError("feature_request", "Restore this request before editing evidence.")+ if feature_request.version != expected_version:+ raise FeatureRequestConflictError("This request changed since you opened it. Reload it and try again.")+ return feature_request, account_link+++def _record_feature_request_changes(+ *,+ feature_request: FeatureRequest,+ changes: list[contracts.FeatureRequestHistoryChange],+ actor_id: int,+) -> None:+ changed_at = timezone.now()+ feature_request.version += 1+ feature_request.updated_by_id = actor_id+ feature_request.updated_at = changed_at+ feature_request.save(update_fields=["version", "updated_by_id", "updated_at"])+ FeatureRequestHistory.objects.for_team(feature_request.team_id).create(+ team_id=feature_request.team_id,+ feature_request=feature_request,+ changes=changes,+ source=FeatureRequestHistorySource.MANUAL,+ actor_id=actor_id,+ changed_at=changed_at,+ )+++def _record_evidence_change(+ *,+ feature_request: FeatureRequest,+ before: dict[str, object] | None,+ after: dict[str, object] | None,+ actor_id: int,+) -> None:+ _record_feature_request_changes(+ feature_request=feature_request,+ changes=[{"field": "evidence", "before": before, "after": after}],+ actor_id=actor_id,+ )+++def add_feature_request_account(+ *,+ team_id: int,+ feature_request_id: UUID,+ input: contracts.AddFeatureRequestAccountInput,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestView | None:+ evidence_input = input.evidence+ validated_evidence = _validate_evidence(evidence_input) if evidence_input is not None else None+ with transaction.atomic():+ feature_request = _get_accessible_feature_request_for_update(+ team_id=team_id,+ feature_request_id=feature_request_id,+ user_access_control=user_access_control,+ )+ if feature_request is None:+ return None+ if feature_request.archived_at is not None:+ raise FeatureRequestValidationError("feature_request", "Restore this request before adding an account.")+ if feature_request.version != input.expected_version:+ raise FeatureRequestConflictError("This request changed since you opened it. Reload it and try again.")++ account = _get_accessible_account(+ team_id=team_id,+ account_id=input.account_id,+ user_access_control=user_access_control,+ )+ active_links = list(+ FeatureRequestAccountLink.objects.for_team(team_id)+ .filter(feature_request=feature_request, unlinked_at__isnull=True)+ .select_related("account")+ )+ if any(link.account_id == account.id for link in active_links):+ raise FeatureRequestValidationError("account_id", "This account is already linked to the request.")++ _ensure_initial_history(feature_request)+ changed_at = timezone.now()+ account_link, created = FeatureRequestAccountLink.objects.for_team(team_id).get_or_create(+ team_id=team_id,+ feature_request=feature_request,+ account=account,+ )+ if not created:+ account_link.unlinked_at = None+ account_link.unlinked_by_id = None+ account_link.updated_at = changed_at+ account_link.save(update_fields=["unlinked_at", "unlinked_by_id", "updated_at"])++ history_changes: list[contracts.FeatureRequestHistoryChange] = [+ {+ "field": "accounts",+ "before": _account_snapshots([link.account for link in active_links]),+ "after": _account_snapshots([link.account for link in active_links] + [account]),+ }+ ]+ if validated_evidence is not None and evidence_input is not None:+ evidence = FeatureRequestEvidence.objects.for_team(team_id).create(+ team_id=team_id,+ account_link=account_link,+ summary=validated_evidence.summary,+ customer_quote=validated_evidence.customer_quote,+ source=validated_evidence.source,+ source_url=validated_evidence.source_url,+ requested_on=evidence_input.requested_on,+ created_by_id=actor_id,+ updated_by_id=actor_id,+ )+ history_changes.append(+ {+ "field": "evidence",+ "before": None,+ "after": _evidence_snapshot(evidence, account=account),+ }+ )+ _record_feature_request_changes(+ feature_request=feature_request,+ changes=history_changes,+ actor_id=actor_id,+ )++ return _refresh_feature_request(+ team_id=team_id,+ feature_request_id=feature_request_id,+ user_access_control=user_access_control,+ )+++def create_feature_request_evidence(+ *,+ team_id: int,+ feature_request_id: UUID,+ input: contracts.CreateFeatureRequestEvidenceInput,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestView | None:+ validated_evidence = _validate_evidence(input)+ with transaction.atomic():+ result = _get_evidence_account_link(+ team_id=team_id,+ feature_request_id=feature_request_id,+ account_link_id=input.account_link_id,+ expected_version=input.expected_version,+ user_access_control=user_access_control,+ )+ if result is None:+ return None+ feature_request, account_link = result+ evidence = FeatureRequestEvidence.objects.for_team(team_id).create(+ team_id=team_id,+ account_link=account_link,+ summary=validated_evidence.summary,+ customer_quote=validated_evidence.customer_quote,+ source=validated_evidence.source,+ source_url=validated_evidence.source_url,+ requested_on=input.requested_on,+ created_by_id=actor_id,+ updated_by_id=actor_id,+ )+ _record_evidence_change(+ feature_request=feature_request,+ before=None,+ after=_evidence_snapshot(evidence, account=account_link.account),+ actor_id=actor_id,+ )+ return _refresh_feature_request(+ team_id=team_id,+ feature_request_id=feature_request_id,+ user_access_control=user_access_control,+ )+++def update_feature_request_evidence(+ *,+ team_id: int,+ feature_request_id: UUID,+ input: contracts.UpdateFeatureRequestEvidenceInput,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestView | None:+ validated_evidence = _validate_evidence(input)+ with transaction.atomic():+ evidence = (+ FeatureRequestEvidence.objects.for_team(team_id)+ .select_related("account_link__account")+ .filter(id=input.evidence_id, account_link__feature_request_id=feature_request_id)+ .first()+ )+ if evidence is None:+ return None+ result = _get_evidence_account_link(+ team_id=team_id,+ feature_request_id=feature_request_id,+ account_link_id=evidence.account_link_id,+ expected_version=input.expected_version,+ user_access_control=user_access_control,+ )+ if result is None:+ return None+ feature_request, account_link = result+ before = _evidence_snapshot(evidence, account=account_link.account)+ evidence.summary = validated_evidence.summary+ evidence.customer_quote = validated_evidence.customer_quote+ evidence.source = validated_evidence.source+ evidence.source_url = validated_evidence.source_url+ evidence.requested_on = input.requested_on+ after = _evidence_snapshot(evidence, account=account_link.account)+ if before != after:+ evidence.updated_by_id = actor_id+ evidence.save(+ update_fields=[+ "summary",+ "customer_quote",+ "source",+ "source_url",+ "requested_on",+ "updated_by_id",+ "updated_at",+ ]+ )+ _record_evidence_change(+ feature_request=feature_request,+ before=before,+ after=after,+ actor_id=actor_id,+ )+ return _refresh_feature_request(+ team_id=team_id,+ feature_request_id=feature_request_id,+ user_access_control=user_access_control,+ )+++def delete_feature_request_evidence(+ *,+ team_id: int,+ feature_request_id: UUID,+ input: contracts.DeleteFeatureRequestEvidenceInput,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestView | None:+ with transaction.atomic():+ evidence = (+ FeatureRequestEvidence.objects.for_team(team_id)+ .select_related("account_link__account")+ .filter(id=input.evidence_id, account_link__feature_request_id=feature_request_id)+ .first()+ )+ if evidence is None:+ return None+ result = _get_evidence_account_link(+ team_id=team_id,+ feature_request_id=feature_request_id,+ account_link_id=evidence.account_link_id,+ expected_version=input.expected_version,+ user_access_control=user_access_control,+ )+ if result is None:+ return None+ feature_request, account_link = result+ before = _evidence_snapshot(evidence, account=account_link.account)+ evidence.delete()+ _record_evidence_change(+ feature_request=feature_request,+ before=before,+ after=None,+ actor_id=actor_id,+ )+ return _refresh_feature_request(+ team_id=team_id,+ feature_request_id=feature_request_id,+ user_access_control=user_access_control,+ )++def set_feature_request_archived(*,team_id: int,@@ -633,12 +1172,17 @@ def list_feature_request_history(history_account_ids: set[UUID] = set()for entry in history:for change in entry.changes:- if change.get("field") != "account":- continue+ field = change.get("field")for value in (change.get("before"), change.get("after")):- account_id = _history_account_id(value)- if account_id is not None:- history_account_ids.add(account_id)+ if field == "account":+ account_ids = [_history_account_id(value)]+ elif field == "accounts" and isinstance(value, list):+ account_ids = [_history_account_id(item) for item in value]+ elif field == "evidence":+ account_ids = [_evidence_history_account_id(value)]+ else:+ account_ids = []+ history_account_ids.update(account_id for account_id in account_ids if account_id is not None)accessible_account_ids = set(user_access_control.filter_queryset_by_access_level(Account.objects.for_team(team_id)).filter(id__in=history_account_ids)@@ -646,18 +1190,23 @@ def list_feature_request_history()actors = User.objects.filter(id__in={entry.actor_id for entry in history if entry.actor_id is not None})actor_names = {actor.id: actor.get_full_name().strip() or actor.email for actor in actors}- return [- contracts.FeatureRequestHistoryView(- id=entry.id,- changes=_redact_inaccessible_history_accounts(entry.changes, accessible_account_ids),- is_initial=entry.is_initial,- change_source=entry.source,- actor_id=entry.actor_id,- actor_name=actor_names.get(entry.actor_id),- changed_at=entry.changed_at,+ visible_history: list[contracts.FeatureRequestHistoryView] = []+ for entry in history:+ visible_changes = _redact_inaccessible_history_accounts(entry.changes, accessible_account_ids)+ if not visible_changes:+ continue+ visible_history.append(+ contracts.FeatureRequestHistoryView(+ id=entry.id,+ changes=visible_changes,+ is_initial=entry.is_initial,+ change_source=entry.source,+ actor_id=entry.actor_id,+ actor_name=actor_names.get(entry.actor_id),+ changed_at=entry.changed_at,+ ))- for entry in history- ]+ return visible_historydef list_feature_request_status_history(diff --git a/products/customer_analytics/backend/migrations/0038_feature_request_multi_account_evidence.py b/products/customer_analytics/backend/migrations/0038_feature_request_multi_account_evidence.pynew file mode 100644index 000000000000..4f33e1ebb9bf--- /dev/null+++ b/products/customer_analytics/backend/migrations/0038_feature_request_multi_account_evidence.py@@ -0,0 +1,117 @@+# Generated by Django 5.2.17 on 2026-08-17 19:53++import django.db.models.deletion+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("customer_analytics", "0037_account_ignored_at"),+ ("posthog", "1304_organization_has_active_subscription"),+ ]++ operations = [+ migrations.CreateModel(+ name="FeatureRequestEvidence",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "account_link",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="evidence",+ to="customer_analytics.featurerequestaccountlink",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ ("summary", models.TextField(blank=True, default="")),+ ("customer_quote", models.TextField(blank=True, default="")),+ ("source", models.CharField(max_length=200)),+ (+ "source_url",+ models.URLField(blank=True, default="", max_length=2000),+ ),+ ("requested_on", models.DateField(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="posthog.user",+ ),+ ),+ (+ "updated_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ db_index=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to="posthog.user",+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ ],+ options={+ "ordering": [models.F("requested_on").desc(nulls_last=True), "-created_at", "-id"],+ },+ ),+ migrations.AddField(+ model_name="featurerequestaccountlink",+ name="unlinked_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="featurerequestaccountlink",+ name="unlinked_by",+ field=models.ForeignKey(+ blank=True,+ db_constraint=False,+ db_index=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to="posthog.user",+ ),+ ),+ migrations.SeparateDatabaseAndState(+ database_operations=[+ migrations.AddField(+ model_name="featurerequestaccountlink",+ name="updated_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ],+ state_operations=[+ migrations.AddField(+ model_name="featurerequestaccountlink",+ name="updated_at",+ field=models.DateTimeField(auto_now=True, blank=True, null=True),+ ),+ ],+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txtindex 9d1d6d897dba..ae0f1270a652 100644--- a/products/customer_analytics/backend/migrations/max_migration.txt+++ b/products/customer_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0037_account_ignored_at+0038_feature_request_multi_account_evidencediff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.pyindex 0e930c832b36..47323d619f3a 100644--- a/products/customer_analytics/backend/models/__init__.py+++ b/products/customer_analytics/backend/models/__init__.py@@ -20,6 +20,7 @@ from .event_stream import EventStream, EventStreamMemberfrom .feature_request import (FeatureRequest,FeatureRequestAccountLink,+ FeatureRequestEvidence,FeatureRequestHistory,FeatureRequestHistorySource,FeatureRequestPriority,@@ -53,6 +54,7 @@ __all__ = ["EventStreamMember","FeatureRequest","FeatureRequestAccountLink",+ "FeatureRequestEvidence","FeatureRequestHistory","FeatureRequestHistorySource","FeatureRequestPriority",diff --git a/products/customer_analytics/backend/models/feature_request.py b/products/customer_analytics/backend/models/feature_request.pyindex 3c36a803aaca..3ebfc627c1dc 100644--- a/products/customer_analytics/backend/models/feature_request.py+++ b/products/customer_analytics/backend/models/feature_request.py@@ -119,7 +119,18 @@ class FeatureRequestAccountLink(TeamScopedRootMixin, UUIDModel):on_delete=models.CASCADE,related_name="feature_request_links",)+ unlinked_at = models.DateTimeField(null=True, blank=True)+ unlinked_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, null=True, blank=True)class Meta:constraints = [@@ -130,6 +141,43 @@ class FeatureRequestAccountLink(TeamScopedRootMixin, UUIDModel):]+class FeatureRequestEvidence(TeamScopedRootMixin, UUIDModel):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ account_link = models.ForeignKey(+ FeatureRequestAccountLink,+ on_delete=models.CASCADE,+ related_name="evidence",+ )+ summary = models.TextField(blank=True, default="")+ customer_quote = models.TextField(blank=True, default="")+ source = models.CharField(max_length=200)+ source_url = models.URLField(max_length=2000, blank=True, default="")+ requested_on = models.DateField(null=True, blank=True)+ created_by = models.ForeignKey(+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ db_constraint=False,+ db_index=False,+ related_name="+",+ )+ updated_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)++ class Meta:+ ordering = [models.F("requested_on").desc(nulls_last=True), "-created_at", "-id"]++class FeatureRequestProductAreaLink(TeamScopedRootMixin, UUIDModel):team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)feature_request = models.ForeignKey(diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex c7071c05ae69..07f413cc1864 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -57,7 +57,9 @@ from products.customer_analytics.backend.facade.contracts import (CustomPropertySourceView,CustomPropertySyncRunView,EventStreamView,+ FeatureRequestAccountLinkView,FeatureRequestAccountView,+ FeatureRequestEvidenceView,FeatureRequestHistoryView,FeatureRequestProductAreaView,FeatureRequestStatusHistoryView,@@ -172,6 +174,73 @@ class FeatureRequestAccountSerializer(DataclassSerializer):fields = ["id", "name"]+class FeatureRequestEvidenceSerializer(DataclassSerializer):+ id = serializers.UUIDField(read_only=True, help_text="Stable evidence ID.")+ summary = serializers.CharField(read_only=True, help_text="Internal summary of this account's request evidence.")+ customer_quote = serializers.CharField(read_only=True, help_text="Customer quote kept with this evidence item.")+ evidence_source = serializers.CharField(+ read_only=True,+ max_length=200,+ help_text="Free-form name of the source where this evidence was recorded.",+ )+ source_url = serializers.URLField(read_only=True, help_text="HTTP or HTTPS link to the source, or an empty string.")+ requested_on = serializers.DateField(+ read_only=True,+ allow_null=True,+ help_text="Date the account made the request, or null when unknown.",+ )+ created_by = serializers.IntegerField(+ read_only=True, allow_null=True, help_text="ID of the user who added the evidence."+ )+ updated_by = serializers.IntegerField(+ read_only=True, allow_null=True, help_text="ID of the last user to update the evidence."+ )+ created_at = serializers.DateTimeField(read_only=True, help_text="When the evidence was added.")+ updated_at = serializers.DateTimeField(read_only=True, help_text="When the evidence was last updated.")++ class Meta:+ dataclass = FeatureRequestEvidenceView+ ref_name = "FeatureRequestEvidence"+ fields = [+ "id",+ "summary",+ "customer_quote",+ "evidence_source",+ "source_url",+ "requested_on",+ "created_by",+ "updated_by",+ "created_at",+ "updated_at",+ ]+++class FeatureRequestAccountLinkSerializer(DataclassSerializer):+ id = serializers.UUIDField(read_only=True, help_text="Stable link ID between the request and account.")+ account = FeatureRequestAccountSerializer(read_only=True, help_text="Affected Customer Analytics account.")+ evidence = FeatureRequestEvidenceSerializer(+ many=True,+ read_only=True,+ help_text="Evidence recorded for this account and request. List responses omit these items.",+ )+ evidence_count = serializers.IntegerField(+ read_only=True,+ min_value=0,+ help_text="Total evidence items recorded for this account and request.",+ )+ created_at = serializers.DateTimeField(read_only=True, help_text="When the account was first linked.")+ updated_at = serializers.DateTimeField(+ read_only=True,+ allow_null=True,+ help_text="When the account link was last changed.",+ )++ class Meta:+ dataclass = FeatureRequestAccountLinkView+ ref_name = "FeatureRequestAccountLink"+ fields = ["id", "account", "evidence", "evidence_count", "created_at", "updated_at"]++class FeatureRequestSerializer(DataclassSerializer):id = serializers.UUIDField(read_only=True, help_text="Stable feature request ID.")title = serializers.CharField(read_only=True, help_text="Customer-facing request title.")@@ -203,7 +272,19 @@ class FeatureRequestSerializer(DataclassSerializer):min_value=1,help_text="Version required for optimistic concurrency on mutations.",)- account = FeatureRequestAccountSerializer(read_only=True, help_text="Affected account in the first release.")+ can_update = serializers.BooleanField(+ read_only=True,+ help_text="Whether the caller can update this request and all its active account links.",+ )+ account = FeatureRequestAccountSerializer(+ read_only=True,+ help_text="First visible account retained for client compatibility. Use account_links for the complete list.",+ )+ account_links = FeatureRequestAccountLinkSerializer(+ many=True,+ read_only=True,+ help_text="Active account links visible to the caller, with account-specific evidence.",+ )product_areas = FeatureRequestProductAreaSerializer(many=True,read_only=True,@@ -231,7 +312,9 @@ class FeatureRequestSerializer(DataclassSerializer):"archived_at","archived_by","version",+ "can_update","account",+ "account_links","product_areas","created_by","updated_by",@@ -263,6 +346,34 @@ _FEATURE_REQUEST_HISTORY_VALUE_SCHEMA = {},},},+ {+ "type": "object",+ "required": [+ "id",+ "account",+ "summary",+ "customer_quote",+ "source",+ "source_url",+ "requested_on",+ ],+ "properties": {+ "id": {"type": "string", "format": "uuid"},+ "account": {+ "type": "object",+ "required": ["id", "name"],+ "properties": {+ "id": {"type": "string", "format": "uuid"},+ "name": {"type": "string"},+ },+ },+ "summary": {"type": "string"},+ "customer_quote": {"type": "string"},+ "source": {"type": "string"},+ "source_url": {"type": "string"},+ "requested_on": {"type": "string", "format": "date", "nullable": True},+ },+ },],}@@ -279,6 +390,8 @@ class FeatureRequestHistoryChangeSerializer(serializers.Serializer):("status", "Status"),("priority", "Priority"),("account", "Account"),+ ("accounts", "Accounts"),+ ("evidence", "Evidence"),("product_areas", "Product areas"),],help_text="Request field represented by this change.",@@ -469,7 +582,16 @@ class FeatureRequestUpdateSerializer(serializers.Serializer):trim_whitespace=True,help_text="Updated optional customer-facing request description in Markdown.",)- account_id = serializers.UUIDField(required=False, help_text="Updated affected Customer Analytics account ID.")+ account_id = serializers.UUIDField(+ required=False,+ help_text="Deprecated single affected account ID. Use account_ids.",+ )+ account_ids = serializers.ListField(+ required=False,+ child=serializers.UUIDField(),+ allow_empty=False,+ help_text="One or more affected account IDs. Removed accounts are unlinked without deleting their evidence.",+ )product_area_ids = serializers.ListField(required=False,child=serializers.UUIDField(),@@ -489,6 +611,76 @@ class FeatureRequestUpdateSerializer(serializers.Serializer):)+class FeatureRequestEvidencePayloadSerializer(serializers.Serializer):+ summary = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ trim_whitespace=True,+ help_text="Internal summary of this account's request evidence.",+ )+ customer_quote = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ trim_whitespace=True,+ help_text="Customer quote kept with this evidence item.",+ )+ evidence_source = serializers.CharField(+ max_length=200,+ help_text="Free-form name of the source where this evidence was recorded.",+ )+ source_url = serializers.URLField(+ required=False,+ allow_blank=True,+ default="",+ max_length=2000,+ help_text="Optional HTTP or HTTPS link to the source.",+ )+ requested_on = serializers.DateField(+ required=False,+ allow_null=True,+ default=None,+ help_text="Date the account made the request, or null when unknown.",+ )+++class FeatureRequestEvidenceWriteSerializer(FeatureRequestEvidencePayloadSerializer):+ expected_version = serializers.IntegerField(+ min_value=1,+ help_text="Request version loaded by the editor. Stale versions return 409 Conflict.",+ )+++class FeatureRequestAddAccountSerializer(serializers.Serializer):+ expected_version = serializers.IntegerField(+ min_value=1,+ help_text="Request version loaded by the editor. Stale versions return 409 Conflict.",+ )+ account_id = serializers.UUIDField(help_text="Accessible account to link to this feature request.")+ evidence = FeatureRequestEvidencePayloadSerializer(+ required=False,+ allow_null=True,+ help_text="Optional first evidence item to create for the account in the same change.",+ )+++class FeatureRequestEvidenceCreateSerializer(FeatureRequestEvidenceWriteSerializer):+ account_link_id = serializers.UUIDField(help_text="Active account link that owns this evidence.")+++class FeatureRequestEvidenceUpdateSerializer(FeatureRequestEvidenceWriteSerializer):+ evidence_id = serializers.UUIDField(help_text="Evidence item to replace.")+++class FeatureRequestEvidenceDeleteSerializer(serializers.Serializer):+ expected_version = serializers.IntegerField(+ min_value=1,+ help_text="Request version loaded by the editor. Stale versions return 409 Conflict.",+ )+ evidence_id = serializers.UUIDField(help_text="Evidence item to delete.")++class FeatureRequestVersionSerializer(serializers.Serializer):expected_version = serializers.IntegerField(min_value=1,diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 6df68a9ab2e5..126d223ee566 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -76,7 +76,11 @@ from products.customer_analytics.backend.presentation.views.serializers import (EventStreamMemberWriteSerializer,EventStreamSerializer,EventStreamTestMessageSerializer,+ FeatureRequestAddAccountSerializer,FeatureRequestCreateSerializer,+ FeatureRequestEvidenceCreateSerializer,+ FeatureRequestEvidenceDeleteSerializer,+ FeatureRequestEvidenceUpdateSerializer,FeatureRequestHistorySerializer,FeatureRequestListQuerySerializer,FeatureRequestProductAreaListQuerySerializer,@@ -384,7 +388,11 @@ class FeatureRequestViewSet(expected_version=data["expected_version"],title=data.get("title"),description=data.get("description"),- account_id=data.get("account_id"),+ account_ids=(+ tuple(data["account_ids"])+ if "account_ids" in request.data+ else ((data["account_id"],) if "account_id" in request.data else None)+ ),product_area_ids=(tuple(data["product_area_ids"]) if "product_area_ids" in request.data else None),request_status=data.get("request_status"),request_priority=data.get("request_priority"),@@ -405,6 +413,129 @@ class FeatureRequestViewSet(def partial_update(self, request: Request, *args, **kwargs) -> Response:return self.update(request, *args, **kwargs)+ @extend_schema(request=FeatureRequestAddAccountSerializer, responses={200: FeatureRequestSerializer})+ @action(methods=["POST"], detail=True)+ def add_account(self, request: Request, *args, **kwargs) -> Response:+ serializer = FeatureRequestAddAccountSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data+ evidence_data = data.get("evidence")+ evidence = (+ contracts.FeatureRequestEvidenceInput(+ summary=evidence_data["summary"],+ customer_quote=evidence_data["customer_quote"],+ evidence_source=evidence_data["evidence_source"],+ source_url=evidence_data["source_url"],+ requested_on=evidence_data["requested_on"],+ )+ if evidence_data is not None+ else None+ )+ try:+ feature_request = api.add_feature_request_account(+ team_id=self.team_id,+ feature_request_id=self.kwargs["pk"],+ input=contracts.AddFeatureRequestAccountInput(+ expected_version=data["expected_version"],+ account_id=data["account_id"],+ evidence=evidence,+ ),+ actor_id=cast(User, request.user).id,+ user_access_control=self.user_access_control,+ )+ except api.FeatureRequestValidationError as error:+ raise ValidationError({error.field: error.message})+ except api.FeatureRequestConflictError as error:+ raise Conflict(str(error))+ if feature_request is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(FeatureRequestSerializer(instance=feature_request).data)++ @extend_schema(request=FeatureRequestEvidenceCreateSerializer, responses={200: FeatureRequestSerializer})+ @action(methods=["POST"], detail=True)+ def add_evidence(self, request: Request, *args, **kwargs) -> Response:+ serializer = FeatureRequestEvidenceCreateSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data+ try:+ feature_request = api.create_feature_request_evidence(+ team_id=self.team_id,+ feature_request_id=self.kwargs["pk"],+ input=contracts.CreateFeatureRequestEvidenceInput(+ expected_version=data["expected_version"],+ account_link_id=data["account_link_id"],+ summary=data["summary"],+ customer_quote=data["customer_quote"],+ evidence_source=data["evidence_source"],+ source_url=data["source_url"],+ requested_on=data["requested_on"],+ ),+ actor_id=cast(User, request.user).id,+ user_access_control=self.user_access_control,+ )+ except api.FeatureRequestValidationError as error:+ raise ValidationError({error.field: error.message})+ except api.FeatureRequestConflictError as error:+ raise Conflict(str(error))+ if feature_request is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(FeatureRequestSerializer(instance=feature_request).data)++ @extend_schema(request=FeatureRequestEvidenceUpdateSerializer, responses={200: FeatureRequestSerializer})+ @action(methods=["POST"], detail=True)+ def update_evidence(self, request: Request, *args, **kwargs) -> Response:+ serializer = FeatureRequestEvidenceUpdateSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data+ try:+ feature_request = api.update_feature_request_evidence(+ team_id=self.team_id,+ feature_request_id=self.kwargs["pk"],+ input=contracts.UpdateFeatureRequestEvidenceInput(+ expected_version=data["expected_version"],+ evidence_id=data["evidence_id"],+ summary=data["summary"],+ customer_quote=data["customer_quote"],+ evidence_source=data["evidence_source"],+ source_url=data["source_url"],+ requested_on=data["requested_on"],+ ),+ actor_id=cast(User, request.user).id,+ user_access_control=self.user_access_control,+ )+ except api.FeatureRequestValidationError as error:+ raise ValidationError({error.field: error.message})+ except api.FeatureRequestConflictError as error:+ raise Conflict(str(error))+ if feature_request is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(FeatureRequestSerializer(instance=feature_request).data)++ @extend_schema(request=FeatureRequestEvidenceDeleteSerializer, responses={200: FeatureRequestSerializer})+ @action(methods=["POST"], detail=True)+ def remove_evidence(self, request: Request, *args, **kwargs) -> Response:+ serializer = FeatureRequestEvidenceDeleteSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data+ try:+ feature_request = api.delete_feature_request_evidence(+ team_id=self.team_id,+ feature_request_id=self.kwargs["pk"],+ input=contracts.DeleteFeatureRequestEvidenceInput(+ expected_version=data["expected_version"],+ evidence_id=data["evidence_id"],+ ),+ actor_id=cast(User, request.user).id,+ user_access_control=self.user_access_control,+ )+ except api.FeatureRequestValidationError as error:+ raise ValidationError({error.field: error.message})+ except api.FeatureRequestConflictError as error:+ raise Conflict(str(error))+ if feature_request is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(FeatureRequestSerializer(instance=feature_request).data)+def _set_archived(self, request: Request, *, archived: bool) -> Response:serializer = FeatureRequestVersionSerializer(data=request.data)serializer.is_valid(raise_exception=True)diff --git a/products/customer_analytics/backend/test/test_feature_requests.py b/products/customer_analytics/backend/test/test_feature_requests.pyindex 5aafe83b2376..c7d2df06b258 100644--- a/products/customer_analytics/backend/test/test_feature_requests.py+++ b/products/customer_analytics/backend/test/test_feature_requests.py@@ -1,3 +1,5 @@+from datetime import date+from typing import TypedDict, castfrom uuid import uuid4from posthog.test.base import APIBaseTest@@ -9,12 +11,35 @@ from posthog.models import OrganizationMembership, Team, Userfrom posthog.models.organization import AvailableFeaturefrom posthog.models.scoping import team_scope-from products.customer_analytics.backend.models import FeatureRequest, FeatureRequestHistory, FeatureRequestProductArea+from products.customer_analytics.backend.models import (+ FeatureRequest,+ FeatureRequestAccountLink,+ FeatureRequestEvidence,+ FeatureRequestHistory,+ FeatureRequestProductArea,+)from products.customer_analytics.backend.test.factories import create_accountfrom ee.models.rbac.access_control import AccessControl+class _EvidenceResponse(TypedDict):+ id: str+ summary: str+++class _AccountLinkResponse(TypedDict):+ id: str+ evidence: list[_EvidenceResponse]+ evidence_count: int+++class _FeatureRequestResponse(TypedDict):+ id: str+ version: int+ account_links: list[_AccountLinkResponse]++class TestFeatureRequestsAPI(APIBaseTest):def setUp(self) -> None:super().setUp()@@ -63,6 +88,31 @@ class TestFeatureRequestsAPI(APIBaseTest):organization_member=membership,)+ def _add_evidence(+ self,+ *,+ request_id: str,+ version: int,+ account_link_id: str,+ summary: str,+ customer_quote: str = "",+ ) -> _FeatureRequestResponse:+ response = self.client.post(+ f"{self.requests_url}{request_id}/add_evidence/",+ {+ "expected_version": version,+ "account_link_id": account_link_id,+ "summary": summary,+ "customer_quote": customer_quote,+ "evidence_source": "conversation",+ "source_url": "",+ "requested_on": date.today().isoformat(),+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ return cast(_FeatureRequestResponse, response.json())+def test_editor_can_create_and_view_a_request_with_multiple_product_areas_idempotently(self) -> None:payload = self._payload()@@ -76,8 +126,10 @@ class TestFeatureRequestsAPI(APIBaseTest):self.assertEqual(repeated.json()["id"], created.json()["id"])self.assertEqual(listed.status_code, status.HTTP_200_OK)self.assertEqual(listed.json()["count"], 1)+ self.assertTrue(listed.json()["results"][0]["can_update"])self.assertEqual(retrieved.status_code, status.HTTP_200_OK)- self.assertEqual(retrieved.json()["account"]["name"], "Acme")+ self.assertTrue(retrieved.json()["can_update"])+ self.assertEqual(retrieved.json()["account_links"][0]["account"]["name"], "Acme")self.assertEqual({area["name"] for area in retrieved.json()["product_areas"]},{"Product analytics", "Session replay"},@@ -172,12 +224,105 @@ class TestFeatureRequestsAPI(APIBaseTest):{"expected_version": created["version"]},format="json",)+ evidence_attempt = self.client.post(+ f"{self.requests_url}{created['id']}/add_evidence/",+ {+ "expected_version": created["version"],+ "account_link_id": created["account_links"][0]["id"],+ "summary": "Viewer must not add this.",+ "evidence_source": "conversation",+ },+ format="json",+ )self.assertEqual(listed.status_code, status.HTTP_200_OK)self.assertEqual(retrieved.status_code, status.HTTP_200_OK)+ self.assertFalse(retrieved.json()["can_update"])self.assertEqual(create_attempt.status_code, status.HTTP_403_FORBIDDEN)self.assertEqual(update_attempt.status_code, status.HTTP_403_FORBIDDEN)self.assertEqual(archive_attempt.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(evidence_attempt.status_code, status.HTTP_403_FORBIDDEN)++ def test_account_viewer_cannot_mutate_request_or_evidence_as_customer_analytics_editor(self) -> None:+ created = self.client.post(self.requests_url, self._payload(), format="json").json()+ with_evidence = self._add_evidence(+ request_id=created["id"],+ version=created["version"],+ account_link_id=created["account_links"][0]["id"],+ summary="Original evidence",+ )+ evidence_id = with_evidence["account_links"][0]["evidence"][0]["id"]+ other_account = create_account(team_id=self.team.id, name="Globex")+ account_viewer = User.objects.create_and_join(+ self.organization,+ "[email protected]",+ "testtest",+ )+ self._set_access_level(account_viewer, "editor")+ membership = OrganizationMembership.objects.get(user=account_viewer, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="account",+ resource_id=str(self.account.id),+ access_level="viewer",+ organization_member=membership,+ )+ self.client.force_login(account_viewer)++ update_attempt = self.client.patch(+ f"{self.requests_url}{created['id']}/",+ {"expected_version": with_evidence["version"], "request_status": "planned"},+ format="json",+ )+ add_account_attempt = self.client.post(+ f"{self.requests_url}{created['id']}/add_account/",+ {+ "expected_version": with_evidence["version"],+ "account_id": str(other_account.id),+ },+ format="json",+ )+ add_evidence_attempt = self.client.post(+ f"{self.requests_url}{created['id']}/add_evidence/",+ {+ "expected_version": with_evidence["version"],+ "account_link_id": created["account_links"][0]["id"],+ "summary": "Unauthorized evidence",+ "evidence_source": "conversation",+ },+ format="json",+ )+ update_evidence_attempt = self.client.post(+ f"{self.requests_url}{created['id']}/update_evidence/",+ {+ "expected_version": with_evidence["version"],+ "evidence_id": evidence_id,+ "summary": "Unauthorized update",+ "evidence_source": "conversation",+ },+ format="json",+ )+ remove_evidence_attempt = self.client.post(+ f"{self.requests_url}{created['id']}/remove_evidence/",+ {"expected_version": with_evidence["version"], "evidence_id": evidence_id},+ format="json",+ )++ self.assertEqual(+ [+ response.status_code+ for response in (+ update_attempt,+ add_account_attempt,+ add_evidence_attempt,+ update_evidence_attempt,+ remove_evidence_attempt,+ )+ ],+ [status.HTTP_403_FORBIDDEN] * 5,+ )+ evidence = FeatureRequestEvidence.objects.for_team(self.team.id).get(id=evidence_id)+ self.assertEqual(evidence.summary, "Original evidence")def test_editor_groups_tracked_changes_once_and_stale_writes_fail(self) -> None:created = self.client.post(self.requests_url, self._payload(), format="json").json()@@ -196,7 +341,7 @@ class TestFeatureRequestsAPI(APIBaseTest):"title": "Export account retention data","request_status": "planned","request_priority": "high",- "account_id": str(other_account.id),+ "account_ids": [str(other_account.id)],"product_area_ids": [str(self.area_two.id), str(area_three.id)],},format="json",@@ -234,7 +379,7 @@ class TestFeatureRequestsAPI(APIBaseTest):["status","priority",- "account",+ "accounts","product_areas",],)@@ -244,9 +389,9 @@ class TestFeatureRequestsAPI(APIBaseTest):{"field": "status", "before": "requested", "after": "planned"},{"field": "priority", "before": None, "after": "high"},{- "field": "account",- "before": {"id": str(self.account.id), "name": "Acme"},- "after": {"id": str(other_account.id), "name": "Globex"},+ "field": "accounts",+ "before": [{"id": str(self.account.id), "name": "Acme"}],+ "after": [{"id": str(other_account.id), "name": "Globex"}],},{"field": "product_areas",@@ -264,7 +409,7 @@ class TestFeatureRequestsAPI(APIBaseTest):self.assertTrue(history.json()[1]["is_initial"])self.assertEqual([change["field"] for change in history.json()[1]["changes"]],- ["status", "priority", "account", "product_areas"],+ ["status", "priority", "accounts", "product_areas"],)self.assertEqual([(entry["previous_status"], entry["request_status"]) for entry in status_history.json()],@@ -294,11 +439,11 @@ class TestFeatureRequestsAPI(APIBaseTest):history = self.client.get(f"{self.requests_url}{created['id']}/history/").json()changes = {change["field"]: change for change in history[0]["changes"]}- self.assertEqual(changes["account"]["before"]["name"], "Acme")- self.assertEqual(changes["account"]["after"]["name"], "Globex")+ self.assertEqual(changes["accounts"]["before"][0]["name"], "Acme")+ self.assertEqual(changes["accounts"]["after"][0]["name"], "Globex")self.assertEqual(changes["product_areas"]["before"][0]["name"], "Product analytics")initial_changes = {change["field"]: change for change in history[1]["changes"]}- self.assertEqual(initial_changes["account"]["after"]["name"], "Acme")+ self.assertEqual(initial_changes["accounts"]["after"][0]["name"], "Acme")self.assertEqual(initial_changes["product_areas"]["after"][0]["name"], "Product analytics")def test_history_redacts_snapshots_for_accounts_the_viewer_cannot_access(self) -> None:@@ -308,7 +453,7 @@ class TestFeatureRequestsAPI(APIBaseTest):f"{self.requests_url}{created['id']}/",{"expected_version": created["version"],- "account_id": str(other_account.id),+ "account_ids": [str(other_account.id)],},format="json",)@@ -332,16 +477,257 @@ class TestFeatureRequestsAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)updated_changes = {change["field"]: change for change in response.json()[0]["changes"]}- self.assertEqual(updated_changes["account"]["before"], {"id": None, "name": "Restricted account"})+ self.assertEqual(updated_changes["accounts"]["before"], [])self.assertEqual(- updated_changes["account"]["after"],- {"id": str(other_account.id), "name": "Globex"},+ updated_changes["accounts"]["after"],+ [{"id": str(other_account.id), "name": "Globex"}],)initial_changes = {change["field"]: change for change in response.json()[1]["changes"]}- self.assertEqual(initial_changes["account"]["after"], {"id": None, "name": "Restricted account"})+ self.assertNotIn("accounts", initial_changes)self.assertNotIn(str(self.account.id), str(response.json()))self.assertNotIn("Acme", str(response.json()))+ def test_multiple_accounts_keep_separate_evidence_across_unlink_and_relink(self) -> None:+ created = self.client.post(self.requests_url, self._payload(), format="json").json()+ other_account = create_account(team_id=self.team.id, name="Aardvark")+ request_url = f"{self.requests_url}{created['id']}/"+ linked = self.client.patch(+ request_url,+ {+ "expected_version": created["version"],+ "account_ids": [str(self.account.id), str(other_account.id)],+ },+ format="json",+ ).json()+ links_by_account_id = {link["account"]["id"]: link for link in linked["account_links"]}++ with_acme_evidence = self._add_evidence(+ request_id=created["id"],+ version=linked["version"],+ account_link_id=links_by_account_id[str(self.account.id)]["id"],+ summary="Acme needs monthly exports.",+ )+ with_second_acme_evidence = self._add_evidence(+ request_id=created["id"],+ version=with_acme_evidence["version"],+ account_link_id=links_by_account_id[str(self.account.id)]["id"],+ summary="Acme repeated the request during renewal.",+ )+ with_other_evidence = self._add_evidence(+ request_id=created["id"],+ version=with_second_acme_evidence["version"],+ account_link_id=links_by_account_id[str(other_account.id)]["id"],+ summary="Aardvark needs a weekly export.",+ )+ listed = self.client.get(self.requests_url).json()["results"][0]++ self.assertTrue(all(not link["evidence"] for link in listed["account_links"]))+ self.assertEqual(+ {link["account"]["name"]: link["evidence_count"] for link in listed["account_links"]},+ {"Acme": 2, "Aardvark": 1},+ )++ unlinked = self.client.patch(+ request_url,+ {+ "expected_version": with_other_evidence["version"],+ "account_ids": [str(self.account.id)],+ },+ format="json",+ ).json()+ restored = self.client.patch(+ request_url,+ {+ "expected_version": unlinked["version"],+ "account_ids": [str(self.account.id), str(other_account.id)],+ },+ format="json",+ ).json()++ self.assertEqual(len(unlinked["account_links"]), 1)+ self.assertEqual(len(unlinked["account_links"][0]["evidence"]), 2)+ self.assertEqual([link["account"]["name"] for link in restored["account_links"]], ["Acme", "Aardvark"])+ restored_links = {link["account"]["id"]: link for link in restored["account_links"]}+ self.assertEqual(+ [evidence["summary"] for evidence in restored_links[str(self.account.id)]["evidence"]],+ ["Acme repeated the request during renewal.", "Acme needs monthly exports."],+ )+ self.assertEqual(+ restored_links[str(other_account.id)]["evidence"][0]["summary"], "Aardvark needs a weekly export."+ )+ other_link = FeatureRequestAccountLink.objects.for_team(self.team.id).get(account=other_account)+ self.assertIsNone(other_link.unlinked_at)+ self.assertEqual(+ FeatureRequestEvidence.objects.for_team(self.team.id).filter(account_link=other_link).count(), 1+ )++ def test_add_account_can_create_its_first_evidence_in_the_same_change(self) -> None:+ created = self.client.post(self.requests_url, self._payload(), format="json").json()+ other_account = create_account(team_id=self.team.id, name="Globex")++ response = self.client.post(+ f"{self.requests_url}{created['id']}/add_account/",+ {+ "expected_version": created["version"],+ "account_id": str(other_account.id),+ "evidence": {+ "summary": "Globex needs a weekly export.",+ "customer_quote": "We need this before our Monday review.",+ "evidence_source": "productboard",+ "source_url": "https://example.com/meeting/1",+ "requested_on": date.today().isoformat(),+ },+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["version"], created["version"] + 1)+ links_by_account = {link["account"]["id"]: link for link in response.json()["account_links"]}+ self.assertEqual(+ links_by_account[str(other_account.id)]["evidence"][0]["summary"],+ "Globex needs a weekly export.",+ )+ self.assertEqual(links_by_account[str(other_account.id)]["evidence"][0]["evidence_source"], "productboard")+ history = self.client.get(f"{self.requests_url}{created['id']}/history/").json()+ self.assertEqual([change["field"] for change in history[0]["changes"]], ["accounts", "evidence"])++ def test_dated_evidence_sorts_before_undated_evidence(self) -> None:+ created = self.client.post(self.requests_url, self._payload(), format="json").json()+ account_link_id = created["account_links"][0]["id"]+ undated = self.client.post(+ f"{self.requests_url}{created['id']}/add_evidence/",+ {+ "expected_version": created["version"],+ "account_link_id": account_link_id,+ "summary": "Undated evidence",+ "evidence_source": "conversation",+ "requested_on": None,+ },+ format="json",+ ).json()+ dated = self.client.post(+ f"{self.requests_url}{created['id']}/add_evidence/",+ {+ "expected_version": undated["version"],+ "account_link_id": account_link_id,+ "summary": "Dated evidence",+ "evidence_source": "conversation",+ "requested_on": "2026-01-01",+ },+ format="json",+ )++ self.assertEqual(dated.status_code, status.HTTP_200_OK)+ self.assertEqual(+ [item["summary"] for item in dated.json()["account_links"][0]["evidence"]],+ ["Dated evidence", "Undated evidence"],+ )++ def test_evidence_updates_and_deletes_with_request_version_checks(self) -> None:+ created = self.client.post(self.requests_url, self._payload(), format="json").json()+ account_link_id = created["account_links"][0]["id"]+ with_evidence = self._add_evidence(+ request_id=created["id"],+ version=created["version"],+ account_link_id=account_link_id,+ summary="Initial summary",+ )+ evidence_id = with_evidence["account_links"][0]["evidence"][0]["id"]+ update_url = f"{self.requests_url}{created['id']}/update_evidence/"++ stale = self.client.post(+ update_url,+ {+ "expected_version": created["version"],+ "evidence_id": evidence_id,+ "summary": "Stale summary",+ "evidence_source": "slack",+ },+ format="json",+ )+ updated = self.client.post(+ update_url,+ {+ "expected_version": with_evidence["version"],+ "evidence_id": evidence_id,+ "summary": "Updated summary",+ "customer_quote": "Please add this.",+ "evidence_source": "slack",+ "source_url": "https://example.com/thread/1",+ },+ format="json",+ ).json()+ deleted = self.client.post(+ f"{self.requests_url}{created['id']}/remove_evidence/",+ {+ "expected_version": updated["version"],+ "evidence_id": evidence_id,+ },+ format="json",+ )++ self.assertEqual(stale.status_code, status.HTTP_409_CONFLICT)+ self.assertEqual(updated["account_links"][0]["evidence"][0]["summary"], "Updated summary")+ self.assertEqual(deleted.status_code, status.HTTP_200_OK)+ self.assertEqual(deleted.json()["account_links"][0]["evidence"], [])+ self.assertFalse(FeatureRequestEvidence.objects.for_team(self.team.id).filter(id=evidence_id).exists())++ def test_viewer_only_receives_data_for_accessible_accounts(self) -> None:+ created = self.client.post(self.requests_url, self._payload(), format="json").json()+ other_account = create_account(team_id=self.team.id, name="Globex")+ linked = self.client.patch(+ f"{self.requests_url}{created['id']}/",+ {+ "expected_version": created["version"],+ "account_ids": [str(self.account.id), str(other_account.id)],+ },+ format="json",+ ).json()+ links = {link["account"]["id"]: link for link in linked["account_links"]}+ with_restricted_evidence = self._add_evidence(+ request_id=created["id"],+ version=linked["version"],+ account_link_id=links[str(self.account.id)]["id"],+ summary="Restricted account evidence",+ )+ self._add_evidence(+ request_id=created["id"],+ version=with_restricted_evidence["version"],+ account_link_id=links[str(other_account.id)]["id"],+ summary="Visible account evidence",+ )+ viewer = User.objects.create_and_join(+ self.organization,+ "[email protected]",+ "testtest",+ )+ self._set_access_level(viewer, "viewer")+ membership = OrganizationMembership.objects.get(user=viewer, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="account",+ resource_id=str(self.account.id),+ access_level="none",+ organization_member=membership,+ )+ self.client.force_login(viewer)++ response = self.client.get(f"{self.requests_url}{created['id']}/")+ history = self.client.get(f"{self.requests_url}{created['id']}/history/")+ restricted_filter = self.client.get(self.requests_url, {"account_ids": str(self.account.id)})+ visible_filter = self.client.get(self.requests_url, {"account_ids": str(other_account.id)})++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([link["account"]["name"] for link in response.json()["account_links"]], ["Globex"])+ self.assertEqual(response.json()["account_links"][0]["evidence"][0]["summary"], "Visible account evidence")+ self.assertNotIn("Restricted account evidence", str(response.json()))+ self.assertNotIn("Restricted account evidence", str(history.json()))+ self.assertTrue(all(entry["changes"] for entry in history.json()))+ self.assertEqual(restricted_filter.json()["count"], 0)+ self.assertEqual(visible_filter.json()["count"], 1)+ self.assertFalse(response.json()["can_update"])+def test_list_combines_filters_orders_priorities_and_hides_archived_requests(self) -> None:first = self.client.post(self.requests_url, self._payload(), format="json").json()second_payload = self._payload()@@ -424,7 +810,7 @@ class TestFeatureRequestsAPI(APIBaseTest):self.assertTrue(archived.json()["is_archived"])self.assertEqual(archived_update.status_code, status.HTTP_400_BAD_REQUEST)self.assertFalse(restored.json()["is_archived"])- self.assertEqual(restored.json()["account"], created["account"])+ self.assertEqual(restored.json()["account_links"], created["account_links"])self.assertEqual(restored.json()["product_areas"], created["product_areas"])self.assertEqual(len(history.json()), 2)diff --git a/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsx b/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsxindex f9f6d2adeadf..65fe197fc7df 100644--- a/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsx+++ b/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsx@@ -109,6 +109,47 @@ const featureRequestStoryItem = {archived_by: null,version: 1,account: { id: '018f47de-7e12-7000-8000-000000000002', name: 'Acme' },+ account_links: [+ {+ id: '018f47de-7e12-7000-8000-000000000007',+ account: { id: '018f47de-7e12-7000-8000-000000000002', name: 'Acme' },+ evidence: [+ {+ id: '018f47de-7e12-7000-8000-000000000008',+ summary: 'Acme needs a monthly export for its reporting workflow.',+ customer_quote: 'We need to share account retention with our leadership team.',+ evidence_source: 'conversation',+ source_url: '',+ requested_on: '2024-01-08',+ created_by: 1,+ updated_by: 1,+ created_at: '2024-01-12T10:00:00Z',+ updated_at: '2024-01-12T10:00:00Z',+ },+ ...Array.from({ length: 5 }, (_, index) => ({+ id: `018f47de-7e12-7000-8000-00000000001${index}`,+ summary: `Acme repeated this request in follow-up ${index + 1}.`,+ customer_quote: '',+ evidence_source: 'meeting',+ source_url: '',+ requested_on: `2024-01-${String(index + 9).padStart(2, '0')}`,+ created_by: 1,+ updated_by: 1,+ created_at: `2024-01-${String(index + 13).padStart(2, '0')}T10:00:00Z`,+ updated_at: `2024-01-${String(index + 13).padStart(2, '0')}T10:00:00Z`,+ })),+ ],+ created_at: '2024-01-12T10:00:00Z',+ updated_at: '2024-01-12T10:00:00Z',+ },+ {+ id: '018f47de-7e12-7000-8000-000000000009',+ account: { id: '018f47de-7e12-7000-8000-000000000010', name: 'Globex' },+ evidence: [],+ created_at: '2024-01-13T10:00:00Z',+ updated_at: '2024-01-13T10:00:00Z',+ },+ ],product_areas: [{id: '018f47de-7e12-7000-8000-000000000003',@@ -171,9 +212,9 @@ export const FeatureRequests: Story = {{ field: 'status', before: null, after: 'requested' },{ field: 'priority', before: null, after: null },{- field: 'account',- before: null,- after: { id: '018f47de-7e12-7000-8000-000000000002', name: 'Acme' },+ field: 'accounts',+ before: [],+ after: [{ id: '018f47de-7e12-7000-8000-000000000002', name: 'Acme' }],},{field: 'product_areas',@@ -190,10 +231,13 @@ export const FeatureRequests: Story = {],'api/projects/:team_id/feature_request_product_areas/': featureRequestStoryItem.product_areas,'api/projects/:team_id/accounts/': {- count: 1,+ count: 3,next: null,previous: null,- results: [featureRequestStoryItem.account],+ results: [+ ...featureRequestStoryItem.account_links.map((link) => link.account),+ { id: '018f47de-7e12-7000-8000-000000000020', name: 'Initech' },+ ],},},})diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 91a6ac9e97cc..e53d46ebd114 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -25,10 +25,11 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc│ AccountsOverviewTilesButton + AccountsColumnConfigurator on the right├── AccountsOverviewTiles metric tiles across the filtered set└── AccountsTable the DataTable; keyed row renderers; controlled row expansion- └── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Usage/Spend/Opportunities/Summaries/Support tickets/Email threads/Meetings/Event stream)+ └── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Feature requests/Usage/Spend/Opportunities/Summaries/Support tickets/Email threads/Meetings/Event stream)├── (notes) paginated/searchable/sortable LemonTable + "New note" button (accountNotebooksLogic, keyed by accountId)├── (users) AccountRelatedUsersExpansion (accountRelatedUsersLogic, keyed by externalId)├── (relationships) AccountRelationshipsExpansion (accountRelationshipsLogic, keyed by accountId — full assignment timeline, paginated; assign/end controls + definition filter, current assignments sorted on top)+ ├── (feature requests) AccountFeatureRequestsExpansion (accountFeatureRequestsLogic, keyed by accountId — linked requests and link-existing flow)├── (usage) AccountBillingExpansion kind="usage" (accountBillingLogic — a saved billing-usage insight)├── (spend) AccountBillingExpansion kind="spend" (accountBillingLogic — saved billing-spend insights)└── (opportunities) AccountOpportunitiesExpansion (accountOpportunitiesLogic, keyed by accountId — DWH Salesforce opportunities)@@ -41,23 +42,24 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc### Logics and what each owns-| Logic | Owns |-| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `accountsLogic` | The hub. Search (debounced), tag / assigned-to/unassigned / custom-property filters, sort, inline role assignment, typed Postgres list and metrics queries, shareable URL-hash view state, and `openAccount` (the Max entry point). `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references. `connect`s column-config, overview-tiles, and expansion logics. |-| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select). Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. |-| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), Postgres-backed column-picker groups, the per-team saved column config (`columnConfigurations` API), and custom-property definitions. It seeds `propertyDefinitionsModel` so the filter UI resolves per-type operator sets. Warehouse-backed columns and SQL expressions are not offered. |-| `accountsExpansionLogic` | Which rows are expanded (`expandedAccountIds`) and the active tab per account (`activeTabByAccount`). Pure state — no DOM, no data fetching. |-| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`). It translates supported tile definitions into typed Postgres metrics for `accountsLogic.metricsQuery`, then reads the separate metrics data node. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. |-| `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). |-| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). US-region orgs come from the org-members endpoint; when it returns no members, the logic falls back to the `eu_org_members` data warehouse view (a materialized pre-join of the EU postgres sync, prod-only, refreshed daily), fetched once per expansion and paginated client-side. A missing view (local dev) degrades to the normal empty state. |-| `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint) and `endRelationship` (per active row, POSTs the end endpoint) — both guarded by a shared `relationshipSaving` flag, reload the timeline, and force-refresh the list's data nodes so relationship columns stay in sync. |-| `accountBillingLogic` | Billing data behind the Usage and Spend tabs (keyed by `accountId:kind`); injects the account's org + date range into saved billing insights' SQL variables, preloads each insight result when the account expands, and owns the per-view hidden-series state (`ephemeralHiddenSeriesKeysByShortId`) behind the chart chips. |-| `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. |-| `accountSummariesLogic` | The Summaries tab (keyed by `accountId`): fetches the account (for its linked `slack_channel_id` and `slack_summary_cadence`) plus the first page of the `accountsSummariesList` endpoint, navigates server pages via `loadSummariesPage` (5 per page, `page` reducer; each page replaces the last), holds per-summary collapse state (`expandedSummaryIds` / `toggleSummaryExpanded`), and owns the cadence opt-in (`setCadence` PATCHes the account through `accountsPartialUpdate`, guarded by a `cadenceSaving` flag). Turning the cadence on with no summaries yet starts `generatingFirstSummary` polling (`startFirstSummaryPolling` / `stopFirstSummaryPolling`, two `cache.disposables` keys) so the backfill the backend kicks off appears without a refresh; the poll deadline lives in a module-level map keyed by account id, because this logic unmounts whenever its row collapses while the backfill keeps running. Distinguishes not-loaded / no-channel-linked / generating / loaded-empty / load-failed; captures unexpected failures. |-| `accountSupportTicketsLogic` | Conversations support tickets behind the Support tickets tab (keyed by `accountId`): fetches the account's tickets from the generated `accountsSupportTicketsList` endpoint (backed by the customer-analytics facade → conversations facade → `Ticket`s matched on `organization_id = external_id`). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. |-| `accountEmailThreadsLogic` | Matched email communication behind the Email threads tab (keyed by `accountId`): fetches server-paginated summaries from `accountsEmailThreadsList`, keeps one row expanded, and fetches paginated ordered messages through `accountsEmailThreadMessagesList`. The current message page is cached while the row remains expanded; list and detail failures leave explicit retry guidance instead of an infinite skeleton. |-| `accountMeetingsLogic` | The Meetings tab (keyed by `accountId`): fetches synced calendar meetings from the generated `accountsMeetingsList` endpoint (customer-analytics facade `get_account_meetings` over the `Meeting` model, populated by the Google Calendar Temporal sync). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. Also owns the project-admin-gated "Edit matching" editor: `email_domains` / `known_emails` drafts, normalization (trim, lowercase, strip a leading `@`, dedupe), and `saveMatching` — merges them into the account's `properties` via `accountsPartialUpdate` (guarded by `savingMatching`) and propagates the updated account through `accountLinksLogic.loadAccountSuccess` (it connects to that logic for the account instead of fetching its own copy). |-| `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |+| Logic | Owns |+| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `accountsLogic` | The hub. Search (debounced), tag / assigned-to/unassigned / custom-property filters, sort, inline role assignment, typed Postgres list and metrics queries, shareable URL-hash view state, and `openAccount` (the Max entry point). `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references. `connect`s column-config, overview-tiles, and expansion logics. |+| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select). Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. |+| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), Postgres-backed column-picker groups, the per-team saved column config (`columnConfigurations` API), and custom-property definitions. It seeds `propertyDefinitionsModel` so the filter UI resolves per-type operator sets. Warehouse-backed columns and SQL expressions are not offered. |+| `accountsExpansionLogic` | Which rows are expanded (`expandedAccountIds`) and the active tab per account (`activeTabByAccount`). Pure state — no DOM, no data fetching. |+| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`). It translates supported tile definitions into typed Postgres metrics for `accountsLogic.metricsQuery`, then reads the separate metrics data node. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. |+| `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). |+| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). US-region orgs come from the org-members endpoint; when it returns no members, the logic falls back to the `eu_org_members` data warehouse view (a materialized pre-join of the EU postgres sync, prod-only, refreshed daily), fetched once per expansion and paginated client-side. A missing view (local dev) degrades to the normal empty state. |+| `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint) and `endRelationship` (per active row, POSTs the end endpoint) — both guarded by a shared `relationshipSaving` flag, reload the timeline, and force-refresh the list's data nodes so relationship columns stay in sync. |+| `accountFeatureRequestsLogic` | Feature requests for one account (keyed by `accountId`): loads linked requests with server pagination, then searches a bounded server page of accessible, editable active requests for the link picker. The picker exposes load failures with retry guidance and refreshes stale options after optimistic-concurrency conflicts. |+| `accountBillingLogic` | Billing data behind the Usage and Spend tabs (keyed by `accountId:kind`); injects the account's org + date range into saved billing insights' SQL variables, preloads each insight result when the account expands, and owns the per-view hidden-series state (`ephemeralHiddenSeriesKeysByShortId`) behind the chart chips. |+| `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. |+| `accountSummariesLogic` | The Summaries tab (keyed by `accountId`): fetches the account (for its linked `slack_channel_id` and `slack_summary_cadence`) plus the first page of the `accountsSummariesList` endpoint, navigates server pages via `loadSummariesPage` (5 per page, `page` reducer; each page replaces the last), holds per-summary collapse state (`expandedSummaryIds` / `toggleSummaryExpanded`), and owns the cadence opt-in (`setCadence` PATCHes the account through `accountsPartialUpdate`, guarded by a `cadenceSaving` flag). Turning the cadence on with no summaries yet starts `generatingFirstSummary` polling (`startFirstSummaryPolling` / `stopFirstSummaryPolling`, two `cache.disposables` keys) so the backfill the backend kicks off appears without a refresh; the poll deadline lives in a module-level map keyed by account id, because this logic unmounts whenever its row collapses while the backfill keeps running. Distinguishes not-loaded / no-channel-linked / generating / loaded-empty / load-failed; captures unexpected failures. |+| `accountSupportTicketsLogic` | Conversations support tickets behind the Support tickets tab (keyed by `accountId`): fetches the account's tickets from the generated `accountsSupportTicketsList` endpoint (backed by the customer-analytics facade → conversations facade → `Ticket`s matched on `organization_id = external_id`). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. |+| `accountEmailThreadsLogic` | Matched email communication behind the Email threads tab (keyed by `accountId`): fetches server-paginated summaries from `accountsEmailThreadsList`, keeps one row expanded, and fetches paginated ordered messages through `accountsEmailThreadMessagesList`. The current message page is cached while the row remains expanded; list and detail failures leave explicit retry guidance instead of an infinite skeleton. |+| `accountMeetingsLogic` | The Meetings tab (keyed by `accountId`): fetches synced calendar meetings from the generated `accountsMeetingsList` endpoint (customer-analytics facade `get_account_meetings` over the `Meeting` model, populated by the Google Calendar Temporal sync). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. Also owns the project-admin-gated "Edit matching" editor: `email_domains` / `known_emails` drafts, normalization (trim, lowercase, strip a leading `@`, dedupe), and `saveMatching` — merges them into the account's `properties` via `accountsPartialUpdate` (guarded by `savingMatching`) and propagates the updated account through `accountLinksLogic.loadAccountSuccess` (it connects to that logic for the account instead of fetching its own copy). |+| `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |## Data & query model@@ -112,9 +114,9 @@ Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemove## The expanded row-`AccountsTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `relationships` / `usage` / `spend` / `opportunities` / `summaries` / `support_tickets` / `email_threads` / `meetings` / `event_stream` (`AccountExpansionTab`; the `event_stream` tab is gated by the `CUSTOMER_ANALYTICS_CSP` flag) plus the sidebar (Useful links + an active-relationships summary, `ActiveRelationships`, hidden when nothing is assigned). Active tab comes from `activeTabFor(accountId)` (defaults to `notes`). Pagination inside these tabs keeps its page state out of the URL so changing pages does not rerun deep-link restoration and replace the active tab.+`AccountsTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `relationships` / `feature_requests` / `usage` / `spend` / `opportunities` / `summaries` / `support_tickets` / `email_threads` / `meetings` / `event_stream` (`AccountExpansionTab`; the `event_stream` tab is gated by the `CUSTOMER_ANALYTICS_CSP` flag) plus the sidebar (Useful links + an active-relationships summary, `ActiveRelationships`, hidden when nothing is assigned). Active tab comes from `activeTabFor(accountId)` (defaults to `notes`). Pagination inside these tabs keeps its page state out of the URL so changing pages does not rerun deep-link restoration and replace the active tab.-**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `LemonTabs` only renders the active tab's content (keyed by `activeKey`), so a tab's logic would normally unmount the moment you switch away and refetch on return. To avoid that, `AccountNotebooksExpansion` holds a mount reference to each per-tab logic via `useMountedLogic` — `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, `accountOpportunitiesLogic({ accountId })`, `accountSummariesLogic({ accountId })`, `accountSupportTicketsLogic({ accountId })`, `accountEmailThreadsLogic({ accountId })`, and `accountMeetingsLogic({ accountId })`. Since `AccountNotebooksExpansion` stays mounted for as long as the row is expanded (it's the `expandedRowRender` body), those keyed instances survive tab switches and only tear down when the row collapses. The `useMountedLogic` props must stay identical to the `useValues` props in the tab components (`AccountRelatedUsersExpansion`, `AccountRelationshipsExpansion`, `AccountBillingExpansion`, `AccountOpportunitiesExpansion`, `AccountSummariesExpansion`, `AccountSupportTicketsExpansion`, `AccountEmailThreadsExpansion`, `AccountMeetingsExpansion`) so both resolve to the same keyed instance. `accountNotebooksLogic` and `accountLinksLogic` already mount at this level (Notes content and the always-rendered sidebar), so they need no explicit mount reference. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live.+**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `LemonTabs` only renders the active tab's content (keyed by `activeKey`), so a tab's logic would normally unmount the moment you switch away and refetch on return. To avoid that, `AccountNotebooksExpansion` holds a mount reference to each per-tab logic via `useMountedLogic` — `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, `accountOpportunitiesLogic({ accountId })`, `accountSummariesLogic({ accountId })`, `accountSupportTicketsLogic({ accountId })`, `accountEmailThreadsLogic({ accountId })`, and `accountMeetingsLogic({ accountId })`. Since `AccountNotebooksExpansion` stays mounted for as long as the row is expanded (it's the `expandedRowRender` body), those keyed instances survive tab switches and only tear down when the row collapses. The `useMountedLogic` props must stay identical to the `useValues` props in the tab components (`AccountRelatedUsersExpansion`, `AccountRelationshipsExpansion`, `AccountBillingExpansion`, `AccountOpportunitiesExpansion`, `AccountSummariesExpansion`, `AccountSupportTicketsExpansion`, `AccountEmailThreadsExpansion`, `AccountMeetingsExpansion`) so both resolve to the same keyed instance. `accountNotebooksLogic` and `accountLinksLogic` already mount at this level (Notes content and the always-rendered sidebar), so they need no explicit mount reference. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live. The flag-gated Feature requests tab loads when opened instead of mounting its logic while the flag is off.The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so the root mount above keeps it cached. The **Usage/Spend** tabs are different: their insight results live in `dataNodeLogic`/`dataVisualizationLogic`. After each `accountBillingLogic` loads its saved-insight metadata, it mounts those result logics immediately. Because the expanded-row root mounts both billing kinds, all Usage and Spend queries start when the account expands instead of waiting for a tab click. The result logics stay mounted until the row collapses. Changing the date range replaces each insight's preload and aborts work under the previous query key. The tab body reuses the same keyed logics and attaches them to `accountBillingLogic` via `useAttachedLogic` — `AccountBillingChart` does this directly, and the fallback `<Query>` path uses `attachTo={accountBillingLogic-instance}` plus matching insight context. This prevents duplicate loads and keeps results across tab switches. (The Opportunities tab loads its data in `accountOpportunitiesLogic` directly, not via an embedded query, so the root `useMountedLogic` above is enough — it needs no attachment.)diff --git a/products/customer_analytics/frontend/components/Accounts/AccountFeatureRequestsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountFeatureRequestsExpansion.tsxnew file mode 100644index 000000000000..3fcb8ecaebfe--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountFeatureRequestsExpansion.tsx@@ -0,0 +1,170 @@+import { useActions, useValues } from 'kea'+import { combineUrl } from 'kea-router'++import { IconPlus } from '@posthog/icons'+import {+ LemonBanner,+ LemonButton,+ LemonInputSelect,+ LemonModal,+ LemonTable,+ LemonTableColumns,+ Link,+} from '@posthog/lemon-ui'++import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'+import { urls } from 'scenes/urls'++import { AccessControlLevel, AccessControlResourceType } from '~/types'++import type { FeatureRequestApi } from '../../generated/api.schemas'+import { ACCOUNT_FEATURE_REQUESTS_PAGE_SIZE, accountFeatureRequestsLogic } from './accountFeatureRequestsLogic'++export function AccountFeatureRequestsExpansion({ accountId }: { accountId: string }): JSX.Element {+ const logic = accountFeatureRequestsLogic({ accountId })+ const {+ accountRequests,+ accountRequestsPage,+ accountRequestsLoading,+ accountRequestsError,+ requestPickerOpen,+ selectedRequestId,+ candidateOptions,+ availableRequestsLoading,+ availableRequestsError,+ linkingRequest,+ } = useValues(logic)+ const {+ loadAccountRequests,+ loadAvailableRequests,+ openRequestPicker,+ closeRequestPicker,+ setSelectedRequestId,+ setAccountRequestsPage,+ setRequestSearch,+ linkSelectedRequest,+ } = useActions(logic)++ const editorDisabledReason = getAccessControlDisabledReason(+ AccessControlResourceType.CustomerAnalytics,+ AccessControlLevel.Editor+ )++ const columns: LemonTableColumns<FeatureRequestApi> = [+ {+ title: 'Request',+ key: 'title',+ render: (_, request) => (+ <Link to={urls.customerAnalyticsFeatureRequests(request.id)} className="font-medium">+ {request.title}+ </Link>+ ),+ },+ {+ title: 'Evidence',+ key: 'evidence',+ render: (_, request) => {+ const accountLink = request.account_links.find((link) => link.account.id === accountId)+ const count = accountLink?.evidence_count ?? 0+ return `${count} ${count === 1 ? 'item' : 'items'}`+ },+ },+ {+ title: '',+ key: 'actions',+ width: 120,+ render: (_, request) => (+ <LemonButton+ type="secondary"+ size="xsmall"+ to={+ combineUrl(urls.customerAnalyticsFeatureRequests(request.id), {+ evidence_account: accountId,+ }).url+ }+ disabledReason={editorDisabledReason}+ >+ Add evidence+ </LemonButton>+ ),+ },+ ]++ return (+ <div className="flex flex-col gap-3" data-attr="account-feature-requests">+ <div className="flex justify-end">+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPlus />}+ onClick={openRequestPicker}+ disabledReason={editorDisabledReason}+ >+ Link request+ </LemonButton>+ </div>+ {accountRequestsError && (+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadAccountRequests }}>+ {accountRequestsError}+ </LemonBanner>+ )}+ <LemonTable+ size="small"+ embedded+ dataSource={accountRequests.results}+ columns={columns}+ rowKey="id"+ loading={accountRequestsLoading}+ emptyState="No feature requests linked to this account."+ pagination={{+ controlled: true,+ pageSize: ACCOUNT_FEATURE_REQUESTS_PAGE_SIZE,+ currentPage: accountRequestsPage,+ useUrl: false,+ entryCount: accountRequests.count,+ onForward: () => setAccountRequestsPage(accountRequestsPage + 1),+ onBackward: () => setAccountRequestsPage(accountRequestsPage - 1),+ }}+ />+ <LemonModal+ isOpen={requestPickerOpen}+ onClose={closeRequestPicker}+ title="Link feature request"+ width={480}+ footer={+ <>+ <LemonButton type="secondary" onClick={closeRequestPicker}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={linkSelectedRequest}+ loading={linkingRequest}+ disabledReason={selectedRequestId ? undefined : 'Select a feature request'}+ >+ Link request+ </LemonButton>+ </>+ }+ >+ <div className="flex flex-col gap-3">+ {availableRequestsError && (+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadAvailableRequests }}>+ {availableRequestsError}+ </LemonBanner>+ )}+ <LemonInputSelect+ mode="single"+ value={selectedRequestId ? [selectedRequestId] : []}+ onChange={(values) => setSelectedRequestId(values[0] ?? null)}+ onInputChange={setRequestSearch}+ options={candidateOptions}+ loading={availableRequestsLoading}+ placeholder="Search for a feature request"+ fullWidth+ />+ </div>+ </LemonModal>+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsxindex b3282cb7b0b3..7bc53269f225 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx@@ -39,6 +39,7 @@ import { AccountBillingExpansion } from './AccountBillingExpansion'import { accountBillingLogic } from './accountBillingLogic'import { AccountEmailThreadsExpansion } from './AccountEmailThreadsExpansion'import { accountEmailThreadsLogic } from './accountEmailThreadsLogic'+import { AccountFeatureRequestsExpansion } from './AccountFeatureRequestsExpansion'import { accountLinksLogic } from './accountLinksLogic'import { AccountMeetingsExpansion } from './AccountMeetingsExpansion'import { accountMeetingsLogic } from './accountMeetingsLogic'@@ -323,6 +324,11 @@ export function AccountNotebooksExpansion({label: 'Relationships',content: <AccountRelationshipsExpansion accountId={accountId} />,},+ !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_FEATURE_REQUESTS] && {+ key: 'feature_requests' as const,+ label: 'Feature requests',+ content: <AccountFeatureRequestsExpansion accountId={accountId} />,+ },{key: 'usage',label: 'Usage',diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsxindex dbdbebf1461f..ffe4c2a63bdd 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx@@ -17,6 +17,7 @@ const ACCOUNT_NOTEBOOKS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/nconst ACCOUNT_EMAIL_THREADS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/email_threads/'const ACCOUNT_EMAIL_THREAD_DETAIL_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/email_threads/:thread_id/'const ACCOUNT_RELATIONSHIPS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/relationships/'+const FEATURE_REQUESTS_ENDPOINT = 'api/projects/:team_id/feature_requests/'const RELATIONSHIP_DEFINITIONS_ENDPOINT = 'api/projects/:team_id/account_relationship_definitions/'const ORGANIZATION_MEMBERS_ENDPOINT = 'api/projects/:team_id/organization_members/'const WAREHOUSE_VIEW_LINK_ENDPOINT = 'api/environments/:team_id/warehouse_view_link/'@@ -123,6 +124,33 @@ const ACCOUNT_WITHOUT_LINKS = {updated_at: '2026-05-15T10:30:00Z',}+const ACCOUNT_FEATURE_REQUEST = {+ id: '11111111-2222-3333-4444-555555555555',+ title: 'Scheduled account exports',+ description: 'Send account reports on a schedule.',+ request_status: 'requested',+ request_priority: null,+ is_archived: false,+ archived_at: null,+ archived_by: null,+ version: 1,+ account: { id: 'acc-1', name: 'Acme Inc' },+ account_links: [+ {+ id: '66666666-7777-8888-9999-aaaaaaaaaaaa',+ account: { id: 'acc-1', name: 'Acme Inc' },+ evidence: [],+ created_at: '2026-05-15T10:30:00Z',+ updated_at: '2026-05-15T10:30:00Z',+ },+ ],+ product_areas: [],+ created_by: 1,+ updated_by: 1,+ created_at: '2026-05-15T10:30:00Z',+ updated_at: '2026-05-15T10:30:00Z',+}+const EMPTY_INSIGHTS = { count: 0, next: null, previous: null, results: [] }const EMPTY_EMAIL_THREADS: PaginatedAccountEmailThreadListApi = {count: 0,@@ -387,6 +415,49 @@ export const RowExpandedWithNote: Story = {},}+export const RowExpandedFeatureRequests: Story = {+ render: () => <App />,+ parameters: {+ featureFlags: [+ FEATURE_FLAGS.CUSTOMER_ANALYTICS,+ FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,+ FEATURE_FLAGS.CUSTOMER_ANALYTICS_FEATURE_REQUESTS,+ ],+ testOptions: {+ ...EXPANDED_ROW_TEST_OPTIONS,+ waitForSelector: ['[data-attr="accounts-refresh"]', '[data-attr="account-feature-requests"]'],+ },+ },+ decorators: [+ ...expandedRowDecorators(),+ mswDecorator({+ get: {+ [ACCOUNT_RETRIEVE_ENDPOINT]: ACCOUNT_WITH_LINKS,+ [ACCOUNT_NOTEBOOKS_ENDPOINT]: { count: 0, next: null, previous: null, results: [] },+ [FEATURE_REQUESTS_ENDPOINT]: {+ count: 1,+ next: null,+ previous: null,+ results: [ACCOUNT_FEATURE_REQUEST],+ },+ },+ post: {+ [QUERY_ENDPOINT]: mockAccountsTableQuery(SINGLE_ROW),+ },+ }),+ ],+ play: async ({ canvasElement }) => {+ await expandFirstRow(canvasElement)+ const expansion = canvasElement.querySelector('[data-attr="account-expansion"]') as HTMLElement+ await userEvent.click(await within(expansion).findByText('Feature requests', {}, { timeout: 15000 }))+ await waitFor(() => {+ if (!canvasElement.querySelector('[data-attr="account-feature-requests"]')) {+ throw new Error('Feature requests tab did not render')+ }+ })+ },+}+export const RowExpandedEmailThreads: Story = {render: () => <App />,parameters: {diff --git a/products/customer_analytics/frontend/components/Accounts/accountFeatureRequestsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountFeatureRequestsLogic.test.tsnew file mode 100644index 000000000000..2d594a4f2ba9--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountFeatureRequestsLogic.test.ts@@ -0,0 +1,173 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { ApiError } from 'lib/api'++import { initKeaTests } from '~/test/init'++import * as generatedApi from '../../generated/api'+import type { FeatureRequestApi } from '../../generated/api.schemas'+import { accountFeatureRequestsLogic } from './accountFeatureRequestsLogic'++const existingRequest: FeatureRequestApi = {+ id: 'request-1',+ title: 'Scheduled exports',+ description: 'Send exports on a schedule.',+ request_status: 'requested',+ request_priority: null,+ is_archived: false,+ archived_at: null,+ archived_by: null,+ version: 3,+ can_update: true,+ account: { id: 'account-1', name: 'Acme' },+ account_links: [+ {+ id: 'link-1',+ account: { id: 'account-1', name: 'Acme' },+ evidence: [],+ evidence_count: 0,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ },+ ],+ product_areas: [],+ created_by: 1,+ updated_by: 1,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+}++const emptyPage = { count: 0, next: null, previous: null, results: [] }++describe('accountFeatureRequestsLogic', () => {+ beforeEach(() => {+ initKeaTests(true, MOCK_DEFAULT_TEAM)+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ it('links an existing request without replacing its current accounts', async () => {+ const listSpy = jest+ .spyOn(generatedApi, 'featureRequestsList')+ .mockResolvedValueOnce(emptyPage)+ .mockResolvedValueOnce({ ...emptyPage, count: 1, results: [existingRequest] })+ .mockResolvedValueOnce({ ...emptyPage, count: 1, results: [existingRequest] })+ const updateSpy = jest.spyOn(generatedApi, 'featureRequestsUpdate').mockResolvedValue(existingRequest)+ const logic = accountFeatureRequestsLogic({ accountId: 'account-2' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ await expectLogic(logic, () => logic.actions.openRequestPicker()).toFinishAllListeners()+ logic.actions.setSelectedRequestId(existingRequest.id)+ await expectLogic(logic, () => logic.actions.linkSelectedRequest()).toFinishAllListeners()++ expect(updateSpy).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), existingRequest.id, {+ expected_version: existingRequest.version,+ account_ids: ['account-1', 'account-2'],+ })+ expect(listSpy).toHaveBeenCalledWith(+ String(MOCK_DEFAULT_TEAM.id),+ expect.objectContaining({ account_ids: ['account-2'] })+ )+ expect(logic.values.requestPickerOpen).toBe(false)+ expect(logic.values.linkingRequest).toBe(false)+ logic.unmount()+ })++ it('paginates linked requests on the server', async () => {+ const requests = Array.from({ length: 21 }, (_, index) => ({+ ...existingRequest,+ id: `request-${index + 1}`,+ title: `Request ${index + 1}`,+ }))+ const listSpy = jest.spyOn(generatedApi, 'featureRequestsList').mockImplementation(async (_teamId, params) => {+ const offset = params?.offset ?? 0+ const limit = params?.limit ?? 20+ return {+ count: requests.length,+ next: offset + limit < requests.length ? 'next' : null,+ previous: offset > 0 ? 'previous' : null,+ results: requests.slice(offset, offset + limit),+ }+ })+ const logic = accountFeatureRequestsLogic({ accountId: 'account-2' })+ logic.mount()++ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.accountRequests.results).toHaveLength(20)++ await expectLogic(logic, () => logic.actions.setAccountRequestsPage(2)).toFinishAllListeners()++ expect(logic.values.accountRequests.results).toHaveLength(1)+ expect(listSpy).toHaveBeenCalledWith(+ String(MOCK_DEFAULT_TEAM.id),+ expect.objectContaining({ account_ids: ['account-2'], limit: 20, offset: 20 })+ )+ logic.unmount()+ })++ it('searches a bounded page and excludes requests the caller cannot update', async () => {+ const readOnlyRequest = { ...existingRequest, id: 'request-2', can_update: false }+ const listSpy = jest+ .spyOn(generatedApi, 'featureRequestsList')+ .mockResolvedValueOnce(emptyPage)+ .mockResolvedValue({ ...emptyPage, count: 2, results: [existingRequest, readOnlyRequest] })+ const logic = accountFeatureRequestsLogic({ accountId: 'account-2' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.openRequestPicker()+ await expectLogic(logic, () => logic.actions.setRequestSearch('scheduled')).toFinishAllListeners()++ expect(logic.values.availableRequests).toEqual([existingRequest])+ expect(listSpy).toHaveBeenLastCalledWith(+ String(MOCK_DEFAULT_TEAM.id),+ expect.objectContaining({+ archive_state: 'active',+ limit: 50,+ offset: 0,+ search: 'scheduled',+ })+ )+ logic.unmount()+ })++ it('exposes picker load failures for retry', async () => {+ jest.spyOn(console, 'error').mockImplementation()+ jest.spyOn(generatedApi, 'featureRequestsList')+ .mockResolvedValueOnce(emptyPage)+ .mockRejectedValueOnce(new Error('network failure'))+ const logic = accountFeatureRequestsLogic({ accountId: 'account-2' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ await expectLogic(logic, () => logic.actions.openRequestPicker()).toFinishAllListeners()++ expect(logic.values.availableRequestsError).toBe("Couldn't load available feature requests.")+ logic.unmount()+ })++ it('refreshes picker options after a version conflict', async () => {+ const listSpy = jest+ .spyOn(generatedApi, 'featureRequestsList')+ .mockResolvedValueOnce(emptyPage)+ .mockResolvedValue({ ...emptyPage, count: 1, results: [existingRequest] })+ jest.spyOn(generatedApi, 'featureRequestsUpdate').mockRejectedValueOnce(new ApiError('Conflict', 409))+ const logic = accountFeatureRequestsLogic({ accountId: 'account-2' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ await expectLogic(logic, () => logic.actions.openRequestPicker()).toFinishAllListeners()+ logic.actions.setSelectedRequestId(existingRequest.id)++ await expectLogic(logic, () => logic.actions.linkSelectedRequest()).toFinishAllListeners()++ expect(logic.values.selectedRequestId).toBeNull()+ expect(listSpy).toHaveBeenCalledTimes(3)+ expect(logic.values.requestPickerOpen).toBe(true)+ logic.unmount()+ })+})diff --git a/products/customer_analytics/frontend/components/Accounts/accountFeatureRequestsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountFeatureRequestsLogic.tsnew file mode 100644index 000000000000..a7da0315ca08--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountFeatureRequestsLogic.ts@@ -0,0 +1,255 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { ApiError } from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { teamLogic } from 'scenes/teamLogic'++import type { TeamPublicType, TeamType } from '../../../../../frontend/src/types'+import { featureRequestsList, featureRequestsUpdate } from '../../generated/api'+import type { FeatureRequestApi, PaginatedFeatureRequestListApi } from '../../generated/api.schemas'++export const ACCOUNT_FEATURE_REQUESTS_PAGE_SIZE = 20+const AVAILABLE_REQUESTS_LIMIT = 50+const EMPTY_REQUESTS_RESPONSE: PaginatedFeatureRequestListApi = {+ count: 0,+ next: null,+ previous: null,+ results: [],+}++export interface AccountFeatureRequestsLogicProps {+ accountId: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface accountFeatureRequestsLogicValues {+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ accountRequests: PaginatedFeatureRequestListApi+ accountRequestsError: string | null+ accountRequestsLoading: boolean+ accountRequestsPage: number+ availableRequests: FeatureRequestApi[]+ availableRequestsError: string | null+ availableRequestsLoading: boolean+ candidateOptions: {+ key: string+ label: string+ }[]+ linkingRequest: boolean+ requestPickerOpen: boolean+ requestSearch: string+ selectedRequestId: string | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface accountFeatureRequestsLogicActions {+ closeRequestPicker: () => {+ value: true+ }+ linkSelectedRequest: () => {+ value: true+ }+ loadAccountRequests: () => any+ loadAccountRequestsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadAccountRequestsSuccess: (+ accountRequests: PaginatedFeatureRequestListApi,+ payload?: any+ ) => {+ accountRequests: PaginatedFeatureRequestListApi+ payload?: any+ }+ loadAvailableRequests: () => any+ loadAvailableRequestsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadAvailableRequestsSuccess: (+ availableRequests: FeatureRequestApi[],+ payload?: any+ ) => {+ availableRequests: FeatureRequestApi[]+ payload?: any+ }+ openRequestPicker: () => {+ value: true+ }+ setAccountRequestsPage: (page: number) => {+ page: number+ }+ setLinkingRequest: (linkingRequest: boolean) => {+ linkingRequest: boolean+ }+ setRequestSearch: (search: string) => {+ search: string+ }+ setSelectedRequestId: (selectedRequestId: string | null) => {+ selectedRequestId: string | null+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface accountFeatureRequestsLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ candidateOptions: (availableRequests: FeatureRequestApi[]) => {+ key: string+ label: string+ }[]+ }+}++export type accountFeatureRequestsLogicType = MakeLogicType<+ accountFeatureRequestsLogicValues,+ accountFeatureRequestsLogicActions,+ AccountFeatureRequestsLogicProps,+ accountFeatureRequestsLogicMeta+>++export const accountFeatureRequestsLogic = kea<accountFeatureRequestsLogicType>([+ props({} as AccountFeatureRequestsLogicProps),+ key((props) => props.accountId),+ path((key) => ['products', 'customerAnalytics', 'accountFeatureRequestsLogic', key]),+ connect(() => ({ values: [teamLogic, ['currentTeam']] })),+ actions({+ openRequestPicker: true,+ closeRequestPicker: true,+ setSelectedRequestId: (selectedRequestId: string | null) => ({ selectedRequestId }),+ setAccountRequestsPage: (page: number) => ({ page }),+ setRequestSearch: (search: string) => ({ search }),+ linkSelectedRequest: true,+ setLinkingRequest: (linkingRequest: boolean) => ({ linkingRequest }),+ }),+ loaders(({ props, values }) => ({+ accountRequests: [+ EMPTY_REQUESTS_RESPONSE,+ {+ loadAccountRequests: async () =>+ featureRequestsList(String(values.currentTeam?.id), {+ account_ids: [props.accountId],+ archive_state: 'all',+ limit: ACCOUNT_FEATURE_REQUESTS_PAGE_SIZE,+ offset: (values.accountRequestsPage - 1) * ACCOUNT_FEATURE_REQUESTS_PAGE_SIZE,+ }),+ },+ ],+ availableRequests: [+ [] as FeatureRequestApi[],+ {+ loadAvailableRequests: async () => {+ const response = await featureRequestsList(String(values.currentTeam?.id), {+ archive_state: 'active',+ limit: AVAILABLE_REQUESTS_LIMIT,+ offset: 0,+ search: values.requestSearch.trim() || undefined,+ })+ return response.results.filter(+ (request) =>+ request.can_update &&+ !request.account_links.some((link) => link.account.id === props.accountId)+ )+ },+ },+ ],+ })),+ reducers({+ requestPickerOpen: [false, { openRequestPicker: () => true, closeRequestPicker: () => false }],+ selectedRequestId: [+ null as string | null,+ {+ setSelectedRequestId: (_, { selectedRequestId }) => selectedRequestId,+ setRequestSearch: () => null,+ openRequestPicker: () => null,+ closeRequestPicker: () => null,+ },+ ],+ accountRequestsPage: [+ 1,+ {+ setAccountRequestsPage: (_, { page }) => page,+ },+ ],+ requestSearch: [+ '',+ {+ setRequestSearch: (_, { search }) => search,+ openRequestPicker: () => '',+ closeRequestPicker: () => '',+ },+ ],+ linkingRequest: [false, { setLinkingRequest: (_, { linkingRequest }) => linkingRequest }],+ accountRequestsError: [+ null as string | null,+ {+ loadAccountRequests: () => null,+ loadAccountRequestsSuccess: () => null,+ loadAccountRequestsFailure: () => "Couldn't load feature requests.",+ },+ ],+ availableRequestsError: [+ null as string | null,+ {+ loadAvailableRequests: () => null,+ loadAvailableRequestsSuccess: () => null,+ loadAvailableRequestsFailure: () => "Couldn't load available feature requests.",+ closeRequestPicker: () => null,+ },+ ],+ }),+ selectors({+ candidateOptions: [+ (selectors) => [selectors.availableRequests],+ (requests: FeatureRequestApi[]): { key: string; label: string }[] =>+ requests.map((request) => ({ key: request.id, label: request.title })),+ ],+ }),+ listeners(({ props, values, actions }) => ({+ openRequestPicker: () => actions.loadAvailableRequests(),+ setAccountRequestsPage: () => actions.loadAccountRequests(),+ setRequestSearch: async (_, breakpoint) => {+ await breakpoint(300)+ actions.loadAvailableRequests()+ },+ linkSelectedRequest: async () => {+ if (!values.selectedRequestId || values.linkingRequest) {+ return+ }+ const request = values.availableRequests.find((item) => item.id === values.selectedRequestId)+ if (!request) {+ return+ }+ actions.setLinkingRequest(true)+ try {+ await featureRequestsUpdate(String(values.currentTeam?.id), request.id, {+ expected_version: request.version,+ account_ids: [...request.account_links.map((link) => link.account.id), props.accountId],+ })+ actions.closeRequestPicker()+ actions.loadAccountRequests()+ lemonToast.success('Feature request linked')+ } catch (error) {+ if (error instanceof ApiError && error.status === 409) {+ actions.setSelectedRequestId(null)+ actions.loadAvailableRequests()+ lemonToast.error('This request changed. Select it again to retry.')+ } else {+ lemonToast.error("Couldn't link the feature request.")+ }+ } finally {+ actions.setLinkingRequest(false)+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.loadAccountRequests()+ }),+])diff --git a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.tsindex bcfa2aa225d5..af1cc827377c 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts@@ -7,6 +7,7 @@ export type AccountExpansionTab =| 'notes'| 'users'| 'relationships'+ | 'feature_requests'| 'usage'| 'spend'| 'opportunities'@@ -20,6 +21,7 @@ export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = ['notes','users','relationships',+ 'feature_requests','usage','spend','opportunities',diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestAccountEvidenceModal.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestAccountEvidenceModal.tsxnew file mode 100644index 000000000000..4e65b3f29dd7--- /dev/null+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestAccountEvidenceModal.tsx@@ -0,0 +1,186 @@+import { useActions, useValues } from 'kea'++import {+ LemonBanner,+ LemonButton,+ LemonInput,+ LemonInputSelect,+ LemonLabel,+ LemonModal,+ LemonSelect,+ LemonTextArea,+} from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'++import { featureRequestsLogic } from './featureRequestsLogic'++const EVIDENCE_SOURCE_OPTIONS: { value: string; label: string }[] = [+ { value: 'conversation', label: 'Customer conversation' },+ { value: 'slack', label: 'Slack' },+ { value: 'zendesk', label: 'Zendesk' },+ { value: 'email', label: 'Email' },+ { value: 'meeting', label: 'Meeting' },+ { value: 'buildbetter', label: 'BuildBetter' },+ { value: 'other', label: 'Other' },+]++export function FeatureRequestAccountEvidenceModal(): JSX.Element {+ const {+ evidenceModalOpen,+ addingAccount,+ addAccountId,+ addAccountOptions,+ accountsLoading,+ accountsError,+ editingEvidenceId,+ evidenceSummary,+ evidenceQuote,+ evidenceSource,+ evidenceUrl,+ evidenceRequestedOn,+ evidenceError,+ savingEvidence,+ evidenceSaveDisabledReason,+ } = useValues(featureRequestsLogic)+ const {+ closeEvidence,+ setAddAccountId,+ setAccountSearch,+ loadAccounts,+ setEvidenceSummary,+ setEvidenceQuote,+ setEvidenceSource,+ setEvidenceUrl,+ setEvidenceRequestedOn,+ saveEvidence,+ removeEvidence,+ } = useActions(featureRequestsLogic)++ return (+ <LemonModal+ isOpen={evidenceModalOpen}+ onClose={closeEvidence}+ title={addingAccount ? 'Add account and evidence' : editingEvidenceId ? 'Edit evidence' : 'Add evidence'}+ width={560}+ footer={+ <>+ {editingEvidenceId && !addingAccount && (+ <LemonButton+ type="secondary"+ status="danger"+ onClick={() =>+ LemonDialog.open({+ title: 'Remove evidence?',+ description:+ 'This removes the evidence from the account. The change remains in request history.',+ primaryButton: {+ status: 'danger',+ children: 'Remove',+ onClick: removeEvidence,+ },+ secondaryButton: { children: 'Cancel' },+ })+ }+ loading={savingEvidence}+ className="mr-auto"+ >+ Remove evidence+ </LemonButton>+ )}+ <LemonButton type="secondary" onClick={closeEvidence}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={saveEvidence}+ loading={savingEvidence}+ disabledReason={evidenceSaveDisabledReason}+ data-attr={addingAccount ? 'save-feature-request-account' : 'save-feature-request-evidence'}+ >+ {addingAccount ? 'Add account' : 'Save evidence'}+ </LemonButton>+ </>+ }+ >+ <div className="flex flex-col gap-4">+ {accountsError && addingAccount && (+ <LemonBanner type="error" action={{ children: 'Try again', onClick: () => loadAccounts('') }}>+ {accountsError}+ </LemonBanner>+ )}+ {evidenceError && <LemonBanner type="error">{evidenceError}</LemonBanner>}+ {addingAccount && (+ <>+ <div className="flex flex-col gap-1">+ <LemonLabel>Account</LemonLabel>+ <LemonInputSelect+ mode="single"+ value={addAccountId ? [addAccountId] : []}+ onChange={(values) => setAddAccountId(values[0] ?? null)}+ onInputChange={setAccountSearch}+ options={addAccountOptions}+ placeholder="Search for an account"+ loading={accountsLoading}+ fullWidth+ />+ </div>+ <div className="font-medium">Evidence (optional)</div>+ </>+ )}+ <div className="flex flex-col gap-1">+ <LemonLabel>Summary</LemonLabel>+ <LemonTextArea+ value={evidenceSummary}+ onChange={setEvidenceSummary}+ placeholder="Summarize what this account needs"+ minRows={3}+ />+ </div>+ <div className="flex flex-col gap-1">+ <LemonLabel>Customer quote</LemonLabel>+ <LemonTextArea+ value={evidenceQuote}+ onChange={setEvidenceQuote}+ placeholder="Add the customer's words"+ minRows={3}+ />+ </div>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div className="flex flex-col gap-1">+ <LemonLabel>Source</LemonLabel>+ <LemonSelect+ value={evidenceSource}+ onChange={setEvidenceSource}+ options={EVIDENCE_SOURCE_OPTIONS}+ fullWidth+ />+ </div>+ <div className="flex flex-col gap-1">+ <LemonLabel>Request date</LemonLabel>+ <LemonCalendarSelectInput+ value={evidenceRequestedOn ? dayjs(evidenceRequestedOn) : null}+ onChange={(value) => setEvidenceRequestedOn(value?.format('YYYY-MM-DD') ?? null)}+ selectionPeriod="past"+ granularity="day"+ clearable+ placeholder="Select a date"+ />+ </div>+ </div>+ <div className="flex flex-col gap-1">+ <LemonLabel>Source URL</LemonLabel>+ <LemonInput+ type="url"+ value={evidenceUrl}+ onChange={setEvidenceUrl}+ placeholder="https://example.com/source"+ fullWidth+ />+ </div>+ </div>+ </LemonModal>+ )+}diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestAccountItem.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestAccountItem.tsxnew file mode 100644index 000000000000..8e4d1089dfd9--- /dev/null+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestAccountItem.tsx@@ -0,0 +1,60 @@+import { useActions } from 'kea'++import { IconBuilding, IconPlus } from '@posthog/icons'+import { LemonButton, Link } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import type { FeatureRequestAccountLinkApi } from '../../generated/api.schemas'+import { FeatureRequestEvidenceItem } from './FeatureRequestEvidenceItem'+import { featureRequestAccountElementId, featureRequestsLogic } from './featureRequestsLogic'++export function FeatureRequestAccountItem({+ accountLink,+ canEdit,+}: {+ accountLink: FeatureRequestAccountLinkApi+ canEdit: boolean+}): JSX.Element {+ const { openNewEvidence } = useActions(featureRequestsLogic)++ return (+ <div+ id={featureRequestAccountElementId(accountLink.account.id)}+ className="flex flex-col gap-3 rounded border border-primary p-3"+ >+ <div className="flex items-center justify-between gap-2">+ <Link+ to={urls.customerAnalyticsAccount(accountLink.account.id)}+ className="flex min-w-0 items-center gap-2 font-medium"+ >+ <IconBuilding className="size-4 shrink-0" />+ <span className="truncate">{accountLink.account.name}</span>+ </Link>+ {canEdit && (+ <LemonButton+ type="secondary"+ size="xsmall"+ icon={<IconPlus />}+ onClick={() => openNewEvidence(accountLink)}+ data-attr="add-feature-request-evidence"+ >+ Add evidence+ </LemonButton>+ )}+ </div>+ {accountLink.evidence.length > 0 && (+ <div className="flex flex-col gap-2">+ {accountLink.evidence.map((evidence) => (+ <FeatureRequestEvidenceItem+ key={evidence.id}+ accountLink={accountLink}+ evidence={evidence}+ canEdit={canEdit}+ />+ ))}+ </div>+ )}+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestDetail.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestDetail.tsxindex a6b579b64aa6..d63ef40ebb06 100644--- a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestDetail.tsx+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestDetail.tsx@@ -1,8 +1,16 @@import { useActions, useValues } from 'kea'import { combineUrl } from 'kea-router'-import { IconArchive, IconArrowLeft, IconBuilding, IconDocument, IconFolder, IconPencil } from '@posthog/icons'-import { LemonBanner, LemonButton, LemonTag, Link } from '@posthog/lemon-ui'+import {+ IconArchive,+ IconArrowLeft,+ IconBuilding,+ IconDocument,+ IconFolder,+ IconPencil,+ IconPlus,+} from '@posthog/icons'+import { LemonBanner, LemonButton, LemonTag } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'@@ -12,20 +20,41 @@ import { urls } from 'scenes/urls'import { AccessControlLevel, AccessControlResourceType } from '~/types'import type { FeatureRequestApi } from '../../generated/api.schemas'+import { FeatureRequestAccountEvidenceModal } from './FeatureRequestAccountEvidenceModal'+import { FeatureRequestAccountItem } from './FeatureRequestAccountItem'import { FeatureRequestDetailSection } from './FeatureRequestDetailSection'import { FeatureRequestEditModal } from './FeatureRequestEditModal'import { FeatureRequestHistorySection } from './FeatureRequestHistorySection'import { FeatureRequestPriorityBadge } from './FeatureRequestPriorityBadge'-import { featureRequestsLogic } from './featureRequestsLogic'+import { FEATURE_REQUEST_ACCOUNT_PREVIEW_SIZE, featureRequestsLogic } from './featureRequestsLogic'import { FeatureRequestStatusBadge } from './FeatureRequestStatusBadge'export function FeatureRequestDetail({ request }: { request: FeatureRequestApi }): JSX.Element {- const { mutatingArchive, listSearchParams } = useValues(featureRequestsLogic)- const { openEditRequest, archiveActiveRequest, restoreActiveRequest } = useActions(featureRequestsLogic)+ const {+ mutatingArchive,+ listSearchParams,+ activeRequestAccountLinks,+ activeRequestEvidenceCount,+ visibleActiveRequestAccountLinks,+ requestAccountsShowingAll,+ accountsEvidenceCollapsed,+ } = useValues(featureRequestsLogic)+ const {+ openEditRequest,+ openAddAccount,+ archiveActiveRequest,+ restoreActiveRequest,+ setRequestAccountsShowingAll,+ setAccountsEvidenceCollapsed,+ } = useActions(featureRequestsLogic)const editorDisabledReason = getAccessControlDisabledReason(AccessControlResourceType.CustomerAnalytics,AccessControlLevel.Editor)+ const canEdit = !request.is_archived && !editorDisabledReason+ const addAccountDisabledReason = request.is_archived+ ? 'Restore this request before adding an account'+ : editorDisabledReasonreturn (<div className="@container w-full max-w-[calc(160ch+5rem)] mx-auto px-6 py-5 text-sm">@@ -108,18 +137,6 @@ export function FeatureRequestDetail({ request }: { request: FeatureRequestApi }</div><aside className="flex flex-col min-w-0 gap-5">- <FeatureRequestDetailSection icon={<IconBuilding />} title="Account">- <Link- to={urls.customerAnalyticsAccount(request.account.id)}- className="flex items-center gap-3 rounded border border-primary bg-surface-primary px-3 py-2.5 text-default hover:text-primary"- >- <span className="flex size-8 shrink-0 items-center justify-center rounded bg-fill-highlight-50 text-secondary">- <IconBuilding className="size-4" />- </span>- <span className="truncate font-medium">{request.account.name}</span>- </Link>- </FeatureRequestDetailSection>-<FeatureRequestDetailSection icon={<IconFolder />} title="Product areas"><div className="flex flex-wrap gap-1.5">{request.product_areas.map((area) => (@@ -128,10 +145,63 @@ export function FeatureRequestDetail({ request }: { request: FeatureRequestApi }</div></FeatureRequestDetailSection>+ <FeatureRequestDetailSection+ icon={<IconBuilding />}+ title="Accounts and evidence"+ collapsible+ collapsed={accountsEvidenceCollapsed}+ onCollapsedChange={setAccountsEvidenceCollapsed}+ dataAttr="feature-request-accounts-evidence-collapse"+ meta={+ <span className="text-xs text-tertiary tabular-nums">+ {activeRequestAccountLinks.length}{' '}+ {activeRequestAccountLinks.length === 1 ? 'account' : 'accounts'} ·{' '}+ {activeRequestEvidenceCount}{' '}+ {activeRequestEvidenceCount === 1 ? 'evidence item' : 'evidence items'}+ </span>+ }+ action={+ <LemonButton+ type="secondary"+ size="xsmall"+ icon={<IconPlus />}+ onClick={openAddAccount}+ disabledReason={addAccountDisabledReason}+ data-attr="add-feature-request-account"+ >+ Add account+ </LemonButton>+ }+ >+ <div className="flex flex-col gap-2">+ {visibleActiveRequestAccountLinks.map((accountLink) => (+ <FeatureRequestAccountItem+ key={accountLink.id}+ accountLink={accountLink}+ canEdit={canEdit}+ />+ ))}+ {activeRequestAccountLinks.length > FEATURE_REQUEST_ACCOUNT_PREVIEW_SIZE && (+ <LemonButton+ type="tertiary"+ size="small"+ onClick={() => setRequestAccountsShowingAll(!requestAccountsShowingAll)}+ data-attr="feature-request-accounts-show-all"+ className="self-start"+ >+ {requestAccountsShowingAll+ ? `Show first ${FEATURE_REQUEST_ACCOUNT_PREVIEW_SIZE} accounts`+ : `Show all ${activeRequestAccountLinks.length} accounts`}+ </LemonButton>+ )}+ </div>+ </FeatureRequestDetailSection>+<FeatureRequestHistorySection requestId={request.id} /></aside></div><FeatureRequestEditModal />+ <FeatureRequestAccountEvidenceModal /></div>)}diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestDetailSection.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestDetailSection.tsxindex a4e04bf5570a..e163a51b25d2 100644--- a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestDetailSection.tsx+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestDetailSection.tsx@@ -8,8 +8,11 @@ interface FeatureRequestDetailSectionProps {title: stringchildren: ReactNodemeta?: ReactNode+ action?: ReactNodecollapsible?: booleandefaultCollapsed?: boolean+ collapsed?: boolean+ onCollapsedChange?: (collapsed: boolean) => voiddataAttr?: string}@@ -18,12 +21,17 @@ export function FeatureRequestDetailSection({title,children,meta,+ action,collapsible = false,defaultCollapsed = false,+ collapsed,+ onCollapsedChange,dataAttr,}: FeatureRequestDetailSectionProps): JSX.Element {- const [collapsed, setCollapsed] = useState(defaultCollapsed)- const open = !collapsible || !collapsed+ const [localCollapsed, setLocalCollapsed] = useState(defaultCollapsed)+ const effectiveCollapsed = collapsed ?? localCollapsed+ const setCollapsed = onCollapsedChange ?? setLocalCollapsed+ const open = !collapsible || !effectiveCollapsedconst header = (<div className="flex flex-1 items-center gap-3 min-w-0"><div className="flex items-center gap-2 min-w-0">@@ -43,7 +51,7 @@ export function FeatureRequestDetailSection({type="tertiary"size="small"fullWidth- onClick={() => setCollapsed(!collapsed)}+ onClick={() => setCollapsed(!effectiveCollapsed)}aria-expanded={open}sideIcon={open ? <IconCollapse /> : <IconExpand />}className="min-w-0 flex-1 -ml-2 -my-px"@@ -54,6 +62,7 @@ export function FeatureRequestDetailSection({) : (<div className="flex flex-1 items-center min-w-0 py-1">{header}</div>)}+ {action && <div className="shrink-0">{action}</div>}</div>{open && <div>{children}</div>}</section>diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestEditModal.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestEditModal.tsxindex 8af52c274e9a..39372d8d31e4 100644--- a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestEditModal.tsx+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestEditModal.tsx@@ -20,7 +20,7 @@ export function FeatureRequestEditModal(): JSX.Element {editRequestOpen,editTitle,editDescription,- editAccountId,+ editAccountIds,editProductAreaIds,editStatus,editPriority,@@ -37,7 +37,7 @@ export function FeatureRequestEditModal(): JSX.Element {closeEditRequest,setEditTitle,setEditDescription,- setEditAccountId,+ setEditAccountIds,setAccountSearch,setEditProductAreaIds,setEditStatus,@@ -109,14 +109,14 @@ export function FeatureRequestEditModal(): JSX.Element {<LemonTextArea value={editDescription} onChange={setEditDescription} minRows={5} /></div><div className="flex flex-col gap-1">- <LemonLabel>Account</LemonLabel>+ <LemonLabel>Accounts</LemonLabel><LemonInputSelect- mode="single"- value={editAccountId ? [editAccountId] : []}- onChange={(values) => setEditAccountId(values[0] ?? null)}+ mode="multiple"+ value={editAccountIds}+ onChange={setEditAccountIds}onInputChange={setAccountSearch}options={accountOptions}- placeholder="Search for an account"+ placeholder="Search for accounts"loading={accountsLoading}fullWidth/>diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestEvidenceItem.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestEvidenceItem.tsxnew file mode 100644index 000000000000..ce544aba91d7--- /dev/null+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestEvidenceItem.tsx@@ -0,0 +1,71 @@+import { useActions } from 'kea'++import { IconPencil } from '@posthog/icons'+import { LemonButton, LemonCard, Link } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'++import type { FeatureRequestAccountLinkApi, FeatureRequestEvidenceApi } from '../../generated/api.schemas'+import { featureRequestEvidenceElementId, featureRequestsLogic } from './featureRequestsLogic'++const EVIDENCE_SOURCE_LABELS: Record<string, string> = {+ conversation: 'Customer conversation',+ slack: 'Slack',+ zendesk: 'Zendesk',+ email: 'Email',+ meeting: 'Meeting',+ buildbetter: 'BuildBetter',+ other: 'Other',+}++export function FeatureRequestEvidenceItem({+ accountLink,+ evidence,+ canEdit,+}: {+ accountLink: FeatureRequestAccountLinkApi+ evidence: FeatureRequestEvidenceApi+ canEdit: boolean+}): JSX.Element {+ const { openEditEvidence } = useActions(featureRequestsLogic)++ return (+ <div id={featureRequestEvidenceElementId(evidence.id)}>+ <LemonCard hoverEffect={false} className="p-3 shadow-none">+ <div className="flex items-start justify-between gap-2">+ <div className="flex min-w-0 flex-col gap-2">+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-tertiary">+ <span>{EVIDENCE_SOURCE_LABELS[evidence.evidence_source] ?? evidence.evidence_source}</span>+ {evidence.requested_on && <span>{evidence.requested_on}</span>}+ {evidence.source_url && (+ <Link to={evidence.source_url} target="_blank">+ Open source+ </Link>+ )}+ </div>+ {evidence.summary && (+ <p className="m-0 whitespace-pre-wrap text-secondary">{evidence.summary}</p>+ )}+ {evidence.customer_quote && (+ <blockquote className="m-0 border-l-2 pl-3 text-secondary whitespace-pre-wrap">+ {evidence.customer_quote}+ </blockquote>+ )}+ <span className="text-xs text-tertiary">+ Added <TZLabel time={evidence.created_at} />+ </span>+ </div>+ {canEdit && (+ <LemonButton+ type="tertiary"+ size="xsmall"+ icon={<IconPencil />}+ onClick={() => openEditEvidence(accountLink, evidence)}+ aria-label="Edit evidence"+ />+ )}+ </div>+ </LemonCard>+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistory.test.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistory.test.tsxnew file mode 100644index 000000000000..6b6a77898c1b--- /dev/null+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistory.test.tsx@@ -0,0 +1,75 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import type { FeatureRequestHistoryApi } from '../../generated/api.schemas'+import { FeatureRequestHistory } from './FeatureRequestHistory'++const history: FeatureRequestHistoryApi[] = [+ {+ id: 'history-evidence',+ changes: [+ {+ field: 'evidence',+ before: null,+ after: {+ id: 'evidence-1',+ account: { id: 'account-1', name: 'Acme' },+ summary: 'Acme needs weekly exports.',+ customer_quote: '',+ source: 'conversation',+ source_url: '',+ requested_on: '2026-01-03',+ },+ },+ ],+ is_initial: false,+ change_source: 'manual',+ actor_id: 1,+ actor_name: 'Test user',+ changed_at: '2026-01-03T00:00:00Z',+ },+ {+ id: 'history-account',+ changes: [+ {+ field: 'accounts',+ before: [{ id: 'account-1', name: 'Acme' }],+ after: [+ { id: 'account-1', name: 'Acme' },+ { id: 'account-2', name: 'Globex' },+ ],+ },+ ],+ is_initial: false,+ change_source: 'manual',+ actor_id: 1,+ actor_name: 'Test user',+ changed_at: '2026-01-02T00:00:00Z',+ },+]++describe('FeatureRequestHistory', () => {+ afterEach(cleanup)++ it('reveals the account or evidence referenced by a history entry', () => {+ const onShowTarget = jest.fn()+ render(+ <FeatureRequestHistory+ history={history}+ loading={false}+ error={null}+ showingAll+ onRetry={jest.fn()}+ onSetShowingAll={jest.fn()}+ onShowTarget={onShowTarget}+ />+ )++ fireEvent.click(screen.getByText('Evidence:'))+ expect(onShowTarget).toHaveBeenLastCalledWith('account-1', 'evidence-1')++ fireEvent.click(screen.getByText('Accounts:'))+ expect(onShowTarget).toHaveBeenLastCalledWith('account-2', undefined)+ })+})diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistory.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistory.tsxindex 84cca830ed18..565b499dd8e6 100644--- a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistory.tsx+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistory.tsx@@ -14,6 +14,8 @@ import type {import { featureRequestPriorityLabel, featureRequestStatusLabel } from './featureRequestOptions'type RelationSnapshot = { id: string; name: string }+type EvidenceSnapshot = { id: string; account: RelationSnapshot }+type ShowHistoryTarget = (accountId: string, evidenceId?: string) => voidconst FEATURE_REQUEST_STATUSES = new Set<string>(['requested', 'planned', 'completed', 'wont_fix', 'duplicate'])const FEATURE_REQUEST_PRIORITIES = new Set<string>(['high', 'medium', 'low'])@@ -39,6 +41,14 @@ function accountSnapshotName(value: unknown): string {: 'No account'}+function evidenceSnapshot(value: unknown): EvidenceSnapshot | null {+ if (typeof value !== 'object' || value === null || !('id' in value) || typeof value.id !== 'string') {+ return null+ }+ const account = 'account' in value ? relationSnapshot(value.account) : null+ return account ? { id: value.id, account } : null+}+function relationSnapshots(value: unknown): RelationSnapshot[] {return Array.isArray(value)? value.map(relationSnapshot).filter((snapshot): snapshot is RelationSnapshot => snapshot !== null)@@ -57,10 +67,37 @@ function priorityName(value: unknown): string {: 'Unknown priority'}-function scalarChange(label: string, before: string, after: string, isInitial: boolean): JSX.Element {+function historyTargetLabel(+ label: string,+ target: { accountId: string; evidenceId?: string } | null,+ onShowTarget: ShowHistoryTarget+): JSX.Element {+ if (!target) {+ return <span className="font-medium">{label}:</span>+ }+ return (+ <button+ type="button"+ onClick={() => onShowTarget(target.accountId, target.evidenceId)}+ data-attr="feature-request-history-target"+ className="m-0 cursor-pointer border-0 bg-transparent p-0 font-medium text-current hover:text-accent"+ >+ {label}:+ </button>+ )+}++function scalarChange(+ label: string,+ before: string,+ after: string,+ isInitial: boolean,+ onShowTarget: ShowHistoryTarget,+ target: { accountId: string; evidenceId?: string } | null = null+): JSX.Element {return (<div>- <span className="font-medium">{label}:</span>{' '}+ {historyTargetLabel(label, target, onShowTarget)}{' '}{isInitial ? (after) : (@@ -89,6 +126,7 @@ function historyMarker(entry: FeatureRequestHistoryApi): ComponentType<{ classNacase 'priority':return IconFlagcase 'account':+ case 'accounts':return IconBuildingcase 'product_areas':return IconFolder@@ -97,44 +135,138 @@ function historyMarker(entry: FeatureRequestHistoryApi): ComponentType<{ classNa}}-function describeChange(change: FeatureRequestHistoryChangeApi, isInitial: boolean): JSX.Element | null {- if (change.field === 'status') {- return scalarChange('Status', statusName(change.before), statusName(change.after), isInitial)- }- if (change.field === 'priority') {- return scalarChange('Priority', priorityName(change.before), priorityName(change.after), isInitial)- }- if (change.field === 'account') {- return scalarChange('Account', accountSnapshotName(change.before), accountSnapshotName(change.after), isInitial)+function describeAccountChange(+ change: FeatureRequestHistoryChangeApi,+ isInitial: boolean,+ onShowTarget: ShowHistoryTarget+): JSX.Element {+ const before = relationSnapshot(change.before)+ const after = relationSnapshot(change.after)+ const target = after ?? before+ return scalarChange(+ 'Account',+ accountSnapshotName(change.before),+ accountSnapshotName(change.after),+ isInitial,+ onShowTarget,+ target ? { accountId: target.id } : null+ )+}++function describeAccountsChange(+ change: FeatureRequestHistoryChangeApi,+ isInitial: boolean,+ onShowTarget: ShowHistoryTarget+): JSX.Element {+ const before = relationSnapshots(change.before)+ const after = relationSnapshots(change.after)+ const beforeIds = new Set(before.map((account) => account.id))+ const afterIds = new Set(after.map((account) => account.id))+ const added = after.filter((account) => !beforeIds.has(account.id))+ const removed = before.filter((account) => !afterIds.has(account.id))+ const target = added[0] ?? removed[0] ?? after[0] ?? before[0]+ const label = historyTargetLabel('Accounts', target ? { accountId: target.id } : null, onShowTarget)++ if (isInitial) {+ return (+ <div>+ {label} {after.map((account) => account.name).join(', ')}+ </div>+ )}- if (change.field === 'product_areas') {- const before = relationSnapshots(change.before)- const after = relationSnapshots(change.after)- if (isInitial) {- return (- <div>- <span className="font-medium">Product areas:</span>{' '}- {after.map((area) => area.name).join(', ') || 'None'}- </div>- )- }- const beforeIds = new Set(before.map((area) => area.id))- const afterIds = new Set(after.map((area) => area.id))- const added = after.filter((area) => !beforeIds.has(area.id)).map((area) => area.name)- const removed = before.filter((area) => !afterIds.has(area.id)).map((area) => area.name)+ return (+ <div>+ {label}{' '}+ {[+ added.length ? `added ${added.map((account) => account.name).join(', ')}` : null,+ removed.length ? `removed ${removed.map((account) => account.name).join(', ')}` : null,+ ]+ .filter(Boolean)+ .join('; ')}+ </div>+ )+}++function describeEvidenceChange(change: FeatureRequestHistoryChangeApi, onShowTarget: ShowHistoryTarget): JSX.Element {+ const before = evidenceSnapshot(change.before)+ const after = evidenceSnapshot(change.after)+ const target = after ?? before+ return (+ <div>+ {historyTargetLabel(+ 'Evidence',+ target ? { accountId: target.account.id, evidenceId: target.id } : null,+ onShowTarget+ )}{' '}+ {before && after+ ? `updated for ${after.account.name}`+ : after+ ? `added for ${after.account.name}`+ : `removed for ${before?.account.name ?? 'an account'}`}+ </div>+ )+}++function describeProductAreasChange(+ change: FeatureRequestHistoryChangeApi,+ isInitial: boolean,+ onShowTarget: ShowHistoryTarget+): JSX.Element {+ const before = relationSnapshots(change.before)+ const after = relationSnapshots(change.after)+ const label = historyTargetLabel('Product areas', null, onShowTarget)++ if (isInitial) {return (<div>- <span className="font-medium">Product areas:</span>{' '}- {[- added.length ? `added ${added.join(', ')}` : null,- removed.length ? `removed ${removed.join(', ')}` : null,- ]- .filter(Boolean)- .join('; ')}+ {label} {after.map((area) => area.name).join(', ') || 'None'}</div>)}- return null+ const beforeIds = new Set(before.map((area) => area.id))+ const afterIds = new Set(after.map((area) => area.id))+ const added = after.filter((area) => !beforeIds.has(area.id)).map((area) => area.name)+ const removed = before.filter((area) => !afterIds.has(area.id)).map((area) => area.name)+ return (+ <div>+ {label}{' '}+ {[+ added.length ? `added ${added.join(', ')}` : null,+ removed.length ? `removed ${removed.join(', ')}` : null,+ ]+ .filter(Boolean)+ .join('; ')}+ </div>+ )+}++function describeChange(+ change: FeatureRequestHistoryChangeApi,+ isInitial: boolean,+ onShowTarget: ShowHistoryTarget+): JSX.Element | null {+ switch (change.field) {+ case 'status':+ return scalarChange('Status', statusName(change.before), statusName(change.after), isInitial, onShowTarget)+ case 'priority':+ return scalarChange(+ 'Priority',+ priorityName(change.before),+ priorityName(change.after),+ isInitial,+ onShowTarget+ )+ case 'account':+ return describeAccountChange(change, isInitial, onShowTarget)+ case 'accounts':+ return describeAccountsChange(change, isInitial, onShowTarget)+ case 'evidence':+ return describeEvidenceChange(change, onShowTarget)+ case 'product_areas':+ return describeProductAreasChange(change, isInitial, onShowTarget)+ default:+ return null+ }}export interface FeatureRequestHistoryProps {@@ -144,6 +276,7 @@ export interface FeatureRequestHistoryProps {showingAll: booleanonRetry: () => voidonSetShowingAll: (showingAll: boolean) => void+ onShowTarget: ShowHistoryTarget}export function FeatureRequestHistory({@@ -153,6 +286,7 @@ export function FeatureRequestHistory({showingAll,onRetry,onSetShowingAll,+ onShowTarget,}: FeatureRequestHistoryProps): JSX.Element {if (loading) {return (@@ -208,7 +342,9 @@ export function FeatureRequestHistory({<LemonCard hoverEffect={false} className="w-full p-2 shadow-none"><div className="flex flex-col gap-1 text-secondary">{entry.changes.map((change) => (- <div key={change.field}>{describeChange(change, entry.is_initial)}</div>+ <div key={change.field}>+ {describeChange(change, entry.is_initial, onShowTarget)}+ </div>))}</div></LemonCard>diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistorySection.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistorySection.tsxindex 630ee3bff477..b3484f378275 100644--- a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistorySection.tsx+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistorySection.tsx@@ -9,7 +9,7 @@ import { featureRequestsLogic } from './featureRequestsLogic'export function FeatureRequestHistorySection({ requestId }: { requestId: string }): JSX.Element {const { requestHistory, requestHistoryLoading, requestHistoryError, requestHistoryShowingAll } =useValues(featureRequestsLogic)- const { loadRequestHistory, setRequestHistoryShowingAll } = useActions(featureRequestsLogic)+ const { loadRequestHistory, setRequestHistoryShowingAll, showHistoryTarget } = useActions(featureRequestsLogic)return (<FeatureRequestDetailSection@@ -32,6 +32,7 @@ export function FeatureRequestHistorySection({ requestId }: { requestId: stringshowingAll={requestHistoryShowingAll}onRetry={() => loadRequestHistory(requestId)}onSetShowingAll={setRequestHistoryShowingAll}+ onShowTarget={showHistoryTarget}/></FeatureRequestDetailSection>)diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestList.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestList.tsxindex b03236b40fa1..bb4ba133ef2b 100644--- a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestList.tsx+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestList.tsx@@ -57,9 +57,9 @@ export function FeatureRequestList(): JSX.Element {),},{- title: 'Account',- key: 'account',- render: (_, request) => request.account.name,+ title: 'Accounts',+ key: 'account_links',+ render: (_, request) => request.account_links.map((link) => link.account.name).join(', '),},{title: 'Product areas',diff --git a/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.test.ts b/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.test.tsindex 8c92c6e17897..0dc2164c2769 100644--- a/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.test.ts+++ b/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.test.ts@@ -1,8 +1,10 @@import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import { ApiError } from 'lib/api'+import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -36,7 +38,18 @@ const createdRequest: FeatureRequestApi = {archived_at: null,archived_by: null,version: 1,+ can_update: true,account: { id: 'account-1', name: 'Acme' },+ account_links: [+ {+ id: 'account-link-1',+ account: { id: 'account-1', name: 'Acme' },+ evidence: [],+ evidence_count: 0,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ },+ ],product_areas: [{id: 'area-1',@@ -81,14 +94,14 @@ describe('featureRequestsLogic', () => {logic.actions.openCreateRequest()logic.actions.setTitle(createdRequest.title)logic.actions.setDescription(createdRequest.description)- logic.actions.setAccountId(createdRequest.account.id)+ logic.actions.setAccountId(createdRequest.account_links[0].account.id)logic.actions.setProductAreaIds(['area-1'])await expectLogic(logic, () => logic.actions.submitRequest()).toFinishAllListeners()expect(logic.values.title).toBe(createdRequest.title)expect(logic.values.description).toBe(createdRequest.description)- expect(logic.values.accountId).toBe(createdRequest.account.id)+ expect(logic.values.accountId).toBe(createdRequest.account_links[0].account.id)expect(logic.values.productAreaIds).toEqual(['area-1'])expect(logic.values.createRequestOpen).toBe(true)expect(logic.values.submittingRequest).toBe(false)@@ -277,6 +290,200 @@ describe('featureRequestsLogic', () => {expect(logic.values.editIsStale).toBe(false)})+ it('adds evidence to the selected account link and refreshes request state', async () => {+ const evidenceRequest: FeatureRequestApi = {+ ...createdRequest,+ version: 2,+ account_links: [+ {+ ...createdRequest.account_links[0],+ evidence: [+ {+ id: 'evidence-1',+ summary: 'Acme needs weekly exports.',+ customer_quote: '',+ evidence_source: 'conversation',+ source_url: '',+ requested_on: null,+ created_by: 1,+ updated_by: 1,+ created_at: '2026-01-02T00:00:00Z',+ updated_at: '2026-01-02T00:00:00Z',+ },+ ],+ },+ ],+ }+ const addSpy = jest.spyOn(generatedApi, 'featureRequestsAddEvidenceCreate').mockResolvedValue(evidenceRequest)+ await expectLogic(logic, () => logic.actions.setActiveRequestId(createdRequest.id)).toFinishAllListeners()+ logic.actions.loadActiveRequestSuccess(createdRequest)+ logic.actions.openNewEvidence(createdRequest.account_links[0])+ logic.actions.setEvidenceSummary('Acme needs weekly exports.')++ await expectLogic(logic, () => logic.actions.saveEvidence()).toFinishAllListeners()++ expect(addSpy).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), createdRequest.id, {+ expected_version: 1,+ account_link_id: 'account-link-1',+ summary: 'Acme needs weekly exports.',+ customer_quote: '',+ evidence_source: 'conversation',+ source_url: '',+ requested_on: null,+ })+ expect(logic.values.activeRequest).toEqual(evidenceRequest)+ expect(logic.values.evidenceModalOpen).toBe(false)+ expect(logic.values.savingEvidence).toBe(false)+ })++ it('adds an account and its first evidence in one request', async () => {+ const otherAccount: AccountApi = {+ ...account,+ id: 'account-2',+ name: 'Globex',+ }+ const updatedRequest: FeatureRequestApi = {+ ...createdRequest,+ version: 2,+ account_links: [+ ...createdRequest.account_links,+ {+ id: 'account-link-2',+ account: { id: otherAccount.id, name: otherAccount.name },+ evidence: [+ {+ id: 'evidence-2',+ summary: 'Globex needs a weekly export.',+ customer_quote: '',+ evidence_source: 'meeting',+ source_url: '',+ requested_on: null,+ created_by: 1,+ updated_by: 1,+ created_at: '2026-01-03T00:00:00Z',+ updated_at: '2026-01-03T00:00:00Z',+ },+ ],+ evidence_count: 1,+ created_at: '2026-01-03T00:00:00Z',+ updated_at: '2026-01-03T00:00:00Z',+ },+ ],+ }+ const addAccountSpy = jest+ .spyOn(generatedApi, 'featureRequestsAddAccountCreate')+ .mockResolvedValue(updatedRequest)+ logic.actions.loadActiveRequestSuccess(createdRequest)+ logic.actions.loadAccountsSuccess([account, otherAccount])+ logic.actions.openAddAccount()+ logic.actions.setAddAccountId(otherAccount.id)+ logic.actions.setEvidenceSummary('Globex needs a weekly export.')+ logic.actions.setEvidenceSource('meeting')+ expect(logic.values.addAccountOptions).toEqual([{ key: otherAccount.id, label: otherAccount.name }])++ await expectLogic(logic, () => logic.actions.saveEvidence()).toFinishAllListeners()++ expect(addAccountSpy).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), createdRequest.id, {+ expected_version: 1,+ account_id: otherAccount.id,+ evidence: {+ summary: 'Globex needs a weekly export.',+ customer_quote: '',+ evidence_source: 'meeting',+ source_url: '',+ requested_on: null,+ },+ })+ expect(logic.values.activeRequest).toEqual(updatedRequest)+ expect(logic.values.evidenceModalOpen).toBe(false)+ })++ it('orders accounts by evidence count', () => {+ const evidence = {+ id: 'evidence-1',+ summary: 'Requested export',+ customer_quote: '',+ evidence_source: 'conversation',+ source_url: '',+ requested_on: '2026-01-03',+ created_by: 1,+ updated_by: 1,+ created_at: '2026-01-03T00:00:00Z',+ updated_at: '2026-01-03T00:00:00Z',+ }+ const requestWithEvidence: FeatureRequestApi = {+ ...createdRequest,+ account_links: [+ {+ ...createdRequest.account_links[0],+ account: { id: 'account-1', name: 'No evidence' },+ evidence: [],+ },+ {+ ...createdRequest.account_links[0],+ id: 'account-link-2',+ account: { id: 'account-2', name: 'One evidence' },+ evidence: [evidence],+ },+ {+ ...createdRequest.account_links[0],+ id: 'account-link-3',+ account: { id: 'account-3', name: 'Two evidences' },+ evidence: [evidence, { ...evidence, id: 'evidence-2' }],+ },+ ],+ }++ logic.actions.loadActiveRequestSuccess(requestWithEvidence)++ expect(logic.values.activeRequestAccountLinks.map((link) => link.account.name)).toEqual([+ 'Two evidences',+ 'One evidence',+ 'No evidence',+ ])+ })++ it('shows five account cards before expanding the full list', () => {+ const requestWithAccounts: FeatureRequestApi = {+ ...createdRequest,+ account_links: Array.from({ length: 6 }, (_, index) => ({+ ...createdRequest.account_links[0],+ id: `account-link-${index + 1}`,+ account: { id: `account-${index + 1}`, name: `Account ${index + 1}` },+ })),+ }++ logic.actions.loadActiveRequestSuccess(requestWithAccounts)++ expect(logic.values.visibleActiveRequestAccountLinks).toHaveLength(5)++ logic.actions.setRequestAccountsShowingAll(true)+ expect(logic.values.visibleActiveRequestAccountLinks).toHaveLength(6)+ })++ it('opens the accounts section for a history target', () => {+ logic.actions.setAccountsEvidenceCollapsed(true)++ logic.actions.showHistoryTarget('account-1', 'evidence-1')++ expect(logic.values.accountsEvidenceCollapsed).toBe(false)+ expect(logic.values.requestAccountsShowingAll).toBe(true)+ })++ it('opens the account evidence form from an account page link', () => {+ router.actions.push(urls.customerAnalyticsFeatureRequests(createdRequest.id), {+ evidence_account: createdRequest.account.id,+ })++ logic.actions.loadActiveRequestSuccess(createdRequest)++ expect(logic.values.evidenceModalOpen).toBe(true)+ expect(logic.values.evidenceAccountLinkId).toBe(createdRequest.account_links[0].id)++ logic.actions.closeEvidence()+ expect(router.values.searchParams.evidence_account).toBeUndefined()+ })+it('ignores a second submit while the first request is in flight', async () => {let resolveCreate: (request: FeatureRequestApi) => void = () => undefinedconst createPromise = new Promise<FeatureRequestApi>((resolve) => {@@ -286,7 +493,7 @@ describe('featureRequestsLogic', () => {logic.actions.openCreateRequest()logic.actions.setTitle(createdRequest.title)logic.actions.setDescription(createdRequest.description)- logic.actions.setAccountId(createdRequest.account.id)+ logic.actions.setAccountId(createdRequest.account_links[0].account.id)logic.actions.setProductAreaIds(['area-1'])logic.actions.submitRequest()diff --git a/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.ts b/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.tsindex a7c2ac5c9e64..42f6f8fbcc6b 100644--- a/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.ts+++ b/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.ts@@ -14,18 +14,24 @@ import {featureRequestProductAreasCreate,featureRequestProductAreasList,featureRequestProductAreasPartialUpdate,+ featureRequestsAddAccountCreate,+ featureRequestsAddEvidenceCreate,featureRequestsArchiveCreate,featureRequestsCreate,featureRequestsHistoryList,featureRequestsList,+ featureRequestsRemoveEvidenceCreate,featureRequestsRestoreCreate,featureRequestsRetrieve,featureRequestsUpdate,+ featureRequestsUpdateEvidenceCreate,} from '../../generated/api'import type {AccountApi,FeatureRequestAccountApi,+ FeatureRequestAccountLinkApi,FeatureRequestApi,+ FeatureRequestEvidenceApi,FeatureRequestHistoryApi,FeatureRequestProductAreaApi,FeatureRequestStatusEnumApi,@@ -42,6 +48,15 @@ import {} from './featureRequestOptions'export const FEATURE_REQUESTS_PAGE_SIZE = 20+export const FEATURE_REQUEST_ACCOUNT_PREVIEW_SIZE = 5++export function featureRequestAccountElementId(accountId: string): string {+ return `feature-request-account-${accountId}`+}++export function featureRequestEvidenceElementId(evidenceId: string): string {+ return `feature-request-evidence-${evidenceId}`+}const FILTER_URL_KEYS = ['search', 'status', 'priority', 'product_area', 'account', 'archive', 'sort', 'page'] as constconst VALID_STATUSES = new Set(FEATURE_REQUEST_STATUS_OPTIONS.map((option) => option.value))@@ -151,17 +166,26 @@ export interface featureRequestsLogicValues {accountSearch: stringaccounts: AccountApi[]accountsError: string | null+ accountsEvidenceCollapsed: booleanaccountsLoading: booleanactiveProductAreas: FeatureRequestProductAreaApi[]activeRequest: FeatureRequestApi | null+ activeRequestAccountLinks: FeatureRequestAccountLinkApi[]activeRequestError: string | null+ activeRequestEvidenceCount: numberactiveRequestId: string | nullactiveRequestLoading: boolean+ addAccountId: string | null+ addAccountOptions: {+ key: string+ label: string+ }[]+ addingAccount: booleanarchiveState: FeatureRequestArchiveStatecreateRequestOpen: booleancurrentTeamId: stringdescription: string- editAccountId: string | null+ editAccountIds: string[]editDescription: stringeditDisabledReason: string | undefinededitError: string | null@@ -177,7 +201,17 @@ export interface featureRequestsLogicValues {editRequestOpen: booleaneditStatus: FeatureRequestStatusEnumApieditTitle: string+ editingEvidenceId: string | nulleditingProductAreaId: string | null+ evidenceAccountLinkId: string | null+ evidenceError: string | null+ evidenceModalOpen: boolean+ evidenceQuote: string+ evidenceRequestedOn: string | null+ evidenceSaveDisabledReason: string | undefined+ evidenceSource: string+ evidenceSummary: string+ evidenceUrl: stringfeatureRequestsError: string | nullfeatureRequestsPage: numberfeatureRequestsResponse: PaginatedFeatureRequestListApi@@ -205,11 +239,13 @@ export interface featureRequestsLogicValues {productAreasError: string | nullproductAreasLoading: booleanproductAreasOpen: boolean+ requestAccountsShowingAll: booleanrequestHistory: FeatureRequestHistoryApi[]requestHistoryError: string | nullrequestHistoryLoading: booleanrequestHistoryShowingAll: booleanrequestOrdering: FeatureRequestOrdering+ savingEvidence: booleansavingProductArea: booleansavingRequestChanges: booleansearchQuery: string@@ -218,6 +254,7 @@ export interface featureRequestsLogicValues {submitDisabledReason: string | undefinedsubmittingRequest: booleantitle: string+ visibleActiveRequestAccountLinks: FeatureRequestAccountLinkApi[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -234,6 +271,9 @@ export interface featureRequestsLogicActions {closeEditRequest: () => {value: true}+ closeEvidence: () => {+ value: true+ }closeProductAreaForm: () => {value: true}@@ -315,21 +355,40 @@ export interface featureRequestsLogicActions {requestHistory: FeatureRequestHistoryApi[]payload?: string}+ openAddAccount: () => {+ value: true+ }openCreateRequest: () => {value: true}+ openEditEvidence: (+ accountLink: FeatureRequestAccountLinkApi,+ evidence: FeatureRequestEvidenceApi+ ) => {+ accountLink: FeatureRequestAccountLinkApi+ evidence: FeatureRequestEvidenceApi+ }openEditRequest: (featureRequest: FeatureRequestApi) => {featureRequest: FeatureRequestApi}+ openNewEvidence: (accountLink: FeatureRequestAccountLinkApi) => {+ accountLink: FeatureRequestAccountLinkApi+ }openProductAreas: () => {value: true}reloadLatestForEdit: () => {value: true}+ removeEvidence: () => {+ value: true+ }restoreActiveRequest: () => {value: true}+ saveEvidence: () => {+ value: true+ }saveProductArea: () => {value: true}@@ -342,17 +401,23 @@ export interface featureRequestsLogicActions {setAccountSearch: (accountSearch: string) => {accountSearch: string}+ setAccountsEvidenceCollapsed: (collapsed: boolean) => {+ collapsed: boolean+ }setActiveRequestId: (requestId: string | null) => {requestId: string | null}+ setAddAccountId: (accountId: string | null) => {+ accountId: string | null+ }setArchiveState: (archiveState: FeatureRequestArchiveState) => {archiveState: FeatureRequestArchiveState}setDescription: (description: string) => {description: string}- setEditAccountId: (editAccountId: string | null) => {- editAccountId: string | null+ setEditAccountIds: (editAccountIds: string[]) => {+ editAccountIds: string[]}setEditDescription: (editDescription: string) => {editDescription: string@@ -378,6 +443,24 @@ export interface featureRequestsLogicActions {setEditTitle: (editTitle: string) => {editTitle: string}+ setEvidenceError: (evidenceError: string | null) => {+ evidenceError: string | null+ }+ setEvidenceQuote: (evidenceQuote: string) => {+ evidenceQuote: string+ }+ setEvidenceRequestedOn: (evidenceRequestedOn: string | null) => {+ evidenceRequestedOn: string | null+ }+ setEvidenceSource: (evidenceSource: string) => {+ evidenceSource: string+ }+ setEvidenceSummary: (evidenceSummary: string) => {+ evidenceSummary: string+ }+ setEvidenceUrl: (evidenceUrl: string) => {+ evidenceUrl: string+ }setFeatureRequestsPage: (page: number) => {page: number}@@ -405,12 +488,18 @@ export interface featureRequestsLogicActions {setProductAreaSearch: (productAreaSearch: string) => {productAreaSearch: string}+ setRequestAccountsShowingAll: (showingAll: boolean) => {+ showingAll: boolean+ }setRequestHistoryShowingAll: (showingAll: boolean) => {showingAll: boolean}setRequestOrdering: (requestOrdering: FeatureRequestOrdering) => {requestOrdering: FeatureRequestOrdering}+ setSavingEvidence: (savingEvidence: boolean) => {+ savingEvidence: boolean+ }setSavingProductArea: (savingProductArea: boolean) => {savingProductArea: boolean}@@ -429,6 +518,13 @@ export interface featureRequestsLogicActions {setTitle: (title: string) => {title: string}+ showHistoryTarget: (+ accountId: string,+ evidenceId?: string+ ) => {+ accountId: string+ evidenceId: string | undefined+ }startEditingProductArea: (productArea: FeatureRequestProductAreaApi) => {productArea: FeatureRequestProductAreaApi}@@ -463,11 +559,28 @@ export interface featureRequestsLogicMeta {) => FeatureRequestProductAreaApi[]accountOptions: (accounts: AccountApi[],- selectedAccount: FeatureRequestAccountApi | null+ selectedAccount: FeatureRequestAccountApi | null,+ activeRequest: FeatureRequestApi | null) => {key: stringlabel: string}[]+ addAccountOptions: (+ accountOptions: {+ key: string+ label: string+ }[],+ activeRequest: FeatureRequestApi | null+ ) => {+ key: string+ label: string+ }[]+ activeRequestAccountLinks: (activeRequest: FeatureRequestApi | null) => FeatureRequestAccountLinkApi[]+ visibleActiveRequestAccountLinks: (+ activeRequestAccountLinks: FeatureRequestAccountLinkApi[],+ requestAccountsShowingAll: boolean+ ) => FeatureRequestAccountLinkApi[]+ activeRequestEvidenceCount: (activeRequestAccountLinks: FeatureRequestAccountLinkApi[]) => numberproductAreaOptions: (activeProductAreas: FeatureRequestProductAreaApi[]) => {key: stringlabel: string@@ -488,10 +601,18 @@ export interface featureRequestsLogicMeta {) => string | undefinededitDisabledReason: (editTitle: string,- editAccountId: string | null,+ editAccountIds: string[],editProductAreaIds: string[],savingRequestChanges: boolean) => string | undefined+ evidenceSaveDisabledReason: (+ addingAccount: boolean,+ addAccountId: string | null,+ evidenceSummary: string,+ evidenceQuote: string,+ evidenceUrl: string,+ savingEvidence: boolean+ ) => string | undefinedproductAreaSaveDisabledReason: (productAreaName: string, savingProductArea: boolean) => string | undefinedhasActiveFilters: (searchQuery: string,@@ -562,7 +683,7 @@ export const featureRequestsLogic = kea<featureRequestsLogicType>([closeEditRequest: true,setEditTitle: (editTitle: string) => ({ editTitle }),setEditDescription: (editDescription: string) => ({ editDescription }),- setEditAccountId: (editAccountId: string | null) => ({ editAccountId }),+ setEditAccountIds: (editAccountIds: string[]) => ({ editAccountIds }),setEditProductAreaIds: (editProductAreaIds: string[]) => ({ editProductAreaIds }),setEditStatus: (editStatus: FeatureRequestStatusEnumApi) => ({ editStatus }),setEditPriority: (editPriority: RequestPriorityEnumApi | null) => ({ editPriority }),@@ -576,6 +697,26 @@ export const featureRequestsLogic = kea<featureRequestsLogicType>([restoreActiveRequest: true,setMutatingArchive: (mutatingArchive: boolean) => ({ mutatingArchive }),setRequestHistoryShowingAll: (showingAll: boolean) => ({ showingAll }),+ setRequestAccountsShowingAll: (showingAll: boolean) => ({ showingAll }),+ setAccountsEvidenceCollapsed: (collapsed: boolean) => ({ collapsed }),+ showHistoryTarget: (accountId: string, evidenceId?: string) => ({ accountId, evidenceId }),+ openAddAccount: true,+ setAddAccountId: (accountId: string | null) => ({ accountId }),+ openNewEvidence: (accountLink: FeatureRequestAccountLinkApi) => ({ accountLink }),+ openEditEvidence: (accountLink: FeatureRequestAccountLinkApi, evidence: FeatureRequestEvidenceApi) => ({+ accountLink,+ evidence,+ }),+ closeEvidence: true,+ setEvidenceSummary: (evidenceSummary: string) => ({ evidenceSummary }),+ setEvidenceQuote: (evidenceQuote: string) => ({ evidenceQuote }),+ setEvidenceSource: (evidenceSource: string) => ({ evidenceSource }),+ setEvidenceUrl: (evidenceUrl: string) => ({ evidenceUrl }),+ setEvidenceRequestedOn: (evidenceRequestedOn: string | null) => ({ evidenceRequestedOn }),+ setEvidenceError: (evidenceError: string | null) => ({ evidenceError }),+ saveEvidence: true,+ removeEvidence: true,+ setSavingEvidence: (savingEvidence: boolean) => ({ savingEvidence }),}),loaders(({ values }) => ({featureRequestsResponse: [@@ -708,9 +849,11 @@ export const featureRequestsLogic = kea<featureRequestsLogicType>([null as FeatureRequestAccountApi | null,{setSelectedAccount: (_, { selectedAccount }) => selectedAccount,+ openAddAccount: () => null,openEditRequest: (_, { featureRequest }) => featureRequest.account,closeCreateRequest: () => null,closeEditRequest: () => null,+ closeEvidence: () => null,},],accountsError: [@@ -755,6 +898,23 @@ export const featureRequestsLogic = kea<featureRequestsLogicType>([setActiveRequestId: () => false,},],+ requestAccountsShowingAll: [+ false,+ {+ setRequestAccountsShowingAll: (_, { showingAll }) => showingAll,+ showHistoryTarget: () => true,+ loadActiveRequest: () => false,+ setActiveRequestId: () => false,+ },+ ],+ accountsEvidenceCollapsed: [+ false,+ {+ setAccountsEvidenceCollapsed: (_, { collapsed }) => collapsed,+ showHistoryTarget: () => false,+ setActiveRequestId: () => false,+ },+ ],productAreasError: [null as string | null,{@@ -857,11 +1017,11 @@ export const featureRequestsLogic = kea<featureRequestsLogicType>([setEditDescription: (_, { editDescription }) => editDescription,},],- editAccountId: [- null as string | null,+ editAccountIds: [+ [] as string[],{- openEditRequest: (_, { featureRequest }) => featureRequest.account.id,- setEditAccountId: (_, { editAccountId }) => editAccountId,+ openEditRequest: (_, { featureRequest }) => featureRequest.account_links.map((link) => link.account.id),+ setEditAccountIds: (_, { editAccountIds }) => editAccountIds,},],editProductAreaIds: [@@ -913,6 +1073,106 @@ export const featureRequestsLogic = kea<featureRequestsLogicType>([{ setSavingRequestChanges: (_, { savingRequestChanges }) => savingRequestChanges },],mutatingArchive: [false, { setMutatingArchive: (_, { mutatingArchive }) => mutatingArchive }],+ evidenceModalOpen: [+ false,+ {+ openAddAccount: () => true,+ openNewEvidence: () => true,+ openEditEvidence: () => true,+ closeEvidence: () => false,+ },+ ],+ addingAccount: [+ false,+ {+ openAddAccount: () => true,+ openNewEvidence: () => false,+ openEditEvidence: () => false,+ closeEvidence: () => false,+ },+ ],+ addAccountId: [+ null as string | null,+ {+ openAddAccount: () => null,+ setAddAccountId: (_, { accountId }) => accountId,+ closeEvidence: () => null,+ },+ ],+ evidenceAccountLinkId: [+ null as string | null,+ {+ openAddAccount: () => null,+ openNewEvidence: (_, { accountLink }) => accountLink.id,+ openEditEvidence: (_, { accountLink }) => accountLink.id,+ closeEvidence: () => null,+ },+ ],+ editingEvidenceId: [+ null as string | null,+ {+ openAddAccount: () => null,+ openNewEvidence: () => null,+ openEditEvidence: (_, { evidence }) => evidence.id,+ closeEvidence: () => null,+ },+ ],+ evidenceSummary: [+ '',+ {+ openAddAccount: () => '',+ openNewEvidence: () => '',+ openEditEvidence: (_, { evidence }) => evidence.summary,+ setEvidenceSummary: (_, { evidenceSummary }) => evidenceSummary,+ },+ ],+ evidenceQuote: [+ '',+ {+ openAddAccount: () => '',+ openNewEvidence: () => '',+ openEditEvidence: (_, { evidence }) => evidence.customer_quote,+ setEvidenceQuote: (_, { evidenceQuote }) => evidenceQuote,+ },+ ],+ evidenceSource: [+ 'conversation',+ {+ openAddAccount: () => 'conversation',+ openNewEvidence: () => 'conversation',+ openEditEvidence: (_, { evidence }) => evidence.evidence_source,+ setEvidenceSource: (_, { evidenceSource }) => evidenceSource,+ },+ ],+ evidenceUrl: [+ '',+ {+ openAddAccount: () => '',+ openNewEvidence: () => '',+ openEditEvidence: (_, { evidence }) => evidence.source_url,+ setEvidenceUrl: (_, { evidenceUrl }) => evidenceUrl,+ },+ ],+ evidenceRequestedOn: [+ null as string | null,+ {+ openAddAccount: () => null,+ openNewEvidence: () => null,+ openEditEvidence: (_, { evidence }) => evidence.requested_on,+ setEvidenceRequestedOn: (_, { evidenceRequestedOn }) => evidenceRequestedOn,+ },+ ],+ evidenceError: [+ null as string | null,+ {+ openAddAccount: () => null,+ openNewEvidence: () => null,+ openEditEvidence: () => null,+ closeEvidence: () => null,+ setEvidenceError: (_, { evidenceError }) => evidenceError,+ },+ ],+ savingEvidence: [false, { setSavingEvidence: (_, { savingEvidence }) => savingEvidence }],}),selectors({currentTeamId: [@@ -937,18 +1197,53 @@ export const featureRequestsLogic = kea<featureRequestsLogicType>([},],accountOptions: [- (selectors) => [selectors.accounts, selectors.selectedAccount],+ (selectors) => [selectors.accounts, selectors.selectedAccount, selectors.activeRequest],(accounts: AccountApi[],- selectedAccount: FeatureRequestAccountApi | null+ selectedAccount: FeatureRequestAccountApi | null,+ activeRequest: FeatureRequestApi | null+ ): { key: string; label: string }[] => {+ const accountById = new Map<string, FeatureRequestAccountApi>(+ accounts.map((account) => [account.id, account])+ )+ if (selectedAccount) {+ accountById.set(selectedAccount.id, selectedAccount)+ }+ for (const link of activeRequest?.account_links ?? []) {+ accountById.set(link.account.id, link.account)+ }+ return [...accountById.values()].map((account) => ({ key: account.id, label: account.name }))+ },+ ],+ addAccountOptions: [+ (selectors) => [selectors.accountOptions, selectors.activeRequest],+ (+ accountOptions: { key: string; label: string }[],+ activeRequest: FeatureRequestApi | null): { key: string; label: string }[] => {- const displayAccounts =- selectedAccount && !accounts.some((account) => account.id === selectedAccount.id)- ? [selectedAccount, ...accounts]- : accounts- return displayAccounts.map((account) => ({ key: account.id, label: account.name }))+ const linkedAccountIds = new Set(activeRequest?.account_links.map((link) => link.account.id) ?? [])+ return accountOptions.filter((option) => !linkedAccountIds.has(option.key))},],+ activeRequestAccountLinks: [+ (selectors) => [selectors.activeRequest],+ (activeRequest: FeatureRequestApi | null): FeatureRequestAccountLinkApi[] =>+ [...(activeRequest?.account_links ?? [])].sort(+ (first, second) =>+ second.evidence.length - first.evidence.length ||+ first.account.name.localeCompare(second.account.name)+ ),+ ],+ visibleActiveRequestAccountLinks: [+ (selectors) => [selectors.activeRequestAccountLinks, selectors.requestAccountsShowingAll],+ (accountLinks: FeatureRequestAccountLinkApi[], showingAll: boolean): FeatureRequestAccountLinkApi[] =>+ showingAll ? accountLinks : accountLinks.slice(0, FEATURE_REQUEST_ACCOUNT_PREVIEW_SIZE),+ ],+ activeRequestEvidenceCount: [+ (selectors) => [selectors.activeRequestAccountLinks],+ (accountLinks: FeatureRequestAccountLinkApi[]): number =>+ accountLinks.reduce((total, accountLink) => total + accountLink.evidence.length, 0),+ ],productAreaOptions: [(selectors) => [selectors.activeProductAreas],(productAreas: FeatureRequestProductAreaApi[]): { key: string; label: string }[] =>@@ -1001,13 +1296,13 @@ export const featureRequestsLogic = kea<featureRequestsLogicType>([editDisabledReason: [(selectors) => [selectors.editTitle,- selectors.editAccountId,+ selectors.editAccountIds,selectors.editProductAreaIds,selectors.savingRequestChanges,],(editTitle: string,- editAccountId: string | null,+ editAccountIds: string[],editProductAreaIds: string[],savingRequestChanges: boolean): string | undefined => {@@ -1017,8 +1312,8 @@ export const featureRequestsLogic = kea<featureRequestsLogicType>([if (!editTitle.trim()) {return 'Enter a title'}- if (!editAccountId) {- return 'Select an account'+ if (editAccountIds.length === 0) {+ return 'Select at least one account'}if (editProductAreaIds.length === 0) {return 'Select at least one product area'@@ -1026,6 +1321,35 @@ export const featureRequestsLogic = kea<featureRequestsLogicType>([return undefined},],+ evidenceSaveDisabledReason: [+ (selectors) => [+ selectors.addingAccount,+ selectors.addAccountId,+ selectors.evidenceSummary,+ selectors.evidenceQuote,+ selectors.evidenceUrl,+ selectors.savingEvidence,+ ],+ (+ addingAccount: boolean,+ addAccountId: string | null,+ summary: string,+ quote: string,+ sourceUrl: string,+ saving: boolean+ ): string | undefined => {+ if (saving) {+ return addingAccount ? 'Adding account' : 'Saving evidence'+ }+ if (addingAccount && !addAccountId) {+ return 'Select an account'+ }+ if (!addingAccount && !summary.trim() && !quote.trim() && !sourceUrl.trim()) {+ return 'Enter a summary, customer quote, or source URL'+ }+ return undefined+ },+ ],productAreaSaveDisabledReason: [(selectors) => [selectors.productAreaName, selectors.savingProductArea],(productAreaName: string, savingProductArea: boolean): string | undefined => {@@ -1116,6 +1440,22 @@ export const featureRequestsLogic = kea<featureRequestsLogicType>([actions.loadAccounts('')actions.loadProductAreas()},+ openAddAccount: () => actions.loadAccounts(''),+ showHistoryTarget: ({ accountId, evidenceId }) => {+ window.setTimeout(() => {+ const evidenceElement = evidenceId+ ? document.getElementById(featureRequestEvidenceElementId(evidenceId))+ : null+ const accountElement = document.getElementById(featureRequestAccountElementId(accountId))+ const targetElement = evidenceElement ?? accountElement+ targetElement?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })+ }, 0)+ },+ setAddAccountId: ({ accountId }) => {+ actions.setSelectedAccount(+ accountId ? (values.accounts.find((account) => account.id === accountId) ?? null) : null+ )+ },setAccountId: ({ accountId }) => {actions.setSelectedAccount(accountId ? (values.accounts.find((account) => account.id === accountId) ?? null) : null@@ -1136,6 +1476,24 @@ export const featureRequestsLogic = kea<featureRequestsLogicType>([actions.loadRequestHistory(requestId)}},+ loadActiveRequestSuccess: ({ activeRequest }) => {+ const accountId = router.values.searchParams.evidence_account+ if (typeof accountId !== 'string' || activeRequest.is_archived) {+ return+ }+ const accountLink = activeRequest.account_links.find((link) => link.account.id === accountId)+ if (accountLink) {+ actions.openNewEvidence(accountLink)+ }+ },+ closeEvidence: () => {+ if (!router.values.searchParams.evidence_account) {+ return+ }+ const searchParams = { ...router.values.searchParams }+ delete searchParams.evidence_account+ router.actions.replace(router.values.location.pathname, searchParams, router.values.hashParams)+ },submitRequest: async () => {if (values.submitDisabledReason || !values.accountId) {return@@ -1197,7 +1555,7 @@ export const featureRequestsLogic = kea<featureRequestsLogicType>([actions.loadProductAreas()},saveRequestChanges: async () => {- if (values.editDisabledReason || !values.activeRequestId || !values.editAccountId) {+ if (values.editDisabledReason || !values.activeRequestId) {return}actions.setSavingRequestChanges(true)@@ -1208,7 +1566,7 @@ export const featureRequestsLogic = kea<featureRequestsLogicType>([expected_version: values.editExpectedVersion,title: values.editTitle.trim(),description: values.editDescription.trim(),- account_id: values.editAccountId,+ account_ids: values.editAccountIds,product_area_ids: values.editProductAreaIds,request_status: values.editStatus,request_priority: values.editPriority,@@ -1247,6 +1605,106 @@ export const featureRequestsLogic = kea<featureRequestsLogicType>([actions.setEditError("Couldn't load the latest version. Try again.")}},+ saveEvidence: async () => {+ if (values.evidenceSaveDisabledReason || !values.activeRequest) {+ return+ }+ const addingAccount = values.addingAccount+ const editingEvidenceId = values.editingEvidenceId+ const evidenceAccountLinkId = values.evidenceAccountLinkId+ if (!addingAccount && !evidenceAccountLinkId) {+ return+ }+ actions.setSavingEvidence(true)+ actions.setEvidenceError(null)+ try {+ const evidenceFields = {+ summary: values.evidenceSummary.trim(),+ customer_quote: values.evidenceQuote.trim(),+ evidence_source: values.evidenceSource,+ source_url: values.evidenceUrl.trim(),+ requested_on: values.evidenceRequestedOn,+ }+ const hasEvidence = Boolean(+ evidenceFields.summary || evidenceFields.customer_quote || evidenceFields.source_url+ )+ let updated: FeatureRequestApi+ if (addingAccount && values.addAccountId) {+ updated = await featureRequestsAddAccountCreate(values.currentTeamId, values.activeRequest.id, {+ expected_version: values.activeRequest.version,+ account_id: values.addAccountId,+ evidence: hasEvidence ? evidenceFields : undefined,+ })+ } else if (editingEvidenceId) {+ updated = await featureRequestsUpdateEvidenceCreate(values.currentTeamId, values.activeRequest.id, {+ expected_version: values.activeRequest.version,+ ...evidenceFields,+ evidence_id: editingEvidenceId,+ })+ } else if (evidenceAccountLinkId) {+ updated = await featureRequestsAddEvidenceCreate(values.currentTeamId, values.activeRequest.id, {+ expected_version: values.activeRequest.version,+ ...evidenceFields,+ account_link_id: evidenceAccountLinkId,+ })+ } else {+ return+ }+ actions.loadActiveRequestSuccess(updated)+ actions.loadRequestHistory(updated.id)+ actions.loadFeatureRequests()+ actions.closeEvidence()+ lemonToast.success(+ addingAccount+ ? hasEvidence+ ? 'Account and evidence added'+ : 'Account added'+ : editingEvidenceId+ ? 'Evidence updated'+ : 'Evidence added'+ )+ } catch (error) {+ actions.setEvidenceError(+ error instanceof ApiError && error.status === 409+ ? 'This request changed. Close this form, reload the request, and try again.'+ : addingAccount+ ? "Couldn't add the account. Check the fields and try again."+ : "Couldn't save the evidence. Check the fields and try again."+ )+ } finally {+ actions.setSavingEvidence(false)+ }+ },+ removeEvidence: async () => {+ if (!values.activeRequest || !values.editingEvidenceId || values.savingEvidence) {+ return+ }+ actions.setSavingEvidence(true)+ actions.setEvidenceError(null)+ try {+ const updated = await featureRequestsRemoveEvidenceCreate(+ values.currentTeamId,+ values.activeRequest.id,+ {+ expected_version: values.activeRequest.version,+ evidence_id: values.editingEvidenceId,+ }+ )+ actions.loadActiveRequestSuccess(updated)+ actions.loadRequestHistory(updated.id)+ actions.loadFeatureRequests()+ actions.closeEvidence()+ lemonToast.success('Evidence removed')+ } catch (error) {+ actions.setEvidenceError(+ error instanceof ApiError && error.status === 409+ ? 'This request changed. Close this form, reload the request, and try again.'+ : "Couldn't remove the evidence. Try again."+ )+ } finally {+ actions.setSavingEvidence(false)+ }+ },archiveActiveRequest: async () => {if (!values.activeRequest || values.mutatingArchive) {returndiff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 1a26a288dbf5..abf00cbb33a2 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -1587,6 +1587,62 @@ export interface FeatureRequestAccountApi {readonly name: string}+export interface FeatureRequestEvidenceApi {+ /** Stable evidence ID. */+ readonly id: string+ /** Internal summary of this account's request evidence. */+ readonly summary: string+ /** Customer quote kept with this evidence item. */+ readonly customer_quote: string+ /**+ * Free-form name of the source where this evidence was recorded.+ * @maxLength 200+ */+ readonly evidence_source: string+ /** HTTP or HTTPS link to the source, or an empty string. */+ readonly source_url: string+ /**+ * Date the account made the request, or null when unknown.+ * @nullable+ */+ readonly requested_on: string | null+ /**+ * ID of the user who added the evidence.+ * @nullable+ */+ readonly created_by: number | null+ /**+ * ID of the last user to update the evidence.+ * @nullable+ */+ readonly updated_by: number | null+ /** When the evidence was added. */+ readonly created_at: string+ /** When the evidence was last updated. */+ readonly updated_at: string+}++export interface FeatureRequestAccountLinkApi {+ /** Stable link ID between the request and account. */+ readonly id: string+ /** Affected Customer Analytics account. */+ readonly account: FeatureRequestAccountApi+ /** Evidence recorded for this account and request. List responses omit these items. */+ readonly evidence: readonly FeatureRequestEvidenceApi[]+ /**+ * Total evidence items recorded for this account and request.+ * @minimum 0+ */+ readonly evidence_count: number+ /** When the account was first linked. */+ readonly created_at: string+ /**+ * When the account link was last changed.+ * @nullable+ */+ readonly updated_at: string | null+}+export interface FeatureRequestApi {/** Stable feature request ID. */readonly id: string@@ -1625,8 +1681,12 @@ export interface FeatureRequestApi {* @minimum 1*/readonly version: number- /** Affected account in the first release. */+ /** Whether the caller can update this request and all its active account links. */+ readonly can_update: boolean+ /** First visible account retained for client compatibility. Use account_links for the complete list. */readonly account: FeatureRequestAccountApi+ /** Active account links visible to the caller, with account-specific evidence. */+ readonly account_links: readonly FeatureRequestAccountLinkApi[]/** Product areas affected by this request. */readonly product_areas: readonly FeatureRequestProductAreaApi[]/**@@ -1683,8 +1743,10 @@ export interface FeatureRequestUpdateApi {title?: string/** Updated optional customer-facing request description in Markdown. */description?: string- /** Updated affected Customer Analytics account ID. */+ /** Deprecated single affected account ID. Use account_ids. */account_id?: string+ /** One or more affected account IDs. Removed accounts are unlinked without deleting their evidence. */+ account_ids?: string[]/** One or more product area IDs. Existing inactive areas can remain linked. */product_area_ids?: string[]/** Updated customer-facing lifecycle status.@@ -1716,8 +1778,10 @@ export interface PatchedFeatureRequestUpdateApi {title?: string/** Updated optional customer-facing request description in Markdown. */description?: string- /** Updated affected Customer Analytics account ID. */+ /** Deprecated single affected account ID. Use account_ids. */account_id?: string+ /** One or more affected account IDs. Removed accounts are unlinked without deleting their evidence. */+ account_ids?: string[]/** One or more product area IDs. Existing inactive areas can remain linked. */product_area_ids?: string[]/** Updated customer-facing lifecycle status.@@ -1736,6 +1800,69 @@ export interface PatchedFeatureRequestUpdateApi {request_priority?: RequestPriorityEnumApi | null}+export interface FeatureRequestEvidencePayloadApi {+ /** Internal summary of this account's request evidence. */+ summary?: string+ /** Customer quote kept with this evidence item. */+ customer_quote?: string+ /**+ * Free-form name of the source where this evidence was recorded.+ * @maxLength 200+ */+ evidence_source: string+ /**+ * Optional HTTP or HTTPS link to the source.+ * @maxLength 2000+ */+ source_url?: string+ /**+ * Date the account made the request, or null when unknown.+ * @nullable+ */+ requested_on?: string | null+}++export interface FeatureRequestAddAccountApi {+ /**+ * Request version loaded by the editor. Stale versions return 409 Conflict.+ * @minimum 1+ */+ expected_version: number+ /** Accessible account to link to this feature request. */+ account_id: string+ /** Optional first evidence item to create for the account in the same change. */+ evidence?: FeatureRequestEvidencePayloadApi | null+}++export interface FeatureRequestEvidenceCreateApi {+ /** Internal summary of this account's request evidence. */+ summary?: string+ /** Customer quote kept with this evidence item. */+ customer_quote?: string+ /**+ * Free-form name of the source where this evidence was recorded.+ * @maxLength 200+ */+ evidence_source: string+ /**+ * Optional HTTP or HTTPS link to the source.+ * @maxLength 2000+ */+ source_url?: string+ /**+ * Date the account made the request, or null when unknown.+ * @nullable+ */+ requested_on?: string | null+ /**+ * Request version loaded by the editor. Stale versions return 409 Conflict.+ * @minimum 1+ */+ expected_version: number+ /** Active account link that owns this evidence. */+ account_link_id: string+}+export interface FeatureRequestVersionApi {/*** Request version loaded by the editor. Stale versions return 409 Conflict.@@ -1748,6 +1875,8 @@ export interface FeatureRequestVersionApi {* * `status` - Status* * `priority` - Priority* * `account` - Account+ * * `accounts` - Accounts+ * * `evidence` - Evidence* * `product_areas` - Product areas*/export type FieldEnumApi = (typeof FieldEnumApi)[keyof typeof FieldEnumApi]@@ -1756,6 +1885,8 @@ export const FieldEnumApi = {Status: 'status',Priority: 'priority',Account: 'account',+ Accounts: 'accounts',+ Evidence: 'evidence',ProductAreas: 'product_areas',} as const@@ -1773,6 +1904,19 @@ export type FeatureRequestHistoryChangeApiBefore =id: stringname: string}[]+ | {+ id: string+ account: {+ id: string+ name: string+ }+ summary: string+ customer_quote: string+ source: string+ source_url: string+ /** @nullable */+ requested_on: string | null+ }| null/**@@ -1789,6 +1933,19 @@ export type FeatureRequestHistoryChangeApiAfter =id: stringname: string}[]+ | {+ id: string+ account: {+ id: string+ name: string+ }+ summary: string+ customer_quote: string+ source: string+ source_url: string+ /** @nullable */+ requested_on: string | null+ }| nullexport interface FeatureRequestHistoryChangeApi {@@ -1797,6 +1954,8 @@ export interface FeatureRequestHistoryChangeApi {* * `status` - Status* * `priority` - Priority* * `account` - Account+ * * `accounts` - Accounts+ * * `evidence` - Evidence* * `product_areas` - Product areas */readonly field: FieldEnumApi/** Value before the update, including relation snapshots. */@@ -1839,6 +1998,16 @@ export interface FeatureRequestHistoryApi {readonly changed_at: string}+export interface FeatureRequestEvidenceDeleteApi {+ /**+ * Request version loaded by the editor. Stale versions return 409 Conflict.+ * @minimum 1+ */+ expected_version: number+ /** Evidence item to delete. */+ evidence_id: string+}+export interface FeatureRequestStatusHistoryApi {/** Stable status history entry ID. */readonly id: string@@ -1876,6 +2045,35 @@ export interface FeatureRequestStatusHistoryApi {readonly changed_at: string}+export interface FeatureRequestEvidenceUpdateApi {+ /** Internal summary of this account's request evidence. */+ summary?: string+ /** Customer quote kept with this evidence item. */+ customer_quote?: string+ /**+ * Free-form name of the source where this evidence was recorded.+ * @maxLength 200+ */+ evidence_source: string+ /**+ * Optional HTTP or HTTPS link to the source.+ * @maxLength 2000+ */+ source_url?: string+ /**+ * Date the account made the request, or null when unknown.+ * @nullable+ */+ requested_on?: string | null+ /**+ * Request version loaded by the editor. Stale versions return 409 Conflict.+ * @minimum 1+ */+ expected_version: number+ /** Evidence item to replace. */+ evidence_id: string+}+/*** * `numeric` - numeric* * `currency` - currencydiff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex 27e1e1efcf5f..c79a78c23c24 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -49,8 +49,12 @@ import type {EventStreamMemberWriteApi,EventStreamTestMessageApi,ExternalAccountListPageApi,+ FeatureRequestAddAccountApi,FeatureRequestApi,FeatureRequestCreateApi,+ FeatureRequestEvidenceCreateApi,+ FeatureRequestEvidenceDeleteApi,+ FeatureRequestEvidenceUpdateApi,FeatureRequestHistoryApi,FeatureRequestProductAreaApi,FeatureRequestProductAreasListParams,@@ -1734,6 +1738,42 @@ export const featureRequestsPartialUpdate = async (})}+export const getFeatureRequestsAddAccountCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/feature_requests/${id}/add_account/`+}++export const featureRequestsAddAccountCreate = async (+ projectId: string,+ id: string,+ featureRequestAddAccountApi: FeatureRequestAddAccountApi,+ options?: RequestInit+): Promise<FeatureRequestApi> => {+ return apiMutator<FeatureRequestApi>(getFeatureRequestsAddAccountCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(featureRequestAddAccountApi),+ })+}++export const getFeatureRequestsAddEvidenceCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/feature_requests/${id}/add_evidence/`+}++export const featureRequestsAddEvidenceCreate = async (+ projectId: string,+ id: string,+ featureRequestEvidenceCreateApi: FeatureRequestEvidenceCreateApi,+ options?: RequestInit+): Promise<FeatureRequestApi> => {+ return apiMutator<FeatureRequestApi>(getFeatureRequestsAddEvidenceCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(featureRequestEvidenceCreateApi),+ })+}+export const getFeatureRequestsArchiveCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/feature_requests/${id}/archive/`}@@ -1767,6 +1807,24 @@ export const featureRequestsHistoryList = async (})}+export const getFeatureRequestsRemoveEvidenceCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/feature_requests/${id}/remove_evidence/`+}++export const featureRequestsRemoveEvidenceCreate = async (+ projectId: string,+ id: string,+ featureRequestEvidenceDeleteApi: FeatureRequestEvidenceDeleteApi,+ options?: RequestInit+): Promise<FeatureRequestApi> => {+ return apiMutator<FeatureRequestApi>(getFeatureRequestsRemoveEvidenceCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(featureRequestEvidenceDeleteApi),+ })+}+export const getFeatureRequestsRestoreCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/feature_requests/${id}/restore/`}@@ -1800,6 +1858,24 @@ export const featureRequestsStatusHistoryList = async (})}+export const getFeatureRequestsUpdateEvidenceCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/feature_requests/${id}/update_evidence/`+}++export const featureRequestsUpdateEvidenceCreate = async (+ projectId: string,+ id: string,+ featureRequestEvidenceUpdateApi: FeatureRequestEvidenceUpdateApi,+ options?: RequestInit+): Promise<FeatureRequestApi> => {+ return apiMutator<FeatureRequestApi>(getFeatureRequestsUpdateEvidenceCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(featureRequestEvidenceUpdateApi),+ })+}+export const getGroupsTypesMetricsListUrl = (projectId: string,groupTypeIndex: number,diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex 76aff87e7d0d..e13f188f29fa 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -1010,7 +1010,11 @@ export const FeatureRequestsUpdateBody = /* @__PURE__ */ zod.object({.optional().describe('Updated customer-facing request title.'),description: zod.string().optional().describe('Updated optional customer-facing request description in Markdown.'),- account_id: zod.uuid().optional().describe('Updated affected Customer Analytics account ID.'),+ account_id: zod.uuid().optional().describe('Deprecated single affected account ID. Use account_ids.'),+ account_ids: zod+ .array(zod.uuid())+ .optional()+ .describe('One or more affected account IDs. Removed accounts are unlinked without deleting their evidence.'),product_area_ids: zod.array(zod.uuid()).optional()@@ -1049,7 +1053,11 @@ export const FeatureRequestsPartialUpdateBody = /* @__PURE__ */ zod.object({.optional().describe('Updated customer-facing request title.'),description: zod.string().optional().describe('Updated optional customer-facing request description in Markdown.'),- account_id: zod.uuid().optional().describe('Updated affected Customer Analytics account ID.'),+ account_id: zod.uuid().optional().describe('Deprecated single affected account ID. Use account_ids.'),+ account_ids: zod+ .array(zod.uuid())+ .optional()+ .describe('One or more affected account IDs. Removed accounts are unlinked without deleting their evidence.'),product_area_ids: zod.array(zod.uuid()).optional()@@ -1074,6 +1082,83 @@ export const FeatureRequestsPartialUpdateBody = /* @__PURE__ */ zod.object({),})+export const featureRequestsAddAccountCreateBodyEvidenceOneSummaryDefault = ``+export const featureRequestsAddAccountCreateBodyEvidenceOneCustomerQuoteDefault = ``+export const featureRequestsAddAccountCreateBodyEvidenceOneEvidenceSourceMax = 200++export const featureRequestsAddAccountCreateBodyEvidenceOneSourceUrlDefault = ``+export const featureRequestsAddAccountCreateBodyEvidenceOneSourceUrlMax = 2000++export const FeatureRequestsAddAccountCreateBody = /* @__PURE__ */ zod.object({+ expected_version: zod+ .number()+ .min(1)+ .describe('Request version loaded by the editor. Stale versions return 409 Conflict.'),+ account_id: zod.uuid().describe('Accessible account to link to this feature request.'),+ evidence: zod+ .union([+ zod.object({+ summary: zod+ .string()+ .default(featureRequestsAddAccountCreateBodyEvidenceOneSummaryDefault)+ .describe("Internal summary of this account's request evidence."),+ customer_quote: zod+ .string()+ .default(featureRequestsAddAccountCreateBodyEvidenceOneCustomerQuoteDefault)+ .describe('Customer quote kept with this evidence item.'),+ evidence_source: zod+ .string()+ .max(featureRequestsAddAccountCreateBodyEvidenceOneEvidenceSourceMax)+ .describe('Free-form name of the source where this evidence was recorded.'),+ source_url: zod+ .url()+ .max(featureRequestsAddAccountCreateBodyEvidenceOneSourceUrlMax)+ .default(featureRequestsAddAccountCreateBodyEvidenceOneSourceUrlDefault)+ .describe('Optional HTTP or HTTPS link to the source.'),+ requested_on: zod.iso+ .date()+ .nullish()+ .describe('Date the account made the request, or null when unknown.'),+ }),+ zod.null(),+ ])+ .optional()+ .describe('Optional first evidence item to create for the account in the same change.'),+})++export const featureRequestsAddEvidenceCreateBodySummaryDefault = ``+export const featureRequestsAddEvidenceCreateBodyCustomerQuoteDefault = ``+export const featureRequestsAddEvidenceCreateBodyEvidenceSourceMax = 200++export const featureRequestsAddEvidenceCreateBodySourceUrlDefault = ``+export const featureRequestsAddEvidenceCreateBodySourceUrlMax = 2000++export const FeatureRequestsAddEvidenceCreateBody = /* @__PURE__ */ zod.object({+ summary: zod+ .string()+ .default(featureRequestsAddEvidenceCreateBodySummaryDefault)+ .describe("Internal summary of this account's request evidence."),+ customer_quote: zod+ .string()+ .default(featureRequestsAddEvidenceCreateBodyCustomerQuoteDefault)+ .describe('Customer quote kept with this evidence item.'),+ evidence_source: zod+ .string()+ .max(featureRequestsAddEvidenceCreateBodyEvidenceSourceMax)+ .describe('Free-form name of the source where this evidence was recorded.'),+ source_url: zod+ .url()+ .max(featureRequestsAddEvidenceCreateBodySourceUrlMax)+ .default(featureRequestsAddEvidenceCreateBodySourceUrlDefault)+ .describe('Optional HTTP or HTTPS link to the source.'),+ requested_on: zod.iso.date().nullish().describe('Date the account made the request, or null when unknown.'),+ expected_version: zod+ .number()+ .min(1)+ .describe('Request version loaded by the editor. Stale versions return 409 Conflict.'),+ account_link_id: zod.uuid().describe('Active account link that owns this evidence.'),+})+export const FeatureRequestsArchiveCreateBody = /* @__PURE__ */ zod.object({expected_version: zod.number()@@ -1081,6 +1166,14 @@ export const FeatureRequestsArchiveCreateBody = /* @__PURE__ */ zod.object({.describe('Request version loaded by the editor. Stale versions return 409 Conflict.'),})+export const FeatureRequestsRemoveEvidenceCreateBody = /* @__PURE__ */ zod.object({+ expected_version: zod+ .number()+ .min(1)+ .describe('Request version loaded by the editor. Stale versions return 409 Conflict.'),+ evidence_id: zod.uuid().describe('Evidence item to delete.'),+})+export const FeatureRequestsRestoreCreateBody = /* @__PURE__ */ zod.object({expected_version: zod.number()@@ -1088,6 +1181,39 @@ export const FeatureRequestsRestoreCreateBody = /* @__PURE__ */ zod.object({.describe('Request version loaded by the editor. Stale versions return 409 Conflict.'),})+export const featureRequestsUpdateEvidenceCreateBodySummaryDefault = ``+export const featureRequestsUpdateEvidenceCreateBodyCustomerQuoteDefault = ``+export const featureRequestsUpdateEvidenceCreateBodyEvidenceSourceMax = 200++export const featureRequestsUpdateEvidenceCreateBodySourceUrlDefault = ``+export const featureRequestsUpdateEvidenceCreateBodySourceUrlMax = 2000++export const FeatureRequestsUpdateEvidenceCreateBody = /* @__PURE__ */ zod.object({+ summary: zod+ .string()+ .default(featureRequestsUpdateEvidenceCreateBodySummaryDefault)+ .describe("Internal summary of this account's request evidence."),+ customer_quote: zod+ .string()+ .default(featureRequestsUpdateEvidenceCreateBodyCustomerQuoteDefault)+ .describe('Customer quote kept with this evidence item.'),+ evidence_source: zod+ .string()+ .max(featureRequestsUpdateEvidenceCreateBodyEvidenceSourceMax)+ .describe('Free-form name of the source where this evidence was recorded.'),+ source_url: zod+ .url()+ .max(featureRequestsUpdateEvidenceCreateBodySourceUrlMax)+ .default(featureRequestsUpdateEvidenceCreateBodySourceUrlDefault)+ .describe('Optional HTTP or HTTPS link to the source.'),+ requested_on: zod.iso.date().nullish().describe('Date the account made the request, or null when unknown.'),+ expected_version: zod+ .number()+ .min(1)+ .describe('Request version loaded by the editor. Stale versions return 409 Conflict.'),+ evidence_id: zod.uuid().describe('Evidence item to replace.'),+})+export const groupsTypesMetricsCreateBodyNameMax = 255export const groupsTypesMetricsCreateBodyFormatDefault = `numeric`diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex b1c00555f977..6b1c69ecb29e 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -904,6 +904,12 @@ tools:feature-request-product-areas-update:operation: feature_request_product_areas_updateenabled: false+ feature-requests-add-account-create:+ operation: feature_requests_add_account_create+ enabled: false+ feature-requests-add-evidence-create:+ operation: feature_requests_add_evidence_create+ enabled: falsefeature-requests-archive-create:operation: feature_requests_archive_createenabled: false@@ -919,6 +925,9 @@ tools:feature-requests-partial-update:operation: feature_requests_partial_updateenabled: false+ feature-requests-remove-evidence-create:+ operation: feature_requests_remove_evidence_create+ enabled: falsefeature-requests-restore-create:operation: feature_requests_restore_createenabled: false@@ -931,6 +940,9 @@ tools:feature-requests-update:operation: feature_requests_updateenabled: false+ feature-requests-update-evidence-create:+ operation: feature_requests_update_evidence_create+ enabled: falseusage-metrics-create:operation: groups_types_metrics_createenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 1a34b534f637..8282af6d4f2a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -37545,6 +37545,62 @@ export namespace Schemas {readonly name: string;}+ export interface FeatureRequestEvidence {+ /** Stable evidence ID. */+ readonly id: string;+ /** Internal summary of this account's request evidence. */+ readonly summary: string;+ /** Customer quote kept with this evidence item. */+ readonly customer_quote: string;+ /**+ * Free-form name of the source where this evidence was recorded.+ * @maxLength 200+ */+ readonly evidence_source: string;+ /** HTTP or HTTPS link to the source, or an empty string. */+ readonly source_url: string;+ /**+ * Date the account made the request, or null when unknown.+ * @nullable+ */+ readonly requested_on: string | null;+ /**+ * ID of the user who added the evidence.+ * @nullable+ */+ readonly created_by: number | null;+ /**+ * ID of the last user to update the evidence.+ * @nullable+ */+ readonly updated_by: number | null;+ /** When the evidence was added. */+ readonly created_at: string;+ /** When the evidence was last updated. */+ readonly updated_at: string;+ }++ export interface FeatureRequestAccountLink {+ /** Stable link ID between the request and account. */+ readonly id: string;+ /** Affected Customer Analytics account. */+ readonly account: FeatureRequestAccount;+ /** Evidence recorded for this account and request. List responses omit these items. */+ readonly evidence: readonly FeatureRequestEvidence[];+ /**+ * Total evidence items recorded for this account and request.+ * @minimum 0+ */+ readonly evidence_count: number;+ /** When the account was first linked. */+ readonly created_at: string;+ /**+ * When the account link was last changed.+ * @nullable+ */+ readonly updated_at: string | null;+ }+export interface FeatureRequestProductArea {/** Stable product area ID. */readonly id: string;@@ -37604,8 +37660,12 @@ export namespace Schemas {* @minimum 1*/readonly version: number;- /** Affected account in the first release. */+ /** Whether the caller can update this request and all its active account links. */+ readonly can_update: boolean;+ /** First visible account retained for client compatibility. Use account_links for the complete list. */readonly account: FeatureRequestAccount;+ /** Active account links visible to the caller, with account-specific evidence. */+ readonly account_links: readonly FeatureRequestAccountLink[];/** Product areas affected by this request. */readonly product_areas: readonly FeatureRequestProductArea[];/**@@ -37624,6 +37684,40 @@ export namespace Schemas {readonly updated_at: string;}+ export interface FeatureRequestEvidencePayload {+ /** Internal summary of this account's request evidence. */+ summary?: string;+ /** Customer quote kept with this evidence item. */+ customer_quote?: string;+ /**+ * Free-form name of the source where this evidence was recorded.+ * @maxLength 200+ */+ evidence_source: string;+ /**+ * Optional HTTP or HTTPS link to the source.+ * @maxLength 2000+ */+ source_url?: string;+ /**+ * Date the account made the request, or null when unknown.+ * @nullable+ */+ requested_on?: string | null;+ }++ export interface FeatureRequestAddAccount {+ /**+ * Request version loaded by the editor. Stale versions return 409 Conflict.+ * @minimum 1+ */+ expected_version: number;+ /** Accessible account to link to this feature request. */+ account_id: string;+ /** Optional first evidence item to create for the account in the same change. */+ evidence?: FeatureRequestEvidencePayload | null;+ }+export interface FeatureRequestCreate {/*** Required customer-facing request title.@@ -37640,10 +37734,80 @@ export namespace Schemas {idempotency_key: string;}+ export interface FeatureRequestEvidenceCreate {+ /** Internal summary of this account's request evidence. */+ summary?: string;+ /** Customer quote kept with this evidence item. */+ customer_quote?: string;+ /**+ * Free-form name of the source where this evidence was recorded.+ * @maxLength 200+ */+ evidence_source: string;+ /**+ * Optional HTTP or HTTPS link to the source.+ * @maxLength 2000+ */+ source_url?: string;+ /**+ * Date the account made the request, or null when unknown.+ * @nullable+ */+ requested_on?: string | null;+ /**+ * Request version loaded by the editor. Stale versions return 409 Conflict.+ * @minimum 1+ */+ expected_version: number;+ /** Active account link that owns this evidence. */+ account_link_id: string;+ }++ export interface FeatureRequestEvidenceDelete {+ /**+ * Request version loaded by the editor. Stale versions return 409 Conflict.+ * @minimum 1+ */+ expected_version: number;+ /** Evidence item to delete. */+ evidence_id: string;+ }++ export interface FeatureRequestEvidenceUpdate {+ /** Internal summary of this account's request evidence. */+ summary?: string;+ /** Customer quote kept with this evidence item. */+ customer_quote?: string;+ /**+ * Free-form name of the source where this evidence was recorded.+ * @maxLength 200+ */+ evidence_source: string;+ /**+ * Optional HTTP or HTTPS link to the source.+ * @maxLength 2000+ */+ source_url?: string;+ /**+ * Date the account made the request, or null when unknown.+ * @nullable+ */+ requested_on?: string | null;+ /**+ * Request version loaded by the editor. Stale versions return 409 Conflict.+ * @minimum 1+ */+ expected_version: number;+ /** Evidence item to replace. */+ evidence_id: string;+ }+/*** * `status` - Status* * `priority` - Priority* * `account` - Account+ * * `accounts` - Accounts+ * * `evidence` - Evidence* * `product_areas` - Product areas*/export type FieldEnum = typeof FieldEnum[keyof typeof FieldEnum];@@ -37653,6 +37817,8 @@ export namespace Schemas {Status: 'status',Priority: 'priority',Account: 'account',+ Accounts: 'accounts',+ Evidence: 'evidence',ProductAreas: 'product_areas',} as const;@@ -37666,7 +37832,19 @@ export namespace Schemas {} | {id: string;name: string;- }[] | null;+ }[] | {+ id: string;+ account: {+ id: string;+ name: string;+ };+ summary: string;+ customer_quote: string;+ source: string;+ source_url: string;+ /** @nullable */+ requested_on: string | null;+ } | null;/*** Value after the update, including relation snapshots.@@ -37678,7 +37856,19 @@ export namespace Schemas {} | {id: string;name: string;- }[] | null;+ }[] | {+ id: string;+ account: {+ id: string;+ name: string;+ };+ summary: string;+ customer_quote: string;+ source: string;+ source_url: string;+ /** @nullable */+ requested_on: string | null;+ } | null;export interface FeatureRequestHistoryChange {/** Request field represented by this change.@@ -37686,6 +37876,8 @@ export namespace Schemas {* * `status` - Status* * `priority` - Priority* * `account` - Account+ * * `accounts` - Accounts+ * * `evidence` - Evidence* * `product_areas` - Product areas */readonly field: FieldEnum;/** Value before the update, including relation snapshots. */@@ -37769,8 +37961,10 @@ export namespace Schemas {title?: string;/** Updated optional customer-facing request description in Markdown. */description?: string;- /** Updated affected Customer Analytics account ID. */+ /** Deprecated single affected account ID. Use account_ids. */account_id?: string;+ /** One or more affected account IDs. Removed accounts are unlinked without deleting their evidence. */+ account_ids?: string[];/** One or more product area IDs. Existing inactive areas can remain linked. */product_area_ids?: string[];/** Updated customer-facing lifecycle status.@@ -58850,8 +59044,10 @@ export namespace Schemas {title?: string;/** Updated optional customer-facing request description in Markdown. */description?: string;- /** Updated affected Customer Analytics account ID. */+ /** Deprecated single affected account ID. Use account_ids. */account_id?: string;+ /** One or more affected account IDs. Removed accounts are unlinked without deleting their evidence. */+ account_ids?: string[];/** One or more product area IDs. Existing inactive areas can remain linked. */product_area_ids?: string[];/** Updated customer-facing lifecycle status.