Files
karaoke-gen/backend/services/fake_workers/checkout.py
T
Andrew Beveridge ☄️andClaude Opus 5.5 c277bc8ee3 feat: local E2E stack (fake workers + test API) + email-code sign-in (v0.275.0) (#1165)
## Summary
- **Local stack:** `scripts/local-stack.sh up --frontend` runs the
**real** backend on the Firestore + GCS emulators with `FAKE_WORKERS=1`.
In-process fake workers move jobs through their real states in seconds,
using tiny real media, so web Playwright and mobile Maestro full-journey
tests can run offline against the same endpoints.
- **Email-code sign-in** (nomad-mobile spec §4.1): `POST
/api/users/auth/send-code` + `verify-code`. The code logic is shared
with kjbox via `LoginCodeStore`, and sends are throttled per email and
per IP.
- **Bug fix found by the new suite:** `confirm-duration` moved jobs to
`separating_stage1`, from which they can never reach review. It now
resumes at `downloading`. No prod job had taken this path yet.

## Changes
- `backend/services/fake_workers/`: dispatch seam in
`WorkerService.trigger_*`, plus fake search, download, checkout and
outbox, scenarios, and per-user config. The real stem upload, transcode,
backing-vocals analysis and preview render are reused. Every check is
strict (`is True`), so a MagicMock settings object never enables the
fakes, and startup **refuses FAKE_WORKERS in production**.
- `/api/test/*` router (mounted only in that mode): `status`,
`scenario`, `fake-config`, `emails`, `reset`, plus the fake Stripe
checkout page. Paying it runs the real webhook handler.
- `frontend/e2e/local-stack/` (9 specs, ~50s):
  - sign-up → make → review → instrumental → download
  - buy and cancel credits
  - duration confirm, failed, complete and review states
  - code sign-in and lockout
- New required CI job `local-stack-e2e`.
- Docs: TESTING.md § Local stack, DEVELOPMENT.md, API.md, README,
LESSONS-LEARNED.
- `MAX_SIGNUPS_PER_IP` can now be set by env. Only the local stack
raises it; production keeps the default of 2.

## Testing
- [x] Backend unit: 6175 passed
- [x] Emulator: 152 passed
- [x] Frontend Jest: 1706 passed
- [x] Local-stack Playwright: 9/9 passed (CI mode)

## Review
- [x] CodeRabbit CLI review completed locally. 1 minor finding declined:
it suggested swallowing infrastructure errors in send-code as fake
"sent" responses, which would hide real outages from users.

@coderabbitai ignore

---
🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01AGuxtgoscF6RJGtpjHPg3W

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:00:24 -04:00

69 lines
2.7 KiB
Python

"""Fake Stripe Checkout for the local stack.
``StripeService`` calls :func:`create_fake_checkout` instead of
``stripe.checkout.Session.create`` when Stripe isn't configured and
FAKE_WORKERS is on. The returned URL is a tiny "checkout" page served by
``/api/test/fake-checkout/{id}``; paying it runs the same completion handler as
the real webhook (via ``/api/internal/test-webhook``'s logic), then redirects to
the session's success URL, just as Stripe would.
"""
from __future__ import annotations
import os
import secrets
from datetime import datetime, timezone
from types import SimpleNamespace
from typing import Any, Dict, Optional
CHECKOUTS_COLLECTION = "local_stack_checkouts"
# Must start with "e2e-test-" so the shared test-webhook handler accepts it.
SESSION_PREFIX = "e2e-test-local-"
def public_api_url() -> str:
"""Base URL browsers / devices use to reach this API (LOCAL_STACK_API_URL)."""
return os.getenv("LOCAL_STACK_API_URL", f"http://127.0.0.1:{os.getenv('PORT', '8000')}").rstrip("/")
def _db():
from backend.services.firestore_service import FirestoreService
return FirestoreService().db
def _amount_cents(session_params: Dict[str, Any]) -> int:
return sum(
(item.get("price_data") or {}).get("unit_amount", 0) * item.get("quantity", 1)
for item in session_params.get("line_items") or []
)
def create_fake_checkout(session_params: Dict[str, Any]) -> SimpleNamespace:
session_id = SESSION_PREFIX + secrets.token_hex(8)
line_items = session_params.get("line_items") or [{}]
_db().collection(CHECKOUTS_COLLECTION).document(session_id).set({
"session_id": session_id,
"customer_email": session_params.get("customer_email"),
"metadata": session_params.get("metadata") or {},
"success_url": session_params.get("success_url"),
"cancel_url": session_params.get("cancel_url"),
"product_name": ((line_items[0].get("price_data") or {}).get("product_data") or {}).get("name"),
"amount_cents": _amount_cents(session_params),
"status": "open",
"created_at": datetime.now(timezone.utc),
})
return SimpleNamespace(id=session_id, url=f"{public_api_url()}/api/test/fake-checkout/{session_id}")
def get_checkout(session_id: str) -> Optional[Dict[str, Any]]:
snap = _db().collection(CHECKOUTS_COLLECTION).document(session_id).get()
return snap.to_dict() if snap.exists else None
def mark_checkout(session_id: str, status: str) -> None:
_db().collection(CHECKOUTS_COLLECTION).document(session_id).update({"status": status})
def resolve_url(url: Optional[str], session_id: str) -> str:
return (url or "/").replace("{CHECKOUT_SESSION_ID}", session_id)