Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

List every search API key holder on the paying users page

Claude2410d0b29d22
diff --git a/mwmbl/admin_views.py b/mwmbl/admin_views.py
index 442474c..99a14b4 100644
--- a/mwmbl/admin_views.py
+++ b/mwmbl/admin_views.py
@@ -22,6 +22,7 @@ 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.db.models import F, OuterRef, Q, Subquery
from django.shortcuts import render
from redis import RedisError
@@ -37,7 +38,7 @@ from mwmbl.indexer.blacklist_snapshot import (
)
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.models import ApiKey, Membership, MwmblUser
from mwmbl.utils import utc_today
logger = getLogger(__name__)
@@ -179,44 +180,60 @@ def blacklist_status_view(request):
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.
+def _api_users() -> list[dict]:
+ """Users holding a search API key, plus anyone with a Polar usage subscription.
- 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.
+ Subscribers are included even without a key, because they are still being billed for
+ the month's usage until it is reported. A subscriber at $0 has given card details but
+ is still hard-capped at the free allowance.
"""
- billings = list(
- UserBilling.objects.exclude(polar_subscription_id="")
- .select_related("user")
- .order_by("-max_monthly_spend_cents")
+ last_key_use = (
+ ApiKey.objects.filter(user=OuterRef("pk"), scopes__contains=[ApiKey.Scope.SEARCH])
+ .order_by(F("last_used").desc(nulls_last=True))
+ .values("last_used")[:1]
+ )
+ users = list(
+ MwmblUser.objects.filter(
+ Q(apikey__scopes__contains=[ApiKey.Scope.SEARCH]) | Q(billing__polar_subscription_id__gt="")
+ )
+ .distinct()
+ .select_related("billing")
+ .annotate(last_key_use=Subquery(last_key_use))
)
# 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_keys = {user.id: quota._monthly_key(user.id) for user in users}
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:
+ api_users = []
+ for user in users:
+ usage = usage_by_key.get(usage_keys[user.id], 0)
+ billing = getattr(user, "billing", None)
+ subscribed = billing is not None and billing.polar_subscription_id != ""
+ spend_cents = billing.max_monthly_spend_cents if billing else 0
+ if not subscribed:
+ status = "no subscription"
+ elif spend_cents == 0:
status = "free"
elif billing.cancel_at_period_end:
status = "canceling"
else:
status = "active"
- customers.append(
+ api_users.append(
{
- "user": billing.user,
+ "user": user,
"status": status,
+ "subscribed": subscribed,
"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,
+ "last_key_use": user.last_key_use,
+ "current_period_end": billing.current_period_end if billing else None,
+ "polar_customer_id": billing.polar_customer_id if billing else "",
}
)
- return customers
+ api_users.sort(key=lambda api_user: (api_user["estimated_cost_cents"], api_user["usage"]), reverse=True)
+ return api_users
def _members() -> list[dict]:
@@ -259,15 +276,16 @@ def _tier_summary(members: list[dict]) -> list[dict]:
@staff_member_required
def paying_users_view(request):
- api_customers = _api_customers()
+ api_users = _api_users()
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),
+ "api_users": api_users,
+ "api_subscribed_count": sum(1 for api_user in api_users if api_user["subscribed"]),
+ "api_billed_count": sum(1 for api_user in api_users if api_user["estimated_cost_cents"] > 0),
+ "api_estimated_revenue_cents": sum(api_user["estimated_cost_cents"] for api_user in api_users),
"members": members,
"tier_summary": tier_summary,
"membership_revenue_pence": sum(tier["monthly_revenue_pence"] for tier in tier_summary),
diff --git a/mwmbl/templates/admin/mwmbl_index.html b/mwmbl/templates/admin/mwmbl_index.html
index b2e3d12..890e2b1 100644
--- a/mwmbl/templates/admin/mwmbl_index.html
+++ b/mwmbl/templates/admin/mwmbl_index.html
@@ -16,7 +16,7 @@
</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>
+ <td>API users and members, their quotas, usage and what they pay.</td>
</tr>
</table>
</div>
diff --git a/mwmbl/templates/admin/paying_users.html b/mwmbl/templates/admin/paying_users.html
index 6a31868..d7aa850 100644
--- a/mwmbl/templates/admin/paying_users.html
+++ b/mwmbl/templates/admin/paying_users.html
@@ -24,8 +24,8 @@
<h2>Summary</h2>
<table>
<tr>
- <td>API subscribers</td>
- <td class="num">{{ api_customers|length }} ({{ api_billed_count }} billed this month)</td>
+ <td>API users</td>
+ <td class="num">{{ api_users|length }} ({{ api_subscribed_count }} subscribed, {{ api_billed_count }} billed this month)</td>
</tr>
<tr>
<td>API estimated revenue this month</td>
@@ -43,9 +43,9 @@
</div>
<div class="module">
- <h2>API customers</h2>
+ <h2>API users</h2>
<p class="note">
- Users with a Polar usage subscription. The first {{ free_keyed_monthly_limit }} requests a
+ Users with a search API key or 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>
@@ -59,25 +59,27 @@
<th class="num">Monthly cap</th>
<th class="num">Usage</th>
<th class="num">Estimated cost</th>
+ <th>Key last used</th>
<th>Period end</th>
<th>Polar customer</th>
</tr>
</thead>
<tbody>
- {% for customer in api_customers %}
+ {% for api_user in api_users %}
<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>
+ <td><a href="{% url 'admin:mwmbl_mwmbluser_change' api_user.user.pk %}">{{ api_user.user.username }}</a></td>
+ <td>{{ api_user.user.email }}</td>
+ <td>{{ api_user.status }}</td>
+ <td class="num">{{ api_user.max_monthly_spend_cents|minor_units:"$" }}</td>
+ <td class="num">{{ api_user.monthly_cap }}</td>
+ <td class="num{% if api_user.usage >= api_user.monthly_cap %} over{% endif %}">{{ api_user.usage }}</td>
+ <td class="num">{{ api_user.estimated_cost_cents|minor_units:"$" }}</td>
+ <td>{{ api_user.last_key_use|default:"-" }}</td>
+ <td>{{ api_user.current_period_end|default:"-" }}</td>
+ <td>{{ api_user.polar_customer_id|default:"-" }}</td>
</tr>
{% empty %}
- <tr><td colspan="9">No API subscribers.</td></tr>
+ <tr><td colspan="10">No API users.</td></tr>
{% endfor %}
</tbody>
</table>
diff --git a/test/test_admin_paying_users.py b/test/test_admin_paying_users.py
index e044c96..51254d1 100644
--- a/test/test_admin_paying_users.py
+++ b/test/test_admin_paying_users.py
@@ -5,7 +5,7 @@ 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.models import ApiKey, Membership, UserBilling
from mwmbl.templatetags.money import minor_units
User = get_user_model()
@@ -41,30 +41,51 @@ 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 API users." in response.content
assert b"No members." in response.content
-def test_api_customer_quota_usage_and_cost(staff_client):
+def test_api_subscriber_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"]
+ [row] = response.context["api_users"]
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_subscribed_count"] == 1
assert response.context["api_billed_count"] == 1
assert response.context["api_estimated_revenue_cents"] == 500
+
+
+def test_search_key_holders_without_a_subscription_are_listed(staff_client):
+ key_holder = User.objects.create_user(username="key_holder")
+ ApiKey.objects.create(user=key_holder, key="hash_1", scopes=[ApiKey.Scope.SEARCH])
+ ApiKey.objects.create(user=key_holder, key="hash_2", scopes=[ApiKey.Scope.SEARCH, ApiKey.Scope.CRAWL])
+ crawler = User.objects.create_user(username="crawler_only")
+ ApiKey.objects.create(user=crawler, key="hash_3", scopes=[ApiKey.Scope.CRAWL])
+ # A billing row with no subscription, as a spend-limit request without checkout leaves.
+ UserBilling.objects.create(user=User.objects.create_user(username="never_paid"))
+ quota.increment_monthly(key_holder.id)
+
+ response = staff_client.get(PAYING_USERS_URL)
+
+ [row] = response.context["api_users"]
+ assert row["user"] == key_holder
+ assert row["status"] == "no subscription"
+ assert row["monthly_cap"] == 2_000
+ assert row["usage"] == 1
+ assert row["estimated_cost_cents"] == 0
+ assert response.context["api_subscribed_count"] == 0
+ assert b"crawler_only" not in response.content
assert b"never_paid" not in response.content