> ## Documentation Index
> Fetch the complete documentation index at: https://docs.brainstormer.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Credit Billing

> Platform credit billing architecture: pricing model, database schema, atomic billing function, integration contract, and coverage matrix.

## Overview

The platform credit billing system converts all external provider costs into a common credit system, applies configurable margin at the cost-event level, deducts credits where external costs are incurred, and provides superadmin-only cost-vs-sale visibility.

## Pricing Model

Default configuration stored in `platform_billing_config`:

| Parameter           | Default | Description                 |
| ------------------- | ------- | --------------------------- |
| `credit_value_usd`  | 0.50    | 1 credit = \$0.50           |
| `margin_multiplier` | 2.00    | charged cost = raw cost x 2 |

**For each external cost event:**

```
1. charged_usd = raw_cost_usd * margin_multiplier
2. credits_burned = charged_usd / credit_value_usd
3. Organization wallet debited by credits_burned
```

<Tip>
  **Example:** If raw cost is $0.01, charged cost is $0.02. Credits burned = $0.02 / $0.50 = **0.04 credits**.
</Tip>

## Database Schema

### Core Tables

| Table                           | Purpose                                        |
| ------------------------------- | ---------------------------------------------- |
| `platform_billing_config`       | Single-row global pricing defaults             |
| `platform_billing_plans`        | Plan catalog (`starter`, `growth`, `scale`)    |
| `organization_billing_accounts` | Per-organization plan + credit wallet          |
| `organization_credit_ledger`    | Immutable credit transactions                  |
| `external_cost_events`          | Billable provider events (raw/charged/credits) |

### Analytics View

| View                             | Purpose                             |
| -------------------------------- | ----------------------------------- |
| `platform_billing_daily_summary` | Day-level aggregation for reporting |

## Atomic Debit Function

`record_external_cost_event(...)` performs all billing writes in one transaction:

<Steps>
  <Step title="Load Defaults">
    Load `credit_value_usd` and `margin_multiplier` from billing config.
  </Step>

  <Step title="Ensure Account">
    Ensure organization billing account exists (create if not).
  </Step>

  <Step title="Lock Wallet">
    Lock wallet row with `FOR UPDATE` for concurrency safety.
  </Step>

  <Step title="Calculate">
    Calculate `charged_usd` and `credits_burned`.
  </Step>

  <Step title="Update Wallet">
    Update wallet balances and counters.
  </Step>

  <Step title="Record Cost Event">
    Insert into `external_cost_events`.
  </Step>

  <Step title="Record Ledger Entry">
    Insert matching row in `organization_credit_ledger`.
  </Step>

  <Step title="Return Result">
    Return billing result payload (event id, burn, charged, balance after).
  </Step>
</Steps>

<Note>
  This function is the **canonical low-level billing entry point**. All provider cost recording must go through this function.
</Note>

## Current Coverage Matrix

| Integration                                            | Status            | Provider/Operation                                                                |
| ------------------------------------------------------ | ----------------- | --------------------------------------------------------------------------------- |
| Bot chat completions                                   | Billed            | `openrouter` / `chat_completion`                                                  |
| Knowledge embeddings (single + batch)                  | Billed            | `openai_embeddings` or `openrouter_embeddings` / `embedding_generate`             |
| Pinecone vector ops (upsert, query, delete, deleteAll) | Billed            | `pinecone` / `vector_*`                                                           |
| Voice cloning / synthesis / Whisper STT                | Billed            | `elevenlabs` + `openai_whisper`                                                   |
| File upload/storage (S3)                               | Billed            | `aws_s3` / `file_store_put`, `file_store_get`, `file_store_delete`, `file_egress` |
| File-aware LLM chat                                    | Billed indirectly | Via chat completion token cost                                                    |
| LiveKit operations                                     | Not billed        | Room/token/session events unmetered                                               |
| LlamaParse parsing                                     | Not billed        | No billing hook yet                                                               |

## Mandatory Integration Contract

