carlos / platform Public

plan: billing dashboard 1 (money record) and 2 (pages)

Plan 1: neutral payment records in internal/billing with the Stripe
mapping (balance movements, charges and refunds, charge webhooks), an
hourly reconcile with a cursor and an automatic backfill, the yearly
subscription amount on billing_accounts, the paying rule and account
groups, daily ECB rates through internal/fxrate, a daily ARR snapshot,
and carlos billing revenue and payments.

Plan 2: the Billing rail item, /fleet/billing, its accounts and payments
lists and the Dashboard tile, reading Plan 1's interfaces and Plan 3's
carlosPlatformCostUSD through one platformCostEUR function.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 101f5614cafae9c0f95a8e19fe5545b3a7588b13 parent c61c05f
2 files changed, +1,262 −0
  • docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md +740 −0
  • docs/superpowers/plans/2026-11-09-billing-dashboard-2-pages.md +522 −0
diff --git a/docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md b/docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md
new file mode 100644
index 000000000..c3013dd17
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md
@@ -0,0 +1,740 @@
+# Billing dashboard 1: the money record Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** On a console with billing on, record every payment, refund and
+provider fee from the billing provider, store each subscription's yearly
+amount, sort every account into one group, keep daily euro reference rates
+and a daily ARR snapshot, and show the result through `carlos billing
+revenue` and `carlos billing payments`.
+
+**Architecture:** Neutral records and three new read-only `billing.Provider`
+methods in `internal/billing`; the Stripe mapping (balance transactions,
+charges with their refunds, invoice billing reasons, discounts) in
+`internal/billingstripe`. The console stores payments in a new
+`billing_payments` table, fed by the webhook (new `EventPayment`), by an
+hourly reconcile over balance movements with a cursor, and by a backfill that
+the reconcile runs on its own when no cursor exists. Rates come from the ECB
+through a new `internal/fxrate` adapter. The reconcile, the rate fetch and
+the ARR snapshot run inside the existing billing worker
+(`StartBillingSyncPass`), after the subscription sync. Plan 2
+(`2026-11-09-billing-dashboard-2-pages.md`) builds the pages on the
+interfaces named here.
+
+**Tech Stack:** Go, `database/sql` (console SQLite), `encoding/xml`, Stripe
+REST API version `2025-02-24.acacia` (pinned in `client.go`).
+
+**Spec:** `docs/superpowers/specs/2026-11-09-billing-dashboard-design.md`
+(approved 2026-11-09): §3, §4.2, §4.3, §4.4, §4.7. Plan 2 covers §4.1, §4.6
+and §5; Plan 3 (written separately) covers §4.5.
+
+## Global Constraints
+
+- **Provider-neutral core.** The console imports `internal/billing` types
+ only. Stripe objects and words (`txn_`, `billing_reason`, `stripe_fee`)
+ stay in `internal/billingstripe`; ECB XML stays in `internal/fxrate`
+ behind `fxrate.Source`.
+- **Reads only.** Every new provider call is a GET. Nothing here writes to
+ Stripe (spec §2 non-goals; Invariant 5 of `billingSyncPass`).
+- **Never gate readiness on the new reads.** A restricted key without the
+ new permissions fails the money pass (logged, `jobFailed`), never
+ `Check`, the webhook's other kinds or the subscription sync.
+- **Idempotent on the provider id.** `billing_payments.provider_id` is the
+ primary key; a second record of the same id writes nothing.
+- **Integer minor units everywhere stored.** Converting to euros happens on
+ read, for display only; no converted figure is stored back into billing
+ state (spec §3). Rates are stored as the ECB publishes them (units per
+ euro).
+- **"Paying"** (spec §4.2): provider status `active` or `past_due` AND at
+ least one recorded payment of kind `subscription` for the account's
+ current subscription. `billing_accounts.state` is not used for it.
+- **ARR** (spec §4.2): yearly amount after discounts, before tax, over paying
+ accounts, excluding any with `cancel_at_period_end` and the exempt
+ account. `past_due` stays in.
+- **Groups** (spec §4.7), first match wins: Ours (`planExempt`), Paying
+ (paying and yearly amount not 0; unknown counts as not 0), House
+ (`billing_house` row), Sponsored (`account_plans.source = 'sponsored'` or
+ sponsored limits set), Free.
+- **No request calls out.** CLI doors read the console DB only; the provider
+ and the ECB are read by the billing worker alone.
+- **New tables** are classified `NonApp` in `internal/console/store_gate.go`.
+- **Record-write census.** When `TestPlan9B8RecordWriteCensus`
+ (`internal/provision`) names a changed unit, re-pin it in
+ `internal/provision/billing_dashboard_1_census_test.go` (form of
+ `first_run_next_steps_census_test.go`: a function
+ `billingDashboard1WriteCensusInventory()` layered on the inventory the test
+ calls, `gvisorDemosWriteCensusInventory` on 2026-11-09, with a comment
+ saying what was reviewed), and point the test at the new function. Expect
+ `Server.registerCLIRoutes` in Task 9.
+- **Root-read census (#280)** applies to Task 9 only: `billing_cli.go` and
+ `billing_cli_copy.go` are root-binary files. `internal/billing`,
+ `internal/billingstripe`, `internal/fxrate`, `internal/console` and
+ `cmd/console` are out of its scope.
+- **Per-task review** (AGENTS.md stopping rule 3): Tasks 1, 3 and 5 touch
+ provider reads and money records, so each gets its own Opus or Astra
+ review; the rest ride the whole-branch review.
+- **Copy:** CLI and docs strings come from the Task 8 deck, applied
+ verbatim. No em dashes. Operator log lines are outside copy review.
+- **Tests:** only touched packages, `go test ./internal/<pkg> -run '<Name>'
+ -count=1`; CI runs the full suite. Go commands may need the Bash sandbox
+ disabled; leave `GOCACHE` at its default.
+- **Commits:** subject under 80 characters, prefixed (`billing:`,
+ `billingstripe:`, `console:`, `fxrate:`, `cli:`, `docs:`), body after a
+ blank line.
+- **Neutral examples** in tests: account `bab` (claim harness) or `shop`,
+ customer `cus_1`, `shop.example.com`.
+
+## Review Focus
+
+1. **A webhook and the reconcile record the same charge at once.** One row,
+ no error from the loser (Task 4 `TestRecordPaymentIdempotent`, Task 5
+ `TestWebhookThenReconcileOneRow`).
+2. **More than 1,000 movements in one window.** The window halves until the
+ list fits; the cursor never passes a movement that was not recorded
+ (Task 5 `TestReconcileHalvesWindowOnIncomplete`,
+ `TestReconcileCursorHoldsOnError`).
+3. **A refund whose charge was never recorded** (refunded before the
+ backfill read it, or the webhook lost). The refund is recorded against
+ the same account, from the charge read the refund triggers (Task 5
+ `TestReconcileRefundOfUnrecordedCharge`).
+4. **The ECB is down or answers nonsense.** The last good rates stay; a
+ rate of 0, a negative rate or an empty set is refused, never stored
+ (Task 6 `TestECBRefusesBadRates`, `TestRatesPassKeepsLastGood`).
+5. **A house account (100% coupon) and a cancel-at-renewal account.** The
+ house account has yearly amount 0 and no payment, so it is House, not
+ Paying; the cancelling account is Paying but outside ARR (Task 1
+ `TestAnnualOf`, Task 7 `TestARROf`).
+
+---
+
+### Task 1: The subscription's yearly amount
+
+**Files:**
+- Modify: `internal/billing/billing.go` (`Subscription`)
+- Modify: `internal/billingstripe/client.go` (`SubscriptionItem`,
+ `Subscription`, `getSubscription` ~792), `internal/billingstripe/catalog.go`
+ (`Coupon` gains `Currency`)
+- Create: `internal/billingstripe/annual.go`
+- Modify: `internal/billingstripe/adapter.go` (`subscriptionOf` ~222)
+- Modify: `internal/console/billingstore.go` (`migrateBilling6b` ALTER list,
+ `billingAccount`, `billingAccountColumns`, `scanBillingAccount`,
+ `putBillingState`)
+- Modify: `internal/console/billingsync.go` (`decideBilling`)
+- Test: `internal/billingstripe/annual_test.go`,
+ `internal/billingstripe/prepared_test.go` (~939),
+ `internal/console/billingstore_test.go`, `internal/console/billingsync_test.go`
+
+**Interfaces:**
+- Produces:
+ - `billing.Subscription` gains `Annual int64` (what the next year will
+ charge, after discounts, before tax, minor units of `Currency`) and
+ `AnnualKnown bool` (false: the adapter could not tell; `Annual` is 0).
+ - `billingstripe.SubscriptionItem` gains `UnitAmount *int64`
+ (`price.unit_amount`) and `HasDiscounts bool` (the item's own
+ `discounts` is non-empty). `billingstripe.Subscription` gains
+ `Discounts []Discount`; `type Discount struct { Coupon Coupon; End
+ time.Time }` (zero `End`: none). `Coupon` gains `Currency string`.
+ - `func annualOf(s *Subscription) (amount int64, known bool)` in
+ `annual.go`.
+ - Column `billing_accounts.annual_amount INTEGER NOT NULL DEFAULT -1`;
+ `billingAccount.Annual int64` (-1 unknown). The sync stores
+ `sub.Annual` when `AnnualKnown`, else -1. The currency is the existing
+ `billing_accounts.currency`, which the sync already sets from
+ `sub.Currency`.
+
+- [ ] **Step 1: Write the failing tests**
+ - `TestAnnualOf` (table, usd): one Personal item `unit_amount 2800 × 1` →
+ `2800, true`; plus a pack `1200 × 2` → `5200, true`; a 100% forever
+ coupon → `0, true`; 50% forever → `1400, true`; `amount_off 500 usd`
+ forever → `2300, true`; `amount_off` larger than the total → `0, true`;
+ `duration once` → `2800, true` (it does not reach the next year);
+ `repeating` with `End` after `CurrentPeriodEnd` → discounted, with `End`
+ before it → `2800, true`; `amount_off` in eur on a usd subscription →
+ `0, false`; a coupon with `AppliesToProducts` → `0, false`; an item
+ with no `unit_amount` → `0, false`; an item with its own discount →
+ `0, false`; `ItemsHasMore` → `0, false`.
+ - `TestSubscriptionDecodesDiscounts`: a JSON body with expanded
+ `discounts` and `items.data[].price.unit_amount` decodes into the new
+ fields; the request carries `expand[]=latest_invoice` and
+ `expand[]=discounts` (update the check at `prepared_test.go:941` to read
+ `r.URL.Query()["expand[]"]`).
+ - `TestBillingAccountAnnualRoundTrip`: a fresh row reads `Annual == -1`;
+ `PutBillingState` with 2400 reads back 2400.
+ - `TestDecideBillingStoresAnnual`: paid, `AnnualKnown` 2400 →
+ `Next.Annual == 2400`; `AnnualKnown false` → -1; an ended read keeps
+ the read's value (the row is not paying either way).
+- [ ] **Step 2: Run** `go test ./internal/billingstripe ./internal/console -run 'TestAnnualOf|TestSubscriptionDecodesDiscounts|TestBillingAccountAnnualRoundTrip|TestDecideBillingStoresAnnual' -count=1` → FAIL (undefined).
+- [ ] **Step 3: Implement.** `annualOf`: `known=false` if `ItemsHasMore`,
+ any item lacks `UnitAmount` or `HasDiscounts`; gross = Σ unit × quantity;
+ then each subscription discount in listed order that reaches the next
+ renewal (`Duration == "forever"`, or `"repeating"` with `End` after
+ `CurrentPeriodEnd`): `PercentOff` subtracts `round(gross × pct / 100)`,
+ `AmountOff` subtracts itself when `Coupon.Currency == s.Currency`, else
+ unknown; `AppliesToProducts` non-empty is unknown; floor at 0.
+ `subscriptionOf` sets both fields. Add the ALTER to the 6b list, the
+ field everywhere `billingAccount` columns are listed, and
+ `next.Annual` in `decideBilling` beside the other provider facts.
+- [ ] **Step 4: Run** the Step 2 command plus `-run 'Billing|Subscription|Decide'` on both packages → PASS.
+- [ ] **Step 5: Commit** `billing: store each subscription's yearly amount`.
+
+### Task 2: Neutral payment records and the fake
+
+**Files:**
+- Create: `internal/billing/payments.go`
+- Create: `internal/billing/billingtest/fake_money.go`
+- Modify: `internal/billing/billingtest/fake.go` (`init`, `ParseEvent`
+ accepts kind `payment`)
+- Test: `internal/billing/payments_test.go`,
+ `internal/billing/billingtest/fake_money_test.go`
+
+**Interfaces:**
+- Produces (all in `internal/billing`):
+ - `type MovementKind string` = `MovementCharge "charge"`,
+ `MovementRefund "refund"`, `MovementRefundFailure "refund_failure"`,
+ `MovementFee "fee"`, `MovementOther "other"`.
+ - `type Movement struct { ID string; Kind MovementKind; Type string /* the
+ provider's own word, for logs */; Source string /* the charge or refund
+ it settles */; Charge string /* for charge, refund and refund failure:
+ the charge */; Amount, Fee int64 /* settled, signed */; Currency string
+ /* settlement */; At time.Time }`.
+ - `type PaymentKind string` = `PaymentSubscription "subscription"`,
+ `PaymentOnceOff "once_off"`, `PaymentRefund "refund"`, `PaymentFee "fee"`.
+ - Reasons: `ReasonFirst "first"`, `ReasonRenewal "renewal"`,
+ `ReasonChange "change"`, `ReasonDomain "domain"`, `ReasonOther "other"`,
+ `ReasonReversed "reversed"` (a refund that failed and came back).
+ - `type Payment struct { ID, Movement string; Kind PaymentKind; Reason
+ string; Customer, Subscription, PaymentIntent, Charge string; Amount,
+ Tax int64; Currency string /* as charged, signed: negative for refunds
+ and fees */; Settled, Fee, SettledTax int64; SettledCurrency string; At
+ time.Time; LiveMode bool }`. `ID` is the provider id of what was paid
+ or refunded, or the movement id for a fee or a reversal.
+ - `type ChargeRecord struct { Captured bool; Charge Payment; Refunds
+ []Payment }` (refunds already settled, each `Kind PaymentRefund`).
+ - `func SettledShare(part, whole, settled int64) int64` — `round(part ×
+ settled / whole)`, 0 when `whole` is 0 (settled tax, and a refund's
+ tax share).
+ - `func FeePayment(m Movement, live bool) Payment` and
+ `func ReversalPayment(m Movement, refunded *Payment, live bool) Payment`
+ (copy customer, subscription and charge from the refunded row when
+ known).
+ - `EventPayment EventKind = "payment"`: `Event.Object` is a charge id.
+- Produces (`billingtest.Fake`): fields `Movements []billing.Movement`,
+ `Charges map[string]billing.ChargeRecord`, `AccountOpened time.Time`, and
+ the three methods Task 3 adds to `billing.Provider`, with these
+ semantics: `MoneyMovements` filters `Movements` to `[from, to)`, pages
+ them like `list` (counted under `CallsBy["MoneyMovements"]`, one per
+ page; more than `MaxListPages` pages is `billing.ErrIncomplete`);
+ `ChargePayments` returns `Charges[id]` or `billing.ErrNotFound`;
+ `AccountCreated` returns `AccountOpened`. `Err` fails all three.
+
+- [ ] **Step 1: Write the failing tests**: `TestSettledShare` (tax 400 of
+ 2800 charged, 2610 settled → 373; whole 0 → 0; negative settled keeps
+ its sign); `TestFeePaymentAndReversal` (fee movement -45 eur →
+ `Kind fee, Settled -45, Fee 0, ID == movement id`; reversal copies the
+ refunded row's customer and charge, `Reason reversed`, positive
+ `Settled`); `TestFakeMoneyMovementsWindowAndPages` (five movements, a
+ window holding three returns those three oldest first; `PageSize 1` and
+ eleven movements → `ErrIncomplete`); `TestFakeParsesPaymentEvent`.
+- [ ] **Step 2: Run** `go test ./internal/billing/... -run 'TestSettledShare|TestFeePayment|TestFakeMoney|TestFakeParsesPayment' -count=1` → FAIL.
+- [ ] **Step 3: Implement** both files.
+- [ ] **Step 4: Run** the same → PASS.
+- [ ] **Step 5: Commit** `billing: neutral payment records and a fake to feed them`.
+
+### Task 3: The Stripe mapping and the payment events
+
+**Files:**
+- Modify: `internal/billing/billing.go` (`Provider` gains three methods)
+- Create: `internal/billingstripe/money.go`
+- Modify: `internal/billingstripe/merchant.go` (read `created` from
+ `/v1/account`)
+- Modify: `internal/billingstripe/adapter.go` (`ParseEvent` ~158)
+- Modify: `scripts/stripe-setup.sh` (`WEBHOOK_EVENTS` ~106; the "six"
+ wording in `WEBHOOK_PROBLEM` from the Task 8 deck, so this one line waits
+ for Task 8), `cmd/console/stripesetup_script_test.go` (~547)
+- Test: `internal/billingstripe/money_test.go`,
+ `internal/billingstripe/adapter_test.go` (`TestParseEventKinds`)
+
+**Interfaces:**
+- Consumes: Task 2 types.
+- Produces, on `billing.Provider` and `*billingstripe.Provider`:
+ - `MoneyMovements(ctx context.Context, from, to time.Time) ([]billing.Movement, error)`
+ — `GET /v1/balance_transactions` with `created[gte]`, `created[lt]`,
+ `expand[]=data.source`, through `listAll` (so `billing.ErrIncomplete`
+ past `MaxListPages`), returned oldest first. Types `charge`, `payment`
+ → `MovementCharge` (`Charge` = source id); `refund`, `payment_refund` →
+ `MovementRefund` (`Charge` = the refund's `charge`); `refund_failure`,
+ `payment_failure_refund` → `MovementRefundFailure`; `stripe_fee`,
+ `tax_fee` → `MovementFee`; anything else (payouts, adjustments) →
+ `MovementOther`.
+ - `ChargePayments(ctx context.Context, charge string) (billing.ChargeRecord, error)`
+ — `GET /v1/charges/<id>` with `expand[]` `balance_transaction`,
+ `invoice`, `refunds`, `refunds.data.balance_transaction`; refunds past
+ the first page through `GET /v1/refunds?charge=<id>` (`listAll`, same
+ expansion). 404 → `billing.ErrNotFound`. `Captured` is
+ `captured && balance_transaction != null`. Kind and reason from the
+ invoice's `billing_reason`: `subscription_create` → subscription/first,
+ `subscription_cycle` → subscription/renewal, `subscription_update` →
+ once-off/change, other or no invoice → once-off/other. `Tax` is the
+ invoice's `tax` (0 without an invoice); `Subscription` the invoice's
+ subscription; `SettledTax` by `billing.SettledShare`. A refund is
+ `Kind refund`, `Amount` and `Settled` negative, `Tax` its share of the
+ charge's tax, refunds without a balance transaction or with status
+ `failed` or `canceled` left out.
+ - `AccountCreated(ctx context.Context) (time.Time, error)` — `created`
+ of `GET /v1/account`.
+ - `ParseEvent`: `charge.succeeded`, `charge.captured`, `charge.refunded`
+ → `EventPayment` with `Object` the charge id (validated like the
+ other ids). `invoice.paid` keeps mapping to `EventSubscription`.
+ - `WEBHOOK_EVENTS` gains those three events.
+
+- [ ] **Step 1: Write the failing tests** with `httptest` fixtures in the
+ pinned API version's shapes:
+ - `TestMoneyMovementsMapsTypes`: one fixture page holding `charge`,
+ `payment`, `refund` (source expanded with `charge`), `refund_failure`,
+ `stripe_fee`, `payout`; assert each `Kind`, `Charge`, signed `Amount`,
+ `Fee`, `Currency "eur"`; the request carries both `created` bounds and
+ `expand[]=data.source`; result oldest first.
+ - `TestMoneyMovementsIncomplete`: eleven full pages → `billing.ErrIncomplete`.
+ - `TestChargePaymentsSubscriptionFirst`: a usd charge 2800 with invoice
+ `subscription_create`, `tax 0`, balance transaction eur 2610 fee 106
+ → `Captured`, `Kind subscription`, `Reason first`, `Subscription
+ "sub_1"`, `Settled 2610`, `Fee 106`, `SettledCurrency "eur"`.
+ - `TestChargePaymentsTaxAndRefund`: eur charge 2904 with invoice tax 504
+ and one 2904 refund → charge `Tax 504`, `SettledTax 504`; refund
+ `Amount -2904`, `Tax -504`, `Kind refund`, `Charge` set.
+ - `TestChargePaymentsUpdateIsOnceOff`: `subscription_update` →
+ once-off/change; a charge with no invoice → once-off/other, `Tax 0`.
+ - `TestChargePaymentsUncaptured`: `captured false` → `Captured false`,
+ no records; 404 → `billing.ErrNotFound`.
+ - `TestChargePaymentsRefundPages`: `refunds.has_more` → the second page
+ is read from `/v1/refunds?charge=`.
+ - `TestAccountCreated`.
+ - `TestParseEventKinds`: add rows for the three charge events (→
+ `EventPayment`, object the charge id) and a charge event with an
+ unusable id → `ErrBadEvent`.
+ - `stripesetup_script_test.go`: the expected `enabled_events` list.
+- [ ] **Step 2: Run** `go test ./internal/billingstripe ./cmd/console -run 'TestMoneyMovements|TestChargePayments|TestAccountCreated|TestParseEventKinds|Stripe' -count=1` → FAIL.
+- [ ] **Step 3: Implement** `money.go` (wire structs local to the file,
+ strict `id`/`livemode` decoding as `Subscription.UnmarshalJSON` does),
+ the interface methods, the event mapping and the script list. Run `go
+ build ./...` to find any other `billing.Provider` implementation.
+- [ ] **Step 4: Run** the Step 2 command → PASS; `go vet ./internal/billing/... ./internal/billingstripe` clean.
+- [ ] **Step 5: Commit** `billingstripe: read balance movements and charges`.
+
+### Task 4: The payment table and account matching
+
+**Files:**
+- Create: `internal/console/billingpayments_store.go`
+- Modify: `internal/console/billingstore.go` (`migrateBillingOperations`
+ ends with `return s.migrateBillingMoney()`)
+- Modify: `internal/console/store_gate.go` (classify the new tables)
+- Test: `internal/console/billingpayments_store_test.go`
+
+**Interfaces:**
+- Consumes: Task 2 `billing.Payment`.
+- Produces:
+ - `func (s *Store) migrateBillingMoney() error` creating
+ `billing_payments (provider_id TEXT PRIMARY KEY, movement_id TEXT NOT
+ NULL, kind TEXT NOT NULL, reason TEXT NOT NULL, account_id INTEGER NOT
+ NULL DEFAULT 0, customer, subscription, payment_intent, charge TEXT NOT
+ NULL DEFAULT '', amount INTEGER NOT NULL, tax INTEGER NOT NULL,
+ currency TEXT NOT NULL, settled INTEGER NOT NULL, fee INTEGER NOT NULL,
+ settled_tax INTEGER NOT NULL, settled_currency TEXT NOT NULL, detail
+ TEXT NOT NULL DEFAULT '', at INTEGER NOT NULL, live INTEGER NOT NULL,
+ recorded_at INTEGER NOT NULL)` with indexes on `at`, `(account_id,
+ at)` and `subscription`, and `billing_payment_cursor (id INTEGER
+ PRIMARY KEY CHECK (id = 1), through INTEGER NOT NULL)`. Task 6 and Task
+ 7 add their tables to this function.
+ - `type paymentRow struct { billing.Payment; AccountID int64; Detail
+ string; RecordedAt time.Time }` (`AccountID` 0: unmatched).
+ - `func (s *Store) RecordPayment(p billing.Payment, now time.Time) (bool, error)`
+ — one transaction: match, then `INSERT ... ON CONFLICT(provider_id) DO
+ NOTHING`; true when a row was written. Matching, first hit wins:
+ 1. `p.PaymentIntent` equals a `domain_purchases.payment_intent` → that
+ purchase's account, `Reason domain`, `Detail` the domain; when
+ `p.Tax == 0`, the purchase's currency is `p.Currency` and `p.Amount
+ > purchase.amount`, `Tax = p.Amount − amount` and `SettledTax` by
+ `billing.SettledShare`;
+ 2. `p.Customer` equals a `billing_accounts.customer` → that account;
+ 3. `p.Charge` names a recorded row → that row's account (and its
+ subscription when `p.Subscription` is empty);
+ 4. otherwise 0.
+ - `func (s *Store) HasPayment(providerID string) (bool, error)`
+ - `func (s *Store) PaymentByID(providerID string) (*paymentRow, error)` (nil when none)
+ - `func (s *Store) RematchPayments() (int, error)` — re-runs rules 1-3 for
+ rows with `account_id = 0`; returns how many matched.
+ - `type paymentFilter struct { From, To time.Time /* zero: open */; Kind
+ string /* "": every kind but fee; "subscription", "once_off",
+ "refund", "fee", "unmatched" (account 0, fees excluded) */; AccountID
+ int64 /* 0: all */; Offset, Limit int /* Limit 0: no limit */ }`
+ - `func (s *Store) Payments(f paymentFilter) ([]paymentRow, int, error)`
+ — newest first by `at` then `provider_id`, and the count matching.
+ - `func (s *Store) PaymentCursor() (through time.Time, ok bool, err error)`
+ and `func (s *Store) SetPaymentCursor(through time.Time) error`.
+ - Gate rows: `billing_payments` {NonApp: "money received, refunded or
+ kept as fees, keyed by the provider's id and the account; names no
+ app"}, `billing_payment_cursor` {NonApp: "how far the payment
+ reconcile has read; names no app"}.
+ - Account deletion leaves payment rows alone: they are the money record.
+
+- [ ] **Step 1: Write the failing tests**
+ - `TestRecordPaymentIdempotent`: the same `billing.Payment` twice → true
+ then false, one row; a second record with other amounts does not
+ change the first.
+ - `TestRecordPaymentMatchesCustomer`, `TestRecordPaymentMatchesDomainPurchase`
+ (purchase amount 1500 usd, charge 1800 usd, tax 0 → `Tax 300`,
+ `Reason domain`, `Detail` the domain), `TestRecordPaymentRefundFollowsCharge`
+ (refund with no customer, `Charge` recorded on account A → A),
+ `TestRecordPaymentUnmatched` (→ 0, listed by `Kind "unmatched"`).
+ - `TestRematchPayments`: unmatched row, then the customer is bound →
+ `RematchPayments` returns 1 and the row has the account.
+ - `TestPaymentsFilter`: month bounds, each kind, `""` leaving out fee
+ rows, account, offset/limit, total, newest first.
+ - `TestPaymentCursorRoundTrip`: none → `ok false`; set, read back.
+ - `TestPaymentsSurviveAccountReap`: `ReapAccount` keeps the rows.
+- [ ] **Step 2: Run** `go test ./internal/console -run 'TestRecordPayment|TestRematchPayments|TestPaymentsFilter|TestPaymentCursor|TestPaymentsSurvive' -count=1` → FAIL.
+- [ ] **Step 3: Implement**, plus the gate rows. If a table-inventory test
+ lists tables, add the new ones there.
+- [ ] **Step 4: Run** the same plus `-run 'StoreGate|Billing'` → PASS.
+- [ ] **Step 5: Commit** `console: billing payment table and account matching`.
+
+### Task 5: Reconcile, backfill and the webhook
+
+**Files:**
+- Create: `internal/console/billingmoneypass.go`
+- Modify: `internal/console/billingpass.go` (the `jobs.Run` closure in
+ `StartBillingSyncPass` ~93 runs `billingMoneyPass` after
+ `billingSyncPass`)
+- Modify: `internal/console/billingwebhook.go` (`EventPayment` branch)
+- Modify: `internal/console/jobs_test.go` (`jobPassFuncs["StartBillingSyncPass"]`
+ gains `"billingMoneyPass"`, `"reconcilePayments"`, `"recordCharge"`)
+- Test: `internal/console/billingmoneypass_test.go`,
+ `internal/console/billingwebhook_test.go`
+
+**Interfaces:**
+- Consumes: Tasks 2-4.
+- Produces:
+ - Constants `billingMoneyWindow = 31 * 24 * time.Hour`,
+ `billingMoneyMinWindow = time.Hour`, `billingMoneyOverlap = time.Hour`.
+ - `func (s *Server) billingMoneyPass(ctx context.Context, now time.Time)`
+ — returns at once unless billing is on and ready; under
+ `s.billingClock(ctx)`, runs `reconcilePayments`, then
+ `billingRatesPass` (Task 6), then `billingSnapshotPass` (Task 7), each
+ failure logged and passed to `jobFailed`, none stopping the next.
+ - `func (s *Server) reconcilePayments(ctx context.Context, now time.Time) error`:
+ 1. `through, ok := PaymentCursor()`; with no cursor this is the
+ backfill: `from = AccountCreated(ctx)`; else `from = through −
+ billingMoneyOverlap`.
+ 2. While `from < now`: `to = min(from + window, now)`;
+ `MoneyMovements(from, to)`. On `billing.ErrIncomplete` halve the
+ window and retry the same `from`; below `billingMoneyMinWindow`
+ return the error. Any other error returns it.
+ 3. For the window's movements, oldest first: charge and refund kinds
+ whose `Source` is not yet recorded add `Charge` to a set; fee →
+ `RecordPayment(billing.FeePayment(m, live))`; refund failure →
+ `RecordPayment(billing.ReversalPayment(m, PaymentByID(m.Source), live))`;
+ other → logged once per type per run.
+ 4. `recordCharge` for each charge in the set; the first error returns
+ it, leaving the cursor where it was.
+ 5. `SetPaymentCursor(to)`, `from = to`, window back to
+ `billingMoneyWindow`.
+ 6. After the loop, `RematchPayments`.
+ - `func (s *Server) recordCharge(ctx context.Context, charge string, now time.Time) error`
+ — `ChargePayments`; `billing.ErrNotFound` or `!Captured` → nil; a
+ record whose `LiveMode` is not the console's → logged and skipped,
+ nil; else `RecordPayment` for the charge and every refund.
+ - Webhook: `case billing.EventPayment:` → `recordCharge(s.billingClock(r.Context()), ev.Object, now)`;
+ error → 503 (the provider redelivers); success → 204. Its doc comment
+ gains the case.
+
+- [ ] **Step 1: Write the failing tests** (on `newBillingFixture`, the fake
+ seeded with `Movements`, `Charges` and `AccountOpened`):
+ - `TestReconcileBackfillsFromAccountCreation`: no cursor, account opened
+ 90 days ago, movements spread across it → every charge recorded; the
+ fake saw windows starting at `AccountOpened`; cursor = now.
+ - `TestReconcileFromCursor`: cursor 2 h ago → the first window starts
+ at 3 h ago (overlap); an already recorded charge is not read again
+ (`CallsBy["ChargePayments"]` counts only new ones).
+ - `TestReconcileHalvesWindowOnIncomplete`: `PageSize 1` and more than
+ `MaxListPages` movements in 31 days, fewer in 7 → all recorded.
+ - `TestReconcileCursorHoldsOnError`: `ChargePayments` fails for one
+ charge in the second window → the first window's cursor is stored, the
+ second's is not; a later run with the failure cleared records it.
+ - `TestReconcileRefundOfUnrecordedCharge`: only a refund movement in the
+ window, its charge never recorded → charge and refund recorded, refund
+ on the charge's account.
+ - `TestReconcileFeesAndReversals`: a fee movement → one fee row; a
+ refund failure → a reversal row with the refunded row's account.
+ - `TestReconcileSkipsOtherMode`: a charge record with the other
+ `LiveMode` → nothing recorded, no error.
+ - `TestWebhookPaymentEventRecords` (204, row present),
+ `TestWebhookPaymentEventTransient` (fake `Err` → 503, nothing written),
+ `TestWebhookThenReconcileOneRow` (webhook records, reconcile over the
+ same window → still one row).
+ - `TestMoneyPassFailureDoesNotStopSync`: `MoneyMovements` failing leaves
+ the subscription sync's writes in place and fails the job.
+- [ ] **Step 2: Run** `go test ./internal/console -run 'TestReconcile|TestWebhookPayment|TestWebhookThenReconcile|TestMoneyPass' -count=1` → FAIL.
+- [ ] **Step 3: Implement.** `billingRatesPass` and `billingSnapshotPass`
+ do not exist yet: call only `reconcilePayments` here; Tasks 6 and 7 add
+ their calls.
+- [ ] **Step 4: Run** the same plus `-run 'TestPassFailureLogsAlsoFailTheJob|Webhook|BillingSync'` → PASS.
+- [ ] **Step 5: Commit** `console: reconcile payments hourly, from the webhook too`.
+
+### Task 6: Daily euro reference rates
+
+**Files:**
+- Create: `internal/fxrate/fxrate.go`, `internal/fxrate/fxrate_test.go`,
+ `internal/fxrate/testdata/eurofxref-daily.xml`
+- Create: `internal/console/billingrates.go`
+- Modify: `internal/console/billing.go` (`BillingConfig.Rates`)
+- Modify: `internal/console/billingpayments_store.go` (`migrateBillingMoney`
+ adds the table), `internal/console/store_gate.go`
+- Modify: `cmd/console/billing.go:101` (`Rates: fxrate.ECB{URL: fxrate.ECBDailyURL}`)
+- Modify: `internal/console/billingmoneypass.go` (call `billingRatesPass`)
+- Test: `internal/console/billingrates_test.go`
+
+**Interfaces:**
+- Produces (`internal/fxrate`):
+ - `type Rates struct { Day string /* "2006-01-02", the ECB's date */;
+ PerEUR map[string]float64 /* lower-case code → units per euro */ }`
+ - `type Source interface { Latest(ctx context.Context) (Rates, error) }`
+ - `const ECBDailyURL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"`
+ - `type ECB struct { URL string; Client *http.Client /* nil: 20 s timeout */ }`
+ and `func (e ECB) Latest(ctx context.Context) (Rates, error)`: GET,
+ status 200 only, body at most 64 KiB, `encoding/xml` over
+ `Cube/Cube[@time]/Cube[@currency,@rate]`; refuses a missing or
+ unparsable date, an empty set, or any rate that is not a positive
+ finite number.
+- Produces (`internal/console`):
+ - `BillingConfig.Rates fxrate.Source` (nil: no rates are fetched).
+ - Table `billing_eur_rates (day TEXT NOT NULL, currency TEXT NOT NULL,
+ per_eur REAL NOT NULL, fetched_at INTEGER NOT NULL, PRIMARY KEY (day,
+ currency))`; gate {NonApp: "daily euro reference rates; names no app"}.
+ - `type eurRates struct { Day string; PerEUR map[string]float64 }`
+ - `func (r eurRates) eurCents(minor int64, currency string) (int64, bool)`
+ — `eur` is itself; another currency is `round(minor / PerEUR[c])`;
+ false when the currency has no rate. Every selling currency has two
+ decimals, so minor units convert to cents directly.
+ - `func (s *Store) PutEURRates(r fxrate.Rates, now time.Time) error` (upsert per row)
+ - `func (s *Store) LatestEURRates() (eurRates, error)` — the newest day's
+ set; zero `Day` when none was ever stored.
+ - `const billingRatesEvery = 20 * time.Hour`
+ - `func (s *Server) billingRatesPass(ctx context.Context, now time.Time) error`
+ — skips when `Rates` is nil or the newest row's `fetched_at` is within
+ `billingRatesEvery`; otherwise `Latest` and `PutEURRates`. A failure
+ returns the error and stores nothing; the last good rates stay in use.
+
+- [ ] **Step 1: Write the failing tests**
+ - `TestECBParsesDaily` (testdata: date `2026-11-06`, `USD 1.0823`,
+ `GBP 0.8412` → lower-case keys, those values); `TestECBRefusesBadRates`
+ (rate `0`, `-1`, `NaN`, no `time`, no cubes, status 500, a body over
+ 64 KiB → errors).
+ - `TestEURCents`: 2800 usd at 1.12 → 2500; 2400 eur → 2400; unknown
+ currency → false.
+ - `TestRatesPassFetchesDaily`: fake `Source` counting calls; first pass
+ fetches, a pass 2 h later does not, one 21 h later does.
+ - `TestRatesPassKeepsLastGood`: a stored day, then a failing source →
+ error, `LatestEURRates` still the stored day.
+- [ ] **Step 2: Run** `go test ./internal/fxrate ./internal/console -run 'TestECB|TestEURCents|TestRatesPass' -count=1` → FAIL.
+- [ ] **Step 3: Implement** and wire `billingRatesPass` into `billingMoneyPass`.
+- [ ] **Step 4: Run** the same plus `go build ./cmd/console` → PASS.
+- [ ] **Step 5: Commit** `fxrate: daily ECB reference rates for the billing figures`.
+
+### Task 7: Paying, groups, ARR and the daily snapshot
+
+**Files:**
+- Create: `internal/console/billingrevenue.go`
+- Modify: `internal/console/billingpayments_store.go` (`migrateBillingMoney`
+ adds the snapshot table), `internal/console/store_gate.go`
+- Modify: `internal/console/billingmoneypass.go` (call `billingSnapshotPass`)
+- Test: `internal/console/billingrevenue_test.go`
+
+**Interfaces:**
+- Consumes: Tasks 1, 4, 6.
+- Produces:
+ - `type billingFact struct { AccountID int64; Sqid, Name string; Created
+ time.Time; Apps int; Plan string; Packs map[string]int; Seats int;
+ PlanSource string; Sponsored, House bool; Subscription, ProviderStatus,
+ Currency string; CancelAtPeriodEnd bool; PeriodEnd time.Time; Annual
+ int64 /* -1 unknown */; Paid bool; FirstPaid time.Time }` — `Paid` and
+ `FirstPaid` from `billing_payments` rows of kind `subscription` for
+ `Subscription`.
+ - `func (s *Store) BillingFacts() ([]billingFact, error)` — every live
+ account, in id order, one query (accounts, `account_plans`,
+ `billing_house`, `billing_accounts`, app counts, payments).
+ - `type billingGroup string` = `groupOurs "ours"`, `groupPaying
+ "paying"`, `groupHouse "house"`, `groupSponsored "sponsored"`,
+ `groupFree "free"`; `var billingGroupOrder = []billingGroup{groupPaying,
+ groupFree, groupSponsored, groupHouse, groupOurs}` (the page's tab order).
+ - `func payingNow(f billingFact) bool`
+ - `func billingGroupOf(f billingFact, exemptID int64) billingGroup`
+ - `func inARR(f billingFact, exemptID int64) bool` — paying, not
+ cancelling, `Annual > 0`, not exempt.
+ - `type arrTotals struct { ByCurrency map[string]int64; EUR int64;
+ EURKnown bool; RateDay string; Paying, Attention int }` — `Attention`
+ counts paying accounts that are `past_due` or cancelling; `EURKnown`
+ false when a currency in `ByCurrency` has no rate.
+ - `func arrOf(facts []billingFact, exemptID int64, r eurRates) arrTotals`
+ - Table `billing_arr_daily (day TEXT PRIMARY KEY, arr TEXT NOT NULL /*
+ JSON currency → minor */, arr_eur INTEGER NOT NULL, eur_known INTEGER
+ NOT NULL, rate_day TEXT NOT NULL, paying INTEGER NOT NULL, rebuilt
+ INTEGER NOT NULL DEFAULT 0, written_at INTEGER NOT NULL)`; gate
+ {NonApp: "daily recurring revenue totals; names no app"}.
+ - `type arrSnapshot struct { Day string; ARR map[string]int64; EUR int64;
+ EURKnown bool; RateDay string; Paying int; Rebuilt bool }`
+ - `func (s *Store) PutARRSnapshot(a arrSnapshot, now time.Time) (bool, error)` (insert or ignore)
+ - `func (s *Store) ARRSnapshots(fromDay, toDay string) ([]arrSnapshot, error)` (inclusive, oldest first)
+ - `func rebuildARR(rows []paymentRow, days []time.Time, r eurRates) []arrSnapshot`
+ — pure, for each day: per currency, the pre-tax amounts (`Amount −
+ Tax`) of subscription payments in the 365 days up to that day, less
+ refunds of those charges; `Paying` the distinct accounts among them;
+ `Rebuilt true`.
+ - `func (s *Server) billingSnapshotPass(ctx context.Context, now time.Time) error`
+ — writes today's (UTC) row once. When the table is empty it first
+ writes rebuilt rows for the first of each month from the month of the
+ earliest subscription payment through this month, skipping today.
+ - `type billingRevenue struct { arrTotals; Groups map[billingGroup]int;
+ Accounts int; MonthStart *arrSnapshot /* first snapshot on or after
+ the 1st of this month, nil when none */; TestMode bool }`
+ - `func (s *Server) billingRevenueNow(now time.Time) (billingRevenue, []billingFact, error)`
+ — `BillingFacts`, `LatestEURRates`, `arrOf`, the group counts and
+ `MonthStart`; `TestMode` is `!s.billing.cfg.LiveMode`. Plan 2's pages
+ and Task 9's door both read through it.
+
+- [ ] **Step 1: Write the failing tests**
+ - `TestPayingNow`: active+paid → true; past_due+paid → true;
+ trialing+paid → false; active, no payment → false; incomplete → false.
+ - `TestBillingGroupOf` (table): exempt id → ours even when paying;
+ paying with Annual 2400 → paying; paying with Annual -1 → paying;
+ paying with Annual 0 and a house row → house; sponsored source →
+ sponsored; operator source with sponsored limits → sponsored;
+ otherwise free.
+ - `TestARROf`: eur 2400 + usd 2800 at usd 1.12 → `ByCurrency
+ {eur:2400, usd:2800}`, `EUR 4900`, `EURKnown`; a cancelling account adds
+ nothing to ARR and 1 to `Attention`; a past_due one adds to both; gbp
+ with no rate → `EURKnown false`.
+ - `TestBillingFactsQuery`: an account per group, a deleted account
+ (absent), apps counted, `FirstPaid` the earliest subscription payment.
+ - `TestRebuildARR`: one 2400 eur first payment on 7 Oct, a refunded 1000
+ usd payment → the 1 Nov point is `{eur:2400}`, `Paying 1`; the 1 Sep
+ point is empty.
+ - `TestSnapshotPassOncePerDay`: two passes on one day → one row; the
+ next day → a second row; first ever pass with old payments → rebuilt
+ month rows plus today's.
+- [ ] **Step 2: Run** `go test ./internal/console -run 'TestPayingNow|TestBillingGroupOf|TestARROf|TestBillingFactsQuery|TestRebuildARR|TestSnapshotPass' -count=1` → FAIL.
+- [ ] **Step 3: Implement** and wire `billingSnapshotPass` into `billingMoneyPass` (after rates).
+- [ ] **Step 4: Run** the same → PASS.
+- [ ] **Step 5: Commit** `console: paying accounts, groups, ARR and its daily snapshot`.
+
+### Task 8: The copy deck for the CLI and docs, reviewed
+
+**Files:**
+- Create: `docs/superpowers/plans/2026-11-09-billing-dashboard-1-copy.md`
+ (rows `BDC-1..n`, columns id | file | text | status, the format of
+ `2026-11-08-edge-page-cache-copy.md`)
+
+**Slots to draft** (the wording is the reviewer's; the draft is a start):
+- `billing_cli_copy.go`: the usage line with the two new verbs; flag help
+ for `-month` and `-kind`; the revenue lines (ARR with the per-currency
+ note and the rate date, MRR, paying of all accounts, needs attention,
+ one line of group counts, the test-mode line, "no rate yet"); the
+ payments head and its empty line; "unmatched"; the kind words; the bad
+ `-month` and bad `-kind` refusals.
+- `internal/console` door refusals for a bad month or kind (JSON errors).
+- `docs/site/cli.md` `### carlos billing`: one paragraph for the two verbs
+ and their example lines.
+- `docs/site/plans.md`: one sentence after the variables table saying the
+ key also needs read access to balance, charges and refunds, and that
+ Stripe's webhook also sends `charge.succeeded`, `charge.captured` and
+ `charge.refunded`.
+- `scripts/stripe-setup.sh`: the `WEBHOOK_PROBLEM` line that says "the six".
+
+- [ ] **Step 1: Draft the deck**, every row `pending`, no em dashes.
+- [ ] **Step 2: Run the `copy-review` skill**; apply Paul's edits verbatim,
+ mark rows `approved`, and note the review id in the record's header.
+- [ ] **Step 3: Commit** `docs: billing dashboard 1 copy deck, approved`.
+
+### Task 9: `carlos billing revenue` and `carlos billing payments`
+
+**Files:**
+- Modify: `internal/console/apibilling.go` (two handlers),
+ `internal/console/authcli.go` (`registerCLIRoutes` ~1085)
+- Modify: `billing_cli.go`, `billing_cli_copy.go`
+- Modify: `docs/site/cli.md` (~2305), `docs/site/plans.md` (~158),
+ `scripts/stripe-setup.sh` (the approved line)
+- Modify: `internal/console/claim_invariant_fixtures_test.go` (~900),
+ `internal/console/claim_invariant_probes_read_test.go` (~359)
+- Create: `approved_billing_dashboard_copy_test.go` (repo root, gate of the
+ Task 8 record: inventory `BDC-1..n`, built list `billingDashboardCopyBuilt`,
+ using the moves gate's helpers as `approved_operator_pages_copy_test.go` does)
+- Create: `internal/provision/billing_dashboard_1_census_test.go`; modify
+ `internal/provision/plan9_b8_census_test.go:369`
+- Create: the root-read census overlay and card via `make census-propose
+ NAME=billing-dashboard-1 CLAIMS=<file>`
+- Test: `internal/console/apibilling_test.go`, `billing_cli_test.go`
+
+**Interfaces:**
+- Consumes: Task 4 `Payments`, Task 7 `billingRevenueNow`, Task 8 copy.
+- Produces:
+ - `GET /api/cli/billing/revenue` (`billingDoor`): `{"arr":{"eur":2400},
+ "arr_eur":2400,"eur_known":true,"rate_day":"2026-11-06","mrr_eur":200,
+ "paying":1,"accounts":38,"attention":0,"groups":{"paying":1,...},
+ "test_mode":false}`; amounts in minor units; `mrr_eur` is `arr_eur / 12`
+ rounded.
+ - `GET /api/cli/billing/payments?month=YYYY-MM&kind=K` (`billingDoor`;
+ `kind` as `paymentFilter.Kind`, limit 500): an array of `{"id","at",
+ "account","kind","reason","detail","amount","tax","currency","settled",
+ "fee","settled_currency"}`, newest first; `account` the sqid, "" when
+ unmatched or deleted. A bad month or kind is 400 with the approved text.
+ - `carlos billing revenue` and `carlos billing payments [-month YYYY-MM]
+ [-kind subscription|once-off|refund|fee|unmatched]` in
+ `runBillingWithSession`, printing the approved lines.
+ - Claim fixtures: `"route GET /api/cli/billing/revenue"` and
+ `"route GET /api/cli/billing/payments"` as `claimRead("operator view of
+ billing revenue|payments; names no app")`, probes `claimAPIRead` on
+ `claimBillingWorld`.
+
+- [ ] **Step 1: Write the failing tests**
+ - `TestAPIBillingRevenue`: billing world with one paying eur account and
+ a stored rate → the JSON above; a member (not operator) → 404; billing
+ off → 409 like `problems`.
+ - `TestAPIBillingPayments`: month and kind filters, unmatched shows `""`;
+ `month=2026-13` and `kind=x` → 400.
+ - `TestBillingRevenueCLI` and `TestBillingPaymentsCLI` (beside the
+ `problems` CLI tests): output lines equal the approved copy; `-kind
+ once-off` sends `once_off`.
+ - `TestApprovedBillingDashboardCopy` (inventory and built rows).
+ - The `internal/docsite` gate over `docs/site/cli.md`.
+- [ ] **Step 2: Run** `go test . ./internal/console ./internal/docsite -run 'TestAPIBilling|TestBilling.*CLI|TestApprovedBillingDashboardCopy|TestClaimConsoleMutationInvariant|Docsite' -count=1` → FAIL.
+- [ ] **Step 3: Implement** the doors, the routes, the verbs, the docs, the
+ script line and the fixtures.
+- [ ] **Step 4: Censuses.**
+ - Record-write: run `go test ./internal/provision -run TestPlan9B8RecordWriteCensus -count=1`,
+ re-pin each unit it names (expect `Server.registerCLIRoutes`) per Global
+ Constraints, rerun → PASS.
+ - Root-read (#280): `make census-card`; write the CLAIMS file under
+ `$TMPDIR` (one line
+ per changed unit of `billing_cli.go` and `billing_cli_copy.go`: "adds
+ the revenue and payments verbs; no root read added"); `make
+ census-propose NAME=billing-dashboard-1 CLAIMS=<file>`; `go test
+ ./internal/provision -run 'TestPlan14RootReadCensus|TestCensusScopeIsTheRootBinary' -count=1`
+ → PASS. Brief an Astra reviewer from
+ `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`; record its verdict
+ on #280 with the tip.
+- [ ] **Step 5: Run** the Step 2 command → PASS; `gofmt -l .` empty.
+- [ ] **Step 6: Commit** `cli: carlos billing revenue and payments`.
+
+---
+
+## After the plan
+
+- Before the first roll that carries this, Paul adds Balance, Charges and
+ Refunds read to the dev and flagship restricted keys, and the three
+ charge events to both webhook endpoints. Without them the money pass
+ fails its job and nothing else changes; once added, the next hourly pass
+ backfills everything.
+- Done means (spec §7, the parts this plan owns): on flagship `carlos
+ billing revenue` shows the first customer with the right ARR, and
+ `carlos billing payments` shows their payment with Stripe's fee and the
+ settled euros; on dev the same with the test-mode line; stopping the
+ webhook for an hour loses nothing.
diff --git a/docs/superpowers/plans/2026-11-09-billing-dashboard-2-pages.md b/docs/superpowers/plans/2026-11-09-billing-dashboard-2-pages.md
new file mode 100644
index 000000000..483d94f55
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-09-billing-dashboard-2-pages.md
@@ -0,0 +1,522 @@
+# Billing dashboard 2: the pages Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** A **Billing** section in the operator pages of a billing-on
+console: a rail item under Dashboard, an overview at `/fleet/billing`, the
+full account list at `/fleet/billing/accounts`, the full payment list at
+`/fleet/billing/payments`, and a Paying accounts tile on the Dashboard,
+all in euros, and none of it on a console without billing.
+
+**Architecture:** Read-only pages over Plan 1's records
+(`billingRevenueNow`, `BillingFacts`, `Payments`, `LatestEURRates`,
+`ARRSnapshots`), Economics' modelled per-account cost (`LoadEconomics(ctx,
+"last")`) and the platform cost through one function, `platformCostEUR`,
+over Plan 3's `carlosPlatformCostUSD`. Pure builders turn those inputs into view models;
+thin handlers behind `operatorOnly` gather the inputs and render
+`opshell.html` pages built from the operator parts (`rst-*`, `co-*`).
+Nothing calls Stripe, Cost Explorer or the ECB while rendering.
+
+**Tech Stack:** Go, `html/template`, `static/ops.css`, console SQLite, the
+deployment bucket (Economics bills).
+
+**Spec:** `docs/superpowers/specs/2026-11-09-billing-dashboard-design.md`
+(approved 2026-11-09): §4.1, §4.5 (display side), §4.6, §5. Final mockup:
+the brainstorm's `billing-v4` (banner removed; whole rows clickable).
+**Depends on** Plan 1 (`2026-11-09-billing-dashboard-1-data.md`) and Plan 3
+slice A (`2026-11-09-billing-dashboard-3-carlos-only-cost.md`, Tasks 1-4)
+merged (AGENTS.md stopping rule 4).
+
+## Global Constraints
+
+- **Invisible with billing off** (spec §2 goal 7): no rail item, no tile,
+ and every billing route answers exactly what an unknown route answers
+ (`http.NotFound`), to operators too. The routes are registered without a
+ method prefix (as `/fleet/architecture` is), so a POST cannot draw a 405
+ that shows the route exists; each handler checks `r.Method == GET`
+ itself. They are registered on every console, so the claim census sees
+ them; the 404 comes from the handler.
+- **Operators only** (`operatorOnly`), checked before the billing check.
+- **Euros everywhere**, converted with Plan 1's `eurRates.eurCents`; the
+ native-currency breakdown stays beside every converted total; every
+ converted figure carries the rate date. With no stored rate, converted
+ figures show the approved "no rate yet" text, never €0.
+- **Estimates are labelled** wherever they appear: per-account costs
+ (Economics' model) and anything built from them.
+- **Platform cost is shown only when `platformCostEUR` says `OK`** (spec
+ §4.5), always with its `Label`. Otherwise the platform cost, profit,
+ cash after costs and "Shared and idle" are hidden and its `Hint` shows
+ in their place.
+- **Revenue is before tax** everywhere; tax collected is its own column of
+ the money table and never counted as revenue or profit.
+- **Lists show at most 5 rows** with a link to the full list; **every row is
+ clickable across its whole width** (`co-rowlink`, Task 4). Account rows
+ open `/fleet/activity?account=<sqid>` (the operator pages' account view,
+ as People and accounts links it); payment rows open the paying account;
+ month rows open the payments list for that month; reason rows open the
+ Accounts tab.
+- **Test mode** (`!s.billing.cfg.LiveMode`): every billing page and the
+ Dashboard tile say plainly that the figures are Stripe test-mode figures.
+- **Copy:** every user-facing string comes from the Task 1 record, applied
+ verbatim through `opbilling_copy.go`; no string is typed into a template
+ or Go file before it is approved. No em dashes; brand via `.Brand`.
+- **Design rules:** existing operator parts only (`op_page_header`,
+ `rst-stats`, `rst-card`, `rst-lrow`, `rst-box-head`, `co-bars`,
+ `op_seg_tabs`, `op_empty`); new CSS only in `static/ops.css`; no coloured
+ left-border accents; no Bricolage Grotesque; check 390 px wide.
+- **Record-write census:** Task 2 changes `NewServer`. Re-pin it (and any
+ other unit `TestPlan9B8RecordWriteCensus` names) in
+ `internal/provision/billing_dashboard_2_census_test.go`, function
+ `billingDashboard2WriteCensusInventory()`, layered on the inventory the
+ test calls at the time (Plan 1's `billingDashboard1WriteCensusInventory`
+ once that merges), and point the test at it. The root-read census (#280)
+ does not apply: everything here is console-only.
+- **Tests:** `go test ./internal/console -run '<Name>' -count=1`; CI runs
+ the full suite. Go commands may need the Bash sandbox disabled; leave
+ `GOCACHE` at its default.
+- **Commits:** subject under 80 characters, prefixed (`console:`, `docs:`),
+ body after a blank line.
+- **Neutral examples:** `shop`, `you@example.com`, `shop.example.com`.
+
+## Interfaces from Plan 1 (consumed as named)
+
+`billingRevenueNow(now) (billingRevenue, []billingFact, error)`;
+`billingRevenue{arrTotals; Groups; Accounts; MonthStart; TestMode}`;
+`arrTotals{ByCurrency; EUR; EURKnown; RateDay; Paying; Attention}`;
+`billingFact` (fields as Plan 1 Task 7); `payingNow`, `billingGroupOf`,
+`inARR`, `billingGroup` and `billingGroupOrder`; `Store.Payments(paymentFilter)`
+and `paymentRow`; `billing.Payment`, `billing.PaymentKind` constants and
+reasons; `Store.LatestEURRates()`, `eurRates.eurCents`;
+`Store.ARRSnapshots(fromDay, toDay)`; `s.store.planExemptID`.
+
+## The platform cost: one function over Plan 3's seam
+
+Plan 3 (`2026-11-09-billing-dashboard-3-carlos-only-cost.md`, Task 2,
+"names are final") provides `func (s *Server) carlosPlatformCostUSD(ctx
+context.Context, month string) (usd float64, basis string, ok bool)`, `ok`
+only for a CARLOS-only basis (`economics.BasisAccount` or
+`economics.BasisTagged`), `basis` `""` for a whole-account bill and
+`costBasisMissing` for none; `costBasisLabel(basis, deployment string)
+string` (its copy C1-C3); and `costBasisHint(scope CostScope, basis, month
+string) string` (C4-C6, the line shown in place of a hidden cost). Plan 2
+reads platform cost through one function of its own, in Task 3:
+
+```go
+// platformCost is one month's platform cost as the Billing pages may show it.
+type platformCost struct {
+ Cents int64 // euro cents; meaningful only when OK
+ Basis string // as carlosPlatformCostUSD returns it
+ Label string // costBasisLabel(Basis, ""): shown beside a figure
+ Hint string // costBasisHint(s.cfg.CostScope, Basis, month), or the
+ // approved "no rate yet" text: shown in place of a figure
+ OK bool // a CARLOS-only figure exists and its dollars converted
+}
+
+// platformCostEUR is the month's ("2006-01") platform cost: Plan 3's
+// carlosPlatformCostUSD, converted with r (eurCents of round(usd × 100),
+// "usd"). Every page reads platform cost through this function only.
+func (s *Server) platformCostEUR(ctx context.Context, month string, r eurRates) platformCost
+```
+
+So Plan 2 is built after Plan 3's slice A (its Tasks 1-4) merges, as well as
+Plan 1. The basis lines and hints are Plan 3's approved copy; Plan 2's
+record does not repeat them.
+
+## Review Focus
+
+1. **Billing off.** An operator's GET and POST to all three routes answer
+ the body and status of an unknown route; no rail item; no tile (Task 2
+ `TestBillingRoutesHiddenWhenOff`, Task 7 `TestDashboardTileOnlyWithBilling`).
+2. **No CARLOS-only figure.** A whole-account bill on a console with no
+ cost setting, or no bill for the month: no platform cost, profit, cash
+ after costs or "Shared and idle" figure appears, and Plan 3's hint does
+ (Task 3 `TestEarnedHiddenWithoutBasis`, Task 4
+ `TestOverviewHidesCostWithoutBasis`).
+3. **No rate stored yet.** A fresh console whose rate fetch never succeeded
+ shows "no rate yet" for converted figures and still shows the
+ native-currency notes, never €0 (Task 4 `TestOverviewNoRate`).
+4. **Nothing yet.** No payments, no paying accounts, no Economics data: the
+ page renders its empty states, percentages do not divide by zero, and
+ the six month rows show €0.00 (Task 4 `TestOverviewEmpty`).
+5. **Payments of a deleted or unknown account.** An unmatched row shows the
+ approved Unmatched label and is not a link; a deleted account's row
+ shows the approved deleted label and is not a link (Task 6
+ `TestPaymentsUnmatchedAndDeleted`).
+
+---
+
+### Task 1: The copy record, reviewed before any string is written
+
+**Files:**
+- Create: `docs/superpowers/plans/2026-11-09-billing-dashboard-2-copy.md`
+ (rows `BDP-1..n`; id | file | text | status; the format of
+ `2026-10-25-operator-pages-copy.md`, files relative to `internal/console/`)
+
+**Slots to draft** (from the mockup where it has words; the wording is the
+reviewer's):
+- Rail label `Billing`; the three pages' subheads; the Accounts and
+ Payments page titles.
+- Test-mode line; rate note (`at ECB rates of %s`); "no rate yet";
+ estimate label; "unknown" (no Economics figure). The basis lines and the
+ hidden-cost hints are Plan 3's C1-C6, not rows here.
+- Overview tiles: ARR (with `+%s this month` and the per-currency note),
+ MRR (`ARR ÷ 12`), Received this month (net, its note), Paying accounts
+ (`%s of %s (%s)` and its change), Needs attention (its note).
+- Paying accounts list: heading, link, column heads, statuses (Paid,
+ Cancels at renewal, Payment failing), the footnote, "paying since %s".
+- Earned panel: heading per month (`%s so far, earned`), lines (Recurring
+ (MRR), Once-off, Refunds, AWS bill (month to date), Profit), the note.
+- Funnel: heading and its four steps.
+- Money by month: heading, column heads (with Tax), "%s so far", the
+ footnote.
+- Recent payments: heading, link, column heads, the What words per reason
+ (first year, renewal, plan change, domain, other, refund, reversed), the
+ status words (Paid, Refund, Unmatched), the deleted-account label.
+- Weekly bars: heading, axis words, the screen-reader caption.
+- Not paying by reason: heading, link, column heads (`Cost to run, %s`),
+ one label per group, `Shared and idle`.
+- Free accounts closest to limits: heading, link, column heads, `%s of %s`,
+ the note.
+- Accounts page: tab labels, column heads, sort labels, pager text, empty
+ state per tab.
+- Payments page: filter labels (month, kind words), column heads, pager,
+ empty state.
+- Dashboard tile: label `Paying accounts`, note `%s a year`, the link word.
+
+- [ ] **Step 1: Draft the record,** every row `pending`, no em dashes.
+- [ ] **Step 2: Run the `copy-review` skill;** apply Paul's edits
+ verbatim, mark rows `approved`, note the review id in the header.
+- [ ] **Step 3: Commit** `docs: billing pages copy record, approved`.
+
+Every later task takes its strings from this record through
+`opbilling_copy.go` and adds the ids it writes to
+`billingPagesCopyBuilt` (Task 2 creates both).
+
+### Task 2: The rail item, the routes and the page shells
+
+**Files:**
+- Modify: `internal/console/opshell.go` (`opShell.Billing`,
+ `opRailItem.BillingOnly`, `opRail`, `opRailFor`, `opPage`)
+- Create: `internal/console/opbilling.go`, `internal/console/opbilling_copy.go`
+- Create: `internal/console/templates/ops_billing.html`,
+ `ops_billing_accounts.html`, `ops_billing_payments.html` (header and the
+ test-mode line only)
+- Modify: `internal/console/server.go` (`page` fields; three
+ `registerRoute` calls beside `/fleet/economics` ~1978)
+- Modify: `internal/console/claim_invariant_fixtures_test.go`,
+ `internal/console/claim_invariant_probes_read_test.go`
+- Modify: `approved_billing_dashboard_copy_test.go` (repo root, Plan 1):
+ the second record's inventory `BDP-1..n` and built list
+ `billingPagesCopyBuilt`, with its two tests
+- Create: `internal/provision/billing_dashboard_2_census_test.go`; modify
+ `internal/provision/plan9_b8_census_test.go`
+- Test: `internal/console/opbilling_test.go`, `internal/console/opshell_test.go`
+
+**Interfaces:**
+- Produces:
+ - `opRailItem.BillingOnly bool`; `opShell.Billing bool`, set by `opPage`
+ to `s.billing != nil`; `opRailFor` drops `BillingOnly` items when
+ `!op.Billing`. `opRail` gains `{Key: "billing", Href: "/fleet/billing",
+ Label: <BDP rail label>, BillingOnly: true}` directly after Dashboard.
+ - `func (s *Server) billingPageGate(w http.ResponseWriter, r *http.Request) (addr, raw string, ok bool)`
+ — `operatorOnly`; then a method other than GET, or `s.billing == nil`,
+ is `http.NotFound`.
+ - Handlers `handleOpBilling`, `handleOpBillingAccounts`,
+ `handleOpBillingPayments`, registered as `"/fleet/billing"`,
+ `"/fleet/billing/accounts"`, `"/fleet/billing/payments"`; templates
+ `ops_billing`, `ops_billing_accounts`, `ops_billing_payments`.
+ - `page` fields `OpBilling *opBillingView`, `OpBillingAccounts
+ *opBillingAccountsView`, `OpBillingPayments *opBillingPaymentsView`;
+ each view carries `TestMode bool`.
+ - `opbilling_copy.go`: one `const` or `var` per approved row, named
+ `billCopy<Thing>`, each with its `BDP-n` id in a comment.
+ - Claim fixtures `"route /fleet/billing"`, `"route
+ /fleet/billing/accounts"`, `"route /fleet/billing/payments"` as
+ `claimRead("operator billing view; reads billing records; names no
+ app")`, probes `claimPageRead` on `claimBillingWorld` wanting the
+ page's `<h1>`.
+
+- [ ] **Step 1: Write the failing tests**
+ - `TestBillingRoutesHiddenWhenOff`: an operator, billing off: GET and
+ POST on each route → status and body equal to GET `/fleet/no-such`.
+ - `TestBillingRoutesOperatorOnly`: billing on, a member → the same 404;
+ no session → the same 404.
+ - `TestBillingRoutesRender`: billing on, operator → 200, the page `<h1>`;
+ test mode shows the test-mode line, live mode does not.
+ - `TestOpRailBillingGate` (in `opshell_test.go`): rail with `Billing` has
+ the item second; without it, absent; `/fleet/index` likewise.
+ - `TestApprovedBillingPagesCopy` (inventory and built rows).
+- [ ] **Step 2: Run** `go test ./internal/console . -run 'TestBillingRoutes|TestOpRail|TestApprovedBillingPagesCopy|TestClaimConsoleMutationInvariant' -count=1` → FAIL.
+- [ ] **Step 3: Implement**, then the census:
+ `go test ./internal/provision -run TestPlan9B8RecordWriteCensus -count=1`,
+ re-pin what it names (expect `NewServer`), rerun.
+- [ ] **Step 4: Run** the Step 2 command and the census → PASS.
+- [ ] **Step 5: Commit** `console: Billing in the operator rail, behind billing`.
+
+### Task 3: Money for the pages (pure)
+
+**Files:**
+- Create: `internal/console/opbilling_money.go`
+- Test: `internal/console/opbilling_money_test.go`
+
+**Interfaces:**
+- Consumes: Plan 1 `paymentRow`, `billingFact`, `eurRates`, `payingNow`,
+ `billingGroupOf`; Plan 3 `carlosPlatformCostUSD`, `costBasisLabel`,
+ `costBasisHint`, `s.cfg.CostScope`.
+- Produces:
+ - `platformCost` and `platformCostEUR` exactly as above. Plan 3's `ok`
+ with a usd rate → `OK`, `Cents`, `Label`; Plan 3's `ok` without a rate
+ → not `OK`, `Hint` the approved "no rate yet"; not `ok` → not `OK`,
+ `Hint` from `costBasisHint`.
+ - `func eurText(cents int64) string` — `€24.00`, `−€188.00` (U+2212, as
+ `dashDelta`), thousands with commas; `func minorText(minor int64,
+ currency string) string` — `$28.00`, `£22.00`, `€24.00`, any other
+ currency as `28.00 XYZ`.
+ - `type moneyMonth struct { Month string /* "2006-01" */; Subscriptions,
+ OnceOff, Refunds, Tax, Fees, Net int64 /* euro cents */; EURKnown bool;
+ Platform platformCost; Cash int64; CashShown bool }`.
+ - `func moneyByMonth(rows []paymentRow, months []string, r eurRates, platform map[string]platformCost) []moneyMonth`
+ — per row, in euros from `Settled`/`SettledTax`/`Fee` and
+ `SettledCurrency`: subscription and once-off rows add `Settled −
+ SettledTax` to their column; refunds and reversals to `Refunds`
+ (signed); `SettledTax` of every row to `Tax`; `Fee` of every row plus
+ `−Settled` of fee rows to `Fees`; `Net = Subscriptions + OnceOff +
+ Refunds − Fees`. `CashShown` only with `Platform.OK`;
+ `Cash = Net − Platform.Cents`. A row whose currency has no rate makes
+ `EURKnown` false.
+ - `type earnedView struct { Month string; MRR, OnceOff, Refunds int64;
+ Platform platformCost; Profit int64; ProfitShown bool }`.
+ - `func earnedSoFar(arrEUR int64, m moneyMonth, now time.Time) earnedView`
+ — `MRR = round(arrEUR / 12 × day-of-month / days-in-month)`;
+ `Profit = MRR + OnceOff + Refunds − Platform.Cents`, shown only with
+ `Platform.OK`.
+ - `type accountMoney struct { Fact billingFact; Group billingGroup;
+ Earns, Costs, Margin int64 /* euro cents, the month */; CostKnown,
+ EURKnown bool; NearUsed, NearLimit int64; NearCap capID }`.
+ - `func accountMoneyRows(facts []billingFact, exemptID int64, monthRows []paymentRow, costUSD map[string]float64, near map[int64]capState, r eurRates) []accountMoney`
+ — per account: `Group` by `billingGroupOf`; `Earns` = (`Annual / 12`
+ in euros when `payingNow` and `Annual > 0`, cancelling accounts
+ included: they paid for this year) plus that month's once-off less
+ refunds, before tax; `Costs` = `costUSD[sqid]` in euros (`CostKnown`
+ false when `costUSD` is nil; an account absent from a non-nil map
+ costs 0); `Margin = Earns − Costs`; `NearCap`, `NearUsed`, `NearLimit`
+ from `near` (zero when absent). `monthRows` is the last complete
+ month's payments, so every per-account figure is that month's.
+- Decision recorded: the earned view subtracts refunds, matching the
+ per-account rule (spec §4.6 per-account says "less refunds").
+
+- [ ] **Step 1: Write the failing tests**
+ - `TestEURText` (0, 2400, 120000, −18800); `TestMinorText`.
+ - `TestMoneyByMonth`: a 2800 usd first payment settled 2610 eur fee 106,
+ a 504-tax eur once-off, a refund, a fee row of −45 in one month →
+ exact columns; an empty month → zeros; `CashShown` false with a
+ platform cost that is not `OK`, true with one that is.
+ - `TestEarnedSoFar`: ARR 2400 on 9 Nov → MRR `round(200 × 9 / 30) = 60`;
+ `TestEarnedHiddenWithoutBasis`.
+ - `TestAccountMoneyRows`: paying eur 2400 with an October once-off 1000
+ and cost 1.10 usd at 1.10 → `Earns 1200`, `Costs 100`, `Margin 1100`;
+ a cancelling paying account still earns its MRR; a free account earns
+ 0; `costUSD` nil → `CostKnown false`; a `near` row fills `NearCap`.
+ - `TestPlatformCostEUR` (bills seeded as Plan 3's tests seed them): a
+ 110 usd bill under `CostScope{AccountCarlosOnly: true}` at usd 1.10 →
+ `OK`, `Cents 10000`, `Label` C2; the zero scope → not `OK`, `Hint` C4;
+ no bill → not `OK`, `Hint` C6; no usd rate → not `OK`, `Hint` "no rate
+ yet".
+- [ ] **Step 2: Run** `go test ./internal/console -run 'TestEURText|TestMinorText|TestMoneyByMonth|TestEarned|TestAccountMoneyRows|TestPlatformCostEUR' -count=1` → FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** the same → PASS.
+- [ ] **Step 5: Commit** `console: billing page money, and the platform cost seam`.
+
+### Task 4: The overview
+
+**Files:**
+- Modify: `internal/console/opbilling.go` (`buildOpBillingView`,
+ `handleOpBilling`)
+- Create: `internal/console/opbilling_store.go`
+- Modify: `internal/console/templates/ops_billing.html`,
+ `internal/console/static/ops.css`
+- Test: `internal/console/opbilling_test.go`, `internal/console/opbilling_store_test.go`
+
+**Interfaces:**
+- Consumes: Task 3; Plan 1 `billingRevenueNow`, `Payments`, `ARRSnapshots`;
+ `LoadEconomics(ctx, "last")` (`Accounts[].Account` sqid, `CostUSD`).
+- Produces:
+ - `func (s *Store) BillingFunnel(now time.Time) (signedUp, withApp, active30 int, err error)`
+ — live accounts; those with a live app; those where a member's
+ `users.last_seen` or a session's `created_at` is within 30 days, or an
+ audit row of `deployActions` for the account is.
+ - `func (s *Store) NearestCaps() (map[int64]capState, error)` — per
+ account, the `plan_cap_state` row with the highest `used / cap_limit`
+ among `cap_limit > 0`.
+ - `type opBillingInput struct { Now time.Time; Rev billingRevenue; Facts
+ []billingFact; ExemptID int64; Rates eurRates; Months []moneyMonth /*
+ 6, newest first */; LastMonth string; LastRows []paymentRow /* last
+ complete month */; Recent []paymentRow /* 5 */; CostUSD
+ map[string]float64; Platform map[string]platformCost; Funnel [3]int;
+ Near map[int64]capState }`
+ - Row types the later tasks reuse: `type opBillingAccountRow struct {
+ Href, Name, Plan, PlanNote string; Apps int; Earns, Costs, Margin,
+ Renews, Joined string; Status opPill }` (`PlanNote` the packs and seats
+ line, or "paying since" on the overview); `type opBillingPaymentRow
+ struct { Href /* "" when not a link */, When, Account, What, Charged,
+ Net, Fee string; Status opPill }`; `type opBillingReasonRow struct {
+ Href, Label string; Count int; Cost, Biggest string }`. Money cells are
+ already formatted (`eurText`, `minorText`, or the approved "unknown" /
+ "no rate yet").
+ - `func buildOpBillingView(in opBillingInput) *opBillingView` (pure) and
+ `opBillingView`'s sections, in the mockup's order (spec §5.2):
+ 1. `Tiles []opStat`: ARR (EUR; delta = now − `MonthStart.EUR`; note =
+ each currency in `ByCurrency`, `minorText`, joined, plus the rate
+ note), MRR (`EUR / 12`), Received this month (`Months[0].Net`),
+ Paying accounts (`Paying of Accounts (pct)`, change vs
+ `MonthStart.Paying`), Needs attention (`Attention`).
+ 2. `Paying []opBillingAccountRow`: the 5 most recent `FirstPaid` among
+ paying accounts, with plan, packs and seats, earns, costs
+ (estimate), margin, renews (`PeriodEnd`), status (Payment failing
+ for `past_due`, Cancels at renewal, else Paid).
+ 3. `Earned earnedView` beside `Funnel` (signed up, made an app, active
+ last 30 days, paying).
+ 4. `Months []moneyMonth`, each linking to
+ `/fleet/billing/payments?month=YYYY-MM`.
+ 5. `Recent`: when, account, what (reason word, plan label for
+ subscription rows, detail for domain rows), amount (`minorText`),
+ status.
+ 6. `Weeks []dashBar`: `dashBars` over 12 `DayCount`s, one per week
+ ending today, counting `FirstPaid`.
+ 7. `Reasons []opBillingReasonRow`: Free, Sponsored, House, Ours with
+ count, cost to run (last month, estimate) and the costliest account;
+ then Shared and idle (`Platform[LastMonth] − Σ all accounts' costs`)
+ only with `Platform[LastMonth].OK`. Rows link to `/fleet/billing/accounts?tab=<group>`.
+ 8. `NearLimits`: Free accounts in `Near`, highest ratio first, 5, with
+ the cap's label (`billingCopy["usage.label.*"]` as
+ `billingusage.go:193` maps them) and `capAmount` for used and limit.
+ - `handleOpBilling` gathers the inputs (`LoadEconomics` failure → logged,
+ `CostUSD` nil, costs show "unknown"); renders `ops_billing`.
+ - `static/ops.css`: `[co-rowlink]` rows are `position: relative` with a
+ hover tint, and their first `a.rst-nm::after` covers the row
+ (`position: absolute; inset: 0`), so the whole row opens the link and
+ the link stays the one focus stop. Column sets `co-cols="billpaying"`,
+ `"billmonths"`, `"billpayments"`, `"billreasons"`, `"billlimits"`, with
+ the narrow-screen hiding rules the other `co-cols` have.
+
+- [ ] **Step 1: Write the failing tests**
+ - `TestBuildOpBillingView`: one eur paying account (2400, first paid 7
+ Nov), 37 others across groups, a rate, a CARLOS-only bill (account scope) → tile values
+ and notes as approved, `Paying` one row with status Paid, `Weeks` with
+ 1 in the last bar, `Reasons` four rows plus Shared and idle.
+ - `TestOverviewHidesCostWithoutBasis`: a whole-account bill under the zero scope → no AWS bill line,
+ no profit, no cash column values, no Shared and idle, Plan 3's C4
+ hint present.
+ - `TestOverviewNoRate`: no rates → converted tiles show "no rate yet";
+ the per-currency note is present.
+ - `TestOverviewEmpty`: no payments, no paying accounts, no Economics →
+ empty states, `0 of N (0%)`, six €0.00 months.
+ - `TestOverviewCapsAtFive`: seven paying accounts → five rows, newest
+ first, and the "All paying accounts" link.
+ - `TestOverviewRowsAreLinks`: rendered HTML: each list row has
+ `co-rowlink` and a first `a.rst-nm` with the documented href.
+ - `TestBillingFunnel`, `TestNearestCaps` (store).
+- [ ] **Step 2: Run** `go test ./internal/console -run 'TestBuildOpBillingView|TestOverview|TestBillingFunnel|TestNearestCaps' -count=1` → FAIL.
+- [ ] **Step 3: Implement.** Check the page at 390 px and at desktop width.
+- [ ] **Step 4: Run** the same plus `-run 'TestBillingRoutes'` → PASS.
+- [ ] **Step 5: Commit** `console: the billing overview`.
+
+### Task 5: The accounts list
+
+**Files:**
+- Modify: `internal/console/opbilling.go` (`buildOpBillingAccounts`,
+ `handleOpBillingAccounts`), `templates/ops_billing_accounts.html`,
+ `static/ops.css` (`co-cols="billaccounts"`)
+- Test: `internal/console/opbilling_test.go`
+
+**Interfaces:**
+- Consumes: Task 3 `accountMoneyRows`, Task 4 `NearestCaps`.
+- Produces:
+ - Query `tab` (a `billingGroup`, default `paying`), `sort` (`earns`,
+ `costs`, `margin`, `joined`, `limit`; default `costs`), `page` (1-based).
+ - `type opBillingAccountsView struct { Tabs opTabs /* billingGroupOrder,
+ each label with its count */; Sort opTabs; Rows []opBillingAccountRow;
+ Prev, Next string; TestMode bool; RateNote string; MonthName string }`
+ - `func buildOpBillingAccounts(rows []accountMoney, group billingGroup, sort string, page int, q url.Values) opBillingAccountsView`
+ — 50 per page; sorts descending except `joined` (newest first) and
+ `limit` (highest ratio first, accounts with no cap row last); ties by
+ account id. Columns: account, plan, apps, earns, costs (estimate),
+ margin, joined. An unknown `tab` or `sort` falls back to the default.
+
+- [ ] **Step 1: Write the failing tests**: `TestBillingAccountsTabsAndCounts`,
+ `TestBillingAccountsSorts` (each sort key, ties stable),
+ `TestBillingAccountsPages` (120 free accounts → 50, 50, 20; Prev/Next
+ keep `tab` and `sort`), `TestBillingAccountsBadQuery` (defaults).
+- [ ] **Step 2: Run** `go test ./internal/console -run 'TestBillingAccounts' -count=1` → FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** the same → PASS.
+- [ ] **Step 5: Commit** `console: the billing accounts list`.
+
+### Task 6: The payments list
+
+**Files:**
+- Modify: `internal/console/opbilling.go` (`buildOpBillingPayments`,
+ `handleOpBillingPayments`), `templates/ops_billing_payments.html`
+- Test: `internal/console/opbilling_test.go`
+
+**Interfaces:**
+- Consumes: Plan 1 `Store.Payments(paymentFilter)`; Task 3 text helpers.
+- Produces:
+ - Query `month` (`YYYY-MM`, empty: all), `kind` (`subscription`,
+ `once_off`, `refund`, `unmatched`; empty: every kind but fees), `page`.
+ A malformed `month` or unknown `kind` is ignored (all), never a 400:
+ this is a page, not a door.
+ - `type opBillingPaymentsView struct { Month, Kind string; Kinds opTabs;
+ Rows []opBillingPaymentRow; Prev, Next string; Total int; TestMode
+ bool; RateNote string }`; a row: when, account (link unless unmatched or
+ deleted), what, charged (`minorText(Amount, Currency)`), net in euros
+ (`Settled − SettledTax − Fee`), fee, status.
+ - 50 per page, newest first.
+
+- [ ] **Step 1: Write the failing tests**: `TestBillingPaymentsFilters`
+ (month, each kind, both), `TestBillingPaymentsPages`,
+ `TestPaymentsUnmatchedAndDeleted`, `TestBillingPaymentsBadQuery`.
+- [ ] **Step 2: Run** `go test ./internal/console -run 'TestBillingPayments|TestPaymentsUnmatched' -count=1` → FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** the same → PASS.
+- [ ] **Step 5: Commit** `console: the billing payments list`.
+
+### Task 7: The Dashboard tile
+
+**Files:**
+- Modify: `internal/console/opparts.go` (`opStat.Href`),
+ `internal/console/templates/opparts.html` (`op_stat`: an `<a rst-stat
+ ...>` when `Href` is set), `internal/console/opdashboard.go`
+ (`handleDashboard`)
+- Test: `internal/console/opdashboard_test.go`
+
+**Interfaces:**
+- Consumes: Plan 1 `billingRevenueNow`.
+- Produces: `func billingDashStat(rev billingRevenue) opStat` — label
+ Paying accounts, value the paying count, note the ARR in euros `a year`
+ (or "no rate yet"), the test-mode word when `TestMode`, `Href:
+ "/fleet/billing"`. `handleDashboard` appends it to `d.Stats` only when
+ `s.billing != nil`; a `billingRevenueNow` error is logged and the tile
+ left out.
+
+- [ ] **Step 1: Write the failing tests**: `TestDashboardTileOnlyWithBilling`
+ (off → five stats, no `/fleet/billing` link; on → six, the last links
+ to Billing with the approved note), `TestOpStatLinks` (an `opStat` with
+ `Href` renders as one link; without, unchanged markup).
+- [ ] **Step 2: Run** `go test ./internal/console -run 'TestDashboardTile|TestOpStat|TestDashboard' -count=1` → FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** the same → PASS.
+- [ ] **Step 5: Commit** `console: paying accounts tile on the dashboard`.
+
+---
+
+## After the plan
+
+- Done means (spec §7, the parts this plan owns): on flagship the Billing
+ rail item and tile appear and the first customer shows as paying with
+ the right ARR and their payment's fee and euros; on dev the same, marked
+ test mode; on a console without `CARLOS_BILLING`, no rail item, no tile,
+ and the routes answer 404. The platform cost and both profit views show
+ on a console whose bill is CARLOS-only (Carloku, once Plan 3's
+ `CONSOLE_COST_ACCOUNT_CARLOS_ONLY` is on), with the basis line; anywhere
+ else Plan 3's hint shows in their place.