: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(devex): add organization pages and tool actions to the admin console (#130715)
Julian Bezbb8ab19baa7a
diff --git a/.agents/skills/extending-the-admin-console/SKILL.md b/.agents/skills/extending-the-admin-console/SKILL.mdindex 460cd7665c1a..4d35ae94ceec 100644--- a/.agents/skills/extending-the-admin-console/SKILL.md+++ b/.agents/skills/extending-the-admin-console/SKILL.md@@ -12,10 +12,10 @@ Read [`posthog/admin/console/AGENTS.md`](../../../posthog/admin/console/AGENTS.m## 1. Decide where it goes- **Plain create, read, update or delete on one model** stays in Django admin. The console is not a second CRUD layer.-- **Facts and actions about one team** go in a panel. One panel per product concern, owned by the team that owns the data.-- **A report across many teams** is a tool. Tools only read. An action from a tool row links to the team page.+- **Facts and actions about one team or one organization** go in a panel on that record's page. One panel per product concern, owned by the team that owns the data.+- **A report across many teams, or an action that is not about one record** (a backfill, a re-save across teams) is a tool. An action on one team from a tool row links to that team's page instead of becoming a tool operation.- **A staff page your product already has in the app** (a DRF staff endpoint and scene) is legacy. Do not extend it and do not bridge to it. Ask the user whether to move it into the console as its own change.-- **Anything else** (a new record type such as an organization or user page, a new block kind, a new tool group, a template change) is a shell change. Stop and ask the user: those need a review by the console owners (team-devex), not a product team alone.+- **Anything else** (a new record type such as a user or project page, a new block kind, a new tool group, a template change) is a shell change. Stop and ask the user: those need a review by the console owners (team-devex), not a product team alone.## 2. Write the panel or tool as data@@ -47,13 +47,13 @@ Invoke `/writing-user-facing-copy`. In the console that means:## 5. Move a Django admin action without losing anyone1. Point the operation at the old view with `AdminViewBridge(Model, SomeAdmin.view_method)` while the logic still lives in the `ModelAdmin`.-2. Replace the old button in Django admin with `MovedToConsole.team_action(team, "<panel-key>", "<what moved>")`, so staff who look in the usual place find the new one.+2. Replace the old button in Django admin with `MovedToConsole.action("<record>", obj, "<panel-key>", "<what moved>")`, so staff who look in the usual place find the new one.3. When a whole page moves, keep its old URL name and route it to `MovedToConsole.page_redirect`, which tells staff the page moved.-4. Every old URL keeps working, query parameters included. Support staff keep bookmarks to old admin pages and actions. When you delete a team action's view, add its old path to `MOVED_TEAM_ACTIONS` in `posthog/admin/console/urls.py`, so it redirects to the console form or panel.+4. Every old URL keeps working, query parameters included. Support staff keep bookmarks to old admin pages and actions. When you delete a record action's view, add its old path to `MOVED_TEAM_ACTIONS` or `MOVED_ORGANIZATION_ACTIONS` in `posthog/admin/console/urls.py`, so it redirects to the console form or panel.## 6. Before you call it done-- Extend `posthog/admin/test_admin_console.py`: add the panel title to the team page test, and a parameterized case for each new operation's success and refusal. Do not add a new test file.+- Extend `posthog/admin/test_admin_console.py`: add the panel title to the record page test, and a parameterized case for each new operation's success and refusal. Do not add a new test file.- Run `pnpm --filter=@posthog/frontend build:admin-console` when you add an owner crest. Commit the output.-- Open `/admin/console/teams/<id>/` on the local stack (log in as `[email protected]`) and look at the page at a narrow and a wide window. A panel that reads wrong in the browser is not done, whatever the tests say.+- Open the record page (`/admin/console/teams/<id>/` or `/admin/console/organizations/<uuid>/`) on the local stack (log in as `[email protected]`) and look at the page at a narrow and a wide window. A panel that reads wrong in the browser is not done, whatever the tests say.- Put a screenshot of the panel in the PR description.diff --git a/ee/urls.py b/ee/urls.pyindex d3dc429fc274..fd1b248f27b9 100644--- a/ee/urls.py+++ b/ee/urls.py@@ -77,7 +77,6 @@ if settings.ADMIN_PORTAL_ENABLED:notebook_markdown_migration_stats_view,notebook_markdown_migration_view,)- from posthog.admin.admins.resave_cohorts_admin import resave_cohorts_viewfrom posthog.admin.admins.tophog_admin import tophog_dashboard_view, tophog_restrictions_viewfrom posthog.admin.console.urls import urlpatterns as console_urlpatterns@@ -92,7 +91,7 @@ if settings.ADMIN_PORTAL_ENABLED:path("admin/apikeysearch", api_key_search_view, name="api_key_search"),path("admin/resave-cohorts/",- admin.site.admin_view(resave_cohorts_view),+ MovedToConsole.page_redirect("Re-save cohorts", "/admin/console/tools/resave-cohorts/"),name="resave-cohorts",),path(diff --git a/frontend/public/admin-console/console.css b/frontend/public/admin-console/console.cssindex aa56a8f57da2..c5c8d0001293 100644--- a/frontend/public/admin-console/console.css+++ b/frontend/public/admin-console/console.css@@ -560,6 +560,9 @@.max-h-\[320px\] {max-height: 320px;}+ .max-h-\[480px\] {+ max-height: 480px;+ }.min-h-7 {min-height: calc(0.25rem * 7);}@@ -833,6 +836,9 @@text-overflow: ellipsis;white-space: nowrap;}+ .overflow-auto {+ overflow: auto;+ }.overflow-hidden {overflow: hidden;}@@ -842,6 +848,9 @@.\!rounded-full {border-radius: calc(infinity * 1px) !important;}+ .rounded {+ border-radius: 0.25rem;+ }.rounded-full {border-radius: calc(infinity * 1px);}@@ -1103,6 +1112,9 @@.whitespace-nowrap {white-space: nowrap;}+ .whitespace-pre-wrap {+ white-space: pre-wrap;+ }.text-current {color: currentcolor;}diff --git a/frontend/public/admin-console/crests/billing.svg b/frontend/public/admin-console/crests/billing.svgnew file mode 100644index 000000000000..d779cc90ea83--- /dev/null+++ b/frontend/public/admin-console/crests/billing.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 115 115"><g filter="url(#crests-billing-filter0_d_26_8966)"><path fill="#fff" d="m75.79 38.99-30.64-27.2a6 6 0 0 0-8.52.57l-8.26 9.53a2 2 0 0 1-1.9.65l-.7-.14a6 6 0 0 0-7.01 4.48l-1.54 6.4a2 2 0 0 1-.45.86l-2.65 3a4 4 0 0 0-1.01 2.65v4.65a2 2 0 0 1-.11.64L8.07 59.53a6 6 0 0 0 3.8 7.64l39.35 12.97a2 2 0 0 1 .7.4l22.44 19.59a6 6 0 0 0 8.65-.8l5-6.3a2 2 0 0 1 1.56-.76h2.33a4 4 0 0 0 3.71-2.52l3.88-9.68a2 2 0 0 1 .32-.55l6.5-7.73a5.83 5.83 0 0 0-.78-8.26 1.9 1.9 0 0 1-.66-1.93l1.94-8.76a4 4 0 0 0-2.7-4.68l-27.6-8.76a2 2 0 0 1-.72-.41"/></g><rect width="36" height="81" x="13.38" y="61.69" fill="#597f32" stroke="#416021" stroke-width="3" rx="2.5" transform="rotate(-71.46 13.38 61.69)"/><rect width="22.62" height="68.74" x="21.32" y="57.29" fill="#8db464" stroke="#416021" stroke-width="3" rx="2.5" transform="rotate(-71.46 21.32 57.3)"/><path fill="#8db464" stroke="#416021" stroke-width="3" d="M43.01 52.8c1.88-5.58 9.6-8.66 17.82-5.9 8.2 2.77 12.5 9.9 10.61 15.48-1.88 5.58-9.6 8.66-17.81 5.9-8.21-2.77-12.5-9.9-10.62-15.48Zm-13.92-5.18c.49-1.47 2.77-2.66 5.65-1.68 2.89.97 3.99 3.3 3.5 4.76s-2.78 2.65-5.67 1.68c-2.88-.98-3.98-3.3-3.48-4.76ZM75.88 64.2c.5-1.45 2.77-2.64 5.66-1.67 2.88.97 3.98 3.3 3.49 4.76-.5 1.46-2.78 2.65-5.66 1.68s-3.98-3.3-3.49-4.76Z"/><rect width="36" height="81" x="17.24" y="42.16" fill="#8db464" stroke="#577f2e" stroke-width="3" rx="2.5" transform="rotate(-48.52 17.24 42.16)"/><rect width="22.62" height="68.74" x="26.26" y="41.21" fill="#d6e080" stroke="#577f2e" stroke-width="3" rx="2.5" transform="rotate(-48.52 26.26 41.21)"/><path fill="#d6e080" stroke="#577f2e" stroke-width="3" d="M48 45.53c3.9-4.41 12.21-4.24 18.7 1.51s7.65 13.98 3.74 18.39c-3.9 4.4-12.22 4.23-18.7-1.52s-7.66-13.98-3.75-18.38ZM37.19 35.32c1.02-1.15 3.58-1.36 5.86.66s2.38 4.6 1.36 5.75-3.59 1.36-5.86-.66-2.38-4.6-1.36-5.75Zm36.63 33.52c1.02-1.15 3.58-1.36 5.86.66s2.38 4.6 1.36 5.75-3.59 1.36-5.87-.66-2.38-4.6-1.35-5.75Z"/><path stroke="#40396e" stroke-width="3" d="m39.79 16.75-9.8 11.03a2 2 0 0 1-2.13.57l-1.26-.42a2 2 0 0 0-2.56 1.37l-1.84 6.62a2 2 0 0 1-.3.64l-3.14 4.31a2 2 0 0 0-.24 1.92l.31.79a2 2 0 0 1 .04 1.39l-5.1 14.89a2 2 0 0 0 1.25 2.55l39.7 13.23a2 2 0 0 1 .7.4l21 18.87a2 2 0 0 0 2.84-.18l6.51-7.5a2 2 0 0 1 2.06-.61l.6.17a2 2 0 0 0 2.38-1.13l3.42-7.85a2 2 0 0 1 .34-.53l6.12-6.92a2 2 0 0 0-.27-2.9l-1.7-1.32a2 2 0 0 1-.67-2.21l2.92-8.75a2 2 0 0 0-1.27-2.54L74.5 44.4a2 2 0 0 1-.7-.4L42.6 16.58a2 2 0 0 0-2.81.17Z"/><defs><filter id="crests-billing-filter0_d_26_8966" width="102.93" height="94.32" x="7.74" y="10.28" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" result="hardAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/><feOffset dx="3" dy="3"/><feComposite in2="hardAlpha" operator="out"/><feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.4 0"/><feBlend in2="BackgroundImageFix" result="effect1_dropShadow_26_8966"/><feBlend in="SourceGraphic" in2="effect1_dropShadow_26_8966" result="shape"/></filter></defs></svg>\ No newline at end of filediff --git a/frontend/public/admin-console/crests/feature-flags.svg b/frontend/public/admin-console/crests/feature-flags.svgnew file mode 100644index 000000000000..a3fb736673ed--- /dev/null+++ b/frontend/public/admin-console/crests/feature-flags.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 115 115"><g stroke="#fff" stroke-width="4" filter="url(#crests-feature-flags-filter0_d_23_15324)"><rect width="83" height="48" x="94.5" y="79.25" fill="#bddaff" rx="24" transform="rotate(-180 94.5 79.25)"/><circle cx="69" cy="55.75" r="18.5" fill="#4571ab" transform="rotate(-180 69 55.75)"/><path stroke-linecap="round" stroke-linejoin="round" d="m74.5 54.25 6 22 5.5-4.5 4.5 4.5 3.5-3.5-4.5-4.5 6-4.5"/><path fill="#fff" d="M72 52.67a2.75 2.75 0 0 1 3.83-3.2l20.76 9.84a2.75 2.75 0 0 1 .59 4.6l-2.89 2.41L97.04 69a2.75 2.75 0 0 1 .01 3.93l-4.33 4.27a2.75 2.75 0 0 1-4-.15l-2.75-3.14-3.5 2.74a2.75 2.75 0 0 1-4.34-1.44z"/><path d="M74 31.25c6.37 0 11.95 2.79 15.76 7.64 3.57 4.55 5.53 10.81 5.3 18.12l2.14 1a6 6 0 0 1 1.69 9.68l-.64.64.17.2a6 6 0 0 1-.37 8.34l-3.35 3.17a6 6 0 0 1-8.36-.12l-.84-.84-.64.63a6 6 0 0 1-8.9-.46H37.5c-8.49 0-14.97-2.93-19.31-7.5a23.5 23.5 0 0 1-6.32-16.52 24.2 24.2 0 0 1 6.6-16.49c4.37-4.55 10.78-7.49 19.03-7.49z"/></g><rect width="79" height="44" x="92.5" y="77.25" fill="#bddaff" rx="22" transform="rotate(-180 92.5 77.25)"/><circle cx="69" cy="55.75" r="15" fill="#4571ab" stroke="#538ad2" stroke-width="3" transform="rotate(-180 69 55.75)"/><path stroke="#776db6" stroke-linecap="round" stroke-linejoin="round" stroke-width="5" d="m74.5 54.25 6 22 5.5-4.5 4.5 4.5 3.5-3.5-4.5-4.5 6-4.5"/><path fill="#fff" d="m95.74 61.12-20.77-9.85a.75.75 0 0 0-1.04.88l6.13 22.53c.14.52.76.73 1.18.4l4.43-3.48a.75.75 0 0 1 1.02.1l3.54 4.03c.28.33.78.34 1.09.04l4.33-4.27c.3-.3.3-.77 0-1.07L91.9 66.8a.75.75 0 0 1 .05-1.11l3.95-3.3a.75.75 0 0 0-.16-1.26"/><path stroke="#40396e" stroke-width="3" d="M74 33.25H37.5c-31 0-32 44 0 44H77l.3.44a4 4 0 0 0 6.15.6l2.05-2.04 2.25 2.25a4 4 0 0 0 5.58.08l3.35-3.17a4 4 0 0 0 .24-5.56l-1.42-1.6 1.98-1.98a4 4 0 0 0-1.13-6.44L93 58.25c1-15-7.5-25-19-25Z"/><defs><filter id="crests-feature-flags-filter0_d_23_15324" width="96.15" height="57.42" x="9.5" y="29.25" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" result="hardAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/><feOffset dx="3" dy="3"/><feComposite in2="hardAlpha" operator="out"/><feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.4 0"/><feBlend in2="BackgroundImageFix" result="effect1_dropShadow_23_15324"/><feBlend in="SourceGraphic" in2="effect1_dropShadow_23_15324" result="shape"/></filter></defs></svg>\ No newline at end of filediff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.pyindex 7fddcd84c513..9d563b2cf36b 100644--- a/posthog/admin/admins/organization_admin.py+++ b/posthog/admin/admins/organization_admin.py@@ -1,5 +1,5 @@import re-from datetime import UTC, timedelta+from datetime import UTCfrom typing import Anyfrom uuid import UUID@@ -25,6 +25,8 @@ from django.views.decorators.http import require_http_methodsfrom posthog.admin.ai_training_opt_in_history import get_ai_training_opt_in_historyfrom posthog.admin.authorization import can_trigger_admin_deletion+from posthog.admin.console.moved import MovedToConsole+from posthog.admin.console.usage_reports_tool import ReportDateFormfrom posthog.admin.inline_registry import extra_inlines_forfrom posthog.admin.inlines.events_retention_config_inline import OrganizationEventsRetentionConfigInlinefrom posthog.admin.inlines.organization_domain_inline import OrganizationDomainInline@@ -128,16 +130,6 @@ def get_model_counts_for_organization(organization: Organization) -> list[dict]:return sorted(results, key=lambda x: x["name"])-class UsageReportForm(forms.Form):- report_date = forms.DateField(widget=forms.DateInput(attrs={"type": "date"}))-- def clean_report_date(self):- report_date = self.cleaned_data["report_date"]- if report_date > (timezone.now().date() + timedelta(days=1)):- raise forms.ValidationError("The date cannot be more than one day in the future.")- return report_date--class DatasetRetentionForm(forms.Form):enabled = forms.TypedChoiceField(label="Dataset cleanup",@@ -381,7 +373,13 @@ class OrganizationAdmin(admin.ModelAdmin):return mark_safe(render_to_string("admin/organization/limited_products.html",- {"limited": limited, "organization_id": organization.id, "total_teams": total_teams},+ {+ "limited": limited,+ "total_teams": total_teams,+ "actions_moved": MovedToConsole.action(+ "organization", organization, "billing", "Limit and unlimit"+ ),+ },request=request,))@@ -462,15 +460,7 @@ class OrganizationAdmin(admin.ModelAdmin):def sync_to_billing_display(self, organization: Organization):if not organization.pk:return "-"- request = getattr(self, "_current_request", None)- # nosemgrep: python.django.security.audit.avoid-mark-safe.avoid-mark-safe (admin-only, renders trusted template)- return mark_safe(- render_to_string(- "admin/organization/sync_to_billing.html",- {"organization_id": organization.pk},- request=request,- )- )+ return MovedToConsole.action("organization", organization, "billing", "Sync members to billing")@admin.display(description="Danger zone")def trigger_deletion_display(self, organization: Organization):@@ -570,71 +560,9 @@ class OrganizationAdmin(admin.ModelAdmin):)return redirect(change_url)- def sync_to_billing_view(self, request, organization_id):- from posthog.tasks.sync_billing import sync_members_to_billing-- try:- organization = Organization.objects.get(id=organization_id)- except Organization.DoesNotExist:- messages.error(request, f"Organization with id {organization_id} not found.")- return redirect(reverse("admin:posthog_organization_changelist"))-- if request.method == "POST":- try:- sync_members_to_billing.delay(organization.id)- messages.success(- request, f"Queued sync to billing for organization {organization.name} ({organization.id})."- )- except Exception as e:- messages.error(request, f"Error queuing sync to billing: {e}")-- return redirect(reverse("admin:posthog_organization_change", args=[organization_id]))-- def limit_product_view(self, request, organization_id):- from ee.billing.quota_limiting import QuotaResource-- organization: Organization = Organization.objects.get(id=organization_id)- assert organization-- if request.method == "POST":- resource_name = request.POST.get("resource")- try:- resource = QuotaResource(resource_name)- organization.limit_product_until_end_of_billing_cycle(resource)- messages.success(request, f"Successfully limited {resource_name} for organization {organization.name}")- except ValueError:- messages.error(request, f"Invalid resource: {resource_name}")- except Exception as e:- messages.error(request, f"Error limiting {resource_name}: {str(e)}")-- return redirect(reverse("admin:posthog_organization_change", args=[organization_id]))-- def unlimit_product_view(self, request, organization_id):- from ee.billing.quota_limiting import QuotaResource-- organization = Organization.objects.get(id=organization_id)-- if request.method == "POST":- resource_name = request.POST.get("resource")- try:- resource = QuotaResource(resource_name)- organization.unlimit_product(resource)- messages.success(- request, f"Successfully unlimited {resource_name} for organization {organization.name}"- )- except ValueError:- messages.error(request, f"Invalid resource: {resource_name}")- except Exception as e:- messages.error(request, f"Error unlimiting {resource_name}: {str(e)}")-- return redirect(reverse("admin:posthog_organization_change", args=[organization_id]))-def get_urls(self):urls = super().get_urls()custom_urls = [- path(- "send-usage-report/", self.admin_site.admin_view(self.send_usage_report_view), name="send-usage-report"- ),path("send-ai-observability-usage-report/",self.admin_site.admin_view(self.send_ai_observability_usage_report_view),@@ -650,26 +578,11 @@ class OrganizationAdmin(admin.ModelAdmin):self.admin_site.admin_view(self.bulk_deactivate_view),name="organization_bulk_deactivate",),- path(- "<path:organization_id>/limit-product/",- self.admin_site.admin_view(self.limit_product_view),- name="limit_product",- ),- path(- "<path:organization_id>/unlimit-product/",- self.admin_site.admin_view(self.unlimit_product_view),- name="unlimit_product",- ),path("<path:organization_id>/model-counts/",self.admin_site.admin_view(self.model_counts_view),name="organization_model_counts",),- path(- "<path:organization_id>/sync-to-billing/",- self.admin_site.admin_view(self.sync_to_billing_view),- name="organization_sync_to_billing",- ),path("<path:organization_id>/trigger-deletion/",self.admin_site.admin_view(self.trigger_deletion_view),@@ -799,28 +712,11 @@ class OrganizationAdmin(admin.ModelAdmin):},)- def send_usage_report_view(self, request):- if not request.user.groups.filter(name="Billing Team").exists():- messages.error(request, "You are not authorized to send usage reports.")- return redirect(reverse("admin:posthog_organization_changelist"))-- if request.method == "POST":- form = UsageReportForm(request.POST)- if form.is_valid():- report_date = form.cleaned_data["report_date"]- call_command("send_usage_report", f"--date={report_date.strftime('%Y-%m-%d')}", "--async=1")- messages.success(request, f"Usage report for date {report_date} was sent successfully.")- return redirect(reverse("admin:posthog_organization_changelist"))- else:- form = UsageReportForm()-- return render(request, "admin/posthog/organization/send_usage_report.html", {"form": form})-def send_ai_observability_usage_report_view(self, request):# Staff-only on purpose, unlike the sibling billing view: nothing here is customer-facing, and# the task now skips organizations that already have a report for the period.if request.method == "POST":- form = UsageReportForm(request.POST)+ form = ReportDateForm(request.POST)if form.is_valid():report_date = form.cleaned_data["report_date"]try:@@ -835,7 +731,7 @@ class OrganizationAdmin(admin.ModelAdmin):messages.success(request, f"AI observability usage report for date {report_date} was queued.")return redirect(reverse("admin:posthog_organization_changelist"))else:- form = UsageReportForm()+ form = ReportDateForm()return render(request,diff --git a/posthog/admin/admins/resave_cohorts_admin.py b/posthog/admin/admins/resave_cohorts_admin.pydeleted file mode 100644index 6eb80686873b..000000000000--- a/posthog/admin/admins/resave_cohorts_admin.py+++ /dev/null@@ -1,66 +0,0 @@-from django import forms-from django.contrib import admin, messages-from django.core.exceptions import PermissionDenied-from django.core.management import call_command-from django.shortcuts import redirect, render--from posthog.management.commands.resave_cohorts import IncompleteResaveError---class ResaveCohortsForm(forms.Form):- team_id = forms.IntegerField(required=False, help_text="Only process cohorts for this team id (optional)")- batch_size = forms.IntegerField(initial=500, min_value=1, max_value=5000, help_text="Cohorts per batch")- dry_run = forms.BooleanField(initial=True, required=False, help_text="Do not save, only report summary")---def resave_cohorts_view(request):- """- Admin view to trigger cohort re-save to regenerate compiled bytecode and cohort_type.- Delegates to the `resave_cohorts` management command.- """- if not request.user.is_staff:- raise PermissionDenied-- if request.method == "POST":- form = ResaveCohortsForm(request.POST)- if form.is_valid():- command_kwargs = {- "batch_size": form.cleaned_data["batch_size"],- "dry_run": form.cleaned_data["dry_run"],- }- team_id = form.cleaned_data.get("team_id")- if team_id is not None:- # Presence, not truthiness: team 0 has to reach the command, which rejects it. Reading- # it as "no team given" would silently widen the run to every team.- # `call_command` skips argparse coercion for keyword options, so the list the- # `--team-id` flag builds has to be passed already built.- command_kwargs["team_id"] = [team_id]-- try:- call_command("resave_cohorts", **command_kwargs)- scope = f"team {team_id}" if team_id is not None else "all teams"- mode = "dry-run" if form.cleaned_data["dry_run"] else "apply"- messages.success(- request,- f"Cohort re-save started ({mode}) for {scope} with batch_size={form.cleaned_data['batch_size']}.",- )- except IncompleteResaveError as e:- # The run finished and persisted its saves, so this is not a failure to start.- messages.warning(request, f"Cohort re-save finished with problems: {str(e)}")- except Exception as e:- messages.error(request, f"Failed to start cohort re-save: {str(e)}")-- return redirect("resave-cohorts")- else:- form = ResaveCohortsForm()-- context = {- "form": form,- "title": "Resave Cohorts (Regenerate Bytecode & Type)",- "has_view_permission": True,- "site_title": admin.site.site_title,- "site_header": admin.site.site_header,- "site_url": admin.site.site_url,- "has_permission": True,- }- return render(request, "admin/resave_cohorts.html", context)diff --git a/posthog/admin/console/AGENTS.md b/posthog/admin/console/AGENTS.mdindex c20abc428d0e..71925b4d8a53 100644--- a/posthog/admin/console/AGENTS.md+++ b/posthog/admin/console/AGENTS.md@@ -13,11 +13,12 @@ Before you add or change a panel, operation or tool, invoke `/extending-the-admi- **A panel returns data, not markup.** Subclass `Panel` and return `Fact` and `Operation` objects. Do not write templates, `format_html`, or `mark_safe` for a panel. The shell renders every panel the same way, so a new panel cannot drift from the design.- **Only the shell writes templates** (`posthog/templates/admin_console/`). They use quill's `quill-*` classes and Tailwind utilities, with the markup quill's React components emit, including their `data-*` attributes.- **A destructive operation sets `danger=True`, has a form with a `reason` field, and sets `undo_hint`.** `Operation` refuses it otherwise. The console writes the reason to the audit log and shows the undo hint on the confirm page.+- **An operation that only some staff may run sets `gate`.** Use `Gate.group(name)` or a `Gate` with a reviewed rule. Never gate on a Django model permission: `User.is_superuser` mirrors `is_staff`, so every staff member passes. The console shows a gated operation disabled with who may run it, and refuses the request with 403.- **The contract checks itself.** The registry refuses a key that is not a slug, a blank title and a tool group outside `TOOL_GROUPS`. `Fact` refuses markup, and `Page` refuses unknown blocks and table rows of the wrong width. When a check fires, fix the contribution. Do not loosen the check in the same change.## Add a panel-1. In `products/<product>/backend/console.py`, subclass `Panel` and decorate it with `@console.register_panel`. Import only your product's `facade/`, `posthog.admin.console`, and, for a bridge, the `ModelAdmin` that still holds the view. `products/workflows/backend/console.py` is the reference.+1. In `products/<product>/backend/console.py`, subclass `Panel` and decorate it with `@console.register_panel`. Set `record` to a key from `RECORD_TYPES` in `records.py` (`team` or `organization`). Import only your product's `facade/`, `posthog.admin.console`, and, for a bridge, the `ModelAdmin` that still holds the view. `products/workflows/backend/console.py` is the reference.2. Set `owner = Owner(name=..., crest=...)`. The crest is a mini crest slug from `@posthog/brand`, for example `workflows`.3. For each action, return an `Operation`. Put its inputs in a Django `forms.Form` (`form_class`); the console renders and validates it. Its `handler(request, obj, form)` returns `None` when done. The handler is a service function, or `AdminViewBridge(Model, SomeAdmin.view_method)` while the logic still lives in a `ModelAdmin`. A bridged view must take a POST and answer with a redirect. Later, replace the bridge with a service function; the panel stays as it is.4. Run `pnpm --filter=@posthog/frontend build:admin-console` when you add an owner crest or change a template. `posthog/admin/test_admin_console.py` fails when a template class, a linked asset or an owner crest is missing from the build output.@@ -27,13 +28,14 @@ Before you add or change a panel, operation or tool, invoke `/extending-the-admiA tool is a page that is not about one record, for example a report across all teams.1. In `products/<product>/backend/console.py`, subclass `ConsoleTool` and decorate it with `@console.register_tool`. Set `key`, `title`, `owner` and `group`; the group is the navigation heading. `posthog/admin/console/events_retention_tool.py` is the reference.-2. `page(request)` returns a `Page` of blocks (`Notice`, `Table` with `Row` and `GroupRow`, `Paging`). The console renders the blocks, so a tool needs no template. When a tool needs a block that does not exist, add it to `tools.py` and `tool.html` in the shell, not a template in the product.-3. When a tool replaces a Django admin page, keep the old URL name and point it at `MovedToConsole.page_redirect`, so existing links keep working.+2. `page(request)` returns a `Page` of blocks (`Notice`, `Table` with `Row` and `GroupRow`, `Paging`, `Output`). It only reads; the console serves it for GET and HEAD only. The console renders the blocks, so a tool needs no template. When a tool needs a block that does not exist, add it to `tools.py` and `tool.html` in the shell, not a template in the product.+3. For an action that is not about one record, return a `ToolOperation` from `operations(request)`. It works like a record `Operation` without the record: `handler(request, form)`. Its handler returns `None` (back to the tool with its messages), or a `Page` that the console shows as the result. Return a result `Page` only when running the operation again is harmless, such as a dry run, because a reload submits the form again. `products/cohorts/backend/console.py` is the reference.+4. When a tool replaces a Django admin page, keep the old URL name and point it at `MovedToConsole.page_redirect`, so existing links keep working.## Move a Django admin action-Replace the old button with `MovedToConsole.team_action(team, panel_key, label)` from `moved.py`. It links to the panel on the console team page, so staff who look in the usual place find the new one. When a whole page moves, route its old URL to `MovedToConsole.page_redirect(title, url)`, which tells staff the page moved.-Old URLs never break, because staff keep bookmarks to them, query parameters included. When a team action's view is deleted, its old path goes into `MOVED_TEAM_ACTIONS` in `urls.py`, which redirects to the console form or panel.+Replace the old button with `MovedToConsole.action(record, obj, panel_key, label)` from `moved.py`. It links to the panel on the console record page, so staff who look in the usual place find the new one. When a whole page moves, route its old URL to `MovedToConsole.page_redirect(title, url)`, which tells staff the page moved.+Old URLs never break, because staff keep bookmarks to them, query parameters included. When a record action's view is deleted, its old path goes into `MOVED_TEAM_ACTIONS` or `MOVED_ORGANIZATION_ACTIONS` in `urls.py`, which redirects to the console form or panel.## Read when neededdiff --git a/posthog/admin/console/events_retention_tool.py b/posthog/admin/console/events_retention_tool.pyindex 12bfd35baf60..710b620741eb 100644--- a/posthog/admin/console/events_retention_tool.py+++ b/posthog/admin/console/events_retention_tool.py@@ -52,7 +52,7 @@ def _team_row(retention: ConfiguredEventsRetention, now: datetime) -> Row:cells = (Cell(text=f"{retention.team_name} ({retention.team_id})",- href=reverse("admin_console_team", kwargs={"team_id": retention.team_id}),+ href=reverse("admin_console_team", kwargs={"pk": retention.team_id}),),Cell(text=f"{retention.billing_months} months"),_months(retention.team_months),diff --git a/posthog/admin/console/moved.py b/posthog/admin/console/moved.pyindex 7c0ab2a50892..bb739d8824cb 100644--- a/posthog/admin/console/moved.py+++ b/posthog/admin/console/moved.py@@ -1,6 +1,7 @@from collections.abc import Callable-from django.contrib import messages+from django.contrib import admin, messages+from django.db.models import Modelfrom django.http import HttpRequest, HttpResponse, HttpResponseRedirectfrom django.urls import reversefrom django.utils.html import format_html@@ -24,18 +25,22 @@ class MovedToConsole:query = request.META.get("QUERY_STRING", "")return HttpResponseRedirect(url + (f"?{query}" if query else ""))- return view+ # Like every console route, an old URL answers only to signed-in staff.+ return admin.site.admin_view(view)@staticmethod- def team_redirect(target: str) -> Callable[[HttpRequest, int], HttpResponse]:- """A view for the old URL of a team action that moved. `target` is relative to the console team page."""+ def record_redirect(plural: str, target: str) -> Callable[..., HttpResponse]:+ """A view for the old URL of a record action that moved. `target` is relative to the console record page.++ The old URL pattern names its primary key `pk`, for example `admin/posthog/team/<int:pk>/rebuild-cache/`.+ """- def view(request: HttpRequest, team_id: int) -> HttpResponse:+ def view(request: HttpRequest, pk: object) -> HttpResponse:messages.info(request, "This action moved to PostHog Admin. Update your bookmark to this page.")page, _, anchor = target.partition("#")query = request.META.get("QUERY_STRING", "")return HttpResponseRedirect(- f"/admin/console/teams/{team_id}/{page}"+ f"/admin/console/{plural}/{pk}/{page}"+ (f"?{query}" if query else "")+ (f"#{anchor}" if anchor else ""))@@ -43,11 +48,15 @@ class MovedToConsole:return view@staticmethod- def team_action(team: Team, panel_key: str, action: str) -> SafeString:- url = reverse("admin_console_team", kwargs={"team_id": team.pk})+ def action(record: str, obj: Model, panel_key: str, action: str) -> SafeString:+ url = reverse(f"admin_console_{record}", kwargs={"pk": obj.pk})return format_html('<a href="{}#panel-{}">{}: now in PostHog Admin ↗</a>',url,panel_key,action,)++ @classmethod+ def team_action(cls, team: Team, panel_key: str, action: str) -> SafeString:+ return cls.action("team", team, panel_key, action)diff --git a/posthog/admin/console/organization_panels.py b/posthog/admin/console/organization_panels.pynew file mode 100644index 000000000000..68bfaceccdf4--- /dev/null+++ b/posthog/admin/console/organization_panels.py@@ -0,0 +1,177 @@+from datetime import UTC, datetime++from django import forms+from django.contrib import messages+from django.db.models import Model+from django.http import HttpRequest, HttpResponse++import structlog++from posthog.admin.console.panels import MAX_FACTS_PER_PANEL, Fact, Operation, Owner, Panel, Tone+from posthog.admin.console.records import RECORD_TYPES+from posthog.admin.console.registry import console+from posthog.admin.console.team_panels import DEV_EXPERIENCE+from posthog.models.organization import Organization++from ee.billing.quota_limiting import QuotaResource++logger = structlog.get_logger(__name__)++BILLING = Owner(name="Billing", crest="billing")++[email protected]_panel+class OrganizationOverviewPanel(Panel):+ record = "organization"+ key = "overview"+ title = "Overview"+ owner = DEV_EXPERIENCE++ def facts(self, obj: Model) -> list[Fact]:+ assert isinstance(obj, Organization)+ if obj.is_active is False:+ status = Fact(+ label="Status", value=f"Deactivated: {obj.is_not_active_reason or 'no reason'}", tone=Tone.DESTRUCTIVE+ )+ else:+ status = Fact(label="Status", value="Active", tone=Tone.SUCCESS)+ facts = [+ status,+ Fact(label="Members", value=str(obj.members.count())),+ Fact(label="Created", value=obj.created_at.strftime("%b %-d, %Y")),+ ]+ if obj.is_pending_deletion:+ facts.append(Fact(label="Deletion", value="Pending", tone=Tone.WARNING))+ return facts++[email protected]_panel+class OrganizationTeamsPanel(Panel):+ record = "organization"+ key = "teams"+ title = "Teams"+ owner = DEV_EXPERIENCE++ def facts(self, obj: Model) -> list[Fact]:+ assert isinstance(obj, Organization)+ team_record = RECORD_TYPES["team"]+ teams = list(obj.teams.order_by("id").only("id", "name")[: MAX_FACTS_PER_PANEL + 1])+ if not teams:+ return [Fact(label="Teams", value="This organization has no teams.")]+ shown = teams if len(teams) <= MAX_FACTS_PER_PANEL else teams[: MAX_FACTS_PER_PANEL - 1]+ facts = [+ Fact(label=team.name, value=f"Team {team.pk}", mono=True, href=team_record.url(team)) for team in shown+ ]+ if len(shown) < len(teams):+ hidden = obj.teams.count() - len(shown)+ facts.append(Fact(label="More", value=f"{hidden} more teams. Look up the organization name to see all."))+ return facts+++class QuotaLimits:+ """Which products are quota limited right now, read from the limiter cache that ingestion checks."""++ @staticmethod+ def limited(organization: Organization) -> dict[QuotaResource, int | None]:+ limited: dict[QuotaResource, int | None] = {}+ for resource_value, info in organization.get_limited_products().items():+ if info["is_limited_in_redis"]:+ limited[QuotaResource(resource_value)] = info["redis_quota_limited_until"]+ return limited+++_RESOURCE_CHOICES = [(resource.value, resource.value) for resource in QuotaResource]+++class LimitProductForm(forms.Form):+ resource = forms.ChoiceField(label="Product", choices=_RESOURCE_CHOICES)+ reason = forms.CharField(widget=forms.Textarea(attrs={"rows": 3}), help_text="Goes into the audit log.")+++class UnlimitProductForm(forms.Form):+ resource = forms.ChoiceField(label="Product", choices=_RESOURCE_CHOICES)+++def limit_product(request: HttpRequest, obj: Model, form: forms.Form | None) -> HttpResponse | None:+ assert isinstance(obj, Organization) and form is not None+ resource = QuotaResource(form.cleaned_data["resource"])+ try:+ obj.limit_product_until_end_of_billing_cycle(resource)+ except RuntimeError as error:+ messages.error(request, f"Could not limit {resource.value}: {error}.")+ return HttpResponse(status=400)+ messages.success(request, f"Limited {resource.value} for '{obj.name}' until the end of the billing period.")+ return None+++def unlimit_product(request: HttpRequest, obj: Model, form: forms.Form | None) -> HttpResponse | None:+ assert isinstance(obj, Organization) and form is not None+ resource = QuotaResource(form.cleaned_data["resource"])+ obj.unlimit_product(resource)+ messages.success(request, f"Removed the {resource.value} limit for '{obj.name}'.")+ return None+++def sync_members_to_billing(request: HttpRequest, obj: Model, form: forms.Form | None) -> HttpResponse | None:+ from posthog.tasks.sync_billing import sync_members_to_billing as sync_task # noqa: PLC0415 — Celery task module++ assert isinstance(obj, Organization)+ sync_task.delay(obj.id)+ messages.success(request, f"Queued a member sync to billing for '{obj.name}'.")+ return None++[email protected]_panel+class BillingPanel(Panel):+ record = "organization"+ key = "billing"+ title = "Billing"+ owner = BILLING++ def facts(self, obj: Model) -> list[Fact]:+ assert isinstance(obj, Organization)+ limited = QuotaLimits.limited(obj)+ if not limited:+ return [Fact(label="Limited products", value="None", tone=Tone.SUCCESS)]+ ordered = sorted(limited.items(), key=lambda item: item[0].value)+ # Past the panel's fact limit, the last fact counts the rest, so a long list never looks complete when it is not.+ shown = ordered if len(ordered) <= MAX_FACTS_PER_PANEL else ordered[: MAX_FACTS_PER_PANEL - 1]+ facts = []+ for resource, until in shown:+ when = datetime.fromtimestamp(until, tz=UTC).strftime("%b %-d, %Y") if until else "no end date"+ facts.append(Fact(label=resource.value, value=f"Limited until {when}", tone=Tone.WARNING))+ if len(shown) < len(ordered):+ facts.append(+ Fact(+ label="More limits",+ value=f"{len(ordered) - len(shown)} more products are limited. The raw record in Django admin lists every one.",+ tone=Tone.WARNING,+ )+ )+ return facts++ def operations(self, obj: Model) -> list[Operation]:+ return [+ Operation(+ key="limit",+ label="Limit a product",+ handler=limit_product,+ danger=True,+ description="Drops the product's new data for every team in the organization until the billing period ends.",+ form_class=LimitProductForm,+ undo_hint="To undo, use Remove a limit in the Billing panel.",+ ),+ Operation(+ key="unlimit",+ label="Remove a limit",+ handler=unlimit_product,+ description="Lets the product's data in again for every team in the organization.",+ form_class=UnlimitProductForm,+ ),+ Operation(+ key="sync-members",+ label="Sync members to billing",+ handler=sync_members_to_billing,+ description="Sends the current member list to the billing service.",+ ),+ ]diff --git a/posthog/admin/console/panels.py b/posthog/admin/console/panels.pyindex bedd257efc48..45ea816413b8 100644--- a/posthog/admin/console/panels.py+++ b/posthog/admin/console/panels.py@@ -1,3 +1,4 @@+from collections.abc import Callablefrom enum import StrEnumfrom typing import TYPE_CHECKING, ClassVar, Protocol@@ -36,11 +37,47 @@ class Fact:value: strtone: Tone | None = Nonemono: bool = False+ # A console page the value links to, for example the team page of a team the fact names.+ href: str | None = Nonedef __post_init__(self) -> None:# The shell escapes facts. Markup from format_html or mark_safe would bypass the shared design.if isinstance(self.label, SafeData) or isinstance(self.value, SafeData):raise ValueError(f"Fact {self.label!r} must be plain text, not markup")+ # Facts link within PostHog only, so a value that came from customer data cannot become an outside link.+ # Browsers read a leading "/\\" like "//", so both would leave the site.+ if self.href is not None and (not self.href.startswith("/") or self.href.startswith(("//", "/\\"))):+ raise ValueError(f"Fact {self.label!r} links to {self.href!r}. Link to a PostHog path that starts with /.")+++@frozen+class Gate:+ """Who may run an operation, on top of the staff check that every console page has.++ Use a Django group or a reviewed rule. Not a Django model permission: `User.is_superuser` mirrors+ `is_staff` in PostHog, so every staff member has every permission and such a gate would let everyone in.+ """++ # Who passes, shown next to the disabled button so staff know whom to ask, for example "the Billing Team group".+ label: str+ check: Callable[["HttpRequest"], bool]++ @staticmethod+ def group(name: str) -> "Gate":+ return Gate(label=f"the {name} group", check=lambda request: request.user.groups.filter(name=name).exists())++ def allows(self, request: "HttpRequest") -> bool:+ return self.check(request)+++def check_danger(key: str, danger: bool, form_class: type[forms.Form] | None, undo_hint: str) -> None:+ # The console writes the reason to the audit log, so nobody runs a destructive action without saying why.+ if danger and (form_class is None or "reason" not in form_class.base_fields):+ raise ValueError(f"Danger operation {key!r} needs a form with a reason field")+ if danger and not undo_hint.strip():+ raise ValueError(+ f"Danger operation {key!r} needs an undo_hint that says how to undo it, or that it cannot be undone"+ )class OperationHandler(Protocol):@@ -65,15 +102,10 @@ class Operation:form_initial: dict[str, object] | None = Nonedescription: str = ""undo_hint: str = ""+ gate: Gate | None = Nonedef __post_init__(self) -> None:- # The console writes the reason to the audit log, so nobody runs a destructive action without saying why.- if self.danger and (self.form_class is None or "reason" not in self.form_class.base_fields):- raise ValueError(f"Danger operation {self.key!r} needs a form with a reason field")- if self.danger and not self.undo_hint.strip():- raise ValueError(- f"Danger operation {self.key!r} needs an undo_hint that says how to undo it, or that it cannot be undone"- )+ check_danger(self.key, self.danger, self.form_class, self.undo_hint)class ReasonForm(forms.Form):diff --git a/posthog/admin/console/records.py b/posthog/admin/console/records.pynew file mode 100644index 000000000000..a7b2b970604c--- /dev/null+++ b/posthog/admin/console/records.py@@ -0,0 +1,116 @@+from typing import ClassVar++from django.db.models import Model, QuerySet+from django.urls import reverse++from posthog.dataclasses import frozen+from posthog.models.organization import Organization+from posthog.models.team.team import Team+++@frozen+class RecordLink:+ label: str+ href: str+ title: str = ""+++class RecordType:+ """A kind of record the console has pages for, for example a team.++ The shell owns the record types. A panel names one by `key`, and the console builds the record's page,+ its operation pages and their URLs from it.+ """++ key: ClassVar[str]+ # The URL segment, for example "teams" in /admin/console/teams/7/.+ plural: ClassVar[str]+ label: ClassVar[str]+ # A Django path converter for the primary key, so a malformed key is a 404 before any query runs.+ pk_converter: ClassVar[str]++ def queryset(self) -> QuerySet:+ raise NotImplementedError++ def title(self, obj: Model) -> str:+ raise NotImplementedError++ def subtitle(self, obj: Model) -> str:+ return ""++ def parents(self, obj: Model) -> list[RecordLink]:+ """The records above this one, for the breadcrumb. A team sits under its organization."""+ return []++ def links(self, obj: Model) -> list[RecordLink]:+ """Buttons in the page header that leave the console, for example to the raw row in Django admin."""+ return []++ @property+ def url_name(self) -> str:+ return f"admin_console_{self.key}"++ @property+ def operation_url_name(self) -> str:+ return f"admin_console_{self.key}_operation"++ def url(self, obj: Model) -> str:+ return reverse(self.url_name, kwargs={"pk": obj.pk})+++class TeamRecord(RecordType):+ key = "team"+ plural = "teams"+ label = "Team"+ pk_converter = "int"++ def queryset(self) -> QuerySet:+ return Team.objects.select_related("organization")++ def title(self, obj: Model) -> str:+ assert isinstance(obj, Team)+ return obj.name++ def subtitle(self, obj: Model) -> str:+ assert isinstance(obj, Team)+ return obj.organization.name++ def parents(self, obj: Model) -> list[RecordLink]:+ assert isinstance(obj, Team)+ return [RecordLink(label=obj.organization.name, href=RECORD_TYPES["organization"].url(obj.organization))]++ def links(self, obj: Model) -> list[RecordLink]:+ return [+ RecordLink(+ label="Raw record in Django admin",+ href=reverse("admin:posthog_team_change", args=[obj.pk]),+ title="The raw Team row, with every field",+ ),+ RecordLink(label="Open in app ↗", href=f"/project/{obj.pk}"),+ ]+++class OrganizationRecord(RecordType):+ key = "organization"+ plural = "organizations"+ label = "Organization"+ pk_converter = "uuid"++ def queryset(self) -> QuerySet:+ return Organization.objects.all()++ def title(self, obj: Model) -> str:+ assert isinstance(obj, Organization)+ return obj.name++ def links(self, obj: Model) -> list[RecordLink]:+ return [+ RecordLink(+ label="Raw record in Django admin",+ href=reverse("admin:posthog_organization_change", args=[obj.pk]),+ title="The raw Organization row, with every field",+ ),+ ]+++RECORD_TYPES: dict[str, RecordType] = {record.key: record for record in (TeamRecord(), OrganizationRecord())}diff --git a/posthog/admin/console/registry.py b/posthog/admin/console/registry.pyindex 58407f8fcfcd..cef3f423027b 100644--- a/posthog/admin/console/registry.py+++ b/posthog/admin/console/registry.py@@ -3,11 +3,11 @@ import refrom django.utils.module_loading import autodiscover_modulesfrom posthog.admin.console.panels import Panel+from posthog.admin.console.records import RECORD_TYPESfrom posthog.admin.console.tools import ConsoleTool-RECORD_TYPES = frozenset({"team"})# Navigation headings. Add one here, in the shell, only when no existing group fits a new tool.-TOOL_GROUPS = frozenset({"Data"})+TOOL_GROUPS = frozenset({"Data", "Billing"})KEY_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")@@ -72,6 +72,8 @@ class ConsoleRegistry:return# Core panels register first, so they lead each page.import posthog.admin.console.team_panels # noqa: F401, PLC0415 — registers the core Team panels+ import posthog.admin.console.usage_reports_tool # noqa: F401, PLC0415 — registers a core tool+ import posthog.admin.console.organization_panels # noqa: F401, PLC0415 — registers the core Organization panelsimport posthog.admin.console.events_retention_tool # noqa: F401, PLC0415 — registers a core toolautodiscover_modules("console")diff --git a/posthog/admin/console/tools.py b/posthog/admin/console/tools.pyindex ebd71a454b4a..bfee891456b6 100644--- a/posthog/admin/console/tools.py+++ b/posthog/admin/console/tools.py@@ -1,10 +1,12 @@-from typing import TYPE_CHECKING, ClassVar+from typing import TYPE_CHECKING, ClassVar, Protocol-from posthog.admin.console.panels import Owner, Tone+from django import forms++from posthog.admin.console.panels import Gate, Owner, Tone, check_dangerfrom posthog.dataclasses import frozenif TYPE_CHECKING:- from django.http import HttpRequest+ from django.http import HttpRequest, HttpResponse@frozen@@ -44,6 +46,14 @@ class Notice:text: str+@frozen+class Output:+ """Plain text output, for example what a management command printed. The shell shows it as written."""++ kind: ClassVar[str] = "output"+ text: str++@frozenclass Paging:kind: ClassVar[str] = "paging"@@ -54,7 +64,7 @@ class Paging:next_url: str | None-Block = Notice | Table | Paging+Block = Notice | Table | Paging | Output@frozen@@ -64,7 +74,7 @@ class Page:def __post_init__(self) -> None:# tool.html renders only the block kinds it knows, so an unknown block would vanish without an error.for block in self.blocks:- if not isinstance(block, Notice | Table | Paging):+ if not isinstance(block, Notice | Table | Paging | Output):raise ValueError(f"{type(block).__name__} is not a console block. Add new blocks to the shell.")if isinstance(block, Table):for row in block.rows:@@ -72,10 +82,40 @@ class Page:raise ValueError(f"A table row has {len(row.cells)} cells for {len(block.columns)} columns")+class ToolOperationHandler(Protocol):+ """Returns None when done, and the console sends staff back to the tool with the messages the handler added.++ It may return a `Page` instead, which the console shows as the result. Do that only when running the+ operation again is harmless, for example a dry run, because reloading a result page submits the form again.+ To report a failure, add an error message and return a 4xx or 5xx response.+ """++ def __call__(self, request: "HttpRequest", form: forms.Form | None) -> "HttpResponse | Page | None": ...+++@frozen+class ToolOperation:+ """An action a tool offers, for example starting a backfill. Like a record `Operation`, without a record."""++ key: str+ label: str+ handler: ToolOperationHandler+ danger: bool = False+ form_class: type[forms.Form] | None = None+ form_initial: dict[str, object] | None = None+ description: str = ""+ undo_hint: str = ""+ gate: Gate | None = None++ def __post_init__(self) -> None:+ check_danger(self.key, self.danger, self.form_class, self.undo_hint)++class ConsoleTool:"""A console page that is not about one record, for example a report across all teams.- A tool returns a `Page` of blocks. The console renders it, so tools need no templates.+ A tool returns a `Page` of blocks and, optionally, operations. The console renders both, so tools need no+ templates.Subclass it in `<app>/console.py` and register it with `console.register_tool`.Read posthog/admin/console/AGENTS.md before you add one."""@@ -88,3 +128,7 @@ class ConsoleTool:def page(self, request: "HttpRequest") -> Page:raise NotImplementedError++ def operations(self, request: "HttpRequest") -> list[ToolOperation]:+ """The actions the tool page offers. The console runs them; `page` stays read-only."""+ return []diff --git a/posthog/admin/console/urls.py b/posthog/admin/console/urls.pyindex 1fad0aece41b..83556e7e24c1 100644--- a/posthog/admin/console/urls.py+++ b/posthog/admin/console/urls.py@@ -3,6 +3,7 @@ from django.urls import path, re_pathfrom posthog.admin.console import viewsfrom posthog.admin.console.moved import MovedToConsole+from posthog.admin.console.records import RECORD_TYPES# Old Django admin URLs of team actions that moved. Staff keep bookmarks to them, query parameters included.MOVED_TEAM_ACTIONS = {@@ -16,32 +17,62 @@ MOVED_TEAM_ACTIONS = {"recompute-email-sending-tier": "#panel-email-sending",}+MOVED_ORGANIZATION_ACTIONS = {+ "limit-product": "#panel-billing",+ "unlimit-product": "#panel-billing",+ "sync-to-billing": "#panel-billing",+}+# Every route sits under /admin/, so AdminOAuth2Middleware adds its Google step-up, and admin_view# adds the staff check, the login redirect and CSRF protection. The console needs no auth of its own.urlpatterns = [path("admin/console/", admin.site.admin_view(views.console_home), name="admin_console_home"),- path(- "admin/console/teams/<int:team_id>/",- admin.site.admin_view(views.team_detail),- name="admin_console_team",- ),- path(- "admin/console/teams/<int:team_id>/<slug:panel_key>/<slug:operation_key>/",- admin.site.admin_view(views.run_team_operation),- name="admin_console_team_operation",- ),+ *[+ route+ for record_type in RECORD_TYPES.values()+ for route in (+ path(+ f"admin/console/{record_type.plural}/<{record_type.pk_converter}:pk>/",+ admin.site.admin_view(views.record_detail),+ {"record": record_type.key},+ name=record_type.url_name,+ ),+ path(+ f"admin/console/{record_type.plural}/<{record_type.pk_converter}:pk>/<slug:panel_key>/<slug:operation_key>/",+ admin.site.admin_view(views.run_operation),+ {"record": record_type.key},+ name=record_type.operation_url_name,+ ),+ )+ ],path("admin/console/tools/<slug:tool_key>/",admin.site.admin_view(views.tool_page),name="admin_console_tool",),+ path(+ "admin/console/tools/<slug:tool_key>/<slug:operation_key>/",+ admin.site.admin_view(views.run_tool_operation),+ name="admin_console_tool_operation",+ ),*[path(- f"admin/posthog/team/<int:team_id>/{old}/",- admin.site.admin_view(MovedToConsole.team_redirect(target)),+ f"admin/posthog/team/<int:pk>/{old}/",+ admin.site.admin_view(MovedToConsole.record_redirect("teams", target)),)for old, target in MOVED_TEAM_ACTIONS.items()],+ *[+ path(+ f"admin/posthog/organization/<uuid:pk>/{old}/",+ admin.site.admin_view(MovedToConsole.record_redirect("organizations", target)),+ )+ for old, target in MOVED_ORGANIZATION_ACTIONS.items()+ ],+ path(+ "admin/posthog/organization/send-usage-report/",+ MovedToConsole.page_redirect("Sending usage reports", "/admin/console/tools/usage-reports/"),+ ),# APPEND_SLASH is off, so a console URL typed without its trailing slash would fall through to the# Django admin catch-all.re_path(diff --git a/posthog/admin/console/usage_reports_tool.py b/posthog/admin/console/usage_reports_tool.pynew file mode 100644index 000000000000..88960b236a58--- /dev/null+++ b/posthog/admin/console/usage_reports_tool.py@@ -0,0 +1,69 @@+from datetime import timedelta++from django import forms+from django.contrib import messages+from django.core.management import call_command+from django.http import HttpRequest, HttpResponse+from django.utils import timezone++from posthog.admin.console.organization_panels import BILLING+from posthog.admin.console.panels import Gate+from posthog.admin.console.registry import console+from posthog.admin.console.tools import ConsoleTool, Notice, Page, ToolOperation++# Usage reports go to the billing service and customers get invoiced on them, so only billing staff send one.+BILLING_TEAM = Gate.group("Billing Team")+++class ReportDateForm(forms.Form):+ report_date = forms.DateField(+ widget=forms.DateInput(attrs={"type": "date"}),+ help_text="The day the report would have run, which reports usage of the day before.",+ )++ def clean_report_date(self):+ report_date = self.cleaned_data["report_date"]+ if report_date > (timezone.now().date() + timedelta(days=1)):+ raise forms.ValidationError("The date cannot be more than one day in the future.")+ return report_date+++def send_usage_report(request: HttpRequest, form: forms.Form | None) -> HttpResponse | Page | None:+ assert form is not None+ report_date = form.cleaned_data["report_date"]+ call_command("send_usage_report", f"--date={report_date.strftime('%Y-%m-%d')}", "--async=1")+ messages.success(request, f"Queued the usage reports for {report_date}.")+ return None++[email protected]_tool+class UsageReportsTool(ConsoleTool):+ key = "usage-reports"+ title = "Usage reports"+ owner = BILLING+ group = "Billing"+ description = "Sends the daily usage reports again for a day they are missing."++ def page(self, request: HttpRequest) -> Page:+ return Page(+ blocks=(+ Notice(+ text=(+ "A report reports usage of the day before its date. If reports are missing for May 11, "+ "send them for May 12. Read more at posthog.com/docs/advanced/usage-reports."+ )+ ),+ )+ )++ def operations(self, request: HttpRequest) -> list[ToolOperation]:+ return [+ ToolOperation(+ key="send",+ label="Send usage report",+ handler=send_usage_report,+ description="Queues the usage reports of every organization for one day.",+ form_class=ReportDateForm,+ gate=BILLING_TEAM,+ )+ ]diff --git a/posthog/admin/console/views.py b/posthog/admin/console/views.pyindex 827a84df4cee..3ec1d31ddba4 100644--- a/posthog/admin/console/views.py+++ b/posthog/admin/console/views.py@@ -1,21 +1,26 @@import uuid+from collections.abc import Callablefrom pathlib import Path-from typing import cast+from typing import TypeVar, cast+from django import formsfrom django.conf import settingsfrom django.contrib import messagesfrom django.contrib.staticfiles import finders-from django.db.models import Q+from django.core.exceptions import PermissionDenied+from django.db.models import Model, Qfrom django.http import Http404, HttpRequest, HttpResponse, HttpResponseNotAllowed, HttpResponseRedirectfrom django.shortcuts import get_object_or_404, redirect, renderfrom django.urls import reverse+from django.views.decorators.http import require_safeimport structlogfrom posthog.admin.console.bridge import QueuedMessagesfrom posthog.admin.console.panels import Fact, Operation, Panel, Tone+from posthog.admin.console.records import RECORD_TYPES, RecordLink, RecordTypefrom posthog.admin.console.registry import console-from posthog.admin.console.tools import ConsoleTool+from posthog.admin.console.tools import ConsoleTool, Page, ToolOperationfrom posthog.dataclasses import frozenfrom posthog.git import get_git_commit_shortfrom posthog.models.team.team import Team@@ -23,15 +28,39 @@ from posthog.models.user import Userlogger = structlog.get_logger(__name__)+R = TypeVar("R")+SEARCH_LIMIT = 25RECENT_TEAMS_LIMIT = 8+@frozen+class RenderedOperation:+ operation: Operation | ToolOperation+ url: str+ # False when the operation's gate keeps this staff member out. The page shows it disabled, with who may run it.+ allowed: bool++@frozenclass RenderedPanel:panel: Panelfacts: list[Fact]- operations: list[Operation]+ operations: list[RenderedOperation]+++@frozen+class OperationTarget:+ """What an operation page acts on: a record, or a tool when the operation is not about one record."""++ kicker: str+ title: str+ badge: str+ subtitle: str+ back_url: str+ breadcrumbs: tuple[RecordLink, ...]+ # The submit button names a record ("Suspend for Acme"), so staff see which one they are about to change.+ is_record: bool@frozen@@ -127,7 +156,7 @@ def console_home(request: HttpRequest) -> HttpResponse:if len(teams) == 1:if not query.isdigit():messages.info(request, f'Opened the only team that matches "{query}".')- return redirect("admin_console_team", team_id=teams[0].pk)+ return redirect("admin_console_team", pk=teams[0].pk)return render(request,"admin_console/home.html",@@ -142,19 +171,54 @@ def console_home(request: HttpRequest) -> HttpResponse:)-def team_detail(request: HttpRequest, team_id: int) -> HttpResponse:- team = get_object_or_404(Team.objects.select_related("organization"), pk=team_id)- RecentTeams.remember(request, team)+def _record_type(record: str) -> RecordType:+ record_type = RECORD_TYPES.get(record)+ if record_type is None:+ raise Http404("Unknown console record type")+ return record_type+++def _record_context(record_type: RecordType, obj: Model) -> dict[str, object]:+ return {+ **ConsoleEnvironment.context(),+ "record_type": record_type,+ "obj": obj,+ "record_title": record_type.title(obj),+ "record_subtitle": record_type.subtitle(obj),+ "record_url": record_type.url(obj),+ "record_parents": record_type.parents(obj),+ }+++def record_detail(request: HttpRequest, record: str, pk: object) -> HttpResponse:+ record_type = _record_type(record)+ obj = get_object_or_404(record_type.queryset(), pk=pk)+ if isinstance(obj, Team):+ RecentTeams.remember(request, obj)panels = [- RenderedPanel(panel=panel, facts=panel.facts(team), operations=panel.operations(team))- for panel in console.panels_for("team")+ RenderedPanel(+ panel=panel,+ facts=panel.facts(obj),+ operations=[+ RenderedOperation(+ operation=operation,+ url=reverse(+ record_type.operation_url_name,+ kwargs={"pk": obj.pk, "panel_key": panel.key, "operation_key": operation.key},+ ),+ allowed=_is_allowed(request, operation),+ )+ for operation in panel.operations(obj)+ ],+ )+ for panel in console.panels_for(record_type.key)]return render(request,- "admin_console/team.html",+ "admin_console/record.html",{- **ConsoleEnvironment.context(),- "team": team,+ **_record_context(record_type, obj),+ "record_links": record_type.links(obj),"attention": [AttentionItem(panel=rendered.panel, fact=fact)for rendered in panels@@ -167,67 +231,109 @@ def team_detail(request: HttpRequest, team_id: int) -> HttpResponse:)-def _is_offered(panel: Panel, team: Team, operation_key: str) -> bool:- return any(operation.key == operation_key for operation in panel.operations(team))+def _is_offered(panel: Panel, obj: Model, operation_key: str) -> bool:+ return any(operation.key == operation_key for operation in panel.operations(obj))-def _find_operation(panel: Panel, team: Team, operation_key: str) -> Operation:+def _find_operation(panel: Panel, obj: Model, operation_key: str) -> Operation:# Look the operation up in what the panel offers now, so a stale form cannot run an operation the# current state no longer allows, for example suspending a team that is already suspended.- for operation in panel.operations(team):+ for operation in panel.operations(obj):if operation.key == operation_key:return operation- raise Http404("This operation is not available for this team right now")+ raise Http404("This operation is not available for this record right now")+++def _is_allowed(request: HttpRequest, operation: Operation | ToolOperation) -> bool:+ return operation.gate is None or operation.gate.allows(request)++def _require_gate(request: HttpRequest, operation: Operation | ToolOperation, audit: structlog.BoundLogger) -> None:+ # The page only disables the button. This check is the one that keeps a hand-built request out.+ if operation.gate is not None and not operation.gate.allows(request):+ audit.warning("admin_console_operation_denied", method=request.method)+ raise PermissionDenied(f"{operation.label} needs {operation.gate.label}")-def run_team_operation(request: HttpRequest, team_id: int, panel_key: str, operation_key: str) -> HttpResponse:- team = get_object_or_404(Team.objects.select_related("organization"), pk=team_id)- panel = console.get_panel("team", panel_key)++def _audited(audit: structlog.BoundLogger, run: Callable[[], R]) -> R:+ audit.info("admin_console_operation_started")+ try:+ result = run()+ except Exception:+ audit.exception("admin_console_operation_crashed")+ raise+ status = result.status_code if isinstance(result, HttpResponse) else None+ audit.info("admin_console_operation_finished", status=status, result_page=isinstance(result, Page))+ return result+++def _operation_context(+ target: OperationTarget, operation: Operation | ToolOperation, form: forms.Form | None, request: HttpRequest+) -> dict[str, object]:+ return {+ **ConsoleEnvironment.context(),+ "target": target,+ "operation": operation,+ "form": form,+ # Handlers that move money or send messages build an idempotency key from it, so a double submit runs once.+ "form_nonce": request.POST.get("form_nonce") or str(uuid.uuid4()),+ }+++def run_operation(request: HttpRequest, record: str, pk: object, panel_key: str, operation_key: str) -> HttpResponse:+ record_type = _record_type(record)+ obj = get_object_or_404(record_type.queryset(), pk=pk)+ panel = console.get_panel(record_type.key, panel_key)if panel is None:raise Http404("Unknown console panel")- operation = _find_operation(panel, team, operation_key)- team_url = reverse("admin_console_team", kwargs={"team_id": team.pk})+ operation = _find_operation(panel, obj, operation_key)+ record_url = record_type.url(obj)if request.method not in ("GET", "POST"):return HttpResponseNotAllowed(["GET", "POST"])+ audit = logger.bind(+ record=record_type.key,+ record_id=str(obj.pk),+ panel=panel.key,+ operation=operation.key,+ triggered_by=cast(User, request.user).email,+ )+ _require_gate(request, operation, audit)if request.method == "GET" and operation.form_class is None:- return redirect(team_url)+ return redirect(record_url)form = Noneif operation.form_class is not None:form = operation.form_class(request.POST if request.method == "POST" else None, initial=operation.form_initial)- context = {- **ConsoleEnvironment.context(),- "team": team,- "panel": panel,- "operation": operation,- "form": form,- # Handlers that move money or send messages build an idempotency key from it, so a double submit runs once.- "form_nonce": request.POST.get("form_nonce") or str(uuid.uuid4()),- }+ title = record_type.title(obj)+ target = OperationTarget(+ kicker="This acts on",+ title=title,+ badge=f"{record_type.label} {obj.pk}",+ subtitle=record_type.subtitle(obj),+ back_url=record_url,+ breadcrumbs=(+ *record_type.parents(obj),+ RecordLink(label=title, href=record_url),+ RecordLink(label=panel.title, href=f"{record_url}#panel-{panel.key}"),+ ),+ is_record=True,+ )+ context = _operation_context(target, operation, form, request)if request.method == "GET":return render(request, "admin_console/operation.html", context)if form is not None and not form.is_valid():return render(request, "admin_console/operation.html", context, status=400)- audit = logger.bind(- record="team",- team_id=team.pk,- panel=panel.key,- operation=operation.key,- reason=form.cleaned_data.get("reason") if form is not None else None,- triggered_by=cast(User, request.user).email,- )- audit.info("admin_console_operation_started")- response = operation.handler(request, team, form)- audit.info("admin_console_operation_finished", status=response.status_code if response is not None else None)+ audit = audit.bind(reason=form.cleaned_data.get("reason") if form is not None else None)+ response = _audited(audit, lambda: operation.handler(request, obj, form))if response is None:- return redirect(team_url)+ return redirect(record_url)if response.status_code >= 400:- team.refresh_from_db()+ obj.refresh_from_db()# A handler can fail after its state change committed, for example when a notification fails.- # The operation is then no longer offered, and staff belong on the team page, not on a dead form.- if form is not None and _is_offered(panel, team, operation.key):+ # The operation is then no longer offered, and staff belong on the record page, not on a dead form.+ if form is not None and _is_offered(panel, obj, operation.key):return render(request, "admin_console/operation.html", context, status=400)if QueuedMessages.error_count(request) == 0:messages.error(@@ -235,22 +341,91 @@ def run_team_operation(request: HttpRequest, team_id: int, panel_key: str, operaf"{operation.label} failed with status {response.status_code}. The page below shows the current "f"state. Try again, or ask the {panel.owner.name} team if it keeps failing.",)- return redirect(team_url)+ return redirect(record_url)return response-def tool_page(request: HttpRequest, tool_key: str) -> HttpResponse:+def _get_tool(tool_key: str) -> ConsoleTool:tool = console.get_tool(tool_key)if tool is None:raise Http404("Unknown console tool")- page = tool.page(request)+ return tool+++def _with_query(url: str, request: HttpRequest) -> str:+ # A tool can have sub-pages picked by query parameters, so its operations and the way back keep them.+ query = request.META.get("QUERY_STRING", "")+ return url + (f"?{query}" if query else "")+++@require_safe+def tool_page(request: HttpRequest, tool_key: str) -> HttpResponse:+ tool = _get_tool(tool_key)+ operations = [+ RenderedOperation(+ operation=operation,+ url=_with_query(+ reverse("admin_console_tool_operation", kwargs={"tool_key": tool.key, "operation_key": operation.key}),+ request,+ ),+ allowed=_is_allowed(request, operation),+ )+ for operation in tool.operations(request)+ ]return render(request,"admin_console/tool.html",- {**ConsoleEnvironment.context(), "tool": tool, "page": page},+ {**ConsoleEnvironment.context(), "tool": tool, "page": tool.page(request), "operations": operations},)+def run_tool_operation(request: HttpRequest, tool_key: str, operation_key: str) -> HttpResponse:+ tool = _get_tool(tool_key)+ operation = next((op for op in tool.operations(request) if op.key == operation_key), None)+ if operation is None:+ raise Http404("This operation is not available right now")+ tool_url = _with_query(reverse("admin_console_tool", kwargs={"tool_key": tool.key}), request)++ if request.method not in ("GET", "POST"):+ return HttpResponseNotAllowed(["GET", "POST"])+ audit = logger.bind(tool=tool.key, operation=operation.key, triggered_by=cast(User, request.user).email)+ _require_gate(request, operation, audit)+ if request.method == "GET" and operation.form_class is None:+ return redirect(tool_url)++ form = None+ if operation.form_class is not None:+ form = operation.form_class(request.POST if request.method == "POST" else None, initial=operation.form_initial)+ target = OperationTarget(+ kicker="This runs from",+ title=tool.title,+ badge=tool.group,+ subtitle=tool.description,+ back_url=tool_url,+ breadcrumbs=(RecordLink(label=tool.title, href=tool_url),),+ is_record=False,+ )+ context = _operation_context(target, operation, form, request)+ if request.method == "GET":+ return render(request, "admin_console/operation.html", context)+ if form is not None and not form.is_valid():+ return render(request, "admin_console/operation.html", context, status=400)++ audit = audit.bind(reason=form.cleaned_data.get("reason") if form is not None else None)+ result = _audited(audit, lambda: operation.handler(request, form))+ if result is None:+ return redirect(tool_url)+ if isinstance(result, Page):+ return render(request, "admin_console/result.html", {**context, "page": result})+ if result.status_code >= 400:+ if form is not None:+ return render(request, "admin_console/operation.html", context, status=400)+ if QueuedMessages.error_count(request) == 0:+ messages.error(request, f"{operation.label} failed with status {result.status_code}.")+ return redirect(tool_url)+ return result++def append_slash(request: HttpRequest, rest: str) -> HttpResponse:query = request.META.get("QUERY_STRING", "")return HttpResponseRedirect(f"/admin/console{rest}/" + (f"?{query}" if query else ""))diff --git a/posthog/admin/test_admin_console.py b/posthog/admin/test_admin_console.pyindex 76de554d61cc..d5c91c9f11a8 100644--- a/posthog/admin/test_admin_console.py+++ b/posthog/admin/test_admin_console.py@@ -7,6 +7,7 @@ from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patchfrom django.conf import settings+from django.contrib.auth.models import Groupfrom django.http import HttpRequest, HttpResponsefrom django.template.loader import render_to_stringfrom django.test import Client, RequestFactory, SimpleTestCase, override_settings@@ -14,17 +15,22 @@ from django.utils.html import format_htmlfrom parameterized import parameterized+from posthog.admin.console.organization_panels import BillingPanel, QuotaLimitsfrom posthog.admin.console.panels import MAX_FACTS_PER_PANEL, Fact, Operation, Owner, Panel, ReasonForm+from posthog.admin.console.records import RECORD_TYPESfrom posthog.admin.console.registry import ConsoleRegistry, consolefrom posthog.admin.console.tools import Cell, ConsoleTool, Page, Row, Tablefrom posthog.csp_middleware import CSPMiddlewarefrom posthog.models.events_retention_config import OrganizationEventsRetentionConfig+from posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom products.ai_gateway.backend.facade.contracts import TeamCreditAdded, TeamCreditRefusedfrom products.workflows.backend.facade.api import get_email_sending_state+from ee.billing.quota_limiting import QuotaResource+TEMPLATE_DIR = Path(settings.BASE_DIR) / "posthog" / "templates" / "admin_console"CONSOLE_ASSETS = Path(settings.BASE_DIR) / "frontend" / "public" / "admin-console"REBUILD = "pnpm --filter=@posthog/frontend build:admin-console"@@ -96,7 +102,9 @@ class TestAdminConsoleAssets(SimpleTestCase):)def test_every_owner_crest_ships(self) -> None:- owners = [panel.owner for panel in console.panels_for("team")] + [tool.owner for tool in console.tools()]+ owners = [panel.owner for record in RECORD_TYPES for panel in console.panels_for(record)] + [+ tool.owner for tool in console.tools()+ ]missing = sorted({owner.crest for owner in owners if not (CONSOLE_ASSETS / "crests" / f"{owner.crest}.svg").is_file()})@@ -140,6 +148,16 @@ class TestAdminConsoleAssets(SimpleTestCase):"undo_hint",),("fact_with_markup", lambda: Fact(label="Plan", value=format_html("<b>{}</b>", "Scale")), "plain text"),+ (+ "fact_linking_off_site",+ lambda: Fact(label="Docs", value="Read", href="//example.com/phish"),+ "starts with /",+ ),+ (+ "fact_linking_off_site_with_a_backslash",+ lambda: Fact(label="Docs", value="Read", href="/\\example.com/phish"),+ "starts with /",+ ),("unknown_tool_block", lambda: Page(blocks=(Fact(label="a", value="b"),)), "not a console block"), # type: ignore[arg-type]("table_row_missing_a_cell",@@ -154,6 +172,22 @@ class TestAdminConsoleAssets(SimpleTestCase):with self.assertRaisesRegex(ValueError, message):contribute()+ @parameterized.expand(+ [+ ("fits", MAX_FACTS_PER_PANEL, MAX_FACTS_PER_PANEL, False),+ ("overflows", MAX_FACTS_PER_PANEL + 1, MAX_FACTS_PER_PANEL, True),+ ]+ )+ def test_billing_facts_count_the_limits_past_the_panel_cap(+ self, _name: str, limited_count: int, expected_facts: int, mentions_more: bool+ ) -> None:+ limited: dict[QuotaResource, int | None] = dict.fromkeys(list(QuotaResource)[:limited_count])+ with patch.object(QuotaLimits, "limited", return_value=limited):+ facts = BillingPanel().facts(Organization(name="Many limits"))++ assert len(facts) == expected_facts+ assert (facts[-1].label == "More limits") == mentions_more+class TestAdminConsoleTheme(SimpleTestCase):def _request(self, theme_mode: str | None) -> HttpRequest:@@ -229,6 +263,15 @@ class TestAdminConsoleViews(BaseTest):for panel in console.panels_for("team"):assert len(panel.facts(self.team)) <= MAX_FACTS_PER_PANEL, f"{panel.key} shows too many facts"+ assert f"/admin/console/organizations/{self.organization.pk}/" in content++ organization_page = self.client.get(f"/admin/console/organizations/{self.organization.pk}/")+ assert organization_page.status_code == 200+ organization_content = organization_page.content.decode()+ for title in ("Overview", "Teams", "Billing"):+ assert title in organization_content+ assert f"/admin/console/teams/{self.team.pk}/" in organization_content+home = self.client.get("/admin/console/").content.decode()assert "Recently opened" in homeassert f"/admin/console/teams/{self.team.pk}/" in home@@ -253,15 +296,19 @@ class TestAdminConsoleViews(BaseTest):@parameterized.expand([- ("form_page_keeps_its_parameters", "set-api-token/?from=ticket", "api-token/set/?from=ticket"),- ("button_action_lands_on_its_panel", "rebuild-cache/", "#panel-remote-config"),+ ("form_page_keeps_its_parameters", "team", "set-api-token/?from=ticket", "api-token/set/?from=ticket"),+ ("button_action_lands_on_its_panel", "team", "rebuild-cache/", "#panel-remote-config"),+ ("organization_action", "organization", "limit-product/?resource=events", "?resource=events#panel-billing"),])- def test_an_old_django_admin_action_url_lands_on_the_console(self, _name: str, old: str, new: str) -> None:- response = self.client.get(f"/admin/posthog/team/{self.team.pk}/{old}")+ def test_an_old_django_admin_action_url_lands_on_the_console(+ self, _name: str, record: str, old: str, new: str+ ) -> None:+ obj = self.team if record == "team" else self.organization+ response = self.client.get(f"/admin/posthog/{record}/{obj.pk}/{old}")assert response.status_code == 302- assert response["Location"] == f"/admin/console/teams/{self.team.pk}/{new}"+ assert response["Location"] == f"/admin/console/{record}s/{obj.pk}/{new}"def test_django_admin_team_page_points_moved_actions_to_the_console(self) -> None:response = self.client.get(f"/admin/posthog/team/{self.team.pk}/change/")@@ -370,6 +417,53 @@ class TestAdminConsoleViews(BaseTest):assert "gateway down" in contentassert "Outage goodwill" in content+ @parameterized.expand(+ [+ ("limit_without_reason", "limit", {"resource": "events", "reason": " "}, True, 400, False),+ ("limit_without_billing_period", "limit", {"resource": "events", "reason": "Abuse"}, False, 400, False),+ ("limit", "limit", {"resource": "events", "reason": "Abuse"}, True, 302, True),+ ("unlimit", "unlimit", {"resource": "events"}, True, 302, False),+ ]+ )+ @time_machine.travel("2026-10-20T12:00:00Z", tick=False)+ def test_billing_operations_limit_and_unlimit_a_product(+ self,+ _name: str,+ operation_key: str,+ data: dict[str, str],+ has_billing_period: bool,+ expected_status: int,+ expect_limited: bool,+ ) -> None:+ if has_billing_period:+ self.organization.usage = {"period": ["2026-10-01T00:00:00Z", "2026-11-01T00:00:00Z"]}+ self.organization.save()+ if operation_key == "unlimit":+ self.organization.limit_product_until_end_of_billing_cycle(QuotaResource.EVENTS)++ response = self.client.post(+ f"/admin/console/organizations/{self.organization.pk}/billing/{operation_key}/", data+ )++ assert response.status_code == expected_status+ assert (QuotaResource.EVENTS in QuotaLimits.limited(self.organization)) == expect_limited++ @parameterized.expand([("billing_staff", True, 302), ("other_staff", False, 403)])+ @patch("posthog.admin.console.usage_reports_tool.call_command")+ @time_machine.travel("2026-10-20T12:00:00Z", tick=False)+ def test_sending_usage_reports_needs_the_billing_team_group(+ self, _name: str, in_group: bool, expected_status: int, call_command: MagicMock+ ) -> None:+ if in_group:+ Group.objects.get_or_create(name="Billing Team")[0].user_set.add(self.user)++ page = self.client.get("/admin/console/tools/usage-reports/").content.decode()+ response = self.client.post("/admin/console/tools/usage-reports/send/", {"report_date": "2026-10-19"})++ assert ("Needs the Billing Team group" in page) != in_group+ assert response.status_code == expected_status+ assert call_command.called == in_group+@time_machine.travel("2026-10-20T12:00:00Z", tick=False)def test_events_retention_tool_lists_the_teams_of_an_organization_with_a_default(self) -> None:empty = self.client.get("/admin/console/tools/events-retention/")diff --git a/posthog/templates/admin/organization/limited_products.html b/posthog/templates/admin/organization/limited_products.htmlindex 426a8775c2dc..1a98d2d3af74 100644--- a/posthog/templates/admin/organization/limited_products.html+++ b/posthog/templates/admin/organization/limited_products.html@@ -1,3 +1,4 @@+<p>{{ actions_moved }}</p><table style="border-collapse: collapse; width: 100%;"><thead><tr>@@ -6,7 +7,6 @@<th style="padding: 8px; text-align: left;">Limited Teams</th><th style="padding: 8px; text-align: left;">Redis Until</th><th style="padding: 8px; text-align: left;">Usage Until</th>- <th style="padding: 8px; text-align: left;">Actions</th></tr></thead><tbody>@@ -19,31 +19,6 @@<td style="padding: 8px;">{{ info.limited_teams|length }}<span style="color: #888">/{{ total_teams }}</span></td><td style="padding: 8px;">{{ info.redis_quota_limited_until_formatted }}</td><td style="padding: 8px;">{{ info.usage_quota_limited_until_formatted }}</td>- <td style="padding: 8px;">- <form method="post"- action="{% url 'admin:limit_product' organization_id %}"- style="display: inline-block;- margin-right: 4px">- {% csrf_token %}- <input type="hidden" name="resource" value="{{ resource }}">- <button type="submit"- class="button"- style="padding: 2px 8px;- font-size: 11px"- {% if info.is_limited_in_redis %}disabled{% endif %}>Limit</button>- </form>- <form method="post"- action="{% url 'admin:unlimit_product' organization_id %}"- style="display: inline-block">- {% csrf_token %}- <input type="hidden" name="resource" value="{{ resource }}">- <button type="submit"- class="button"- style="padding: 2px 8px;- font-size: 11px"- {% if not info.is_limited_in_redis %}disabled{% endif %}>Unlimit</button>- </form>- </td></tr>{% endfor %}</tbody>diff --git a/posthog/templates/admin/organization/sync_to_billing.html b/posthog/templates/admin/organization/sync_to_billing.htmldeleted file mode 100644index 2fea63b541a1..000000000000--- a/posthog/templates/admin/organization/sync_to_billing.html+++ /dev/null@@ -1,9 +0,0 @@-<form method="post"- action="{% url 'admin:organization_sync_to_billing' organization_id %}"- style="display: inline-block">- {% csrf_token %}- <button type="submit" class="button">Sync to billing</button>-</form>-<p style="color: #666; margin-top: 8px;">- Queues a Celery task that syncs this organization's members to the billing service (equivalent to <code>./manage.py sync_to_billing --action=organization_users --organization-ids=<id> --async=1</code>).-</p>diff --git a/posthog/templates/admin/posthog/organization/send_usage_report.html b/posthog/templates/admin/posthog/organization/send_usage_report.htmldeleted file mode 100644index c852b9bfed32..000000000000--- a/posthog/templates/admin/posthog/organization/send_usage_report.html+++ /dev/null@@ -1,31 +0,0 @@-{% extends "admin/base_site.html" %}-{% load i18n admin_urls %}-{% block content %}- <div id="content-main">- <form method="post">- <p>- The date is the day that the usage report would have been run, so is one day past the date where usage reports are missing.- <br />- For instance, if we had 0 usage reports on May 11, the date you'd use is actually May 12 (because usage reports are reporting usage for the previous day).- <br />- Read more <b><a href="https://posthog.com/docs/advanced/usage-reports"- target="_blank">here</a></b>.- </p>- {% csrf_token %}- <fieldset class="module aligned">- {% for field in form %}- <div class="form-row">- {{ field.errors }}- {{ field.label_tag }} {{ field }}- </div>- {% endfor %}- </fieldset>- <div class="submit-row">- <input type="submit"- value="Send Usage Report"- class="default"- name="_send_report">- </div>- </form>- </div>-{% endblock %}diff --git a/posthog/templates/admin/posthog/team/change_form.html b/posthog/templates/admin/posthog/team/change_form.htmlindex 7d5ec11bf5b2..847339724843 100644--- a/posthog/templates/admin/posthog/team/change_form.html+++ b/posthog/templates/admin/posthog/team/change_form.html@@ -7,7 +7,7 @@{% endblock %}{% block admin_console_url %}{% if original.pk %}- {% url 'admin_console_team' team_id=original.pk %}+ {% url 'admin_console_team' pk=original.pk %}{% else %}{{ block.super }}{% endif %}diff --git a/posthog/templates/admin/resave_cohorts.html b/posthog/templates/admin/resave_cohorts.htmldeleted file mode 100644index 41ca49e507e4..000000000000--- a/posthog/templates/admin/resave_cohorts.html+++ /dev/null@@ -1,53 +0,0 @@-{% extends "admin/base_site.html" %}-{% load i18n admin_urls static %}-{% block extrastyle %}- {{ block.super }}- <style>- .form-row { margin-bottom: 15px; }- .help { font-size: 11px; color: #666; }- .submit-row { margin-top: 30px; }- .alert { padding: 10px; margin: 20px 0; border-radius: 5px; }- .alert-info { background: #e3f2fd; border: 1px solid #90caf9; color: #1565c0; }- </style>-{% endblock %}-{% block content %}- <div class="alert alert-info">- <strong>Note:</strong> This tool re-saves cohorts to regenerate compiled bytecode and cohort_type using the- current backend logic. It runs in batches to avoid load. Use dry-run to preview a summary first.- Check server logs for command output.- <br />- Scope: target a single team (team id) or all teams if left blank.- </div>- {% if messages %}- {% for message in messages %}- <div class="alert alert-{{ message.tags }}">{{ message }}</div>- {% endfor %}- {% endif %}- <form method="post" id="resave-cohorts-form">- {% csrf_token %}- <fieldset class="module aligned">- <h2>Configuration</h2>- <div class="form-row">- <label for="{{ form.team_id.id_for_label }}">{{ form.team_id.label }}:</label>- {{ form.team_id }}- {% if form.team_id.help_text %}<p class="help">{{ form.team_id.help_text }}</p>{% endif %}- {{ form.team_id.errors }}- </div>- <div class="form-row">- <label for="{{ form.batch_size.id_for_label }}" class="required">{{ form.batch_size.label }}:</label>- {{ form.batch_size }}- {% if form.batch_size.help_text %}<p class="help">{{ form.batch_size.help_text }}</p>{% endif %}- {{ form.batch_size.errors }}- </div>- <div class="form-row">- <label for="{{ form.dry_run.id_for_label }}">{{ form.dry_run.label }}:</label>- {{ form.dry_run }}- {% if form.dry_run.help_text %}<p class="help">{{ form.dry_run.help_text }}</p>{% endif %}- {{ form.dry_run.errors }}- </div>- </fieldset>- <div class="submit-row">- <input type="submit" value="Run Resave" class="default" />- </div>- </form>-{% endblock %}diff --git a/posthog/templates/admin_console/_blocks.html b/posthog/templates/admin_console/_blocks.htmlnew file mode 100644index 000000000000..11e1329e01b3--- /dev/null+++ b/posthog/templates/admin_console/_blocks.html@@ -0,0 +1,14 @@+{# The blocks of a console Page. `page` is a Page from posthog/admin/console/tools.py. #}+<div class="flex flex-col gap-4">+ {% for block in page.blocks %}+ {% if block.kind == "notice" %}+ <p class="m-0 max-w-3xl text-muted-foreground">{{ block.text }}</p>+ {% elif block.kind == "table" %}+ {% include "admin_console/_table.html" with table=block %}+ {% elif block.kind == "output" %}+ <pre class="m-0 p-3 max-h-[480px] overflow-auto rounded border border-border bg-chrome font-mono text-xs whitespace-pre-wrap break-words">{{ block.text }}</pre>+ {% elif block.kind == "paging" %}+ {% include "admin_console/_paging.html" with paging=block %}+ {% endif %}+ {% endfor %}+</div>diff --git a/posthog/templates/admin_console/_operations.html b/posthog/templates/admin_console/_operations.htmlnew file mode 100644index 000000000000..1cedc38e1b9e--- /dev/null+++ b/posthog/templates/admin_console/_operations.html@@ -0,0 +1,34 @@+{# Operation buttons. `operations` is a list of RenderedOperation from posthog/admin/console/views.py. #}+<ul class="m-0 p-0 list-none grid grid-cols-[max-content_1fr] items-center gap-x-3 gap-y-2">+ {% for rendered_operation in operations %}+ {% with operation=rendered_operation.operation %}+ <li class="grid grid-cols-subgrid col-span-2 items-center">+ {% if not rendered_operation.allowed %}+ <button type="button"+ disabled+ class="quill-button quill-button--variant-outline quill-button--size-sm group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap">+ {{ operation.label }}+ </button>+ {% elif operation.form_class %}+ <a href="{{ rendered_operation.url }}"+ class="quill-button {% if operation.danger %}quill-button--variant-destructive-outline{% else %}quill-button--variant-outline{% endif %} quill-button--size-sm group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap">{{ operation.label }}</a>+ {% else %}+ <form method="post" action="{{ rendered_operation.url }}">+ {% csrf_token %}+ <button type="submit"+ class="quill-button quill-button--variant-outline quill-button--size-sm group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap">+ {{ operation.label }}+ </button>+ </form>+ {% endif %}+ <span class="text-xs text-muted-foreground">+ {% if operation.danger %}+ {% include "admin_console/_badge.html" with label="Risky" tone="destructive" %}+ {% endif %}+ {{ operation.description }}+ {% if not rendered_operation.allowed %}Needs {{ operation.gate.label }}.{% endif %}+ </span>+ </li>+ {% endwith %}+ {% endfor %}+</ul>diff --git a/posthog/templates/admin_console/_panel.html b/posthog/templates/admin_console/_panel.htmlindex f8a4a3603c4c..6bb33de736f6 100644--- a/posthog/templates/admin_console/_panel.html+++ b/posthog/templates/admin_console/_panel.html@@ -30,7 +30,10 @@{% for fact in rendered.facts %}<dt class="text-muted-foreground">{{ fact.label }}</dt><dd class="m-0 min-w-0 break-words">- {% if fact.tone %}+ {% if fact.href %}+ <a class="text-foreground underline decoration-border underline-offset-2 hover:decoration-current{% if fact.mono %} font-mono text-xs{% endif %}"+ href="{{ fact.href }}">{{ fact.value }}</a>+ {% elif fact.tone %}{% include "admin_console/_badge.html" with label=fact.value tone=fact.tone mono=fact.mono %}{% elif fact.mono %}<span class="font-mono text-xs">{{ fact.value }}</span>@@ -42,31 +45,9 @@</dl>{% endif %}{% if rendered.operations %}- <ul class="m-0 p-0 list-none grid grid-cols-[max-content_1fr] items-center gap-x-3 gap-y-2 pt-3 border-t border-border">- {% for operation in rendered.operations %}- <li class="grid grid-cols-subgrid col-span-2 items-center">- {% if operation.form_class %}- <a href="{% url 'admin_console_team_operation' team_id=team.pk panel_key=rendered.panel.key operation_key=operation.key %}"- class="quill-button {% if operation.danger %}quill-button--variant-destructive-outline{% else %}quill-button--variant-outline{% endif %} quill-button--size-sm group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap">{{ operation.label }}</a>- {% else %}- <form method="post"- action="{% url 'admin_console_team_operation' team_id=team.pk panel_key=rendered.panel.key operation_key=operation.key %}">- {% csrf_token %}- <button type="submit"- class="quill-button quill-button--variant-outline quill-button--size-sm group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap">- {{ operation.label }}- </button>- </form>- {% endif %}- <span class="text-xs text-muted-foreground">- {% if operation.danger %}- {% include "admin_console/_badge.html" with label="Risky" tone="destructive" %}- {% endif %}- {{ operation.description }}- </span>- </li>- {% endfor %}- </ul>+ <div class="pt-3 border-t border-border">+ {% include "admin_console/_operations.html" with operations=rendered.operations %}+ </div>{% endif %}</div></section>diff --git a/posthog/templates/admin_console/_team_list.html b/posthog/templates/admin_console/_team_list.htmlindex d2f77946f6d0..3555e072bd6c 100644--- a/posthog/templates/admin_console/_team_list.html+++ b/posthog/templates/admin_console/_team_list.html@@ -10,7 +10,7 @@{% for team in teams %}<tr class="border-b border-border last:border-b-0"><td class="py-1.5"><a class="font-semibold text-foreground underline decoration-border underline-offset-2 hover:decoration-current"- href="{% url 'admin_console_team' team_id=team.pk %}">{{ team.name }}</a></td>+ href="{% url 'admin_console_team' pk=team.pk %}">{{ team.name }}</a></td><td class="py-1.5">{{ team.organization.name }}</td><td class="py-1.5 font-mono text-xs">{{ team.pk }}</td></tr>diff --git a/posthog/templates/admin_console/operation.html b/posthog/templates/admin_console/operation.htmlindex 5fc01c5b071c..02d47d18413a 100644--- a/posthog/templates/admin_console/operation.html+++ b/posthog/templates/admin_console/operation.html@@ -1,14 +1,12 @@{% extends "admin_console/base.html" %}-{% block title %}{{ operation.label }} · {{ team.name }} · PostHog Admin{% endblock %}+{% block title %}{{ operation.label }} · {{ target.title }} · PostHog Admin{% endblock %}{% block content %}<nav class="text-xs text-muted-foreground" aria-label="Breadcrumb">- <a class="text-muted-foreground" href="{% url 'admin_console_home' %}">Teams</a>- ›- <a class="text-muted-foreground"- href="{% url 'admin_console_team' team_id=team.pk %}">{{ team.name }}</a>- ›- <a class="text-muted-foreground"- href="{% url 'admin_console_team' team_id=team.pk %}#panel-{{ panel.key }}">{{ panel.title }}</a>+ <a class="text-muted-foreground" href="{% url 'admin_console_home' %}">Home</a>+ {% for crumb in target.breadcrumbs %}+ ›+ <a class="text-muted-foreground" href="{{ crumb.href }}">{{ crumb.label }}</a>+ {% endfor %}</nav><h1 class="mt-1.5 mb-4 text-[22px] font-extrabold">{{ operation.label }}</h1><section class="quill-card group/card flex flex-col max-w-xl{% if operation.danger %} console-danger{% endif %}"@@ -17,15 +15,15 @@data-size="default"><div class="quill-card__header group/card-header" data-slot="card-header"><div class="flex flex-col gap-1 min-w-0">- <span class="text-xs text-muted-foreground">This acts on</span>+ <span class="text-xs text-muted-foreground">{{ target.kicker }}</span><span class="flex flex-wrap items-center gap-2">- <strong class="text-[15px] break-words">{{ team.name }}</strong>- <span class="quill-badge inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden whitespace-nowrap quill-badge--variant-default font-mono">Team {{ team.pk }}</span>+ <strong class="text-[15px] break-words">{{ target.title }}</strong>+ <span class="quill-badge inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden whitespace-nowrap quill-badge--variant-default font-mono">{{ target.badge }}</span><span class="console-env-pill inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[11px] font-bold uppercase tracking-wide whitespace-nowrap"><span class="console-env-dot size-[7px] rounded-full"></span>{{ console_env_label }}</span></span>- <span class="text-muted-foreground">{{ team.organization.name }}</span>+ {% if target.subtitle %}<span class="text-muted-foreground">{{ target.subtitle }}</span>{% endif %}</div></div><form method="post" class="flex flex-col" data-autofocus>@@ -46,9 +44,9 @@data-slot="card-footer"><button type="submit"class="quill-button {% if operation.danger %}quill-button--variant-destructive{% else %}quill-button--variant-primary{% endif %} quill-button--size-default group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap">- {{ operation.label }} for {{ team.name|truncatechars:40 }}+ {{ operation.label }}{% if target.is_record %} for {{ target.title|truncatechars:40 }}{% endif %}</button>- <a href="{% url 'admin_console_team' team_id=team.pk %}"+ <a href="{{ target.back_url }}"class="quill-button quill-button--variant-outline quill-button--size-default group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap">Cancel</a></div></form>diff --git a/posthog/templates/admin_console/team.html b/posthog/templates/admin_console/record.htmlsimilarity index 73%rename from posthog/templates/admin_console/team.htmlrename to posthog/templates/admin_console/record.htmlindex e352b6236b84..55ff81a16a45 100644--- a/posthog/templates/admin_console/team.html+++ b/posthog/templates/admin_console/record.html@@ -1,26 +1,27 @@{% extends "admin_console/base.html" %}-{% block title %}{{ team.name }} · PostHog Admin{% endblock %}+{% block title %}{{ record_title }} · PostHog Admin{% endblock %}{% block content %}<nav class="text-xs text-muted-foreground" aria-label="Breadcrumb">- <a class="text-muted-foreground" href="{% url 'admin_console_home' %}">Teams</a>- ›- <a class="text-muted-foreground"- href="{% url 'admin_console_home' %}?q={{ team.organization.name|urlencode }}">{{ team.organization.name }}</a>+ <a class="text-muted-foreground" href="{% url 'admin_console_home' %}">Home</a>+ {% for parent in record_parents %}+ ›+ <a class="text-muted-foreground" href="{{ parent.href }}">{{ parent.label }}</a>+ {% endfor %}</nav><div class="flex flex-wrap items-start gap-4 mt-1.5 mb-4"><div class="min-w-0">- <h1 class="m-0 text-[22px] font-extrabold break-words">{{ team.name }}</h1>+ <h1 class="m-0 text-[22px] font-extrabold break-words">{{ record_title }}</h1><div class="flex flex-wrap items-center gap-2 mt-1 text-muted-foreground">- <span class="quill-badge inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden whitespace-nowrap quill-badge--variant-default font-mono">Team {{ team.pk }}</span>- <span>{{ team.organization.name }}</span>+ <span class="quill-badge inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden whitespace-nowrap quill-badge--variant-default font-mono">{{ record_type.label }} {{ obj.pk }}</span>+ {% if record_subtitle %}<span>{{ record_subtitle }}</span>{% endif %}</div></div><div class="ml-auto flex flex-wrap gap-2">- <a class="quill-button quill-button--variant-outline quill-button--size-default group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap"- href="{% url 'admin:posthog_team_change' team.pk %}"- title="The raw Team row, with every field">Raw record in Django admin</a>- <a class="quill-button quill-button--variant-outline quill-button--size-default group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap"- href="/project/{{ team.pk }}">Open in app ↗</a>+ {% for link in record_links %}+ <a class="quill-button quill-button--variant-outline quill-button--size-default group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap"+ href="{{ link.href }}"+ {% if link.title %}title="{{ link.title }}"{% endif %}>{{ link.label }}</a>+ {% endfor %}</div></div>{% if attention %}diff --git a/posthog/templates/admin_console/result.html b/posthog/templates/admin_console/result.htmlnew file mode 100644index 000000000000..981a413e207d--- /dev/null+++ b/posthog/templates/admin_console/result.html@@ -0,0 +1,17 @@+{% extends "admin_console/base.html" %}+{% block title %}{{ operation.label }} · {{ target.title }} · PostHog Admin{% endblock %}+{% block content %}+ <nav class="text-xs text-muted-foreground" aria-label="Breadcrumb">+ <a class="text-muted-foreground" href="{% url 'admin_console_home' %}">Home</a>+ {% for crumb in target.breadcrumbs %}+ ›+ <a class="text-muted-foreground" href="{{ crumb.href }}">{{ crumb.label }}</a>+ {% endfor %}+ </nav>+ <div class="flex flex-wrap items-start gap-4 mt-1.5 mb-4">+ <h1 class="m-0 text-[22px] font-extrabold">{{ operation.label }}: result</h1>+ <a class="ml-auto quill-button quill-button--variant-outline quill-button--size-default group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap"+ href="{{ target.back_url }}">Back to {{ target.title }}</a>+ </div>+ {% include "admin_console/_blocks.html" %}+{% endblock %}diff --git a/posthog/templates/admin_console/tool.html b/posthog/templates/admin_console/tool.htmlindex 0b9d278b2116..8dfec5f3e6e5 100644--- a/posthog/templates/admin_console/tool.html+++ b/posthog/templates/admin_console/tool.html@@ -17,15 +17,19 @@alt="" /></div></div>- <div class="flex flex-col gap-4">- {% for block in page.blocks %}- {% if block.kind == "notice" %}- <p class="m-0 max-w-3xl text-muted-foreground">{{ block.text }}</p>- {% elif block.kind == "table" %}- {% include "admin_console/_table.html" with table=block %}- {% elif block.kind == "paging" %}- {% include "admin_console/_paging.html" with paging=block %}- {% endif %}- {% endfor %}- </div>+ {% if operations %}+ <section class="quill-card group/card flex flex-col mb-4 max-w-3xl"+ data-quill+ data-slot="card"+ data-size="sm"+ aria-labelledby="tool-actions-title">+ <div class="quill-card__header group/card-header" data-slot="card-header">+ <h2 id="tool-actions-title"+ class="quill-card__title m-0"+ data-slot="card-title">Actions</h2>+ </div>+ <div class="quill-card__content" data-slot="card-content">{% include "admin_console/_operations.html" %}</div>+ </section>+ {% endif %}+ {% include "admin_console/_blocks.html" %}{% endblock %}diff --git a/posthog/templates/organization_tools/app.html b/posthog/templates/organization_tools/app.htmlindex 6afd39c13333..d2cad55046ab 100644--- a/posthog/templates/organization_tools/app.html+++ b/posthog/templates/organization_tools/app.html@@ -8,7 +8,7 @@</caption><tr class="model-sendusagereport"><th scope="row">- <a href="{% url 'admin:send-usage-report' %}">Send usage report</a>+ <a href="{% url 'admin_console_tool' tool_key='usage-reports' %}">Send usage report</a></th><td>Queue a usage report for a selected report date</td></tr>diff --git a/posthog/test/test_resave_cohorts_admin.py b/posthog/test/test_resave_cohorts_admin.pydeleted file mode 100644index 5b926764174a..000000000000--- a/posthog/test/test_resave_cohorts_admin.py+++ /dev/null@@ -1,57 +0,0 @@-from posthog.test.base import BaseTest-from unittest.mock import MagicMock, patch--from django.test import Client, override_settings--from parameterized import parameterized--from posthog.management.commands.resave_cohorts import UnclassifiedCohortsError---@override_settings(ADMIN_PORTAL_ENABLED=True)-class TestResaveCohortsAdminView(BaseTest):- def setUp(self):- super().setUp()- self.client = Client()- self.user.is_staff = True- self.user.save()- self.client.force_login(self.user)-- def _post(self, team_id: str, follow: bool = False):- return self.client.post("/admin/resave-cohorts/", {"batch_size": 500, "team_id": team_id}, follow=follow)-- @parameterized.expand(- [- ("explicit_team", "7", [7]),- # Team 0 has to reach the command, which rejects it. Reading it as "no team given" would- # silently resave every team.- ("team_zero", "0", [0]),- ("blank_team", "", None),- ]- )- @patch("posthog.admin.admins.resave_cohorts_admin.call_command")- def test_form_team_id_reaches_the_command(- self, _name: str, submitted: str, expected: list[int] | None, mock_call_command: MagicMock- ) -> None:- self._post(submitted)-- assert mock_call_command.call_args.kwargs.get("team_id") == expected-- @patch("posthog.admin.admins.resave_cohorts_admin.call_command")- def test_unclassified_cohorts_report_as_a_warning(self, mock_call_command: MagicMock) -> None:- mock_call_command.side_effect = UnclassifiedCohortsError("2 cohorts still have a null condition_type: 1, 2")-- response = self._post("7", follow=True)-- message = next(iter(response.context["messages"]))- assert message.level_tag == "warning"- assert "finished" in str(message)-- @patch("posthog.admin.admins.resave_cohorts_admin.call_command")- def test_a_run_that_never_started_reports_as_an_error(self, mock_call_command: MagicMock) -> None:- mock_call_command.side_effect = Exception("boom")-- response = self._post("7", follow=True)-- message = next(iter(response.context["messages"]))- assert message.level_tag == "error"diff --git a/products/cohorts/backend/console.py b/products/cohorts/backend/console.pynew file mode 100644index 000000000000..52f249b7f39e--- /dev/null+++ b/products/cohorts/backend/console.py@@ -0,0 +1,130 @@+from collections import deque+from io import TextIOBase++from django import forms+from django.contrib import messages+from django.core.management import CommandError, call_command+from django.http import HttpRequest, HttpResponse++import structlog++from posthog.admin.console.panels import Owner+from posthog.admin.console.registry import console+from posthog.admin.console.tools import ConsoleTool, Notice, Output, Page, ToolOperation+from posthog.management.commands.resave_cohorts import IncompleteResaveError++logger = structlog.get_logger(__name__)++FEATURE_FLAGS = Owner(name="Feature flags", crest="feature-flags")+# The command prints a line per team. A result page past this many lines is too long to read anyway.+MAX_OUTPUT_LINES = 400+++class ResaveCohortsForm(forms.Form):+ team_id = forms.IntegerField(required=False, help_text="Leave empty to re-save the cohorts of every team.")+ batch_size = forms.IntegerField(initial=500, min_value=1, max_value=5000, help_text="Cohorts per batch.")+ dry_run = forms.BooleanField(+ initial=True, required=False, help_text="Report what would change without saving anything."+ )+++class OutputTail(TextIOBase):+ """Keeps the last lines a command prints and counts them all, so a run across every team stays small in memory."""++ def __init__(self, keep: int) -> None:+ super().__init__()+ self.lines: deque[str] = deque(maxlen=keep)+ self.line_count = 0+ self._partial = ""++ def write(self, text: str) -> int:+ *complete, self._partial = (self._partial + text).split("\n")+ for line in complete:+ if line.strip():+ self.lines.append(line)+ self.line_count += 1+ return len(text)++ def finish(self) -> list[str]:+ if self._partial.strip():+ self.lines.append(self._partial)+ self.line_count += 1+ self._partial = ""+ return list(self.lines)+++class ResaveCohorts:+ """Runs the `resave_cohorts` management command from the console and keeps the end of what it printed."""++ @staticmethod+ def run(form: forms.Form) -> tuple[OutputTail, CommandError | None]:+ command_kwargs: dict[str, object] = {+ "batch_size": form.cleaned_data["batch_size"],+ "dry_run": form.cleaned_data["dry_run"],+ }+ team_id = form.cleaned_data.get("team_id")+ if team_id is not None:+ # Presence, not truthiness: team 0 has to reach the command, which rejects it. Reading it as+ # "no team given" would widen the run to every team. `call_command` skips argparse coercion for+ # keyword options, so the list that `--team-id` builds is passed already built.+ command_kwargs["team_id"] = [team_id]+ output = OutputTail(keep=MAX_OUTPUT_LINES)+ try:+ call_command("resave_cohorts", stdout=output, no_color=True, **command_kwargs)+ except IncompleteResaveError as error:+ # The run finished and kept its saves, so this is a result with problems, not a failure to start.+ return output, error+ return output, None+++def resave_cohorts(request: HttpRequest, form: forms.Form | None) -> HttpResponse | Page | None:+ assert form is not None+ try:+ output, problem = ResaveCohorts.run(form)+ except CommandError as error:+ messages.error(request, f"The re-save did not start: {error}")+ return HttpResponse(status=400)+ lines = output.finish()+ summary = lines[-1] if lines else "The command printed nothing."+ if problem is not None:+ messages.warning(request, f"The re-save finished with problems: {problem}")+ if form.cleaned_data["dry_run"]:+ # Nothing was saved, so a reload that runs it again is harmless.+ notice = "Dry run, nothing was saved."+ if len(lines) < output.line_count:+ notice += f" Showing the last {len(lines)} of {output.line_count} lines."+ return Page(blocks=(Notice(text=notice), Output(text="\n".join(lines))))+ messages.success(request, summary)+ return None++[email protected]_tool+class ResaveCohortsTool(ConsoleTool):+ key = "resave-cohorts"+ title = "Re-save cohorts"+ owner = FEATURE_FLAGS+ group = "Data"+ description = "Re-saves cohorts so their compiled bytecode and cohort type match the current backend logic."++ def page(self, request: HttpRequest) -> Page:+ return Page(+ blocks=(+ Notice(+ text=(+ "The re-save runs while the page loads, team by team, so a run across every team takes a "+ "while. Start with a dry run: it shows each team's changes without saving them."+ )+ ),+ )+ )++ def operations(self, request: HttpRequest) -> list[ToolOperation]:+ return [+ ToolOperation(+ key="run",+ label="Re-save cohorts",+ handler=resave_cohorts,+ description="Re-saves the cohorts of one team, or of every team.",+ form_class=ResaveCohortsForm,+ )+ ]diff --git a/products/cohorts/backend/test/test_resave_cohorts_tool.py b/products/cohorts/backend/test/test_resave_cohorts_tool.pynew file mode 100644index 000000000000..d85225020837--- /dev/null+++ b/products/cohorts/backend/test/test_resave_cohorts_tool.py@@ -0,0 +1,99 @@+from io import TextIOBase++from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.contrib.messages import get_messages+from django.core.management import CommandError++from parameterized import parameterized++from posthog.management.commands.resave_cohorts import UnclassifiedCohortsError++from products.cohorts.backend.console import MAX_OUTPUT_LINES++RUN_URL = "/admin/console/tools/resave-cohorts/run/"+CALL_COMMAND = "products.cohorts.backend.console.call_command"+++class TestResaveCohortsTool(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.user.is_staff = True+ self.user.save()+ self.client.force_login(self.user)++ def _messages(self, response) -> list[tuple[str, str]]:+ return [(message.level_tag, str(message)) for message in get_messages(response.wsgi_request)]++ def test_a_dry_run_shows_what_the_command_printed(self) -> None:+ response = self.client.post(RUN_URL, {"team_id": self.team.pk, "batch_size": 500, "dry_run": "on"})++ assert response.status_code == 200+ content = response.content.decode()+ assert "Dry run, nothing was saved." in content+ assert f"Starting cohort resave for team {self.team.pk}" in content+ assert "Done (dry run)" in content++ @parameterized.expand(+ [+ ("explicit_team", "7", [7]),+ # Team 0 has to reach the command, which rejects it. Reading it as "no team given" would+ # re-save every team.+ ("team_zero", "0", [0]),+ ("blank_team", "", None),+ ]+ )+ @patch(CALL_COMMAND)+ def test_the_team_id_reaches_the_command(+ self, _name: str, submitted: str, expected: list[int] | None, call_command: MagicMock+ ) -> None:+ self.client.post(RUN_URL, {"batch_size": 500, "team_id": submitted})++ assert call_command.call_args.kwargs.get("team_id") == expected++ @parameterized.expand(+ [+ ("finished_with_problems", UnclassifiedCohortsError("2 cohorts still unclassified"), 302, "warning"),+ ("never_started", CommandError("No team with id 7"), 400, "error"),+ ]+ )+ @patch(CALL_COMMAND)+ def test_a_command_error_reports_what_happened(+ self, _name: str, error: CommandError, expected_status: int, expected_level: str, call_command: MagicMock+ ) -> None:+ call_command.side_effect = error++ response = self.client.post(RUN_URL, {"batch_size": 500, "team_id": "7"})++ assert response.status_code == expected_status+ assert any(level == expected_level and str(error) in text for level, text in self._messages(response))++ @parameterized.expand(+ [+ ("staff", True, "/admin/console/tools/resave-cohorts/?team_id=7"),+ ("signed_out", False, "/admin/login/"),+ ]+ )+ def test_the_old_admin_page_redirects_staff_to_the_tool(self, _name: str, signed_in: bool, expected: str) -> None:+ if not signed_in:+ self.client.logout()++ response = self.client.get("/admin/resave-cohorts/?team_id=7")++ assert response.status_code == 302+ assert response["Location"].startswith(expected)++ @patch(CALL_COMMAND)+ def test_a_long_dry_run_keeps_only_the_last_lines(self, call_command: MagicMock) -> None:+ def print_teams(*args: object, stdout: TextIOBase, **kwargs: object) -> None:+ for team in range(1, MAX_OUTPUT_LINES + 51):+ stdout.write(f"Processing team {team}\n")++ call_command.side_effect = print_teams++ content = self.client.post(RUN_URL, {"batch_size": 500, "dry_run": "on"}).content.decode()++ assert f"Showing the last {MAX_OUTPUT_LINES} of {MAX_OUTPUT_LINES + 50} lines." in content+ assert f"Processing team {MAX_OUTPUT_LINES + 50}" in content+ assert content.count("Processing team ") == MAX_OUTPUT_LINES