| 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. |