# The account's billing

How a Praecise product's server records who pays Praecise, what it bills or covers, and its invoices, so that the person sees all of it on one page of their account. For products of the family only.

## What it is

A record at the account service of who pays Praecise (a billing relationship), and under it what each product bills or covers (lines) and the invoices each product reports. The person sees all of it on one page of their account, `https://accounts.praecise.com/billing`; each product's own billing screen links there.

Products push; the account service stores and shows. It calls no product, holds no key of the card processor, and never holds card or bank data. The processor's portal is reached through the product that owns the subscription, by the `manage_url` it gives.

## Who may do what

Every call is server to server, at `https://accounts.praecise.com`, with HTTP Basic: the product's own client id and secret, as for the lookup and [the feed](feed.md). No person's token, no browser call.

- A family product may write only for an account that has signed in to it (the account service's sign-in record), and only its own lines and invoices.
- Any such product may ensure a relationship for the account, read the account's relationships, and set a relationship's details. It reads back only its own lines and invoices, and only the processor reference it set itself.
- Only the owning account sees the Billing page. A second administrator of the same business does not, and a relationship cannot be moved to another account (a product's own billing screen may still show more people what it shows today).

`{account}` is the Praecise account id (`sub`). `{product}` is the caller's client id (`rivier`). An outside application has no credential for any of this.

## A relationship

```
{ "id": "6f1c…", "name": "Harbour Supplies Ltd", "country": "MV", "tax_id": "TIN 1234567",
  "currency": "USD", "state": "open", "processor_ref": "cus_…",      ← only to the product that set it
  "created_at": "…", "updated_at": "…" }
```

- `name`: the legal name for an invoice, 1 to 200 characters, or null. `country`: ISO 3166-1 alpha-2, upper case, or null. `tax_id`: up to 64 characters, or null.
- `currency`: ISO 4217, three upper-case letters; one per relationship. It may be null until the first amount: the first line or invoice with an amount sets it, and an amount in another currency is refused (409). Once set it does not change.
- `processor_ref`: the payer's reference at the card processor, an opaque string up to 255 characters. Stored, never shown on the page, never returned to another product.
- `state`: `open` or `closed`. A closed relationship takes no new lines and no changed lines (409); its invoices may still be written, and it stays on the page with its invoices.

### Ensure one

```
POST /api/billing/{account}/relationships
{ "id": "6f1c…" }                       → 200 that one (404 if the account has no such relationship)
{ }                                     → 200 the account's only one, or 201 its first (made now)
                                        → 409 {"error": "...", "relationships": [{"id", "name"}, ...]} when it has several
{ "new": true, "name": "…", ... }       → 201 a further one, only on the person's word
```

Making one may carry `name`, `country`, `tax_id`, `currency` and `processor_ref`; ensuring one that exists changes nothing (set details with PATCH).

### Read and set

```
GET   /api/billing/{account}/relationships               → 200 {"relationships": [...]}
GET   /api/billing/{account}/relationships/{id}          → 200 {"relationship": {...}, "lines": [...], "invoices": [...]}   the caller's own lines and invoices
PATCH /api/billing/{account}/relationships/{id}          → 200 {"relationship": {...}}
      { "name": …, "country": …, "tax_id": …, "currency": …, "processor_ref": …, "state": "closed" }   any of them; null clears name, country or tax_id
```

`state` may be set to `closed`, and back to `open`. `processor_ref` is the caller's: a second product setting one keeps its own beside the first (one payer per relationship is the products' rule to keep; the account service only stores what each says).

## Lines

```
PUT /api/billing/{account}/relationships/{id}/lines/{product}/{ref}
{
  "kind": "subscription",
  "label": "Rivier, Harbour Supplies website project",
  "plan": "Team",
  "state": "active",
  "period": { "start": "2026-11-01T00:00:00Z", "end": "2026-12-01T00:00:00Z" },
  "amount": { "value": 4900, "currency": "USD" },
  "manage_url": "https://app.rivier.ai/go/usage"
}
→ 201 (new) or 200 (replaced, or the same again) {"line": {...}}

DELETE /api/billing/{account}/relationships/{id}/lines/{product}/{ref}   → 204, 404 when there is none
```

- `ref`: the product's own reference (for Rivier the project id: a Rivier subscription belongs to a project, never to an organisation; see GOVERNING-DESIGN-RIVIER-ON-PRAECISE.md), 1 to 120 characters of `A-Z a-z 0-9 . _ : -`. The same line again replaces it; the same content again changes nothing, `updated_at` included.
- `kind`: `subscription` (something billed), `covered` (a Praecise resource a subscription pays for) or `usage` (a billed quantity).
- `covers`: for a `covered` line, compulsory: the `ref` of one of the same product's `subscription` lines on the same relationship. Removing a subscription line removes the lines that it covers. Other kinds carry no `covers`.
- `label`: what it is, 1 to 140 characters on one line, in English (the source). `labels`: optional, the same by any other language tag, up to 12; stored and returned, and shown once the account pages are offered in that language (today they are in English, the source).
- `plan`: the plan's name as data, up to 60 characters, or null. Never a figure the owner has not set.
- `state`: for a subscription, one of the processor's eight: `trialing`, `active`, `past_due`, `unpaid`, `paused`, `canceled`, `incomplete`, `incomplete_expired`; null otherwise.
- `period`: for a subscription, its current period, `start` before `end`; null otherwise.
- `amount`: `{ "value": whole minor units, 0 or more, "currency": ISO 4217 }`, or null when no price is set. A `covered` line carries none: it says who pays, not how much.
- `manage_url`: optional; where the person manages it, an https address on one of the writing product's own registered hosts (as the feed's `url`). No credentials, codes or tokens in it.
- Limit: 500 lines per product per relationship.

