Skip to content

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

feat(customer-analytics): seed account widget examples (#107164)

Arthur Moreira de Deusecbf74feb083
diff --git a/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py b/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py
index 6c735473d28d..bd7416f29ae2 100644
--- a/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py
+++ b/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py
@@ -8,9 +8,11 @@ so it has no dependency on ClickHouse->Postgres sync timing. For the given team
- ensures a small shared pool of organization-member users and assigns them as each account's
CSM / account executive / account owner,
- adds a few notes (internal notebooks) to a handful of accounts,
+- creates production-shaped billing insights with stable short IDs,
+- adds meetings and conversation fixtures to a handful of accounts,
- points the team's customer-analytics config at group type index 0.
-Re-running is safe: existing accounts, pool users, and notes are left alone.
+Re-running is safe: existing accounts, users, notes, insights, meetings, and conversations are reused.
Usage:
python manage.py seed_customer_analytics_accounts --team-id 1
@@ -31,6 +33,7 @@ from posthog.persons_db import persons_db_connection
from products.customer_analytics.backend.facade.api import create_account
from products.customer_analytics.backend.facade.enums import AccountRelationshipSource
from products.customer_analytics.backend.logic import relationships as relationships_logic
+from products.customer_analytics.backend.management.seed_widget_data import WIDGET_ACCOUNT_COUNT, seed_widget_data
from products.customer_analytics.backend.models.account import Account, AccountProperties
from products.customer_analytics.backend.models.relationship import AccountRelationshipDefinition
from products.customer_analytics.backend.models.team_customer_analytics_config import TeamCustomerAnalyticsConfig
@@ -64,12 +67,22 @@ class Command(BaseCommand):
parser.add_argument(
"--notes-per-account", type=int, default=2, help="Notes created per selected account (default: 2)."
)
+ parser.add_argument(
+ "--accounts-with-widget-data",
+ type=int,
+ default=WIDGET_ACCOUNT_COUNT,
+ help=f"How many accounts get meetings and conversations (default: {WIDGET_ACCOUNT_COUNT}).",
+ )
parser.add_argument(
"--limit", type=int, default=None, help="Cap how many groups become accounts (default: all)."
)
parser.add_argument("--dry-run", action="store_true", help="Report what would be created without writing.")
def handle(self, *args: Any, **options: Any) -> None:
+ account_count = options["accounts_with_widget_data"]
+ if account_count < 0:
+ raise CommandError("--accounts-with-widget-data must be zero or greater.")
+
team = self._get_team(options["team_id"])
groups = self._read_account_groups(team, options["limit"])
if not groups:
@@ -81,12 +94,14 @@ class Command(BaseCommand):
if options["dry_run"]:
note_account_count = min(options["accounts_with_notes"], len(groups))
- self.stdout.write(self.style.WARNING("Dry run — no changes will be written."))
+ widget_account_count = min(options["accounts_with_widget_data"], len(groups))
+ self.stdout.write(self.style.WARNING("Dry run - no changes will be written."))
self.stdout.write(
f"Would set account_group_type_index = {ACCOUNT_GROUP_TYPE_INDEX}, "
f"create up to {len(groups)} account(s), ensure a pool of {options['users']} user(s), "
- f"and add up to {note_account_count * options['notes_per_account']} note(s) "
- f"across {note_account_count} account(s)."
+ f"add up to {note_account_count * options['notes_per_account']} note(s) "
+ f"across {note_account_count} account(s), create three billing insights, "
+ f"and add meetings and conversations to {widget_account_count} account(s)."
)
return
@@ -94,6 +109,13 @@ class Command(BaseCommand):
user_pool = self._ensure_user_pool(team, options["users"])
accounts = self._create_accounts(team, groups, user_pool)
self._create_notes(team, accounts, user_pool, options["accounts_with_notes"], options["notes_per_account"])
+ seed_widget_data(
+ team=team,
+ accounts=accounts,
+ user_pool=user_pool,
+ output=self.stdout.write,
+ account_count=account_count,
+ )
self.stdout.write(self.style.SUCCESS("Done."))
def _get_team(self, team_id: int) -> Team:
diff --git a/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.py b/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.py
index 5c7892a1e347..5b790155c3bb 100644
--- a/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.py
+++ b/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.py
@@ -10,11 +10,22 @@ from posthog.models import OrganizationMembership, User
from posthog.persons_db import persons_db_connection
from posthog.persons_seed import insert_seed_group
-from products.customer_analytics.backend.models.account import Account
+from products.conversations.backend.models import (
+ EmailThread,
+ EmailThreadAccountLink,
+ EmailThreadMessage,
+ EmailThreadParticipant,
+)
+from products.conversations.backend.models.ticket import Ticket
+from products.customer_analytics.backend.management.seed_widget_data import BILLING_INSIGHT_SHORT_IDS
+from products.customer_analytics.backend.models import AccountChannelSummary, Meeting, MeetingParticipant
+from products.customer_analytics.backend.models.account import Account, AccountProperties
+from products.customer_analytics.backend.models.account_channel_summary import SlackSummaryCadence
from products.customer_analytics.backend.models.relationship import AccountRelationship
from products.customer_analytics.backend.models.team_customer_analytics_config import TeamCustomerAnalyticsConfig
from products.notebooks.backend.facade.content import is_markdown_notebook_content
from products.notebooks.backend.models import Notebook, ResourceNotebook
+from products.product_analytics.backend.facade.models import Insight, InsightVariable
pytestmark = pytest.mark.persons_db_direct
@@ -86,13 +97,72 @@ class TestSeedCustomerAnalyticsAccounts(BaseTest):
)
assert accounts_with_notes == {accounts["acme-id"].id, accounts["globex-id"].id}
+ assert set(Insight.objects.filter(team=self.team).values_list("short_id", flat=True)) >= set(
+ BILLING_INSIGHT_SHORT_IDS.values()
+ )
+ assert set(InsightVariable.objects.filter(team=self.team).values_list("code_name", flat=True)) >= {
+ "billing_org_id",
+ "billing_start_date",
+ "billing_end_date",
+ }
+
+ assert Meeting.objects.for_team(self.team.pk).count() == 6
+ assert MeetingParticipant.objects.for_team(self.team.pk).count() == 18
+ assert EmailThread.objects.for_team(self.team.pk).count() == 3
+ assert EmailThreadAccountLink.objects.for_team(self.team.pk).count() == 3
+ assert EmailThreadMessage.objects.for_team(self.team.pk).count() == 6
+ assert EmailThreadParticipant.objects.for_team(self.team.pk).count() == 6
+ assert Ticket.objects.filter(team=self.team).count() == 3
+ assert AccountChannelSummary.objects.for_team(self.team.pk).count() == 3
+ assert all(account.properties.email_domains for account in accounts.values())
+ assert all(account.properties.slack_channel_id for account in accounts.values())
+
def test_is_idempotent(self):
self._make_group("acme-id", "Acme")
self._make_group("globex-id", "Globex")
self._run(users=3, accounts_with_notes=2, notes_per_account=1)
+
+ account = self._accounts()["acme-id"]
+ account.properties = AccountProperties(
+ website_domain="acme.example.com",
+ email_domains=["acme.example.com"],
+ known_emails=["[email protected]"],
+ slack_channel_id="CUSER0001",
+ )
+ account.slack_summary_cadence = SlackSummaryCadence.MONTHLY
+ account.save(update_fields=["_properties", "slack_summary_cadence", "updated_at"])
+ insight = Insight.objects.get(team=self.team, short_id=BILLING_INSIGHT_SHORT_IDS["usage"])
+ insight.name = "Custom billing usage"
+ insight.query = {"kind": "TrendsQuery", "series": []}
+ insight.save()
+ ticket = Ticket.objects.get(team=self.team, widget_session_id=f"ca-seed-{str(account.id)[:48]}")
+ ticket.status = "resolved"
+ ticket.priority = "high"
+ ticket.save(update_fields=["status", "priority", "updated_at"])
+ meeting = Meeting.objects.for_team(self.team.pk).get(
+ ical_uid=f"customer-analytics-seed-{account.id}-quarterly-review",
+ recurrence_instance_id="",
+ )
+ meeting.title = "Custom quarterly review"
+ meeting.save(update_fields=["title", "updated_at"])
+
self._run(users=3, accounts_with_notes=2, notes_per_account=1)
+ account.refresh_from_db()
+ insight.refresh_from_db()
+ ticket.refresh_from_db()
+ meeting.refresh_from_db()
+ assert account.properties.website_domain == "acme.example.com"
+ assert account.properties.email_domains == ["acme.example.com"]
+ assert account.properties.known_emails == ["[email protected]"]
+ assert account.properties.slack_channel_id == "CUSER0001"
+ assert account.slack_summary_cadence == SlackSummaryCadence.MONTHLY
+ assert insight.name == "Custom billing usage"
+ assert insight.query == {"kind": "TrendsQuery", "series": []}
+ assert (ticket.status, ticket.priority) == ("resolved", "high")
+ assert meeting.title == "Custom quarterly review"
+
assert Account.objects.for_team(self.team.pk).count() == 2
assert len(self._pool_emails()) == 3
assert (
@@ -102,6 +172,38 @@ class TestSeedCustomerAnalyticsAccounts(BaseTest):
== 3
)
assert ResourceNotebook.objects.filter(account__team_id=self.team.pk).count() == 2
+ assert Insight.objects.filter(team=self.team, short_id__in=BILLING_INSIGHT_SHORT_IDS.values()).count() == 3
+ assert Meeting.objects.for_team(self.team.pk).count() == 4
+ assert MeetingParticipant.objects.for_team(self.team.pk).count() == 12
+ assert EmailThread.objects.for_team(self.team.pk).count() == 2
+ assert EmailThreadAccountLink.objects.for_team(self.team.pk).count() == 2
+ assert EmailThreadMessage.objects.for_team(self.team.pk).count() == 4
+ assert EmailThreadParticipant.objects.for_team(self.team.pk).count() == 4
+ assert Ticket.objects.filter(team=self.team).count() == 2
+ assert AccountChannelSummary.objects.for_team(self.team.pk).count() == 2
+
+ def test_preserves_colliding_soft_deleted_insight(self):
+ self._make_group("acme-id", "Acme")
+ short_id = BILLING_INSIGHT_SHORT_IDS["usage"]
+ insight = Insight.objects_including_soft_deleted.create(
+ team=self.team,
+ short_id=short_id,
+ name="Deleted billing usage",
+ query={"kind": "TrendsQuery", "series": []},
+ deleted=True,
+ )
+
+ self._run(accounts_with_widget_data=0)
+
+ insight.refresh_from_db()
+ assert insight.deleted
+ assert insight.name == "Deleted billing usage"
+ assert insight.query == {"kind": "TrendsQuery", "series": []}
+ assert Insight.objects_including_soft_deleted.filter(team=self.team, short_id=short_id).count() == 1
+
+ def test_rejects_negative_widget_account_count_before_dry_run(self):
+ with self.assertRaisesMessage(CommandError, "--accounts-with-widget-data must be zero or greater."):
+ self._run(dry_run=True, accounts_with_widget_data=-1)
def test_dry_run_writes_nothing(self):
self._make_group("acme-id", "Acme")
@@ -114,6 +216,10 @@ class TestSeedCustomerAnalyticsAccounts(BaseTest):
assert not TeamCustomerAnalyticsConfig.objects.filter(
team=self.team, account_group_type_index__isnull=False
).exists()
+ assert not Insight.objects.filter(team=self.team, short_id__in=BILLING_INSIGHT_SHORT_IDS.values()).exists()
+ assert not Meeting.objects.for_team(self.team.pk).exists()
+ assert not EmailThread.objects.for_team(self.team.pk).exists()
+ assert not Ticket.objects.filter(team=self.team).exists()
def test_errors_when_no_groups(self):
with self.assertRaises(CommandError):
diff --git a/products/customer_analytics/backend/management/seed_widget_data.py b/products/customer_analytics/backend/management/seed_widget_data.py
new file mode 100644
index 000000000000..de8721ed8d26
--- /dev/null
+++ b/products/customer_analytics/backend/management/seed_widget_data.py
@@ -0,0 +1,419 @@
+from __future__ import annotations
+
+from collections.abc import Callable
+from datetime import timedelta
+from typing import TypedDict
+
+from django.db import transaction
+from django.utils import timezone
+
+from posthog.models.comment import Comment
+from posthog.models.team import Team
+from posthog.models.user import User
+
+from products.conversations.backend.models import (
+ EMAIL_THREAD_COMMENT_SCOPE,
+ EmailThread,
+ EmailThreadAccountLink,
+ EmailThreadMessage,
+ EmailThreadMessageDirection,
+ EmailThreadParticipant,
+ EmailThreadParticipantKind,
+)
+from products.conversations.backend.models.ticket import Ticket
+from products.customer_analytics.backend.logic.channel_summaries import get_last_closed_period
+from products.customer_analytics.backend.models import Account, AccountChannelSummary, Meeting, MeetingParticipant
+from products.customer_analytics.backend.models.account_channel_summary import SlackSummaryCadence
+from products.customer_analytics.backend.models.meeting import MeetingResponseStatus, MeetingStatus
+from products.product_analytics.backend.facade import api as product_analytics
+from products.product_analytics.backend.facade.enums import InsightVariableType
+
+WIDGET_ACCOUNT_COUNT = 5
+
+
+class InsightVariablePayload(TypedDict):
+ variableId: str
+ code_name: str
+ value: str
+
+
+BILLING_INSIGHT_SHORT_IDS = {
+ "usage": "fiJDsKLp",
+ "spend_history": "o4I9sdFE",
+ "spend_by_product": "Tjo4bsux",
+}
+
+USAGE_SQL = """SELECT
+ today() - number AS date,
+ 800 + cityHash64(toString({variables.billing_org_id})) % 500 + number * 7 AS Events,
+ 120 + cityHash64(toString({variables.billing_org_id})) % 90 + number * 2 AS `Identified Events`,
+ 300 + cityHash64(toString({variables.billing_org_id})) % 150 + number * 3 AS `Feature Flag Requests`,
+ 20 + cityHash64(toString({variables.billing_org_id})) % 30 + number AS Recordings,
+ 5 + cityHash64(toString({variables.billing_org_id})) % 8 + number % 4 AS `Survey Responses`
+FROM numbers(31)
+WHERE today() - number >= toDate({variables.billing_start_date})
+ AND today() - number <= toDate({variables.billing_end_date})
+ORDER BY date"""
+
+SPEND_HISTORY_SQL = """SELECT
+ toStartOfMonth(today()) - toIntervalMonth(number) AS period,
+ 1800 + cityHash64(toString({variables.billing_org_id})) % 700 + number * 55 AS confirmed_MRR,
+ if(number % 4 = 0, 120 + number * 5, 0) AS credits_used,
+ 1950 + cityHash64(toString({variables.billing_org_id})) % 750 + number * 60 AS forecasted_MRR,
+ if(number = 10, 75, 0) AS refunded
+FROM numbers(13)
+WHERE period >= toStartOfMonth(toDate({variables.billing_start_date}))
+ AND period <= toStartOfMonth(toDate({variables.billing_end_date}))
+ORDER BY period"""
+
+SPEND_BY_PRODUCT_SQL = """SELECT
+ toStartOfMonth(today()) - toIntervalMonth(intDiv(number, 3)) AS month,
+ multiIf(
+ number % 3 = 0, 'Product analytics',
+ number % 3 = 1, 'Session replay',
+ 'Feature flags'
+ ) AS cleaned_description,
+ 120 + cityHash64(toString({variables.billing_org_id})) % 90
+ + intDiv(number, 3) * 12
+ + (number % 3) * 45 AS total_amount
+FROM numbers(39)
+WHERE month >= toStartOfMonth(toDate({variables.billing_start_date}))
+ AND month <= toStartOfMonth(toDate({variables.billing_end_date}))
+ORDER BY month, cleaned_description"""
+
+
+def seed_widget_data(
+ *,
+ team: Team,
+ accounts: list[Account],
+ user_pool: list[User],
+ output: Callable[[str], None],
+ account_count: int = WIDGET_ACCOUNT_COUNT,
+) -> None:
+ if account_count < 0:
+ raise ValueError("account_count must not be negative")
+
+ creator = team.organization.members.first()
+ _seed_billing_insights(team=team, creator=creator, accounts=accounts)
+
+ selected_accounts = accounts[:account_count]
+ for index, account in enumerate(selected_accounts, start=1):
+ manager = user_pool[(index - 1) % len(user_pool)] if user_pool else creator
+ _seed_account_contact_data(account=account, index=index)
+ _seed_meetings(team=team, account=account, manager=manager, index=index)
+ _seed_email_thread(team=team, account=account, manager=manager, index=index)
+ _seed_support_ticket(team=team, account=account, index=index)
+ _seed_channel_summary(team=team, account=account, index=index)
+
+ output(f"Seeded billing insights and widget data for {len(selected_accounts)} account(s).")
+
+
+def _ensure_billing_variables(team: Team, accounts: list[Account]) -> dict[str, InsightVariablePayload]:
+ today = timezone.now().date()
+ default_org = accounts[0].external_id if accounts and accounts[0].external_id else "example-account"
+ specs = {
+ "billing_org_id": ("Billing organization", InsightVariableType.STRING, default_org),
+ "billing_start_date": ("Billing start date", InsightVariableType.DATE, str(today - timedelta(days=365))),
+ "billing_end_date": ("Billing end date", InsightVariableType.DATE, str(today)),
+ }
+ existing = {
+ variable.code_name: variable
+ for variable in product_analytics.insight_variables_by_code_names(team.id, specs.keys())
+ if variable.code_name
+ }
+ variables: dict[str, InsightVariablePayload] = {}
+ for code_name, (name, variable_type, default_value) in specs.items():
+ variable = existing.get(code_name)
+ if variable is None:
+ variable = product_analytics.create_insight_variable(
+ team_id=team.id,
+ name=name,
+ type=variable_type,
+ code_name=code_name,
+ default_value=default_value,
+ )
+ variables[str(variable.id)] = {
+ "variableId": str(variable.id),
+ "code_name": code_name,
+ "value": default_value,
+ }
+ return variables
+
+
+def _seed_billing_insights(*, team: Team, creator: User | None, accounts: list[Account]) -> None:
+ variables = _ensure_billing_variables(team, accounts)
+ usage_columns = [
+ "Events",
+ "Identified Events",
+ "Feature Flag Requests",
+ "Recordings",
+ "Survey Responses",
+ ]
+ currency_format = {"style": "number", "prefix": "$", "suffix": "", "decimalPlaces": 2}
+ insight_specs: list[tuple[str, str, str, dict[str, object]]] = [
+ (
+ BILLING_INSIGHT_SHORT_IDS["usage"],
+ "Billing usage by metric (warehouse)",
+ "Daily billing usage for a selected organization.",
+ {
+ "kind": "DataVisualizationNode",
+ "source": {"kind": "HogQLQuery", "query": USAGE_SQL, "variables": variables},
+ "display": "Auto",
+ "chartSettings": {
+ "xAxis": {"column": "date"},
+ "yAxis": [{"column": column} for column in usage_columns],
+ "chartStyle": {"curve": "smooth"},
+ "showLegend": True,
+ "legendPosition": "bottom",
+ },
+ "tableSettings": {"columns": [{"column": "date"}, *({"column": column} for column in usage_columns)]},
+ },
+ ),
+ (
+ BILLING_INSIGHT_SHORT_IDS["spend_history"],
+ "Billing history with credits/refunds",
+ "Monthly billing history with forecast, credits, and refunds.",
+ {
+ "kind": "DataVisualizationNode",
+ "source": {"kind": "HogQLQuery", "query": SPEND_HISTORY_SQL, "variables": variables},
+ "display": "ActionsStackedBar",
+ "chartSettings": {
+ "xAxis": {"column": "period"},
+ "yAxis": [
+ {"column": column, "settings": {"formatting": currency_format}}
+ for column in ("confirmed_MRR", "credits_used", "forecasted_MRR", "refunded")
+ ],
+ "showNullsAsZero": True,
+ },
+ },
+ ),
+ (
+ BILLING_INSIGHT_SHORT_IDS["spend_by_product"],
+ "Per product spend for credited invoices/startup",
+ "Monthly spend split across products.",
+ {
+ "kind": "DataVisualizationNode",
+ "source": {"kind": "HogQLQuery", "query": SPEND_BY_PRODUCT_SQL, "variables": variables},
+ "display": "ActionsStackedBar",
+ "chartSettings": {
+ "xAxis": {"column": "month"},
+ "yAxis": [{"column": "total_amount", "settings": {"formatting": currency_format}}],
+ "seriesBreakdownColumn": "cleaned_description",
+ },
+ },
+ ),
+ ]
+ for short_id, name, description, query in insight_specs:
+ product_analytics.get_or_create_saved_insight(
+ team_id=team.id,
+ user_id=creator.id if creator else None,
+ short_id=short_id,
+ name=name,
+ description=description,
+ query=query,
+ revive_deleted=False,
+ )
+
+
+def _seed_account_contact_data(*, account: Account, index: int) -> None:
+ domain = f"customer-{index}.example.com"
+ properties = account.properties
+ account.properties = properties.model_copy(
+ update={
+ "website_domain": properties.website_domain or domain,
+ "email_domains": properties.email_domains or [domain],
+ "known_emails": properties.known_emails or [f"champion@{domain}", f"finance@{domain}"],
+ "slack_channel_id": properties.slack_channel_id or f"CSEED{index:04d}",
+ }
+ )
+ if not properties.slack_channel_id:
+ account.slack_summary_cadence = SlackSummaryCadence.WEEKLY
+ account.save(update_fields=["_properties", "slack_summary_cadence", "updated_at"])
+
+
+def _seed_meetings(*, team: Team, account: Account, manager: User | None, index: int) -> None:
+ now = timezone.now()
+ meetings = [
+ ("quarterly-review", "Quarterly business review", now - timedelta(days=3), MeetingStatus.CONFIRMED),
+ ("implementation", "Implementation check-in", now + timedelta(days=4), MeetingStatus.TENTATIVE),
+ ]
+ for suffix, title, start_time, status in meetings:
+ meeting, _ = Meeting.objects.for_team(team.id).get_or_create(
+ team=team,
+ ical_uid=f"customer-analytics-seed-{account.id}-{suffix}",
+ recurrence_instance_id="",
+ defaults={
+ "account": account,
+ "title": title,
+ "description": "Customer analytics development fixture",
+ "start_time": start_time,
+ "end_time": start_time + timedelta(minutes=45),
+ "organizer_email": manager.email if manager else "[email protected]",
+ "status": status,
+ },
+ )
+ participants = [
+ (f"champion@customer-{index}.example.com", "Customer champion", MeetingResponseStatus.ACCEPTED, False),
+ (
+ manager.email if manager else "[email protected]",
+ manager.first_name if manager else "Account manager",
+ MeetingResponseStatus.ACCEPTED,
+ True,
+ ),
+ (f"finance@customer-{index}.example.com", "Finance partner", MeetingResponseStatus.TENTATIVE, False),
+ ]
+ for email, display_name, response_status, is_organizer in participants:
+ MeetingParticipant.objects.for_team(team.id).get_or_create(
+ team=team,
+ meeting=meeting,
+ email=email,
+ defaults={
+ "display_name": display_name,
+ "response_status": response_status,
+ "is_organizer": is_organizer,
+ },
+ )
+
+
+def _seed_email_thread(*, team: Team, account: Account, manager: User | None, index: int) -> None:
+ now = timezone.now()
+ thread, _ = EmailThread.objects.for_team(team.id).get_or_create(
+ team=team,
+ canonical_thread_key=f"customer-analytics-seed-{account.id}",
+ defaults={
+ "subject": "Renewal planning",
+ "first_message_at": now - timedelta(days=5),
+ "last_message_at": now - timedelta(days=1),
+ "message_count": 2,
+ "preview": "Could we review next quarter's rollout?",
+ },
+ )
+ EmailThreadAccountLink.objects.for_team(team.id).get_or_create(
+ team=team,
+ thread=thread,
+ account_id=str(account.id),
+ defaults={"account_external_id": account.external_id, "match_source": "email_domain"},
+ )
+ participants = [
+ (f"champion@customer-{index}.example.com", "Customer champion", EmailThreadParticipantKind.CUSTOMER),
+ (
+ manager.email if manager else "[email protected]",
+ manager.first_name if manager else "Account manager",
+ EmailThreadParticipantKind.INTERNAL,
+ ),
+ ]
+ for email, display_name, kind in participants:
+ EmailThreadParticipant.objects.for_team(team.id).get_or_create(
+ team=team,
+ thread=thread,
+ email=email,
+ defaults={"display_name": display_name, "kind": kind},
+ )
+ messages = [
+ (
+ "customer",
+ "Could we review next quarter's rollout and expected usage?",
+ now - timedelta(days=5),
+ f"champion@customer-{index}.example.com",
+ "Customer champion",
+ EmailThreadMessageDirection.INBOUND,
+ ),
+ (
+ "manager",
+ "Yes. I added a review meeting and a usage summary for the team.",
+ now - timedelta(days=1),
+ manager.email if manager else "[email protected]",
+ manager.first_name if manager else "Account manager",
+ EmailThreadMessageDirection.OUTBOUND,
+ ),
+ ]
+ for suffix, content, sent_at, sender_email, sender_name, direction in messages:
+ source_id = f"customer-analytics-seed-{account.id}-{suffix}"
+ message = (
+ EmailThreadMessage.objects.for_team(team.id)
+ .filter(team=team, source_type="customer_analytics_seed", source_id=source_id)
+ .first()
+ )
+ if message is None:
+ with transaction.atomic():
+ comment = Comment.objects.create(
+ team=team,
+ scope=EMAIL_THREAD_COMMENT_SCOPE,
+ item_id=str(thread.id),
+ content=content,
+ )
+ EmailThreadMessage.objects.for_team(team.id).create(
+ team=team,
+ thread=thread,
+ comment=comment,
+ message_id=f"<{source_id}@example.com>",
+ sent_at=sent_at,
+ sender_email=sender_email,
+ sender_name=sender_name,
+ to_recipients=[],
+ cc_recipients=[],
+ direction=direction,
+ source_type="customer_analytics_seed",
+ source_id=source_id,
+ )
+
+
+def _seed_support_ticket(*, team: Team, account: Account, index: int) -> None:
+ session_id = f"ca-seed-{str(account.id)[:48]}"
+ ticket = Ticket.objects.filter(team=team, widget_session_id=session_id).first()
+ if ticket is None:
+ ticket = Ticket.objects.create_with_number(
+ team=team,
+ widget_session_id=session_id,
+ distinct_id="",
+ organization_id=account.external_id,
+ status="open",
+ priority="medium",
+ anonymous_traits={
+ "name": "Customer champion",
+ "email": f"champion@customer-{index}.example.com",
+ },
+ )
+ Comment.objects.get_or_create(
+ team=team,
+ scope="conversations_ticket",
+ item_id=str(ticket.id),
+ content="Could you help us review our workspace configuration?",
+ defaults={"item_context": {"author_type": "customer", "is_private": False}},
+ )
+
+
+def _seed_channel_summary(*, team: Team, account: Account, index: int) -> None:
+ period = get_last_closed_period(SlackSummaryCadence.WEEKLY, timezone.now(), team.timezone_info)
+ period_start = period.start
+ values = {
+ "slack_channel_id": account.properties.slack_channel_id or f"CSEED{index:04d}",
+ "model_name": "customer-analytics-dev-seed",
+ "period_end": period.end,
+ "content": "The team reviewed adoption, rollout timing, and next steps for the account.",
+ "message_count": 3,
+ "messages": [
+ {
+ "author": "Customer champion",
+ "sent_at": str(period_start + timedelta(days=1)),
+ "permalink": "https://example.com/customer-conversation",
+ },
+ {
+ "author": "Account manager",
+ "sent_at": str(period_start + timedelta(days=3)),
+ "permalink": "https://example.com/account-manager-reply",
+ },
+ {
+ "author": "Customer champion",
+ "sent_at": str(period_start + timedelta(days=5)),
+ "permalink": "https://example.com/customer-follow-up",
+ },
+ ],
+ }
+ AccountChannelSummary.objects.for_team(team.id).get_or_create(
+ team=team,
+ account=account,
+ cadence=SlackSummaryCadence.WEEKLY,
+ period_start=period_start,
+ defaults=values,
+ )
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index a503b709ccfe..3802722fd9f5 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -352,7 +352,7 @@ Use a full devbox stack when checking account tabs against real product routing
5. Restart the backend after syncing flags so local flag evaluation reloads them.
6. Open `/project/<team_id>/customer_analytics/accounts` and confirm the seeded group appears as an account.
-The seed command does not create communication data. For the Email threads tab, capture a message through the Mailgun flow or add an invented local thread linked to one seeded account.
+The seed command also adds billing insights, meetings, an email thread, a Support ticket, and a weekly Slack summary to the first five accounts (`--accounts-with-widget-data`). It fills missing contact fields on those accounts and keeps values you set.
## Conventions
diff --git a/products/product_analytics/backend/facade/api.py b/products/product_analytics/backend/facade/api.py
index 3228f1edfd0c..ff5f98515f1b 100644
--- a/products/product_analytics/backend/facade/api.py
+++ b/products/product_analytics/backend/facade/api.py
@@ -151,14 +151,22 @@ def get_query_specific_instructions(kind: str) -> str:
def get_or_create_saved_insight(
*,
team_id: int,
- user_id: int,
+ user_id: int | None,
short_id: str,
name: str | None,
description: str | None,
query: dict[str, object] | None,
+ revive_deleted: bool = True,
) -> tuple[int, bool]:
+ """Create a saved insight, optionally restoring a soft-deleted short-ID collision."""
return logic.get_or_create_saved_insight(
- team_id=team_id, user_id=user_id, short_id=short_id, name=name, description=description, query=query
+ team_id=team_id,
+ user_id=user_id,
+ short_id=short_id,
+ name=name,
+ description=description,
+ query=query,
+ revive_deleted=revive_deleted,
)
diff --git a/products/product_analytics/backend/logic.py b/products/product_analytics/backend/logic.py
index 3f68560103c4..08f3f5e3e101 100644
--- a/products/product_analytics/backend/logic.py
+++ b/products/product_analytics/backend/logic.py
@@ -171,18 +171,19 @@ def get_query_specific_instructions(kind: str) -> str:
def get_or_create_saved_insight(
*,
team_id: int,
- user_id: int,
+ user_id: int | None,
short_id: str,
name: str | None,
description: str | None,
query: dict[str, object] | None,
+ revive_deleted: bool = True,
) -> tuple[int, bool]:
insight, created = Insight.objects_including_soft_deleted.get_or_create(
team_id=team_id,
short_id=short_id,
defaults={"created_by_id": user_id, "name": name, "description": description, "query": query, "saved": True},
)
- if insight.deleted:
+ if insight.deleted and revive_deleted:
insight.deleted = False
insight.save(update_fields=["deleted"])
return insight.id, created