Skip to content
Merged
37 changes: 37 additions & 0 deletions squarelet/organizations/entitlement_shape.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,40 @@ def grants_old(resources, quantity):
* resources.get(f"{base_key[len(BASE_PREFIX):]}{PER_USER_SUFFIX}", 0)
for base_key in base_keys(resources)
}


def grants_new(resources, quantity):
"""What the clients grant once they switch: `base * quantity`."""
return {
base_key: resources[base_key] * quantity for base_key in base_keys(resources)
}


def grant_old(resources, quantity):
"""`grants_old` totalled, for an entitlement with one key."""
return sum(grants_old(resources, quantity).values())


def grant_new(resources, quantity):
"""`grants_new` totalled, for an entitlement with one key."""
return sum(grants_new(resources, quantity).values())


def reshape(resources, *, is_pack):
"""The shape in which both formulas give the same number.

`minimum_users = 1` and `per_user = base` make `base + max(q - 1, 0) * base`
equal `base * q` for every q >= 1. A pack's value lives in `per_user` with
`base` at zero, so it moves the other way; the tier transform would zero it.
"""
new = dict(resources)
pairs = scaling_pairs(resources)
if not pairs:
return new
for per_user_key, base_key in pairs:
if is_pack:
new[base_key] = resources[per_user_key]
else:
new[per_user_key] = resources[base_key]
new["minimum_users"] = 1
return new
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,11 @@
EXPECTED_GRANT_CHANGES,
LEGACY_PLAN_MAP,
PACK_DECOMPOSITION,
PACK_SLUGS,
)

logger = logging.getLogger(__name__)

# Pack lines are this command's output, never its input.
PACK_SLUGS = {slug for packs in PACK_DECOMPOSITION.values() for slug in packs}


def is_billing(item):
"""Whether Stripe is charging for this line.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
# Django
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

# Standard Library
import collections

# Squarelet
from squarelet.organizations.entitlement_shape import (
BASE_PREFIX,
grants_new,
grants_old,
reshape,
scaling_pairs,
)
from squarelet.organizations.models.payment import Entitlement, Plan, SubscriptionItem
from squarelet.organizations.plan_mapping import PACK_SLUGS


def amounts(grants):
"""`{"base_requests": 50}` as "50 requests"."""
return ", ".join(
f"{amount} {key[len(BASE_PREFIX):]}" for key, amount in sorted(grants.items())
)


class Command(BaseCommand):
"""Move every entitlement onto a shape both grant formulas agree on.

Clients compute `base + max(quantity - minimum_users, 0) * per_user` and
will move to `base * quantity`; with `minimum_users = 1` and
`per_user = base` they agree, so either client can switch at any time.
Writes only `Entitlement.resources`. Needs the pricing migration first,
which puts every tier line at quantity 1, and `archive_legacy_plans`,
which stops new lines arriving above it.
"""

help = "Move every entitlement onto a shape both grant formulas agree on"

def add_arguments(self, parser):
parser.add_argument(
"--dry-run",
action="store_true",
help="Report what would change without writing anything",
)

def handle(self, *args, **options):
dry_run = options["dry_run"]
if dry_run:
self.stdout.write(self.style.WARNING("DRY RUN - nothing written"))

self._preflight()

counts = collections.Counter()
# Collected rather than raised at the first, so one dry run names all.
changed_grants = []
with transaction.atomic():
for entitlement in Entitlement.objects.prefetch_related(
"plans", "grants"
).order_by("pk"):
counts[self._migrate(entitlement, changed_grants)] += 1
if changed_grants:
raise CommandError(
"\n".join(changed_grants)
+ "\nThe transform is wrong for these shapes; nothing was "
"written."
)
if dry_run:
transaction.set_rollback(True)

self.stdout.write(
f"\n{counts['reshaped']} reshaped, {counts['unchanged']} already "
f"in shape, {counts['not_scaled']} do not scale with quantity, "
f"{counts['unused']} granted by nothing"
)

def _preflight(self):
"""Refuse while any line on a scaling tier is, or could be bought, above 1.

