Skip to content

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

feat: add admin bulk organization deactivation (#83820)

Pawel Cebula8f2f0b20b38c
diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.py
index 184cc2ed6e4d..7d7d27779507 100644
--- a/posthog/admin/admins/organization_admin.py
+++ b/posthog/admin/admins/organization_admin.py
@@ -1,11 +1,17 @@
+import re
from datetime import UTC, timedelta
+from typing import Any
+from uuid import UUID
from django import forms
from django.apps import apps
from django.conf import settings
from django.contrib import admin, messages
+from django.core import signing
+from django.core.exceptions import PermissionDenied
from django.core.management import call_command
from django.core.management.base import CommandError
+from django.db import transaction
from django.shortcuts import redirect, render
from django.template.loader import render_to_string
from django.urls import path, reverse
@@ -25,6 +31,7 @@ from posthog.admin.paginators.no_count_paginator import NoCountPaginator
from posthog.models.organization import Organization
from posthog.person_db_router import PERSONS_DB_MODELS
from posthog.tasks.ai_observability_usage_report import internal_reporting_team_id
+from posthog.utils import pluralize
# Registry of default-db models to count for bulk-delete report.
# Format: (app_label.ModelName, filter_field, display_name)
@@ -124,6 +131,104 @@ class UsageReportForm(forms.Form):
return report_date
+class BulkDeactivateOrganizationsForm(forms.Form):
+ CUSTOM_REASON = "__custom__"
+ MAX_ORGANIZATIONS = 100
+ PREVIEW_TOKEN_SALT = "posthog.admin.bulk_deactivate_organizations"
+
+ organization_ids = forms.CharField(
+ label="Organization IDs",
+ widget=forms.Textarea(
+ attrs={
+ "rows": 10,
+ "placeholder": "Paste one organization ID per line, or separate IDs with commas.",
+ }
+ ),
+ help_text=f"Paste up to {MAX_ORGANIZATIONS} organization IDs separated by new lines, commas, or spaces.",
+ )
+ reason = forms.ChoiceField(
+ label="Reason",
+ choices=[*Organization.DeactivationReason.choices, (CUSTOM_REASON, "Custom reason")],
+ initial=Organization.DeactivationReason.DESKTOP_ABUSE,
+ )
+ custom_reason = forms.CharField(
+ label="Custom reason",
+ required=False,
+ max_length=Organization._meta.get_field("is_not_active_reason").max_length,
+ widget=forms.Textarea(attrs={"rows": 3}),
+ help_text="Used only when reason is set to custom reason.",
+ )
+
+ def clean_organization_ids(self) -> list[UUID]:
+ raw_value = self.cleaned_data["organization_ids"]
+ invalid_tokens: list[str] = []
+ organization_ids: list[UUID] = []
+ seen_ids: set[UUID] = set()
+ token_count = 0
+
+ for match in re.finditer(r"[^,\s]+", raw_value):
+ token_count += 1
+ if token_count > self.MAX_ORGANIZATIONS:
+ raise forms.ValidationError(f"Enter {self.MAX_ORGANIZATIONS} organization IDs or fewer.")
+
+ token = match.group()
+ try:
+ organization_id = UUID(token)
+ except ValueError:
+ invalid_tokens.append(token)
+ continue
+
+ if organization_id in seen_ids:
+ continue
+
+ seen_ids.add(organization_id)
+ organization_ids.append(organization_id)
+
+ if token_count == 0:
+ raise forms.ValidationError("Enter at least one organization ID.")
+
+ if invalid_tokens:
+ raise forms.ValidationError(
+ "These organization IDs are not valid UUIDs: %(ids)s",
+ params={"ids": ", ".join(invalid_tokens[:10])},
+ )
+
+ return organization_ids
+
+ def clean(self) -> dict[str, Any]:
+ cleaned_data = super().clean() or {}
+ reason = cleaned_data.get("reason")
+ custom_reason = (cleaned_data.get("custom_reason") or "").strip()
+
+ if reason == self.CUSTOM_REASON:
+ if not custom_reason:
+ self.add_error("custom_reason", "Enter a custom reason.")
+ return cleaned_data
+ cleaned_data["resolved_reason"] = custom_reason
+ elif reason:
+ cleaned_data["resolved_reason"] = reason
+
+ return cleaned_data
+
+ def preview_payload(self) -> dict[str, str | list[str]]:
+ return {
+ "organization_ids": [str(organization_id) for organization_id in self.cleaned_data["organization_ids"]],
+ "reason": self.cleaned_data["resolved_reason"],
+ }
+
+ def preview_token(self) -> str:
+ return signing.dumps(self.preview_payload(), salt=self.PREVIEW_TOKEN_SALT)
+
+ def preview_token_matches(self, preview_token: str) -> bool:
+ if not preview_token:
+ return False
+
+ try:
+ return signing.loads(preview_token, salt=self.PREVIEW_TOKEN_SALT) == self.preview_payload()
+ except signing.BadSignature:
+ return False
+
+
@admin.register(Organization)
class OrganizationAdmin(admin.ModelAdmin):
show_full_result_count = False # prevent count() queries to show the no of filtered results
@@ -515,6 +620,11 @@ class OrganizationAdmin(admin.ModelAdmin):
self.admin_site.admin_view(self.send_ai_observability_usage_report_view),
name="send-ai-observability-usage-report",
),
+ path(
+ "bulk-deactivate/",
+ 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),
@@ -543,6 +653,110 @@ class OrganizationAdmin(admin.ModelAdmin):
]
return custom_urls + urls
+ def _bulk_deactivation_candidates(self, organization_ids: list[UUID]) -> tuple[list[Organization], list[str]]:
+ organizations_by_id = Organization.objects.only("id", "name", "is_active", "is_not_active_reason").in_bulk(
+ organization_ids
+ )
+ organizations = [
+ organizations_by_id[organization_id]
+ for organization_id in organization_ids
+ if organization_id in organizations_by_id
+ ]
+ missing_ids = [
+ str(organization_id) for organization_id in organization_ids if organization_id not in organizations_by_id
+ ]
+ return organizations, missing_ids
+
+ def bulk_deactivate_view(self, request):
+ if not self.has_change_permission(request):
+ raise PermissionDenied
+
+ form = BulkDeactivateOrganizationsForm(request.POST or None)
+ preview_organizations: list[Organization] = []
+ deactivation_organizations: list[Organization] = []
+ already_inactive_organizations: list[Organization] = []
+ missing_ids: list[str] = []
+ preview_token = ""
+ resolved_reason = ""
+
+ if request.method == "POST" and form.is_valid():
+ organization_ids = form.cleaned_data["organization_ids"]
+ resolved_reason = form.cleaned_data["resolved_reason"]
+ preview_organizations, missing_ids = self._bulk_deactivation_candidates(organization_ids)
+ deactivation_organizations = [
+ organization for organization in preview_organizations if organization.is_active is not False
+ ]
+ already_inactive_organizations = [
+ organization for organization in preview_organizations if organization.is_active is False
+ ]
+
+ if not preview_organizations:
+ form.add_error("organization_ids", "No organizations matched these IDs.")
+ elif not deactivation_organizations:
+ form.add_error("organization_ids", "All matched organizations are already inactive.")
+ elif "confirm" in request.POST:
+ preview_token = form.preview_token()
+ if not form.preview_token_matches(request.POST.get("preview_token", "")):
+ form.add_error(None, "Review the organizations again before deactivating.")
+ else:
+ deactivation_ids = [organization.id for organization in deactivation_organizations]
+ with transaction.atomic():
+ locked_deactivation_organizations = list(
+ Organization.objects.select_for_update()
+ .only("id", "is_active", "is_not_active_reason")
+ .filter(id__in=deactivation_ids)
+ .exclude(is_active=False)
+ )
+ for organization in locked_deactivation_organizations:
+ organization.is_active = False
+ organization.is_not_active_reason = resolved_reason
+ organization.save(update_fields=["is_active", "is_not_active_reason", "updated_at"])
+
+ count = len(locked_deactivation_organizations)
+ if count:
+ messages.success(request, f"Deactivated {pluralize(count, 'organization')}.")
+ if missing_ids:
+ missing_count = len(missing_ids)
+ messages.warning(
+ request,
+ (
+ f"Skipped {pluralize(missing_count, 'organization ID')} "
+ f"that {'were' if missing_count != 1 else 'was'} not found."
+ ),
+ )
+ skipped_inactive_count = len(already_inactive_organizations) + (
+ len(deactivation_organizations) - count
+ )
+ if skipped_inactive_count:
+ messages.warning(
+ request,
+ (
+ f"Skipped {pluralize(skipped_inactive_count, 'already inactive organization')} "
+ "without changing the existing reason."
+ ),
+ )
+ return redirect(reverse("admin:posthog_organization_changelist"))
+ else:
+ preview_token = form.preview_token()
+
+ return render(
+ request,
+ "admin/posthog/organization/bulk_deactivate.html",
+ {
+ **self.admin_site.each_context(request),
+ "title": "Bulk deactivate organizations",
+ "opts": self.model._meta,
+ "form": form,
+ "preview_organizations": preview_organizations,
+ "deactivation_organizations": deactivation_organizations,
+ "already_inactive_organizations": already_inactive_organizations,
+ "missing_ids": missing_ids,
+ "preview_token": preview_token,
+ "resolved_reason": resolved_reason,
+ "custom_reason_value": BulkDeactivateOrganizationsForm.CUSTOM_REASON,
+ },
+ )
+
def model_counts_view(self, request, organization_id):
organization = Organization.objects.get(id=organization_id)
counts = get_model_counts_for_organization(organization)
@@ -604,11 +818,6 @@ class OrganizationAdmin(admin.ModelAdmin):
{"form": form, "can_skip_existing_reports": internal_reporting_team_id() is not None},
)
- def changelist_view(self, request, extra_context=None):
- extra_context = extra_context or {}
- extra_context["show_usage_report_button"] = True
- return super().changelist_view(request, extra_context=extra_context)
-
def change_view(self, request, object_id, form_url="", extra_context=None):
extra_context = extra_context or {}
# Store request for access in display methods (needed for CSRF tokens in templates)
diff --git a/posthog/admin/test_organization_bulk_deactivation_admin.py b/posthog/admin/test_organization_bulk_deactivation_admin.py
new file mode 100644
index 000000000000..5a4f99f819e7
--- /dev/null
+++ b/posthog/admin/test_organization_bulk_deactivation_admin.py
@@ -0,0 +1,363 @@
+from uuid import uuid4
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.contrib import admin
+from django.contrib.admin.sites import AdminSite
+from django.contrib.messages.storage.fallback import FallbackStorage
+from django.core.exceptions import PermissionDenied
+from django.http import HttpRequest
+from django.template.loader import render_to_string
+from django.test import RequestFactory, SimpleTestCase
+from django.urls import reverse
+
+from posthog.admin.admins.organization_admin import BulkDeactivateOrganizationsForm, OrganizationAdmin
+from posthog.models import Organization
+
+
+def _attach_messages(request) -> None:
+ request.session = {}
+ request._messages = FallbackStorage(request)
+
+
+class _PostHogPermissions:
+ def __init__(self, *, change_organization: bool):
+ self.view_organization = True
+ self.change_organization = change_organization
+
+
+class _TemplatePermissions:
+ def __init__(self, *, change_organization: bool):
+ self.posthog = _PostHogPermissions(change_organization=change_organization)
+
+
+class TestOrganizationToolsAdminTemplate(SimpleTestCase):
+ def test_links_to_bulk_deactivation_for_users_with_change_permission(self) -> None:
+ rendered = render_to_string(
+ "organization_tools/app.html",
+ {"perms": _TemplatePermissions(change_organization=True)},
+ )
+
+ assert "Organization tools" in rendered
+ assert 'id="organization-tools"' in rendered
+ assert "Bulk deactivate organizations" in rendered
+ assert reverse("admin:organization_bulk_deactivate") in rendered
+
+ def test_hides_bulk_deactivation_without_change_permission(self) -> None:
+ rendered = render_to_string(
+ "organization_tools/app.html",
+ {"perms": _TemplatePermissions(change_organization=False)},
+ )
+
+ assert "Organization tools" in rendered
+ assert "Send usage report" in rendered
+ assert "Bulk deactivate organizations" not in rendered
+
+
+class TestBulkDeactivateOrganizationsForm(SimpleTestCase):
+ def test_defaults_to_desktop_abuse_reason_and_parses_pasted_ids(self) -> None:
+ first_organization_id = uuid4()
+ second_organization_id = uuid4()
+ form = BulkDeactivateOrganizationsForm(
+ {
+ "organization_ids": f"{first_organization_id},\n{second_organization_id} {first_organization_id}",
+ "reason": Organization.DeactivationReason.DESKTOP_ABUSE.value,
+ "custom_reason": "",
+ }
+ )
+
+ assert (
+ BulkDeactivateOrganizationsForm().fields["reason"].initial == Organization.DeactivationReason.DESKTOP_ABUSE
+ )
+ assert form.is_valid()
+ assert form.cleaned_data["organization_ids"] == [first_organization_id, second_organization_id]
+ assert form.cleaned_data["resolved_reason"] == Organization.DeactivationReason.DESKTOP_ABUSE.value
+
+ def test_custom_reason_is_required_when_custom_is_selected(self) -> None:
+ organization_id = uuid4()
+ form = BulkDeactivateOrganizationsForm(
+ {
+ "organization_ids": str(organization_id),
+ "reason": BulkDeactivateOrganizationsForm.CUSTOM_REASON,
+ "custom_reason": "",
+ }
+ )
+
+ assert not form.is_valid()
+ assert "custom_reason" in form.errors
+
+ def test_rejects_invalid_uuid(self) -> None:
+ organization_id = uuid4()
+ form = BulkDeactivateOrganizationsForm(
+ {
+ "organization_ids": f"{organization_id},not-a-uuid",
+ "reason": Organization.DeactivationReason.DESKTOP_ABUSE.value,
+ "custom_reason": "",
+ }
+ )
+
+ assert not form.is_valid()
+ assert "organization_ids" in form.errors
+
+ def test_preview_token_is_bound_to_ids_and_reason(self) -> None:
+ organization_id = uuid4()
+ form = BulkDeactivateOrganizationsForm(
+ {
+ "organization_ids": str(organization_id),
+ "reason": Organization.DeactivationReason.DESKTOP_ABUSE.value,
+ "custom_reason": "",
+ }
+ )
+
+ assert form.is_valid()
+ preview_token = form.preview_token()
+ assert form.preview_token_matches(preview_token)
+
+ changed_form = BulkDeactivateOrganizationsForm(
+ {
+ "organization_ids": str(organization_id),
+ "reason": Organization.DeactivationReason.UNPAID_BALANCE.value,
+ "custom_reason": "",
+ }
+ )
+
+ assert changed_form.is_valid()
+ assert not changed_form.preview_token_matches(preview_token)
+
+ def test_rejects_more_than_max_organization_ids(self) -> None:
+ form = BulkDeactivateOrganizationsForm(
+ {
+ "organization_ids": "\n".join(
+ str(uuid4()) for _ in range(BulkDeactivateOrganizationsForm.MAX_ORGANIZATIONS + 1)
+ ),
+ "reason": Organization.DeactivationReason.DESKTOP_ABUSE.value,
+ "custom_reason": "",
+ }
+ )
+
+ assert not form.is_valid()
+ assert "organization_ids" in form.errors
+
+
+class TestOrganizationAdminBulkDeactivate(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.user.is_staff = True
+ self.user.save()
+ self.factory = RequestFactory()
+ self.admin = OrganizationAdmin(Organization, AdminSite())
+
+ def test_changelist_links_to_organization_tools_module(self) -> None:
+ self.client.force_login(self.user)
+
+ with patch.object(
+ admin.site,
+ "each_context",
+ return_value={
+ "site_title": admin.site.site_title,
+ "site_header": admin.site.site_header,
+ "site_url": admin.site.site_url,
+ "has_permission": True,
+ "available_apps": [],
+ "is_popup": False,
+ "is_nav_sidebar_enabled": False,
+ "log_entries": [],
+ },
+ ):
+ response = self.client.get(reverse("admin:posthog_organization_changelist"))
+
+ assert response.status_code == 200
+ assert b"Organization tools" in response.content
+ assert f"{reverse('admin:index')}#organization-tools".encode() in response.content
+
+ def _post(self, data: dict[str, str]) -> HttpRequest:
+ request = self.factory.post("/admin/posthog/organization/bulk-deactivate/", data)
+ request.user = self.user
+ _attach_messages(request)
+ return request
+
+ def _preview_token(self, organization_ids: str, reason: str, custom_reason: str = "") -> str:
+ form = BulkDeactivateOrganizationsForm(
+ {
+ "organization_ids": organization_ids,
+ "reason": reason,
+ "custom_reason": custom_reason,
+ }
+ )
+ assert form.is_valid()
+ return form.preview_token()
+
+ def test_preview_shows_matched_organizations_and_missing_ids_without_deactivating(self) -> None:
+ missing_id = uuid4()
+ request = self._post(
+ {
+ "organization_ids": f"{self.organization.id}\n{missing_id}",
+ "reason": Organization.DeactivationReason.DESKTOP_ABUSE.value,
+ "custom_reason": "",
+ "preview": "1",
+ }
+ )
+
+ response = self.admin.bulk_deactivate_view(request)
+
+ assert response.status_code == 200
+ self.organization.refresh_from_db()
+ assert self.organization.is_active
+ assert str(self.organization.id).encode() in response.content
+ assert str(missing_id).encode() in response.content
+
+ def test_confirm_deactivates_matched_organizations_with_selected_reason(self) -> None:
+ other_organization = Organization.objects.create(name="Bulk deactivate target")
+ missing_id = uuid4()
+ organization_ids = f"{self.organization.id}\n{other_organization.id}\n{missing_id}"
+ reason = Organization.DeactivationReason.DESKTOP_ABUSE.value
+ request = self._post(
+ {
+ "organization_ids": organization_ids,
+ "reason": reason,
+ "custom_reason": "",
+ "preview_token": self._preview_token(organization_ids, reason),
+ "confirm": "1",
+ }
+ )
+
+ response = self.admin.bulk_deactivate_view(request)
+
+ assert response.status_code == 302
+ for organization in (self.organization, other_organization):
+ organization.refresh_from_db()
+ assert organization.is_active is False
+ assert organization.is_not_active_reason == Organization.DeactivationReason.DESKTOP_ABUSE.value
+
+ def test_confirm_accepts_custom_reason(self) -> None:
+ organization_ids = str(self.organization.id)
+ custom_reason = "Manual review required."
+ request = self._post(
+ {
+ "organization_ids": organization_ids,
+ "reason": BulkDeactivateOrganizationsForm.CUSTOM_REASON,
+ "custom_reason": custom_reason,
+ "preview_token": self._preview_token(
+ organization_ids, BulkDeactivateOrganizationsForm.CUSTOM_REASON, custom_reason
+ ),
+ "confirm": "1",
+ }
+ )
+
+ response = self.admin.bulk_deactivate_view(request)
+
+ assert response.status_code == 302
+ self.organization.refresh_from_db()
+ assert self.organization.is_active is False
+ assert self.organization.is_not_active_reason == "Manual review required."
+
+ def test_confirm_skips_already_inactive_organizations(self) -> None:
+ inactive_organization = Organization.objects.create(
+ name="Already inactive target",
+ is_active=False,
+ is_not_active_reason=Organization.DeactivationReason.COMPLIANCE_REVIEW.value,
+ )
+ organization_ids = f"{self.organization.id}\n{inactive_organization.id}"
+ reason = Organization.DeactivationReason.DESKTOP_ABUSE.value
+ request = self._post(
+ {
+ "organization_ids": organization_ids,
+ "reason": reason,
+ "custom_reason": "",
+ "preview_token": self._preview_token(organization_ids, reason),
+ "confirm": "1",
+ }
+ )
+
+ response = self.admin.bulk_deactivate_view(request)
+
+ assert response.status_code == 302
+ self.organization.refresh_from_db()
+ inactive_organization.refresh_from_db()
+ assert self.organization.is_active is False
+ assert self.organization.is_not_active_reason == Organization.DeactivationReason.DESKTOP_ABUSE.value
+ assert inactive_organization.is_active is False
+ assert inactive_organization.is_not_active_reason == Organization.DeactivationReason.COMPLIANCE_REVIEW.value
+
+ def test_confirm_rechecks_active_state_before_saving_reason(self) -> None:
+ stale_organization = Organization.objects.get(id=self.organization.id)
+ self.organization.is_active = False
+ self.organization.is_not_active_reason = Organization.DeactivationReason.COMPLIANCE_REVIEW.value
+ self.organization.save(update_fields=["is_active", "is_not_active_reason"])
+ organization_ids = str(self.organization.id)
+ reason = Organization.DeactivationReason.DESKTOP_ABUSE.value
+ request = self._post(
+ {
+ "organization_ids": organization_ids,
+ "reason": reason,
+ "custom_reason": "",
+ "preview_token": self._preview_token(organization_ids, reason),
+ "confirm": "1",
+ }
+ )
+
+ with patch.object(self.admin, "_bulk_deactivation_candidates", return_value=([stale_organization], [])):
+ response = self.admin.bulk_deactivate_view(request)
+
+ assert response.status_code == 302
+ self.organization.refresh_from_db()
+ assert self.organization.is_active is False
+ assert self.organization.is_not_active_reason == Organization.DeactivationReason.COMPLIANCE_REVIEW.value
+
+ def test_preview_requires_at_least_one_active_organization(self) -> None:
+ inactive_organization = Organization.objects.create(
+ name="Only inactive target",
+ is_active=False,
+ is_not_active_reason=Organization.DeactivationReason.COMPLIANCE_REVIEW.value,
+ )
+ request = self._post(
+ {
+ "organization_ids": str(inactive_organization.id),
+ "reason": Organization.DeactivationReason.DESKTOP_ABUSE.value,
+ "custom_reason": "",
+ "preview": "1",
+ }
+ )
+
+ response = self.admin.bulk_deactivate_view(request)
+
+ assert response.status_code == 200
+ assert b"All matched organizations are already inactive." in response.content
+
+ def test_confirm_requires_matching_preview_token(self) -> None:
+ other_organization = Organization.objects.create(name="Unpreviewed target")
+ reason = Organization.DeactivationReason.DESKTOP_ABUSE.value
+ request = self._post(
+ {
+ "organization_ids": str(other_organization.id),
+ "reason": reason,
+ "custom_reason": "",
+ "preview_token": self._preview_token(str(self.organization.id), reason),
+ "confirm": "1",
+ }
+ )
+
+ response = self.admin.bulk_deactivate_view(request)
+
+ assert response.status_code == 200
+ assert b"Review the organizations again before deactivating." in response.content
+ self.organization.refresh_from_db()
+ other_organization.refresh_from_db()
+ assert self.organization.is_active
+ assert other_organization.is_active
+
+ def test_view_requires_change_permission(self) -> None:
+ self.user.is_staff = False
+ self.user.save()
+ request = self._post(
+ {
+ "organization_ids": str(self.organization.id),
+ "reason": Organization.DeactivationReason.DESKTOP_ABUSE.value,
+ "custom_reason": "",
+ "preview": "1",
+ }
+ )
+
+ with self.assertRaises(PermissionDenied):
+ self.admin.bulk_deactivate_view(request)
diff --git a/posthog/templates/admin/index.html b/posthog/templates/admin/index.html
index f4f79dc4840b..758cec299451 100644
--- a/posthog/templates/admin/index.html
+++ b/posthog/templates/admin/index.html
@@ -2,6 +2,7 @@
{% block content %}
<div id="content-main">
{% include "admin/app_list.html" with app_list=app_list show_changelinks=True %}
+ {% include "organization_tools/app.html" %}
{% include "redis/app.html" with app_list=app_list %}
{% include "api_key_search/app.html" with app_list=app_list %}
{% include "custom_tools/app.html" with app_list=app_list %}
diff --git a/posthog/templates/admin/posthog/organization/bulk_deactivate.html b/posthog/templates/admin/posthog/organization/bulk_deactivate.html
new file mode 100644
index 000000000000..0cd5ee9bcf28
--- /dev/null
+++ b/posthog/templates/admin/posthog/organization/bulk_deactivate.html
@@ -0,0 +1,114 @@
+{% extends "admin/base_site.html" %}
+{% load i18n admin_urls %}
+
+{% block extrahead %}
+ {{ block.super }}
+ <script nonce="{{ request.csp_nonce }}">
+ document.addEventListener("DOMContentLoaded", () => {
+ const settings = document.getElementById("bulk-deactivate-settings")
+ const customReasonValue = settings ? settings.dataset.customReasonValue : null
+ const reasonSelect = document.getElementById("id_reason")
+ const customReasonField = document.getElementById("id_custom_reason")
+ const customReasonRow = customReasonField ? customReasonField.closest(".form-row") : null
+
+ if (!customReasonValue || !reasonSelect || !customReasonRow) {
+ return
+ }
+
+ const updateCustomReasonVisibility = () => {
+ customReasonRow.style.display = reasonSelect.value === customReasonValue ? "" : "none"
+ }
+
+ reasonSelect.addEventListener("change", updateCustomReasonVisibility)
+ updateCustomReasonVisibility()
+ })
+ </script>
+{% endblock %}
+
+{% block content %}
+<div id="content-main">
+ <h1>{{ title }}</h1>
+ <p>Paste organization IDs, choose the reason users will see, then review the matched organizations before deactivation.</p>
+ <div id="bulk-deactivate-settings" data-custom-reason-value="{{ custom_reason_value }}"></div>
+
+ <form method="post">
+ {% csrf_token %}
+ {{ form.non_field_errors }}
+ <fieldset class="module aligned">
+ {% for field in form %}
+ <div class="form-row field-{{ field.name }}">
+ {{ field.errors }}
+ {{ field.label_tag }} {{ field }}
+ {% if field.help_text %}
+ <div class="help">{{ field.help_text }}</div>
+ {% endif %}
+ </div>
+ {% endfor %}
+ </fieldset>
+
+ {% if preview_organizations %}
+ <input type="hidden" name="preview_token" value="{{ preview_token }}">
+
+ <h2>Review organizations</h2>
+ <p>This will deactivate {{ deactivation_organizations|length }} active organization{{ deactivation_organizations|length|pluralize }} with this reason:</p>
+ <blockquote>{{ resolved_reason }}</blockquote>
+
+ {% if missing_ids %}
+ <p><strong>These IDs were not found and will be skipped:</strong></p>
+ <ul>
+ {% for organization_id in missing_ids %}
+ <li><code>{{ organization_id }}</code></li>
+ {% endfor %}
+ </ul>
+ {% endif %}
+
+ {% if already_inactive_organizations %}
+ <p><strong>These organizations are already inactive and will be skipped:</strong></p>
+ <ul>
+ {% for organization in already_inactive_organizations %}
+ <li><code>{{ organization.id }}</code> {{ organization.name }}</li>
+ {% endfor %}
+ </ul>
+ {% endif %}
+
+ <table>
+ <thead>
+ <tr>
+ <th scope="col">Organization ID</th>
+ <th scope="col">Name</th>
+ <th scope="col">Current status</th>
+ <th scope="col">Current reason</th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for organization in preview_organizations %}
+ <tr>
+ <td><code>{{ organization.id }}</code></td>
+ <td>
+ <a href="{% url 'admin:posthog_organization_change' organization.id %}">
+ {{ organization.name }}
+ </a>
+ </td>
+ <td>{% if organization.is_active %}Active{% else %}Not active{% endif %}</td>
+ <td>{{ organization.is_not_active_reason|default:"-" }}</td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+
+ <div class="submit-row">
+ {% if deactivation_organizations %}
+ <input type="submit" value="Deactivate organizations" class="default" name="confirm">
+ {% endif %}
+ <input type="submit" value="Refresh preview" name="preview">
+ <a href="{% url 'admin:posthog_organization_changelist' %}" class="closelink">Back to organization list</a>
+ </div>
+ {% else %}
+ <div class="submit-row">
+ <input type="submit" value="Preview deactivation" class="default" name="preview">
+ <a href="{% url 'admin:posthog_organization_changelist' %}" class="closelink">Back to organization list</a>
+ </div>
+ {% endif %}
+ </form>
+</div>
+{% endblock %}
diff --git a/posthog/templates/admin/posthog/organization/change_list.html b/posthog/templates/admin/posthog/organization/change_list.html
index 1ea7859b9727..12870f073127 100644
--- a/posthog/templates/admin/posthog/organization/change_list.html
+++ b/posthog/templates/admin/posthog/organization/change_list.html
@@ -2,13 +2,8 @@
{% load i18n admin_urls %}
{% block object-tools-items %}
- {% if show_usage_report_button %}
- <li>
- <a href="{% url 'admin:send-usage-report' %}">Send Usage Report</a>
- </li>
- <li>
- <a href="{% url 'admin:send-ai-observability-usage-report' %}">Send AI observability usage report</a>
- </li>
- {% endif %}
+ <li>
+ <a href="{% url 'admin:index' %}#organization-tools">Organization tools</a>
+ </li>
{{ block.super }}
{% endblock %}
diff --git a/posthog/templates/organization_tools/app.html b/posthog/templates/organization_tools/app.html
new file mode 100644
index 000000000000..60fb5497932a
--- /dev/null
+++ b/posthog/templates/organization_tools/app.html
@@ -0,0 +1,29 @@
+{% if perms.posthog.view_organization %}
+<div id="organization-tools" class="module">
+ <table summary="Organization admin tools">
+ <caption>
+ <a href="{% url 'admin:posthog_organization_changelist' %}" class="section" title="Organization Tools">Organization tools</a>
+ </caption>
+ <tr class="model-sendusagereport">
+ <th scope="row">
+ <a href="{% url 'admin:send-usage-report' %}">Send usage report</a>
+ </th>
+ <td>Queue a usage report for a selected report date</td>
+ </tr>
+ <tr class="model-sendaioobservabilityusagereport">
+ <th scope="row">
+ <a href="{% url 'admin:send-ai-observability-usage-report' %}">Send AI observability usage report</a>
+ </th>
+ <td>Queue an AI observability usage report for a selected report date</td>
+ </tr>
+ {% if perms.posthog.change_organization %}
+ <tr class="model-bulkdeactivateorganizations">
+ <th scope="row">
+ <a href="{% url 'admin:organization_bulk_deactivate' %}">Bulk deactivate organizations</a>
+ </th>
+ <td>Deactivate organizations from pasted IDs after a preview step</td>
+ </tr>
+ {% endif %}
+ </table>
+</div>
+{% endif %}