: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
chore(admin): move group type mapping updates to team page (#65299)
Nick Bestbef3752ed36b
diff --git a/posthog/admin/admins/group_type_mapping_admin.py b/posthog/admin/admins/group_type_mapping_admin.pydeleted file mode 100644index 7601a74e976c..000000000000--- a/posthog/admin/admins/group_type_mapping_admin.py+++ /dev/null@@ -1,143 +0,0 @@-import threading--from django.contrib import admin-from django.db.models import Q-from django.urls import NoReverseMatch, reverse-from django.utils.html import format_html--from posthog.models import Project, Team-from posthog.models.group_type_mapping import GroupTypeMapping, invalidate_group_types_cache--[email protected](GroupTypeMapping)-class GroupTypeMappingAdmin(admin.ModelAdmin):- list_display = (- "group_type_index",- "group_type",- "name_singular",- "name_plural",- "team_link",- "organization_link",- "created_at",- )- search_fields = ("group_type", "name_singular", "name_plural")- fields = (- "organization_link",- "team_link",- "project_link",- "group_type",- "group_type_index",- "name_singular",- "name_plural",- "default_columns",- "detail_dashboard_link",- "created_at",- )- readonly_fields = (- "organization_link",- "team_link",- "project_link",- "group_type",- "group_type_index",- "detail_dashboard_link",- )-- # ModelAdmin is a per-site singleton; under threaded WSGI we can't stash request-scoped- # state on `self` without one thread's cache leaking into another's row rendering.- _request_local = threading.local()-- def save_model(self, request, obj, form, change):- super().save_model(request, obj, form, change)- if obj.project_id:- invalidate_group_types_cache(obj.project_id)-- def get_queryset(self, request):- qs = super().get_queryset(request)- # `posthog_grouptypemapping` lives in the persons DB while Team/Project/Dashboard- # live in the main DB, so Django can't JOIN across them. Prefetch the Team rows- # (with organization for organization_link) from the main DB to avoid N+1.- team_ids = list(qs.values_list("team_id", flat=True).distinct()[:1000])- teams = Team.objects.filter(id__in=team_ids).select_related("organization") if team_ids else []- self._request_local.team_cache = {team.id: team for team in teams}- return qs-- def get_search_results(self, request, queryset, search_term):- base_queryset = queryset- queryset, may_have_duplicates = super().get_search_results(request, queryset, search_term)- if not search_term:- return queryset, may_have_duplicates-- # Resolve team/org name matches on the main DB first, then add an IN-filter on- # the persons-DB queryset – see get_queryset above for the same cross-DB pattern.- team_ids = list(- Team.objects.filter(- Q(name__icontains=search_term) | Q(organization__name__icontains=search_term)- ).values_list("id", flat=True)[:1000]- )- if team_ids:- queryset = queryset | base_queryset.filter(team_id__in=team_ids)- may_have_duplicates = True-- return queryset, may_have_duplicates-- def _cached_team(self, team_id: int) -> Team | None:- cache = getattr(self._request_local, "team_cache", {})- team = cache.get(team_id)- if team is None:- team = Team.objects.filter(pk=team_id).select_related("organization").first()- if team is not None:- cache[team_id] = team- return team-- @admin.display(description="Team")- def team_link(self, group_type_mapping: GroupTypeMapping) -> str:- team_id = group_type_mapping.team_id- if not team_id:- return "-"- team = self._cached_team(team_id)- if team is None:- return f"Team {team_id} (not found)"- return format_html(- '<a href="{}">{}</a>',- reverse("admin:posthog_team_change", args=[team.pk]),- team.name,- )-- @admin.display(description="Organization")- def organization_link(self, group_type_mapping: GroupTypeMapping) -> str:- team_id = group_type_mapping.team_id- if not team_id:- return "-"- team = self._cached_team(team_id)- if team is None or team.organization_id is None:- return "-"- return format_html(- '<a href="{}">{}</a>',- reverse("admin:posthog_organization_change", args=[team.organization_id]),- team.organization.name,- )-- @admin.display(description="Project")- def project_link(self, group_type_mapping: GroupTypeMapping) -> str:- project_id = group_type_mapping.project_id- if not project_id:- return "-"- project = Project.objects.filter(pk=project_id).only("id", "name").first()- if project is None:- return f"Project {project_id} (not found)"- return format_html(- '<a href="{}">{}</a>',- reverse("admin:posthog_project_change", args=[project.pk]),- project.name,- )-- @admin.display(description="Detail dashboard")- def detail_dashboard_link(self, group_type_mapping: GroupTypeMapping) -> str:- dashboard_id = group_type_mapping.detail_dashboard_id- if not dashboard_id:- return "-"- try:- url = reverse("admin:dashboards_dashboard_change", args=[dashboard_id])- except NoReverseMatch:- return f"Dashboard {dashboard_id}"- return format_html('<a href="{}">Dashboard {}</a>', url, dashboard_id)diff --git a/posthog/admin/admins/team_admin.py b/posthog/admin/admins/team_admin.pyindex df0d6891c39d..8f787cba4885 100644--- a/posthog/admin/admins/team_admin.py+++ b/posthog/admin/admins/team_admin.py@@ -7,6 +7,7 @@ import hashlibimport tempfilefrom datetime import datetime, timedeltafrom decimal import Decimal, InvalidOperation+from typing import Anyfrom urllib import parsefrom django.conf import settings@@ -18,7 +19,7 @@ from django.forms import ModelForm, ValidationErrorfrom django.http import HttpResponse, HttpResponseNotAllowed, JsonResponsefrom django.shortcuts import redirect, renderfrom django.template.loader import render_to_string-from django.urls import path, reverse+from django.urls import NoReverseMatch, path, reversefrom django.utils import timezonefrom django.utils.html import escapejs, format_htmlfrom django.utils.safestring import mark_safe@@ -36,8 +37,16 @@ from posthog.cloud_utils import is_cloudfrom posthog.llm.gateway_internal_client import AIGatewayInternalError, AIGatewayNotConfigured, add_credit, get_walletfrom posthog.models import Teamfrom posthog.models.activity_logging.activity_log import Detail, log_activity+from posthog.models.group_type_mapping import invalidate_group_types_cachefrom posthog.models.remote_config import RemoteConfigfrom posthog.models.team.team import DEPRECATED_ATTRS+from posthog.personhog_client.client import get_personhog_client+from posthog.personhog_client.converters import proto_group_type_mapping_to_dict+from posthog.personhog_client.proto import (+ GetGroupTypeMappingsByProjectIdRequest,+ GetGroupTypeMappingsByTeamIdRequest,+ UpdateGroupTypeMappingRequest,+)from posthog.session_recordings.recordings import recording_s3_clientfrom posthog.storage.gateway_credential_cache import validate_overspend_allowance_usdfrom posthog.temporal.common.client import sync_connect@@ -136,6 +145,7 @@ class TeamAdmin(admin.ModelAdmin):"ai_gateway_actions","ai_gateway_wallet","policy_cache_blob",+ "group_type_mappings_display",]exclude = DEPRECATED_ATTRS@@ -242,6 +252,15 @@ class TeamAdmin(admin.ModelAdmin):],},),+ (+ "Group type mappings",+ {+ "classes": ["collapse"],+ "fields": [+ "group_type_mappings_display",+ ],+ },+ ),("Session replay actions",{@@ -297,6 +316,173 @@ class TeamAdmin(admin.ModelAdmin):)return "-"+ @admin.display(description="Group type mappings")+ def group_type_mappings_display(self, team: Team):+ if not team.pk:+ return "-"+ client = get_personhog_client()+ if client is None:+ return format_html("<em>personhog client not configured</em>")+ try:+ resp = client.get_group_type_mappings_by_team_id(GetGroupTypeMappingsByTeamIdRequest(team_id=team.id))+ mappings_raw = sorted(+ [proto_group_type_mapping_to_dict(m) for m in resp.mappings],+ key=lambda d: d["group_type_index"],+ )+ except Exception as exc:+ logger.warning("admin_group_type_mappings_fetch_failed", team_id=team.id, error=str(exc))+ return format_html(+ '<p style="color: #856404; background: #fff3cd; border: 1px solid #ffc107; '+ 'padding: 8px 12px; border-radius: 4px; margin: 4px 0; font-size: 13px;">'+ "Failed to fetch group type mappings from personhog</p>",+ )+ mappings = []+ for m in mappings_raw:+ detail_dashboard_id = m.get("detail_dashboard") or m.get("detail_dashboard_id")+ detail_dashboard_url = None+ if detail_dashboard_id:+ try:+ detail_dashboard_url = reverse("admin:dashboards_dashboard_change", args=[detail_dashboard_id])+ except NoReverseMatch:+ pass+ mappings.append(+ {+ **m,+ "detail_dashboard_id": detail_dashboard_id,+ "detail_dashboard_url": detail_dashboard_url,+ "edit_url": reverse(+ "admin:posthog_team_edit_group_type_mapping",+ args=[team.pk, m["group_type_index"]],+ ),+ }+ )+ # nosemgrep: python.django.security.audit.avoid-mark-safe.avoid-mark-safe (admin-only, renders trusted template)+ return mark_safe(+ render_to_string(+ "admin/posthog/team/group_type_mappings_display.html",+ {"mappings": mappings, "team": team},+ request=getattr(self, "_current_request", None),+ )+ )++ def _get_personhog_client_or_error(self, request, redirect_url):+ """Return (client, None) or (None, redirect_response) if personhog is unavailable."""+ client = get_personhog_client()+ if client is None:+ messages.error(request, "personhog client is not configured — cannot manage group type mappings.")+ return None, redirect(redirect_url)+ return client, None++ def _fetch_group_type_mapping_via_personhog(self, client, project_id, group_type_index):+ """Fetch a single mapping from personhog by project_id + group_type_index. Returns dict or None."""+ resp = client.get_group_type_mappings_by_project_id(+ GetGroupTypeMappingsByProjectIdRequest(project_id=project_id)+ )+ for m in resp.mappings:+ d = proto_group_type_mapping_to_dict(m)+ if d["group_type_index"] == group_type_index:+ return d+ return None++ def edit_group_type_mapping_view(self, request, object_id, group_type_index):+ team = Team.objects.select_related("project").get(pk=object_id)+ if not self.has_change_permission(request, team):+ raise PermissionDenied+ group_type_index = int(group_type_index)+ team_url = reverse("admin:posthog_team_change", args=[object_id])++ client, err_response = self._get_personhog_client_or_error(request, team_url)+ if err_response is not None:+ return err_response++ try:+ mapping_dict = self._fetch_group_type_mapping_via_personhog(client, team.project_id, group_type_index)+ except Exception as exc:+ logger.warning(+ "admin_group_type_mapping_fetch_failed",+ team_id=team.id,+ group_type_index=group_type_index,+ error=str(exc),+ )+ messages.warning(request, "Failed to fetch group type mappings from personhog")+ return redirect(team_url)++ if mapping_dict is None:+ messages.error(request, f"Group type mapping with index {group_type_index} not found for this team.")+ return redirect(team_url)++ if request.method == "GET":+ default_columns = mapping_dict.get("default_columns")+ default_columns_json = json.dumps(default_columns) if default_columns else ""+ context = {+ **self.admin_site.each_context(request),+ "team": team,+ "mapping": mapping_dict,+ "default_columns_json": default_columns_json,+ "title": f"Edit group type mapping - {team.name} - index {group_type_index}",+ }+ return render(request, "admin/posthog/team/group_type_mapping_edit.html", context)+ if request.method != "POST":+ return HttpResponseNotAllowed(["GET", "POST"])++ name_singular = request.POST.get("name_singular", "").strip()+ name_plural = request.POST.get("name_plural", "").strip()++ default_columns_raw = request.POST.get("default_columns", "").strip()+ parsed_default_columns: list[str] | None = None+ if default_columns_raw:+ try:+ parsed = json.loads(default_columns_raw)+ if not isinstance(parsed, list):+ raise ValueError+ parsed_default_columns = parsed+ except (json.JSONDecodeError, ValueError):+ messages.error(request, "Default columns must be a valid JSON array.")+ return redirect(+ reverse("admin:posthog_team_edit_group_type_mapping", args=[object_id, group_type_index])+ )++ update_mask = ["name_singular", "name_plural"]+ update_kwargs: dict[str, Any] = {+ "project_id": team.project_id,+ "group_type_index": group_type_index,+ "name_singular": name_singular,+ "name_plural": name_plural,+ }+ if default_columns_raw:+ update_mask.append("default_columns")+ if parsed_default_columns is not None:+ update_kwargs["default_columns"] = json.dumps(parsed_default_columns).encode()+ update_kwargs["update_mask"] = update_mask++ try:+ client.update_group_type_mapping(UpdateGroupTypeMappingRequest(**update_kwargs))+ except Exception as exc:+ logger.exception(+ "admin_edit_group_type_mapping_failed",+ team_id=team.id,+ group_type_index=group_type_index,+ error=str(exc),+ )+ messages.error(request, f"Failed to update via personhog: {exc}")+ return redirect(reverse("admin:posthog_team_edit_group_type_mapping", args=[object_id, group_type_index]))++ if team.project_id:+ invalidate_group_types_cache(team.project_id)++ logger.info(+ "admin_edit_group_type_mapping",+ team_id=team.id,+ group_type_index=group_type_index,+ fields=update_kwargs["update_mask"],+ triggered_by=request.user.email,+ )+ messages.success(+ request,+ f"Updated group type mapping (index {group_type_index}) for team '{team.name}'.",+ )+ return redirect(reverse("admin:posthog_team_change", args=[object_id]))+@admin.display(description="PostHog system internal properties")def internal_properties(self, team: Team):from posthog import settings@@ -645,6 +831,11 @@ class TeamAdmin(admin.ModelAdmin):def get_urls(self):urls = super().get_urls()custom_urls = [+ path(+ "<path:object_id>/group-type-mapping/<int:group_type_index>/edit/",+ self.admin_site.admin_view(self.edit_group_type_mapping_view),+ name="posthog_team_edit_group_type_mapping",+ ),path("<path:object_id>/view-cache/",self.admin_site.admin_view(self.view_cache),diff --git a/posthog/admin/inlines/group_type_mapping_inline.py b/posthog/admin/inlines/group_type_mapping_inline.pydeleted file mode 100644index 0f7adf366087..000000000000--- a/posthog/admin/inlines/group_type_mapping_inline.py+++ /dev/null@@ -1,14 +0,0 @@-from django.contrib import admin--from posthog.models import GroupTypeMapping---class GroupTypeMappingInline(admin.TabularInline):- extra = 0- model = GroupTypeMapping- fields = ("group_type_index", "group_type", "name_singular", "name_plural")- readonly_fields = fields- classes = ("collapse",)- max_num = 5- min_num = 5- show_change_link = Truediff --git a/posthog/admin/inlines/team_inline.py b/posthog/admin/inlines/team_inline.pyindex 34fc30334035..becc373ae729 100644--- a/posthog/admin/inlines/team_inline.py+++ b/posthog/admin/inlines/team_inline.py@@ -51,6 +51,7 @@ class TeamInline(TabularInlinePaginated):"ai_gateway_actions","ai_gateway_wallet","policy_cache_blob",+ "group_type_mappings_display",)] + ["displayed_name"]diff --git a/posthog/templates/admin/posthog/team/group_type_mapping_edit.html b/posthog/templates/admin/posthog/team/group_type_mapping_edit.htmlnew file mode 100644index 000000000000..11f1a5a798af--- /dev/null+++ b/posthog/templates/admin/posthog/team/group_type_mapping_edit.html@@ -0,0 +1,42 @@+{% extends "admin/base_site.html" %}+{% load i18n %}++{% block content %}+<p>Edit group type mapping for <strong>{{ team.name }}</strong> (team {{ team.pk }}).</p>++<table style="margin-bottom: 20px; border-collapse: collapse;">+ <tr>+ <td style="padding: 4px 12px 4px 0; font-weight: bold;">Group type index:</td>+ <td style="padding: 4px 0;">{{ mapping.group_type_index }}</td>+ </tr>+ <tr>+ <td style="padding: 4px 12px 4px 0; font-weight: bold;">Group type:</td>+ <td style="padding: 4px 0;"><code>{{ mapping.group_type }}</code></td>+ </tr>+ <tr>+ <td style="padding: 4px 12px 4px 0; font-weight: bold;">Created at:</td>+ <td style="padding: 4px 0;">{{ mapping.created_at|default:"-" }}</td>+ </tr>+</table>++<form method="post" onsubmit="this.querySelector('input[type=submit]').disabled = true;">+ {% csrf_token %}+ <div style="margin: 20px 0;">+ <label for="name_singular" style="display: block; margin-bottom: 5px; font-weight: bold;">Name (singular):</label>+ <input type="text" id="name_singular" name="name_singular" value="{{ mapping.name_singular|default:'' }}" style="width: 400px; padding: 8px;" />+ </div>+ <div style="margin: 20px 0;">+ <label for="name_plural" style="display: block; margin-bottom: 5px; font-weight: bold;">Name (plural):</label>+ <input type="text" id="name_plural" name="name_plural" value="{{ mapping.name_plural|default:'' }}" style="width: 400px; padding: 8px;" />+ </div>+ <div style="margin: 20px 0;">+ <label for="default_columns" style="display: block; margin-bottom: 5px; font-weight: bold;">Default columns (JSON array):</label>+ <input type="text" id="default_columns" name="default_columns" value="{{ default_columns_json }}" style="width: 400px; padding: 8px;" />+ <p style="margin-top: 4px; color: #666; font-size: 12px;">JSON array of column names, e.g. <code>["name", "email"]</code>. Leave blank to clear.</p>+ </div>+ <div style="margin-top: 20px;">+ <input type="submit" class="default" value="Save changes" style="padding: 10px 20px;" />+ <a href="{% url 'admin:posthog_team_change' team.pk %}" style="margin-left: 10px;">Cancel</a>+ </div>+</form>+{% endblock %}diff --git a/posthog/templates/admin/posthog/team/group_type_mappings_display.html b/posthog/templates/admin/posthog/team/group_type_mappings_display.htmlnew file mode 100644index 000000000000..83298185c71a--- /dev/null+++ b/posthog/templates/admin/posthog/team/group_type_mappings_display.html@@ -0,0 +1,42 @@+<div style="margin: 10px 0;">+{% if mappings %}+<table style="border-collapse: collapse; width: 100%;">+ <thead>+ <tr>+ <th style="border: 1px solid #ddd; padding: 8px; text-align: left; background: #f5f5f5;">Index</th>+ <th style="border: 1px solid #ddd; padding: 8px; text-align: left; background: #f5f5f5;">Group type</th>+ <th style="border: 1px solid #ddd; padding: 8px; text-align: left; background: #f5f5f5;">Name (singular)</th>+ <th style="border: 1px solid #ddd; padding: 8px; text-align: left; background: #f5f5f5;">Name (plural)</th>+ <th style="border: 1px solid #ddd; padding: 8px; text-align: left; background: #f5f5f5;">Detail dashboard</th>+ <th style="border: 1px solid #ddd; padding: 8px; text-align: left; background: #f5f5f5;">Actions</th>+ </tr>+ </thead>+ <tbody>+ {% for m in mappings %}+ <tr>+ <td style="border: 1px solid #ddd; padding: 8px;">{{ m.group_type_index }}</td>+ <td style="border: 1px solid #ddd; padding: 8px;"><code>{{ m.group_type }}</code></td>+ <td style="border: 1px solid #ddd; padding: 8px;">{{ m.name_singular|default:"-" }}</td>+ <td style="border: 1px solid #ddd; padding: 8px;">{{ m.name_plural|default:"-" }}</td>+ <td style="border: 1px solid #ddd; padding: 8px;">+ {% if m.detail_dashboard_id %}+ {% if m.detail_dashboard_url %}+ <a href="{{ m.detail_dashboard_url }}">Dashboard {{ m.detail_dashboard_id }}</a>+ {% else %}+ Dashboard {{ m.detail_dashboard_id }}+ {% endif %}+ {% else %}+ -+ {% endif %}+ </td>+ <td style="border: 1px solid #ddd; padding: 8px;">+ <a class="button" href="{{ m.edit_url }}" style="padding: 4px 12px; font-size: 12px;">Edit</a>+ </td>+ </tr>+ {% endfor %}+ </tbody>+</table>+{% else %}+<p style="color: #666;">No group type mappings found for this team.</p>+{% endif %}+</div>