# Billing

Charge for hosted use with [Mollie](https://www.mollie.com): paid plans, team seats and credit
top-ups, with VAT and renewals handled by Opisense.

## Setup

Billing stays off unless `MOLLIE_API_KEY` is set (see `.env.example`). A `test_` key uses Mollie's
test mode; a `live_` key takes real payments. Set it on both the API, which runs checkout, and the
worker, which renews plans. The worker also needs `WEB_ORIGIN`. A worker without the key logs a
warning at start and renews nothing.

Mollie calls `<WEB_ORIGIN>/api/v1/billing/webhook` for every payment. Opisense names that URL on
each payment, so there's nothing to set in Mollie's dashboard. The payload only names a payment;
Opisense reads the payment back from Mollie before acting on it. When `WEB_ORIGIN` is a loopback
address Mollie can't reach, no webhook is sent and the checkout return page applies the payment.

Your Mollie account needs card payments and recurring card charges in each currency you sell in.
Plans and seats are paid by card; top-ups take any method your Mollie account offers.

`ENTERPRISE_CONTACT_URL` is optional: the billing page links to it for organizations that need more
than the self-serve plans. It must be an `https://` URL; anything else is ignored with a warning at
start.

### Moving off Stripe

Opisense no longer reads Stripe. Before you switch, cancel your customers' Stripe subscriptions in
the Stripe dashboard so they aren't charged twice, and delete the Opisense webhook endpoint there.
Owners then subscribe again through Mollie.

## Plans and prices

Prices, allowances, seat prices, top-up packs and Free limits live in one catalog,
`packages/contracts/src/plans.ts`. Prices there exclude VAT. Norway pays in NOK, Europe in EUR and
everyone else in USD, from the billing country. An organization keeps the currency of its first
payment.

- **Individual plans** are `plus`, `premium`, `super` and `ultra`, monthly or yearly.
- **Teams** pay monthly per seat at `premium`, `super` or `ultra`. A period is charged for the most
  members it has had.
- **Top-ups** are fixed packs of credit for the organization's pool. They don't expire.
- **Upgrades** charge the prorated difference at once. Downgrades start at renewal.
- **Cancel** ends the plan with its paid period; the organization then drops to Free.

## VAT

Opisense computes VAT before every charge from the billing country and VAT ID, and stores it with
the payment:

- Norway: 25%.
- EU business with a valid VAT ID: 0%, reverse charge.
- EU consumer, or a business without a valid ID: that country's standard rate.
- Everywhere else: no VAT.

EU VAT IDs are checked with VIES. If VIES is down, the ID is saved unchecked and VAT is charged
until it validates. The rate table is in `packages/core/src/vat.ts`.

> [!IMPORTANT]
> Have an accountant confirm these rules for your own registrations before you take live payments.

## Invoices

Every payment that buys something gets an invoice, issued as the payment is applied. A refund or
chargeback gets a credit note for the amount reversed, so a partly refunded payment can have
several. A payment-method check and a payment that bought nothing, which Opisense refunds, get none.
Invoices and credit notes share one number series without gaps, starting at 1.

Set who issues them on the API, all three or none:

```bash
INVOICE_SELLER_NAME=Example Seller AS
INVOICE_SELLER_ADDRESS=Storgata 1, 0155 Oslo, Norway
INVOICE_SELLER_REGISTRATION=Foretaksregisteret NO 999 999 999 MVA
```

The address takes comma-separated lines. The registration line is printed as you write it; in
Norway it carries the organization number with `MVA` when you are VAT registered, and
`Foretaksregisteret` for a registered company. Without these settings the API logs a warning at
start and no invoice is issued; payments made meanwhile get theirs once you set them. To continue a
series you started elsewhere, insert the last number you used into `invoice_sequence` (`id`
`default`, `lastNumber`) before the first invoice.

An invoice is stored with everything printed on it, seller and customer included, and never changes.
It shows the number, issue date, service period or delivery date, seller and customer with their VAT
IDs, each line with its VAT rate, the net, VAT and total, and why no VAT was charged when none was.
Dates are in UTC.

Owners download them from **Settings → Billing → Payments**. With email configured, each invoice and
credit note is also sent to the organization's invoice email as a PDF, once; a failed send is tried
again within the hour, for a week.

## Renewals

The worker charges each plan's saved card when its period ends, one organization at a time per
lease, so several workers never charge twice. A failed renewal is retried after 1, 3 and 5 days,
and the owner gets an email after each failure. After 7 days unpaid, an individual plan drops to
Free and a team keeps its members but loses its paid limits. Paying later restores the plan.

A full chargeback on a plan payment ends the plan at once; the customer can subscribe again. A
dispute you later win doesn't bring the plan back. A refunded or charged-back top-up removes only
the credit not yet spent.

## Refunds

Refunds are made by the operator. Pass the Opisense payment id from the `payments` table:

```bash
docker compose -f docker-compose.images.yml exec api node dist/cli/billing-refund.js \
  --payment <payment-id> [--amount <minor-units>]
```

From a checkout, run `pnpm --filter @rakazo/api billing-refund --payment <payment-id>`. Without
`--amount` the rest of the payment is refunded. Each refund is recorded as `billing.refunded` in the
[audit log](/docs/self-host-audit-log/).

- A full refund of a subscription or renewal payment ends the plan.
- A refunded upgrade leaves the higher plan in place; the owner can schedule a downgrade.
- A refunded seat payment stops seat charges on that card until the owner changes it; the renewal
  charges every member.

Opisense refunds on its own a payment that bought nothing, such as a second subscription paid in
another tab. A payment whose amount or organization doesn't match its record is refunded too, and
recorded as `billing.payment_mismatch`.

## Team plan

An organization is on the `individual` or `team` plan. The team plan unlocks [teams](/docs/teams/):
members, roles and team spaces. With billing on, the **Team features** switch is hidden. Instead,
the owner of an individual organization starts a team in **Settings → Billing → Upgrade**: they
choose **Team**, pick a seat level, name the team and pay for their own seat. The organization
becomes the team only once that payment succeeds; if someone joined it in the meantime, the payment
is refunded and nothing changes. An owner paying for an individual plan can start a team once that
plan has ended.

You can also set the plan with the `organization-plan` command, which works with or without
billing:

```bash
docker compose -f docker-compose.images.yml exec api node dist/cli/organization-plan.js \
  --organization <id-or-slug> --plan team
```

From a checkout, use `-f infra/compose/docker-compose.yml`, or run
`pnpm --filter @rakazo/api organization-plan --organization <id-or-slug> --plan team`.

- `--organization` takes the organization's id or slug.
- `--plan` is `individual` or `team`.
- `--seat-level` is optional: `premium`, `super` or `ultra`. A team keeps its current level, or
  `premium` when it has none. An individual organization has no seat level.
- `--name` is optional and renames the organization, for example to the team's name.
- `--tier` is optional and only for `--plan individual`: `free`, `plus`, `premium`, `super` or
  `ultra`. The tier renews each calendar month without a payment until you change it; `free`
  removes it.
- `--complimentary` is optional and only for `--plan team`, together with `--seat-level`. The team
  gets that level's monthly allowance, renewed each calendar month, without a payment.

A team's owner subscribes once the organization is on the team plan. Switching to `team` is refused
while the organization pays for an individual plan; the owner cancels it and waits for it to end.
Switching to `individual` is refused while the organization has more than one member; remove the
others first, and it ends a complimentary team plan. Each change is recorded as `organization.plan_changed`, and `--tier` or
`--complimentary` as `subscription.set_by_operator`, in the
[audit log](/docs/self-host-audit-log/).

## Usage plans

With billing on, an organization is on Free, a paid plan, or a lapsed team.

- **Allowance.** Each person gets a monthly usage allowance from their plan, granted on their first
  use in the period, prorated from when they joined, and expired at the period's end. Their runs
  spend it before anything else. Settings → Billing shows the person's own allowance.
- **Pool.** Top-ups and referral rewards form one pool shared by the organization. A paid or lapsed
  team's members spend it once their own allowance is gone. It shows as zero, not negative, when the
  account owes.
- **Free.** No pool and no top-ups. `FREE_LIMITS` caps spaces, bots, routines and messages per UTC
  month, and `FREE_USAGE_CENTS` is the monthly usage. Free cannot use a personal model connection.
  Past a cap, creating one more is refused and a run stops with the limit message.
- **Pool warnings.** The pool is flagged low when under a fifth of its last grant or $2, and empty
  when spent or owed. Paid organizations get a "Credits low" or "Out of credits" notice in the
  sidebar and their owners one email per state; a pool grant clears it.
- **Referrals.** Each owner gets an invite link. When an invited organization first pays for a plan,
  the referrer's pool gets credits worth one month of Plus, unless the card was the referrer's own or
  was already used by another referral or subscription.

Configure the deployment's model through the existing model connection settings; runs on it are
charged at model cost. Personal connections use their own keys and never spend credits.

Sending a bot to a meeting needs a paid plan with allowance or credits left, and its time there is
charged at `MEETING_COST_USD_PER_HOUR`. See
[Meeting bots](/docs/self-host-integrations/#who-can-use-it).

## Accounting

Postgres owns accounting. `payments` keeps every charge with its VAT and the billing details used,
and outlives the organization, as does `invoices`. `billing_audit_events` is an append-only journal enforced by database
triggers; credit entries, usage rows, and balances are projections. Each model call shares one
`callId` across reservation, durable provider receipt, usage, and settlement. Provider generation
IDs, token buckets, cost provenance, and pricing snapshots are retained. Usage and settlement
commit together, and journal and usage history survive clearing messages or deleting a bot or
organization. Corrections append evidence rather than rewriting earlier journal events.

The API and worker reconciler recovers saved receipts and, when the configured provider supports
it, fetches authoritative generation costs for interrupted calls and estimates. Retries use leases
and idempotent settlement. Unverifiable calls keep their holds and become `needs_review` after six
attempts. An hourly, paginated audit rebuilds drifted balance caches from the journal and records
repairs. Investigate `Model credit hold requires review` logs using the shared call ID; do not turn
missing provider evidence into a zero-cost settlement.

OpenRouter inference requests include the normal Opisense user ID in `user`, `HTTP-Referer`
(`https://opisense.com`), and `X-OpenRouter-Title` (`Opisense`). These values are sent only to
OpenRouter's HTTPS inference endpoints, never to compatible custom hosts.

## Testing with Mollie test mode

1. Put a `test_` key from your Mollie dashboard in an ignored `.env` as `MOLLIE_API_KEY`. Never
   commit it.
2. Fill in billing details in **Settings → Billing**, then subscribe and pay with one of Mollie's
   test cards. The test checkout also lets you pick the payment's outcome.
3. Without a public `WEB_ORIGIN`, returning from checkout applies the payment. To try webhooks,
   expose the web origin through a tunnel and set `WEB_ORIGIN` to it.

Automated tests never call Mollie: they run against an in-process emulator.