<Warning>
  Any new integration that incurs provider cost **MUST** integrate with credit billing from the first implementation.
</Warning>

### Requirements

1. Identify cost-incurring operations at the provider boundary
2. Record costs using `record_external_cost_event(...)` in the same execution path
3. Pass `organizationId` (required) and `userId` (when available) to the billing call
4. Store normalized metadata: `provider`, `operation`, `reference_type`, `reference_id`
5. Define failure policy:
   * **Strict:** fail request if billing write fails
   * **Best-effort:** log and continue (only for non-critical async paths)
6. Add tests verifying:
   * External cost event row is created
   * Ledger row is created
   * Expected margin/credit conversion is applied

### New Knowledge Base Connector Checklist

1. Connector jobs include `organizationId` and `userId` in job payload
2. Embedding generation routed through `EmbeddingService` (billing is automatic)
3. If connector calls paid third-party APIs, add a billing event for that API call
4. Set connector-specific `reference_type` values (e.g., `kb_connector_sync`)
5. Add integration tests for indexing success and retry/idempotency

### New Publish Destination Checklist

1. Treat outbound provider calls as billable operations
2. Add billing calls at the destination adapter layer (not only in route handlers)
3. Use operation names mapping to destination actions (`publish_send`, `publish_webhook`)
4. Include destination/channel IDs in metadata for auditing
5. Add dashboard-facing provider normalization for readable superadmin reporting

## Superadmin Reporting

```mermaid theme={null}
graph LR
    A[Web Dashboard] -->|GET /api/billing/summary| B[Gateway]
    B -->|Proxy /billing/*| C[Bot Service]
    C -->|Enforce superadmin| D[BillingRepository]
    D -->|Query| E[PostgreSQL]
    E -->|Totals, trend,<br/>provider rollup,<br/>org rollup| C
    C -->|Response| A
```

**Frontend:** `apps/web/src/components/billing/PlatformBillingDashboard.tsx` -- visible only when `user.isSuperAdmin === true`.

**Response includes:** totals, daily trend, provider rollup, organization rollup, and plan mix.

## Service Integrations

<Tabs>
  <Tab title="Bot Service">
    * `bot.service.ts`: Chat cost calculated from synced model pricing, calls `BillingRepository.recordExternalCost(...)` after each completion
    * `billing.repository.ts`: Wraps `record_external_cost_event`, exposes `getPlatformSummary()` for dashboard
  </Tab>

  <Tab title="Knowledge Service">
    * `embedding.service.ts`: Embedding generation estimates token usage and records external cost
    * `vector-store.service.ts`: Pinecone vector ops record cost events with org/user context
    * `queue.service.ts`: Document/URL indexing includes billing context in embedding batches
  </Tab>

  <Tab title="Realtime Audio">
    * ElevenLabs hooks: `voice_clone`, `voice_tts`, `voice_tts_stream_session`, `voice_tts_stream_usage`
    * Whisper hooks: `voice_stt_transcription`
    * Best-effort billing (errors logged, request continues)
  </Tab>

  <Tab title="File Storage">
    * `cloud-storage.service.ts`: Records S3 cost events for put/get/delete/egress
    * `file-upload.service.ts`: Passes billing context into CloudStorageService
  </Tab>
</Tabs>

## Access Control

Superadmin emails configured via:

* Backend: `PLATFORM_SUPERADMIN_EMAILS`
* Frontend: `NEXT_PUBLIC_PLATFORM_SUPERADMIN_EMAILS`

Bot service route rejects non-superadmin callers with `403`.

## Operational Notes

* Migration `014_platform_credit_billing.sql` is idempotent (safe to re-run)
* Keep gateway proxy from forwarding `content-length` when body is reserialized
* Billing function uses row locking for consistent wallet debits under concurrency

## Future Extensions

* Stripe checkout + invoice sync into `organization_credit_ledger`
* Auto top-up workers based on wallet thresholds
* Plan upgrade/downgrade lifecycle automation
* Hard balance floor and configurable overage behavior per plan
