Files
orion/app/modules/billing/routes/api/store_checkout.py
Samir Boulahtit 7c43d6f4a2 refactor: fix all architecture validator findings (202 → 0)
Eliminate all 103 errors and 96 warnings from the architecture validator:

Phase 1 - Validator rules & YAML:
- Add NAM-001/NAM-002 exceptions for module-scoped router/service files
- Fix API-004 to detect # public comments on decorator lines
- Add module-specific exception bases to EXC-004 valid_bases
- Exclude storefront files from AUTH-004 store context check
- Add SVC-006 exceptions for loyalty service atomic commits
- Fix _get_rule() to search naming_rules and auth_rules categories
- Use plain # CODE comments instead of # noqa: CODE for custom rules

Phase 2 - Billing module (5 route files):
- Move _resolve_store_to_merchant to subscription_service
- Move tier/feature queries to feature_service, admin_subscription_service
- Extract 22 inline Pydantic schemas to billing/schemas/billing.py
- Replace all HTTPException with domain exceptions

Phase 3 - Loyalty module (4 routes + points_service):
- Add 7 domain exceptions (Apple auth, enrollment, device registration)
- Add service methods to card_service, program_service, apple_wallet_service
- Move all db.query() from routes to service layer
- Fix SVC-001: replace HTTPException in points_service with domain exception

Phase 4 - Remaining modules:
- tenancy: move store stats queries to admin_service
- cms: move platform resolution to content_page_service, add NoPlatformSubscriptionException
- messaging: move user/customer lookups to messaging_service
- Add ConfigDict(from_attributes=True) to ContentPageResponse

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 18:49:24 +01:00

180 lines
5.9 KiB
Python

# app/modules/billing/routes/api/store_checkout.py
"""
Store checkout and subscription management endpoints.
Provides:
- Stripe checkout session creation
- Stripe portal session creation
- Subscription cancellation and reactivation
- Upcoming invoice preview
- Tier changes (upgrade/downgrade)
All routes require module access control for the 'billing' module.
Resolves store_id to (merchant_id, platform_id) for all billing service calls.
"""
import logging
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.api.deps import get_current_store_api, require_module_access
from app.core.config import settings
from app.core.database import get_db
from app.modules.billing.schemas.billing import (
CancelRequest,
CancelResponse,
ChangeTierRequest,
ChangeTierResponse,
CheckoutRequest,
CheckoutResponse,
PortalResponse,
UpcomingInvoiceResponse,
)
from app.modules.billing.services import billing_service
from app.modules.billing.services.subscription_service import subscription_service
from app.modules.enums import FrontendType
from models.schema.auth import UserContext
store_checkout_router = APIRouter(
dependencies=[Depends(require_module_access("billing", FrontendType.STORE))],
)
logger = logging.getLogger(__name__)
# ============================================================================
# Endpoints
# ============================================================================
@store_checkout_router.post("/checkout", response_model=CheckoutResponse)
def create_checkout_session(
request: CheckoutRequest,
current_user: UserContext = Depends(get_current_store_api),
db: Session = Depends(get_db),
):
"""Create a Stripe checkout session for subscription."""
store_id = current_user.token_store_id
merchant_id, platform_id = subscription_service.resolve_store_to_merchant(db, store_id)
store_code = subscription_service.get_store_code(db, store_id)
base_url = f"https://{settings.platform_domain}"
success_url = f"{base_url}/store/{store_code}/billing?success=true"
cancel_url = f"{base_url}/store/{store_code}/billing?cancelled=true"
result = billing_service.create_checkout_session(
db=db,
merchant_id=merchant_id,
platform_id=platform_id,
tier_code=request.tier_code,
is_annual=request.is_annual,
success_url=success_url,
cancel_url=cancel_url,
)
db.commit()
return CheckoutResponse(checkout_url=result["checkout_url"], session_id=result["session_id"])
@store_checkout_router.post("/portal", response_model=PortalResponse)
def create_portal_session(
current_user: UserContext = Depends(get_current_store_api),
db: Session = Depends(get_db),
):
"""Create a Stripe customer portal session."""
store_id = current_user.token_store_id
merchant_id, platform_id = subscription_service.resolve_store_to_merchant(db, store_id)
store_code = subscription_service.get_store_code(db, store_id)
return_url = f"https://{settings.platform_domain}/store/{store_code}/billing"
result = billing_service.create_portal_session(db, merchant_id, platform_id, return_url)
return PortalResponse(portal_url=result["portal_url"])
@store_checkout_router.post("/cancel", response_model=CancelResponse)
def cancel_subscription(
request: CancelRequest,
current_user: UserContext = Depends(get_current_store_api),
db: Session = Depends(get_db),
):
"""Cancel subscription."""
store_id = current_user.token_store_id
merchant_id, platform_id = subscription_service.resolve_store_to_merchant(db, store_id)
result = billing_service.cancel_subscription(
db=db,
merchant_id=merchant_id,
platform_id=platform_id,
reason=request.reason,
immediately=request.immediately,
)
db.commit()
return CancelResponse(
message=result["message"],
effective_date=result["effective_date"],
)
@store_checkout_router.post("/reactivate")
def reactivate_subscription(
current_user: UserContext = Depends(get_current_store_api),
db: Session = Depends(get_db),
):
"""Reactivate a cancelled subscription."""
store_id = current_user.token_store_id
merchant_id, platform_id = subscription_service.resolve_store_to_merchant(db, store_id)
result = billing_service.reactivate_subscription(db, merchant_id, platform_id)
db.commit()
return result
@store_checkout_router.get("/upcoming-invoice", response_model=UpcomingInvoiceResponse)
def get_upcoming_invoice(
current_user: UserContext = Depends(get_current_store_api),
db: Session = Depends(get_db),
):
"""Preview the upcoming invoice."""
store_id = current_user.token_store_id
merchant_id, platform_id = subscription_service.resolve_store_to_merchant(db, store_id)
result = billing_service.get_upcoming_invoice(db, merchant_id, platform_id)
return UpcomingInvoiceResponse(
amount_due_cents=result.get("amount_due_cents", 0),
currency=result.get("currency", "EUR"),
next_payment_date=result.get("next_payment_date"),
line_items=result.get("line_items", []),
)
@store_checkout_router.post("/change-tier", response_model=ChangeTierResponse)
def change_tier(
request: ChangeTierRequest,
current_user: UserContext = Depends(get_current_store_api),
db: Session = Depends(get_db),
):
"""Change subscription tier (upgrade/downgrade)."""
store_id = current_user.token_store_id
merchant_id, platform_id = subscription_service.resolve_store_to_merchant(db, store_id)
result = billing_service.change_tier(
db=db,
merchant_id=merchant_id,
platform_id=platform_id,
new_tier_code=request.tier_code,
is_annual=request.is_annual,
)
db.commit()
return ChangeTierResponse(
message=result["message"],
new_tier=result["new_tier"],
effective_immediately=result["effective_immediately"],
)