plan: billing dashboard 1-2, Astra round 3 fixes
One gate with per-figure inputs: subscription facts current (a new per-account facts_read_at, set only by a saved fresh read), payment reconcile current, rates current (costs included: usd), amounts known, Economics complete, platform cost OK. Each figure declares exactly the inputs it uses; a recorded eur charge needs only the reconcile; ARR points use their stored day's completeness. Every builder takes the gate inputs explicitly. Economics counts real read failures in sweepUsage. No carry-forward over missing snapshot days. One table-driven gate invariant test per page and door (checkGateInvariant), a source test keeping money formatting inside opMoney, and a Known limitations section (past-month margins first in January 2027).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+390
−250
docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md+152 −73docs/superpowers/plans/2026-11-09-billing-dashboard-2-pages.md+238 −177
CI passed — run details
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| index 677b04046..ed53f6716 100644 |
| --- a/docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md |
| +++ b/docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md |
| @@ -48,18 +48,22 @@ and §5; Plan 3 (written separately) covers §4.5. |
| reversals all carry their tax share (`Tax`, `SettledTax`), so revenue |
| before tax is `Settled − SettledTax` for every kind: a fully refunded |
| €120 charge with €20 tax nets 0 before fees. |
| -- **Refuse up front: one money gate.** Every money figure (the revenue |
| - door and CLI here; every page figure in Plan 2) passes `moneyReady` |
| - (Task 7) before it is computed for display. The gate checks, in order: |
| - the payment reconcile succeeded within `billingReconcileMaxAge`; the |
| - rates were fetched within `billingRatesMaxAge` and cover every currency |
| - the figure converts; no paying account's yearly amount is unknown; and, |
| - for cost figures, the Economics read is complete and the platform cost |
| - is `OK`. When it says no, the figure is replaced by the approved "not |
| - available yet" text with the reason, never by a partial number. A |
| - snapshot day stored while the gate said no is stored as incomplete, and |
| - every consumer treats it as unknown. No other completeness flag is |
| - carried through totals. |
| +- **Refuse up front: one money gate, per-figure inputs.** Every money |
| + figure (the revenue door and CLI here; every page figure in Plan 2) |
| + declares exactly the inputs it uses and passes `moneyReady` (Task 7) |
| + before it is computed for display. The inputs: subscription facts |
| + current (every paying account's last fresh subscription read within |
| + `billingFactsMaxAge`), payment reconcile current, rates current (any |
| + converted figure, costs included), every yearly amount known, Economics |
| + complete, platform cost `OK`. A figure is refused iff an input it |
| + declares is incomplete; it then reads "not available yet" with the |
| + reason, never a partial number. A recorded EUR charge needs only the |
| + reconcile. A stored snapshot day carries its own completeness, decided |
| + when it was written; historical figures read that, not today's gate. A |
| + missing or incomplete day is unknown to every consumer. One |
| + table-driven invariant test per page and per door checks, for every |
| + figure and every input, that flipping the input refuses the figure iff |
| + the figure declares it. |
| - **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 |
| @@ -158,9 +162,16 @@ and §5; Plan 3 (written separately) covers §4.5. |
| - `billing.Subscription` gains `Annual int64` (what the next year will |
| charge, after discounts, before tax, minor units of `Currency`), |
| `AnnualKnown bool` (false: the adapter could not tell; `Annual` is 0) |
| - and `AnnualRead bool` (true only on `Provider.Subscription` reads; a |
| - write's answer leaves it false, and the sync then keeps the stored |
| - amount). |
| + and `FreshRead bool` (true only on `Provider.Subscription` reads; a |
| + write's answer and the sync's synthesised "ended" read leave it false, |
| + and the sync then keeps the stored amount). |
| + - Column `billing_accounts.facts_read_at INTEGER NOT NULL DEFAULT 0`; |
| + `billingAccount.FactsReadAt time.Time`. `applyBillingRead` |
| + (`billingsync.go:355`) sets `d.Next.FactsReadAt = now` when `d.Save && |
| + sub.FreshRead`. It is the per-account record of a successful |
| + subscription read: a failed read (`billingpass.go:131` logs and |
| + continues), a read whose decision opens a problem instead of saving, |
| + and a write's answer all leave it where it was. |
| - `Provider.Subscription` reads each discount's coupon with the existing |
| `Client.GetCoupon` (which expands `applies_to`, `catalog.go:290`; |
| Stripe omits it otherwise) and uses that coupon in `annualOf`. A |
| @@ -200,17 +211,22 @@ and §5; Plan 3 (written separately) covers §4.5. |
| `Provider.Subscription`): a usd 2800 subscription with one forever |
| discount on coupon `half`; `/v1/coupons/half` is asked with |
| `expand[]=applies_to`. The coupon answering 50% with no `applies_to` |
| - → `Annual 1400, AnnualKnown, AnnualRead`; answering with |
| + → `Annual 1400, AnnualKnown, FreshRead`; answering with |
| `applies_to.products ["prod_x"]` → `AnnualKnown false`; answering 500 |
| → `AnnualKnown false` and the subscription's other fields still |
| mapped. |
| - `TestBillingAccountAnnualRoundTrip`: a fresh row reads `Annual == -1`; |
| `PutBillingState` with 2400 reads back 2400. |
| - - `TestDecideBillingStoresAnnual`: a read (`AnnualRead`) with |
| + - `TestDecideBillingStoresAnnual`: a read (`FreshRead`) with |
| `AnnualKnown` 2400 → `Next.Annual == 2400`; a read with `AnnualKnown |
| - false` → -1; a write's answer (`AnnualRead false`) keeps the stored |
| + false` → -1; a write's answer (`FreshRead false`) keeps the stored |
| value. |
| -- [ ] **Step 2: Run** `go test ./internal/billingstripe ./internal/console -run 'TestAnnualOf|TestSubscriptionDecodesDiscounts|TestSubscriptionAnnualReadsCoupons|TestBillingAccountAnnualRoundTrip|TestDecideBillingStoresAnnual' -count=1` → FAIL (undefined). |
| + - `TestFactsReadAt` (on `newBillingFixture`): a successful sync sets |
| + `FactsReadAt` to now; a later sync whose `Provider.Subscription` fails |
| + (fake `SubErr`) leaves it; a sync opening an account-mismatch problem |
| + leaves it; an operation's write answer applied through |
| + `applyBillingRead` leaves it. |
| +- [ ] **Step 2: Run** `go test ./internal/billingstripe ./internal/console -run 'TestAnnualOf|TestSubscriptionDecodesDiscounts|TestSubscriptionAnnualReadsCoupons|TestBillingAccountAnnualRoundTrip|TestDecideBillingStoresAnnual|TestFactsReadAt' -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 |
| @@ -220,7 +236,7 @@ and §5; Plan 3 (written separately) covers §4.5. |
| unknown; `AppliesToProducts` non-empty is unknown; floor at 0. |
| `Provider.Subscription` replaces each discount's coupon with its |
| `GetCoupon` read, then `subscriptionOf` sets the fields (it stays pure; |
| - write answers mapped through it set no `AnnualRead`). Add the ALTER to the 6b list, the |
| + write answers mapped through it set no `FreshRead`). 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. |
| @@ -640,7 +656,8 @@ and §5; Plan 3 (written separately) covers §4.5. |
| 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 |
| + int64 /* -1 unknown */; FactsReadAt time.Time; 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 |
| @@ -664,45 +681,88 @@ and §5; Plan 3 (written separately) covers §4.5. |
| - **The money gate** (`internal/console/billingmoney.go`), the one place |
| completeness is decided: |
| ```go |
| + // moneyInput is one input a money figure may use. |
| + type moneyInput uint8 |
| + const ( |
| + inFacts moneyInput = 1 << iota // every paying account's subscription read is current |
| + inPayments // the payment reconcile is current |
| + inRates // the rates are current and cover the figure's currencies |
| + inAmounts // no paying account's yearly amount is unknown |
| + inEconomics // the Economics read is complete |
| + inPlatform // the figure's month has a CARLOS-only platform cost |
| + ) |
| + var moneyInputOrder = []moneyInput{inFacts, inPayments, inRates, inAmounts, inEconomics, inPlatform} |
| + |
| + // moneyUse is what one figure declares: the inputs it uses, the |
| + // currencies it converts (for inRates) and its month (for inPlatform). |
| + type moneyUse struct { |
| + Inputs moneyInput |
| + Currencies []string |
| + Month string |
| + } |
| + |
| type moneyInputs struct { |
| Now time.Time |
| - Rates eurRates // LatestEURRates, with FetchedAt |
| - Currencies []string // every currency the figures convert |
| - Unknown int // arrTotals.Unknown |
| - Reconciled time.Time // PaymentsReconciledAt |
| - EconomicsComplete bool // Plan 2 fills; false here |
| - PlatformOK bool // Plan 2 fills, per month; false here |
| + Rates eurRates // LatestEURRates, with FetchedAt |
| + StaleFacts int // paying, non-exempt accounts whose FactsReadAt is older than billingFactsMaxAge |
| + Unknown int // arrTotals.Unknown |
| + Reconciled time.Time // PaymentsReconciledAt |
| + EconomicsComplete bool // Plan 2 fills; false here |
| + PlatformOK map[string]bool // Plan 2 fills, by month; nil here |
| } |
| - type moneyNeed uint8 |
| - const ( |
| - needRevenue moneyNeed = 1 << iota // payments, rates, amounts |
| - needEconomics // the Economics read |
| - needPlatform // the month's platform cost |
| - ) |
| const ( |
| + billingFactsMaxAge = 2 * time.Hour |
| billingReconcileMaxAge = 2 * time.Hour |
| billingRatesMaxAge = 26 * time.Hour |
| ) |
| - // Reasons, in check order; each has an approved text (Task 8 here, |
| - // Plan 2's record on the pages). |
| + // Reasons, one per input, in moneyInputOrder; each has an approved |
| + // text (Task 8 here, Plan 2's record on the pages). |
| const ( |
| + moneyWhyFacts = "facts" |
| moneyWhyPayments = "payments" |
| moneyWhyRates = "rates" |
| moneyWhyAmounts = "amounts" |
| moneyWhyEconomics = "economics" |
| moneyWhyPlatform = "platform" |
| ) |
| - func moneyReady(in moneyInputs, need moneyNeed) (ok bool, why string) |
| + // moneyReady checks only the inputs u declares, in moneyInputOrder; |
| + // the first incomplete one is the reason. |
| + func moneyReady(in moneyInputs, u moneyUse) (ok bool, why string) |
| + |
| + // moneyFigure is one figure as the gate saw it: what the invariant |
| + // tests enumerate. Plan 2's opMoneyFigure embeds it. |
| + type moneyFigure struct { |
| + Name string |
| + Use moneyUse |
| + Shown bool |
| + Why string |
| + } |
| ``` |
| - `needRevenue`: `Reconciled` zero or older than |
| - `billingReconcileMaxAge` → payments; `Rates.FetchedAt` zero or older |
| - than `billingRatesMaxAge`, or a non-eur currency in `Currencies` with |
| - no rate → rates (a fetch every 20 h keeps it current through weekends, |
| - when the ECB's newest day is Friday's); `Unknown > 0` → amounts. |
| - `needEconomics`: `!EconomicsComplete` → economics. `needPlatform`: |
| - `!PlatformOK` → platform. The first failing check wins. |
| - - `func (s *Server) moneyInputsFor(now time.Time, arr arrTotals, currencies []string) (moneyInputs, error)` |
| - — reads the rates and the reconciled time; the cost fields stay false. |
| + Completeness per input: `inFacts` — `StaleFacts == 0`; `inPayments` — |
| + `Reconciled` set and within `billingReconcileMaxAge`; `inRates` — |
| + `Rates.FetchedAt` set and within `billingRatesMaxAge`, and every |
| + non-eur currency in `u.Currencies` has a rate (a fetch every 20 h keeps |
| + it current through weekends, when the ECB's newest day is Friday's); |
| + `inAmounts` — `Unknown == 0`; `inEconomics` — `EconomicsComplete`; |
| + `inPlatform` — `PlatformOK[u.Month]`. A figure declares `inRates` |
| + exactly when it converts a non-eur currency; an all-eur figure does |
| + not. |
| + - `func ratesUse(currencies ...string) moneyInput` — `inRates` when any |
| + currency is not `eur`, else 0 (the one way figures decide it). |
| + - `func (s *Server) moneyInputsFor(now time.Time, facts []billingFact, arr arrTotals) (moneyInputs, error)` |
| + — reads the rates and the reconciled time and counts `StaleFacts`; |
| + the cost fields stay unset. |
| + - Test helper (`internal/console/billingmoney_test.go`, shared with |
| + Plan 2): `func checkGateInvariant(t *testing.T, good moneyInputs, |
| + build func(in moneyInputs) []moneyFigure)`. It builds once with `good` |
| + (every figure must be `Shown`), then once per input in |
| + `moneyInputOrder` with only that input made incomplete (`StaleFacts |
| + 1`; `Reconciled` 3 h old; `Rates.FetchedAt` 27 h old; `Unknown 1`; |
| + `EconomicsComplete false`; `PlatformOK` all false), plus once with the |
| + usd rate removed. For every figure of the baseline, by `Name`, it |
| + asserts `Shown` is false iff the figure declares the flipped input |
| + (for the usd case: declares `inRates` and lists `usd`), and that a |
| + refused figure's `Why` is that input's reason. |
| - Table `billing_arr_daily (day TEXT PRIMARY KEY, arr TEXT NOT NULL /* |
| JSON currency → minor */, arr_eur INTEGER NOT NULL, rate_day TEXT NOT |
| NULL, paying INTEGER NOT NULL, complete INTEGER NOT NULL, why TEXT NOT |
| @@ -728,14 +788,16 @@ and §5; Plan 3 (written separately) covers §4.5. |
| - `func (s *Store) FirstSnapshotDay() (string, error)` (`""` when none) |
| - `func (s *Server) billingSnapshotPass(ctx context.Context, now time.Time) error` |
| — builds today's (UTC) snapshot from `arrOf` and the same facts and |
| - rates, with `Complete, Why = moneyReady(inputs, needRevenue)`, and |
| + rates, with `Complete, Why = moneyReady(inputs, moneyUse{Inputs: |
| + inFacts|inPayments|inAmounts|ratesUse(ARR currencies...), Currencies: |
| + ARR currencies})` (the inputs the ARR and the account rows use), and |
| writes it with `PutDailySnapshot`. Every hourly pass rewrites today; |
| the last pass of the day is what stays. No earlier day is ever |
| written, so history starts at the first pass. |
| - `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; Inputs |
| - moneyInputs /* currencies: ByCurrency's */ }` |
| + moneyInputs }` |
| - `func (s *Server) billingRevenueNow(now time.Time) (billingRevenue, []billingFact, error)` |
| — `BillingFacts`, `LatestEURRates`, `arrOf`, the group counts, |
| `MonthStart` and `moneyInputsFor`; `TestMode` is |
| @@ -754,15 +816,20 @@ and §5; Plan 3 (written separately) covers §4.5. |
| {eur:2400, usd:2800}`, `EUR 4900`; a cancelling account adds nothing to |
| ARR and 1 to `Attention`; a past_due one adds to both. |
| - `TestARROfUnknownAmount`: an active, paid subscription with `Annual |
| - -1` beside a known eur 2400 → `Paying 2`, `Unknown 1`; `moneyReady(…, |
| - needRevenue)` → `false, "amounts"`. |
| - - `TestMoneyReady` (table): all inputs good → true for every need; then |
| - one input broken at a time (reconciled 3 h ago; never reconciled; |
| - rates fetched 27 h ago; gbp in `Currencies` with no gbp rate; `Unknown |
| - 1`; `EconomicsComplete false`; `PlatformOK false`) → false with its |
| - reason for every need that includes it, true for needs that do not |
| - (economics broken, `needRevenue` alone → true); two broken at once → |
| - the first in check order. |
| + -1` beside a known eur 2400 → `Paying 2`, `Unknown 1`. |
| + - `TestMoneyReady` (table, every `moneyUse` shape): each input broken |
| + alone refuses exactly the uses that declare it, with its reason; |
| + never reconciled and never fetched count as broken; gbp declared with |
| + no gbp rate → rates; an eur-only use is not refused by stale rates; |
| + `inPlatform` reads the use's month; two broken at once → the first in |
| + `moneyInputOrder`. |
| + - `TestMoneyInputsFor`: two paying accounts, one with `FactsReadAt` 3 h |
| + old → `StaleFacts 1`; a non-paying account read long ago → not |
| + counted; the exempt account → not counted. |
| + - `TestCheckGateInvariantCatchesOverDeclared` (the helper tested): a |
| + build that refuses a figure on an input it does not declare, and one |
| + that shows a figure despite a declared broken input, both fail the |
| + helper (run through a fake `testing.TB` recorder). |
| - `TestBillingFactsQuery`: an account per group, a deleted account |
| (absent), apps counted, `FirstPaid` the earliest subscription payment. |
| - `TestSnapshotTodayReplaceable`: a pass while the reconcile is stale, |
| @@ -778,8 +845,11 @@ and §5; Plan 3 (written separately) covers §4.5. |
| on day D, fails at 22:00, 23:00 and 00:30 on D+1, succeeds at 02:00. |
| D's last write (23:00) is `complete 0, why "payments"` and stays so |
| after recovery; D+1 reads `complete 0` after 00:30 and `complete 1` |
| - after 02:00; `moneyReady` for now is true again after 02:00. |
| -- [ ] **Step 2: Run** `go test ./internal/console -run 'TestPayingNow|TestBillingGroupOf|TestARROf|TestMoneyReady|TestBillingFactsQuery|TestSnapshot' -count=1` → FAIL.- [ ] **Step 2: Run** `go test ./internal/console -run 'TestPayingNow|TestBillingGroupOf|TestARROf|TestBillingFactsQuery|TestSnapshot' -count=1` → FAIL. |
| + after 02:00. |
| + - `TestSnapshotStaleFacts`: payments reconcile fine but the subscription |
| + reads fail for 3 h → the snapshot is `complete 0, why "facts"`; the |
| + two provider calls fail independently, each giving its own reason. |
| +- [ ] **Step 2: Run** `go test ./internal/console -run 'TestPayingNow|TestBillingGroupOf|TestARROf|TestMoneyReady|TestMoneyInputsFor|TestCheckGateInvariant|TestBillingFactsQuery|TestSnapshot' -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`. |
| @@ -796,7 +866,8 @@ and §5; Plan 3 (written separately) covers §4.5. |
| 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); the "not available yet" |
| - line and one reason per `moneyWhy*` code (payments, rates, amounts); the |
| + line and one reason per `moneyWhy*` code the door can give (facts, |
| + payments, rates, amounts); 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). |
| @@ -835,15 +906,21 @@ and §5; Plan 3 (written separately) covers §4.5. |
| **Interfaces:** |
| - Consumes: Task 4 `Payments`, Task 7 `billingRevenueNow`, Task 8 copy. |
| - Produces: |
| - - `GET /api/cli/billing/revenue` (`billingDoor`), through |
| - `moneyReady(rev.Inputs, needRevenue)`. Ready: `{"available":true, |
| - "arr":{"eur":2400},"arr_eur":2400,"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. Not ready: `{"available":false, |
| - "why":"payments","groups":{...},"accounts":38,"test_mode":false}`, no |
| - money field and no paying count. The CLI prints the approved "not |
| - available yet" line with the reason's text. |
| + - `func revenueFigures(rev billingRevenue, in moneyInputs) ([]moneyFigure, revenueReply)` |
| + — pure; each field of the reply is a figure through `moneyReady`: |
| + `arr` (`by_currency`, `eur`, `rate_day`) and `mrr` declare |
| + `inFacts|inPayments|inAmounts|ratesUse(ARR currencies)`; `paying`, |
| + `attention` and `groups` declare `inFacts|inPayments`; `accounts` |
| + declares nothing. |
| + - `GET /api/cli/billing/revenue` (`billingDoor`): `{"arr":{"available": |
| + true,"by_currency":{"eur":2400},"eur":2400,"rate_day":"2026-11-06"}, |
| + "mrr":{"available":true,"eur":200},"paying":{"available":true, |
| + "count":1},"attention":{...},"groups":{"available":true, |
| + "counts":{...}},"accounts":38,"test_mode":false}`; amounts in minor |
| + units; `mrr.eur` is `arr.eur / 12` rounded. A refused figure is |
| + `{"available":false,"why":"<code>"}` with no number. The CLI prints |
| + each refused line as the approved "not available yet" text with the |
| + reason's text. |
| - `GET /api/cli/billing/payments?month=YYYY-MM&kind=K` (`billingDoor`; |
| `kind` as `paymentFilter.Kind`, limit 500): an array of `{"movement", |
| "source","at","account","kind","reason","detail","amount","tax","currency","settled", |
| @@ -858,11 +935,13 @@ and §5; Plan 3 (written separately) covers §4.5. |
| `claimBillingWorld`. |
| - [ ] **Step 1: Write the failing tests** |
| - - `TestAPIBillingRevenue`: billing world with one paying eur account and |
| - a stored rate and a fresh reconcile → the JSON above; a second paying |
| - account with an unknown amount → `available false`, `why "amounts"`, no |
| - `arr`; a stale reconcile → `why "payments"`; a member (not operator) → 404; billing |
| - off → 409 like `problems`. |
| + - `TestRevenueFiguresGateInvariant`: `checkGateInvariant` over |
| + `revenueFigures` with a usd and an eur paying account. |
| + - `TestAPIBillingRevenue` (handler to store): one paying eur account, |
| + a stored rate, fresh reads → the JSON above; a second paying account |
| + with an unknown amount → `arr` and `mrr` `{"available":false, |
| + "why":"amounts"}` while `paying` is still shown; 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 |
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| index 74f5cdf8a..d98168776 100644 |
| --- a/docs/superpowers/plans/2026-11-09-billing-dashboard-2-pages.md |
| +++ b/docs/superpowers/plans/2026-11-09-billing-dashboard-2-pages.md |
| @@ -53,15 +53,20 @@ B (tag mode, the untagged inventory, copy C5), which is deferred. |
| refunded charge nets 0 before fees. Tax collected (net of refunded tax) |
| is its own column of the money table and never counted as revenue or |
| profit. |
| -- **One money gate, refused up front.** Every money figure on every page |
| - (tiles, ARR chart points, the money table, both profit views, the |
| - recent payments' amounts, per-account earns, costs and margins, the |
| - reasons table, the Dashboard tile) is built through `opMoney` (Task 3), |
| - which asks Plan 1's `moneyReady` with the figure's needs. When it says |
| - no, the figure is the approved "not available yet" text with the |
| - reason, never a partial number. A snapshot day stored incomplete is |
| - unknown to every consumer (no ARR point, no delta, no month of |
| - earnings). No figure carries its own completeness flag. |
| +- **One money gate, per-figure inputs, refused up front.** Every money |
| + figure on every page (tiles, ARR chart points, the money table, both |
| + profit views, recent payments' amounts, per-account earns, costs and |
| + margins, the reasons table, the payments list, the Dashboard tile) is |
| + built through `opMoney` (Task 3), declaring exactly the inputs it uses |
| + (Plan 1's `moneyInput`s); `moneyReady` refuses it iff a declared input is |
| + incomplete, and it then reads "not available yet" with the reason, |
| + never a partial number. Every builder takes the gate inputs |
| + (`moneyInputs`) as an explicit argument. Historical figures (ARR |
| + points, past-month earnings) use the stored day's completeness, not |
| + today's gate; a missing or incomplete day is unknown. `eurText` and |
| + `minorText` are called only inside `opMoney`'s format functions |
| + (`TestMoneyFormattersOnlyInsideOpMoney`). One table-driven invariant |
| + test per page (Plan 1's `checkGateInvariant`) proves the declarations. |
| - **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, |
| @@ -97,11 +102,15 @@ B (tag mode, the untagged inventory, copy C5), which is deferred. |
| `billingRevenueNow(now) (billingRevenue, []billingFact, error)`; |
| `billingRevenue{arrTotals; Groups; Accounts; MonthStart; TestMode; |
| Inputs}`; `arrTotals{ByCurrency; EUR; RateDay; Paying; Attention; |
| -Unknown}`; the gate `moneyInputs`, `moneyNeed` (`needRevenue`, |
| -`needEconomics`, `needPlatform`), `moneyReady(in, need) (ok bool, why |
| -string)` and the `moneyWhy*` reasons; `arrSnapshot{Day; ARR; EUR; RateDay; |
| -Paying; Complete; Why}`; `accountDay{Day; AccountID; Annual; Currency; |
| -AnnualEUR; Paying; InARR}`; `Store.ARRSnapshots`, `Store.AccountDays`, |
| +Unknown}`; the gate: `moneyInput` (`inFacts`, `inPayments`, `inRates`, |
| +`inAmounts`, `inEconomics`, `inPlatform`), `moneyUse{Inputs; Currencies; |
| +Month}`, `moneyInputs{Now; Rates; StaleFacts; Unknown; Reconciled; |
| +EconomicsComplete; PlatformOK}`, `moneyReady(in, u) (ok bool, why |
| +string)`, `ratesUse(currencies...)`, the `moneyWhy*` reasons, |
| +`moneyFigure{Name; Use; Shown; Why}` and the test helper |
| +`checkGateInvariant`; `arrSnapshot{Day; ARR; EUR; RateDay; Paying; |
| +Complete; Why}`; `accountDay{Day; AccountID; Annual; Currency; AnnualEUR; |
| +Paying; InARR}`; `Store.ARRSnapshots`, `Store.AccountDays`, |
| `Store.FirstSnapshotDay`; `billingFact` (fields as Plan 1 Task 7); |
| `payingNow`, `billingGroupOf`, `inARR`, `billingGroup` and |
| `billingGroupOrder`; `Store.Payments(paymentFilter)` with `Kind ""` (the |
| @@ -152,11 +161,11 @@ approved copy (C1-C4, C7); Plan 2's record does not repeat them. |
| 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. **Any one money input incomplete** (reconcile stale, rates stale or |
| - missing a currency, an unknown yearly amount, a degraded Economics |
| - read, no CARLOS-only platform cost): every figure that needs it, and |
| - only those, shows "not available yet" with the reason (Task 4 |
| - `TestOverviewMoneyGuard`, table-driven over the inputs). |
| +2. **Any one money input incomplete** (stale subscription reads, stale |
| + reconcile, stale or missing rates (usd for costs), an unknown yearly |
| + amount, a failed Economics read, no CARLOS-only platform cost): every |
| + figure that declares it, and only those, shows "not available yet" |
| + with the reason (Tasks 4-7 `Test*GateInvariant`). |
| 3. **A reconcile failure across midnight, then recovery.** The failed day |
| stays unknown (no chart point; its month's earnings unknown); today's |
| figures come back once the reconcile succeeds (Task 4 |
| @@ -166,7 +175,7 @@ approved copy (C1-C4, C7); Plan 2's record does not repeat them. |
| and the six month rows show €0.00 (Task 4 `TestOverviewEmpty`). |
| 5. **Earnings for a month before the history.** October, when the first |
| snapshot is 9 November, shows per-account earnings and margins as not |
| - available, never as today's MRR (Task 3 `TestAccountEarningsBeforeHistory`). |
| + available, never as today's MRR (Task 3 `TestAccountEarningsNotCovered`). |
| 6. **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 |
| @@ -187,9 +196,11 @@ reviewer's): |
| Payments page titles. |
| - Test-mode line; rate note (`at ECB rates of %s`); estimate label; the |
| "not available yet" text and one reason per `moneyWhy*` code except |
| - platform (payments, rates, amounts, economics; platform's reason is |
| - Plan 3's hint); the history reason (`no complete daily record for %s`) |
| - for earnings of a month that is not covered. The basis lines and the |
| + platform (facts, payments, rates, amounts, economics; platform's reason |
| + is Plan 3's hint); the history reason (`no complete daily record for %s`) |
| + for earnings of a month that is not covered; the line that says |
| + past-month margins start once a whole month is recorded (Known |
| + limitations). The basis lines and the |
| hidden-cost hints are Plan 3's C1-C4 and C7, 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 |
| @@ -299,47 +310,55 @@ Every later task takes its strings from this record through |
| - [ ] **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) |
| +### Task 3: Money for the pages, and complete Economics reads |
| **Files:** |
| - Create: `internal/console/opbilling_money.go` |
| -- Test: `internal/console/opbilling_money_test.go` |
| +- Modify: `internal/console/economicspass.go` (`usageSweep` ~322, |
| + `sweepUsage` ~377: count read failures), `internal/console/economicsview.go` |
| + (`EconomicsView.ReadFailures`, set in `buildEconomicsView` from the sweep) |
| +- Test: `internal/console/opbilling_money_test.go`, |
| + `internal/console/economicspass_test.go` |
| **Interfaces:** |
| - Consumes: Plan 1 `paymentRow`, `billingFact`, `eurRates`, `payingNow`, |
| - `billingGroupOf`, `arrTotals`, `arrSnapshot`, `accountDay`, |
| - `moneyInputs`, `moneyReady`; Plan 3 `carlosPlatformCostUSD`, |
| - `costBasisLabel`, `costBasisHint`, `s.cfg.CostScope`; `EconomicsView`. |
| + `billingGroupOf`, `arrTotals`, `arrSnapshot`, `accountDay`, the gate; |
| + Plan 3 `carlosPlatformCostUSD`, `costBasisLabel`, `costBasisHint`, |
| + `s.cfg.CostScope`; `EconomicsView`. |
| - 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 rates reason; not `ok` → not `OK`, `Hint` from |
| - `costBasisHint`. |
| + - `usageSweep.ReadFailures int`: in `sweepUsage`, a metrics or edge day |
| + `Get` that fails with anything but `os.ErrNotExist`, and a day object |
| + that does not parse, each add 1 (today a failed metrics read is |
| + skipped as if absent, so a day with a good edge object still counts |
| + as covered). `EconomicsView.ReadFailures` carries it. Absent objects |
| + stay absent, as now. |
| - `func econComplete(v *EconomicsView, err error) bool` — `err == nil`, |
| - `v != nil`, `v.Warning == ""`, `v.ScenarioWarning == ""` and |
| - `v.CoveredDays == v.PeriodDays`. Its result is |
| - `moneyInputs.EconomicsComplete`. |
| + `v != nil`, `v.Warning == ""`, `v.ScenarioWarning == ""`, |
| + `v.ReadFailures == 0` and `v.CoveredDays == v.PeriodDays`. Its result |
| + is `moneyInputs.EconomicsComplete`. |
| + - `platformCost` and `platformCostEUR` exactly as above. Plan 3's `ok` |
| + → `OK` and `Label`, `Cents` converted when a usd rate exists (0 |
| + otherwise: the figure declares `inRates` for usd and the gate refuses |
| + it); not `ok` → not `OK`, `Hint` from `costBasisHint`. |
| + `moneyInputs.PlatformOK[month] = platformCostEUR(...).OK`. |
| - **The figure helper**, the only way a page shows money: |
| ```go |
| // opMoneyFigure is one money figure as a page shows it. |
| type opMoneyFigure struct { |
| - Name string // stable id, e.g. "tile.arr", "month.2026-10.net" |
| - Needs moneyNeed |
| - Shown bool |
| - Text string // the formatted figure, or the not-available text |
| - Why string // the reason's text when !Shown |
| + moneyFigure // Name, Use, Shown, Why (the code) |
| + Text string // the formatted figure, or the not-available text |
| + Reason string // the reason's text when !Shown |
| } |
| - // opMoney asks moneyReady(in, needs) (with in.PlatformOK set from |
| - // platform when needs has needPlatform) and, only when ready, calls |
| - // format. Every call is recorded in *figs for the guard test. |
| - func opMoney(figs *[]opMoneyFigure, name string, in moneyInputs, needs moneyNeed, platform *platformCost, format func() string) opMoneyFigure |
| + // opMoney asks moneyReady(in, u) and calls format only when ready. |
| + // A refused figure's Reason is the approved text for its Why, or |
| + // platform[u.Month].Hint for moneyWhyPlatform. Every call is appended |
| + // to *figs. |
| + func opMoney(figs *[]opMoneyFigure, name string, in moneyInputs, u moneyUse, platform map[string]platformCost, format func() string) opMoneyFigure |
| ``` |
| - When not ready the reason text is the approved one for `why`, or |
| - `platform.Hint` for `moneyWhyPlatform`. |
| - `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`. |
| + currency as `28.00 XYZ`. Neither is a template func. |
| - `type moneyMonth struct { Month string /* "2006-01" */; Subscriptions, |
| OnceOff, Refunds, Tax, Fees, Net int64 /* euro cents */; Currencies |
| []string /* settled currencies seen */; Platform platformCost }`. |
| @@ -351,47 +370,54 @@ Every later task takes its strings from this record through |
| (signed, so tax never leaks into revenue); `SettledTax` of every row to |
| `Tax` (refund tax negative); `Fee` of every row plus `−Settled` of fee |
| rows to `Fees`; `Net = Subscriptions + OnceOff + Refunds − Fees`. |
| - Cash after costs is `Net − Platform.Cents`, built by the page through |
| - `opMoney` with `needRevenue|needPlatform`. |
| - `type earnedView struct { Month string; MRR, OnceOff, Refunds int64; |
| Platform platformCost }` and `func earnedSoFar(arr arrTotals, m |
| moneyMonth, now time.Time) earnedView` — `MRR = round(arr.EUR / 12 × |
| day-of-month / days-in-month)`; profit is `MRR + OnceOff + Refunds − |
| - Platform.Cents`, shown through `opMoney` with |
| - `needRevenue|needPlatform`. |
| + Platform.Cents`. |
| - `func accountEarnings(month string, days []accountDay, snaps []arrSnapshot) (by map[int64]int64, covered bool)` |
| — pure; MRR = ARR ÷ 12 with calendar-month proration. `covered` is |
| - true only when every day of the month either has a snapshot with |
| - `Complete`, or has none and the latest earlier snapshot day of the |
| - same month is `Complete` (carried forward); a day before the month's |
| - first snapshot, or any incomplete snapshot, makes it false. When |
| - covered, each day an account's row is `InARR` adds `AnnualEUR / 12 / |
| - daysInMonth` (summed exactly, rounded once); a cancelling account (not |
| - `InARR`) adds nothing. When not covered, `by` is nil. |
| + true only when every day of the month has a stored snapshot with |
| + `Complete`. No carry-forward: a missing day, or an incomplete one, |
| + makes the whole month not covered (`by` nil). When covered, each day |
| + an account's row is `InARR` adds `AnnualEUR / 12 / daysInMonth` |
| + (summed exactly, rounded once); a cancelling account (not `InARR`) |
| + adds nothing. |
| - `type accountMoney struct { Fact billingFact; Group billingGroup; |
| - Earns, Costs int64 /* euro cents, the month */; Covered bool; |
| - NearUsed, NearLimit int64; NearCap capID }`. |
| - - `func accountMoneyRows(facts []billingFact, exemptID int64, earned map[int64]int64, covered bool, monthRows []paymentRow, costUSD map[string]float64, near map[int64]capState, r eurRates) []accountMoney` |
| - — per account: `Group` by `billingGroupOf` (today's group); `Earns` = |
| - `earned[id]` plus that month's once-off less refunds, each `Settled − |
| - SettledTax`; `Costs` = `costUSD[sqid]` in euros (absent: 0); `NearCap`, |
| - `NearUsed`, `NearLimit` from `near`. The page shows earns through |
| - `opMoney` with `needRevenue` and only when `Covered` (else the history |
| - reason), costs with `needEconomics`, margin with both and `Covered`. |
| - `monthRows` is the last complete month's payments. |
| + Recurring int64; OnceOff int64 /* that month's once-off less refunds, |
| + Settled − SettledTax */; OnceOffCurrencies []string; CostUSD float64; |
| + HasCost bool; NearUsed, NearLimit int64; NearCap capID }` — raw parts |
| + only; the page builds the figures. |
| + - `func accountMoneyRows(facts []billingFact, exemptID int64, earned map[int64]int64, monthRows []paymentRow, costUSD map[string]float64, near map[int64]capState, r eurRates) []accountMoney` |
| + - `func accountFigures(figs *[]opMoneyFigure, a accountMoney, covered bool, in moneyInputs, r eurRates, prefix string) (earns, costs, margin opMoneyFigure)` |
| + — the per-account figures, used by the overview and the accounts |
| + page alike. Earns declares `inPayments|ratesUse(OnceOffCurrencies...)` |
| + and is refused with the history reason when `!covered` (the stored |
| + days decide that, not today's gate); costs declare |
| + `inEconomics|inRates` with `Currencies: ["usd"]`; margin declares the |
| + union and the history condition. |
| - 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** |
| + - `TestSweepUsageCountsReadFailures` (through the real `sweepUsage`, on |
| + a `release.Store` wrapper that fails one box's metrics day `Get` with |
| + an injected error while that day's edge object reads fine) → |
| + `CoveredDays == PeriodDays` and `ReadFailures == 1`; through |
| + `LoadEconomics` the view's `ReadFailures` is 1 and `econComplete` is |
| + false. An absent metrics object (`os.ErrNotExist`) adds no failure. |
| + - `TestEconComplete`: good → true; a `Warning`, a `ScenarioWarning`, |
| + `ReadFailures 1`, `CoveredDays < PeriodDays`, an error → false each. |
| - `TestEURText` (0, 2400, 120000, −18800); `TestMinorText`. |
| - - `TestOpMoneyRefusesAndRecords`: inputs ready → `Shown`, `Text` from |
| - `format`; reconcile stale → not shown, `Text` the not-available text, |
| - `Why` the payments reason, `format` not called; `needPlatform` with a |
| - platform cost not `OK` → `Why` is its `Hint`; every call appended to |
| - `figs`. |
| - - `TestEconComplete`: nil error and no warnings with full coverage → |
| - true; a `Warning`, a `ScenarioWarning`, `CoveredDays < PeriodDays`, an |
| - error → false each. |
| + - `TestOpMoneyRefusesAndRecords`: ready → `Shown`, `Text` from `format`; |
| + a declared input broken → not shown, `format` not called, `Reason` |
| + the approved text; an undeclared input broken → shown; |
| + `moneyWhyPlatform` → `Reason` is the month's `Hint`; every call |
| + appended to `figs`. |
| + - `TestMoneyFormattersOnlyInsideOpMoney` (source test over |
| + `opbilling*.go`, `go/ast`): every call to `eurText` or `minorText` sits |
| + inside a function literal passed as `opMoney`'s last argument, and the |
| + template func map names neither. |
| - `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. |
| @@ -409,23 +435,26 @@ Every later task takes its strings from this record through |
| `by[C] == 10000`. |
| - `TestAccountEarningsCancelling`: an October row `Paying` but not |
| `InARR` → 0. |
| - - `TestAccountEarningsBeforeHistory`: first snapshot 9 Nov → October and |
| - November not `covered`; one incomplete day in an otherwise complete |
| - month → not covered; a missing day after a complete one carries |
| - forward and stays covered. |
| - - `TestAccountMoneyRows`: earned 200 for A, an October once-off 1000 (tax |
| - 0), cost 1.10 usd at 1.10 → `Earns 1200`, `Costs 100`; `covered false` |
| - → `Covered false`; a `near` row fills `NearCap`. |
| + - `TestAccountEarningsNotCovered`: first snapshot 9 Nov → October and |
| + November not covered; one incomplete day in an otherwise complete |
| + month → not covered; one missing day in an otherwise complete month → |
| + not covered. |
| + - `TestAccountFiguresGateInvariant`: `checkGateInvariant` over |
| + `accountFigures` for a paying usd account with an October once-off in |
| + gbp and a cost row (inputs: facts, payments, rates, amounts, economics, |
| + platform; only the declared ones refuse), plus `covered false` → |
| + earns and margin refused with the history reason whatever the gate. |
| - `TestPlatformCostEUR` (bills seeded as Plan 3's tests seed them): a |
| 110 usd `account` bill at usd 1.10 → `OK`, `Cents 10000`, `Label` C1; |
| an unstated bill under the zero scope → not `OK`, `Hint` C3; a manual |
| `whole` bill under `CostScope{AccountCarlosOnly: true}` → not `OK`, |
| - `Hint` C7; no bill → not `OK`, `Hint` C4; an `account` bill with no |
| - usd rate → not `OK`, `Hint` the rates reason. |
| -- [ ] **Step 2: Run** `go test ./internal/console -run 'TestEURText|TestMinorText|TestOpMoney|TestEconComplete|TestMoneyByMonth|TestEarnedSoFar|TestAccountEarnings|TestAccountMoneyRows|TestPlatformCostEUR' -count=1` → FAIL. |
| -- [ ] **Step 3: Implement.** |
| -- [ ] **Step 4: Run** the same → PASS. |
| -- [ ] **Step 5: Commit** `console: billing page money, the money gate helper, platform cost`. |
| + `Hint` C7; no bill → not `OK`, `Hint` C4. |
| +- [ ] **Step 2: Run** `go test ./internal/console -run 'TestSweepUsageCountsReadFailures|TestEconComplete|TestEURText|TestMinorText|TestOpMoney|TestMoneyFormatters|TestMoneyByMonth|TestEarnedSoFar|TestAccountEarnings|TestAccountFigures|TestPlatformCostEUR' -count=1` → FAIL. |
| +- [ ] **Step 3: Implement.** Run `TestPlan9B8RecordWriteCensus`; if |
| + `sweepUsage` or `buildEconomicsView` is pinned, re-pin it in this |
| + plan's census file. |
| +- [ ] **Step 4: Run** the same plus `-run 'Economics'` → PASS. |
| +- [ ] **Step 5: Commit** `console: billing money figures, the gate helper, full Economics reads`. |
| ### Task 4: The overview |
| @@ -449,14 +478,14 @@ Every later task takes its strings from this record through |
| account, the `plan_cap_state` row with the highest `used / cap_limit` |
| among `cap_limit > 0`. |
| - `type opBillingInput struct { Now time.Time; Rev billingRevenue; Gate |
| - moneyInputs /* Rev.Inputs with Currencies widened to the six months' |
| - settled currencies and EconomicsComplete from econComplete */; Facts |
| - []billingFact; ExemptID int64; Rates eurRates; Months []moneyMonth /* |
| - 6, newest first, from the Kind "all" read */; LastMonth string; |
| - LastRows []paymentRow /* last complete month, Kind "" */; Snaps |
| - []arrSnapshot /* the last 90 days */; Earned map[int64]int64; Covered |
| - bool; Recent []paymentRow /* 5 */; CostUSD map[string]float64; Platform |
| - map[string]platformCost; Funnel [3]int; Near map[int64]capState }` |
| + moneyInputs /* Rev.Inputs plus EconomicsComplete (econComplete) and |
| + PlatformOK (by month) */; Facts []billingFact; ExemptID int64; Rates |
| + eurRates; Months []moneyMonth /* 6, newest first, from the Kind "all" |
| + read */; LastMonth string; LastRows []paymentRow /* last complete |
| + month, Kind "" */; Snaps []arrSnapshot /* the last 90 days */; Earned |
| + map[int64]int64; Covered bool; Recent []paymentRow /* 5 */; CostUSD |
| + map[string]float64; Platform map[string]platformCost; Funnel [3]int; |
| + Near map[int64]capState }` — the gate travels in `Gate`, explicitly. |
| - 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 |
| @@ -472,61 +501,67 @@ Every later task takes its strings from this record through |
| in order (the guard test's inventory). |
| - `func buildOpBillingView(in opBillingInput) *opBillingView` (pure) and |
| `opBillingView`'s sections, in the mockup's order (spec §5.2): |
| - 1. `Tiles []opStat`, each value and note through `opMoney` with |
| - `needRevenue` (names `tile.arr`, `tile.mrr`, `tile.received`, |
| - `tile.paying`, `tile.attention`): ARR (EUR; note = each currency in |
| - `ByCurrency`, `minorText`, joined, plus the rate note; delta = now − |
| - `MonthStart.EUR`, only when `MonthStart` is `Complete`), MRR (`EUR / |
| - 12`), Received this month (`Months[0].Net`), Paying accounts |
| - (`Paying of Accounts (pct)`, change vs a `Complete` `MonthStart`), |
| - Needs attention (`Attention`). Not ready: each tile's value is the |
| - not-available text and its note the reason. |
| - 1a. **ARR over time** (new section, directly under the tiles and |
| - above Paying accounts; nothing moves or goes): `ARRBars |
| - []dashBar` from `Snaps`, one slot per day from the first snapshot |
| - (at most 90), `N` the euro ARR of a `Complete` day; a day with no |
| - snapshot or an incomplete one has no bar (height 0) and is |
| - "not available yet" in the screen-reader table; a note counts those |
| - days. Points are `opMoney` figures (`arr.<day>`, `needRevenue` |
| - against today's gate, plus the day's own `Complete`). The `co-bars` |
| - markup and screen-reader table follow the Dashboard's new-people |
| - chart. With no snapshot yet, `op_empty` with the approved line. |
| + Each figure below names what it declares (`R(c)` is |
| + `ratesUse(c...)` with those currencies). |
| + 1. `Tiles []opStat`: ARR (`tile.arr`: `inFacts|inPayments|inAmounts| |
| + R(ARR currencies)`; note = each currency in `ByCurrency`, |
| + `minorText`, joined, plus the rate note; delta = now − |
| + `MonthStart.EUR`, a figure of its own with the same inputs, shown |
| + only when `MonthStart` is stored `Complete`), MRR (`tile.mrr`, as |
| + ARR), Received this month (`tile.received`: `inPayments|R(that |
| + month's settled currencies)`), Paying accounts (`tile.paying`: |
| + `inFacts|inPayments`; change vs a `Complete` `MonthStart`), Needs |
| + attention (`tile.attention`: `inFacts|inPayments`). |
| + 1a. **ARR over time** (directly under the tiles and above Paying |
| + accounts; nothing moves or goes): one slot per day from the first |
| + snapshot (at most 90); a day's point is shown iff its stored |
| + snapshot is `Complete` (no live input declared: `arr.<day>` with an |
| + empty `moneyUse`); a missing or incomplete day has no bar (height 0) |
| + and is "not available yet" in the screen-reader table; a note |
| + counts those days. The `co-bars` markup and screen-reader table |
| + follow the Dashboard's new-people chart. With no snapshot yet, |
| + `op_empty` with the approved line. |
| 2. `Paying []opBillingAccountRow`: the 5 most recent `FirstPaid` among |
| - paying accounts, with plan, packs and seats, earns (`needRevenue`, |
| - and `Covered`), costs (estimate, `needEconomics`), margin (both), |
| - renews (`PeriodEnd`), status (Payment failing for `past_due`, |
| - Cancels at renewal, else Paid). |
| + paying accounts (the list itself declares `inFacts|inPayments`; |
| + refused, the section shows the reason in place of rows), with plan, |
| + packs and seats, earns, costs (estimate) and margin from |
| + `accountFigures` for `LastMonth`, renews (`PeriodEnd`), status |
| + (Payment failing for `past_due`, Cancels at renewal, else Paid). |
| 3. `Earned` beside `Funnel` (signed up, made an app, active last 30 |
| - days, paying): recurring, once-off and refunds with `needRevenue`; |
| - AWS bill with `needPlatform` (this month's cost); profit with |
| - `needRevenue|needPlatform`. The funnel's paying count with |
| - `needRevenue`. |
| - 4. `Months`: per month, the revenue columns, tax, fees and net with |
| - `needRevenue`; AWS bill with `needPlatform` (that month); cash after |
| - costs with `needRevenue|needPlatform`; each row links to |
| - `/fleet/billing/payments?month=YYYY-MM`. |
| + days, paying): recurring (`inFacts|inPayments|inAmounts|R(ARR |
| + currencies)`), once-off and refunds (`inPayments|R(month)`), AWS |
| + bill (`inPlatform|inRates` usd, this month), profit (the union). |
| + The funnel's paying count `inFacts|inPayments`; the other funnel |
| + counts are not money. |
| + 4. `Months`: per month, the revenue columns, tax, fees and net |
| + (`inPayments|R(that month's settled currencies)`); AWS bill |
| + (`inPlatform|inRates` usd, that month); cash after costs (the |
| + union); each row links 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`, |
| - `needRevenue`), status. |
| + subscription rows, detail for domain rows), amount as charged |
| + (`minorText`, `inPayments` only: no conversion), status. |
| 6. `Weeks []dashBar`: `dashBars` over 12 `DayCount`s, one per week |
| - ending today, counting `FirstPaid`. |
| + ending today, counting `FirstPaid` (a figure declaring |
| + `inFacts|inPayments`). |
| 7. `Reasons []opBillingReasonRow`: Free, Sponsored, House, Ours with |
| - count, cost to run (last month, estimate, `needEconomics`) and the |
| - costliest account; then Shared and idle (`Platform[LastMonth] − Σ |
| - all accounts' costs`, `needEconomics|needPlatform`). Rows link to |
| + count, cost to run (last month, estimate, `inEconomics|inRates` |
| + usd) and the costliest account; then Shared and idle |
| + (`Platform[LastMonth] − Σ all accounts' costs`, |
| + `inEconomics|inPlatform|inRates` usd, `LastMonth`). 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 |
| - (usage, not money: shown as is). |
| + (usage, not money: shown as is), and cost to run |
| + (`inEconomics|inRates` usd). |
| - `handleOpBilling` gathers the inputs: `Payments(paymentFilter{From: |
| six months back, To: now, Kind: "all"})` for the money table and the |
| current month, `Payments(paymentFilter{From, To: last month, Kind: |
| ""})` for per-account once-off, `ARRSnapshots` for 90 days, |
| `AccountDays` for `accountEarnings` over the last complete month, |
| `LoadEconomics(ctx, "last")` (an error is logged; `econComplete` |
| - decides), and `platformCostEUR` for the six months; renders |
| - `ops_billing`. |
| + decides), and `platformCostEUR` for the six months, then builds |
| + `Gate`; 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 |
| @@ -540,20 +575,22 @@ Every later task takes its strings from this record through |
| bill → 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. |
| - - `TestOverviewMoneyGuard` (the guard): a pinned list of figure names the |
| - overview must produce (tiles, ARR points, earned lines, profit, funnel |
| - paying, every month's columns and cash, recent amounts, paying-list |
| - earns, costs and margins, reason costs, Shared and idle) equals the |
| - names in `v.Figures`, so a figure built outside `opMoney` fails here. |
| - Then, table-driven over the inputs (reconcile 3 h stale; rates 27 h |
| - stale; a gbp payment with no gbp rate; one paying account with |
| - `Annual -1`; Economics with a `Warning`; Economics with `CoveredDays < |
| - PeriodDays`; the platform cost not `OK`), each case breaking only that |
| - input: every figure whose `Needs` includes the broken need is not |
| - `Shown`, its `Text` is the not-available text and its `Why` the |
| - reason; every other figure is `Shown`. Last, with revenue, Economics |
| - and platform all broken, the rendered HTML has no match for |
| - `[€$£]\d`. |
| + - `TestOverviewGateInvariant` (the guard): a pinned list of figure names |
| + the overview must produce (tiles and the delta, ARR points, earned |
| + lines and profit, funnel paying, every month's columns and cash, |
| + recent amounts, the paying list and its earns, costs and margins, |
| + weekly bars, reason costs, Shared and idle, limit costs) equals the |
| + names in `v.Figures`, so a figure built outside `opMoney` fails; |
| + then `checkGateInvariant` over `buildOpBillingView` with a world |
| + holding an eur and a usd paying account, a gbp once-off, a cost per |
| + account, an `account` bill and complete snapshots: every figure is |
| + refused iff it declares the flipped input. ARR points declare no live |
| + input, so no flip refuses them. |
| + - `TestOverviewCostsNeedUSD`: Economics complete and the platform cost |
| + `OK`, but the usd rate missing (then, separately, the rates 27 h |
| + stale) → every cost, margin, AWS bill, cash, profit and Shared and |
| + idle figure is refused with the rates reason; recorded eur charges |
| + still show. |
| - `TestOverviewAfterMidnightFailure` (handler to store): snapshots for D |
| stored `complete 0` and D+1 `complete 1`, a fresh reconcile now → |
| tiles shown; D has no ARR bar and is counted in the note; the month |
| @@ -561,9 +598,9 @@ Every later task takes its strings from this record through |
| - `TestOverviewMoneyIncludesFeeRows` (handler to store): a stored fee |
| row of −45 eur and nothing else in the month → the month's Stripe fees |
| cell is €0.45 and Net −€0.45. |
| - - `TestOverviewARRChart`: three days, the middle one stored incomplete → |
| - bars for the first and third only, the note counts one day; no |
| - snapshots → the empty line. |
| + - `TestOverviewARRChart`: four days, the second stored incomplete and |
| + the third missing → bars for the first and fourth only, the note |
| + counts two days; no snapshots → the empty line. |
| - `TestOverviewEmpty`: no payments, no paying accounts, every input good |
| → empty states, `0 of N (0%)`, six €0.00 months. |
| - `TestOverviewCapsAtFive`: seven paying accounts → five rows, newest |
| @@ -571,7 +608,7 @@ Every later task takes its strings from this record through |
| - `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 2: Run** `go test ./internal/console -run 'TestBuildOpBillingView|TestOverview|TestBillingFunnel|TestNearestCaps' -count=1` → FAIL. |
| +- [ ] **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`. |
| @@ -585,29 +622,34 @@ Every later task takes its strings from this record through |
| - Test: `internal/console/opbilling_test.go` |
| **Interfaces:** |
| -- Consumes: Task 3 `accountEarnings` and `accountMoneyRows` (for the last |
| - complete month, as on the overview), Task 4 `NearestCaps`. |
| +- Consumes: Task 3 `accountEarnings`, `accountMoneyRows` and |
| + `accountFigures` (for the last complete month, as on the overview), |
| + 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` |
| + - `func buildOpBillingAccounts(rows []accountMoney, covered bool, in moneyInputs, r eurRates, group billingGroup, sort string, page int, q url.Values) opBillingAccountsView` |
| + — the gate inputs are an argument, so the same rows give different |
| + pages for different inputs; the view carries `Figures |
| + []opMoneyFigure`. |
| — 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; the money columns are `opMoney` figures with the same |
| - needs as on the overview. When a sort's column is not available (its |
| - gate says no, or the month is not covered), the list falls back to |
| - `joined` and says so with the column's reason. An unknown `tab` or |
| + margin, joined; the money columns come from `accountFigures`. The |
| + tab counts declare `inFacts|inPayments` (the paying group depends on |
| + both). When a sort's column is refused for any row (the gate, or the |
| + month not covered), the list sorts by `joined` and says so with that |
| + column's reason. An unknown `tab` or |
| `sort` falls back to the default. |
| - [ ] **Step 1: Write the failing tests**: `TestBillingAccountsTabsAndCounts`, |
| `TestBillingAccountsSorts` (each sort key, ties stable), |
| - `TestBillingAccountsGated` (reconcile stale → earns and margin cells |
| - not available, `sort=earns` falls back to joined; Economics degraded → |
| - costs and margin not available), |
| + `TestBillingAccountsGateInvariant` (`checkGateInvariant` over |
| + `buildOpBillingAccounts` with fixed rows; and `sort=earns` with the |
| + reconcile flipped falls back to joined with the payments reason), |
| `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. |
| @@ -634,17 +676,20 @@ Every later task takes its strings from this record through |
| bool; RateNote string }`; a row: when, account (link unless unmatched or |
| deleted), what, charged (`minorText(Amount, Currency)`), net in euros |
| (`Settled − SettledTax − Fee`, refunds and reversals alike), fee, |
| - status; charged, net and fee are `opMoney` figures with |
| - `needRevenue`, so a stale reconcile or rate shows them as not |
| - available with the reason. Reads `Payments` with `Kind ""` (no fee |
| - rows). |
| + status. Charged declares `inPayments` only (no conversion); net and |
| + fee declare `inPayments|R(SettledCurrency)` (so an eur-settled row |
| + needs no rate). `func buildOpBillingPayments(rows []paymentRow, total |
| + int, in moneyInputs, r eurRates, month, kind string, page int, q |
| + url.Values) opBillingPaymentsView` takes the gate inputs explicitly. |
| + Reads `Payments` with `Kind ""` (no fee rows). |
| - 50 per page, newest first. |
| - [ ] **Step 1: Write the failing tests**: `TestBillingPaymentsFilters` |
| (month, each kind, both), `TestBillingPaymentsPages`, |
| `TestPaymentsUnmatchedAndDeleted`, `TestBillingPaymentsBadQuery`, |
| - `TestBillingPaymentsGated` (stale reconcile → money cells not |
| - available, rows still listed). |
| + `TestBillingPaymentsGateInvariant` (`checkGateInvariant` over |
| + `buildOpBillingPayments` with an eur-settled and a usd-settled row; rows |
| + stay listed when their cells are refused). |
| - [ ] **Step 2: Run** `go test ./internal/console -run 'TestBillingPayments|TestPaymentsUnmatched' -count=1` → FAIL. |
| - [ ] **Step 3: Implement.** |
| - [ ] **Step 4: Run** the same → PASS. |
| @@ -661,18 +706,19 @@ Every later task takes its strings from this record through |
| **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`, |
| - both through `opMoney` with `needRevenue` (not ready: the not-available |
| - text and the reason), the test-mode word when `TestMode`, `Href: |
| +- Produces: `func billingDashStat(rev billingRevenue, in moneyInputs) (opStat, []opMoneyFigure)` — label |
| + Paying accounts, value the paying count (`inFacts|inPayments`), note |
| + the ARR in euros `a year` (`inFacts|inPayments|inAmounts|R(ARR |
| + currencies)`), both through `opMoney` (refused: the not-available text |
| + and the reason), 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; a stale reconcile → the |
| - not-available text), `TestOpStatLinks` (an `opStat` with `Href` renders |
| + to Billing with the approved note), `TestDashStatGateInvariant` |
| + (`checkGateInvariant` over `billingDashStat`), `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.** |
| @@ -685,6 +731,21 @@ Every later task takes its strings from this record through |
| --- |
| +## Known limitations at launch |
| + |
| +- **Past-month margins wait for a whole recorded month.** Per-account |
| + earnings for a past month need a complete snapshot for every day of |
| + it, and history starts on the day this ships (9 November 2026 if it |
| + ships then). So the first month with per-account earnings and margins |
| + is December 2026, first shown in January 2027. Until then the earns and |
| + margin columns say plainly why (the approved line), and costs still |
| + show. |
| +- **One bad day hides a month.** A day whose snapshot was stored |
| + incomplete (a reconcile, subscription-read or rate outage lasting past |
| + the day's last pass), or a day with no snapshot at all, makes that |
| + month's per-account earnings unavailable for good. Today's figures |
| + recover as soon as the inputs do. |
| + |
| ## After the plan |
| - Done means (spec §7, the parts this plan owns): on flagship the Billing |