# Billing & Metering System

> Documentation for Agencio Predict's billing and metering framework.

## Overview

The billing system provides subscription management, usage metering, and Stripe integration for both organizations and individual users.

## Plans

### Pricing

| Plan | Monthly | Yearly | Savings |
|------|---------|--------|---------|
| Free | $0 | $0 | - |
| Pro | $49/mo | $490/yr | 17% |
| Enterprise | $199/mo | $1,990/yr | 17% |

### Usage Limits

| Resource | Free | Pro | Enterprise |
|----------|------|-----|------------|
| API Calls | 1,000/mo | 10,000/mo | Unlimited |
| AI Predictions | 100/mo | 1,000/mo | Unlimited |
| AI Tokens | 100,000/mo | 1,000,000/mo | Unlimited |
| Marketing Predictions | 10/mo | 100/mo | Unlimited |
| Exports (CSV/PDF) | 5/mo | 50/mo | Unlimited |

### Features

| Feature | Free | Pro | Enterprise |
|---------|------|-----|------------|
| **Signal Engine** | | | |
| AI Predictions | ✅ Limited | ✅ | ✅ Unlimited |
| Pattern Detection (FVG) | ✅ | ✅ | ✅ |
| Trust Layer Scoring | ✅ | ✅ | ✅ |
| Black Swan Alerts | ❌ | ✅ | ✅ |
| **Trading** | | | |
| Dashboard & Console | ✅ | ✅ | ✅ |
| Watchlists | 1 list, 10 symbols | 5 lists, 50 symbols | Unlimited |
| Trading Algorithms (view only) | ✅ | ✅ | ✅ |
| Algorithm Builder (create/edit) | ❌ | ❌ | ✅ |
| AI Algorithm Modifications | ❌ | ❌ | ✅ |
| LLM Jury (auto-critique) | ❌ | ❌ | ✅ |
| Paper Trading | ✅ | ✅ | ✅ |
| Live Trading (Alpaca/IBKR) | ❌ | ✅ MFA required | ✅ |
| Full Autonomous AI Trading | ❌ | ❌ | ✅ |
| Backtesting | 90 days | 2 years | Full history |
| **Market Data** | | | |
| Derivatives (VIX, OI, Funding) | ✅ | ✅ | ✅ |
| Forex | ✅ | ✅ | ✅ |
| Crypto | ✅ | ✅ | ✅ |
| Historical Data Depth | 30 days | 1 year | Full history |
| Real-time Tick Data | ❌ | ❌ | ✅ |
| **Marketing Intelligence** | | | |
| Campaign Predictions | ❌ | ✅ | ✅ |
| Attribution Models | ❌ | ✅ | ✅ |
| Ad Platform Sync | ❌ | ✅ | ✅ |
| **Exports & API** | | | |
| CSV/PDF Exports | ❌ | ✅ | ✅ |
| Trade Export CSV | ❌ | ✅ (1yr history) | ✅ Unlimited |
| Trade Export PDF (Compliance) | ❌ | ❌ | ✅ |
| REST API Access | ✅ Rate-limited | ✅ | ✅ |
| Webhooks | ❌ | ✅ | ✅ |
| **Advanced** | | | |
| Custom AI Models | ❌ | ❌ | ✅ |
| White-Label Branding | ❌ | ❌ | ✅ |
| SSO / SAML | ❌ | ❌ | ✅ |
| Audit Logs | ❌ | ✅ | ✅ |

### 7-Day Trial

All new users get a **7-day trial** with full Pro features:
- Access to all features during trial
- No credit card required
- Automatic conversion to Free tier after trial unless upgraded
- Trial period tracked in `billing.subscriptions.trial_ends_at`

Trial behavior:
- `is_trialing = true` while trial is active
- After trial: reverts to Free tier limits
- User can upgrade anytime during or after trial

## Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                        BILLING SYSTEM                            │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ┌──────────────┐   ┌──────────────┐   ┌──────────────┐        │
│  │   Frontend   │   │   Backend    │   │    Stripe    │        │
│  │  ──────────  │   │  ──────────  │   │  ──────────  │        │
│  │ • Settings   │──▶│ • Services   │──▶│ • Checkout   │        │
│  │ • useBilling │   │ • Middleware │   │ • Portal     │        │
│  │ • Components │   │ • Webhooks   │◀──│ • Webhooks   │        │
│  └──────────────┘   └──────────────┘   └──────────────┘        │
│                              │                                   │
│                              ▼                                   │
│                     ┌──────────────┐                            │
│                     │   Database   │                            │
│                     │  ──────────  │                            │
│                     │ • billing.*  │                            │
│                     └──────────────┘                            │
└─────────────────────────────────────────────────────────────────┘
```

## Database Schema

Migration: `db/migrations/028_billing_subscriptions.sql`

### Tables

| Table | Purpose |
|-------|---------|
| `billing.subscription_plans` | Plan definitions with limits and features |
| `billing.subscriptions` | Active subscriptions linked to organizations |
| `billing.usage_meters` | Aggregated usage per billing period |
| `billing.usage_events` | Granular usage events for auditing |
| `billing.invoices` | Invoice records synced from Stripe |
| `billing.payment_methods` | Payment method storage |
| `billing.webhook_events` | Stripe webhook event log |

### Helper Functions

```sql
-- Get current usage for an organization
SELECT * FROM billing.get_current_usage('org-uuid');

