SurfSense/surfsense_backend/app/schemas/stripe.py
Vonic 4eb6ed18d6 Epic 5 Complete: Billing, Subscriptions, and Admin Features
Resolve all 5 deferred items from Epic 5 adversarial code review:
- Migration 124: Add CASCADE to subscriptionstatus enum drop (prevent orphaned references)
- Stripe rate limiting: In-memory per-user limiter (20 calls/60s) on verify-checkout-session
- Subscription request cooldown: 24h cooldown before resubmitting rejected requests
- Token reset date: Initialize on first subscription activation
- Checkout URL validation: Confirmed HTTPS-only (Stripe always returns HTTPS)

Implement Story 5.4 (Usage Tracking & Rate Limit Enforcement):
- Page quota pre-check at HTTP upload layer
- Extend UserRead schema with token quota fields
- Frontend 402 error handling in document upload
- Quota indicator in dashboard sidebar

Story 5.5 (Admin Seed & Approval Flow):
- Seed admin user migration with default credentials warning
- Subscription approval/rejection routes with admin guard
- 24h rejection cooldown enforcement

Story 5.6 (Admin-Only Model Config):
- Global model config visible across all search spaces
- Per-search-space model configs with user access control
- Superuser CRUD for global configs

Additional fixes from code review:
- PageLimitService: PAST_DUE subscriptions enforce free-tier limits
- TokenQuotaService: PAST_DUE subscriptions enforce free-tier limits
- Config routes: Fixed user_id.is_(None) filter on mutation endpoints
- Stripe webhook: Added guard against silent plan downgrade on unrecognized price_id

All changes formatted with Ruff (Python) and Biome (TypeScript).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-15 03:54:45 +07:00

77 lines
1.9 KiB
Python

"""Schemas for Stripe-backed page purchases and subscriptions."""
import uuid
from datetime import datetime
from enum import Enum
from pydantic import BaseModel, ConfigDict, Field
from app.db import PagePurchaseStatus
class PlanId(str, Enum):
"""Supported subscription plan identifiers."""
pro_monthly = "pro_monthly"
pro_yearly = "pro_yearly"
class CreateCheckoutSessionRequest(BaseModel):
"""Request body for creating a page-purchase checkout session."""
quantity: int = Field(ge=1, le=100)
search_space_id: int = Field(ge=1)
class CreateSubscriptionCheckoutRequest(BaseModel):
"""Request body for creating a subscription checkout session."""
plan_id: PlanId
class CreateSubscriptionCheckoutResponse(BaseModel):
"""Response containing the Stripe-hosted subscription checkout URL."""
checkout_url: str
admin_approval_mode: bool = False
class CreateCheckoutSessionResponse(BaseModel):
"""Response containing the Stripe-hosted checkout URL."""
checkout_url: str
class StripeStatusResponse(BaseModel):
"""Response describing Stripe page-buying availability."""
page_buying_enabled: bool
class PagePurchaseRead(BaseModel):
"""Serialized page-purchase record for purchase history."""
id: uuid.UUID
stripe_checkout_session_id: str
stripe_payment_intent_id: str | None = None
quantity: int
pages_granted: int
amount_total: int | None = None
currency: str | None = None
status: PagePurchaseStatus
completed_at: datetime | None = None
created_at: datetime
model_config = ConfigDict(from_attributes=True)
class PagePurchaseHistoryResponse(BaseModel):
"""Response containing the authenticated user's page purchases."""
purchases: list[PagePurchaseRead]
class StripeWebhookResponse(BaseModel):
"""Generic acknowledgement for Stripe webhook delivery."""
received: bool = True