From b7a26fc152c42dd7e0e3a4210ad0a47645387a71 Mon Sep 17 00:00:00 2001 From: claude Date: Wed, 18 Nov 2026 15:40:22 -0500 Subject: [PATCH] Membership: one pay-what-you-want Supporter tier replaces Bronze-Diamond Members choose a monthly amount ($3-$500, suggested $8). Stripe Checkout creates a monthly USD Price for that amount on the existing Subscription product; billing sync accepts only such Prices (right product, USD, monthly, within bounds). SHKeeper prepayments take the same chosen amount. Bronze becomes Supporter and keeps its original Price, so existing Bronze subscriptions continue. Silver-Diamond are retired with "hidden": true: not offered and not buyable, but existing subscriptions and prepaid terms keep their access until they end. The members page now describes drops and no fixed schedule, and drops the tier giveaways and polls. Homepage copy says "Supporters" instead of "Bronze and above". Co-Authored-By: Claude Opus 5.5 --- README.md | 22 +- htdocs/index.html | 4 +- membership/config/settings.py | 23 ++ membership/members/billing.py | 5 +- membership/members/pricing.py | 59 +++++ .../members/tests/test_pay_what_you_want.py | 210 ++++++++++++++++++ .../members/tests/test_service_groups.py | 10 +- membership/members/views.py | 43 +++- membership/templates/crypto_checkout.html | 4 +- membership/templates/members.html | 22 +- membership/tiers.eom.json | 147 ++++++------ tests/site.test.mjs | 3 +- 12 files changed, 450 insertions(+), 102 deletions(-) create mode 100644 membership/members/pricing.py create mode 100644 membership/members/tests/test_pay_what_you_want.py diff --git a/README.md b/README.md index 3161c75..7e3d78c 100644 --- a/README.md +++ b/README.md @@ -246,11 +246,23 @@ metadata, Discourse integration, or existing subscriptions. | Membership | Monthly USD | Existing live Price ID | Proposed dedicated LDAP group | | --- | ---: | --- | --- | | Level 0 · Open Lab | Free | — | — | -| Level 1 · Bronze | $4 | `price_1Rgv4xC5KPXqTvVLfMd6z7wn` | `www-level-1` | -| Level 2 · Silver | $8 | `price_1Rgv5QC5KPXqTvVLv1PaHWb5` | `www-level-2` | -| Level 3 · Gold | $16 | `price_1Rgv5rC5KPXqTvVL8Ol8sMUf` | `www-level-3` | -| Level 4 · Platinum | $32 | `price_1Rgv6FC5KPXqTvVL39mAxYjm` | `www-level-4` | -| Level 5 · Diamond | $64 | `price_1Rgv6mC5KPXqTvVLkcmznWZa` | `www-level-5` | +| Level 1 · Supporter (was Bronze) | Pay what you want, $3–$500 (suggested $8) | `price_1Rgv4xC5KPXqTvVLfMd6z7wn` (Bronze, $4) | `www-level-1` | +| Level 2 · Silver (retired) | $8 | `price_1Rgv5QC5KPXqTvVLv1PaHWb5` | `www-level-2` | +| Level 3 · Gold (retired) | $16 | `price_1Rgv5rC5KPXqTvVL8Ol8sMUf` | `www-level-3` | +| Level 4 · Platinum (retired) | $32 | `price_1Rgv6FC5KPXqTvVL39mAxYjm` | `www-level-4` | +| Level 5 · Diamond (retired) | $64 | `price_1Rgv6mC5KPXqTvVLkcmznWZa` | `www-level-5` | + +**Pay what you want (2026-11-18).** Supporter is the only tier offered. Members +choose a monthly amount between `min_usd` and `max_usd`; Checkout creates a +monthly USD Price for that amount on the Subscription product +(`pay_what_you_want.product_id`), and billing sync accepts only such Prices +(right product, USD, monthly, within the bounds). The original Bronze Price +stays as `price_id`, so existing Bronze subscriptions continue as Supporter. +Retired tiers (`"hidden": true`) are not offered and cannot be bought, but +existing subscriptions and prepaid crypto terms on them keep their access until +they end. SHKeeper prepayments use the same bounds, with the member's chosen +amount stored on the invoice. Benefits are the same at every amount; there are +no giveaways. Every account has a non-null `membership_level`: new/free accounts start at 0, and synchronization records the highest currently valid paid level. The former diff --git a/htdocs/index.html b/htdocs/index.html index 5e66b84..4a117e9 100644 --- a/htdocs/index.html +++ b/htdocs/index.html @@ -304,14 +304,14 @@

Free · Level 0 and above

Discourse · Forums

-

Talk about the music, films, and projects. Bronze and above also get exclusive member content.

+

Talk about the music, films, and projects. Supporters also get supporter-only posts.

Visit the forum

Free · Level 0 and above

Harmony · Chat, voice & video

-

Hang out in community servers and channels, hop into voice and video calls, and follow posts from across the fediverse. Bronze and above also get exclusive member content.

+

Hang out in community servers and channels, hop into voice and video calls, and follow posts from across the fediverse. Supporters also get supporter-only posts.

