# Gate 1 — Billing/Metering Backend Only

## Scope

Implement unified credits billing and metering backend for Geospatial + Secondary Market without changing AI Match behavior.

## Objectives

- Enforce credit debits server-side for billable actions.
- Keep Geospatial Ask AI flow backward compatible (zero downtime).
- Add idempotent debit semantics and auditable ledger events.
- Add Stripe top-up + Odoo sync reliability.

## Included Work

- Action catalog normalization for both products.
- Plan grants + soft cap policy (3x monthly grant).
- Credit state endpoint (tenant-scoped).
- Debit endpoint with idempotency.
- Stripe top-up checkout + confirmation.
- Odoo ledger sync events for billing.
- Usage telemetry for margin visibility (per action).

## Excluded Work

- AI Match ranking model redesign.
- Investor/provider UI flow redesign.
- Dynamic pricing model internals.

## Estimated Effort

- Engineering: 10-14 hours
- QA + verification: 3-4 hours
- Total: 13-18 hours

## Files Touched (Expected)

- `lib/credits-config.js`
- `lib/credits-ledger-odoo.js`
- `lib/odoo.js`
- `api/credits-state.js`
- `api/credits-debit.js`
- `api/credits-plan.js`
- `api/credits-checkout.js`
- `api/credits-topup-confirm.js`
- `api/credits-matrix.js`
- `api/credits-webhook.js`

## Schema Changes (Additive)

1. Credit events ledger (append-only)
   - `event_id`
   - `tenant_id`
   - `client_id`
   - `product`
   - `action_id`
   - `credits_delta`
   - `estimated_cost_eur`
   - `idempotency_key`
   - `trace_id`
   - `created_at`

2. Wallet projection metadata
   - `plan_id`
   - `monthly_grant`
   - `soft_cap`
   - `topup_balance`
   - `updated_at`

No destructive migration. Existing flows remain valid.

## Verification / Proof It Works

1. `GET /api/credits-state` returns correct plan, grant, balance, soft cap.
2. `POST /api/credits-debit` with same idempotency key debits once only.
3. Low-balance scenario returns `402` and no debit event appended.
4. Stripe top-up confirmed via webhook increases available credits.
5. Odoo receives billing events with trace IDs for every debit/top-up.
6. Admin metrics endpoint shows spend vs estimated inference cost for multiple actions.

## Definition of Done

- All included endpoints pass functional tests.
- Debit path is idempotent and auditable.
- Geospatial Ask AI remains unchanged to clients.
- No downtime migration for existing tenants.

