# P2HS Backend - Implementation Status

## Completed

### Foundation
- [x] Project structure with Dev/Prod config (.venv workflow)
- [x] requirements.txt + requirements-dev.txt
- [x] Core modules: database, redis, security (JWT, hashing, encryption), middleware
- [x] Custom exception hierarchy (P2HSError -> HTTP mapping)
- [x] Pagination utilities
- [x] Setup: ruff.toml, pytest.ini, setup.cfg, .gitignore, .env.example, README

### Database
- [x] Alembic setup with initial migration (001_initial_schema)
- [x] All p2hs_ prefixed PostgreSQL enums
- [x] Full schema: 30+ tables across all domains

### Domain: Auth (5 endpoints)
- [x] Models: User, Session, MagicLinkToken
- [x] Schemas, Repository, Service, Router
- [x] Passwordless magic link flow
- [x] JWT access/refresh tokens
- [x] UserFacade for cross-domain access

### Domain: Workspaces (9 endpoints)
- [x] Models: Workspace, Role, Membership, Invite, Settings
- [x] RBAC with permissions
- [x] Invite flow with token acceptance
- [x] WorkspaceFacade for cross-domain access

### Domain: Projects (5+ endpoints)
- [x] Models: Project, ProjectRepo, ProjectSettings, ProjectEnvVar
- [x] MVP types: react_app, nuxt_app, html
- [x] Encrypted environment variables
- [x] Async project creation (status=creating -> ready)

### Domain: Instructions & Prompts (6 endpoints)
- [x] Versioned project instructions
- [x] Prompt sessions with viewer context
- [x] InstructionRepository, PromptSessionRepository, PromptRepository

### Domain: Revisions (4 endpoints)
- [x] ProjectRevision, RevisionTag models
- [x] Non-destructive restore (creates N+1)
- [x] Diff between revisions
- [x] RevisionFacade for codegen/deploy

### Domain: Codegen (3 endpoints)
- [x] CodegenRun model with status tracking
- [x] Prompt wrapper: system prompt + user prompt wrapping
- [x] Viewer-aware context (route, viewport, revision)
- [x] AICodeGeneratorProtocol (unified across providers)

### Domain: Previews (5 endpoints)
- [x] PreviewEnvironment, RoutesManifest models
- [x] PreviewAdapter Protocol
- [x] React, Nuxt, HTML adapters (MVP)
- [x] Routes manifest enumeration

### Domain: Deployments (7 endpoints)
- [x] ProjectDeploy, ProjectDomain models
- [x] Deploy creation and rollback
- [x] Custom domain with DNS verification
- [x] Primary domain management

### Domain: Billing (6 endpoints)
- [x] StripeCustomer (linked to user + workspace), Subscription, Invoice, StripeEvent, UsageLedger
- [x] Predefined subscription plans via Stripe Checkout
- [x] Usage-based metered billing (ai_tokens, build_minutes, preview_minutes, codegen_run, deploy)
- [x] Stripe Customer Portal integration
- [x] Comprehensive webhook handlers (checkout.session.completed, subscription CRUD, invoice events)
- [x] Idempotent event processing (event dedup)
- [x] Usage summary endpoint

### Domain: Public API Keys (3 endpoints)
- [x] ApiKey model (hashed, prefixed)
- [x] Create, list, revoke

### Domain: Artifacts (1 endpoint)
- [x] Source zip export service
- [x] Excludes node_modules, .git, etc.

### Domain: GitHub Webhooks
- [x] Webhook receiver endpoint (POST /v1/webhooks/github)
- [x] HMAC-SHA256 signature verification
- [x] Event handlers: push, pull_request, workflow_run, installation
- [x] Push handler: auto-creates platform revisions from external commits
- [x] PR merge handler: creates revision from merge commit
- [x] Documented required GitHub App permissions and webhook subscriptions

### Integrations
- [x] GitHub App client (repo creation, Git Trees API commits, PRs, file ops, diff)
- [x] Stripe client (customers, checkout, portal, subscriptions, invoices, metered usage)
- [x] Email providers (Resend + Mailgun) with factory
- [x] Cloudflare client (Pages project, deployment, custom domains)

### AI Provider Abstraction
- [x] Unified AICodeGeneratorProtocol + CodegenResult
- [x] Provider factory (get_ai_provider) - switchable via AI_PROVIDER env var
- [x] **OpenAI provider** - GPT-4o plan/code generation with structured JSON output
- [x] **Cursor CLI provider** - Repo-aware agentic coding via Cursor CLI
- [x] **Claude Code provider** - Anthropic API + Claude CLI for agentic coding
- [x] Codegen worker uses the abstracted provider

