Rework platform billing: per-plan clocks, grace from period start
Implements BILLING.md. The architecture was sound -- snapshot-on-Due, dated prices, asymmetric dry-run commands are all kept -- so this fixes the three hardcoded assumptions rather than rewriting. The real defect: grace ran from period_END, so an annual club used the whole unpaid year plus 45 days (~410 days) before anything switched it off. Grace now runs from the period START, and every clock is per-plan. - Tier -> Plan (+ TierPrice -> PlanPrice, and every FK). Migration 0004 is hand-written: run non-interactively, makemigrations emits DeleteModel+CreateModel and drops every price, subscription and due. Its two RemoveConstraints must come first, or SQLite's table-rebuild tries to render a constraint over a just-renamed column. Verified by round-tripping real rows through it. - Plan gains duration_months / renewal_lead_days / grace_days / is_trial, with CheckConstraints and a matching clean() so the form reports an impossible plan instead of 500ing on IntegrityError. - Existing dues keep their stored grace_until. Re-deriving it would put the date in the past for every open annual period and archive the entire paying customer base on the next --commit run. - Trials take their length from the trial plan's own duration_months; start_trial() loses its trial_months argument. - New BillingNotice service drives a club-facing warning: every level on the dashboard, and on every management page once urgent. - send_billing_reminders emails club admins, once per escalation level so a daily cron is not a daily email. SMTP settings are env-driven and provider-agnostic; the backend defaults to console. - Paying does not auto-restore an archived club -- the control panel surfaces a Reactivate prompt instead, since a club can also be archived by hand.
This commit is contained in:
@@ -27,7 +27,7 @@ class Command(MaintenanceAwareCommand):
|
||||
|
||||
for due in overdue:
|
||||
days = (today - due.grace_until).days
|
||||
self.stdout.write(f"{due.club} — {due.tier}, {due.balance} owed, grace ended {due.grace_until} ({days} day{'s'[: days != 1]} ago)")
|
||||
self.stdout.write(f"{due.club} — {due.plan}, {due.balance} owed, grace ended {due.grace_until} ({days} day{'s'[: days != 1]} ago)")
|
||||
|
||||
if not options["commit"]:
|
||||
self.stdout.write(self.style.WARNING(f"\nDry run: {len(overdue)} club(s) would be archived. Re-run with --commit to do it."))
|
||||
|
||||
@@ -9,7 +9,6 @@ fires either. A missed renewal is silent, and silence is the expensive failure.
|
||||
|
||||
from django.core.management.base import CommandError
|
||||
|
||||
from billing.models import RENEWAL_LEAD_DAYS
|
||||
from billing.services import BillingError
|
||||
from billing.services.dues import renew, subscriptions_due_for_renewal
|
||||
from features.commands import MaintenanceAwareCommand
|
||||
@@ -20,7 +19,7 @@ class Command(MaintenanceAwareCommand):
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument("--dry-run", action="store_true", help="Report what would be issued, and issue nothing.")
|
||||
parser.add_argument("--lead-days", type=int, default=RENEWAL_LEAD_DAYS, help=f"Issue this many days before the period ends (default {RENEWAL_LEAD_DAYS}).")
|
||||
parser.add_argument("--lead-days", type=int, default=None, help="Override every plan's own renewal lead. Left off, each plan uses its own.")
|
||||
|
||||
def handle(self, *args, **options):
|
||||
due_for_renewal = subscriptions_due_for_renewal(lead_days=options["lead_days"])
|
||||
@@ -34,13 +33,13 @@ class Command(MaintenanceAwareCommand):
|
||||
club = subscription.club
|
||||
|
||||
if options["dry_run"]:
|
||||
self.stdout.write(f"would renew {club} — {subscription.tier}, current period ends {subscription.latest_period_end or 'never opened'}")
|
||||
self.stdout.write(f"would renew {club} — {subscription.plan}, current period ends {subscription.latest_period_end or 'never opened'}")
|
||||
continue
|
||||
|
||||
try:
|
||||
due = renew(subscription)
|
||||
except BillingError as error:
|
||||
# One unpriced tier must not stop every other club from being billed.
|
||||
# One unpriced plan must not stop every other club from being billed.
|
||||
failures.append(f"{club}: {error}")
|
||||
self.stdout.write(self.style.ERROR(f"{club} — {error}"))
|
||||
continue
|
||||
|
||||
64
billing/management/commands/send_billing_reminders.py
Normal file
64
billing/management/commands/send_billing_reminders.py
Normal file
@@ -0,0 +1,64 @@
|
||||
"""Email club admins about platform fees they owe.
|
||||
|
||||
Reports by default and only sends with --commit, the same posture as archive_overdue_clubs
|
||||
and for a related reason: this one mails paying customers, and a bad clock, a bad import or a
|
||||
rehearsal against production data should cost you a confusing dry-run listing rather than a
|
||||
mailshot you cannot recall.
|
||||
|
||||
Idempotent across runs by design -- one reminder per due per escalation level, tracked on
|
||||
Due.last_reminder_level -- so a daily cron does not produce a daily email.
|
||||
"""
|
||||
|
||||
from django.core.management.base import CommandError
|
||||
|
||||
from billing.services.reminders import reminders_to_send, send_reminder
|
||||
from club.models import Club
|
||||
from features.commands import MaintenanceAwareCommand
|
||||
|
||||
|
||||
class Command(MaintenanceAwareCommand):
|
||||
help = "Email club admins about outstanding platform fees (dry run unless --commit)."
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument("--commit", action="store_true", help="Actually send. Without this the command only reports.")
|
||||
parser.add_argument("--force", action="store_true", help="Re-send even where a reminder already went out at this level.")
|
||||
|
||||
def handle(self, *args, **options):
|
||||
clubs = Club.objects.active().select_related("subscription", "subscription__plan").order_by("name")
|
||||
results = reminders_to_send(clubs, force=options["force"])
|
||||
|
||||
sendable = [result for result in results if result.sent]
|
||||
skipped = [result for result in results if not result.sent]
|
||||
|
||||
if not results:
|
||||
self.stdout.write(self.style.SUCCESS("Nothing owing. No reminders to send."))
|
||||
return
|
||||
|
||||
for result in skipped:
|
||||
style = self.style.WARNING if result.recipients else self.style.ERROR
|
||||
self.stdout.write(style(f"{result.club} — skipped: {result.skipped_reason}"))
|
||||
|
||||
for result in sendable:
|
||||
self.stdout.write(f"{result.notice.level:>7} · {result.club} — €{result.notice.amount_outstanding} owed, {result.notice.days_until_archive}d to archive → {', '.join(result.recipients)}")
|
||||
|
||||
if not options["commit"]:
|
||||
self.stdout.write(self.style.WARNING(f"\nDry run: {len(sendable)} reminder(s) would be sent. Re-run with --commit to send them."))
|
||||
return
|
||||
|
||||
failures = []
|
||||
for result in sendable:
|
||||
try:
|
||||
send_reminder(result.club, result.notice, recipients=result.recipients)
|
||||
except OSError as error:
|
||||
# One bad address or a momentary SMTP failure must not stop the rest of the
|
||||
# run: the clubs further down the list are the ones closest to being archived.
|
||||
failures.append(f"{result.club}: {error}")
|
||||
self.stdout.write(self.style.ERROR(f"{result.club} — {error}"))
|
||||
|
||||
sent = len(sendable) - len(failures)
|
||||
self.stdout.write(self.style.SUCCESS(f"\nSent {sent} reminder(s)."))
|
||||
|
||||
if failures:
|
||||
# Non-zero so cron mails you: a club that could not be warned is a club that gets
|
||||
# archived without notice.
|
||||
raise CommandError(f"{len(failures)} reminder(s) could not be sent:\n " + "\n ".join(failures))
|
||||
Reference in New Issue
Block a user