Skip to content

Commit

Permalink
feat: add a send-usage-report button in the django admin
Browse files Browse the repository at this point in the history
  • Loading branch information
patricio-posthog committed Oct 25, 2024
1 parent 0ad1b5f commit 73ef3ff
Show file tree
Hide file tree
Showing 6 changed files with 104 additions and 2 deletions.
2 changes: 1 addition & 1 deletion latest_migrations.manifest
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ contenttypes: 0002_remove_content_type_name
ee: 0016_rolemembership_organization_member
otp_static: 0002_throttling
otp_totp: 0002_auto_20190420_0723
posthog: 0499_hog_function_type
posthog: 0500_create_group_billing_team
sessions: 0001_initial
social_django: 0010_uid_db_index
two_factor: 0007_auto_20201201_1019
48 changes: 48 additions & 0 deletions posthog/admin/admins/organization_admin.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,29 @@
from django.conf import settings
from django.contrib import admin
from django.core.management import call_command
from django.utils.html import format_html
from django.urls import reverse
from posthog.admin.inlines.organization_member_inline import OrganizationMemberInline
from posthog.admin.inlines.project_inline import ProjectInline
from posthog.admin.inlines.team_inline import TeamInline
from posthog.admin.paginators.no_count_paginator import NoCountPaginator

from posthog.models.organization import Organization
from django.urls import path
from django.shortcuts import render, redirect
from django.contrib import messages
from django import forms
from django.utils import timezone


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():
raise forms.ValidationError("The date cannot be in the future.")
return report_date


class OrganizationAdmin(admin.ModelAdmin):
Expand Down Expand Up @@ -69,3 +86,34 @@ def usage_posthog(self, organization: Organization):
'<a target="_blank" href="/insights/new?insight=TRENDS&interval=day&display=ActionsLineGraph&events=%5B%7B%22id%22%3A%22%24pageview%22%2C%22name%22%3A%22%24pageview%22%2C%22type%22%3A%22events%22%2C%22order%22%3A0%2C%22math%22%3A%22dau%22%7D%5D&properties=%5B%7B%22key%22%3A%22organization_id%22%2C%22value%22%3A%22{}%22%2C%22operator%22%3A%22exact%22%2C%22type%22%3A%22person%22%7D%5D&actions=%5B%5D&new_entity=%5B%5D">See usage on PostHog →</a>',
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"
),
]
return custom_urls + urls

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 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)
2 changes: 1 addition & 1 deletion posthog/admin/admins/user_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class UserAdmin(DjangoUserAdmin):
},
),
(_("Personal info"), {"fields": ("first_name", "last_name")}),
(_("Permissions"), {"fields": ("is_active", "is_staff")}),
(_("Permissions"), {"fields": ("is_active", "is_staff", "groups")}),
(_("Important dates"), {"fields": ("last_login", "date_joined")}),
(_("Toolbar authentication"), {"fields": ("temporary_token",)}),
)
Expand Down
22 changes: 22 additions & 0 deletions posthog/migrations/0500_create_group_billing_team.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Generated by Django 4.2.15 on 2024-10-25 19:31

from django.db import migrations
from django.contrib.auth.models import Group


def create_billing_team_group(apps, schema_editor):
Group.objects.get_or_create(name="Billing Team")


def reverse_create_billing_team_group(apps, schema_editor):
Group.objects.filter(name="Billing Team").delete()


class Migration(migrations.Migration):
dependencies = [
("posthog", "0499_hog_function_type"),
]

operations = [
migrations.RunPython(create_billing_team_group, reverse_create_billing_team_group),
]
11 changes: 11 additions & 0 deletions posthog/templates/admin/posthog/organization/change_list.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{% extends "admin/change_list.html" %}
{% 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>
{% endif %}
{{ block.super }}
{% endblock %}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{% extends "admin/base_site.html" %}
{% load i18n admin_urls %}

{% block content %}
<div id="content-main">
<form method="post">
{% 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 %}

0 comments on commit 73ef3ff

Please sign in to comment.