An open source, non-profit web search engine
Grant a volunteer membership and its notification in one transaction
Claudefefd5625d598
diff --git a/mwmbl/platform/notifications.py b/mwmbl/platform/notifications.pyindex a4d30d3..7aedcc0 100644--- a/mwmbl/platform/notifications.py+++ b/mwmbl/platform/notifications.py@@ -28,7 +28,8 @@ def list_notifications(request):response={204: None},summary="Dismiss a notification",description="Marks one of the user's notifications as dismissed, so it is no longer listed. Dismissing a "- "notification that is already dismissed does nothing.",+ "notification that is already dismissed does nothing. Returns 404 if the notification does not exist or "+ "belongs to another user.",)def dismiss_notification(request, notification_id: int):notifications = UserNotification.objects.filter(user=request.user, id=notification_id)diff --git a/mwmbl/volunteer_membership.py b/mwmbl/volunteer_membership.pyindex 83e9d8a..e665625 100644--- a/mwmbl/volunteer_membership.py+++ b/mwmbl/volunteer_membership.py@@ -3,6 +3,8 @@import calendarfrom datetime import date+from django.db import transaction+from mwmbl.membership import VOLUNTEER_TIERS, combined_search_monthly_limitfrom mwmbl.models import (Membership,@@ -48,23 +50,29 @@ def update_volunteer_memberships(user: MwmblUser, today: date) -> None:days_crawled = sum(num_results >= info.min_results_per_day for num_results in daily_results)if days_crawled < info.days_per_month:continue- _, created = VolunteerMembership.objects.get_or_create(- user=user, tier=info.tier, defaults={"valid_until": valid_until}- )- if created:- notify_volunteer_membership_granted(user.id, info.tier, valid_until)- continue- # Reviving a lapsed membership is a fresh grant, so it's notified; extending a current one isn't.- # Each update is a single statement, so concurrent batches can't both revive it.- revived = VolunteerMembership.objects.filter(user=user, tier=info.tier, valid_until__lt=today).update(- valid_until=valid_until- )- if revived:- notify_volunteer_membership_granted(user.id, info.tier, valid_until)- continue- VolunteerMembership.objects.filter(user=user, tier=info.tier, valid_until__lt=valid_until).update(- valid_until=valid_until- )+ _grant_volunteer_membership(user, info.tier, valid_until, today)+++# Atomic so a grant and its notification commit together: a grant that commits alone would be+# extended, not granted, on the next batch, and the user would never be notified.+def _grant_volunteer_membership(user: MwmblUser, tier: str, valid_until: date, today: date) -> None:+ _, created = VolunteerMembership.objects.get_or_create(user=user, tier=tier, defaults={"valid_until": valid_until})+ if created:+ notify_volunteer_membership_granted(user.id, tier, valid_until)+ return+ # Reviving a lapsed membership is a fresh grant, so it's notified; extending a current one isn't.+ # A concurrent revival blocks on the row lock, then re-checks valid_until < today and matches+ # nothing, so only one batch revives it.+ revived = VolunteerMembership.objects.filter(user=user, tier=tier, valid_until__lt=today).update(+ valid_until=valid_until+ )+ if revived:+ notify_volunteer_membership_granted(user.id, tier, valid_until)+ return+ VolunteerMembership.objects.filter(user=user, tier=tier, valid_until__lt=valid_until).update(+ valid_until=valid_until+ )def notify_volunteer_membership_granted(user_id: int, tier: str, valid_until: date) -> None:diff --git a/test/test_user_notifications.py b/test/test_user_notifications.pyindex f893776..6bdd878 100644--- a/test/test_user_notifications.py+++ b/test/test_user_notifications.py@@ -6,11 +6,9 @@ from unittest.mock import patchimport fakeredisimport pytest-from django.contrib.admin.sites import AdminSitefrom django.test import Clientfrom ninja_jwt.tokens import RefreshToken-from mwmbl.admin import VolunteerMembershipAdminfrom mwmbl.crawler.stats import StatsManagerfrom mwmbl.membership import VolunteerTierfrom mwmbl.models import MwmblUser, NotificationKind, UserNotification, VolunteerMembership@@ -71,18 +69,32 @@ def test_earning_a_lapsed_membership_again_notifies(user):assert _notification_data(user)[1] == {"tier": "pollinator", "valid_until": "2027-02-28"}-def _save_in_admin(volunteer_membership, change: bool, initial_valid_until: date | None = None) -> None:- form = SimpleNamespace(initial={"valid_until": initial_valid_until} if change else {})+def admin_client(client, db):+ admin = MwmblUser.objects.create_superuser(username="admin", email="[email protected]", password="testpass123")+ client.force_login(admin)+ return client+++def _save_in_admin(admin_client, url: str, user, valid_until: date) -> None:+ data = {"user": user.id, "tier": POLLINATOR, "valid_until": valid_until.isoformat()}with patch("mwmbl.admin.utc_today", return_value=TODAY):- VolunteerMembershipAdmin(VolunteerMembership, AdminSite()).save_model(None, volunteer_membership, form, change)+ response = admin_client.post(url, data)+ assert response.status_code == 302-def test_a_membership_gifted_in_the_admin_notifies(user):- _save_in_admin(VolunteerMembership(user=user, tier=POLLINATOR, valid_until=date(2027, 6, 30)), change=False)+def test_a_membership_gifted_in_the_admin_notifies(admin_client, user):+ _save_in_admin(admin_client, "/admin/mwmbl/volunteermembership/add/", user, date(2027, 6, 30))assert _notification_data(user) == [{"tier": "pollinator", "valid_until": "2027-06-30"}]+def test_an_already_expired_membership_added_in_the_admin_does_not_notify(admin_client, user):+ _save_in_admin(admin_client, "/admin/mwmbl/volunteermembership/add/", user, date(2026, 10, 1))++ assert _notification_data(user) == []++@pytest.mark.parametrize("initial_valid_until, valid_until, notified",[@@ -92,17 +104,31 @@ def test_a_membership_gifted_in_the_admin_notifies(user):],ids=["reviving a lapsed one", "extending a current one", "editing a lapsed one that stays lapsed"],)-def test_editing_a_membership_in_the_admin(user, initial_valid_until, valid_until, notified):+def test_editing_a_membership_in_the_admin(admin_client, user, initial_valid_until, valid_until, notified):volunteer_membership = VolunteerMembership.objects.create(user=user, tier=POLLINATOR, valid_until=initial_valid_until)- volunteer_membership.valid_until = valid_until- _save_in_admin(volunteer_membership, change=True, initial_valid_until=initial_valid_until)+ _save_in_admin(+ admin_client, f"/admin/mwmbl/volunteermembership/{volunteer_membership.id}/change/", user, valid_until+ )assert bool(_notification_data(user)) == notified+def test_a_grant_and_its_notification_commit_together(user):+ for day in (1, 2):+ _crawl(user, date(2026, 10, day))+ with patch("mwmbl.volunteer_membership.notify_volunteer_membership_granted", side_effect=RuntimeError):+ with pytest.raises(RuntimeError):+ _crawl(user, date(2026, 10, 3))+ assert not VolunteerMembership.objects.filter(user=user).exists()++ _crawl(user, date(2026, 10, 3))++ assert _notification_data(user) == [{"tier": "pollinator", "valid_until": "2026-11-30"}]++def test_list_notifications(user):_crawl_three_days(user, 2026, 10)