Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Add a paying users admin dashboard

Claude73cc1b947b4c
diff --git a/mwmbl/admin_views.py b/mwmbl/admin_views.py
index bb92f17..442474c 100644
--- a/mwmbl/admin_views.py
+++ b/mwmbl/admin_views.py
@@ -1,4 +1,6 @@
-"""Admin-only visibility on the blacklist filtering state that lives in Redis.
+"""Admin-only status pages: the blacklist filtering state in Redis, and paying users.
+
+The blacklist page gives visibility on the blacklist filtering state that lives in Redis.
Retrieval filtering, the snapshot refresh and the index purge are three processes talking
to each other through Redis keys, and none of that state is reachable from the Django
@@ -19,9 +21,11 @@ from logging import getLogger
from background_task.models import CompletedTask, Task
from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
+from django.core.cache import cache
from django.shortcuts import render
from redis import RedisError
+from mwmbl import pricing, quota
from mwmbl.crawler.stats import BLACKLISTED_REMOVED_COUNT_KEY
from mwmbl.curated_domains import get_curated_domains
from mwmbl.indexer import blacklist_snapshot, purge_queue
@@ -32,6 +36,8 @@ from mwmbl.indexer.blacklist_snapshot import (
get_snapshot_blacklist,
)
from mwmbl.indexer.purge_queue import MAX_QUEUE_SIZE, PURGE_QUEUE_KEY, peek_purge_queue
+from mwmbl.membership import TIERS, combined_search_monthly_limit
+from mwmbl.models import Membership, UserBilling
from mwmbl.utils import utc_today
logger = getLogger(__name__)
@@ -171,3 +177,101 @@ def blacklist_status_view(request):
context["tasks"] = _task_status()
return render(request, "admin/blacklist_status.html", context)
+
+
+def _api_customers() -> list[dict]:
+ """Users with a Polar usage subscription, whether or not their spend limit is above $0.
+
+ A subscriber at $0 has given card details but is still hard-capped at the free
+ allowance, which is worth seeing next to the ones actually being billed.
+ """
+ billings = list(
+ UserBilling.objects.exclude(polar_subscription_id="")
+ .select_related("user")
+ .order_by("-max_monthly_spend_cents")
+ )
+ # One round trip for every counter rather than one per row.
+ usage_keys = {billing.user_id: quota._monthly_key(billing.user_id) for billing in billings}
+ usage_by_key = cache.get_many(list(usage_keys.values()))
+
+ customers = []
+ for billing in billings:
+ usage = usage_by_key.get(usage_keys[billing.user_id], 0)
+ spend_cents = billing.max_monthly_spend_cents
+ if spend_cents == 0:
+ status = "free"
+ elif billing.cancel_at_period_end:
+ status = "canceling"
+ else:
+ status = "active"
+ customers.append(
+ {
+ "user": billing.user,
+ "status": status,
+ "max_monthly_spend_cents": spend_cents,
+ "monthly_cap": pricing.effective_monthly_request_cap(spend_cents),
+ "usage": usage,
+ "estimated_cost_cents": pricing.estimated_cost_cents(usage),
+ "current_period_end": billing.current_period_end,
+ "polar_customer_id": billing.polar_customer_id,
+ }
+ )
+ return customers
+
+
+def _members() -> list[dict]:
+ price_by_tier = {tier_info.tier.value: tier_info.monthly_price_pence for tier_info in TIERS}
+ memberships = list(Membership.objects.select_related("user").order_by("-started"))
+ usage_keys = {
+ membership.user_id: quota._combined_search_monthly_key(membership.user_id) for membership in memberships
+ }
+ usage_by_key = cache.get_many(list(usage_keys.values()))
+
+ return [
+ {
+ "user": membership.user,
+ "tier": membership.get_tier_display(),
+ "monthly_price_pence": price_by_tier[membership.tier],
+ "combined_search_limit": combined_search_monthly_limit(membership.tier),
+ "combined_search_usage": usage_by_key.get(usage_keys[membership.user_id], 0),
+ "current_period_end": membership.current_period_end,
+ "cancel_at_period_end": membership.cancel_at_period_end,
+ "started": membership.started,
+ }
+ for membership in memberships
+ ]
+
+
+def _tier_summary(members: list[dict]) -> list[dict]:
+ summary = []
+ for tier_info in TIERS:
+ tier_members = [member for member in members if member["tier"] == tier_info.tier.label]
+ summary.append(
+ {
+ "tier": tier_info.tier.label,
+ "count": len(tier_members),
+ "monthly_price_pence": tier_info.monthly_price_pence,
+ "monthly_revenue_pence": len(tier_members) * tier_info.monthly_price_pence,
+ }
+ )
+ return summary
+
+
+@staff_member_required
+def paying_users_view(request):
+ api_customers = _api_customers()
+ members = _members()
+ tier_summary = _tier_summary(members)
+ # Members still paying out the current period after cancelling are counted: they have paid.
+ context = {
+ "title": "Paying users",
+ "api_customers": api_customers,
+ "api_billed_count": sum(1 for customer in api_customers if customer["estimated_cost_cents"] > 0),
+ "api_estimated_revenue_cents": sum(customer["estimated_cost_cents"] for customer in api_customers),
+ "members": members,
+ "tier_summary": tier_summary,
+ "membership_revenue_pence": sum(tier["monthly_revenue_pence"] for tier in tier_summary),
+ "free_keyed_monthly_limit": pricing.FREE_KEYED_MONTHLY_LIMIT,
+ "price_per_1000_queries_cents": pricing.PRICE_PER_1000_QUERIES_CENTS,
+ }
+ return render(request, "admin/paying_users.html", context)
diff --git a/mwmbl/templates/admin/mwmbl_index.html b/mwmbl/templates/admin/mwmbl_index.html
index be54f21..b2e3d12 100644
--- a/mwmbl/templates/admin/mwmbl_index.html
+++ b/mwmbl/templates/admin/mwmbl_index.html
@@ -14,6 +14,10 @@
<th scope="row"><a href="{% url 'blacklist_status' %}">Blacklist status</a></th>
<td>The published snapshot, the purge queue and the tasks that maintain them.</td>
</tr>
+ <tr>
+ <th scope="row"><a href="{% url 'paying_users' %}">Paying users</a></th>
+ <td>API customers and members, their quotas, usage and what they pay.</td>
+ </tr>
</table>
</div>
{% endblock %}
diff --git a/mwmbl/templates/admin/paying_users.html b/mwmbl/templates/admin/paying_users.html
new file mode 100644
index 0000000..6a31868
--- /dev/null
+++ b/mwmbl/templates/admin/paying_users.html
@@ -0,0 +1,151 @@
+{% extends "admin/base_site.html" %}
+{% load money %}
+
+{% block title %}Paying users | {{ site_title|default:"Django site admin" }}{% endblock %}
+
+{% block breadcrumbs %}
+ <div class="breadcrumbs">
+ <a href="{% url 'admin:index' %}">Home</a>
+ &rsaquo; Paying users
+ </div>
+{% endblock %}
+
+{% block content %}
+ <style>
+ .paying-users table { width: 100%; margin-bottom: 10px; }
+ .paying-users td.num, .paying-users th.num { text-align: right; }
+ .paying-users .over { color: #ba2121; font-weight: bold; }
+ .paying-users .note { color: #666; font-size: 0.9em; }
+ </style>
+
+ <div id="content-main" class="paying-users">
+
+ <div class="module">
+ <h2>Summary</h2>
+ <table>
+ <tr>
+ <td>API subscribers</td>
+ <td class="num">{{ api_customers|length }} ({{ api_billed_count }} billed this month)</td>
+ </tr>
+ <tr>
+ <td>API estimated revenue this month</td>
+ <td class="num">{{ api_estimated_revenue_cents|minor_units:"$" }}</td>
+ </tr>
+ <tr>
+ <td>Members</td>
+ <td class="num">{{ members|length }}</td>
+ </tr>
+ <tr>
+ <td>Membership revenue per month</td>
+ <td class="num">{{ membership_revenue_pence|minor_units:"£" }}</td>
+ </tr>
+ </table>
+ </div>
+
+ <div class="module">
+ <h2>API customers</h2>
+ <p class="note">
+ Users with a Polar usage subscription. The first {{ free_keyed_monthly_limit }} requests a
+ month are free; beyond that they pay {{ price_per_1000_queries_cents|minor_units:"$" }} per
+ 1,000, up to their spend limit. Usage is this calendar month's live count.
+ </p>
+ <table>
+ <thead>
+ <tr>
+ <th>User</th>
+ <th>Email</th>
+ <th>Status</th>
+ <th class="num">Spend limit</th>
+ <th class="num">Monthly cap</th>
+ <th class="num">Usage</th>
+ <th class="num">Estimated cost</th>
+ <th>Period end</th>
+ <th>Polar customer</th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for customer in api_customers %}
+ <tr>
+ <td><a href="{% url 'admin:mwmbl_mwmbluser_change' customer.user.pk %}">{{ customer.user.username }}</a></td>
+ <td>{{ customer.user.email }}</td>
+ <td>{{ customer.status }}</td>
+ <td class="num">{{ customer.max_monthly_spend_cents|minor_units:"$" }}</td>
+ <td class="num">{{ customer.monthly_cap }}</td>
+ <td class="num{% if customer.usage >= customer.monthly_cap %} over{% endif %}">{{ customer.usage }}</td>
+ <td class="num">{{ customer.estimated_cost_cents|minor_units:"$" }}</td>
+ <td>{{ customer.current_period_end|default:"-" }}</td>
+ <td>{{ customer.polar_customer_id|default:"-" }}</td>
+ </tr>
+ {% empty %}
+ <tr><td colspan="9">No API subscribers.</td></tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ </div>
+
+ <div class="module">
+ <h2>Members by tier</h2>
+ <table>
+ <thead>
+ <tr>
+ <th>Tier</th>
+ <th class="num">Members</th>
+ <th class="num">Price per month</th>
+ <th class="num">Revenue per month</th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for tier in tier_summary %}
+ <tr>
+ <td>{{ tier.tier }}</td>
+ <td class="num">{{ tier.count }}</td>
+ <td class="num">{{ tier.monthly_price_pence|minor_units:"£" }}</td>
+ <td class="num">{{ tier.monthly_revenue_pence|minor_units:"£" }}</td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ </div>
+
+ <div class="module">
+ <h2>Members</h2>
+ <p class="note">
+ Combined Search usage is this calendar month's live count against the tier's monthly quota.
+ Members who have cancelled still count until their period ends.
+ </p>
+ <table>
+ <thead>
+ <tr>
+ <th>User</th>
+ <th>Email</th>
+ <th>Tier</th>
+ <th class="num">Price per month</th>
+ <th class="num">Combined Search quota</th>
+ <th class="num">Usage</th>
+ <th>Period end</th>
+ <th>Cancelling</th>
+ <th>Started</th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for member in members %}
+ <tr>
+ <td><a href="{% url 'admin:mwmbl_mwmbluser_change' member.user.pk %}">{{ member.user.username }}</a></td>
+ <td>{{ member.user.email }}</td>
+ <td>{{ member.tier }}</td>
+ <td class="num">{{ member.monthly_price_pence|minor_units:"£" }}</td>
+ <td class="num">{{ member.combined_search_limit }}</td>
+ <td class="num{% if member.combined_search_usage >= member.combined_search_limit %} over{% endif %}">{{ member.combined_search_usage }}</td>
+ <td>{{ member.current_period_end|default:"-" }}</td>
+ <td>{{ member.cancel_at_period_end|yesno }}</td>
+ <td>{{ member.started }}</td>
+ </tr>
+ {% empty %}
+ <tr><td colspan="9">No members.</td></tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ </div>
+
+ </div>
+{% endblock %}
diff --git a/mwmbl/templatetags/money.py b/mwmbl/templatetags/money.py
new file mode 100644
index 0000000..36207c5
--- /dev/null
+++ b/mwmbl/templatetags/money.py
@@ -0,0 +1,10 @@
+from django import template
+
+register = template.Library()
+
+
+def minor_units(amount: int, symbol: str) -> str:
+ """Format an amount held in cents or pence, e.g. 2500 with "$" as "$25.00"."""
+ major, minor = divmod(amount, 100)
+ return f"{symbol}{major:,}.{minor:02d}"
diff --git a/mwmbl/urls.py b/mwmbl/urls.py
index 96e14eb..2fd16b0 100644
--- a/mwmbl/urls.py
+++ b/mwmbl/urls.py
@@ -21,7 +21,7 @@ from django.urls import include, path
from django.views.generic import RedirectView
import mwmbl.crawler.app as crawler
-from mwmbl.admin_views import blacklist_status_view
+from mwmbl.admin_views import blacklist_status_view, paying_users_view
from mwmbl.api import api as v1_api
from mwmbl.api import register_routers, v2_api
from mwmbl.search_setup import combined_ranker, ranker, tiny_index
@@ -56,6 +56,7 @@ urlpatterns = [
# Before admin.site.urls so the admin catch-all does not shadow it. Access is gated by
# staff_member_required on the view, matching the rest of the admin.
path("admin/blacklist-status/", blacklist_status_view, name="blacklist_status"),
+ path("admin/paying-users/", paying_users_view, name="paying_users"),
path("admin/", admin.site.urls),
path("accounts/", include("allauth.urls")),
path("", index, name="index"),
diff --git a/test/test_admin_paying_users.py b/test/test_admin_paying_users.py
new file mode 100644
index 0000000..e044c96
--- /dev/null
+++ b/test/test_admin_paying_users.py
@@ -0,0 +1,93 @@
+"""Tests for the paying users admin page (mwmbl.admin_views.paying_users_view)."""
+
+import pytest
+from django.contrib.auth import get_user_model
+from django.core.cache import cache
+
+from mwmbl import quota
+from mwmbl.models import Membership, UserBilling
+from mwmbl.templatetags.money import minor_units
+
+User = get_user_model()
+
+PAYING_USERS_URL = "/admin/paying-users/"
+
+
[email protected](autouse=True)
+def clear_cache():
+ cache.clear()
+ yield
+ cache.clear()
+
+
+def staff_client(client, db):
+ user = User.objects.create_user(username="staff_member_1", password="correctpassword", is_staff=True)
+ client.force_login(user)
+ return client
+
+
+def test_requires_staff(client, db):
+ user = User.objects.create_user(username="not_staff", password="correctpassword")
+ client.force_login(user)
+
+ response = client.get(PAYING_USERS_URL)
+
+ assert response.status_code == 302
+ assert "/admin/login/" in response["Location"]
+
+
+def test_empty_page_renders(staff_client):
+ response = staff_client.get(PAYING_USERS_URL)
+
+ assert response.status_code == 200
+ assert b"No API subscribers." in response.content
+ assert b"No members." in response.content
+
+
+def test_api_customer_quota_usage_and_cost(staff_client):
+ customer = User.objects.create_user(username="api_customer", email="[email protected]")
+ UserBilling.objects.create(
+ user=customer, polar_customer_id="cus_1", polar_subscription_id="sub_1", max_monthly_spend_cents=1_000
+ )
+ for _ in range(3_000):
+ quota.increment_monthly(customer.id)
+ # Never subscribed, so not a customer at all.
+ UserBilling.objects.create(user=User.objects.create_user(username="never_paid"))
+
+ response = staff_client.get(PAYING_USERS_URL)
+
+ [row] = response.context["api_customers"]
+ assert row["user"] == customer
+ assert row["status"] == "active"
+ assert row["monthly_cap"] == 4_000
+ assert row["usage"] == 3_000
+ assert row["estimated_cost_cents"] == 500
+ assert response.context["api_billed_count"] == 1
+ assert response.context["api_estimated_revenue_cents"] == 500
+ assert b"never_paid" not in response.content
+
+
+def test_members_quota_usage_and_revenue(staff_client):
+ sapling = User.objects.create_user(username="sapling_member")
+ Membership.objects.create(user=sapling, tier="sapling", polar_subscription_id="sub_sapling")
+ canopy = User.objects.create_user(username="canopy_member")
+ Membership.objects.create(user=canopy, tier="canopy", polar_subscription_id="sub_canopy", cancel_at_period_end=True)
+ quota.increment_monthly_combined_search(sapling.id)
+
+ response = staff_client.get(PAYING_USERS_URL)
+
+ members = {member["user"].username: member for member in response.context["members"]}
+ assert members["sapling_member"]["combined_search_limit"] == 1_500
+ assert members["sapling_member"]["combined_search_usage"] == 1
+ assert members["sapling_member"]["monthly_price_pence"] == 500
+ assert members["canopy_member"]["combined_search_usage"] == 0
+ counts = {tier["tier"]: tier["count"] for tier in response.context["tier_summary"]}
+ assert counts == {"Sprout": 0, "Sapling": 1, "Canopy": 1}
+ assert response.context["membership_revenue_pence"] == 2_500
+ assert "£25.00".encode() in response.content
+
+
+def test_minor_units():
+ assert minor_units(0, "$") == "$0.00"
+ assert minor_units(123_456, "£") == "£1,234.56"