: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 feature request tracking (#82171)
Arthur Moreira de Deusaeda861538a9
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex fa84258a0f8b..c16ba7026ecd 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -172,6 +172,10 @@ rules:|ExternalDataSchemaOOMEvent|ExternalDataSource|FeatureFlag+ |FeatureRequest+ |FeatureRequestAccountLink+ |FeatureRequestProductArea+ |FeatureRequestProductAreaLink|TeamExperimentsConfig|TeamFeatureFlagDefaultsConfig|TeamMCPGatewayConfig@@ -526,6 +530,10 @@ rules:|ExternalDataSchemaOOMEvent|ExternalDataSource|FeatureFlag+ |FeatureRequest+ |FeatureRequestAccountLink+ |FeatureRequestProductArea+ |FeatureRequestProductAreaLink|TeamExperimentsConfig|TeamFeatureFlagDefaultsConfig|TeamMCPGatewayConfigdiff --git a/ee/api/rbac/test/__snapshots__/test_access_control.ambr b/ee/api/rbac/test/__snapshots__/test_access_control.ambrindex f468869cbe81..b9d597e9b29f 100644--- a/ee/api/rbac/test/__snapshots__/test_access_control.ambr+++ b/ee/api/rbac/test/__snapshots__/test_access_control.ambr@@ -34,6 +34,7 @@'account','action','ai_observability_clusters',+ 'customer_analytics','customer_journey','dashboard','dataset',diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 7e760b6eca12..ec768b7724d9 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5622,6 +5622,10 @@ snapshots:hash: v1.k794b7964.828fae9c91deb58c84ba0d76bf0824931870cb75f43a3d9b723d7cd9fbf7be83.JszjQiSxPVwlGEw-b_MPuQBnfdUHtG9CcnhUdSNvmSgscenes-app-customer-analytics-dashboard--b-2-c-mode--light:hash: v1.k794b7964.ff25e11868464e00df352180254dbe0a1017cd1d8c7c4f4c7d6995068e80e2dc.m0XFOZVPCdSaCLaPQ6XTePvkZJ1I11QI2KARZi9QpWs+ scenes-app-customer-analytics-dashboard--feature-requests--dark:+ hash: v1.k794b7964.e16f57d171068ca5a11cf7af66d3d5a52227cab1b15423e7aa05cfce8350cf4f.axjE_1v1TL3Z-3X-2IZgd-GEduD-TIXsiyMucxKAiCY+ scenes-app-customer-analytics-dashboard--feature-requests--light:+ hash: v1.k794b7964.6abefcbc39350e144342e1f74d316bf76ceed96828c76c1cea182423a3c67bad.1ENeSwPLlfvuDgxrwrYiraaRxaOmML-bUMOL0KVThbsscenes-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/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 35821f06a843..d5895389ba72 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -279,6 +279,7 @@ export const FEATURE_FLAGS = {CRM_ITERATION_ONE: 'crm-iteration-one', // owner: @arthurdedeus #team-customer-analyticsCUSTOMER_ANALYTICS: 'customer-analytics-roadmap', // owner: @arthurdedeus #team-customer-analyticsCUSTOMER_ANALYTICS_CSP: 'customer-analytics-csp', // owner: @arthurdedeus #team-customer-analytics, gates the Customer analytics > Accounts settings tab (account_group_type_index dropdown)+ CUSTOMER_ANALYTICS_FEATURE_REQUESTS: 'customer-analytics-feature-requests',CUSTOMER_ANALYTICS_JOURNEYS: 'customer-analytics-journeys', // owner: @arthurdedeus #team-customer-analyticsCUSTOMER_PROFILE_CONFIG_BUTTON: 'customer-profile-config-button', // owner: @arthurdedeus #team-customer-analyticsDASHBOARD_AUTO_PREVIEW_LIMIT: 'dashboard-auto-preview-limit', // owner: @pauldambra #team-product-analyticsdiff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 55a54ba575a5..694b56c33926 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -107,6 +107,8 @@ export const productRoutes: Record<string, [string, string]> = {'/customer_analytics/notes': ['CustomerAnalytics', 'customerAnalyticsNotes'],'/customer_analytics/announcements': ['CustomerAnalytics', 'customerAnalyticsAnnouncements'],'/customer_analytics/feed': ['CustomerAnalytics', 'customerAnalyticsFeed'],+ '/customer_analytics/feature-requests': ['CustomerAnalytics', 'customerAnalyticsFeatureRequests'],+ '/customer_analytics/feature-requests/:requestId': ['CustomerAnalytics', 'customerAnalyticsFeatureRequests'],'/customer_analytics/journeys/new': ['CustomerJourneyBuilder', 'customerJourneyBuilder'],'/customer_analytics/journeys/templates': ['CustomerJourneyTemplates', 'customerJourneyTemplates'],'/customer_analytics/journeys/:id/edit': ['CustomerJourneyBuilder', 'customerJourneyEdit'],@@ -1060,6 +1062,8 @@ export const productUrls = {customerAnalyticsNotes: (): string => '/customer_analytics/notes',customerAnalyticsAnnouncements: (): string => '/customer_analytics/announcements',customerAnalyticsFeed: (): string => '/customer_analytics/feed',+ customerAnalyticsFeatureRequests: (requestId?: string): string =>+ `/customer_analytics/feature-requests${requestId ? `/${requestId}` : ''}`,customerAnalyticsJourneys: (): string => '/customer_analytics/journeys',customerAnalyticsConfiguration: (tab?: string): string =>`/customer_analytics/configuration${tab ? `?tab=${tab}` : ''}`,diff --git a/products/customer_analytics/backend/constants.py b/products/customer_analytics/backend/constants.pyindex f6d43ab3d1e8..8c5466694126 100644--- a/products/customer_analytics/backend/constants.py+++ b/products/customer_analytics/backend/constants.py@@ -7,6 +7,7 @@ SLACK_ARCHIVES_ORIGIN = "https://posthog.slack.com/archives"# Mirrors frontend `FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP`.CUSTOMER_ANALYTICS_CSP_FLAG = "customer-analytics-csp"+CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG = "customer-analytics-feature-requests"# Mirrors frontend `FEATURE_FLAGS.WAREHOUSE_PERSON_PROPERTIES`. Gates the whole warehouse -> person# properties feature: creating person-target custom property sources (API + UI), staging rows duringdiff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 96f942a5a528..6625326ad4a2 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -88,6 +88,7 @@ from products.customer_analytics.backend.logic import (announcements as _announcements_logic,channel_summaries as _channel_summaries_logic,custom_property_values as _custom_property_values_logic,+ feature_requests as _feature_requests_logic,relationships as _relationships_logic,)from products.customer_analytics.backend.logic.custom_property_definitions import (@@ -1960,6 +1961,82 @@ def list_custom_property_sync_runs(return [_to_sync_run_view(run) for run in page], total_count+FeatureRequestValidationError = _feature_requests_logic.FeatureRequestValidationError+FeatureRequestProductAreaConflictError = _feature_requests_logic.FeatureRequestProductAreaConflictError+++def list_feature_request_product_areas(+ team_id: int, *, include_inactive: bool = False+) -> list[contracts.FeatureRequestProductAreaView]:+ return _feature_requests_logic.list_product_areas(team_id, include_inactive=include_inactive)+++def create_feature_request_product_area(+ *, team_id: int, name: str, display_order: int, actor_id: int+) -> contracts.FeatureRequestProductAreaView:+ return _feature_requests_logic.create_product_area(+ team_id=team_id,+ name=name,+ display_order=display_order,+ actor_id=actor_id,+ )+++def update_feature_request_product_area(+ *,+ team_id: int,+ product_area_id: UUID,+ name: str | None,+ display_order: int | None,+ is_active: bool | None,+ actor_id: int,+) -> contracts.FeatureRequestProductAreaView | None:+ return _feature_requests_logic.update_product_area(+ team_id=team_id,+ product_area_id=product_area_id,+ name=name,+ display_order=display_order,+ is_active=is_active,+ actor_id=actor_id,+ )+++def list_feature_requests(+ *, team_id: int, user_access_control: "UserAccessControl", offset: int, limit: int+) -> tuple[list[contracts.FeatureRequestView], int]:+ return _feature_requests_logic.list_feature_requests(+ team_id=team_id,+ user_access_control=user_access_control,+ offset=offset,+ limit=limit,+ )+++def get_feature_request(+ *, team_id: int, feature_request_id: UUID, user_access_control: "UserAccessControl"+) -> contracts.FeatureRequestView | None:+ return _feature_requests_logic.get_feature_request(+ team_id=team_id,+ feature_request_id=feature_request_id,+ user_access_control=user_access_control,+ )+++def create_feature_request(+ *,+ team_id: int,+ input: contracts.CreateFeatureRequestInput,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestCreateOutcome:+ return _feature_requests_logic.create_feature_request(+ team_id=team_id,+ input=input,+ actor_id=actor_id,+ user_access_control=user_access_control,+ )++# --- CustomerJourney ---diff --git a/products/customer_analytics/backend/facade/constants.py b/products/customer_analytics/backend/facade/constants.pyindex 3161fc371f48..96f880543935 100644--- a/products/customer_analytics/backend/facade/constants.py+++ b/products/customer_analytics/backend/facade/constants.py@@ -11,6 +11,7 @@ from products.customer_analytics.backend.constants import (CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES,CUSTOM_PROPERTY_OPTION_COLORS,CUSTOMER_ANALYTICS_CSP_FLAG,+ CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG,DEFAULT_ACTIVITY_EVENT,MAX_ANNOUNCEMENT_CHANNELS,SLACK_ARCHIVES_ORIGIN,@@ -23,6 +24,7 @@ __all__ = ["CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES","CUSTOM_PROPERTY_OPTION_COLORS","CUSTOMER_ANALYTICS_CSP_FLAG",+ "CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG","DEFAULT_ACTIVITY_EVENT","MAX_ANNOUNCEMENT_CHANNELS","SLACK_ARCHIVES_ORIGIN",diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 07fbccd05d5d..6a3784ff0e45 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -539,6 +539,51 @@ class CustomerJourneyView:updated_at: datetime | None = None+@stdlib_dataclass(frozen=True)+class FeatureRequestProductAreaView:+ id: UUID | None = None+ name: str = ""+ display_order: int = 0+ is_active: bool = True+ created_at: datetime | None = None+ updated_at: datetime | None = None+++@stdlib_dataclass(frozen=True)+class FeatureRequestAccountView:+ id: UUID | None = None+ name: str = ""+++@stdlib_dataclass(frozen=True)+class FeatureRequestView:+ id: UUID | None = None+ title: str = ""+ description: str = ""+ request_status: str = "requested"+ account: FeatureRequestAccountView | None = None+ product_areas: list[FeatureRequestProductAreaView] = field(default_factory=list)+ created_by: int | None = None+ updated_by: int | None = None+ created_at: datetime | None = None+ updated_at: datetime | None = None+++@dataclass(frozen=True)+class CreateFeatureRequestInput:+ title: str+ description: str+ account_id: UUID+ product_area_ids: tuple[UUID, ...]+ idempotency_key: UUID+++@dataclass(frozen=True)+class FeatureRequestCreateOutcome:+ request: FeatureRequestView+ created: bool++@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.pynew file mode 100644index 000000000000..f1b9f09e1d28--- /dev/null+++ b/products/customer_analytics/backend/logic/feature_requests.py@@ -0,0 +1,217 @@+from typing import TYPE_CHECKING+from uuid import UUID++from django.db import IntegrityError, transaction+from django.db.models import QuerySet++from products.customer_analytics.backend.facade import contracts+from products.customer_analytics.backend.models import (+ Account,+ FeatureRequest,+ FeatureRequestAccountLink,+ FeatureRequestProductArea,+ FeatureRequestProductAreaLink,+)++if TYPE_CHECKING:+ from posthog.rbac.user_access_control import UserAccessControl+++class FeatureRequestValidationError(ValueError):+ def __init__(self, field: str, message: str) -> None:+ super().__init__(message)+ self.field = field+ self.message = message+++class FeatureRequestProductAreaConflictError(ValueError):+ pass+++def _to_product_area_view(product_area: FeatureRequestProductArea) -> contracts.FeatureRequestProductAreaView:+ return contracts.FeatureRequestProductAreaView(+ id=product_area.id,+ name=product_area.name,+ display_order=product_area.display_order,+ is_active=product_area.is_active,+ created_at=product_area.created_at,+ updated_at=product_area.updated_at,+ )+++def _to_feature_request_view(feature_request: FeatureRequest) -> contracts.FeatureRequestView:+ account_link = next(iter(feature_request.account_links.all()))+ return contracts.FeatureRequestView(+ id=feature_request.id,+ title=feature_request.title,+ description=feature_request.description,+ request_status=feature_request.status,+ account=contracts.FeatureRequestAccountView(id=account_link.account.id, name=account_link.account.name),+ 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,+ created_at=feature_request.created_at,+ updated_at=feature_request.updated_at,+ )+++def _feature_request_queryset(team_id: int, user_access_control: "UserAccessControl") -> QuerySet[FeatureRequest]:+ accessible_account_ids = user_access_control.filter_queryset_by_access_level(+ Account.objects.for_team(team_id)+ ).values("id")+ return (+ FeatureRequest.objects.for_team(team_id)+ .filter(account_links__account_id__in=accessible_account_ids)+ .prefetch_related("product_areas", "account_links__account")+ .distinct()+ )+++def list_product_areas(+ team_id: int, *, include_inactive: bool = False+) -> list[contracts.FeatureRequestProductAreaView]:+ queryset = FeatureRequestProductArea.objects.for_team(team_id)+ if not include_inactive:+ queryset = queryset.filter(is_active=True)+ return [_to_product_area_view(area) for area in queryset.order_by("display_order", "name", "id")]+++def create_product_area(+ *, team_id: int, name: str, display_order: int, actor_id: int+) -> contracts.FeatureRequestProductAreaView:+ normalized_name = name.strip()+ if not normalized_name:+ raise FeatureRequestValidationError("name", "Enter a product area name.")+ try:+ product_area = FeatureRequestProductArea.objects.for_team(team_id).create(+ team_id=team_id,+ name=normalized_name,+ display_order=display_order,+ created_by_id=actor_id,+ updated_by_id=actor_id,+ )+ except IntegrityError:+ raise FeatureRequestProductAreaConflictError("A product area with this name already exists.")+ return _to_product_area_view(product_area)+++def update_product_area(+ *,+ team_id: int,+ product_area_id: UUID,+ name: str | None,+ display_order: int | None,+ is_active: bool | None,+ actor_id: int,+) -> contracts.FeatureRequestProductAreaView | None:+ product_area = FeatureRequestProductArea.objects.for_team(team_id).filter(id=product_area_id).first()+ if product_area is None:+ return None+ if name is not None:+ normalized_name = name.strip()+ if not normalized_name:+ raise FeatureRequestValidationError("name", "Enter a product area name.")+ product_area.name = normalized_name+ if display_order is not None:+ product_area.display_order = display_order+ if is_active is not None:+ product_area.is_active = is_active+ product_area.updated_by_id = actor_id+ try:+ product_area.save()+ except IntegrityError:+ raise FeatureRequestProductAreaConflictError("A product area with this name already exists.")+ return _to_product_area_view(product_area)+++def list_feature_requests(+ *, team_id: int, user_access_control: "UserAccessControl", offset: int, limit: int+) -> tuple[list[contracts.FeatureRequestView], int]:+ queryset = _feature_request_queryset(team_id, user_access_control).order_by("-updated_at", "-created_at", "-id")+ total_count = queryset.count()+ return [_to_feature_request_view(item) for item in queryset[offset : offset + limit]], total_count+++def 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+++def create_feature_request(+ *,+ team_id: int,+ input: contracts.CreateFeatureRequestInput,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestCreateOutcome:+ title = input.title.strip()+ description = input.description.strip()+ if not title:+ raise FeatureRequestValidationError("title", "Enter a title.")+ if not description:+ raise FeatureRequestValidationError("description", "Enter a description.")+ if not input.product_area_ids:+ raise FeatureRequestValidationError("product_area_ids", "Select at least one product area.")++ existing = FeatureRequest.objects.for_team(team_id).filter(idempotency_key=input.idempotency_key).first()+ if existing is not None:+ accessible_existing = _feature_request_queryset(team_id, user_access_control).filter(id=existing.id).first()+ 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),+ created=False,+ )++ accessible_account = (+ user_access_control.filter_queryset_by_access_level(Account.objects.for_team(team_id))+ .filter(id=input.account_id)+ .first()+ )+ if accessible_account is None:+ raise FeatureRequestValidationError("account_id", "Select an account you can access.")++ unique_product_area_ids = tuple(dict.fromkeys(input.product_area_ids))+ product_areas = list(+ FeatureRequestProductArea.objects.for_team(team_id).filter(+ id__in=unique_product_area_ids,+ is_active=True,+ )+ )+ if len(product_areas) != len(unique_product_area_ids):+ raise FeatureRequestValidationError("product_area_ids", "Select active product areas from this project.")++ with transaction.atomic():+ feature_request, created = FeatureRequest.objects.for_team(team_id).get_or_create(+ team_id=team_id,+ idempotency_key=input.idempotency_key,+ defaults={+ "title": title,+ "description": description,+ "created_by_id": actor_id,+ "updated_by_id": actor_id,+ },+ )+ if created:+ FeatureRequestAccountLink.objects.for_team(team_id).create(+ team_id=team_id,+ feature_request=feature_request,+ account=accessible_account,+ )+ FeatureRequestProductAreaLink.objects.for_team(team_id).bulk_create(+ [+ FeatureRequestProductAreaLink(+ team_id=team_id,+ feature_request=feature_request,+ product_area=product_area,+ )+ for product_area in product_areas+ ]+ )++ refreshed = _feature_request_queryset(team_id, user_access_control).filter(id=feature_request.id).first()+ if refreshed is None:+ raise FeatureRequestValidationError("idempotency_key", "This idempotency key is already in use.")+ return contracts.FeatureRequestCreateOutcome(request=_to_feature_request_view(refreshed), created=created)diff --git a/products/customer_analytics/backend/migrations/0031_featurerequest_featurerequestproductarea_and_more.py b/products/customer_analytics/backend/migrations/0031_featurerequest_featurerequestproductarea_and_more.pynew file mode 100644index 000000000000..5274d4fe1f89--- /dev/null+++ b/products/customer_analytics/backend/migrations/0031_featurerequest_featurerequestproductarea_and_more.py@@ -0,0 +1,170 @@+# Generated by Django 5.2.17 on 2026-08-12 14:11++import django.db.models.deletion+import django.db.models.functions.text+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("customer_analytics", "0030_meeting_models"),+ ("posthog", "1300_identityproviderconfig_saml_relay_state_unique"),+ ]++ operations = [+ migrations.CreateModel(+ name="FeatureRequest",+ fields=[+ (+ "id",+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),+ ),+ ("title", models.CharField(max_length=400)),+ ("description", models.TextField()),+ ("status", models.CharField(choices=[("requested", "Requested")], default="requested", max_length=32)),+ ("idempotency_key", models.UUIDField(blank=True, null=True)),+ ("created_by_id", models.BigIntegerField(blank=True, null=True)),+ ("updated_by_id", models.BigIntegerField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "team",+ models.ForeignKey(+ db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to="posthog.team"+ ),+ ),+ ],+ options={+ "ordering": ["-updated_at", "-created_at", "-id"],+ },+ ),+ migrations.CreateModel(+ name="FeatureRequestProductArea",+ fields=[+ (+ "id",+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),+ ),+ ("name", models.CharField(max_length=200)),+ ("display_order", models.PositiveIntegerField(default=0)),+ ("is_active", models.BooleanField(default=True)),+ ("created_by_id", models.BigIntegerField(blank=True, null=True)),+ ("updated_by_id", models.BigIntegerField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "team",+ models.ForeignKey(+ db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to="posthog.team"+ ),+ ),+ ],+ options={+ "ordering": ["display_order", "name", "id"],+ },+ ),+ migrations.CreateModel(+ name="FeatureRequestProductAreaLink",+ fields=[+ (+ "id",+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "feature_request",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="product_area_links",+ to="customer_analytics.featurerequest",+ ),+ ),+ (+ "product_area",+ models.ForeignKey(+ on_delete=django.db.models.deletion.PROTECT,+ related_name="request_links",+ to="customer_analytics.featurerequestproductarea",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to="posthog.team"+ ),+ ),+ ],+ ),+ migrations.AddField(+ model_name="featurerequest",+ name="product_areas",+ field=models.ManyToManyField(+ related_name="feature_requests",+ through="customer_analytics.FeatureRequestProductAreaLink",+ to="customer_analytics.featurerequestproductarea",+ ),+ ),+ migrations.CreateModel(+ name="FeatureRequestAccountLink",+ fields=[+ (+ "id",+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "account",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="feature_request_links",+ to="customer_analytics.account",+ ),+ ),+ (+ "feature_request",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="account_links",+ to="customer_analytics.featurerequest",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to="posthog.team"+ ),+ ),+ ],+ options={+ "constraints": [+ models.UniqueConstraint(+ fields=("team", "feature_request", "account"), name="unique_feature_request_account_link"+ )+ ],+ },+ ),+ migrations.AddConstraint(+ model_name="featurerequestproductarea",+ constraint=models.UniqueConstraint(+ django.db.models.functions.text.Lower("name"),+ models.F("team"),+ name="unique_feature_request_area_name_per_team",+ ),+ ),+ migrations.AddConstraint(+ model_name="featurerequestproductarealink",+ constraint=models.UniqueConstraint(+ fields=("team", "feature_request", "product_area"), name="unique_feature_request_product_area_link"+ ),+ ),+ migrations.AddConstraint(+ model_name="featurerequest",+ constraint=models.UniqueConstraint(+ condition=models.Q(("idempotency_key__isnull", False)),+ fields=("team", "idempotency_key"),+ name="unique_feature_request_idempotency_key_per_team",+ ),+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txtindex 6d4ac5556492..f219f1a5cd83 100644--- a/products/customer_analytics/backend/migrations/max_migration.txt+++ b/products/customer_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0030_meeting_models+0031_featurerequest_featurerequestproductarea_and_morediff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.pyindex 4c54c469c33a..91dab99c068a 100644--- a/products/customer_analytics/backend/models/__init__.py+++ b/products/customer_analytics/backend/models/__init__.py@@ -17,6 +17,13 @@ from .custom_property_value import CustomPropertyValuefrom .customer_journey import CustomerJourneyfrom .customer_profile_config import CustomerProfileConfigfrom .event_stream import EventStream, EventStreamMember+from .feature_request import (+ FeatureRequest,+ FeatureRequestAccountLink,+ FeatureRequestProductArea,+ FeatureRequestProductAreaLink,+ FeatureRequestStatus,+)from .meeting import Meeting, MeetingParticipant, MeetingResponseStatus, MeetingStatusfrom .relationship import AccountRelationship, AccountRelationshipDefinitionfrom .team_customer_analytics_config import TeamCustomerAnalyticsConfig@@ -41,6 +48,11 @@ __all__ = ["DisplayType","EventStream","EventStreamMember",+ "FeatureRequest",+ "FeatureRequestAccountLink",+ "FeatureRequestProductArea",+ "FeatureRequestProductAreaLink",+ "FeatureRequestStatus","Meeting","MeetingParticipant","MeetingResponseStatus",diff --git a/products/customer_analytics/backend/models/feature_request.py b/products/customer_analytics/backend/models/feature_request.pynew file mode 100644index 000000000000..0bffce7d4939--- /dev/null+++ b/products/customer_analytics/backend/models/feature_request.py@@ -0,0 +1,107 @@+from django.db import models+from django.db.models import Q++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel+++class FeatureRequestStatus(models.TextChoices):+ REQUESTED = "requested", "Requested"+++class FeatureRequestProductArea(TeamScopedRootMixin, UUIDModel):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ name = models.CharField(max_length=200)+ display_order = models.PositiveIntegerField(default=0)+ is_active = models.BooleanField(default=True)+ created_by_id = models.BigIntegerField(null=True, blank=True)+ updated_by_id = models.BigIntegerField(null=True, blank=True)+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ constraints = [+ models.UniqueConstraint(+ models.functions.Lower("name"),+ models.F("team"),+ name="unique_feature_request_area_name_per_team",+ ),+ ]+ ordering = ["display_order", "name", "id"]+++class FeatureRequest(TeamScopedRootMixin, UUIDModel):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ title = models.CharField(max_length=400)+ description = models.TextField()+ status = models.CharField(+ max_length=32,+ choices=FeatureRequestStatus.choices,+ default=FeatureRequestStatus.REQUESTED,+ )+ idempotency_key = models.UUIDField(null=True, blank=True)+ created_by_id = models.BigIntegerField(null=True, blank=True)+ updated_by_id = models.BigIntegerField(null=True, blank=True)+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)+ product_areas: models.ManyToManyField = models.ManyToManyField(+ FeatureRequestProductArea,+ through="FeatureRequestProductAreaLink",+ related_name="feature_requests",+ )++ class Meta:+ constraints = [+ models.UniqueConstraint(+ fields=["team", "idempotency_key"],+ condition=Q(idempotency_key__isnull=False),+ name="unique_feature_request_idempotency_key_per_team",+ ),+ ]+ ordering = ["-updated_at", "-created_at", "-id"]+++class FeatureRequestAccountLink(TeamScopedRootMixin, UUIDModel):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ feature_request = models.ForeignKey(+ FeatureRequest,+ on_delete=models.CASCADE,+ related_name="account_links",+ )+ account = models.ForeignKey(+ "customer_analytics.Account",+ on_delete=models.CASCADE,+ related_name="feature_request_links",+ )+ created_at = models.DateTimeField(auto_now_add=True)++ class Meta:+ constraints = [+ models.UniqueConstraint(+ fields=["team", "feature_request", "account"],+ name="unique_feature_request_account_link",+ ),+ ]+++class FeatureRequestProductAreaLink(TeamScopedRootMixin, UUIDModel):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ feature_request = models.ForeignKey(+ FeatureRequest,+ on_delete=models.CASCADE,+ related_name="product_area_links",+ )+ product_area = models.ForeignKey(+ FeatureRequestProductArea,+ on_delete=models.PROTECT,+ related_name="request_links",+ )+ created_at = models.DateTimeField(auto_now_add=True)++ class Meta:+ constraints = [+ models.UniqueConstraint(+ fields=["team", "feature_request", "product_area"],+ name="unique_feature_request_product_area_link",+ ),+ ]diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex 989bd3265e39..71ae0a33ca08 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -50,6 +50,9 @@ from products.customer_analytics.backend.facade.contracts import (CustomPropertySourceView,CustomPropertySyncRunView,EventStreamView,+ FeatureRequestAccountView,+ FeatureRequestProductAreaView,+ FeatureRequestView,MeetingParticipantView,MeetingView,)@@ -97,6 +100,109 @@ class AccountPropertiesField(serializers.JSONField):pass+class FeatureRequestProductAreaSerializer(DataclassSerializer):+ id = serializers.UUIDField(read_only=True, help_text="Stable product area ID.")+ name = serializers.CharField(max_length=200, help_text="Team-maintained product area name.")+ display_order = serializers.IntegerField(+ required=False,+ min_value=0,+ default=0,+ help_text="Position in product area selectors. Lower values appear first.",+ )+ is_active = serializers.BooleanField(+ required=False,+ default=True,+ help_text="Whether editors can select this product area for new requests.",+ )+ created_at = serializers.DateTimeField(read_only=True, help_text="When the product area was created.")+ updated_at = serializers.DateTimeField(read_only=True, help_text="When the product area was last updated.")++ class Meta:+ dataclass = FeatureRequestProductAreaView+ ref_name = "FeatureRequestProductArea"+ fields = ["id", "name", "display_order", "is_active", "created_at", "updated_at"]+++class FeatureRequestProductAreaListQuerySerializer(serializers.Serializer):+ include_inactive = serializers.BooleanField(+ required=False,+ default=False,+ help_text="Include inactive product areas. Defaults to false.",+ )+++class FeatureRequestAccountSerializer(DataclassSerializer):+ id = serializers.UUIDField(read_only=True, help_text="ID of the affected Customer Analytics account.")+ name = serializers.CharField(read_only=True, help_text="Name of the affected account.")++ class Meta:+ dataclass = FeatureRequestAccountView+ ref_name = "FeatureRequestAccount"+ fields = ["id", "name"]+++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.")+ description = serializers.CharField(read_only=True, help_text="Customer-facing request description in Markdown.")+ request_status = serializers.ChoiceField(+ read_only=True,+ choices=[("requested", "Requested")],+ help_text="Current customer-facing status. The first release always creates requests as requested.",+ )+ account = FeatureRequestAccountSerializer(read_only=True, help_text="Affected account in the first release.")+ product_areas = FeatureRequestProductAreaSerializer(+ many=True,+ read_only=True,+ help_text="Product areas affected by this request.",+ )+ created_by = serializers.IntegerField(+ read_only=True, allow_null=True, help_text="ID of the user who created the request."+ )+ updated_by = serializers.IntegerField(+ read_only=True, allow_null=True, help_text="ID of the last user to update the request."+ )+ created_at = serializers.DateTimeField(read_only=True, help_text="When the request was created.")+ updated_at = serializers.DateTimeField(read_only=True, help_text="When the request was last updated.")++ class Meta:+ dataclass = FeatureRequestView+ ref_name = "FeatureRequest"+ fields = [+ "id",+ "title",+ "description",+ "request_status",+ "account",+ "product_areas",+ "created_by",+ "updated_by",+ "created_at",+ "updated_at",+ ]+++class FeatureRequestCreateSerializer(serializers.Serializer):+ title = serializers.CharField(+ max_length=400,+ trim_whitespace=True,+ help_text="Required customer-facing request title.",+ )+ description = serializers.CharField(+ trim_whitespace=True,+ help_text="Required customer-facing request description in Markdown.",+ )+ account_id = serializers.UUIDField(help_text="ID of the affected Customer Analytics account.")+ product_area_ids = serializers.ListField(+ child=serializers.UUIDField(),+ allow_empty=False,+ help_text="One or more active product area IDs. Duplicate IDs are ignored.",+ )+ idempotency_key = serializers.UUIDField(+ help_text="Client-generated key that makes retries return the original request instead of creating a duplicate.",+ )++class CustomerProfileConfigSerializer(DataclassSerializer):id = serializers.UUIDField(read_only=True)scope = serializers.ChoiceField(choices=_PROFILE_CONFIG_SCOPE_CHOICES)diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 39d5221dee42..8bed37824c77 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -37,11 +37,17 @@ from posthog.exceptions import Conflictfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.models import OrganizationMembershipfrom posthog.models.user import User-from posthog.permissions import TeamMemberStrictManagementPermission, get_authenticator_scopes, is_service_auth+from posthog.permissions import (+ PostHogFeatureFlagPermission,+ TeamMemberStrictManagementPermission,+ get_authenticator_scopes,+ is_service_auth,+)from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.rbac.user_access_control import UserAccessControl, model_to_resourcefrom products.customer_analytics.backend.facade import api, contracts+from products.customer_analytics.backend.facade.constants import CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAGfrom products.customer_analytics.backend.presentation.views.serializers import (AccountChannelSummarySerializer,AccountNotebookSerializer,@@ -66,6 +72,10 @@ from products.customer_analytics.backend.presentation.views.serializers import (EventStreamMemberWriteSerializer,EventStreamSerializer,EventStreamTestMessageSerializer,+ FeatureRequestCreateSerializer,+ FeatureRequestProductAreaListQuerySerializer,+ FeatureRequestProductAreaSerializer,+ FeatureRequestSerializer,MeetingSerializer,SupportTicketSerializer,)@@ -185,6 +195,147 @@ def _assert_group_scope(request: Request, *, write: bool) -> None:raise PermissionDenied(f"This action requires the `group:{'write' if write else 'read'}` API scope.")+class FeatureRequestProductAreaViewSet(+ TeamAndOrgViewSetMixin,+ AccessControlViewSetMixin,+ mixins.ListModelMixin,+ mixins.CreateModelMixin,+ mixins.UpdateModelMixin,+ viewsets.GenericViewSet,+):+ scope_object = "customer_analytics"+ serializer_class = FeatureRequestProductAreaSerializer+ queryset = None+ permission_classes = [PostHogFeatureFlagPermission]+ posthog_feature_flag = CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG+ pagination_class = None++ def _require_manager(self) -> None:+ if not self.user_access_control.check_access_level_for_resource("customer_analytics", "manager"):+ raise PermissionDenied("Manager access to Customer Analytics is required to manage product areas.")++ @validated_request(+ query_serializer=FeatureRequestProductAreaListQuerySerializer,+ responses={200: OpenApiResponse(response=FeatureRequestProductAreaSerializer(many=True))},+ )+ def list(self, request: ValidatedRequest, *args, **kwargs) -> Response:+ include_inactive = request.validated_query_data["include_inactive"]+ product_areas = api.list_feature_request_product_areas(+ self.team_id,+ include_inactive=include_inactive,+ )+ return Response(FeatureRequestProductAreaSerializer(instance=product_areas, many=True).data)++ def create(self, request: Request, *args, **kwargs) -> Response:+ self._require_manager()+ serializer = FeatureRequestProductAreaSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data+ try:+ product_area = api.create_feature_request_product_area(+ team_id=self.team_id,+ name=data.name,+ display_order=data.display_order,+ actor_id=cast(User, request.user).id,+ )+ except api.FeatureRequestValidationError as error:+ raise ValidationError({error.field: error.message})+ except api.FeatureRequestProductAreaConflictError as error:+ raise Conflict(str(error))+ return Response(FeatureRequestProductAreaSerializer(instance=product_area).data, status=status.HTTP_201_CREATED)++ def update(self, request: Request, *args, **kwargs) -> Response:+ self._require_manager()+ partial = kwargs.pop("partial", False)+ serializer = FeatureRequestProductAreaSerializer(data=request.data, partial=partial)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data+ try:+ product_area = api.update_feature_request_product_area(+ team_id=self.team_id,+ product_area_id=self.kwargs["pk"],+ name=data.name if "name" in request.data else None,+ display_order=data.display_order if "display_order" in request.data else None,+ is_active=data.is_active if "is_active" in request.data else None,+ actor_id=cast(User, request.user).id,+ )+ except api.FeatureRequestValidationError as error:+ raise ValidationError({error.field: error.message})+ except api.FeatureRequestProductAreaConflictError as error:+ raise Conflict(str(error))+ if product_area is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(FeatureRequestProductAreaSerializer(instance=product_area).data)++ def partial_update(self, request: Request, *args, **kwargs) -> Response:+ kwargs["partial"] = True+ return self.update(request, *args, **kwargs)+++class FeatureRequestViewSet(+ TeamAndOrgViewSetMixin,+ AccessControlViewSetMixin,+ _FacadePaginationMixin,+ mixins.ListModelMixin,+ mixins.RetrieveModelMixin,+ mixins.CreateModelMixin,+ viewsets.GenericViewSet,+):+ scope_object = "customer_analytics"+ serializer_class = FeatureRequestSerializer+ queryset = None+ permission_classes = [PostHogFeatureFlagPermission]+ posthog_feature_flag = CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG++ def list(self, request: Request, *args, **kwargs) -> Response:+ return self._paginate_via_facade(+ request,+ lambda offset, limit: api.list_feature_requests(+ team_id=self.team_id,+ user_access_control=self.user_access_control,+ offset=offset,+ limit=limit,+ ),+ FeatureRequestSerializer,+ )++ def retrieve(self, request: Request, *args, **kwargs) -> Response:+ feature_request = api.get_feature_request(+ team_id=self.team_id,+ feature_request_id=self.kwargs["pk"],+ user_access_control=self.user_access_control,+ )+ 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=FeatureRequestCreateSerializer,+ responses={200: FeatureRequestSerializer, 201: FeatureRequestSerializer},+ )+ def create(self, request: Request, *args, **kwargs) -> Response:+ serializer = FeatureRequestCreateSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data+ try:+ outcome = api.create_feature_request(+ team_id=self.team_id,+ input=contracts.CreateFeatureRequestInput(+ title=data["title"],+ description=data["description"],+ account_id=data["account_id"],+ product_area_ids=tuple(data["product_area_ids"]),+ idempotency_key=data["idempotency_key"],+ ),+ 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})+ response_status = status.HTTP_201_CREATED if outcome.created else status.HTTP_200_OK+ return Response(FeatureRequestSerializer(instance=outcome.request).data, status=response_status)++class CustomerProfileConfigViewSet(TeamAndOrgViewSetMixin,_FacadePaginationMixin,diff --git a/products/customer_analytics/backend/routes.py b/products/customer_analytics/backend/routes.pyindex 78caffc568ec..bcafc3c8bf53 100644--- a/products/customer_analytics/backend/routes.py+++ b/products/customer_analytics/backend/routes.py@@ -17,6 +17,8 @@ from products.customer_analytics.backend.presentation.views.views import (CustomPropertySourceViewSet,CustomPropertyValueViewSet,EventStreamViewSet,+ FeatureRequestProductAreaViewSet,+ FeatureRequestViewSet,)@@ -40,6 +42,18 @@ def register_routes(routers: RouterRegistry) -> None:["team_id"],)routers.projects.register(r"customer_journeys", CustomerJourneyViewSet, "project_customer_journeys", ["team_id"])+ routers.projects.register(+ r"feature_request_product_areas",+ FeatureRequestProductAreaViewSet,+ "project_feature_request_product_areas",+ ["team_id"],+ )+ routers.projects.register(+ r"feature_requests",+ FeatureRequestViewSet,+ "project_feature_requests",+ ["team_id"],+ )routers.projects.register(r"custom_property_definitions",CustomPropertyDefinitionViewSet,diff --git a/products/customer_analytics/backend/test/test_feature_requests.py b/products/customer_analytics/backend/test/test_feature_requests.pynew file mode 100644index 000000000000..016e9a5fcb58--- /dev/null+++ b/products/customer_analytics/backend/test/test_feature_requests.py@@ -0,0 +1,184 @@+from uuid import uuid4++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from rest_framework import status++from posthog.models import OrganizationMembership, Team, User+from posthog.models.organization import AvailableFeature+from posthog.models.scoping import team_scope++from products.customer_analytics.backend.models import FeatureRequest, FeatureRequestProductArea+from products.customer_analytics.backend.test.factories import create_account++from ee.models.rbac.access_control import AccessControl+++class TestFeatureRequestsAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ self.flag_patcher = patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True)+ self.flag_patcher.start()+ self.addCleanup(self.flag_patcher.stop)+ self.account = create_account(team_id=self.team.id, name="Acme")+ self.area_one = FeatureRequestProductArea.objects.for_team(self.team.id).create(+ team=self.team,+ name="Product analytics",+ display_order=1,+ created_by_id=self.user.id,+ updated_by_id=self.user.id,+ )+ self.area_two = FeatureRequestProductArea.objects.for_team(self.team.id).create(+ team=self.team,+ name="Session replay",+ display_order=2,+ created_by_id=self.user.id,+ updated_by_id=self.user.id,+ )+ self.requests_url = f"/api/projects/{self.team.id}/feature_requests/"+ self.product_areas_url = f"/api/projects/{self.team.id}/feature_request_product_areas/"++ def _payload(self) -> dict[str, object]:+ return {+ "title": "Export account-level retention data",+ "description": "The customer needs this for their monthly reporting workflow.",+ "account_id": str(self.account.id),+ "product_area_ids": [str(self.area_one.id), str(self.area_two.id)],+ "idempotency_key": str(uuid4()),+ }++ def _set_access_level(self, user: User, access_level: str) -> None:+ membership = OrganizationMembership.objects.get(user=user, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="customer_analytics",+ resource_id=None,+ access_level=access_level,+ organization_member=membership,+ )++ def test_editor_can_create_and_view_a_request_with_multiple_product_areas_idempotently(self) -> None:+ payload = self._payload()++ created = self.client.post(self.requests_url, payload, format="json")+ repeated = self.client.post(self.requests_url, payload, format="json")+ listed = self.client.get(self.requests_url)+ retrieved = self.client.get(f"{self.requests_url}{created.json()['id']}/")++ self.assertEqual(created.status_code, status.HTTP_201_CREATED)+ self.assertEqual(repeated.status_code, status.HTTP_200_OK)+ self.assertEqual(repeated.json()["id"], created.json()["id"])+ self.assertEqual(listed.status_code, status.HTTP_200_OK)+ self.assertEqual(listed.json()["count"], 1)+ self.assertEqual(retrieved.status_code, status.HTTP_200_OK)+ self.assertEqual(retrieved.json()["account"]["name"], "Acme")+ self.assertEqual(+ {area["name"] for area in retrieved.json()["product_areas"]},+ {"Product analytics", "Session replay"},+ )+ self.assertEqual(retrieved.json()["request_status"], "requested")+ self.assertEqual(FeatureRequest.objects.for_team(self.team.id).count(), 1)++ def test_create_rejects_relations_from_another_team(self) -> None:+ other_team = Team.objects.create(organization=self.organization)+ with team_scope(other_team.id):+ other_account = create_account(team_id=other_team.id, name="Other account")+ other_area = FeatureRequestProductArea.objects.for_team(other_team.id).create(+ team=other_team,+ name="Other area",+ )+ payload = self._payload()+ payload["account_id"] = str(other_account.id)+ payload["product_area_ids"] = [str(other_area.id)]++ response = self.client.post(self.requests_url, payload, format="json")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(FeatureRequest.objects.for_team(self.team.id).count(), 0)++ def test_idempotency_retry_does_not_expose_a_request_for_an_inaccessible_account(self) -> None:+ payload = self._payload()+ created = self.client.post(self.requests_url, payload, format="json").json()+ restricted_editor = User.objects.create_and_join(+ self.organization,+ "[email protected]",+ "testtest",+ )+ self._set_access_level(restricted_editor, "editor")+ membership = OrganizationMembership.objects.get(user=restricted_editor, 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(restricted_editor)++ listed = self.client.get(self.requests_url)+ retrieved = self.client.get(f"{self.requests_url}{created['id']}/")+ response = self.client.post(self.requests_url, payload, format="json")++ self.assertEqual(listed.status_code, status.HTTP_200_OK)+ self.assertEqual(listed.json()["count"], 0)+ self.assertEqual(retrieved.status_code, status.HTTP_404_NOT_FOUND)+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertNotIn("Export account-level retention data", str(response.json()))++ def test_viewer_can_read_but_cannot_create(self) -> None:+ payload = self._payload()+ created = self.client.post(self.requests_url, payload, format="json").json()+ viewer = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ self._set_access_level(viewer, "viewer")+ self.client.force_login(viewer)++ listed = self.client.get(self.requests_url)+ retrieved = self.client.get(f"{self.requests_url}{created['id']}/")+ create_attempt = self.client.post(self.requests_url, self._payload(), format="json")++ self.assertEqual(listed.status_code, status.HTTP_200_OK)+ self.assertEqual(retrieved.status_code, status.HTTP_200_OK)+ self.assertEqual(create_attempt.status_code, status.HTTP_403_FORBIDDEN)++ def test_feature_flag_blocks_the_api_without_deleting_data(self) -> None:+ created = self.client.post(self.requests_url, self._payload(), format="json")++ with patch("posthog.permissions.posthog_feature_flag_enabled", return_value=False):+ blocked = self.client.get(self.requests_url)++ self.assertEqual(created.status_code, status.HTTP_201_CREATED)+ self.assertEqual(blocked.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(FeatureRequest.objects.for_team(self.team.id).count(), 1)++ def test_product_area_list_rejects_invalid_include_inactive(self) -> None:+ response = self.client.get(self.product_areas_url, {"include_inactive": "sometimes"})++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_only_manager_can_create_and_update_product_areas(self) -> None:+ editor = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ self._set_access_level(editor, "editor")+ self.client.force_login(editor)+ denied = self.client.post(self.product_areas_url, {"name": "Surveys"}, format="json")++ manager = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ self._set_access_level(manager, "manager")+ self.client.force_login(manager)+ created = self.client.post(self.product_areas_url, {"name": "Surveys", "display_order": 3}, format="json")+ updated = self.client.patch(+ f"{self.product_areas_url}{created.json()['id']}/",+ {"name": "User surveys", "is_active": False},+ format="json",+ )++ self.assertEqual(denied.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(created.status_code, status.HTTP_201_CREATED)+ self.assertEqual(updated.status_code, status.HTTP_200_OK)+ self.assertEqual(updated.json()["name"], "User surveys")+ self.assertFalse(updated.json()["is_active"])diff --git a/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsx b/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsxindex 18245a47ecc1..66b840038d15 100644--- a/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsx+++ b/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsx@@ -98,6 +98,60 @@ export const B2BModeWithoutGroups: Story = {},}+export const FeatureRequests: Story = {+ render: () => {+ useStorybookMocks({+ get: {+ 'api/projects/:team_id/feature_requests/': {+ count: 1,+ next: null,+ previous: null,+ results: [+ {+ id: '018f47de-7e12-7000-8000-000000000001',+ title: 'Export account-level retention data',+ description: 'The customer needs this export for their monthly reporting workflow.',+ request_status: 'requested',+ account: { id: '018f47de-7e12-7000-8000-000000000002', name: 'Acme' },+ product_areas: [+ {+ id: '018f47de-7e12-7000-8000-000000000003',+ name: 'Product analytics',+ display_order: 1,+ is_active: true,+ created_at: '2024-01-10T10:00:00Z',+ updated_at: '2024-01-10T10:00:00Z',+ },+ {+ id: '018f47de-7e12-7000-8000-000000000004',+ name: 'Data warehouse',+ display_order: 2,+ is_active: true,+ created_at: '2024-01-10T10:00:00Z',+ updated_at: '2024-01-10T10:00:00Z',+ },+ ],+ created_by: 1,+ updated_by: 1,+ created_at: '2024-01-12T10:00:00Z',+ updated_at: '2024-01-14T10:00:00Z',+ },+ ],+ },+ 'api/projects/:team_id/feature_request_product_areas/': [],+ },+ })+ return <App />+ },+ parameters: {+ featureFlags: [FEATURE_FLAGS.CUSTOMER_ANALYTICS, FEATURE_FLAGS.CUSTOMER_ANALYTICS_FEATURE_REQUESTS],+ pageUrl: urls.customerAnalyticsFeatureRequests(),+ testOptions: {+ waitForSelector: '[data-attr="new-feature-request"]',+ },+ },+}+export const GatedWithoutMatchingEarlyAccessFeature: Story = {render: () => <App />,parameters: {diff --git a/products/customer_analytics/frontend/CustomerAnalyticsScene.tsx b/products/customer_analytics/frontend/CustomerAnalyticsScene.tsxindex a59f476deca4..9cd8d7f111ad 100644--- a/products/customer_analytics/frontend/CustomerAnalyticsScene.tsx+++ b/products/customer_analytics/frontend/CustomerAnalyticsScene.tsx@@ -36,6 +36,7 @@ import { CustomerJourneySelect } from './components/CustomerJourneys/CustomerJouimport { customerJourneysLogic } from './components/CustomerJourneys/customerJourneysLogic'import { DeleteJourneyButton } from './components/CustomerJourneys/DeleteJourneyButton'import { journeyEditorLogic } from './components/CustomerJourneys/journeyEditorLogic'+import { FeatureRequestsTabContent } from './components/FeatureRequests/FeatureRequestsTabContent'import { FeedTabContent } from './components/Feed/FeedTabContent'import { FeedbackButton } from './components/FeedbackButton'import { ActiveUsersInsights } from './components/Insights/ActiveUsersInsights'@@ -66,7 +67,7 @@ function CustomerAnalyticsSceneContent(): JSX.Element {const { businessType, activeTab } = useValues(customerAnalyticsSceneLogic)const { shouldShowGroupsIntroduction } = useValues(groupsAccessLogic)const { featureFlags } = useValues(featureFlagLogic)- const { searchParams } = useValues(router)+ const { location, searchParams } = useValues(router)const { isEditMode, stagedNodes, isSaving } = useValues(journeyEditorLogic)const { saveChanges, cancelChanges } = useActions(journeyEditorLogic)const { activeJourney } = useValues(customerJourneysLogic)@@ -90,6 +91,10 @@ function CustomerAnalyticsSceneContent(): JSX.Element {return <NotFound object="page" />}+ if (activeTab === 'feature_requests' && !featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_FEATURE_REQUESTS]) {+ return <NotFound object="page" />+ }+const dashboardContent =businessType === 'b2b' && shouldShowGroupsIntroduction ? (<>@@ -136,6 +141,15 @@ function CustomerAnalyticsSceneContent(): JSX.Element {})}+ if (featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_FEATURE_REQUESTS]) {+ tabs.push({+ key: 'feature_requests',+ label: 'Feature requests',+ content: <FeatureRequestsTabContent />,+ link: combineUrl(urls.customerAnalyticsFeatureRequests(), searchParams).url,+ })+ }+tabs.push({key: 'dashboard',label: 'Dashboard',@@ -158,99 +172,109 @@ function CustomerAnalyticsSceneContent(): JSX.Element {) : (dashboardContent)+ const isFeatureRequestDetail =+ activeTab === 'feature_requests' && /\/customer_analytics\/feature-requests\/[^/]+\/?$/.test(location.pathname)return (<BindLogic logic={dataNodeCollectionLogic} props={{ key: CUSTOMER_ANALYTICS_DATA_COLLECTION_NODE_ID }}>- <SceneContent>- <SceneTitleSection- name={sceneConfigurations[Scene.CustomerAnalytics].name}- description={sceneConfigurations[Scene.CustomerAnalytics].description}- resourceType={{- type: sceneConfigurations[Scene.CustomerAnalytics].iconType || 'default_icon_type',- }}- actions={- <>- <FeedbackButton id="customer-analytics-dashboard-feedback-button" />- {isEditMode ? (- <div className="flex items-center gap-2">- <span className="text-sm text-muted font-medium whitespace-nowrap">- {stagedNodes.length} step{stagedNodes.length !== 1 ? 's' : ''} to add- </span>- <LemonButton type="secondary" size="small" onClick={cancelChanges}>- Cancel- </LemonButton>- <LemonButton- type="primary"- size="small"- onClick={saveChanges}- disabledReason={- accessControlDisabledReason ??- (stagedNodes.length === 0 ? 'No steps staged' : undefined)- }- loading={isSaving}- >- Save- </LemonButton>- </div>- ) : activeTab === 'journeys' ? (+ <SceneContent className={isFeatureRequestDetail ? 'gap-y-0 border-b-0 flex-1 min-h-0' : undefined}>+ {isFeatureRequestDetail ? (+ <div className="flex flex-col -mx-4 flex-1 min-h-0 overflow-auto">+ <FeatureRequestsTabContent />+ </div>+ ) : (+ <>+ <SceneTitleSection+ name={sceneConfigurations[Scene.CustomerAnalytics].name}+ description={sceneConfigurations[Scene.CustomerAnalytics].description}+ resourceType={{+ type: sceneConfigurations[Scene.CustomerAnalytics].iconType || 'default_icon_type',+ }}+ actions={<>- <CustomerJourneySelect />- <LemonButton- type="primary"- size="small"- to={urls.customerJourneyTemplates()}- data-attr="new-journey"- disabledReason={accessControlDisabledReason}- >- New journey- </LemonButton>- {activeJourney && (- <LemonButton- type="secondary"- size="small"- to={`${urls.customerJourneyEdit(activeJourney.id)}?insightId=${activeJourney.insight}`}- data-attr="edit-journey"+ <FeedbackButton id="customer-analytics-dashboard-feedback-button" />+ {isEditMode ? (+ <div className="flex items-center gap-2">+ <span className="text-sm text-muted font-medium whitespace-nowrap">+ {stagedNodes.length} step{stagedNodes.length !== 1 ? 's' : ''} to add+ </span>+ <LemonButton type="secondary" size="small" onClick={cancelChanges}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ size="small"+ onClick={saveChanges}+ disabledReason={+ accessControlDisabledReason ??+ (stagedNodes.length === 0 ? 'No steps staged' : undefined)+ }+ loading={isSaving}+ >+ Save+ </LemonButton>+ </div>+ ) : activeTab === 'journeys' ? (+ <>+ <CustomerJourneySelect />+ <LemonButton+ type="primary"+ size="small"+ to={urls.customerJourneyTemplates()}+ data-attr="new-journey"+ disabledReason={accessControlDisabledReason}+ >+ New journey+ </LemonButton>+ {activeJourney && (+ <LemonButton+ type="secondary"+ size="small"+ to={`${urls.customerJourneyEdit(activeJourney.id)}?insightId=${activeJourney.insight}`}+ data-attr="edit-journey"+ >+ Edit+ </LemonButton>+ )}+ <DeleteJourneyButton />+ </>+ ) : (+ <Shortcut+ name="CustomerAnalyticsSettings"+ keybind={[keyBinds.settings]}+ intent="Configure customer analytics"+ interaction="click"+ scope={Scene.CustomerAnalytics}>- Edit- </LemonButton>+ <LemonButton+ icon={<IconGear />}+ size="small"+ type="secondary"+ to={+ activeTab === 'accounts'+ ? `${urls.customerAnalyticsConfiguration()}?tab=customer-analytics-accounts`+ : urls.customerAnalyticsConfiguration()+ }+ onClick={() => {+ addProductIntent({+ product_type: ProductKey.CUSTOMER_ANALYTICS,+ intent_context:+ ProductIntentContext.CUSTOMER_ANALYTICS_DASHBOARD_CONFIGURATION_BUTTON_CLICKED,+ })+ reportCustomerAnalyticsDashboardConfigurationButtonClicked()+ }}+ tooltip="Configure customer analytics"+ children="Configure"+ data-attr="customer-analytics-config"+ />+ </Shortcut>)}- <DeleteJourneyButton /></>- ) : (- <Shortcut- name="CustomerAnalyticsSettings"- keybind={[keyBinds.settings]}- intent="Configure customer analytics"- interaction="click"- scope={Scene.CustomerAnalytics}- >- <LemonButton- icon={<IconGear />}- size="small"- type="secondary"- to={- activeTab === 'accounts'- ? `${urls.customerAnalyticsConfiguration()}?tab=customer-analytics-accounts`- : urls.customerAnalyticsConfiguration()- }- onClick={() => {- addProductIntent({- product_type: ProductKey.CUSTOMER_ANALYTICS,- intent_context:- ProductIntentContext.CUSTOMER_ANALYTICS_DASHBOARD_CONFIGURATION_BUTTON_CLICKED,- })- reportCustomerAnalyticsDashboardConfigurationButtonClicked()- }}- tooltip="Configure customer analytics"- children="Configure"- data-attr="customer-analytics-config"- />- </Shortcut>- )}- </>- }- />- {tabsContent}+ }+ />+ {tabsContent}+ </>+ )}</SceneContent></BindLogic>)diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestsTabContent.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestsTabContent.tsxnew file mode 100644index 000000000000..477979920fe6--- /dev/null+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestsTabContent.tsx@@ -0,0 +1,545 @@+import { useActions, useValues } from 'kea'+import { ReactNode } from 'react'++import { IconArrowLeft, IconBuilding, IconDocument, IconFolder, IconPeople } from '@posthog/icons'+import {+ LemonBanner,+ LemonButton,+ LemonInput,+ LemonInputSelect,+ LemonLabel,+ LemonModal,+ LemonSkeleton,+ LemonSwitch,+ LemonTable,+ LemonTableColumns,+ LemonTag,+ LemonTextArea,+ Link,+} from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'+import { urls } from 'scenes/urls'++import { AccessControlLevel, AccessControlResourceType } from '~/types'++import type { FeatureRequestApi, FeatureRequestProductAreaApi } from '../../generated/api.schemas'+import { FEATURE_REQUESTS_PAGE_SIZE, featureRequestsLogic } from './featureRequestsLogic'++function CreateRequestModal(): JSX.Element {+ const {+ createRequestOpen,+ title,+ description,+ accountId,+ productAreaIds,+ accountOptions,+ productAreaOptions,+ accountsLoading,+ accountsError,+ productAreasLoading,+ productAreasError,+ submittingRequest,+ submitDisabledReason,+ } = useValues(featureRequestsLogic)+ const {+ closeCreateRequest,+ setTitle,+ setDescription,+ setAccountId,+ setAccountSearch,+ setProductAreaIds,+ submitRequest,+ loadAccounts,+ loadProductAreas,+ } = useActions(featureRequestsLogic)++ return (+ <LemonModal+ isOpen={createRequestOpen}+ onClose={closeCreateRequest}+ title="New feature request"+ width={640}+ footer={+ <>+ <LemonButton type="secondary" onClick={closeCreateRequest}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={submitRequest}+ loading={submittingRequest}+ disabledReason={submitDisabledReason}+ data-attr="save-feature-request"+ >+ Save request+ </LemonButton>+ </>+ }+ >+ <div className="flex flex-col gap-4">+ {accountsError && (+ <LemonBanner type="error" action={{ children: 'Try again', onClick: () => loadAccounts('') }}>+ {accountsError}+ </LemonBanner>+ )}+ {productAreasError && (+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadProductAreas }}>+ {productAreasError}+ </LemonBanner>+ )}+ <div className="flex flex-col gap-1">+ <LemonLabel>Title</LemonLabel>+ <LemonInput+ value={title}+ onChange={setTitle}+ placeholder="What does the customer need?"+ maxLength={400}+ autoFocus+ fullWidth+ />+ </div>+ <div className="flex flex-col gap-1">+ <LemonLabel>Description</LemonLabel>+ <LemonTextArea+ value={description}+ onChange={setDescription}+ placeholder="Describe the request in the customer's language"+ minRows={5}+ />+ </div>+ <div className="flex flex-col gap-1">+ <LemonLabel>Account</LemonLabel>+ <LemonInputSelect+ mode="single"+ value={accountId ? [accountId] : []}+ onChange={(values) => setAccountId(values[0] ?? null)}+ onInputChange={setAccountSearch}+ options={accountOptions}+ placeholder="Search for an account"+ loading={accountsLoading}+ fullWidth+ />+ </div>+ <div className="flex flex-col gap-1">+ <LemonLabel>Product areas</LemonLabel>+ <LemonInputSelect+ mode="multiple"+ value={productAreaIds}+ onChange={setProductAreaIds}+ options={productAreaOptions}+ placeholder="Select one or more product areas"+ loading={productAreasLoading}+ />+ </div>+ </div>+ </LemonModal>+ )+}++function ProductAreasModal(): JSX.Element {+ const {+ productAreasOpen,+ productAreas,+ productAreasLoading,+ productAreasError,+ editingProductAreaId,+ productAreaName,+ productAreaDisplayOrder,+ productAreaActive,+ savingProductArea,+ productAreaSaveDisabledReason,+ } = useValues(featureRequestsLogic)+ const {+ closeProductAreas,+ startNewProductArea,+ startEditingProductArea,+ setProductAreaName,+ setProductAreaDisplayOrder,+ setProductAreaActive,+ saveProductArea,+ loadProductAreas,+ } = useActions(featureRequestsLogic)++ const columns: LemonTableColumns<FeatureRequestProductAreaApi> = [+ { title: 'Name', key: 'name', dataIndex: 'name' },+ {+ title: 'Status',+ key: 'is_active',+ render: (_, area) => (+ <LemonTag type={area.is_active ? 'success' : 'default'}>+ {area.is_active ? 'Active' : 'Inactive'}+ </LemonTag>+ ),+ },+ { title: 'Order', key: 'display_order', render: (_, area) => area.display_order ?? 0 },+ {+ title: '',+ key: 'actions',+ align: 'right',+ render: (_, area) => (+ <LemonButton type="tertiary" size="small" onClick={() => startEditingProductArea(area)}>+ Edit+ </LemonButton>+ ),+ },+ ]++ return (+ <LemonModal+ isOpen={productAreasOpen}+ onClose={closeProductAreas}+ title="Manage product areas"+ width={720}+ footer={+ <LemonButton type="secondary" onClick={closeProductAreas}>+ Done+ </LemonButton>+ }+ >+ <div className="flex flex-col gap-4">+ {productAreasError && (+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadProductAreas }}>+ {productAreasError}+ </LemonBanner>+ )}+ <LemonTable+ dataSource={productAreas}+ columns={columns}+ rowKey="id"+ loading={productAreasLoading}+ emptyState="No product areas yet"+ />+ <div className="border rounded p-4 flex flex-col gap-3">+ <div className="flex items-center justify-between">+ <h3 className="m-0">{editingProductAreaId ? 'Edit product area' : 'New product area'}</h3>+ {editingProductAreaId && (+ <LemonButton type="tertiary" size="small" onClick={startNewProductArea}>+ Add another+ </LemonButton>+ )}+ </div>+ <div className="flex flex-col gap-1">+ <LemonLabel>Name</LemonLabel>+ <LemonInput+ value={productAreaName}+ onChange={setProductAreaName}+ placeholder="Product analytics"+ maxLength={200}+ fullWidth+ />+ </div>+ <div className="flex flex-col gap-1">+ <LemonLabel>Display order</LemonLabel>+ <LemonInput+ type="number"+ min={0}+ value={productAreaDisplayOrder}+ onChange={(value) => setProductAreaDisplayOrder(Math.max(0, value ?? 0))}+ fullWidth+ />+ </div>+ <LemonSwitch+ checked={productAreaActive}+ onChange={setProductAreaActive}+ label="Available for new requests"+ />+ <div>+ <LemonButton+ type="primary"+ onClick={saveProductArea}+ loading={savingProductArea}+ disabledReason={productAreaSaveDisabledReason}+ >+ {editingProductAreaId ? 'Save changes' : 'Add product area'}+ </LemonButton>+ </div>+ </div>+ </div>+ </LemonModal>+ )+}++function FeatureRequestDetailSkeleton(): JSX.Element {+ return (+ <div+ className="@container w-full max-w-[calc(160ch+5rem)] mx-auto px-6 py-5 text-sm"+ role="status"+ aria-label="Loading feature request"+ >+ <div className="flex flex-col gap-3.5 mb-6 pb-5 border-b border-primary" aria-hidden>+ <LemonSkeleton className="h-7 w-32 rounded" />+ <div className="flex flex-col gap-2 min-w-0">+ <LemonSkeleton className="h-6 w-2/3 max-w-xl rounded" />+ <div className="flex items-center gap-2">+ <LemonSkeleton className="h-5 w-20 rounded-full" />+ <LemonSkeleton className="h-3 w-56 rounded" />+ </div>+ </div>+ </div>++ <div className="grid grid-cols-1 @5xl:grid-cols-[minmax(0,80ch)_minmax(22rem,1fr)] gap-5" aria-hidden>+ <div className="min-w-0 flex flex-col gap-3">+ <div className="flex items-center gap-3">+ <LemonSkeleton className="h-4 w-28 rounded" />+ <div className="h-px min-w-4 flex-1 bg-border-light" />+ </div>+ <div className="flex flex-col gap-2.5">+ <LemonSkeleton className="h-3 w-full rounded" />+ <LemonSkeleton className="h-3 w-11/12 rounded" />+ <LemonSkeleton className="h-3 w-4/5 rounded" />+ <LemonSkeleton className="h-3 w-2/3 rounded" />+ </div>+ </div>++ <div className="flex flex-col min-w-0 gap-5">+ <div className="flex flex-col gap-3">+ <div className="flex items-center gap-3">+ <LemonSkeleton className="h-4 w-24 rounded" />+ <div className="h-px min-w-4 flex-1 bg-border-light" />+ </div>+ <div className="flex items-center gap-3 rounded border border-primary bg-surface-primary px-3 py-2.5">+ <LemonSkeleton className="size-8 shrink-0 rounded" />+ <div className="flex flex-1 flex-col gap-1.5">+ <LemonSkeleton className="h-3.5 w-32 rounded" />+ <LemonSkeleton className="h-2.5 w-16 rounded" />+ </div>+ </div>+ </div>+ <div className="flex flex-col gap-3">+ <div className="flex items-center gap-3">+ <LemonSkeleton className="h-4 w-28 rounded" />+ <div className="h-px min-w-4 flex-1 bg-border-light" />+ </div>+ <div className="flex gap-1.5">+ <LemonSkeleton className="h-5 w-24 rounded-full" />+ <LemonSkeleton className="h-5 w-20 rounded-full" />+ </div>+ </div>+ </div>+ </div>+ </div>+ )+}++function FeatureRequestDetailSection({+ icon,+ title,+ children,+}: {+ icon: ReactNode+ title: string+ children: ReactNode+}): JSX.Element {+ return (+ <section className="flex flex-col gap-3">+ <div className="flex items-center gap-3 min-w-0">+ <div className="flex items-center gap-2 min-w-0">+ <span className="flex shrink-0 items-center text-secondary [&_svg]:size-[0.9375rem]">{icon}</span>+ <h2 className="m-0 truncate text-sm font-semibold tracking-tight">{title}</h2>+ </div>+ <div className="h-px min-w-4 flex-1 bg-border-light" />+ </div>+ <div>{children}</div>+ </section>+ )+}++function FeatureRequestDetail({ request }: { request: FeatureRequestApi }): JSX.Element {+ return (+ <div className="@container w-full max-w-[calc(160ch+5rem)] mx-auto px-6 py-5 text-sm">+ <header className="flex flex-col gap-3.5 mb-6 pb-5 border-b border-primary">+ <LemonButton+ type="tertiary"+ size="small"+ icon={<IconArrowLeft />}+ to={urls.customerAnalyticsFeatureRequests()}+ className="-ml-2 w-fit"+ >+ Feature requests+ </LemonButton>+ <div className="flex flex-col gap-2 min-w-0">+ <h1 className="m-0 break-words text-xl font-bold leading-tight tracking-tight">{request.title}</h1>+ <div className="flex items-center gap-2 flex-wrap text-xs text-tertiary">+ <LemonTag type="primary">Requested</LemonTag>+ <span className="flex items-center gap-2 flex-wrap">+ <span className="flex items-center gap-1">+ <span>Created</span>+ <TZLabel time={request.created_at} />+ </span>+ <span aria-hidden>·</span>+ <span className="flex items-center gap-1">+ <span>Last updated</span>+ <TZLabel time={request.updated_at} />+ </span>+ </span>+ </div>+ </div>+ </header>++ <div className="grid grid-cols-1 @5xl:grid-cols-[minmax(0,80ch)_minmax(22rem,1fr)] gap-5">+ <div className="min-w-0">+ <FeatureRequestDetailSection icon={<IconDocument />} title="Description">+ <LemonMarkdown+ disableImages+ className="text-sm text-secondary leading-relaxed break-words [&>*+*]:mt-3"+ >+ {request.description}+ </LemonMarkdown>+ </FeatureRequestDetailSection>+ </div>++ <aside className="flex flex-col min-w-0 gap-5">+ <FeatureRequestDetailSection icon={<IconPeople />} title="Requesters">+ <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="flex flex-col min-w-0">+ <span className="truncate font-medium">{request.account.name}</span>+ <span className="text-xs text-tertiary">Account</span>+ </span>+ </Link>+ </FeatureRequestDetailSection>++ <FeatureRequestDetailSection icon={<IconFolder />} title="Product areas">+ <div className="flex flex-wrap gap-1.5">+ {request.product_areas.map((area) => (+ <LemonTag key={area.id}>{area.name}</LemonTag>+ ))}+ </div>+ </FeatureRequestDetailSection>+ </aside>+ </div>+ </div>+ )+}++export function FeatureRequestsTabContent(): JSX.Element {+ const {+ featureRequestsResponse,+ featureRequestsResponseLoading,+ featureRequestsError,+ featureRequestsPage,+ activeRequest,+ activeRequestLoading,+ activeRequestError,+ activeRequestId,+ } = useValues(featureRequestsLogic)+ const { openCreateRequest, openProductAreas, loadFeatureRequests, loadActiveRequest, setFeatureRequestsPage } =+ useActions(featureRequestsLogic)++ const editorDisabledReason = getAccessControlDisabledReason(+ AccessControlResourceType.CustomerAnalytics,+ AccessControlLevel.Editor+ )+ const managerDisabledReason = getAccessControlDisabledReason(+ AccessControlResourceType.CustomerAnalytics,+ AccessControlLevel.Manager+ )++ if (activeRequestId) {+ if (activeRequestError) {+ return (+ <LemonBanner+ type="error"+ action={{ children: 'Try again', onClick: () => loadActiveRequest(activeRequestId) }}+ >+ {activeRequestError}+ </LemonBanner>+ )+ }+ if (activeRequestLoading || !activeRequest) {+ return <FeatureRequestDetailSkeleton />+ }+ return <FeatureRequestDetail request={activeRequest} />+ }++ const columns: LemonTableColumns<FeatureRequestApi> = [+ {+ title: 'Request',+ key: 'title',+ render: (_, request) => (+ <Link to={urls.customerAnalyticsFeatureRequests(request.id)} className="font-semibold">+ {request.title}+ </Link>+ ),+ },+ {+ title: 'Account',+ key: 'account',+ render: (_, request) => request.account.name,+ },+ {+ title: 'Product areas',+ key: 'product_areas',+ render: (_, request) => (+ <div className="flex flex-wrap gap-1">+ {request.product_areas.map((area) => (+ <LemonTag key={area.id}>{area.name}</LemonTag>+ ))}+ </div>+ ),+ },+ {+ title: 'Status',+ key: 'request_status',+ render: () => <LemonTag type="primary">Requested</LemonTag>,+ },+ {+ title: 'Updated',+ key: 'updated_at',+ render: (_, request) => <TZLabel time={request.updated_at} />,+ },+ ]++ return (+ <div className="flex flex-col gap-4">+ <div className="flex items-center justify-end gap-2">+ <LemonButton type="secondary" onClick={openProductAreas} disabledReason={managerDisabledReason}>+ Manage product areas+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={openCreateRequest}+ disabledReason={editorDisabledReason}+ data-attr="new-feature-request"+ >+ New request+ </LemonButton>+ </div>+ {featureRequestsError && (+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadFeatureRequests }}>+ {featureRequestsError}+ </LemonBanner>+ )}+ <LemonTable+ dataSource={featureRequestsResponse.results}+ columns={columns}+ rowKey="id"+ loading={featureRequestsResponseLoading}+ emptyState="No feature requests yet"+ nouns={['feature request', 'feature requests']}+ pagination={{+ controlled: true,+ currentPage: featureRequestsPage,+ pageSize: FEATURE_REQUESTS_PAGE_SIZE,+ entryCount: featureRequestsResponse.count,+ onBackward:+ featureRequestsPage > 1 ? () => setFeatureRequestsPage(featureRequestsPage - 1) : undefined,+ onForward:+ featureRequestsPage * FEATURE_REQUESTS_PAGE_SIZE < featureRequestsResponse.count+ ? () => setFeatureRequestsPage(featureRequestsPage + 1)+ : undefined,+ }}+ />+ <CreateRequestModal />+ <ProductAreasModal />+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.test.ts b/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.test.tsnew file mode 100644index 000000000000..77f12e864ab5--- /dev/null+++ b/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.test.ts@@ -0,0 +1,143 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import * as generatedApi from '../../generated/api'+import type { FeatureRequestApi } from '../../generated/api.schemas'+import { FEATURE_REQUESTS_PAGE_SIZE, featureRequestsLogic } from './featureRequestsLogic'++const createdRequest: FeatureRequestApi = {+ id: 'request-1',+ title: 'Export account-level retention data',+ description: 'The customer needs this for reporting.',+ request_status: 'requested',+ account: { id: 'account-1', name: 'Acme' },+ product_areas: [+ {+ id: 'area-1',+ name: 'Product analytics',+ display_order: 1,+ is_active: true,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ },+ ],+ created_by: 1,+ updated_by: 1,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+}++describe('featureRequestsLogic', () => {+ let logic: ReturnType<typeof featureRequestsLogic.build>++ beforeEach(() => {+ useMocks({+ get: {+ '/api/projects/:team_id/feature_requests/': { count: 0, next: null, previous: null, results: [] },+ '/api/projects/:team_id/feature_requests/:id/': createdRequest,+ '/api/projects/:team_id/feature_request_product_areas/': [],+ '/api/projects/:team_id/accounts/': { count: 0, next: null, previous: null, results: [] },+ },+ })+ initKeaTests(true, MOCK_DEFAULT_TEAM)+ logic = featureRequestsLogic()+ logic.mount()+ })++ afterEach(() => {+ jest.restoreAllMocks()+ logic.unmount()+ })++ it('keeps the request fields after a failed save so the editor can retry', async () => {+ jest.spyOn(generatedApi, 'featureRequestsCreate').mockRejectedValueOnce(new Error('save failed'))+ logic.actions.openCreateRequest()+ logic.actions.setTitle(createdRequest.title)+ logic.actions.setDescription(createdRequest.description)+ logic.actions.setAccountId(createdRequest.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.productAreaIds).toEqual(['area-1'])+ expect(logic.values.createRequestOpen).toBe(true)+ expect(logic.values.submittingRequest).toBe(false)+ })++ it('reloads request rows after a linked product area changes', async () => {+ await expectLogic(logic).toFinishAllListeners()+ const productArea = createdRequest.product_areas[0]+ const renamedRequest: FeatureRequestApi = {+ ...createdRequest,+ product_areas: [{ ...productArea, name: 'Data platform' }],+ }+ jest.spyOn(generatedApi, 'featureRequestProductAreasPartialUpdate').mockResolvedValue({+ ...productArea,+ name: 'Data platform',+ })+ jest.spyOn(generatedApi, 'featureRequestsList').mockResolvedValue({+ count: 1,+ next: null,+ previous: null,+ results: [renamedRequest],+ })+ logic.actions.startEditingProductArea(productArea)+ logic.actions.setProductAreaName('Data platform')++ await expectLogic(logic, () => logic.actions.saveProductArea())+ .toDispatchActions(['loadFeatureRequests', 'loadFeatureRequestsSuccess'])+ .toFinishAllListeners()++ expect(logic.values.featureRequestsResponse.results).toEqual([renamedRequest])+ })++ it('loads the requested page with 20 requests per page', async () => {+ await expectLogic(logic).toFinishAllListeners()+ const listSpy = jest.spyOn(generatedApi, 'featureRequestsList').mockResolvedValue({+ count: 21,+ next: null,+ previous: null,+ results: [createdRequest],+ })++ await expectLogic(logic, () => logic.actions.setFeatureRequestsPage(2))+ .toDispatchActions(['loadFeatureRequests', 'loadFeatureRequestsSuccess'])+ .toFinishAllListeners()++ expect(listSpy).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), {+ limit: FEATURE_REQUESTS_PAGE_SIZE,+ offset: FEATURE_REQUESTS_PAGE_SIZE,+ })+ expect(logic.values.featureRequestsPage).toBe(2)+ expect(logic.values.featureRequestsResponse.count).toBe(21)+ expect(logic.values.featureRequestsResponse.results).toEqual([createdRequest])+ })++ it('ignores a second submit while the first request is in flight', async () => {+ let resolveCreate: (request: FeatureRequestApi) => void = () => undefined+ const createPromise = new Promise<FeatureRequestApi>((resolve) => {+ resolveCreate = resolve+ })+ const createSpy = jest.spyOn(generatedApi, 'featureRequestsCreate').mockReturnValue(createPromise)+ logic.actions.openCreateRequest()+ logic.actions.setTitle(createdRequest.title)+ logic.actions.setDescription(createdRequest.description)+ logic.actions.setAccountId(createdRequest.account.id)+ logic.actions.setProductAreaIds(['area-1'])++ logic.actions.submitRequest()+ logic.actions.submitRequest()+ resolveCreate(createdRequest)+ await expectLogic(logic).toFinishAllListeners()++ expect(createSpy).toHaveBeenCalledTimes(1)+ expect(logic.values.submittingRequest).toBe(false)+ })+})diff --git a/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.ts b/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.tsnew file mode 100644index 000000000000..6b98362d5a6d--- /dev/null+++ b/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.ts@@ -0,0 +1,526 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { router, urlToAction } from 'kea-router'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { uuid } from 'lib/utils/dom'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import type { TeamPublicType, TeamType } from '../../../../../frontend/src/types'+import {+ accountsList,+ featureRequestProductAreasCreate,+ featureRequestProductAreasList,+ featureRequestProductAreasPartialUpdate,+ featureRequestsCreate,+ featureRequestsList,+ featureRequestsRetrieve,+} from '../../generated/api'+import type {+ AccountApi,+ FeatureRequestApi,+ FeatureRequestProductAreaApi,+ PaginatedFeatureRequestListApi,+} from '../../generated/api.schemas'++export const FEATURE_REQUESTS_PAGE_SIZE = 20++const newIdempotencyKey = (): string => uuid()++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface featureRequestsLogicValues {+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ accountId: string | null+ accountOptions: {+ key: string+ label: string+ }[]+ accountSearch: string+ accounts: AccountApi[]+ accountsError: string | null+ accountsLoading: boolean+ activeProductAreas: FeatureRequestProductAreaApi[]+ activeRequest: FeatureRequestApi | null+ activeRequestError: string | null+ activeRequestId: string | null+ activeRequestLoading: boolean+ createRequestOpen: boolean+ currentTeamId: string+ description: string+ editingProductAreaId: string | null+ featureRequestsError: string | null+ featureRequestsPage: number+ featureRequestsResponse: PaginatedFeatureRequestListApi+ featureRequestsResponseLoading: boolean+ idempotencyKey: string+ productAreaActive: boolean+ productAreaDisplayOrder: number+ productAreaIds: string[]+ productAreaName: string+ productAreaOptions: {+ key: string+ label: string+ }[]+ productAreaSaveDisabledReason: string | undefined+ productAreas: FeatureRequestProductAreaApi[]+ productAreasError: string | null+ productAreasLoading: boolean+ productAreasOpen: boolean+ savingProductArea: boolean+ submitDisabledReason: string | undefined+ submittingRequest: boolean+ title: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface featureRequestsLogicActions {+ closeCreateRequest: () => {+ value: true+ }+ closeProductAreas: () => {+ value: true+ }+ loadAccounts: (search?: string) => string+ loadAccountsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadAccountsSuccess: (+ accounts: AccountApi[],+ payload?: string+ ) => {+ accounts: AccountApi[]+ payload?: string+ }+ loadActiveRequest: (requestId: string) => string+ loadActiveRequestFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadActiveRequestSuccess: (+ activeRequest: FeatureRequestApi,+ payload?: string+ ) => {+ activeRequest: FeatureRequestApi+ payload?: string+ }+ loadFeatureRequests: () => any+ loadFeatureRequestsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadFeatureRequestsSuccess: (+ featureRequestsResponse: PaginatedFeatureRequestListApi,+ payload?: any+ ) => {+ featureRequestsResponse: PaginatedFeatureRequestListApi+ payload?: any+ }+ loadProductAreas: () => any+ loadProductAreasFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadProductAreasSuccess: (+ productAreas: FeatureRequestProductAreaApi[],+ payload?: any+ ) => {+ productAreas: FeatureRequestProductAreaApi[]+ payload?: any+ }+ openCreateRequest: () => {+ value: true+ }+ openProductAreas: () => {+ value: true+ }+ saveProductArea: () => {+ value: true+ }+ setAccountId: (accountId: string | null) => {+ accountId: string | null+ }+ setAccountSearch: (accountSearch: string) => {+ accountSearch: string+ }+ setActiveRequestId: (requestId: string | null) => {+ requestId: string | null+ }+ setDescription: (description: string) => {+ description: string+ }+ setFeatureRequestsPage: (page: number) => {+ page: number+ }+ setIdempotencyKey: (idempotencyKey: string) => {+ idempotencyKey: string+ }+ setProductAreaActive: (productAreaActive: boolean) => {+ productAreaActive: boolean+ }+ setProductAreaDisplayOrder: (productAreaDisplayOrder: number) => {+ productAreaDisplayOrder: number+ }+ setProductAreaIds: (productAreaIds: string[]) => {+ productAreaIds: string[]+ }+ setProductAreaName: (productAreaName: string) => {+ productAreaName: string+ }+ setSavingProductArea: (savingProductArea: boolean) => {+ savingProductArea: boolean+ }+ setSubmittingRequest: (submittingRequest: boolean) => {+ submittingRequest: boolean+ }+ setTitle: (title: string) => {+ title: string+ }+ startEditingProductArea: (productArea: FeatureRequestProductAreaApi) => {+ productArea: FeatureRequestProductAreaApi+ }+ startNewProductArea: () => {+ value: true+ }+ submitRequest: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface featureRequestsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ currentTeamId: (currentTeam: TeamPublicType | TeamType | null) => string+ activeProductAreas: (productAreas: FeatureRequestProductAreaApi[]) => FeatureRequestProductAreaApi[]+ accountOptions: (accounts: AccountApi[]) => {+ key: string+ label: string+ }[]+ productAreaOptions: (activeProductAreas: FeatureRequestProductAreaApi[]) => {+ key: string+ label: string+ }[]+ submitDisabledReason: (+ title: string,+ description: string,+ accountId: string | null,+ productAreaIds: string[],+ submittingRequest: boolean+ ) => string | undefined+ productAreaSaveDisabledReason: (productAreaName: string, savingProductArea: boolean) => string | undefined+ }+}++export type featureRequestsLogicType = MakeLogicType<+ featureRequestsLogicValues,+ featureRequestsLogicActions,+ Record<string, any>,+ featureRequestsLogicMeta+>++export const featureRequestsLogic = kea<featureRequestsLogicType>([+ path(['products', 'customer_analytics', 'frontend', 'components', 'FeatureRequests', 'featureRequestsLogic']),+ connect(() => ({ values: [teamLogic, ['currentTeam']] })),+ actions({+ setActiveRequestId: (requestId: string | null) => ({ requestId }),+ setFeatureRequestsPage: (page: number) => ({ page }),+ openCreateRequest: true,+ closeCreateRequest: true,+ setTitle: (title: string) => ({ title }),+ setDescription: (description: string) => ({ description }),+ setAccountId: (accountId: string | null) => ({ accountId }),+ setAccountSearch: (accountSearch: string) => ({ accountSearch }),+ setProductAreaIds: (productAreaIds: string[]) => ({ productAreaIds }),+ setIdempotencyKey: (idempotencyKey: string) => ({ idempotencyKey }),+ submitRequest: true,+ setSubmittingRequest: (submittingRequest: boolean) => ({ submittingRequest }),+ openProductAreas: true,+ closeProductAreas: true,+ startNewProductArea: true,+ startEditingProductArea: (productArea: FeatureRequestProductAreaApi) => ({ productArea }),+ setProductAreaName: (productAreaName: string) => ({ productAreaName }),+ setProductAreaDisplayOrder: (productAreaDisplayOrder: number) => ({ productAreaDisplayOrder }),+ setProductAreaActive: (productAreaActive: boolean) => ({ productAreaActive }),+ saveProductArea: true,+ setSavingProductArea: (savingProductArea: boolean) => ({ savingProductArea }),+ }),+ loaders(({ values }) => ({+ featureRequestsResponse: [+ { count: 0, next: null, previous: null, results: [] } as PaginatedFeatureRequestListApi,+ {+ loadFeatureRequests: async () =>+ featureRequestsList(String(values.currentTeam?.id), {+ limit: FEATURE_REQUESTS_PAGE_SIZE,+ offset: (values.featureRequestsPage - 1) * FEATURE_REQUESTS_PAGE_SIZE,+ }),+ },+ ],+ activeRequest: [+ null as FeatureRequestApi | null,+ {+ loadActiveRequest: async (requestId: string) =>+ featureRequestsRetrieve(String(values.currentTeam?.id), requestId),+ },+ ],+ accounts: [+ [] as AccountApi[],+ {+ loadAccounts: async (search: string = '') => {+ const response = await accountsList(String(values.currentTeam?.id), {+ limit: 100,+ ordering: 'name',+ search: search.trim() || undefined,+ })+ return response.results+ },+ },+ ],+ productAreas: [+ [] as FeatureRequestProductAreaApi[],+ {+ loadProductAreas: async () =>+ featureRequestProductAreasList(String(values.currentTeam?.id), { include_inactive: true }),+ },+ ],+ })),+ reducers({+ activeRequestId: [null as string | null, { setActiveRequestId: (_, { requestId }) => requestId }],+ featureRequestsPage: [1, { setFeatureRequestsPage: (_, { page }) => page }],+ accountSearch: ['', { setAccountSearch: (_, { accountSearch }) => accountSearch }],+ accountsError: [+ null as string | null,+ {+ loadAccounts: () => null,+ loadAccountsSuccess: () => null,+ loadAccountsFailure: () => "Couldn't load accounts.",+ },+ ],+ featureRequestsError: [+ null as string | null,+ {+ loadFeatureRequests: () => null,+ loadFeatureRequestsSuccess: () => null,+ loadFeatureRequestsFailure: () => "Couldn't load feature requests.",+ },+ ],+ activeRequestError: [+ null as string | null,+ {+ loadActiveRequest: () => null,+ loadActiveRequestSuccess: () => null,+ loadActiveRequestFailure: () => "Couldn't load this feature request.",+ setActiveRequestId: () => null,+ },+ ],+ productAreasError: [+ null as string | null,+ {+ loadProductAreas: () => null,+ loadProductAreasSuccess: () => null,+ loadProductAreasFailure: () => "Couldn't load product areas.",+ },+ ],+ createRequestOpen: [false, { openCreateRequest: () => true, closeCreateRequest: () => false }],+ title: ['', { setTitle: (_, { title }) => title, closeCreateRequest: () => '' }],+ description: ['', { setDescription: (_, { description }) => description, closeCreateRequest: () => '' }],+ accountId: [+ null as string | null,+ { setAccountId: (_, { accountId }) => accountId, closeCreateRequest: () => null },+ ],+ productAreaIds: [+ [] as string[],+ { setProductAreaIds: (_, { productAreaIds }) => productAreaIds, closeCreateRequest: () => [] },+ ],+ idempotencyKey: [newIdempotencyKey(), { setIdempotencyKey: (_, { idempotencyKey }) => idempotencyKey }],+ submittingRequest: [false, { setSubmittingRequest: (_, { submittingRequest }) => submittingRequest }],+ productAreasOpen: [false, { openProductAreas: () => true, closeProductAreas: () => false }],+ editingProductAreaId: [+ null as string | null,+ {+ startNewProductArea: () => null,+ startEditingProductArea: (_, { productArea }) => productArea.id,+ closeProductAreas: () => null,+ },+ ],+ productAreaName: [+ '',+ {+ startNewProductArea: () => '',+ startEditingProductArea: (_, { productArea }) => productArea.name,+ setProductAreaName: (_, { productAreaName }) => productAreaName,+ },+ ],+ productAreaDisplayOrder: [+ 0,+ {+ startNewProductArea: () => 0,+ startEditingProductArea: (_, { productArea }) => productArea.display_order ?? 0,+ setProductAreaDisplayOrder: (_, { productAreaDisplayOrder }) => productAreaDisplayOrder,+ },+ ],+ productAreaActive: [+ true,+ {+ startNewProductArea: () => true,+ startEditingProductArea: (_, { productArea }) => productArea.is_active ?? true,+ setProductAreaActive: (_, { productAreaActive }) => productAreaActive,+ },+ ],+ savingProductArea: [false, { setSavingProductArea: (_, { savingProductArea }) => savingProductArea }],+ }),+ selectors({+ currentTeamId: [+ (s) => [s.currentTeam],+ (currentTeam: TeamPublicType | TeamType | null): string => String(currentTeam?.id ?? ''),+ ],+ activeProductAreas: [+ (s) => [s.productAreas],+ (productAreas: FeatureRequestProductAreaApi[]): FeatureRequestProductAreaApi[] =>+ productAreas.filter((area) => area.is_active),+ ],+ accountOptions: [+ (s) => [s.accounts],+ (accounts: AccountApi[]): { key: string; label: string }[] =>+ accounts.map((account) => ({ key: account.id, label: account.name })),+ ],+ productAreaOptions: [+ (s) => [s.activeProductAreas],+ (productAreas: FeatureRequestProductAreaApi[]): { key: string; label: string }[] =>+ productAreas.map((area) => ({ key: area.id, label: area.name })),+ ],+ submitDisabledReason: [+ (s) => [s.title, s.description, s.accountId, s.productAreaIds, s.submittingRequest],+ (+ title: string,+ description: string,+ accountId: string | null,+ productAreaIds: string[],+ submittingRequest: boolean+ ): string | undefined => {+ if (submittingRequest) {+ return 'Saving request'+ }+ if (!title.trim()) {+ return 'Enter a title'+ }+ if (!description.trim()) {+ return 'Enter a description'+ }+ if (!accountId) {+ return 'Select an account'+ }+ if (productAreaIds.length === 0) {+ return 'Select at least one product area'+ }+ return undefined+ },+ ],+ productAreaSaveDisabledReason: [+ (s) => [s.productAreaName, s.savingProductArea],+ (productAreaName: string, savingProductArea: boolean): string | undefined => {+ if (savingProductArea) {+ return 'Saving product area'+ }+ if (!productAreaName.trim()) {+ return 'Enter a product area name'+ }+ return undefined+ },+ ],+ }),+ listeners(({ values, actions }) => ({+ setFeatureRequestsPage: () => {+ actions.loadFeatureRequests()+ },+ openCreateRequest: () => {+ actions.setIdempotencyKey(newIdempotencyKey())+ actions.loadAccounts('')+ actions.loadProductAreas()+ },+ setAccountSearch: async ({ accountSearch }, breakpoint) => {+ await breakpoint(300)+ actions.loadAccounts(accountSearch)+ },+ setActiveRequestId: ({ requestId }) => {+ if (requestId) {+ actions.loadActiveRequest(requestId)+ }+ },+ submitRequest: async () => {+ if (values.submitDisabledReason || !values.accountId) {+ return+ }+ actions.setSubmittingRequest(true)+ try {+ const created = await featureRequestsCreate(values.currentTeamId, {+ title: values.title.trim(),+ description: values.description.trim(),+ account_id: values.accountId,+ product_area_ids: values.productAreaIds,+ idempotency_key: values.idempotencyKey,+ })+ actions.closeCreateRequest()+ actions.setFeatureRequestsPage(1)+ router.actions.push(urls.customerAnalyticsFeatureRequests(created.id))+ } catch {+ lemonToast.error("Couldn't save the request. Check the fields and try again.")+ } finally {+ actions.setSubmittingRequest(false)+ }+ },+ openProductAreas: () => {+ actions.startNewProductArea()+ actions.loadProductAreas()+ },+ saveProductArea: async () => {+ if (values.productAreaSaveDisabledReason) {+ return+ }+ actions.setSavingProductArea(true)+ try {+ if (values.editingProductAreaId) {+ await featureRequestProductAreasPartialUpdate(values.currentTeamId, values.editingProductAreaId, {+ name: values.productAreaName.trim(),+ display_order: values.productAreaDisplayOrder,+ is_active: values.productAreaActive,+ })+ } else {+ await featureRequestProductAreasCreate(values.currentTeamId, {+ name: values.productAreaName.trim(),+ display_order: values.productAreaDisplayOrder,+ is_active: values.productAreaActive,+ })+ }+ actions.startNewProductArea()+ actions.loadProductAreas()+ actions.loadFeatureRequests()+ } catch {+ lemonToast.error("Couldn't save the product area. Check the name and try again.")+ } finally {+ actions.setSavingProductArea(false)+ }+ },+ })),+ urlToAction(({ actions }) => ({+ [urls.customerAnalyticsFeatureRequests()]: () => actions.setActiveRequestId(null),+ [urls.customerAnalyticsFeatureRequests(':requestId')]: ({ requestId }) =>+ actions.setActiveRequestId(requestId ?? null),+ })),+ afterMount(({ actions }) => {+ actions.loadFeatureRequests()+ actions.loadProductAreas()+ }),+])diff --git a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.ts b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.tsindex cf3660fbe97b..4df14a9e7888 100644--- a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.ts+++ b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.ts@@ -2,6 +2,8 @@ import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import { sceneLogic } from 'scenes/sceneLogic'+import { emptySceneParams } from 'scenes/scenes'+import { Scene } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'import { initKeaTests } from '~/test/init'@@ -52,6 +54,12 @@ describe('customerAnalyticsSceneLogic', () => {})describe('URL sync', () => {+ it('activates the Requests tab for its scene key', () => {+ sceneLogic.actions.setScene(Scene.CustomerAnalytics, 'customerAnalyticsFeatureRequests', emptySceneParams)++ expectLogic(logic).toMatchValues({ activeTab: 'feature_requests' })+ })+it('reads filter_test_accounts from URL', () => {expectLogic(logic).toMatchValues({filterTestAccounts: true,diff --git a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.tsindex 1ac700193f7b..258b60694c78 100644--- a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts+++ b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts@@ -43,7 +43,7 @@ import { customerAnalyticsConfigLogic } from './customerAnalyticsConfigLogic'export type BusinessType = 'b2c' | 'b2b'-type ActiveTab = 'dashboard' | 'journeys' | 'accounts' | 'notes' | 'announcements' | 'feed'+type ActiveTab = 'dashboard' | 'journeys' | 'accounts' | 'notes' | 'announcements' | 'feed' | 'feature_requests'const SCENE_KEY_TO_TAB: Record<string, ActiveTab> = {customerAnalyticsJourneys: 'journeys',@@ -51,6 +51,7 @@ const SCENE_KEY_TO_TAB: Record<string, ActiveTab> = {customerAnalyticsNotes: 'notes',customerAnalyticsAnnouncements: 'announcements',customerAnalyticsFeed: 'feed',+ customerAnalyticsFeatureRequests: 'feature_requests',}export interface InsightDefinition {diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 377f49effbec..d75f6cbacb3e 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -1366,6 +1366,120 @@ export interface EventStreamTestMessageApi {readonly channel_id: string}+export interface FeatureRequestProductAreaApi {+ /** Stable product area ID. */+ readonly id: string+ /**+ * Team-maintained product area name.+ * @maxLength 200+ */+ name: string+ /**+ * Position in product area selectors. Lower values appear first.+ * @minimum 0+ */+ display_order?: number+ /** Whether editors can select this product area for new requests. */+ is_active?: boolean+ /** When the product area was created. */+ readonly created_at: string+ /** When the product area was last updated. */+ readonly updated_at: string+}++export interface PatchedFeatureRequestProductAreaApi {+ /** Stable product area ID. */+ readonly id?: string+ /**+ * Team-maintained product area name.+ * @maxLength 200+ */+ name?: string+ /**+ * Position in product area selectors. Lower values appear first.+ * @minimum 0+ */+ display_order?: number+ /** Whether editors can select this product area for new requests. */+ is_active?: boolean+ /** When the product area was created. */+ readonly created_at?: string+ /** When the product area was last updated. */+ readonly updated_at?: string+}++/**+ * * `requested` - Requested+ */+export type RequestStatusEnumApi = (typeof RequestStatusEnumApi)[keyof typeof RequestStatusEnumApi]++export const RequestStatusEnumApi = {+ Requested: 'requested',+} as const++export interface FeatureRequestAccountApi {+ /** ID of the affected Customer Analytics account. */+ readonly id: string+ /** Name of the affected account. */+ readonly name: string+}++export interface FeatureRequestApi {+ /** Stable feature request ID. */+ readonly id: string+ /** Customer-facing request title. */+ readonly title: string+ /** Customer-facing request description in Markdown. */+ readonly description: string+ /** Current customer-facing status. The first release always creates requests as requested.+ *+ * * `requested` - Requested */+ readonly request_status: RequestStatusEnumApi+ /** Affected account in the first release. */+ readonly account: FeatureRequestAccountApi+ /** Product areas affected by this request. */+ readonly product_areas: readonly FeatureRequestProductAreaApi[]+ /**+ * ID of the user who created the request.+ * @nullable+ */+ readonly created_by: number | null+ /**+ * ID of the last user to update the request.+ * @nullable+ */+ readonly updated_by: number | null+ /** When the request was created. */+ readonly created_at: string+ /** When the request was last updated. */+ readonly updated_at: string+}++export interface PaginatedFeatureRequestListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: FeatureRequestApi[]+}++export interface FeatureRequestCreateApi {+ /**+ * Required customer-facing request title.+ * @maxLength 400+ */+ title: string+ /** Required customer-facing request description in Markdown. */+ description: string+ /** ID of the affected Customer Analytics account. */+ account_id: string+ /** One or more active product area IDs. Duplicate IDs are ignored. */+ product_area_ids: string[]+ /** Client-generated key that makes retries return the original request instead of creating a duplicate. */+ idempotency_key: string+}+/*** * `numeric` - numeric* * `currency` - currency@@ -1713,6 +1827,24 @@ export type CustomerProfileConfigsListParams = {offset?: number}+export type FeatureRequestProductAreasListParams = {+ /**+ * Include inactive product areas. Defaults to false.+ */+ include_inactive?: boolean+}++export type FeatureRequestsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}+export type GroupsTypesMetricsListParams = {/*** Number of results to return per page.diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex acf5eab725d3..ad4b023db945 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -47,6 +47,11 @@ import type {EventStreamMemberWriteApi,EventStreamTestMessageApi,ExternalAccountListPageApi,+ FeatureRequestApi,+ FeatureRequestCreateApi,+ FeatureRequestProductAreaApi,+ FeatureRequestProductAreasListParams,+ FeatureRequestsListParams,GroupUsageMetricApi,GroupsTypesMetricsListParams,PaginatedAccountChannelSummaryListApi,@@ -60,6 +65,7 @@ import type {PaginatedCustomPropertySyncRunListApi,PaginatedCustomerJourneyListApi,PaginatedCustomerProfileConfigListApi,+ PaginatedFeatureRequestListApi,PaginatedGroupUsageMetricListApi,PaginatedMeetingListApi,PatchedAccountApi,@@ -69,6 +75,7 @@ import type {PatchedCustomerJourneyApi,PatchedCustomerProfileConfigApi,PatchedEventStreamApi,+ PatchedFeatureRequestProductAreaApi,PatchedGroupUsageMetricApi,SupportTicketApi,} from './api.schemas'@@ -1471,6 +1478,148 @@ export const eventStreamsSendTestMessageCreate = async (})}+export const getFeatureRequestProductAreasListUrl = (+ projectId: string,+ params?: FeatureRequestProductAreasListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/feature_request_product_areas/?${stringifiedParams}`+ : `/api/projects/${projectId}/feature_request_product_areas/`+}++export const featureRequestProductAreasList = async (+ projectId: string,+ params?: FeatureRequestProductAreasListParams,+ options?: RequestInit+): Promise<FeatureRequestProductAreaApi[]> => {+ return apiMutator<FeatureRequestProductAreaApi[]>(getFeatureRequestProductAreasListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getFeatureRequestProductAreasCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/feature_request_product_areas/`+}++export const featureRequestProductAreasCreate = async (+ projectId: string,+ featureRequestProductAreaApi: NonReadonly<FeatureRequestProductAreaApi>,+ options?: RequestInit+): Promise<FeatureRequestProductAreaApi> => {+ return apiMutator<FeatureRequestProductAreaApi>(getFeatureRequestProductAreasCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(featureRequestProductAreaApi),+ })+}++export const getFeatureRequestProductAreasUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/feature_request_product_areas/${id}/`+}++export const featureRequestProductAreasUpdate = async (+ projectId: string,+ id: string,+ featureRequestProductAreaApi: NonReadonly<FeatureRequestProductAreaApi>,+ options?: RequestInit+): Promise<FeatureRequestProductAreaApi> => {+ return apiMutator<FeatureRequestProductAreaApi>(getFeatureRequestProductAreasUpdateUrl(projectId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(featureRequestProductAreaApi),+ })+}++export const getFeatureRequestProductAreasPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/feature_request_product_areas/${id}/`+}++export const featureRequestProductAreasPartialUpdate = async (+ projectId: string,+ id: string,+ patchedFeatureRequestProductAreaApi?: NonReadonly<PatchedFeatureRequestProductAreaApi>,+ options?: RequestInit+): Promise<FeatureRequestProductAreaApi> => {+ return apiMutator<FeatureRequestProductAreaApi>(getFeatureRequestProductAreasPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedFeatureRequestProductAreaApi),+ })+}++export const getFeatureRequestsListUrl = (projectId: string, params?: FeatureRequestsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/feature_requests/?${stringifiedParams}`+ : `/api/projects/${projectId}/feature_requests/`+}++export const featureRequestsList = async (+ projectId: string,+ params?: FeatureRequestsListParams,+ options?: RequestInit+): Promise<PaginatedFeatureRequestListApi> => {+ return apiMutator<PaginatedFeatureRequestListApi>(getFeatureRequestsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getFeatureRequestsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/feature_requests/`+}++export const featureRequestsCreate = async (+ projectId: string,+ featureRequestCreateApi: FeatureRequestCreateApi,+ options?: RequestInit+): Promise<FeatureRequestApi> => {+ return apiMutator<FeatureRequestApi>(getFeatureRequestsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(featureRequestCreateApi),+ })+}++export const getFeatureRequestsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/feature_requests/${id}/`+}++export const featureRequestsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<FeatureRequestApi> => {+ return apiMutator<FeatureRequestApi>(getFeatureRequestsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}+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 eef935aa059d..b56be425cd18 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -902,6 +902,84 @@ export const EventStreamsRemoveAccountCreateBody = /* @__PURE__ */ zod}).describe('Request body for adding or removing an event-stream member account.')+export const featureRequestProductAreasCreateBodyNameMax = 200++export const featureRequestProductAreasCreateBodyDisplayOrderDefault = 0+export const featureRequestProductAreasCreateBodyDisplayOrderMin = 0++export const featureRequestProductAreasCreateBodyIsActiveDefault = true++export const FeatureRequestProductAreasCreateBody = /* @__PURE__ */ zod.object({+ name: zod.string().max(featureRequestProductAreasCreateBodyNameMax).describe('Team-maintained product area name.'),+ display_order: zod+ .number()+ .min(featureRequestProductAreasCreateBodyDisplayOrderMin)+ .default(featureRequestProductAreasCreateBodyDisplayOrderDefault)+ .describe('Position in product area selectors. Lower values appear first.'),+ is_active: zod+ .boolean()+ .default(featureRequestProductAreasCreateBodyIsActiveDefault)+ .describe('Whether editors can select this product area for new requests.'),+})++export const featureRequestProductAreasUpdateBodyNameMax = 200++export const featureRequestProductAreasUpdateBodyDisplayOrderDefault = 0+export const featureRequestProductAreasUpdateBodyDisplayOrderMin = 0++export const featureRequestProductAreasUpdateBodyIsActiveDefault = true++export const FeatureRequestProductAreasUpdateBody = /* @__PURE__ */ zod.object({+ name: zod.string().max(featureRequestProductAreasUpdateBodyNameMax).describe('Team-maintained product area name.'),+ display_order: zod+ .number()+ .min(featureRequestProductAreasUpdateBodyDisplayOrderMin)+ .default(featureRequestProductAreasUpdateBodyDisplayOrderDefault)+ .describe('Position in product area selectors. Lower values appear first.'),+ is_active: zod+ .boolean()+ .default(featureRequestProductAreasUpdateBodyIsActiveDefault)+ .describe('Whether editors can select this product area for new requests.'),+})++export const featureRequestProductAreasPartialUpdateBodyNameMax = 200++export const featureRequestProductAreasPartialUpdateBodyDisplayOrderDefault = 0+export const featureRequestProductAreasPartialUpdateBodyDisplayOrderMin = 0++export const featureRequestProductAreasPartialUpdateBodyIsActiveDefault = true++export const FeatureRequestProductAreasPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(featureRequestProductAreasPartialUpdateBodyNameMax)+ .optional()+ .describe('Team-maintained product area name.'),+ display_order: zod+ .number()+ .min(featureRequestProductAreasPartialUpdateBodyDisplayOrderMin)+ .default(featureRequestProductAreasPartialUpdateBodyDisplayOrderDefault)+ .describe('Position in product area selectors. Lower values appear first.'),+ is_active: zod+ .boolean()+ .default(featureRequestProductAreasPartialUpdateBodyIsActiveDefault)+ .describe('Whether editors can select this product area for new requests.'),+})++export const featureRequestsCreateBodyTitleMax = 400++export const FeatureRequestsCreateBody = /* @__PURE__ */ zod.object({+ title: zod.string().max(featureRequestsCreateBodyTitleMax).describe('Required customer-facing request title.'),+ description: zod.string().describe('Required customer-facing request description in Markdown.'),+ account_id: zod.uuid().describe('ID of the affected Customer Analytics account.'),+ product_area_ids: zod.array(zod.uuid()).describe('One or more active product area IDs. Duplicate IDs are ignored.'),+ idempotency_key: zod+ .uuid()+ .describe(+ 'Client-generated key that makes retries return the original request instead of creating a duplicate.'+ ),+})+export const groupsTypesMetricsCreateBodyNameMax = 255export const groupsTypesMetricsCreateBodyFormatDefault = `numeric`diff --git a/products/customer_analytics/manifest.tsx b/products/customer_analytics/manifest.tsxindex a93ed22c796e..da88be1f5945 100644--- a/products/customer_analytics/manifest.tsx+++ b/products/customer_analytics/manifest.tsx@@ -53,6 +53,8 @@ export const manifest: ProductManifest = {'/customer_analytics/notes': ['CustomerAnalytics', 'customerAnalyticsNotes'],'/customer_analytics/announcements': ['CustomerAnalytics', 'customerAnalyticsAnnouncements'],'/customer_analytics/feed': ['CustomerAnalytics', 'customerAnalyticsFeed'],+ '/customer_analytics/feature-requests': ['CustomerAnalytics', 'customerAnalyticsFeatureRequests'],+ '/customer_analytics/feature-requests/:requestId': ['CustomerAnalytics', 'customerAnalyticsFeatureRequests'],'/customer_analytics/journeys/new': ['CustomerJourneyBuilder', 'customerJourneyBuilder'],'/customer_analytics/journeys/templates': ['CustomerJourneyTemplates', 'customerJourneyTemplates'],'/customer_analytics/journeys/:id/edit': ['CustomerJourneyBuilder', 'customerJourneyEdit'],@@ -79,6 +81,8 @@ export const manifest: ProductManifest = {customerAnalyticsNotes: (): string => '/customer_analytics/notes',customerAnalyticsAnnouncements: (): string => '/customer_analytics/announcements',customerAnalyticsFeed: (): string => '/customer_analytics/feed',+ customerAnalyticsFeatureRequests: (requestId?: string): string =>+ `/customer_analytics/feature-requests${requestId ? `/${requestId}` : ''}`,customerAnalyticsJourneys: (): string => '/customer_analytics/journeys',customerAnalyticsConfiguration: (tab?: string): string =>`/customer_analytics/configuration${tab ? `?tab=${tab}` : ''}`,diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex 9e7955da680d..b3ab15a690f8 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -875,6 +875,27 @@ tools:event-streams-update:operation: event_streams_updateenabled: false+ feature-request-product-areas-create:+ operation: feature_request_product_areas_create+ enabled: false+ feature-request-product-areas-list:+ operation: feature_request_product_areas_list+ enabled: false+ feature-request-product-areas-partial-update:+ operation: feature_request_product_areas_partial_update+ enabled: false+ feature-request-product-areas-update:+ operation: feature_request_product_areas_update+ enabled: false+ feature-requests-create:+ operation: feature_requests_create+ enabled: false+ feature-requests-list:+ operation: feature_requests_list+ enabled: false+ feature-requests-retrieve:+ operation: feature_requests_retrieve+ 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 2cf6c485d62d..9c208a5a6cd4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -35389,6 +35389,91 @@ export namespace Schemas {readonly modified_by: number | null;}+ /**+ * * `requested` - Requested+ */+ export type RequestStatusEnum = typeof RequestStatusEnum[keyof typeof RequestStatusEnum];+++ export const RequestStatusEnum = {+ Requested: 'requested',+ } as const;++ export interface FeatureRequestAccount {+ /** ID of the affected Customer Analytics account. */+ readonly id: string;+ /** Name of the affected account. */+ readonly name: string;+ }++ export interface FeatureRequestProductArea {+ /** Stable product area ID. */+ readonly id: string;+ /**+ * Team-maintained product area name.+ * @maxLength 200+ */+ name: string;+ /**+ * Position in product area selectors. Lower values appear first.+ * @minimum 0+ */+ display_order?: number;+ /** Whether editors can select this product area for new requests. */+ is_active?: boolean;+ /** When the product area was created. */+ readonly created_at: string;+ /** When the product area was last updated. */+ readonly updated_at: string;+ }++ export interface FeatureRequest {+ /** Stable feature request ID. */+ readonly id: string;+ /** Customer-facing request title. */+ readonly title: string;+ /** Customer-facing request description in Markdown. */+ readonly description: string;+ /** Current customer-facing status. The first release always creates requests as requested.+ *+ * * `requested` - Requested */+ readonly request_status: RequestStatusEnum;+ /** Affected account in the first release. */+ readonly account: FeatureRequestAccount;+ /** Product areas affected by this request. */+ readonly product_areas: readonly FeatureRequestProductArea[];+ /**+ * ID of the user who created the request.+ * @nullable+ */+ readonly created_by: number | null;+ /**+ * ID of the last user to update the request.+ * @nullable+ */+ readonly updated_by: number | null;+ /** When the request was created. */+ readonly created_at: string;+ /** When the request was last updated. */+ readonly updated_at: string;+ }++ export interface FeatureRequestCreate {+ /**+ * Required customer-facing request title.+ * @maxLength 400+ */+ title: string;+ /** Required customer-facing request description in Markdown. */+ description: string;+ /** ID of the affected Customer Analytics account. */+ account_id: string;+ /** One or more active product area IDs. Duplicate IDs are ignored. */+ product_area_ids: string[];+ /** Client-generated key that makes retries return the original request instead of creating a duplicate. */+ idempotency_key: string;+ }+export interface FeaturebaseFeedbackSignalExtra {status: string | null;tags: unknown[];@@ -48041,6 +48126,15 @@ export namespace Schemas {results: FeatureFlag[];}+ export interface PaginatedFeatureRequestList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: FeatureRequest[];+ }+export interface PaginatedFieldNoteList {count: number;/** @nullable */@@ -55732,6 +55826,27 @@ export namespace Schemas {bucketing_identifier?: BucketingIdentifierEnum | null;}+ export interface PatchedFeatureRequestProductArea {+ /** Stable product area ID. */+ readonly id?: string;+ /**+ * Team-maintained product area name.+ * @maxLength 200+ */+ name?: string;+ /**+ * Position in product area selectors. Lower values appear first.+ * @minimum 0+ */+ display_order?: number;+ /** Whether editors can select this product area for new requests. */+ is_active?: boolean;+ /** When the product area was created. */+ readonly created_at?: string;+ /** When the product area was last updated. */+ readonly updated_at?: string;+ }+/*** Structured element metadata (inferred selectors, attributes, component hints).*/@@ -84801,6 +84916,24 @@ export namespace Schemas {groups?: string;};+ export type FeatureRequestProductAreasListParams = {+ /**+ * Include inactive product areas. Defaults to false.+ */+ include_inactive?: boolean;+ };++ export type FeatureRequestsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type FieldNotesListParams = {/*** Filter to field notes in this lifecycle state (e.g. `pending` for unaddressed feedback).