## Invoices

```
PUT /api/billing/{account}/relationships/{id}/invoices/{product}/{ref}
{ "number": "RV-2026-0042", "date": "2026-11-01", "amount": { "value": 4900, "currency": "USD" },
  "state": "paid", "url": "https://app.rivier.ai/go/usage?tab=billing&invoice=in_…" }
→ 201 or 200 {"invoice": {...}}

DELETE /api/billing/{account}/relationships/{id}/invoices/{product}/{ref}   → 204
```

- `number`: as printed on the invoice, 1 to 64 characters. `date`: the date of issue, `YYYY-MM-DD`. `amount`: as for a line, compulsory. `state`: `draft`, `open`, `paid`, `void`, `uncollectible`. `url`: compulsory, the address that opens the invoice, on the writing product's own hosts (the product's endpoint that makes the processor's short-lived link, never that link itself).
- Kept as long as the relationship; the page shows the latest 24.

## The Billing page

`/billing`, for the signed-in owner only. For each relationship: its legal details and currency (never the processor reference); its subscriptions, each with plan, state, period and amount when set, and under it what it covers; usage lines; the invoices, newest first; and each product's way to manage it (`manage_url`). With nothing yet, it says so and sends nobody anywhere. The details are changed where the subscription is managed (the processor holds them for the invoice); the page says so rather than offering a form that would not reach the invoice.

The account page links to it once the setting is on.

## What is never put here

No card or bank numbers, no processor secrets, no short-lived portal links, no passwords or tokens. Legal names and tax ids are a new kind of data at the account service: they are the person's, shown only to them, and go with the account when it is deleted.

## Linking to it

The person's Billing page is `https://accounts.praecise.com/billing`. One invoice has its own address, `https://accounts.praecise.com/billing/invoices/<product>/<ref>`, with your client id and the ref you wrote it under: link a feed item or a notice about an invoice there. It shows the invoice and links on to your `url`; an invoice the person does not hold answers 404.

## Errors and switching on

`400 {"error": "..."}` names the field. `401` without a valid client credential. `403` for another product's line, or an account that has not signed in to the caller. `404` no such account, relationship, line or invoice. `409` several relationships and no id, a currency that differs, a closed relationship. `413` over 16 KB. `429` over 600 writes or 1200 reads a minute per product, with `Retry-After`. `503 {"error": "billing is not switched on"}` while the setting is off; treat it as nothing to do, not something to retry in a loop.

Off until `ACCOUNT_BILLING=on` at the account service.

## What a billing product does