The formulas agree only at quantity 1: an Organization line at 30
would grant 1,500 instead of 300, to every client at once. Packs
are meant to be `base * q`, and a plan with no per-unit rate grants
the same at any quantity, so neither is refused.
"""
carrying = [
item
for item in SubscriptionItem.objects.select_related(
"subscription__organization", "plan"
)
.prefetch_related("plan__entitlements")
.exclude(plan__slug__in=PACK_SLUGS)
.filter(quantity__gt=1)
if any(
scaling_pairs(entitlement.resources)
for entitlement in item.plan.entitlements.all()
)
]
if carrying:
lines = "\n".join(
f" - {item.subscription.organization.slug}: {item.plan.slug} "
f"at quantity {item.quantity}"
for item in carrying
)
raise CommandError(
f"{len(carrying)} line(s) are not at quantity 1, and this "
f"step would multiply their grant instead of preserving it. "
f"Decompose or normalise them first:\n{lines}"
)

# `SubscriptionItem.objects.start` buys an unpriced plan at its
# minimum, a line the check above would have refused.
unpriced = [
plan.slug
for plan in Plan.objects.not_archived()
.exclude(slug__in=PACK_SLUGS)
.filter(minimum_users__gt=1)
.prefetch_related("entitlements")
if any(
scaling_pairs(entitlement.resources)
for entitlement in plan.entitlements.all()
)
and SubscriptionItem.objects.resolve_purchase(plan)[1] is None
]
if unpriced:
raise CommandError(
"These plans are on sale with no price, so a purchase would "
"start above quantity 1 and be overgranted. Archive them "
"first (archive_legacy_plans): " + ", ".join(sorted(unpriced))
)

mixed = [
entitlement.slug
for entitlement in Entitlement.objects.prefetch_related("plans")
if self._is_pack(entitlement) and self._is_tier(entitlement)
]
if mixed:
raise CommandError(
"These entitlements sit on both a pack plan and a tier, so "
"there is no single correct transform for them: "
+ ", ".join(sorted(mixed))
)
Comment thread
duckduckgrayduck marked this conversation as resolved.
Resolved

@staticmethod
def _is_pack(entitlement):
# A pack holds a per-unit value, a tier a flat grant; they reshape in
# opposite directions.
return any(plan.slug in PACK_SLUGS for plan in entitlement.plans.all())

@staticmethod
def _is_tier(entitlement):
return any(plan.slug not in PACK_SLUGS for plan in entitlement.plans.all())

def _migrate(self, entitlement, changed_grants):
# Without a plan it can't be told pack from tier, and no one receives
# it: left as it is rather than guessed.
if not entitlement.plans.all() and not entitlement.grants.all():
self.stdout.write(f" . {entitlement.slug}: nothing grants it, left alone")
return "unused"
is_pack = self._is_pack(entitlement)
target = reshape(entitlement.resources, is_pack=is_pack)

if not scaling_pairs(entitlement.resources):
self.stdout.write(
f" . {entitlement.slug}: no quantity-scaled resources, left alone"
)
return "not_scaled"
if target == entitlement.resources:
self.stdout.write(f" = {entitlement.slug}: already in shape")
return "unchanged"

kind = "pack" if is_pack else "tier"
self.stdout.write(
self.style.SUCCESS(
f" + {entitlement.slug} ({kind}): "
f"{entitlement.resources} -> {target}"
)
)
changed_grants.extend(self._check_grants(entitlement, target))
entitlement.resources = target
entitlement.save(update_fields=["resources"])
return "reshaped"

def _check_grants(self, entitlement, target):
"""Where a reshape would change what anyone receives.

Checked at every quantity held and always at 1, which covers unsold
packs and EntitlementGrants (served at quantity 1). Any one rolls
back every entitlement: it means the transform is wrong for that shape.
"""
changed = []
held = set(
SubscriptionItem.objects.filter(plan__entitlements=entitlement)
.values_list("quantity", flat=True)
.distinct()
)
for quantity in sorted(held | {1}):
# Per resource: a total can hide one going up as another goes down.
before = grants_old(entitlement.resources, quantity)
after_old = grants_old(target, quantity)
after_new = grants_new(target, quantity)
agree = before == after_old == after_new
arithmetic = (
f"{amounts(before)} today, {amounts(after_old)} under the old "
f"formula, {amounts(after_new)} under the new"
)
self.stdout.write(
f" quantity {quantity}: {arithmetic}"
+ ("" if agree else " <-- CHANGED")
)
if not agree:
changed.append(
f"{entitlement.slug}: reshaping would change the grant "
f"at quantity {quantity} - {arithmetic}."
)
return changed
11 changes: 11 additions & 0 deletions squarelet/organizations/plan_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,17 @@
# Bills at both cadences, which one map entry cannot say.
COHORT_SLUG = "election-accountability-cohort"

# Every pack plan, as 0082 seeds them: what decides "is this a pack?".
# PACK_DECOMPOSITION lists only the packs a legacy plan becomes, so a pack
# missing from it would get the tier reshape and grant nothing.
PACK_SLUGS = frozenset(
{
"muckrock-request-pack",
"documentcloud-credit-pack",
"scoutpost-credit-pack",
}
)

# Which pack a legacy plan's resource blocks become, for the plans production
# has block-holders on; the migration refuses any other.
PACK_DECOMPOSITION = {
Expand Down
Loading
Loading