Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Show Seed Search usage by signed-in users on the paying users page

Claudea064772ff139
diff --git a/mwmbl/admin_views.py b/mwmbl/admin_views.py
index 99a14b4..4036417 100644
--- a/mwmbl/admin_views.py
+++ b/mwmbl/admin_views.py
@@ -274,6 +274,44 @@ def _tier_summary(members: list[dict]) -> list[dict]:
return summary
+SEED_SEARCH_TOP_USERS = 25
+
+
+def _seed_search_stats() -> dict:
+ """This month's Seed Search (Combined Search) usage by signed-in users, by tier.
+
+ Combined Search refuses API keys, so every counter belongs to a signed-in web user.
+ "free" is everyone without a membership, matching COMBINED_SEARCH_MONTHLY_LIMITS.
+ """
+ counts = quota.get_all_monthly_combined_search_counts()
+ tier_by_user = dict(Membership.objects.filter(user_id__in=counts).values_list("user_id", "tier"))
+ users_by_id = MwmblUser.objects.in_bulk(list(counts))
+
+ tier_names = ["free"] + [tier_info.tier.value for tier_info in TIERS]
+ by_tier = {tier: {"tier": tier, "users": 0, "queries": 0, "at_limit": 0} for tier in tier_names}
+ rows = []
+ for user_id, count in counts.items():
+ tier = tier_by_user.get(user_id, "free")
+ limit = combined_search_monthly_limit(tier)
+ tier_stats = by_tier[tier]
+ tier_stats["users"] += 1
+ tier_stats["queries"] += count
+ tier_stats["at_limit"] += count >= limit
+ rows.append({"user": users_by_id[user_id], "tier": tier, "usage": count, "limit": limit})
+
+ for tier_stats in by_tier.values():
+ tier_stats["limit"] = combined_search_monthly_limit(tier_stats["tier"])
+
+ rows.sort(key=lambda row: row["usage"], reverse=True)
+ return {
+ "users": len(counts),
+ "queries": sum(counts.values()),
+ "at_limit": sum(tier_stats["at_limit"] for tier_stats in by_tier.values()),
+ "by_tier": list(by_tier.values()),
+ "top_users": rows[:SEED_SEARCH_TOP_USERS],
+ }
+
+
@staff_member_required
def paying_users_view(request):
api_users = _api_users()
@@ -288,6 +326,7 @@ def paying_users_view(request):
"api_estimated_revenue_cents": sum(api_user["estimated_cost_cents"] for api_user in api_users),
"members": members,
"tier_summary": tier_summary,
+ "seed_search": _seed_search_stats(),
"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,
diff --git a/mwmbl/quota.py b/mwmbl/quota.py
index 9fd4f47..facf781 100644
--- a/mwmbl/quota.py
+++ b/mwmbl/quota.py
@@ -144,6 +144,19 @@ def decrement_monthly_combined_search(user_id: int) -> None:
pass
+def get_all_monthly_combined_search_counts() -> dict[int, int]:
+ """This month's combined-search count for every user who has used it, by user id.
+
+ Scans the keyspace via django-redis, so it is for admin pages and background jobs, not
+ the search path.
+ """
+ now = datetime.now(timezone.utc)
+ keys = list(cache.iter_keys(f"combined_search:monthly:*:{now.year}:{now.month:02d}"))
+ counts_by_key = cache.get_many(keys)
+ # Keys are combined_search:monthly:<user_id>:<year>:<month>.
+ return {int(key.split(":")[2]): count for key, count in counts_by_key.items()}
+
+
# ---------------------------------------------------------------------------
# Key scanning (used by background jobs only — requires django-redis)
# ---------------------------------------------------------------------------
diff --git a/mwmbl/templates/admin/mwmbl_index.html b/mwmbl/templates/admin/mwmbl_index.html
index 890e2b1..f4b3fa2 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 users and members, their quotas, usage and what they pay.</td>
+ <td>API users and members, their quotas, usage and what they pay, and Seed Search usage.</td>
</tr>
</table>
</div>
diff --git a/mwmbl/templates/admin/paying_users.html b/mwmbl/templates/admin/paying_users.html
index d7aa850..2f0e47b 100644
--- a/mwmbl/templates/admin/paying_users.html
+++ b/mwmbl/templates/admin/paying_users.html
@@ -7,6 +7,64 @@
<div class="breadcrumbs">
<a href="{% url 'admin:index' %}">Home</a>
&rsaquo; Paying users
+ <div class="module">
+ <h2>Seed Search this month</h2>
+ <p class="note">
+ Seed Search (Combined Search) is only available to signed-in users. Counts are this
+ calendar month's live counters; "free" is everyone without a membership.
+ {{ seed_search.users }} users have made {{ seed_search.queries }} queries, and
+ {{ seed_search.at_limit }} have reached their quota.
+ </p>
+ <table>
+ <thead>
+ <tr>
+ <th>Tier</th>
+ <th class="num">Monthly quota</th>
+ <th class="num">Users</th>
+ <th class="num">Queries</th>
+ <th class="num">At quota</th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for tier in seed_search.by_tier %}
+ <tr>
+ <td>{{ tier.tier|capfirst }}</td>
+ <td class="num">{{ tier.limit }}</td>
+ <td class="num">{{ tier.users }}</td>
+ <td class="num">{{ tier.queries }}</td>
+ <td class="num">{{ tier.at_limit }}</td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ </div>
+
+ <div class="module">
+ <h2>Top Seed Search users this month</h2>
+ <table>
+ <thead>
+ <tr>
+ <th>User</th>
+ <th>Tier</th>
+ <th class="num">Usage</th>
+ <th class="num">Quota</th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for row in seed_search.top_users %}
+ <tr>
+ <td><a href="{% url 'admin:mwmbl_mwmbluser_change' row.user.pk %}">{{ row.user.username }}</a></td>
+ <td>{{ row.tier|capfirst }}</td>
+ <td class="num{% if row.usage >= row.limit %} over{% endif %}">{{ row.usage }}</td>
+ <td class="num">{{ row.limit }}</td>
+ </tr>
+ {% empty %}
+ <tr><td colspan="4">No Seed Search queries this month.</td></tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ </div>
+
</div>
{% endblock %}
@@ -149,5 +207,63 @@
</table>
</div>
+ <div class="module">
+ <h2>Seed Search this month</h2>
+ <p class="note">
+ Seed Search (Combined Search) is only available to signed-in users. Counts are this
+ calendar month's live counters; "free" is everyone without a membership.
+ {{ seed_search.users }} users have made {{ seed_search.queries }} queries, and
+ {{ seed_search.at_limit }} have reached their quota.
+ </p>
+ <table>
+ <thead>
+ <tr>
+ <th>Tier</th>
+ <th class="num">Monthly quota</th>
+ <th class="num">Users</th>
+ <th class="num">Queries</th>
+ <th class="num">At quota</th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for tier in seed_search.by_tier %}
+ <tr>
+ <td>{{ tier.tier|capfirst }}</td>
+ <td class="num">{{ tier.limit }}</td>
+ <td class="num">{{ tier.users }}</td>
+ <td class="num">{{ tier.queries }}</td>
+ <td class="num">{{ tier.at_limit }}</td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ </div>
+
+ <div class="module">
+ <h2>Top Seed Search users this month</h2>
+ <table>
+ <thead>
+ <tr>
+ <th>User</th>
+ <th>Tier</th>
+ <th class="num">Usage</th>
+ <th class="num">Quota</th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for row in seed_search.top_users %}
+ <tr>
+ <td><a href="{% url 'admin:mwmbl_mwmbluser_change' row.user.pk %}">{{ row.user.username }}</a></td>
+ <td>{{ row.tier|capfirst }}</td>
+ <td class="num{% if row.usage >= row.limit %} over{% endif %}">{{ row.usage }}</td>
+ <td class="num">{{ row.limit }}</td>
+ </tr>
+ {% empty %}
+ <tr><td colspan="4">No Seed Search queries this month.</td></tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ </div>
+
</div>
{% endblock %}
diff --git a/test/test_admin_paying_users.py b/test/test_admin_paying_users.py
index 51254d1..c34a474 100644
--- a/test/test_admin_paying_users.py
+++ b/test/test_admin_paying_users.py
@@ -3,6 +3,7 @@
import pytest
from django.contrib.auth import get_user_model
from django.core.cache import cache
+from fakeredis import FakeConnection
from mwmbl import quota
from mwmbl.models import ApiKey, Membership, UserBilling
@@ -14,7 +15,16 @@ PAYING_USERS_URL = "/admin/paying-users/"
@pytest.fixture(autouse=True)
-def clear_cache():
+def redis_cache(settings):
+ """django-redis over fakeredis rather than the test settings' locmem cache, because the
+ Seed Search stats scan the keyspace, which only django-redis supports."""
+ settings.CACHES = {
+ "default": {
+ "BACKEND": "django_redis.cache.RedisCache",
+ "LOCATION": "redis://localhost:6379/0",
+ "OPTIONS": {"CONNECTION_POOL_KWARGS": {"connection_class": FakeConnection}},
+ }
+ }
cache.clear()
yield
cache.clear()
@@ -109,6 +119,30 @@ def test_members_quota_usage_and_revenue(staff_client):
assert "£25.00".encode() in response.content
+def test_seed_search_usage_by_tier(staff_client):
+ free_user = User.objects.create_user(username="free_user")
+ sprout = User.objects.create_user(username="sprout_member")
+ Membership.objects.create(user=sprout, tier="sprout", polar_subscription_id="sub_sprout")
+ for _ in range(30):
+ quota.increment_monthly_combined_search(free_user.id)
+ for _ in range(5):
+ quota.increment_monthly_combined_search(sprout.id)
+ # Standard search usage is a different counter and must not be counted.
+ quota.increment_monthly(sprout.id)
+
+ response = staff_client.get(PAYING_USERS_URL)
+
+ seed_search = response.context["seed_search"]
+ assert seed_search["users"] == 2
+ assert seed_search["queries"] == 35
+ assert seed_search["at_limit"] == 1
+ by_tier = {tier["tier"]: tier for tier in seed_search["by_tier"]}
+ assert by_tier["free"] == {"tier": "free", "users": 1, "queries": 30, "at_limit": 1, "limit": 30}
+ assert by_tier["sprout"] == {"tier": "sprout", "users": 1, "queries": 5, "at_limit": 0, "limit": 300}
+ assert by_tier["canopy"]["users"] == 0
+ assert [row["user"].username for row in seed_search["top_users"]] == ["free_user", "sprout_member"]
+
+
def test_minor_units():
assert minor_units(0, "$") == "$0.00"
assert minor_units(123_456, "£") == "£1,234.56"