Open Harmony
diff --git a/membership/config/settings.py b/membership/config/settings.py index fa79c94..0678511 100755 --- a/membership/config/settings.py +++ b/membership/config/settings.py @@ -160,6 +160,29 @@ for key, tier in MEMBERSHIP_TIERS.items(): raise ValueError except (InvalidOperation, ValueError, TypeError): raise ImproperlyConfigured(f"Tier {key} usd_amount must be a positive USD amount with at most two decimals.") from None + # Pay what you want: members choose a monthly amount in [min_usd, max_usd]; + # checkout creates that Price on product_id. price_id stays the tier's + # original fixed Price, so existing subscriptions to it keep working. + if "pay_what_you_want" in tier: + pwyw = tier["pay_what_you_want"] + try: + if not isinstance(pwyw, dict) or not isinstance(pwyw.get("product_id"), str) or not re.fullmatch(r"prod_[A-Za-z0-9]+", pwyw["product_id"]): + raise ValueError + amounts = [] + for name in ("min_usd", "suggested_usd", "max_usd"): + if not isinstance(pwyw.get(name), str): + raise ValueError + amount = Decimal(pwyw[name]) + if not amount.is_finite() or amount != amount.quantize(Decimal("0.01")): + raise ValueError + amounts.append(amount) + if not Decimal("1.00") <= amounts[0] <= amounts[1] <= amounts[2] <= Decimal("10000.00"): + raise ValueError + except (InvalidOperation, ValueError, TypeError): + raise ImproperlyConfigured(f"Tier {key} pay_what_you_want needs a Stripe product_id and string USD amounts with 1.00 <= min_usd <= suggested_usd <= max_usd <= 10000.00.") from None + # Hidden tiers keep honouring existing subscriptions but are not offered. + if not isinstance(tier.get("hidden", False), bool): + raise ImproperlyConfigured(f"Tier {key} hidden must be true or false.") # Separate from Stripe tiers so free accounts can receive service benefits too. from members.service_groups import validate_service_groups diff --git a/membership/members/billing.py b/membership/members/billing.py index f2cb963..73ceac0 100755 --- a/membership/members/billing.py +++ b/membership/members/billing.py @@ -11,7 +11,7 @@ from django.utils import timezone from .directory import reconcile_groups from .models import Account, CryptoInvoice, ManagedGroup, Subscription, WebhookEvent -from . import shkeeper +from . import pricing, shkeeper from .service_groups import configured_groups logger = logging.getLogger(__name__) @@ -72,6 +72,9 @@ def refresh_billing(account): data = items.get("data") or [] price_id = _id(data[0].get("price")) if len(data) == 1 and not items.get("has_more") else None tier = prices.get(price_id, "") + if not tier and price_id: + # Pay-what-you-want subscriptions each have their own Price. + tier = next((key for key, config in settings.MEMBERSHIP_TIERS.items() if pricing.is_pwyw(config) and pricing.accepts_price(config, data[0].get("price"))), "") eligible = tier and sub.get("status") in {"active", "past_due"} and not sub.get("pause_collection") paid_until = _paid_until(api, sub, price_id, now) if eligible else None if paid_until and sub.get("cancel_at"): diff --git a/membership/members/pricing.py b/membership/members/pricing.py new file mode 100644 index 0000000..ec1dfc1 --- /dev/null +++ b/membership/members/pricing.py @@ -0,0 +1,59 @@ +"""Pay-what-you-want amounts: one validated place for checkout, crypto and billing.""" + +from decimal import Decimal, InvalidOperation + +CENT = Decimal("0.01") + + +def _id(value): + return value.get("id") if isinstance(value, dict) else value + + +def is_pwyw(tier): + return bool(tier.get("pay_what_you_want")) + + +def bounds(tier): + """(minimum, suggested, maximum) monthly USD amounts.""" + options = tier["pay_what_you_want"] + return Decimal(options["min_usd"]), Decimal(options["suggested_usd"]), Decimal(options["max_usd"]) + + +def parse_amount(tier, raw): + """The member's chosen monthly USD amount, or None if it is not a valid choice.""" + if not isinstance(raw, str): + return None + try: + amount = Decimal(raw.strip().removeprefix("$")) + except InvalidOperation: + return None + low, _suggested, high = bounds(tier) + if not amount.is_finite() or amount != amount.quantize(CENT) or not low <= amount <= high: + return None + return amount.quantize(CENT) + + +def cents(amount): + return int(amount * 100) + + +def accepts_price(tier, price): + """True only for a Stripe Price this tier's checkout could have created. + + Pay-what-you-want checkouts create a monthly USD Price on the tier's + product. Anything else on that product (other currencies, intervals or + amounts outside the bounds) grants nothing. + """ + if not isinstance(price, dict): + return False + recurring = price.get("recurring") or {} + amount = price.get("unit_amount") + low, _suggested, high = bounds(tier) + return ( + _id(price.get("product")) == tier["pay_what_you_want"]["product_id"] + and price.get("currency") == "usd" + and recurring.get("interval") == "month" + and recurring.get("interval_count", 1) == 1 + and isinstance(amount, int) and not isinstance(amount, bool) + and cents(low) <= amount <= cents(high) + ) diff --git a/membership/members/tests/test_pay_what_you_want.py b/membership/members/tests/test_pay_what_you_want.py new file mode 100644 index 0000000..f21f3bb --- /dev/null +++ b/membership/members/tests/test_pay_what_you_want.py @@ -0,0 +1,210 @@ +"""Pay-what-you-want Supporter membership: checkout, crypto, billing and settings.""" + +import json +import os +import runpy +from datetime import timedelta +from decimal import Decimal +from pathlib import Path +from unittest.mock import MagicMock, patch + +from django.core.exceptions import ImproperlyConfigured +from django.test import SimpleTestCase, TestCase, override_settings +from django.utils import timezone + +from members import billing, pricing +from members.models import CryptoInvoice, Subscription +from .test_membership import DN, GROUP, OTHER_GROUP, account, paged + +PWYW = {"product_id": "prod_lab", "min_usd": "3.00", "suggested_usd": "8.00", "max_usd": "500.00"} +TIERS = { + "supporter": {"label": "Supporter", "level": 1, "price_id": "price_bronze", "price_label": "Pay what you want", "pay_what_you_want": PWYW, "group_dn": GROUP}, + "retired": {"label": "Diamond", "level": 2, "price_id": "price_diamond", "price_label": "$64 / month", "usd_amount": "64.00", "hidden": True, "group_dn": OTHER_GROUP}, +} +SHKEEPER = {"SHKEEPER_ENABLED": True, "SHKEEPER_URL": "https://pay.example.org", "SHKEEPER_API_KEY": "test-only-key", "SHKEEPER_CA_CERT_FILE": "", "SHKEEPER_CURRENCIES": ["BTC", "XMR"]} + + +def price(**changes): + return {"id": "price_adhoc", "product": "prod_lab", "currency": "usd", "unit_amount": 1250, "recurring": {"interval": "month", "interval_count": 1}, **changes} + + +class AmountParsingTests(SimpleTestCase): + tier = TIERS["supporter"] + + def test_accepts_amounts_within_bounds(self): + for raw, expected in (("3", "3.00"), ("8.00", "8.00"), (" $12.5 ", "12.50"), ("500", "500.00")): + with self.subTest(raw=raw): + self.assertEqual(pricing.parse_amount(self.tier, raw), Decimal(expected)) + + def test_rejects_out_of_bounds_and_malformed_amounts(self): + for raw in ("2.99", "500.01", "0", "-5", "8.001", "NaN", "Infinity", "1e3", "", "eight", None, ["8"]): + with self.subTest(raw=raw): + self.assertIsNone(pricing.parse_amount(self.tier, raw)) + + def test_only_prices_checkout_could_create_are_accepted(self): + self.assertTrue(pricing.accepts_price(self.tier, price())) + self.assertTrue(pricing.accepts_price(self.tier, price(product={"id": "prod_lab"}))) + for changes in ({"product": "prod_other"}, {"currency": "eur"}, {"unit_amount": 299}, {"unit_amount": 50001}, + {"unit_amount": None}, {"unit_amount": True}, {"recurring": {"interval": "year"}}, + {"recurring": {"interval": "month", "interval_count": 3}}, {"recurring": None}): + with self.subTest(changes=changes): + self.assertFalse(pricing.accepts_price(self.tier, price(**changes))) + self.assertFalse(pricing.accepts_price(self.tier, "price_adhoc")) + + +@override_settings(MEMBERSHIP_TIERS=TIERS, STRIPE_PORTAL_CONFIGURATION="bpc_test") +class CheckoutTests(TestCase): + def setUp(self): + self.member = account(stripe_customer="cus_alice") + session = self.client.session + session["account_id"] = str(self.member.pk) + session.save() + + def test_page_offers_only_visible_tier_with_amount_field(self): + response = self.client.get("/members/") + self.assertContains(response, 'name="amount"') + self.assertContains(response, 'value="8.00"') + self.assertContains(response, "Supporter") + self.assertNotContains(response, "$64 / month") + self.assertNotContains(response, "/members/checkout/retired/") + self.assertNotContains(response, "giveaway") + + def test_retired_subscription_keeps_its_label(self): + Subscription.objects.create(stripe_id="sub_old", account=self.member, tier="retired", status="active", paid_until=timezone.now() + timedelta(days=3)) + self.assertContains(self.client.get("/members/"), "Diamond · active") + + @patch("members.views.billing.client") + def test_chosen_amount_becomes_monthly_price_on_product(self, api_factory): + api = api_factory.return_value + api.subscriptions.list.return_value = paged([]) + api.checkout.sessions.create.return_value = {"id": "cs_new", "url": "https://checkout.stripe.com/c/pay/new"} + response = self.client.post("/members/checkout/supporter/", {"amount": "12.50", "price_id": "price_attacker"}) + self.assertEqual(response.status_code, 302) + params = api.checkout.sessions.create.call_args.args[0] + self.assertEqual(params["line_items"], [{"price_data": {"currency": "usd", "product": "prod_lab", "unit_amount": 1250, "recurring": {"interval": "month"}}, "quantity": 1}]) + self.assertEqual(params["customer"], "cus_alice") + self.assertTrue(api.checkout.sessions.create.call_args.kwargs["options"]["idempotency_key"].endswith("-1250")) + + @patch("members.views.billing.client") + def test_invalid_amount_never_reaches_stripe(self, api_factory): + for amount in ("2", "501", "abc", ""): + with self.subTest(amount=amount): + self.assertContains(self.client.post("/members/checkout/supporter/", {"amount": amount}), "Enter a monthly amount from $3.00 to $500.00 USD.") + self.assertContains(self.client.post("/members/checkout/supporter/"), "Choose an amount") + api_factory.assert_not_called() + + @patch("members.views.billing.client") + def test_retired_tier_cannot_be_bought(self, api_factory): + self.assertEqual(self.client.post("/members/checkout/retired/").status_code, 404) + api_factory.assert_not_called() + + @patch("members.views.billing.client") + def test_open_session_reused_for_same_amount_and_replaced_for_new_amount(self, api_factory): + api = api_factory.return_value + api.subscriptions.list.return_value = paged([]) + type(self.member).objects.filter(pk=self.member.pk).update(checkout_id="cs_open") + api.checkout.sessions.retrieve.return_value = {"status": "open", "amount_total": 800, "url": "https://checkout.stripe.com/c/pay/open"} + self.assertEqual(self.client.post("/members/checkout/supporter/", {"amount": "8"})["Location"], "https://checkout.stripe.com/c/pay/open") + api.checkout.sessions.create.assert_not_called() + api.checkout.sessions.create.return_value = {"id": "cs_new", "url": "https://checkout.stripe.com/c/pay/new"} + self.assertEqual(self.client.post("/members/checkout/supporter/", {"amount": "20"})["Location"], "https://checkout.stripe.com/c/pay/new") + api.checkout.sessions.expire.assert_called_once_with("cs_open") + self.assertEqual(api.checkout.sessions.create.call_args.args[0]["line_items"][0]["price_data"]["unit_amount"], 2000) + + +@override_settings(MEMBERSHIP_TIERS=TIERS) +class BillingTests(TestCase): + def setUp(self): + self.member = account(stripe_customer="cus_alice") + self.end = int((timezone.now() + timedelta(days=30)).timestamp()) + + def api(self, item_price): + sub = {"id": "sub_alice", "customer": "cus_alice", "livemode": False, "metadata": {"membership_account": str(self.member.pk)}, "status": "active", "items": {"data": [{"price": item_price}], "has_more": False}, "cancel_at_period_end": False} + invoice = {"id": "in_paid", "customer": "cus_alice", "status": "paid", "livemode": False, "parent": {"subscription_details": {"subscription": "sub_alice"}}} + line = {"amount": item_price.get("unit_amount", 400), "parent": {"subscription_item_details": {"subscription": "sub_alice"}}, "pricing": {"price_details": {"price": item_price["id"]}}, "period": {"start": int(timezone.now().timestamp()) - 60, "end": self.end}} + api = MagicMock() + api.subscriptions.list.return_value = paged([sub]) + api.invoices.list.return_value = paged([invoice]) + api.invoices.line_items.list.return_value = paged([line]) + return api + + @patch("members.billing.reconcile_groups", return_value=DN) + @patch("members.billing.client") + def test_pay_what_you_want_subscription_grants_supporter(self, factory, ldap): + factory.return_value = self.api(price()) + self.assertTrue(billing.sync_account(self.member.pk)) + self.assertEqual(Subscription.objects.get().tier, "supporter") + self.assertEqual(ldap.call_args.args[1], {GROUP}) + + @patch("members.billing.reconcile_groups", return_value=DN) + @patch("members.billing.client") + def test_original_fixed_price_and_retired_tier_still_honoured(self, factory, ldap): + for price_id, tier, group in (("price_bronze", "supporter", GROUP), ("price_diamond", "retired", OTHER_GROUP)): + with self.subTest(price_id=price_id): + factory.return_value = self.api({"id": price_id}) + billing.sync_account(self.member.pk) + self.assertEqual(Subscription.objects.get().tier, tier) + self.assertEqual(ldap.call_args.args[1], {group}) + + @patch("members.billing.reconcile_groups", return_value=DN) + @patch("members.billing.client") + def test_foreign_or_out_of_bounds_price_grants_nothing(self, factory, ldap): + for changes in ({"product": "prod_other"}, {"unit_amount": 100}, {"currency": "eur"}): + with self.subTest(changes=changes): + factory.return_value = self.api(price(**changes)) + billing.sync_account(self.member.pk) + self.assertEqual(Subscription.objects.get().tier, "") + self.assertEqual(ldap.call_args.args[1], set()) + + +@override_settings(MEMBERSHIP_TIERS=TIERS, **SHKEEPER) +class CryptoTests(TestCase): + def setUp(self): + self.member = account() + session = self.client.session + session["account_id"] = str(self.member.pk) + session.save() + + def test_form_asks_for_amount(self): + response = self.client.get("/members/crypto/checkout/supporter/") + self.assertContains(response, 'name="amount"') + self.assertContains(response, "Pay what you want") + self.assertEqual(self.client.get("/members/crypto/checkout/retired/").status_code, 404) + + @patch("members.shkeeper.request") + def test_chosen_amount_is_the_invoice_amount(self, request): + request.return_value = {"status": "success", "id": 61, "wallet": "bc1-test-wallet", "amount": "0.0001", "recalculate_after": 0} + self.client.post("/members/crypto/checkout/supporter/", {"crypto": "BTC", "amount": "15", "usd_amount": "0.01"}) + self.assertEqual(CryptoInvoice.objects.get().usd_amount, Decimal("15.00")) + + def test_invalid_amount_rejected(self): + for amount in ("1", "9999", "x"): + with self.subTest(amount=amount): + self.assertEqual(self.client.post("/members/crypto/checkout/supporter/", {"crypto": "BTC", "amount": amount}).status_code, 400) + self.assertFalse(CryptoInvoice.objects.exists()) + + +class SettingsTests(SimpleTestCase): + settings_file = str(Path(__file__).absolute().parents[2] / "config" / "settings.py") + + def load(self, tiers): + with patch.dict(os.environ, {"MEMBERSHIP_TIERS_JSON": json.dumps(tiers), "MEMBERSHIP_SERVICE_GROUPS_JSON": "{}"}): + return runpy.run_path(self.settings_file) + + def test_valid_and_deployed_tiers_load(self): + self.assertEqual(self.load(TIERS)["MEMBERSHIP_TIERS"], TIERS) + deployed = json.loads((Path(__file__).absolute().parents[2] / "tiers.eom.json").read_text(encoding="utf-8")) + self.assertEqual(self.load(deployed)["MEMBERSHIP_TIERS"], deployed) + self.assertEqual([key for key, tier in deployed.items() if not tier.get("hidden")], ["level-1"]) + self.assertFalse(any("giveaway" in benefit.casefold() for benefit in deployed["level-1"]["benefits"])) + + def test_invalid_pay_what_you_want_rejected(self): + for change in ({"product_id": "price_x"}, {"min_usd": 3}, {"min_usd": "0.50"}, {"min_usd": "9.00"}, + {"max_usd": "20000.00"}, {"suggested_usd": "8.001"}, {"max_usd": None}): + with self.subTest(change=change), self.assertRaises(ImproperlyConfigured): + self.load({"supporter": {**TIERS["supporter"], "pay_what_you_want": {**PWYW, **change}}}) + for bad in ([], "yes"): + with self.subTest(bad=bad), self.assertRaises(ImproperlyConfigured): + self.load({"supporter": {**TIERS["supporter"], "pay_what_you_want": bad}}) + with self.assertRaises(ImproperlyConfigured): + self.load({"retired": {**TIERS["retired"], "hidden": "yes"}}) diff --git a/membership/members/tests/test_service_groups.py b/membership/members/tests/test_service_groups.py index 4f48676..b2543f1 100755 --- a/membership/members/tests/test_service_groups.py +++ b/membership/members/tests/test_service_groups.py @@ -91,10 +91,13 @@ class ServiceDisplayTests(TestCase): deployed = yaml.safe_load(role.read_text(encoding="utf-8"))["www_membership_tiers"] for key, tier in tiers.items(): + self.assertEqual(tier.get("hidden", False), deployed[key].get("hidden", False)) + self.assertEqual(tier.get("pay_what_you_want"), deployed[key].get("pay_what_you_want")) + if tier.get("hidden"): + continue # retired tiers are never shown self.assertEqual(tier["description"], deployed[key]["description"]) self.assertEqual(tier["benefits"], deployed[key]["benefits"]) - self.assertIn(f"{tier['label']}-tier giveaways", tier["benefits"]) - self.assertFalse(any("exclusive to" in benefit.casefold() for benefit in tier["benefits"])) + self.assertFalse(any("giveaway" in benefit.casefold() for benefit in tier["benefits"])) def test_homepage_lists_services_with_clear_access_labels(self): root = Path(__file__).absolute().parents[3] @@ -187,7 +190,8 @@ class ServiceDisplayTests(TestCase): self.assertContains(response, "Plus all previous benefits") self.assertNotContains(response, "except tier-exclusive giveaways") self.assertContains(response, "Support independent projects and the community
  • Plus all previous benefits
  • ") - self.assertContains(response, "How do membership giveaways work?") + self.assertNotContains(response, "giveaway") + self.assertContains(response, "What happened to Bronze, Silver, Gold, Platinum and Diamond?") self.assertContains(response, 'href="https://element.eom.dev/"') self.assertContains(response, 'src="https://element.eom.dev/vector-icons/144.5a63bf2.png"') self.assertIn("https://element.eom.dev", response["Content-Security-Policy"]) diff --git a/membership/members/views.py b/membership/members/views.py index a1ae5da..16de328 100755 --- a/membership/members/views.py +++ b/membership/members/views.py @@ -23,7 +23,7 @@ from django.views.decorators.csrf import csrf_exempt from django.views.decorators.debug import sensitive_post_parameters from django.views.decorators.http import require_GET, require_POST, require_http_methods -from . import billing, directory, newsletter, profiles, shkeeper +from . import billing, directory, newsletter, pricing, profiles, shkeeper from .forms import PasswordForm, RegistrationForm, SocialRegistrationForm from .service_groups import configured_groups, service_access_catalog from .profile_forms import CurrentPasswordForm, ProfileEmailForm, ProfileForm, ProfilePasswordForm @@ -77,10 +77,12 @@ def home(request): invoices = CryptoInvoice.objects.filter(account=account).order_by("-created_at")[:20] if account else [] # Presentation copies only: never mutate authorization/payment settings. tiers = settings.MEMBERSHIP_TIERS - services = service_access_catalog(tiers, settings.MEMBERSHIP_SERVICE_GROUPS) + # Hidden (retired) tiers still label existing subscriptions but are not offered. + offered = {key: tier for key, tier in tiers.items() if not tier.get("hidden")} + services = service_access_catalog(offered, settings.MEMBERSHIP_SERVICE_GROUPS) # Public total across every level (free and paid); never a per-tier breakdown. member_count = Account.objects.count() - return page(request, account=account, tiers=tiers, services=services, subscriptions=subscriptions, crypto_invoices=invoices, shkeeper_enabled=settings.SHKEEPER_ENABLED, now=timezone.now(), member_count=member_count) + return page(request, account=account, tiers=offered, all_tiers=tiers, services=services, subscriptions=subscriptions, crypto_invoices=invoices, shkeeper_enabled=settings.SHKEEPER_ENABLED, now=timezone.now(), member_count=member_count) @require_http_methods(["GET", "POST"]) @@ -574,8 +576,14 @@ def stripe_redirect(url, host): @account_required def checkout(request, tier): config = settings.MEMBERSHIP_TIERS.get(tier) - if not config: + if not config or config.get("hidden"): return HttpResponse(status=404) + amount = None + if pricing.is_pwyw(config): + amount = pricing.parse_amount(config, request.POST.get("amount")) + if amount is None: + low, _suggested, high = pricing.bounds(config) + return page(request, title="Choose an amount", message=f"Enter a monthly amount from ${low} to ${high} USD.") if limited("checkout", str(request.member.pk), 20): return HttpResponse(status=429) try: @@ -595,16 +603,25 @@ def checkout(request, tier): if account.checkout_id: session = api.checkout.sessions.retrieve(account.checkout_id) if session.get("status") == "open": - return stripe_redirect(session["url"], "checkout.stripe.com") + if amount is None or session.get("amount_total") == pricing.cents(amount): + return stripe_redirect(session["url"], "checkout.stripe.com") + # A different amount was chosen: retire the old session first. + api.checkout.sessions.expire(account.checkout_id) account.checkout_key = uuid.uuid4() + if amount is None: + line_item = {"price": config["price_id"], "quantity": 1} + idempotency_key = f"member-checkout-{account.pk}-{account.checkout_key}" + else: + line_item = {"price_data": {"currency": "usd", "product": config["pay_what_you_want"]["product_id"], "unit_amount": pricing.cents(amount), "recurring": {"interval": "month"}}, "quantity": 1} + idempotency_key = f"member-checkout-{account.pk}-{account.checkout_key}-{pricing.cents(amount)}" session = api.checkout.sessions.create({ "mode": "subscription", "customer": account.stripe_customer, - "line_items": [{"price": config["price_id"], "quantity": 1}], + "line_items": [line_item], "client_reference_id": str(account.pk), "subscription_data": {"metadata": {"membership_account": str(account.pk)}}, "success_url": settings.PUBLIC_URL + reverse("members:home") + "?checkout=complete", "cancel_url": settings.PUBLIC_URL + reverse("members:home"), - }, options={"idempotency_key": f"member-checkout-{account.pk}-{account.checkout_key}"}) + }, options={"idempotency_key": idempotency_key}) account.checkout_id = session["id"] account.save(update_fields=["checkout_id", "checkout_key"]) return stripe_redirect(session["url"], "checkout.stripe.com") @@ -652,13 +669,19 @@ def webhook(request): @account_required def crypto_checkout(request, tier): config = settings.MEMBERSHIP_TIERS.get(tier) - if not settings.SHKEEPER_ENABLED or not config or not config.get("usd_amount"): + if not settings.SHKEEPER_ENABLED or not config or config.get("hidden") or not (config.get("usd_amount") or pricing.is_pwyw(config)): return HttpResponse(status=404) + pwyw = pricing.bounds(config) if pricing.is_pwyw(config) else None if request.method == "GET": - return render(request, "crypto_checkout.html", {"tier": config, "tier_key": tier, "currencies": settings.SHKEEPER_CURRENCIES}) + return render(request, "crypto_checkout.html", {"tier": config, "tier_key": tier, "currencies": settings.SHKEEPER_CURRENCIES, "pwyw": pwyw}) crypto = request.POST.get("crypto", "") if crypto not in settings.SHKEEPER_CURRENCIES: return HttpResponse("Choose an available cryptocurrency.", status=400) + usd_amount = config.get("usd_amount") + if pwyw: + usd_amount = pricing.parse_amount(config, request.POST.get("amount")) + if usd_amount is None: + return HttpResponse(f"Enter an amount from ${pwyw[0]} to ${pwyw[2]} USD.", status=400) if limited("crypto-checkout", str(request.member.pk), 20): return HttpResponse(status=429) try: @@ -680,7 +703,7 @@ def crypto_checkout(request, tier): return page(request, title="Stripe checkout is still open", message="Finish or let the existing Stripe Checkout expire before changing payment providers.") if CryptoInvoice.objects.filter(account=account, access_end__gt=timezone.now()).exclude(tier=tier).exists(): return page(request, title="Another prepaid tier is active", message="Renew the same tier, or wait for the current prepaid membership to expire before changing tiers.") - invoice = CryptoInvoice.objects.create(account=account, tier=tier, crypto=crypto, usd_amount=config["usd_amount"]) + invoice = CryptoInvoice.objects.create(account=account, tier=tier, crypto=crypto, usd_amount=usd_amount) remember_groups(account) # Reserve/commit UUID BEFORE API call, so retries and worker recovery # use the same external ID if the process dies after invoice creation. diff --git a/membership/templates/crypto_checkout.html b/membership/templates/crypto_checkout.html index 9d7c758..1ec169c 100755 --- a/membership/templates/crypto_checkout.html +++ b/membership/templates/crypto_checkout.html @@ -1,10 +1,12 @@ {% extends "crypto_base.html" %} {% block content %}

    Prepay {{ tier.label }}

    -

    ${{ tier.usd_amount }} USD / one calendar month

    +{% if pwyw %}

    Pay what you want / one calendar month

    {% else %}

    ${{ tier.usd_amount }} USD / one calendar month

    {% endif %}

    Pay once with cryptocurrency. This is not an automatically renewing subscription. Renewing the same tier adds one calendar month after your current prepaid term ends.

    {% csrf_token %} + {% if pwyw %}

    +

    {% endif %}

    Choose carefully. Tokens on different networks are not interchangeable. SHKeeper supplies the deposit address and crypto amount. Configured processor fees or exchange-rate changes may affect the required amount.

    diff --git a/membership/templates/members.html b/membership/templates/members.html index f53365b..9367cb6 100755 --- a/membership/templates/members.html +++ b/membership/templates/members.html @@ -48,7 +48,7 @@

    Music, films, projects & shared worlds

    Support the work.
    Get closer to what’s next.

    {% if member_count %}

    {{ member_count }} member{{ member_count|pluralize }} and counting

    {% endif %} -

    Membership supports my music, films, writing, open-source projects, and game servers. Join the community for free, or choose a paid tier to support the work and receive the benefits listed below.

    +

    Membership supports my music, films, writing, open-source projects, and game servers. Join the community for free, or support the lab with whatever amount feels right each month.

    {% if account %} {% if request.GET.checkout %}

    Thanks for supporting the work. Your membership benefits become available once Stripe confirms payment and your account access updates.

    {% endif %} {% for subscription in subscriptions %} -

    {% for key, tier in tiers.items %}{% if key == subscription.tier %}{{ tier.label }}{% endif %}{% empty %}Membership{% endfor %} · {{ subscription.status }}{% if subscription.paid_until > now %} · Paid access through {{ subscription.paid_until|date:"M j, Y H:i T" }}{% else %} · No current paid access{% endif %}{% if subscription.cancel_at_period_end %} · Does not renew{% endif %}

    +

    {% for key, tier in all_tiers.items %}{% if key == subscription.tier %}{{ tier.label }}{% endif %}{% empty %}Membership{% endfor %} · {{ subscription.status }}{% if subscription.paid_until > now %} · Paid access through {{ subscription.paid_until|date:"M j, Y H:i T" }}{% else %} · No current paid access{% endif %}{% if subscription.cancel_at_period_end %} · Does not renew{% endif %}

    {% endfor %} {% for invoice in crypto_invoices %} -

    SHKeeper · {% for key, tier in tiers.items %}{% if key == invoice.tier %}{{ tier.label }}{% endif %}{% empty %}Membership{% endfor %} · {{ invoice.status }}{% if invoice.access_end > now %} · Prepaid term {{ invoice.access_start|date:"M j, Y" }}–{{ invoice.access_end|date:"M j, Y" }}{% endif %} · View crypto invoice

    +

    SHKeeper · {% for key, tier in all_tiers.items %}{% if key == invoice.tier %}{{ tier.label }}{% endif %}{% empty %}Membership{% endfor %} · {{ invoice.status }}{% if invoice.access_end > now %} · Prepaid term {{ invoice.access_start|date:"M j, Y" }}–{{ invoice.access_end|date:"M j, Y" }}{% endif %} · View crypto invoice

    {% endfor %}

    Membership access updates automatically, usually within a few minutes. Signing out here does not sign you out of other eom.dev services.

    {% else %} @@ -74,12 +74,12 @@ {% endif %}
    -

    Your support, your choice

    Choose how to take part

    Public recordings, writing, and source code remain available without a paid membership. Your support helps fund creative time, recording, travel, and independent publishing.

    Paid benefits build by level: Bronze adds exclusive Discourse and Harmony content; Silver adds previews when available; Gold adds project-topic polls and occasional feedback sessions. Compare the full benefits below.

    +

    Your support, your choice

    Choose how to take part

    Public recordings, writing, and source code remain available without a paid membership. Your support helps fund creative time, recording, travel, and independent publishing.

    I work in bursts, not on a schedule. The work ships as drops when it's ready: a game build, a song, a film, a write-up. Supporters keep the lab running between drops, choose their own monthly amount, and get the same benefits whatever they give.

    Level 0 · The starting point

    Open Lab

    Free / always

    Join the community without a subscription.

    -
    • Games hosted on eom.dev
    • Open Lab-tier giveaways
    +
    • Games hosted on eom.dev
    • Public build logs, source code and drops
    {% if not account %}Join the community{% else %}

    Your free account is ready.

    {% endif %}
    {% for key, tier in tiers.items %} @@ -87,8 +87,10 @@

    Level {{ tier.level }}

    {{ tier.label }}

    {{ tier.price_label }}

    {{ tier.description|default:"Support the independent work and community." }}

      {% for benefit in tier.benefits %}
    • {{ benefit }}
    • {% empty %}
    • Support independent projects and the community
    • {% endfor %}
    • Plus all previous benefits
    - {% if account %}
    {% csrf_token %} - {% if shkeeper_enabled and tier.usd_amount %}Pay with crypto{% endif %}
    {% else %}Create an account to join{% endif %} + {% if account %}{% if tier.pay_what_you_want %}
    {% csrf_token %}

    + {% if shkeeper_enabled %}Pay with crypto{% endif %}
    + {% else %}
    {% csrf_token %}
    + {% if shkeeper_enabled and tier.usd_amount %}Pay with crypto{% endif %}
    {% endif %}{% else %}Create an account to join{% endif %}
    {% empty %}

    Paid memberships are coming soon.

    You can create your free account now. Paid tiers will appear when their prices and groups are configured.

    {% endfor %} @@ -103,10 +105,10 @@

    Before you join

    Do I need a paid membership to watch, read, or play?

    No. Public videos, writing, and source code can be explored without a paid membership. A free Open Lab (Level 0) account includes access to games hosted on eom.dev, and paid members can play too. No paid-exclusive game servers are currently included.

    -
    How do membership giveaways work?

    Giveaways are associated with a membership tier. Higher tiers include giveaway benefits from lower tiers, including Open Lab. Each giveaway's rules will list its availability, dates, prizes and any eligibility restrictions. Membership does not guarantee a prize.

    -
    What do membership polls influence?

    Gold (Level 3) and above can share preferences about future project topics and experiments. Platinum (Level 4) and Diamond (Level 5) also receive separate polls about the direction of eom.dev itself. Results inform my decisions; they are not binding commitments or guarantees of particular features.

    +
    How much should I give?

    Whatever feels right. Every amount gets the same benefits. To change your amount later, cancel in Manage billing, and once that membership ends, subscribe again with the new amount.

    +
    What happened to Bronze, Silver, Gold, Platinum and Diamond?

    They are now one pay-what-you-want Supporter membership. If you already have one of those memberships, nothing changes: it keeps working until you cancel it. To switch to an amount you choose, cancel in Manage billing, and once it ends, subscribe again as a Supporter.

    What happens when a membership ends?

    Your free eom.dev account stays. Member-only access ends when your paid membership expires. An immediate cancellation removes that access once your membership status updates.

    -
    Where do members connect?

    On Discourse, Harmony and Mastodon, which come with every membership level, including the free one. Bronze and above also receive exclusive content on Discourse and Harmony.

    +
    Where do members connect?

    On Discourse, Harmony and Mastodon, which come with every membership level, including the free one. Supporters also receive supporter-only posts on Discourse and Harmony.

    Can I change or cancel a plan?

    Use Manage billing after signing in. The billing portal offers the changes enabled for your plan. Cancellation at period end keeps access through the paid expiry date.

    {% if shkeeper_enabled %}
    How do crypto memberships renew?

    SHKeeper payments prepay one calendar month, without automatic charges. Create a new invoice for each renewal. Confirmed payment on the same tier extends its prepaid term. Partial or unconfirmed payments do not grant access. Do not send renewal funds to an old invoice address.

    {% endif %}
    diff --git a/membership/tiers.eom.json b/membership/tiers.eom.json index e02097b..7ce31d4 100755 --- a/membership/tiers.eom.json +++ b/membership/tiers.eom.json @@ -1,69 +1,78 @@ -{ - "level-1": { - "level": 1, - "label": "Bronze", - "price_id": "price_1Rgv4xC5KPXqTvVLfMd6z7wn", - "price_label": "$4 USD / month", - "usd_amount": "4.00", - "group_dn": "cn=Level 1,ou=Memberships,dc=eom,dc=dev", - "description": "Go beyond the public feed.", - "benefits": [ - "Exclusive Discourse and Harmony content, including work-in-progress updates", - "Bronze-tier giveaways", - "Optional credit on the community supporters page" - ] - }, - "level-2": { - "level": 2, - "label": "Silver", - "price_id": "price_1Rgv5QC5KPXqTvVLv1PaHWb5", - "price_label": "$8 USD / month", - "usd_amount": "8.00", - "group_dn": "cn=Level 2,ou=Memberships,dc=eom,dc=dev", - "description": "Try new work before release.", - "benefits": [ - "Silver-tier giveaways", - "Early previews, playtests and listening sessions when available" - ] - }, - "level-3": { - "level": 3, - "label": "Gold", - "price_id": "price_1Rgv5rC5KPXqTvVL8Ol8sMUf", - "price_label": "$16 USD / month", - "usd_amount": "16.00", - "group_dn": "cn=Level 3,ou=Memberships,dc=eom,dc=dev", - "description": "Help shape the next experiment.", - "benefits": [ - "Gold-tier giveaways", - "Member polls on future project topics and experiments", - "Invitations to occasional small-group feedback sessions" - ] - }, - "level-4": { - "level": 4, - "label": "Platinum", - "price_id": "price_1Rgv6FC5KPXqTvVL39mAxYjm", - "price_label": "$32 USD / month", - "usd_amount": "32.00", - "group_dn": "cn=Level 4,ou=Memberships,dc=eom,dc=dev", - "description": "Have a voice in the platform's direction.", - "benefits": [ - "Platinum-tier giveaways", - "Exclusive platform-direction polls" - ] - }, - "level-5": { - "level": 5, - "label": "Diamond", - "price_id": "price_1Rgv6mC5KPXqTvVLkcmznWZa", - "price_label": "$64 USD / month", - "usd_amount": "64.00", - "group_dn": "cn=Level 5,ou=Memberships,dc=eom,dc=dev", - "description": "Give the independent work its biggest boost.", - "benefits": [ - "Diamond-tier giveaways", - "Optional Diamond credit on the supporters page" - ] - } -} +{ + "level-1": { + "level": 1, + "label": "Supporter", + "price_id": "price_1Rgv4xC5KPXqTvVLfMd6z7wn", + "price_label": "Pay what you want \u00b7 from $3 USD / month", + "pay_what_you_want": { + "product_id": "prod_Sc9N5J0vNAdLCn", + "min_usd": "3.00", + "suggested_usd": "8.00", + "max_usd": "500.00" + }, + "group_dn": "cn=Level 1,ou=Memberships,dc=eom,dc=dev", + "description": "Keep the lab running between drops, at whatever monthly amount feels right. Every amount gets the same benefits.", + "benefits": [ + "Optional thanks in the credits of every drop", + "Supporter-only posts on Discourse and Harmony, including work in progress", + "Early builds and playtests when they exist" + ] + }, + "level-2": { + "level": 2, + "label": "Silver", + "price_id": "price_1Rgv5QC5KPXqTvVLv1PaHWb5", + "price_label": "$8 USD / month", + "usd_amount": "8.00", + "hidden": true, + "group_dn": "cn=Level 2,ou=Memberships,dc=eom,dc=dev", + "description": "Try new work before release.", + "benefits": [ + "Silver-tier giveaways", + "Early previews, playtests and listening sessions when available" + ] + }, + "level-3": { + "level": 3, + "label": "Gold", + "price_id": "price_1Rgv5rC5KPXqTvVL8Ol8sMUf", + "price_label": "$16 USD / month", + "usd_amount": "16.00", + "hidden": true, + "group_dn": "cn=Level 3,ou=Memberships,dc=eom,dc=dev", + "description": "Help shape the next experiment.", + "benefits": [ + "Gold-tier giveaways", + "Member polls on future project topics and experiments", + "Invitations to occasional small-group feedback sessions" + ] + }, + "level-4": { + "level": 4, + "label": "Platinum", + "price_id": "price_1Rgv6FC5KPXqTvVL39mAxYjm", + "price_label": "$32 USD / month", + "usd_amount": "32.00", + "hidden": true, + "group_dn": "cn=Level 4,ou=Memberships,dc=eom,dc=dev", + "description": "Have a voice in the platform's direction.", + "benefits": [ + "Platinum-tier giveaways", + "Exclusive platform-direction polls" + ] + }, + "level-5": { + "level": 5, + "label": "Diamond", + "price_id": "price_1Rgv6mC5KPXqTvVLkcmznWZa", + "price_label": "$64 USD / month", + "usd_amount": "64.00", + "hidden": true, + "group_dn": "cn=Level 5,ou=Memberships,dc=eom,dc=dev", + "description": "Give the independent work its biggest boost.", + "benefits": [ + "Diamond-tier giveaways", + "Optional Diamond credit on the supporters page" + ] + } +} diff --git a/tests/site.test.mjs b/tests/site.test.mjs index 9a59b0a..7ce2abc 100755 --- a/tests/site.test.mjs +++ b/tests/site.test.mjs @@ -269,7 +269,8 @@ test('homepage groups creative sections before the library and membership distin assert.ok(positions.every((position, index) => position >= 0 && (!index || position > positions[index - 1]))); const template = await readFile(new URL('membership/templates/members.html', repository), 'utf8'); assert.match(template, /services included at your membership level/u); - assert.match(template, /Bronze adds exclusive Discourse and Harmony content; Silver adds previews when available; Gold adds project-topic polls/u); + assert.match(template, /I work in bursts, not on a schedule/u); + assert.doesNotMatch(template, /giveaway/iu); assert.ok(template.indexOf('class="member-grid"') < template.indexOf('Community services by level')); assert.match(template, /No paid-exclusive game servers are currently included/u); assert.match(template, /There is no fixed release schedule/u);