: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(conversations): persist organization_id on tickets (#65989)
Alex V3ea7bb937474
diff --git a/products/conversations/backend/api/tests/test_events.py b/products/conversations/backend/api/tests/test_events.pyindex a27fb5be6c63..8075a5a846b6 100644--- a/products/conversations/backend/api/tests/test_events.py+++ b/products/conversations/backend/api/tests/test_events.py@@ -719,6 +719,39 @@ class TestConversationEvents(BaseTest):else:assert "$groups" not in call.kwargs["properties"]+ @patch("products.conversations.backend.events.capture_internal")+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")+ def test_capture_ticket_created_persists_organization_id(self, mock_get_persons, mock_capture):+ from posthog.models.person.person import Person++ person_org = Organization.objects.create(name="Persist Org")+ person_user = User.objects.create(email="[email protected]", distinct_id="customer-123")+ OrganizationMembership.objects.create(user=person_user, organization=person_org)++ mock_get_persons.return_value = [Person(team_id=self.team.id, is_identified=True)]++ assert self.ticket.organization_id is None+ capture_ticket_created(self.ticket)++ self.ticket.refresh_from_db()+ assert self.ticket.organization_id == str(person_org.id)++ @patch("products.conversations.backend.events.capture_internal")+ @patch("products.conversations.backend.events._resolve_org_groups")+ def test_capture_message_received_uses_stored_organization_id(self, mock_resolve, mock_capture):+ self.ticket.organization_id = "stored-org-123"+ self.ticket.save(update_fields=["organization_id"])++ capture_message_received(self.ticket, "msg-456", "Hello support")++ mock_resolve.assert_not_called()+ call_kwargs = mock_capture.call_args.kwargs+ assert call_kwargs["process_person_profile"] is True+ groups = call_kwargs["properties"]["$groups"]+ assert groups["organization"] == "stored-org-123"+ assert groups["project"] == str(self.team.uuid)+ assert groups["instance"] == SITE_URL+@patch("products.conversations.backend.events.capture_internal")def test_capture_ticket_status_changed_system_actor_uses_customer_distinct_id(self, mock_capture):"""System actions (e.g. snooze wake) use the customer's distinct_id, not an actor's."""diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex 88da2994f7b0..99c8ba39fdcb 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -259,6 +259,7 @@ class TicketSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):"cc_participants","github_repo","github_issue_number",+ "organization_id","person","tags",]@@ -286,6 +287,7 @@ class TicketSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):"cc_participants","github_repo","github_issue_number",+ "organization_id","person","ai_triage",]@@ -294,6 +296,9 @@ class TicketSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):"priority": {"help_text": "Ticket priority: low, medium, or high. Null if unset."},"sla_due_at": {"help_text": "SLA deadline set via workflows. Null means no SLA."},"anonymous_traits": {"help_text": "Customer-provided traits such as name and email"},+ "organization_id": {+ "help_text": "Customer's PostHog organization group key, resolved at ticket creation. Null when unknown."+ },"ai_triage": {"help_text": "AI support pipeline triage and outcome (status, result, ticket_type, confidence, attempts, etc.)."},diff --git a/products/conversations/backend/events.py b/products/conversations/backend/events.pyindex a901bc467c8e..6f32a4b3fce3 100644--- a/products/conversations/backend/events.py+++ b/products/conversations/backend/events.py@@ -212,6 +212,11 @@ def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None]:return False, None+def _groups_from_org_id(team: Team, organization_id: str) -> dict:+ """Rebuild minimal $groups from a stored org id, skipping the expensive resolver."""+ return {"instance": SITE_URL, "project": str(team.uuid), "organization": organization_id}++def _get_ticket_base_properties(ticket: Ticket) -> dict:return {"ticket_id": str(ticket.id),@@ -246,6 +251,10 @@ def capture_ticket_created(ticket: Ticket) -> None:process_person, groups = _resolve_org_groups(ticket, team)if groups is not None:properties["$groups"] = groups+ org_id = groups.get("organization")+ if org_id and not ticket.organization_id:+ Ticket.objects.filter(id=ticket.id).update(organization_id=org_id)+ ticket.organization_id = org_idexcept Exception:logger.exception("ticket_created_person_lookup_failed", team_id=team_id, ticket_id=str(ticket.id))@@ -361,9 +370,13 @@ def capture_message_received(ticket: Ticket, message_id: str, message_content: steam = ticket.teamprocess_person = Falsetry:- process_person, groups = _resolve_org_groups(ticket, team)- if groups is not None:- properties["$groups"] = groups+ if ticket.organization_id:+ properties["$groups"] = _groups_from_org_id(team, ticket.organization_id)+ process_person = True+ else:+ process_person, groups = _resolve_org_groups(ticket, team)+ if groups is not None:+ properties["$groups"] = groupsexcept Exception:logger.exception("message_received_person_lookup_failed", team_id=team.id, ticket_id=str(ticket.id))diff --git a/products/conversations/backend/migrations/0041_ticket_organization_id.py b/products/conversations/backend/migrations/0041_ticket_organization_id.pynew file mode 100644index 000000000000..e07a73551586--- /dev/null+++ b/products/conversations/backend/migrations/0041_ticket_organization_id.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("conversations", "0040_ticket_ai_triage"),+ ]++ operations = [+ migrations.AddField(+ model_name="ticket",+ name="organization_id",+ field=models.CharField(blank=True, max_length=400, null=True),+ ),+ ]diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txtindex a3a5e6323313..4b1dc4731b2d 100644--- a/products/conversations/backend/migrations/max_migration.txt+++ b/products/conversations/backend/migrations/max_migration.txt@@ -1 +1 @@-0040_ticket_ai_triage+0041_ticket_organization_iddiff --git a/products/conversations/backend/models/ticket.py b/products/conversations/backend/models/ticket.pyindex 50bd99186026..29987beb0177 100644--- a/products/conversations/backend/models/ticket.py+++ b/products/conversations/backend/models/ticket.py@@ -98,6 +98,9 @@ class Ticket(UUIDTModel):# Snooze — when set, ticket is "on hold" until this time, then auto-reopened by wake tasksnoozed_until = models.DateTimeField(null=True, blank=True)+ # Customer's PostHog org group key, resolved once at creation (local org pk or cross-region analytics key).+ organization_id = models.CharField(max_length=400, null=True, blank=True)+created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex 2c5a98ac5eb1..b12795bd94d1 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -726,6 +726,11 @@ export interface TicketApi {readonly github_repo: string | null/** @nullable */readonly github_issue_number: number | null+ /**+ * Customer's PostHog organization group key, resolved at ticket creation. Null when unknown.+ * @nullable+ */+ readonly organization_id: string | nullreadonly person: TicketPersonApi | nulltags?: unknown[]}@@ -806,6 +811,11 @@ export interface PatchedTicketApi {readonly github_repo?: string | null/** @nullable */readonly github_issue_number?: number | null+ /**+ * Customer's PostHog organization group key, resolved at ticket creation. Null when unknown.+ * @nullable+ */+ readonly organization_id?: string | nullreadonly person?: TicketPersonApi | nulltags?: unknown[]}diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsxindex 4968f328d964..bac3022ec773 100644--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx@@ -235,6 +235,14 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem</span></div>)}+ {ticket?.organization_id && (+ <div className="flex justify-between items-start gap-2">+ <span className="text-muted-alt shrink-0">Organization</span>+ <span className="text-xs truncate text-right" title={ticket.organization_id}>+ {ticket.organization_id}+ </span>+ </div>+ )}{ticket?.channel_source === 'slack' &&ticket?.slack_channel_id &&ticket?.slack_thread_ts && (diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.tsindex 40cb92b392ba..0934b3ff51de 100644--- a/products/conversations/frontend/types.ts+++ b/products/conversations/frontend/types.ts@@ -128,6 +128,7 @@ export interface Ticket {cc_participants?: string[]github_repo?: string | nullgithub_issue_number?: number | null+ organization_id?: string | nullperson?: TicketPerson | nulltags?: string[]ai_triage?: AITriagediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c442ea052329..f48d29ceec53 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -33587,6 +33587,11 @@ export namespace Schemas {readonly github_repo: string | null;/** @nullable */readonly github_issue_number: number | null;+ /**+ * Customer's PostHog organization group key, resolved at ticket creation. Null when unknown.+ * @nullable+ */+ readonly organization_id: string | null;readonly person: TicketPerson | null;tags?: unknown[];}@@ -40959,6 +40964,11 @@ export namespace Schemas {readonly github_repo?: string | null;/** @nullable */readonly github_issue_number?: number | null;+ /**+ * Customer's PostHog organization group key, resolved at ticket creation. Null when unknown.+ * @nullable+ */+ readonly organization_id?: string | null;readonly person?: TicketPerson | null;tags?: unknown[];}