Monetization app + RevenueCat webhooks (store IAP ledger) (#69)
Deploy Beta / unit-tests (push) Successful in 11s
Unit Tests / test (push) Successful in 11s
Deploy Beta / docker (push) Successful in 21s
Deploy Beta / deploy-beta (push) Successful in 50s

## Summary
- Rename `finance` → **`monetization`** Django app (keep `finance_*` tables via `label = "finance"`)
- Add `services/stripe.py` + `services/revenuecat.py`; RevenueCat webhook upserts **subscription + Invoice/Payment** (billing history parity with Stripe)
- Mount `/api/monetization/` + keep `/api/finance/` alias
- Extend `Source`/`Provider` with `revenuecat`; product→plan mapping via `revenuecat_product_id` / `REVENUECAT_PRODUCT_PLAN_MAP`

Closes #68. Companion to [chat_web_app#100](ai_ml_operations/chat_web_app#100).

## Test plan
- [x] `manage.py test monetization.tests` (54 OK)
- [x] Smoke `chat_backend.tests.test_views_documents` + `test_oauth`
- [ ] Deploy: set `REVENUECAT_WEBHOOK_SECRET`; point RC webhook at `/api/finance/webhooks/revenuecat/`
- [ ] Map store product IDs on `SubscriptionPlan.revenuecat_product_id` (or env JSON map)
- [ ] Sandbox INITIAL_PURCHASE → subscription `source=revenuecat` + invoice in `/finance/invoices/`Reviewed-on: #69
This commit was merged in pull request #69.
This commit is contained in:
2026-08-04 03:40:15 -07:00
parent 2aeb95136a
commit e1e086a474
44 changed files with 965 additions and 102 deletions
@@ -0,0 +1,237 @@
# Generated by Django 6.0 on 2026-07-27 00:16
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
("chat_backend", "0023_promptmetric_tokens_in_promptmetric_tokens_out"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="Invoice",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("created", models.DateTimeField(default=django.utils.timezone.now)),
(
"last_modified",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"provider",
models.CharField(
choices=[("stripe", "Stripe")], default="stripe", max_length=32
),
),
(
"status",
models.CharField(
choices=[
("draft", "Draft"),
("open", "Open"),
("paid", "Paid"),
("void", "Void"),
("uncollectible", "Uncollectible"),
("payment_failed", "Payment failed"),
],
db_index=True,
default="open",
max_length=32,
),
),
("currency", models.CharField(default="usd", max_length=8)),
(
"amount_due",
models.PositiveIntegerField(
default=0,
help_text="Amount due in the smallest currency unit (e.g. cents).",
),
),
(
"amount_paid",
models.PositiveIntegerField(
default=0,
help_text="Amount paid in the smallest currency unit (e.g. cents).",
),
),
("period_start", models.DateTimeField(blank=True, null=True)),
("period_end", models.DateTimeField(blank=True, null=True)),
(
"stripe_invoice_id",
models.CharField(
blank=True,
db_index=True,
max_length=255,
null=True,
unique=True,
),
),
(
"stripe_checkout_session_id",
models.CharField(
blank=True,
db_index=True,
max_length=255,
null=True,
unique=True,
),
),
(
"stripe_subscription_id",
models.CharField(
blank=True, db_index=True, max_length=255, null=True
),
),
(
"stripe_customer_id",
models.CharField(blank=True, default="", max_length=255),
),
("hosted_invoice_url", models.URLField(blank=True, default="")),
(
"description",
models.CharField(blank=True, default="", max_length=512),
),
(
"company",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="invoices",
to="chat_backend.company",
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="invoices",
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"ordering": ["-created"],
},
),
migrations.CreateModel(
name="Payment",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("created", models.DateTimeField(default=django.utils.timezone.now)),
(
"last_modified",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"provider",
models.CharField(
choices=[("stripe", "Stripe")], default="stripe", max_length=32
),
),
(
"status",
models.CharField(
choices=[
("pending", "Pending"),
("succeeded", "Succeeded"),
("failed", "Failed"),
("canceled", "Canceled"),
("requires_action", "Requires action"),
],
db_index=True,
default="pending",
max_length=32,
),
),
("currency", models.CharField(default="usd", max_length=8)),
(
"amount",
models.PositiveIntegerField(
default=0,
help_text="Amount in the smallest currency unit (e.g. cents).",
),
),
(
"stripe_payment_intent_id",
models.CharField(
blank=True,
db_index=True,
max_length=255,
null=True,
unique=True,
),
),
(
"stripe_charge_id",
models.CharField(
blank=True,
db_index=True,
max_length=255,
null=True,
unique=True,
),
),
("paid_at", models.DateTimeField(blank=True, null=True)),
(
"failure_message",
models.CharField(blank=True, default="", max_length=512),
),
(
"company",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="payments",
to="chat_backend.company",
),
),
(
"invoice",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="payments",
to="finance.invoice",
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="payments",
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"ordering": ["-created"],
},
),
]
@@ -0,0 +1,190 @@
# Generated by Django 6.0 on 2026-07-31 11:14
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
def seed_plans(apps, schema_editor):
"""Seed the original 5-plan catalog frozen at this migration's schema.
Deliberately does NOT import ``finance.services.plans`` — that module's
``PLAN_SEED``/model class reflect the *current* code, so a later required
field (e.g. ``allows_rag`` added in #43) would make this historical
RunPython try to write a column that doesn't exist yet when a fresh
database replays migrations in order. Live code re-seeds (and adds any
new fields) via ``seed_subscription_plans()`` calls elsewhere (app
startup, quota checks, test setUp), so this only needs to create the
original rows.
"""
SubscriptionPlan = apps.get_model("finance", "SubscriptionPlan")
seed = [
{
"slug": "founders",
"name": "Founders",
"description": (
"Unlimited product access for early supporters: text plus all future "
"capabilities as they ship. $10/mo."
),
"price_cents": 1000,
"is_public": True,
"is_selectable": True,
"allows_text_generation": True,
"allows_image_generation": True,
"allows_all_future_features": True,
"prompt_quota_per_window": 300,
"prompt_window_hours": 6,
"monthly_token_quota": None,
"sort_order": 10,
},
{
"slug": "standard",
"name": "Standard",
"description": (
"Secure conversational chat and coding assistance for developers "
"and privacy-conscious individuals."
),
"price_cents": 1500,
"is_public": False,
"is_selectable": False,
"allows_text_generation": True,
"allows_image_generation": False,
"allows_all_future_features": False,
"prompt_quota_per_window": 100,
"prompt_window_hours": 6,
"monthly_token_quota": 1_000_000,
"sort_order": 20,
},
{
"slug": "pro",
"name": "Pro / Creator",
"description": (
"Higher message caps and multi-modal workflows for heavy users, "
"including image generation when available."
),
"price_cents": 4000,
"is_public": False,
"is_selectable": False,
"allows_text_generation": True,
"allows_image_generation": True,
"allows_all_future_features": False,
"prompt_quota_per_window": 200,
"prompt_window_hours": 6,
"monthly_token_quota": 3_000_000,
"sort_order": 30,
},
{
"slug": "business",
"name": "Business Team",
"description": (
"Team seats, centralized auth, priority support, and absolute data "
"privacy for local companies handling sensitive data."
),
"price_cents": 9900,
"is_public": False,
"is_selectable": False,
"allows_text_generation": True,
"allows_image_generation": True,
"allows_all_future_features": False,
"prompt_quota_per_window": 300,
"prompt_window_hours": 6,
"monthly_token_quota": 5_000_000,
"sort_order": 40,
},
{
"slug": "backer",
"name": "Backer",
"description": (
"Complimentary Founders-level access for pre-approved emails. "
"Not shown at checkout."
),
"price_cents": 0,
"is_public": False,
"is_selectable": False,
"allows_text_generation": True,
"allows_image_generation": True,
"allows_all_future_features": True,
"prompt_quota_per_window": 300,
"prompt_window_hours": 6,
"monthly_token_quota": None,
"sort_order": 5,
},
]
for row in seed:
slug = row.pop("slug")
SubscriptionPlan.objects.get_or_create(slug=slug, defaults=row)
class Migration(migrations.Migration):
dependencies = [
('finance', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='SubscriptionPlan',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(default=django.utils.timezone.now)),
('last_modified', models.DateTimeField(default=django.utils.timezone.now)),
('slug', models.SlugField(max_length=64, unique=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(default='usd', max_length=8)),
('interval', models.CharField(default='month', max_length=16)),
('stripe_price_id', models.CharField(blank=True, default='', help_text='Optional Stripe Price id; empty uses price_data at Checkout.', max_length=255)),
('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(blank=True, help_text='Optional billing-period token cap (tokens_in + tokens_out). Null = no token-period limit (prompt window still applies).', null=True)),
('sort_order', models.PositiveIntegerField(default=0)),
],
options={
'ordering': ['sort_order', 'price_cents', 'name'],
},
),
migrations.CreateModel(
name='BackerEmail',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(default=django.utils.timezone.now)),
('last_modified', models.DateTimeField(default=django.utils.timezone.now)),
('email', models.EmailField(db_index=True, max_length=254, unique=True)),
('note', models.CharField(blank=True, default='', max_length=512)),
('redeemed_at', models.DateTimeField(blank=True, null=True)),
('redeemed_user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='backer_email_entries', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'Backer email',
'verbose_name_plural': 'Backer emails',
'ordering': ['email'],
},
),
migrations.CreateModel(
name='UserSubscription',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(default=django.utils.timezone.now)),
('last_modified', models.DateTimeField(default=django.utils.timezone.now)),
('status', models.CharField(choices=[('none', 'None'), ('active', 'Active'), ('past_due', 'Past due'), ('canceled', 'Canceled')], db_index=True, default='none', max_length=32)),
('source', models.CharField(choices=[('none', 'None'), ('stripe', 'Stripe'), ('backer', 'Backer'), ('admin', 'Admin')], default='none', max_length=32)),
('stripe_subscription_id', models.CharField(blank=True, db_index=True, default='', max_length=255)),
('monthly_token_quota_override', models.PositiveIntegerField(blank=True, help_text='Optional per-user override of plan monthly_token_quota.', null=True)),
('plan', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='subscriptions', to='finance.subscriptionplan')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='subscription', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'User subscription',
'verbose_name_plural': 'User subscriptions',
},
),
migrations.RunPython(seed_plans, migrations.RunPython.noop),
]
@@ -0,0 +1,30 @@
# Generated by Django 6.0 on 2026-08-01 19:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("finance", "0002_subscription_plans_quotas"),
]
operations = [
migrations.AddField(
model_name="usersubscription",
name="cancel_at_period_end",
field=models.BooleanField(
default=False,
help_text="Stripe: subscription will cancel at current_period_end.",
),
),
migrations.AddField(
model_name="usersubscription",
name="current_period_end",
field=models.DateTimeField(
blank=True,
help_text="Stripe billing period end (access remains until then when canceling).",
null=True,
),
),
]
@@ -0,0 +1,21 @@
# Generated by Django 6.0 on 2026-08-01 20:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("finance", "0003_subscription_cancel_period_fields"),
]
operations = [
migrations.AddField(
model_name="subscriptionplan",
name="allows_rag",
field=models.BooleanField(
default=False,
help_text="Drive/RAG document sync (Google Drive, OneDrive, SharePoint).",
),
),
]
@@ -0,0 +1,63 @@
# Generated by Django 6.0 on 2026-08-03 19:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('finance', '0004_subscriptionplan_allows_rag'),
]
operations = [
migrations.AddField(
model_name='invoice',
name='revenuecat_event_id',
field=models.CharField(blank=True, db_index=True, help_text='RevenueCat webhook event id (idempotency key).', max_length=255, null=True, unique=True),
),
migrations.AddField(
model_name='invoice',
name='revenuecat_store',
field=models.CharField(blank=True, default='', help_text='APP_STORE / PLAY_STORE / etc.', max_length=32),
),
migrations.AddField(
model_name='payment',
name='revenuecat_transaction_id',
field=models.CharField(blank=True, db_index=True, help_text='Store transaction id from RevenueCat.', max_length=255, null=True, unique=True),
),
migrations.AddField(
model_name='subscriptionplan',
name='revenuecat_product_id',
field=models.CharField(blank=True, db_index=True, default='', help_text='Store/RevenueCat product identifier (Play + App Store).', max_length=255),
),
migrations.AddField(
model_name='usersubscription',
name='revenuecat_original_transaction_id',
field=models.CharField(blank=True, db_index=True, default='', help_text='Store original transaction id from RevenueCat events.', max_length=255),
),
migrations.AlterField(
model_name='invoice',
name='provider',
field=models.CharField(choices=[('stripe', 'Stripe'), ('revenuecat', 'RevenueCat')], default='stripe', max_length=32),
),
migrations.AlterField(
model_name='payment',
name='provider',
field=models.CharField(choices=[('stripe', 'Stripe'), ('revenuecat', 'RevenueCat')], default='stripe', max_length=32),
),
migrations.AlterField(
model_name='usersubscription',
name='cancel_at_period_end',
field=models.BooleanField(default=False, help_text='Subscription will cancel at current_period_end.'),
),
migrations.AlterField(
model_name='usersubscription',
name='current_period_end',
field=models.DateTimeField(blank=True, help_text='Billing period end (access remains until then when canceling).', null=True),
),
migrations.AlterField(
model_name='usersubscription',
name='source',
field=models.CharField(choices=[('none', 'None'), ('stripe', 'Stripe'), ('revenuecat', 'RevenueCat'), ('backer', 'Backer'), ('admin', 'Admin')], default='none', max_length=32),
),
]