For the account of the person who starts a trial or a checkout: ensure a relationship, keeping its id and naming it on every later call; set `processor_ref` to its payer at the processor, and mark the payer there with the relationship id and the account id; write its lines whenever a subscription changes state; write each invoice the processor reports; and link its own billing screen to `https://accounts.praecise.com/billing`. "A payment failed" and "a limit is near" go to [the account's feed](feed.md) (kinds `payment` and `limit`).

## Rates (step 1A, 30 Nov 2026)

What a metered thing costs is data in `billing_rates`, entered by the operator; **nothing is seeded**. One row per product, meter, currency and `effective_from` day. A rate is never edited: a new row from a later day replaces it for usage from that day, and a rate can be *retired* (it stops from an end day; the older row does not come back).

Three models:

- `unit`: `unit_price` (minor units, a decimal string, as `"2.2"`) for each `unit_size` of the meter (`"3600"` for per vCPU-hour of seconds), `unit_label` names the unit, `free_quantity` is free each month for each account (same unit as the quantity reported).
- `level`: a quantity held (mailboxes, phone numbers, keys held, bytes stored) that the product reports as the level in each `level_period` (`"hour"` or `"day"`), one report for exactly one such period (anything else is `422`). The billed quantity for a month is the sum of the levels divided by the number of those periods in that calendar month (UTC; 28 to 31 days, times 24 for hours), so a level held all month is billed exactly once at the monthly price in a month of any length, and a level held half of it is billed half. The sum is exact and is priced against `unit_size` times the periods, so nothing is divided early. Nothing is free. Send `quantity`, never `cost`.
- `pass_through`: the product reports its own cost; the rate is `markup_percent` over it (`"10"`). Nothing is free.

Operator calls (`Authorization: Bearer <ACCOUNT_BILLING_OPERATOR_TOKEN>`, at least 32 characters; `503` while the setting is empty, `401` for a wrong token; a product's client credential is not accepted):

```
GET  /api/operator/rates                  → {"rates": [...]}  every row, history included
PUT  /api/operator/rates                  → 201 new, 200 the same again, 409 other figures from the same day
POST /api/operator/rates/retire           {product, meter, currency, effective_from, ended_on} → 200; 404; 409 if already retired from another day
```

A product reads the prices in force (Basic with its client id and secret, as everywhere here):

```
GET /api/rates?on=2026-12-15&product=cloud&currency=GBP   → {"on": "...", "rates": [...]}   `on` defaults to today (UTC)
```

All three need `ACCOUNT_BILLING=on`. Quantities and prices are decimal strings with at most 18 whole and 9 fractional digits. **Rounding**, everywhere: half up to a whole minor unit, done once on a month's running total of a meter (never on each event), so events always add up to the month's total.

## Usage and rating (step 1B)

A product reports a **complete** period of usage for a relationship (same credential and the same "has signed in to you" rule as lines):

```
POST /api/billing/{account}/relationships/{id}/usage
{ "meter": "messages", "key": "2026-11-03T01:msgs", "quantity": "1250.5",
  "period": { "start": "2026-11-03T00:00:00Z", "end": "2026-11-03T01:00:00Z" } }
→ 201 {"usage": {key, meter, month, quantity, cost, free_applied, amount:{value,currency}, rate_id, period}}   200 the same again
```

- `quantity`: a decimal string. For a pass-through meter send `cost` instead: `{"value": 5, "currency": "USD"}`, whole minor units of what the product paid.
- `key`: the idempotency key (1 to 120 of `A-Z a-z 0-9 . _ : -`), scoped to product and relationship. The same key with the same content changes nothing and answers 200 with the first answer; with other content, 409.
- `period` is UTC, `start` before `end`, **ended already** (5 minutes of clock skew allowed) and **inside one calendar month**; a longer span is reported in pieces.
- Priced by the rate in force **on the day the period began** (product = the calling product's client id). No rate: 422 and nothing stored, so the product keeps it and sends again once the operator has entered one.
- Currency: the relationship's. A relationship with none takes the currency given in the first usage (`currency`, or `cost.currency`) and holds it; another currency is 409. One currency per relationship, so one per invoice.
- A closed relationship takes none (409).

**Rating.** The free amount (`free_quantity` of the rate, in the meter's quantity) is taken **once for each account, each month and each meter**, across all of the account's relationships, in the order usage arrives. What remains is the billable quantity; the amount is `billable x unit_price / unit_size`, rounded **half up once on the account's running total** for that rate and month; an event's amount is the difference this makes, so the events always add up to the month's total (tested with twelve events arriving at once). A pass-through's amount is `cost x (100 + markup_percent) / 100`, rounded the same way. If the operator puts a new rate part-way through a month, each period is priced by the rate of its own start day; the free amount stays one for the month.

Each meter and month is **one `usage` line** on the relationship (`ref` = `usage:{meter}:{YYYY-MM}`, the caller's own product), rewritten with the new total each time, so the 500 line limit is met by 500 meter-months only. The caller reads its own totals: `GET /api/billing/{account}/relationships/{id}/usage?month=2026-12`.

Tables: `billing_usage_events` (one row per key), `billing_usage_totals` (the running totals by account, product, meter, month and rate).

## Charging on the Praecise Stripe account (step 1C)

All of Praecise's products bill through ONE Stripe account (`acct_1T2s9DKl0OgvgotR`); a product has no Stripe account of its own for this.

**Settings** (environment, as this service holds every credential; nothing in the database, a page or a log):

| Setting | Meaning |
| --- | --- |
| `STRIPE_SECRET_KEY` (or `STRIPE_SECRET_KEY_FILE`, a file such as a systemd credential) | the secret or restricted key; unset = card payments are off (503) |
| `ACCOUNT_STRIPE_MODE` | `test` (default) or `live`: what this deployment says it is |
| `ACCOUNT_STRIPE_LIVE` | `on` to allow live calls at all; anything else keeps live charging off |
| `STRIPE_WEBHOOK_SECRET` | the signing secret of the `/webhooks/stripe` endpoint |
| `ACCOUNT_BILLING_OPERATOR_TOKEN` | the operator's bearer token (32+ characters) |
| `ACCOUNT_BILLING_CHARGE_SUBSCRIPTIONS` | comma list of products whose `subscription` lines THIS service charges at the close. **Empty by default**: Rivier charges its own subscriptions today, and listing it here would charge them twice |

**The guard** (`src/stripe.ts`, run before every call): a test key under `live` mode, a live key under `test` mode, and any live call while `ACCOUNT_STRIPE_LIVE` is not `on` are refused before anything leaves the machine; a live key is used only against `api.stripe.com`. Every call that changes something carries an idempotency key made from what it is (`close:{relationship}:{month}:item:2`, `customer:{relationship}`).

**A saved card**: `POST /billing/card` (the signed-in owner; field `relationship`) makes the relationship's Stripe customer if needed and sends the person to Stripe's own hosted page (Checkout, setup mode). They return to `/billing/card/return`, and `checkout.session.completed` at `/webhooks/stripe` does the same; either way only brand, last four digits and expiry are kept (`billing_cards`). There is no card field of ours and no card data here.

**The close**: `POST /api/operator/billing/close {"month": "2026-11"}` (operator bearer; add `"relationship"` to close one). Run it from a timer on the first of the month; running it again changes nothing. For each relationship with metered usage that month (and subscription lines of the listed products overlapping it) it writes ONE invoice `INV-YYYY-NNNNNN` (`billing_closes`; also listed as the `praecise` product's invoice on the Billing page, `ref` `close:YYYY-MM`), makes one Stripe invoice with an item per meter and subscription, and pays it off-session with the saved card. A month with nothing owing makes no invoice. A paid one gets a receipt `RCT-YYYY-NNNNNN` (`billing_documents`). Usage for a month already invoiced is refused (409). Numbers are gapless per kind and year.

**Credit notes**: `POST /api/operator/billing/credit-notes {relationship, month, amount, reason}` refunds the card at Stripe and numbers a note `CRN-YYYY-NNNNNN`, at most what the card was charged in all.

Not paid (no card, declined, Stripe down) ends in state `failed` with the reason; step 1E takes it from there.

## Prepaid credit (step 1D)

A balance for each relationship, in the relationship's one currency (`billing_credit`, with a ledger `billing_credit_ledger`; a database check keeps it at 0 or more).

- **Top up by card**: `POST /billing/credit` (the signed-in owner; fields `relationship`, `amount` as typed, `25` or `25.50`, and `currency` only for a relationship that has none yet) sends the person to Stripe's hosted payment page. The return address and the webhook (`checkout.session.completed`, purpose `topup`) both add the credit, **once for each Stripe session** (ledger reference `topup:{session}`). The card paid with is kept (brand, last four) for the month's close. Bounds in minor units: `ACCOUNT_BILLING_TOPUP_MIN` (500) and `ACCOUNT_BILLING_TOPUP_MAX` (100000).
- **Draw down**: at the close, the month's **metered** lines are taken from the balance first (one ledger row, reference `close:{month}`); the card is charged for the rest, and a Stripe invoice shows the credit as a negative line. Subscription lines are not drawn from credit. If credit covers everything, no card is needed, Stripe is not asked for an invoice and a receipt is issued. A draw is cut to what the balance holds; it is never negative.
- **Low-balance notice**: when a close leaves the balance under `ACCOUNT_BILLING_LOW_BALANCE` (minor units; 0 = never), the owner gets one email, and the next only after a top-up lifts the balance back over it.
- **Operator**: `POST /api/operator/billing/credit/adjust {relationship, amount, ref, reason}` adds or takes an amount (once for each `ref`; a take is cut at zero).
- **Products** read the balance, to show or to limit by: `GET /api/billing/{account}/relationships/{id}/credit` → `{"credit": {"value": 2500, "currency": "GBP"}}`.

## Failed payments (step 1E)

A charge that does not go through (no card, a decline, Stripe unreachable) leaves the month's invoice `failed`, with Stripe's reason, and sets the next try. **Nothing is ever deleted**: no account, relationship, project or data; only the relationship's `standing` changes.

- **Retries**: the first try is at the close; then at **1, 3, 5 and 7 days after the first failure** (`ACCOUNT_BILLING_RETRY_DAYS`, a comma list of days, default `1,3,5,7`). Each try has its own idempotency key (`close:{rel}:{month}:pay:{n}`). A saved card is tried at once for what is unpaid, not on the next day.
- **Notices**: each failed try is told once by email and as a `payment` item on the person's feed ("we will try again on…", or "we will not try again by ourselves"), saying what happens after the grace period and that nothing is deleted. A paid month finishes the feed item.
- **Grace period**: `ACCOUNT_BILLING_GRACE_DAYS` (default 7) days from the first failure. A shipped "policy shape" for it was not found in the repository (see RESULT), so it is this setting.
- **Past due**: after the grace period the relationship's `standing` becomes `past_due` (told once). Products read it in the relationship they already read: `GET /api/billing/{account}/relationships/{id}` now carries `"standing": "good" | "past_due"`, and the credit read shows the balance. It is for products to **limit** what the relationship can do (for example stop new resources or raise the price of nothing), never to delete. When everything is paid it returns to `good` and the owner is told.
- **Run it daily** from a timer: `POST /api/operator/billing/dunning` (operator bearer) does the tries that are due, the notices and the standing, and answers `{retried, paid, noticed, past_due, recovered}`. Running it again changes nothing. The close call runs the notices and the standing as well.

## What the Billing pages show (step 1F)

`/billing` (the owner only) now carries, under each relationship: a notice when the payment is overdue and the unpaid invoices; **usage so far this month** with quantity, free amount used and amount for each meter; the **card on file** (brand, last four, expiry) with a button to save or change it; the **credit** balance, its latest movements and a form to add some; **receipts and credit notes**; and the invoices as before. Once for the account, the **prices in force today**. The buttons appear only when card payments are set up (`STRIPE_SECRET_KEY`). A Praecise invoice at `/billing/invoices/praecise/close:YYYY-MM` shows its lines, the credit used, what was charged to the card and its receipts. The page is in English, the source language, like the rest of this page; it uses the account page's own styles and shows no Stripe reference.

## Fixes of 30 Nov 2026 (branch fixes-1130)

- **Webhook events** (`src/webhooks.ts`): `invoice.paid`, `invoice.payment_failed`, `charge.refunded`, `charge.dispute.created`, `charge.dispute.closed`. Each event id is applied once (`billing_webhook_events`; a failed handling deletes its claim so Stripe sends it again). The state is a statement of what Stripe reports, so it is the same whichever of the event or our own call comes first: a close is settled once (one receipt); a failure is recorded on the schedule once; credit notes add up to Stripe's `amount_refunded` (our own credit note already counts); a dispute row (`billing_disputes`) is never reopened once won or lost. A charge that is not an invoice's (a top-up) is ignored and logged: what to do about a disputed top-up is the operator's. Add these events to the Stripe endpoint's list.
- **Timers**: `deploy/` holds the two systemd units and timers (`Persistent=true`); the scripts `scripts/month-close.ts` and `scripts/dunning-run.ts` read the operator token from a credential file and print one line.
- **Rates as data**: `rates/praecise-2026-11-30.json` and `npm run rates:put -- rates/praecise-2026-11-30.json`. The file lists what it leaves out and why.
- **Refunds**: a credit note finds the charge or payment intent that paid the invoice (Stripe's refund call takes those, not an invoice).
- **Sandbox**: `npm run stripe:sandbox` with a test key and a throwaway `DATABASE_URL` (see the header of `scripts/stripe-sandbox-run.ts`).
- Node 22.18 or newer (`engines`).
