## Summary Implements [#16](#16), [#17](#17), and [#36](#36) in one backend PR. - **#36 Multi-plan catalog**: Founders ($10, public), Standard ($15), Pro ($40), Business ($99), Backer ($0). Future tiers seeded but hidden/`is_selectable=false`. Backer email whitelist auto-assigns Founders-level access with no checkout. - **#36 Feature + prompt gating**: plan feature flags (text vs image); rolling **6h** prompt windows (100 / 200 / 300 / 300 / 300). Enforced in both chat consumers when `ENFORCE_SUBSCRIPTION_GATES=true`. - **#17 Token-period quotas**: optional `monthly_token_quota` on plans + per-user override; calendar-month aggregation from `PromptMetric`; warn/block when reported token totals exceed cap. Null provider usage never fabricated as 0; tracked via `turns_missing_token_usage`. - **#16 Token API exposure**: `tokens_in` / `tokens_out` on conversation + prompt serializers (null when unknown). `GET /api/finance/subscription/` returns plan + usage snapshot for the FE. - Checkout defaults to **Founders**; Stripe paid webhooks assign Founders. Registration/OAuth redeem Backer whitelist and return `needs_checkout`. Companion FE PR: `chat_web_app` branch `feature/plans-quotas-token-usage`. ## Test plan - [ ] `manage.py migrate` seeds five plans; admin can add Backer emails - [ ] Public `GET /api/finance/plans/` returns only Founders - [ ] Register with Backer email → active Backer, `needs_checkout=false`, checkout rejected - [ ] Founders checkout + paid webhook → active Founders subscription - [ ] Chat turn blocked without subscription / when prompt window exceeded / when token period exceeded - [ ] Standard plan denies image feature; Pro/Founders/Backer allow - [ ] Conversation/prompt API returns `null` tokens when unreported, sums when present - [ ] `finance.tests.test_plans_quotas` + existing finance/checkout tests passReviewed-on: #37
This commit was merged in pull request #37.
This commit is contained in:
@@ -5,6 +5,176 @@ from django.utils import timezone
|
||||
from chat_backend.models import Company, TimeInfoBase
|
||||
|
||||
|
||||
class SubscriptionPlan(TimeInfoBase):
|
||||
"""Catalog row for a billable (or complimentary) subscription tier."""
|
||||
|
||||
class Slug(models.TextChoices):
|
||||
FOUNDERS = "founders", "Founders"
|
||||
STANDARD = "standard", "Standard"
|
||||
PRO = "pro", "Pro / Creator"
|
||||
BUSINESS = "business", "Business Team"
|
||||
BACKER = "backer", "Backer"
|
||||
|
||||
slug = models.SlugField(max_length=64, unique=True, db_index=True)
|
||||
name = models.CharField(max_length=128)
|
||||
description = models.TextField(blank=True, default="")
|
||||
price_cents = models.PositiveIntegerField(
|
||||
default=0,
|
||||
help_text="List price in cents (0 for complimentary tiers).",
|
||||
)
|
||||
currency = models.CharField(max_length=8, default="usd")
|
||||
interval = models.CharField(max_length=16, default="month")
|
||||
stripe_price_id = models.CharField(
|
||||
max_length=255,
|
||||
blank=True,
|
||||
default="",
|
||||
help_text="Optional Stripe Price id; empty uses price_data at Checkout.",
|
||||
)
|
||||
is_public = models.BooleanField(
|
||||
default=False,
|
||||
help_text="Shown in public pricing / plan list APIs.",
|
||||
)
|
||||
is_selectable = models.BooleanField(
|
||||
default=False,
|
||||
help_text="Selectable at Checkout. Backer is never selectable.",
|
||||
)
|
||||
allows_text_generation = models.BooleanField(default=True)
|
||||
allows_image_generation = models.BooleanField(default=False)
|
||||
allows_all_future_features = models.BooleanField(
|
||||
default=False,
|
||||
help_text="Founders/Backer: unlock new capabilities as they ship.",
|
||||
)
|
||||
prompt_quota_per_window = models.PositiveIntegerField(
|
||||
help_text="Max prompts allowed in each rolling window.",
|
||||
)
|
||||
prompt_window_hours = models.PositiveIntegerField(
|
||||
default=6,
|
||||
help_text="Length of the rolling prompt quota window in hours.",
|
||||
)
|
||||
monthly_token_quota = models.PositiveIntegerField(
|
||||
null=True,
|
||||
blank=True,
|
||||
help_text=(
|
||||
"Optional billing-period token cap (tokens_in + tokens_out). "
|
||||
"Null = no token-period limit (prompt window still applies)."
|
||||
),
|
||||
)
|
||||
sort_order = models.PositiveIntegerField(default=0)
|
||||
|
||||
class Meta:
|
||||
ordering = ["sort_order", "price_cents", "name"]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.name} ({self.slug})"
|
||||
|
||||
def allows_feature(self, feature: str) -> bool:
|
||||
if self.allows_all_future_features:
|
||||
return True
|
||||
if feature in ("text", "text_generation"):
|
||||
return self.allows_text_generation
|
||||
if feature in ("image", "image_generation"):
|
||||
return self.allows_image_generation
|
||||
return False
|
||||
|
||||
|
||||
class BackerEmail(TimeInfoBase):
|
||||
"""Pre-registered emails that receive complimentary Backer (Founders-level) access."""
|
||||
|
||||
email = models.EmailField(unique=True, db_index=True)
|
||||
note = models.CharField(max_length=512, blank=True, default="")
|
||||
redeemed_at = models.DateTimeField(null=True, blank=True)
|
||||
redeemed_user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.SET_NULL,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name="backer_email_entries",
|
||||
)
|
||||
|
||||
class Meta:
|
||||
ordering = ["email"]
|
||||
verbose_name = "Backer email"
|
||||
verbose_name_plural = "Backer emails"
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.email
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
if self.email:
|
||||
self.email = self.email.strip().lower()
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
|
||||
class UserSubscription(TimeInfoBase):
|
||||
"""Per-user plan assignment (Stripe, Backer whitelist, or admin)."""
|
||||
|
||||
class Status(models.TextChoices):
|
||||
NONE = "none", "None"
|
||||
ACTIVE = "active", "Active"
|
||||
PAST_DUE = "past_due", "Past due"
|
||||
CANCELED = "canceled", "Canceled"
|
||||
|
||||
class Source(models.TextChoices):
|
||||
NONE = "none", "None"
|
||||
STRIPE = "stripe", "Stripe"
|
||||
BACKER = "backer", "Backer"
|
||||
ADMIN = "admin", "Admin"
|
||||
|
||||
user = models.OneToOneField(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="subscription",
|
||||
)
|
||||
plan = models.ForeignKey(
|
||||
SubscriptionPlan,
|
||||
on_delete=models.PROTECT,
|
||||
related_name="subscriptions",
|
||||
null=True,
|
||||
blank=True,
|
||||
)
|
||||
status = models.CharField(
|
||||
max_length=32,
|
||||
choices=Status.choices,
|
||||
default=Status.NONE,
|
||||
db_index=True,
|
||||
)
|
||||
source = models.CharField(
|
||||
max_length=32,
|
||||
choices=Source.choices,
|
||||
default=Source.NONE,
|
||||
)
|
||||
stripe_subscription_id = models.CharField(
|
||||
max_length=255,
|
||||
blank=True,
|
||||
default="",
|
||||
db_index=True,
|
||||
)
|
||||
monthly_token_quota_override = models.PositiveIntegerField(
|
||||
null=True,
|
||||
blank=True,
|
||||
help_text="Optional per-user override of plan monthly_token_quota.",
|
||||
)
|
||||
|
||||
class Meta:
|
||||
verbose_name = "User subscription"
|
||||
verbose_name_plural = "User subscriptions"
|
||||
|
||||
def __str__(self) -> str:
|
||||
plan = self.plan.slug if self.plan_id else "none"
|
||||
return f"UserSubscription user={self.user_id} plan={plan} ({self.status})"
|
||||
|
||||
@property
|
||||
def is_active(self) -> bool:
|
||||
return self.status == self.Status.ACTIVE and self.plan_id is not None
|
||||
|
||||
def effective_monthly_token_quota(self):
|
||||
if self.monthly_token_quota_override is not None:
|
||||
return self.monthly_token_quota_override
|
||||
if self.plan_id:
|
||||
return self.plan.monthly_token_quota
|
||||
return None
|
||||
|
||||
|
||||
class Invoice(TimeInfoBase):
|
||||
"""Local ledger row for a billed period / Stripe invoice or checkout session."""
|
||||
|
||||
|
||||
Reference in New Issue
Block a user