-- Increment usage counter atomically
SELECT billing.increment_usage('org-uuid', 'api_call', 1);
```

## API Endpoints

Base path: `/api/predict/v1/billing`

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/plans` | List available subscription plans |
| GET | `/subscription` | Get current subscription |
| POST | `/subscription` | Create subscription |
| POST | `/subscription/cancel` | Cancel subscription |
| POST | `/checkout` | Create Stripe checkout session |
| POST | `/portal` | Create Stripe billing portal session |
| GET | `/usage` | Get current usage and history |
| GET | `/invoices` | List invoices |
| GET | `/payment-methods` | List payment methods |
| POST | `/payment-methods` | Add payment method |
| POST | `/payment-methods/:id` | Set as default |
| DELETE | `/payment-methods/:id` | Remove payment method |
| POST | `/webhooks/stripe` | Stripe webhook handler |

## Usage Metering

### Event Types

| Type | Description | Tracked Per |
|------|-------------|-------------|
| `api_call` | Any API request | Request |
| `prediction` | AI prediction generated | Prediction |
| `ai_tokens` | AI tokens consumed | Token count |
| `marketing_prediction` | Marketing prediction | Prediction |
| `export` | CSV/PDF export | Export |

### Recording Usage

```typescript
import { recordApiCall, recordPrediction, recordAiTokens } from '@agencio-predict/be/billing';

// Record API call
await recordApiCall(organizationId, '/api/predict/v1/events', 'GET', userId);

// Record prediction
await recordPrediction(organizationId, userId, { eventId: '...' });

// Record AI tokens
await recordAiTokens(organizationId, 1500, userId, { model: 'gpt-4' });
```

### Checking Limits

```typescript
import { checkUsageLimit } from '@agencio-predict/be/billing';

const check = await checkUsageLimit(organizationId, 'api_call');

if (!check.allowed) {
  // Return 402 Payment Required
  return NextResponse.json(
    { error: 'Usage limit exceeded', upgradeRequired: true },
    { status: 402 }
  );
}
```

## Frontend Integration

### useBilling Hook

```tsx
import { useBilling } from '@agencio-predict/fe/components/billing';

function BillingPage() {
  const {
    subscription,
    plans,
    usage,
    invoices,
    paymentMethods,
    isLoading,
    error,
    fetchSubscription,
    createCheckoutSession,
    cancelSubscription,
    openBillingPortal,
  } = useBilling();

  const handleUpgrade = async () => {
    const checkoutUrl = await createCheckoutSession('pro', 'monthly');
    if (checkoutUrl) {
      window.location.href = checkoutUrl;
    }
  };

  // ...
}
```

### Components

| Component | Purpose |
|-----------|---------|
| `SubscriptionCard` | Display current plan and status |
| `PlanSelector` | Plan comparison with toggle |
| `UsageMetrics` | Usage gauges with progress bars |
| `InvoiceList` | Invoice history table |
| `PaymentMethodCard` | Payment method management |
| `UpgradePrompt` | Upgrade prompts (inline/banner/modal) |

## Stripe Integration

### Environment Variables

```bash
STRIPE_SECRET_KEY=sk_live_...
STRIPE_WEBHOOK_SECRET=whsec_...

# Optional: Price IDs for each plan
STRIPE_PRICE_PRO_MONTHLY=price_...
STRIPE_PRICE_PRO_YEARLY=price_...
STRIPE_PRICE_ENTERPRISE_MONTHLY=price_...
STRIPE_PRICE_ENTERPRISE_YEARLY=price_...
```

### Webhook Events Handled

| Event | Action |
|-------|--------|
| `customer.subscription.created` | Create subscription record |
| `customer.subscription.updated` | Update subscription status |
| `customer.subscription.deleted` | Mark subscription as canceled |
| `invoice.paid` | Record successful payment |
| `invoice.payment_failed` | Update subscription status |
| `payment_method.attached` | Add payment method |
| `payment_method.detached` | Remove payment method |

### Webhook Endpoint

Configure in Stripe Dashboard:
- URL: `https://your-domain.com/api/predict/v1/billing/webhooks/stripe`
- Events: All subscription, invoice, and payment method events

## Middleware Integration

The usage limit middleware can be integrated with authentication:

```typescript
// In your API route
import { requireAuth } from '@agencio-predict/be/lib/auth/middleware';
import { checkRequestUsageLimit } from '@agencio-predict/be/billing';

export async function GET(request: NextRequest) {
  const user = await requireAuth(request);

  // Check and record usage
  const limitCheck = await checkRequestUsageLimit(
    user.organizationId,
    'api_call',
    request.url
  );

  if (!limitCheck.allowed) {
    return NextResponse.json(
      { error: 'Usage limit exceeded' },
      { status: 402 }
    );
  }

  // Continue with request handling...
}
```

## Settings Page

The billing settings page is located at `/settings/billing` and provides:

1. Current subscription status and plan details
2. Usage metrics with progress bars
3. Plan upgrade/downgrade options
4. Payment method management
5. Invoice history
6. Link to Stripe billing portal

## Testing

### Test Mode

Set `STRIPE_SECRET_KEY` to a test key (`sk_test_...`) for development.

### Test Cards

| Card Number | Scenario |
|-------------|----------|
| 4242424242424242 | Successful payment |
| 4000000000000002 | Declined |
| 4000002500003155 | Requires authentication |

### Webhook Testing

Use Stripe CLI for local webhook testing:

```bash
stripe listen --forward-to localhost:3333/api/predict/v1/billing/webhooks/stripe
```

## Security Considerations

1. **Authentication**: All billing endpoints require authentication via `requireAuth`
2. **Organization Isolation**: Users can only access their organization's billing data
3. **Webhook Verification**: All Stripe webhooks are verified using signature verification
4. **Idempotency**: Webhook events are tracked to prevent duplicate processing
5. **PCI Compliance**: Card details are never stored; Stripe handles all sensitive data