### Workers (arq)
- [x] Worker main with arq settings
- [x] Task: project_setup (repo creation + boilerplate push + revision)
- [x] Task: codegen (AI provider-agnostic)
- [x] Task: build (framework adapter)
- [x] Task: preview provisioning
- [x] Task: cleanup expired previews

### Boilerplates
- [x] React App (Vite + TypeScript + Tailwind)
- [x] Nuxt App (Vue 3 + Nuxt 3)
- [x] HTML (vanilla)

### Tests
- [x] test_prompt_wrapper - codegen prompt wrapping
- [x] test_exceptions - exception hierarchy + HTTP mapping
- [x] test_adapters - preview adapter route enumeration
- [x] test_config - settings defaults
- [x] test_encryption - encrypt/decrypt roundtrip
- [x] test_hashing - token hash/verify
- [x] test_artifacts_service - zip export with exclusions

## Architecture Principles Enforced
- DDD Modular Monolith with bounded contexts
- Dependency Inversion via Python Protocols
- Facades for cross-domain communication
- Single Responsibility Principle
- Workspace-scoped tenancy
- AI provider abstraction (OpenAI / Cursor CLI / Claude Code)

## GitHub App Configuration

### Required Permissions
| Scope | Access | Why |
|-------|--------|-----|
| contents | read & write | Push commits, read files, create branches |
| pull_requests | read & write | Create/merge PRs, read PR status |
| metadata | read | Repo info, branches, tags |
| webhooks | read | Verify delivery |
| actions | read | Workflow run status for CI feedback |

### Webhook Subscriptions
| Event | Purpose |
|-------|---------|
| push | Detect external commits, create platform revisions |
| pull_request | Track PR-based codegen, auto-preview, merge detection |
| workflow_run | CI/CD build status tracking |
| installation | Track app installs/uninstalls |
| installation_repositories | Track managed repos |

## Stripe Configuration

### Webhook Events
Configure these in Stripe Dashboard → Webhooks → Add endpoint → Select events.

| Event | Purpose |
|-------|---------|
| **Subscription & Checkout** | |
| checkout.session.completed | Subscription created via Checkout |
| customer.subscription.created | New subscription sync |
| customer.subscription.updated | Plan change, renewal, trial end |
| customer.subscription.deleted | Cancellation |
| invoice.paid | Successful payment |
| invoice.payment_failed | Failed payment alert |
| **Account & Customer** | |
| account.updated | Connect/Express account changes |
| customer.created | New Stripe customer |
| customer.updated | Customer profile changes |
| **Charges & Refunds** | |
| charge.captured | Charge captured (auth→capture) |
| charge.failed | Failed charge |
| charge.refunded | Full/partial refund |
| charge.refund.updated | Refund status change |
| charge.succeeded | Successful charge |
| **Disputes** | |
| charge.dispute.created | Dispute opened |
| charge.dispute.closed | Dispute resolved |
| **PaymentIntents** | |
| payment_intent.amount_capturable_updated | Auth amount changed |
| payment_intent.payment_failed | Payment failed |
| payment_intent.processing | Payment processing |
| payment_intent.requires_action | SCA / 3DS required |
| payment_intent.succeeded | Payment succeeded |
| **SetupIntents** | |
| setup_intent.succeeded | Payment method saved |
| setup_intent.setup_failed | Setup failed |
| **Radar / Fraud** | |
| review.opened | Fraud review started |
| review.closed | Fraud review resolved |
| **Sources** | |
| source.canceled | Source canceled |
| source.chargeable | Source ready to charge |

### Billing Models
1. **Subscription Plans** - Admin-managed via admin dashboard, synced to Stripe Products + Prices
2. **Usage Metering** - Per-event tracking (AI tokens, builds, previews) reported to Stripe metered pricing

## Admin Domain

### Admin Endpoints (require user in `admins` table)
| Endpoint | Purpose |
|----------|---------|
| POST /v1/admin/plans | Create subscription plan (syncs Product + Price to Stripe) |
| GET /v1/admin/plans | List all plans (admin view, includes inactive) |
| GET /v1/admin/plans/{id} | Get plan details |
| PATCH /v1/admin/plans/{id} | Update plan (price changes create new Stripe Price, deactivate old) |

### Public Endpoint (no auth)
| Endpoint | Purpose |
|----------|---------|
| GET /v1/plans | List active plans (for pricing page) |

### Admin Tables
- `subscription_plans` - Plans with Stripe Product/Price IDs, features, limits, metered billing config
- `admins` - Platform admins; presence grants admin access (user_id FK to users)
