Files
chat_backend/llm_be/finance/models.py
T
westfarn ad44359804
Unit Tests / test (push) Successful in 10s
Add finance app with Stripe Checkout subscriptions (#21) (#23)
## Summary
- Closes #21 — new Django `finance` app with Stripe as payment provider
- Subscription price defaults to **$10 USD / month** via `SUBSCRIPTION_PRICE_AMOUNT_CENTS = 1000` in `settings.py` (env-overridable)
- Persists **Invoice** and **Payment** rows; both registered in Django admin (with payment inline on invoices)
- Checkout Session API redirects users to Stripe hosted payment; webhook verifies signatures and upserts ledger idempotently

## API
- `POST /api/finance/checkout/` — JWT auth → `{ checkout_url, session_id }`
- `GET /api/finance/invoices/` / `GET /api/finance/payments/` — own records
- `POST /api/finance/webhooks/stripe/` — Stripe signature-verified webhook

## Config
Documented in `.env.example` / `.env.prod.example`:
`STRIPE_SECRET_KEY`, `STRIPE_PUBLISHABLE_KEY`, `STRIPE_WEBHOOK_SECRET`, optional `STRIPE_PRICE_ID`, `FRONTEND_BASE_URL`

## Test plan
- [x] `uv run python manage.py test finance` (17 tests)
- [ ] Set Stripe test keys locally; create checkout session; complete payment in Stripe test mode
- [ ] Confirm Invoice/Payment appear in `/admin/`
- [ ] Point Stripe webhook to `/api/finance/webhooks/stripe/` and verify `checkout.session.completed` / `invoice.paid`Reviewed-on: #23
2026-07-26 17:35:06 -07:00

162 lines
4.6 KiB
Python

from django.conf import settings
from django.db import models
from django.utils import timezone
from chat_backend.models import Company, TimeInfoBase
class Invoice(TimeInfoBase):
"""Local ledger row for a billed period / Stripe invoice or checkout session."""
class Provider(models.TextChoices):
STRIPE = "stripe", "Stripe"
class Status(models.TextChoices):
DRAFT = "draft", "Draft"
OPEN = "open", "Open"
PAID = "paid", "Paid"
VOID = "void", "Void"
UNCOLLECTIBLE = "uncollectible", "Uncollectible"
PAYMENT_FAILED = "payment_failed", "Payment failed"
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="invoices",
)
company = models.ForeignKey(
Company,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="invoices",
)
provider = models.CharField(
max_length=32,
choices=Provider.choices,
default=Provider.STRIPE,
)
status = models.CharField(
max_length=32,
choices=Status.choices,
default=Status.OPEN,
db_index=True,
)
currency = models.CharField(max_length=8, default="usd")
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(null=True, blank=True)
period_end = models.DateTimeField(null=True, blank=True)
stripe_invoice_id = models.CharField(
max_length=255,
blank=True,
null=True,
unique=True,
db_index=True,
)
stripe_checkout_session_id = models.CharField(
max_length=255,
blank=True,
null=True,
unique=True,
db_index=True,
)
stripe_subscription_id = models.CharField(
max_length=255,
blank=True,
null=True,
db_index=True,
)
stripe_customer_id = models.CharField(max_length=255, blank=True, default="")
hosted_invoice_url = models.URLField(blank=True, default="")
description = models.CharField(max_length=512, blank=True, default="")
class Meta:
ordering = ["-created"]
def __str__(self) -> str:
return f"Invoice {self.pk} ({self.status}) user={self.user_id}"
class Payment(TimeInfoBase):
"""Local ledger row for a payment attempt / Stripe PaymentIntent or charge."""
class Provider(models.TextChoices):
STRIPE = "stripe", "Stripe"
class Status(models.TextChoices):
PENDING = "pending", "Pending"
SUCCEEDED = "succeeded", "Succeeded"
FAILED = "failed", "Failed"
CANCELED = "canceled", "Canceled"
REQUIRES_ACTION = "requires_action", "Requires action"
invoice = models.ForeignKey(
Invoice,
on_delete=models.CASCADE,
related_name="payments",
null=True,
blank=True,
)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="payments",
)
company = models.ForeignKey(
Company,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="payments",
)
provider = models.CharField(
max_length=32,
choices=Provider.choices,
default=Provider.STRIPE,
)
status = models.CharField(
max_length=32,
choices=Status.choices,
default=Status.PENDING,
db_index=True,
)
currency = models.CharField(max_length=8, default="usd")
amount = models.PositiveIntegerField(
default=0,
help_text="Amount in the smallest currency unit (e.g. cents).",
)
stripe_payment_intent_id = models.CharField(
max_length=255,
blank=True,
null=True,
unique=True,
db_index=True,
)
stripe_charge_id = models.CharField(
max_length=255,
blank=True,
null=True,
unique=True,
db_index=True,
)
paid_at = models.DateTimeField(null=True, blank=True)
failure_message = models.CharField(max_length=512, blank=True, default="")
class Meta:
ordering = ["-created"]
def __str__(self) -> str:
return f"Payment {self.pk} ({self.status}) user={self.user_id}"
def mark_succeeded(self, *, paid_at=None):
self.status = self.Status.SUCCEEDED
self.paid_at = paid_at or timezone.now()
self.save(update_fields=["status", "paid_at", "last_modified"])