carlos / platform Public

plan: billing dashboard 1-2, Astra round 2 fixes

One money gate, refused up front: moneyInputs and moneyReady cover the
payment reconcile (last success within 2 h), current rates for every
converted currency, known yearly amounts, and for costs a complete
Economics read and the platform cost. Every money figure goes through
it (Plan 2's opMoney); refused figures read "not available yet" with the
reason. Snapshots store complete and why; an incomplete day is unknown
to every consumer. Guard test over the overview's figures, and the
failure-across-midnight case.

Historical earnings are ARR / 12 prorated per calendar day for InARR
days only. Coupons are read with applies_to through GetCoupon. Plan 2
matches Plan 3 at 93114fcf (C1-C4, C7; no tag basis). Billing-off
expectations in the perfwalk and shell walks, a billing-on shell test,
and go build plus make test before landing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev bdd92420278a3554accf37f477535d44ee6a3f5a parent 93114fc
2 files changed, +459 −275
  • docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md +174 −81
  • docs/superpowers/plans/2026-11-09-billing-dashboard-2-pages.md +285 −194
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 3456b5238..677b04046 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,11 +48,18 @@ 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.
-- **Completeness travels with every total.** A total that leaves something
- out says so: `EURKnown` (a rate is missing), `AmountsKnown` (a paying
- account's yearly amount is unknown) and `PaymentsCurrent` (the reconcile
- did not finish) are carried through totals, snapshots, the CLI and the
- pages. Nothing shows a figure as complete when one of them is false.
+- **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.
- **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
@@ -91,8 +98,9 @@ and §5; Plan 3 (written separately) covers §4.5.
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
+- **Tests:** while iterating, only touched packages, `go test
+ ./internal/<pkg> -run '<Name>' -count=1`. Before landing, once (Task 9's
+ last step): `go build ./...` and `make test`, as AGENTS.md requires. 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
@@ -119,8 +127,10 @@ and §5; Plan 3 (written separately) covers §4.5.
rate of 0, a negative rate or an empty set is refused, never stored
(Task 6 `TestECBRefusesBadRates`, `TestRatesPassKeepsLastGood`).
5. **A paid subscription whose yearly amount is unknown** (an unsupported
- discount). It is Paying, its amount is left out of ARR, and every ARR
- figure says it is incomplete (Task 7 `TestARROfUnknownAmount`). A house
+ or product-limited discount). It is Paying, and every money figure is
+ refused with the amounts reason until it is known (Task 1
+ `TestSubscriptionAnnualReadsCoupons`, Task 7 `TestARROfUnknownAmount`,
+ `TestMoneyReady`). A house
account (100% coupon) is House, and a cancelling one is Paying outside
ARR (Task 1 `TestAnnualOf`, Task 7 `TestARROf`).
@@ -146,8 +156,17 @@ and §5; Plan 3 (written separately) covers §4.5.
**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).
+ 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).
+ - `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
+ failed coupon read makes `AnnualKnown` false (logged); the
+ subscription read itself still succeeds, so entitlement never waits on
+ a coupon.
- `billingstripe.SubscriptionItem` gains `UnitAmount *int64`
(`price.unit_amount`) and `HasDiscounts bool` (the item's own
`discounts` is non-empty). `billingstripe.Subscription` gains
@@ -177,12 +196,21 @@ and §5; Plan 3 (written separately) covers §4.5.
fields; the request carries `expand[]=latest_invoice` and
`expand[]=discounts` (update the check at `prepared_test.go:941` to read
`r.URL.Query()["expand[]"]`).
+ - `TestSubscriptionAnnualReadsCoupons` (`httptest`, through
+ `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
+ `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`: 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).
+ - `TestDecideBillingStoresAnnual`: a read (`AnnualRead`) with
+ `AnnualKnown` 2400 → `Next.Annual == 2400`; a read with `AnnualKnown
+ false` → -1; a write's answer (`AnnualRead false`) keeps the stored
+ value.
+- [ ] **Step 2: Run** `go test ./internal/billingstripe ./internal/console -run 'TestAnnualOf|TestSubscriptionDecodesDiscounts|TestSubscriptionAnnualReadsCoupons|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
@@ -190,7 +218,9 @@ and §5; Plan 3 (written separately) covers §4.5.
`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
+ `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
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.
@@ -373,7 +403,8 @@ and §5; Plan 3 (written separately) covers §4.5.
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
+ PRIMARY KEY CHECK (id = 1), through INTEGER NOT NULL, succeeded_at
+ INTEGER NOT NULL DEFAULT 0)`. 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).
@@ -407,6 +438,8 @@ and §5; Plan 3 (written separately) covers §4.5.
— newest first by `at` then `movement_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`.
+ - `func (s *Store) PaymentsReconciledAt() (time.Time, error)` (zero when
+ never) and `func (s *Store) SetPaymentsReconciled(at time.Time) error`.
- Gate rows: `billing_payments` {NonApp: "money received, refunded or
kept as fees, one row per provider balance movement, with the account; names no
app"}, `billing_payment_cursor` {NonApp: "how far the payment
@@ -429,7 +462,8 @@ and §5; Plan 3 (written separately) covers §4.5.
`RematchPayments` returns 1 and the row has the account.
- `TestPaymentsFilter`: month bounds, each kind, `""` leaving out fee
rows, `"all"` including them, account, offset/limit, total, newest first.
- - `TestPaymentCursorRoundTrip`: none → `ok false`; set, read back.
+ - `TestPaymentCursorRoundTrip`: none → `ok false`; set, read back; the
+ reconciled time likewise.
- `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
@@ -458,10 +492,8 @@ and §5; Plan 3 (written separately) covers §4.5.
- `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(ctx, now,
- reconciled)` (Task 7) with `reconciled` true only when the reconcile
- returned nil; each failure logged and passed to `jobFailed`, none
- stopping the next.
+ `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 −
@@ -479,7 +511,9 @@ and §5; Plan 3 (written separately) covers §4.5.
it, leaving the cursor where it was.
5. `SetPaymentCursor(to)`, `from = to`, window back to
`billingMoneyWindow`.
- 6. After the loop, `RematchPayments`.
+ 6. After the loop, `RematchPayments`, then
+ `SetPaymentsReconciled(now)`: only a run that reached `now` with no
+ error counts as a success.
- `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,
@@ -501,7 +535,8 @@ and §5; Plan 3 (written separately) covers §4.5.
`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.
+ second's is not, and `PaymentsReconciledAt` is unchanged; a later run
+ with the failure cleared records it and sets the reconciled time.
- `TestReconcileRefundOfUnrecordedCharge`: only a refund movement in the
window, its charge never recorded → charge and refund recorded, refund
on the charge's account.
@@ -558,14 +593,15 @@ and §5; Plan 3 (written separately) covers §4.5.
- 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 }`
+ - `type eurRates struct { Day string; FetchedAt time.Time; 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.
+ set, `FetchedAt` its newest `fetched_at` (a refetch of the same ECB day
+ refreshes it); 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
@@ -591,7 +627,7 @@ and §5; Plan 3 (written separately) covers §4.5.
### Task 7: Paying, groups, ARR and the daily snapshot
**Files:**
-- Create: `internal/console/billingrevenue.go`
+- Create: `internal/console/billingrevenue.go`, `internal/console/billingmoney.go`
- Modify: `internal/console/billingpayments_store.go` (`migrateBillingMoney`
adds the snapshot table), `internal/console/store_gate.go`
- Modify: `internal/console/billingmoneypass.go` (call `billingSnapshotPass`)
@@ -619,32 +655,70 @@ and §5; Plan 3 (written separately) covers §4.5.
- `func inARR(f billingFact, exemptID int64) bool` — paying, not
cancelling, `Annual > 0`, not exempt.
- `type arrTotals struct { ByCurrency map[string]int64; EUR int64;
- EURKnown, AmountsKnown bool; Unknown int; 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; `AmountsKnown` false and `Unknown` the count
- when a paying, non-cancelling, non-exempt account has `Annual == -1`
- (its amount is left out of every sum).
- - `func (a arrTotals) Complete() bool` — `EURKnown && AmountsKnown`.
+ RateDay string; Paying, Attention, Unknown int }` — `Attention` counts
+ paying accounts that are `past_due` or cancelling; `Unknown` the
+ paying, non-cancelling, non-exempt accounts with `Annual == -1` (left
+ out of `ByCurrency`); `EUR` is 0 when a currency has no rate (the gate
+ refuses such figures anyway).
- `func arrOf(facts []billingFact, exemptID int64, r eurRates) arrTotals`
+ - **The money gate** (`internal/console/billingmoney.go`), the one place
+ completeness is decided:
+ ```go
+ 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
+ }
+ type moneyNeed uint8
+ const (
+ needRevenue moneyNeed = 1 << iota // payments, rates, amounts
+ needEconomics // the Economics read
+ needPlatform // the month's platform cost
+ )
+ const (
+ 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).
+ const (
+ moneyWhyPayments = "payments"
+ moneyWhyRates = "rates"
+ moneyWhyAmounts = "amounts"
+ moneyWhyEconomics = "economics"
+ moneyWhyPlatform = "platform"
+ )
+ func moneyReady(in moneyInputs, need moneyNeed) (ok 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.
- 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, amounts_known INTEGER NOT NULL, unknown INTEGER NOT NULL,
- payments_current INTEGER NOT NULL, rate_day TEXT NOT NULL, paying
- INTEGER NOT NULL, written_at INTEGER NOT NULL)`; gate {NonApp: "daily
- recurring revenue totals; names no app"}.
+ JSON currency → minor */, arr_eur INTEGER NOT NULL, rate_day TEXT NOT
+ NULL, paying INTEGER NOT NULL, complete INTEGER NOT NULL, why TEXT NOT
+ NULL, written_at INTEGER NOT NULL)`; gate {NonApp: "daily recurring
+ revenue totals; names no app"}.
- Table `billing_account_daily (day TEXT NOT NULL, account_id INTEGER NOT
NULL, annual INTEGER NOT NULL /* -1 unknown */, currency TEXT NOT NULL,
- annual_eur INTEGER NOT NULL, eur_known INTEGER NOT NULL, paying INTEGER
- NOT NULL, in_arr INTEGER NOT NULL, PRIMARY KEY (day, account_id))` —
- one row per non-exempt account with a subscription on that day; gate
- {NonApp: "each account's yearly amount per day; names no app"}.
+ annual_eur INTEGER NOT NULL, paying INTEGER NOT NULL, in_arr INTEGER NOT
+ NULL, PRIMARY KEY (day, account_id))` — one row per non-exempt account
+ with a subscription that day; a day's account rows are as complete as
+ its ARR row says; gate {NonApp: "each account's yearly amount per day;
+ names no app"}.
- `type arrSnapshot struct { Day string; ARR map[string]int64; EUR int64;
- EURKnown, AmountsKnown bool; Unknown int; PaymentsCurrent bool; RateDay
- string; Paying int }` and `func (a arrSnapshot) Complete() bool` (all
- three flags).
+ RateDay string; Paying int; Complete bool; Why string }`
- `type accountDay struct { Day string; AccountID int64; Annual int64;
- Currency string; AnnualEUR int64; EURKnown, Paying, InARR bool }`
+ Currency string; AnnualEUR int64; Paying, InARR bool }`
- `func (s *Store) PutDailySnapshot(a arrSnapshot, accounts []accountDay, today string, now time.Time) error`
— one transaction. `a.Day == today`: upsert the ARR row and replace
every account row of that day. `a.Day` before `today`: refused with
@@ -652,19 +726,21 @@ and §5; Plan 3 (written separately) covers §4.5.
- `func (s *Store) ARRSnapshots(fromDay, toDay string) ([]arrSnapshot, error)` (inclusive, oldest first)
- `func (s *Store) AccountDays(fromDay, toDay string) ([]accountDay, error)` (inclusive, by day then account)
- `func (s *Store) FirstSnapshotDay() (string, error)` (`""` when none)
- - `func (s *Server) billingSnapshotPass(ctx context.Context, now time.Time, reconciled bool) error`
- — builds today's (UTC) `arrSnapshot` from `arrOf` with
- `PaymentsCurrent = reconciled`, and the account rows from the same
- facts and rates, and writes them 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.
+ - `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
+ 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 }`
+ the 1st of this month, nil when none */; TestMode bool; Inputs
+ moneyInputs /* currencies: ByCurrency's */ }`
- `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.
+ — `BillingFacts`, `LatestEURRates`, `arrOf`, the group counts,
+ `MonthStart` and `moneyInputsFor`; `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;
@@ -675,27 +751,35 @@ and §5; Plan 3 (written separately) covers §4.5.
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`, `AmountsKnown`; a
- cancelling account adds nothing to ARR and 1 to `Attention`; a past_due
- one adds to both; gbp with no rate → `EURKnown false`.
+ {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`, `EUR 2400`, `AmountsKnown
- false`, `Unknown 1`, `Complete()` false; its snapshot stores
- `amounts_known 0`.
+ -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.
- `TestBillingFactsQuery`: an account per group, a deleted account
(absent), apps counted, `FirstPaid` the earliest subscription payment.
- - `TestSnapshotTodayReplaceable`: a pass with `reconciled false` then
- one with `reconciled true` on the same day → one ARR row,
- `payments_current 1`, the second pass's figures; an account that
- stopped paying between them has no row for today.
+ - `TestSnapshotTodayReplaceable`: a pass while the reconcile is stale,
+ then one after a successful reconcile, same day → one ARR row,
+ `complete 1`, the second pass's figures; an account that stopped
+ paying between them has no row for today.
- `TestSnapshotEarlierDaysFrozen`: `PutDailySnapshot` for yesterday →
error, yesterday's rows unchanged; the next day's pass adds a second
day and leaves the first alone.
- `TestSnapshotStartsAtFirstPass`: old payments, no snapshot → the first
pass writes today only; `FirstSnapshotDay` is today.
- - `TestSnapshotIncompleteFlags`: no rate for a gbp account, an unknown
- amount and `reconciled false` → each flag stored false and read back.
-- [ ] **Step 2: Run** `go test ./internal/console -run 'TestPayingNow|TestBillingGroupOf|TestARROf|TestBillingFactsQuery|TestSnapshot' -count=1` → FAIL.
+ - `TestSnapshotFailureAcrossMidnight`: the reconcile succeeds at 21:00
+ 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.
- [ ] **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`.
@@ -711,8 +795,8 @@ and §5; Plan 3 (written separately) covers §4.5.
- `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 line
- saying ARR leaves out %d accounts whose yearly amount is unknown); the
+ one line of group counts, the test-mode line); the "not available yet"
+ line and one reason per `moneyWhy*` code (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).
@@ -751,12 +835,15 @@ 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`): `{"arr":{"eur":2400},
- "arr_eur":2400,"eur_known":true,"amounts_known":true,"unknown_amounts":0,
- "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. The CLI prints the
- unknown-amounts line whenever `amounts_known` is false.
+ - `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.
- `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",
@@ -772,14 +859,16 @@ and §5; Plan 3 (written separately) covers §4.5.
- [ ] **Step 1: Write the failing tests**
- `TestAPIBillingRevenue`: billing world with one paying eur account and
- a stored rate → the JSON above; a second paying account with an
- unknown amount → `amounts_known false`, `unknown_amounts 1`; a member (not operator) → 404; billing
+ 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`.
- `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, the
- unknown-amounts line among them; `-kind once-off` sends `once_off`.
+ not-available line with each reason among them; `-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.
@@ -800,6 +889,10 @@ and §5; Plan 3 (written separately) covers §4.5.
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`.
+- [ ] **Step 7: The landing gate** (AGENTS.md "Build & test"), once, on
+ the branch tip: `go build ./...` and `make test` → both clean. Fix
+ anything they find in its own commit before the branch is described and
+ merged.
---
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 ba0c8f366..74f5cdf8a 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
@@ -41,25 +41,27 @@ B (tag mode, the untagged inventory, copy C5), which is deferred.
- **Operators only** (`operatorOnly`), checked before the billing check.
- **Euros everywhere**, converted with Plan 1's `eurRates.eurCents`; the
native-currency breakdown stays beside every converted total; every
- converted figure carries the rate date. With no stored rate, converted
- figures show the approved "no rate yet" text, never €0.
+ converted figure carries the rate date.
- **Estimates are labelled** wherever they appear: per-account costs
(Economics' model) and anything built from them.
- **Platform cost is shown only when `platformCostEUR` says `OK`** (spec
- §4.5), always with its `Label`. Otherwise the platform cost, profit,
- cash after costs and "Shared and idle" are hidden and its `Hint` shows
- in their place.
+ §4.5), always with its `Label`. Otherwise every figure that needs it
+ shows the approved "not available yet" text with Plan 3's `Hint` as the
+ reason.
- **Revenue is before tax** everywhere, in both directions: every row
counts `Settled − SettledTax`, refunds and reversals included, so a fully
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.
-- **Incomplete is never shown as complete.** A figure built from an
- `arrTotals` or `arrSnapshot` that is not `Complete()`, from a month whose
- `EURKnown` is false, or from earnings that are not known, carries the
- approved incomplete or unknown text in place of (or beside, where the
- record says) the number. Profit and cash after costs need complete
- revenue as well as `Platform.OK`.
+- **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.
- **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,
@@ -82,8 +84,9 @@ B (tag mode, the untagged inventory, copy C5), which is deferred.
test calls at the time (Plan 1's `billingDashboard1WriteCensusInventory`
once that merges), and point the test at it. The root-read census (#280)
does not apply: everything here is console-only.
-- **Tests:** `go test ./internal/console -run '<Name>' -count=1`; CI runs
- the full suite. Go commands may need the Bash sandbox disabled; leave
+- **Tests:** while iterating, `go test ./internal/console -run '<Name>'
+ -count=1`. Before landing, once (Task 7's last step): `go build ./...`
+ and `make test`, as AGENTS.md requires. Go commands may need the Bash sandbox disabled; leave
`GOCACHE` at its default.
- **Commits:** subject under 80 characters, prefixed (`console:`, `docs:`),
body after a blank line.
@@ -92,29 +95,33 @@ B (tag mode, the untagged inventory, copy C5), which is deferred.
## Interfaces from Plan 1 (consumed as named)
`billingRevenueNow(now) (billingRevenue, []billingFact, error)`;
-`billingRevenue{arrTotals; Groups; Accounts; MonthStart; TestMode}`;
-`arrTotals{ByCurrency; EUR; EURKnown; AmountsKnown; Unknown; RateDay;
-Paying; Attention}` and `Complete()`; `arrSnapshot` (with `EURKnown`,
-`AmountsKnown`, `Unknown`, `PaymentsCurrent`, `Complete()`);
-`accountDay`; `Store.AccountDays(fromDay, toDay)`; `Store.FirstSnapshotDay()`;
-`billingFact` (fields as Plan 1 Task 7); `payingNow`, `billingGroupOf`,
-`inARR`, `billingGroup` and `billingGroupOrder`; `Store.Payments(paymentFilter)`
-and `paymentRow`; `billing.Payment`, `billing.PaymentKind` constants and
+`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`,
+`Store.FirstSnapshotDay`; `billingFact` (fields as Plan 1 Task 7);
+`payingNow`, `billingGroupOf`, `inARR`, `billingGroup` and
+`billingGroupOrder`; `Store.Payments(paymentFilter)` with `Kind ""` (the
+lists: no fee rows) and `Kind "all"` (the money sums: fee rows included),
+and `paymentRow` (key `Movement`); `billing.Payment`, its kinds and
reasons; `Store.LatestEURRates()`, `eurRates.eurCents`;
-`Store.ARRSnapshots(fromDay, toDay)`; `s.store.planExemptID`.
-`Payments` with `Kind ""` (the lists: no fee rows) and `Kind "all"` (the
-money sums: fee rows included); a row's key is `Movement`.
+`s.store.planExemptID`.
## The platform cost: one function over Plan 3's seam
-Plan 3 (`2026-11-09-billing-dashboard-3-carlos-only-cost.md`, Task 2,
-"names are final") provides `func (s *Server) carlosPlatformCostUSD(ctx
-context.Context, month string) (usd float64, basis string, ok bool)`, `ok`
-only for a CARLOS-only basis (`economics.BasisAccount` or
-`economics.BasisTagged`), `basis` `""` for a whole-account bill and
-`costBasisMissing` for none; `costBasisLabel(basis, deployment string)
-string` (its copy C1-C3); and `costBasisHint(scope CostScope, basis, month
-string) string` (C4-C6, the line shown in place of a hidden cost). Plan 2
+Plan 3 (`2026-11-09-billing-dashboard-3-carlos-only-cost.md` at
+93114fcf, Task 2, slice A only) provides `func (s *Server)
+carlosPlatformCostUSD(ctx context.Context, month string) (usd float64,
+basis string, ok bool)`: `ok` only for `economics.BasisAccount`; when not
+`ok`, `basis` is `economics.BasisUnstated` (`""`), `economics.BasisWhole`
+(`"whole"`, a manual bill entered as whole, never counted even with the
+setting on) or `costBasisMissing` (no bill). `costBasisLabel(basis,
+deployment string) string` returns C1 for `account`, C2 otherwise.
+`costBasisHint(scope CostScope, basis, month string) string` returns C3
+for unstated, C7 for whole, C4 for missing, `""` for `account`. Plan 2
reads platform cost through one function of its own, in Task 3:
```go
@@ -124,7 +131,7 @@ type platformCost struct {
Basis string // as carlosPlatformCostUSD returns it
Label string // costBasisLabel(Basis, ""): shown beside a figure
Hint string // costBasisHint(s.cfg.CostScope, Basis, month), or the
- // approved "no rate yet" text: shown in place of a figure
+ // approved rates reason when the dollars would not convert
OK bool // a CARLOS-only figure exists and its dollars converted
}
@@ -134,30 +141,32 @@ type platformCost struct {
func (s *Server) platformCostEUR(ctx context.Context, month string, r eurRates) platformCost
```
-So Plan 2 is built after Plan 3's slice A merges, as well as Plan 1. With
-no basis set (no `CONSOLE_COST_ACCOUNT_CARLOS_ONLY`), `ok` is false and
-every cost figure is hidden behind the hint. The basis lines and hints are Plan 3's approved copy; Plan 2's
-record does not repeat them.
+Plan 2 is built after Plan 3's slice A merges, as well as Plan 1. With no
+basis set (no `CONSOLE_COST_ACCOUNT_CARLOS_ONLY`), `ok` is false and every
+figure needing platform cost is refused with the hint. Nothing here uses
+Plan 3's deferred tag basis. The basis lines and hints are Plan 3's
+approved copy (C1-C4, C7); Plan 2's record does not repeat them.
## Review Focus
1. **Billing off.** An operator's GET and POST to all three routes answer
the body and status of an unknown route; no rail item; no tile (Task 2
`TestBillingRoutesHiddenWhenOff`, Task 7 `TestDashboardTileOnlyWithBilling`).
-2. **No CARLOS-only figure.** A whole-account bill on a console with no
- cost setting, or no bill for the month: no platform cost, profit, cash
- after costs or "Shared and idle" figure appears, and Plan 3's hint does
- (Task 3 `TestEarnedHiddenWithoutBasis`, Task 4
- `TestOverviewHidesCostWithoutBasis`).
-3. **No rate stored yet.** A fresh console whose rate fetch never succeeded
- shows "no rate yet" for converted figures and still shows the
- native-currency notes, never €0 (Task 4 `TestOverviewNoRate`).
-4. **Nothing yet.** No payments, no paying accounts, no Economics data: the
- page renders its empty states, percentages do not divide by zero, and
- the six month rows show €0.00 (Task 4 `TestOverviewEmpty`).
+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).
+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
+ `TestOverviewAfterMidnightFailure`).
+4. **Nothing yet.** No payments and no paying accounts, every input good:
+ the page renders its empty states, percentages do not divide by zero,
+ 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
- unknown, never as today's MRR (Task 3 `TestAccountEarningsBeforeHistory`).
+ snapshot is 9 November, shows per-account earnings and margins as not
+ available, never as today's MRR (Task 3 `TestAccountEarningsBeforeHistory`).
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
@@ -176,17 +185,18 @@ record does not repeat them.
reviewer's):
- Rail label `Billing`; the three pages' subheads; the Accounts and
Payments page titles.
-- Test-mode line; rate note (`at ECB rates of %s`); "no rate yet";
- estimate label; "unknown" (no Economics figure, or earnings before the
- history); the incomplete note (`leaves out %d accounts whose yearly
- amount is unknown`); "earnings start on %s" (the first snapshot day);
- the partial-month note. The basis lines and the
- hidden-cost hints are Plan 3's C1-C6, not rows here.
+- 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
+ 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
(`%s of %s (%s)` and its change), Needs attention (its note).
- ARR over time: heading, axis words (first day, today), the
- screen-reader caption and column heads, the note counting incomplete days.
+ screen-reader caption and column heads, the note counting days with no
+ complete record, the empty line.
- Paying accounts list: heading, link, column heads, statuses (Paid,
Cancels at renewal, Payment failing), the footnote, "paying since %s".
- Earned panel: heading per month (`%s so far, earned`), lines (Recurring
@@ -235,6 +245,12 @@ Every later task takes its strings from this record through
`billingPagesCopyBuilt`, with its two tests
- Create: `internal/provision/billing_dashboard_2_census_test.go`; modify
`internal/provision/plan9_b8_census_test.go`
+- Modify: `internal/console/perfwalk_test.go` (`perfTargets` ~485: the
+ three routes expect `http.StatusNotFound` on its billing-off fixture),
+ `internal/console/opshell_test.go` (`assertOpShell` ~126 builds `want`
+ from `opRailFor` with the page's shell flags instead of the raw
+ `opRail`; `TestEveryOperatorPageRendersInTheShell` expects 404 for the
+ three billing routes, which billing-off consoles do not have)
- Test: `internal/console/opbilling_test.go`, `internal/console/opshell_test.go`
**Interfaces:**
@@ -270,8 +286,13 @@ Every later task takes its strings from this record through
test mode shows the test-mode line, live mode does not.
- `TestOpRailBillingGate` (in `opshell_test.go`): rail with `Billing` has
the item second; without it, absent; `/fleet/index` likewise.
+ - `TestEveryBillingPageRendersInTheShell` (in `opshell_test.go`): with
+ `enableBilling` on the fixture, each billing route is 200 and passes
+ `assertOpShell` with the Billing item in the rail and current.
+ - The existing walks with billing off: `TestEveryOperatorPageRendersInTheShell`
+ and the `perfwalk` screen walk pass with the 404 expectations.
- `TestApprovedBillingPagesCopy` (inventory and built rows).
-- [ ] **Step 2: Run** `go test ./internal/console . -run 'TestBillingRoutes|TestOpRail|TestApprovedBillingPagesCopy|TestClaimConsoleMutationInvariant' -count=1` → FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console . -run 'TestBillingRoutes|TestOpRail|TestEvery.*InTheShell|Perf.*Walk|TestApprovedBillingPagesCopy|TestClaimConsoleMutationInvariant' -count=1` → FAIL.
- [ ] **Step 3: Implement**, then the census:
`go test ./internal/provision -run TestPlan9B8RecordWriteCensus -count=1`,
re-pin what it names (expect `NewServer`), rerun.
@@ -286,103 +307,125 @@ Every later task takes its strings from this record through
**Interfaces:**
- Consumes: Plan 1 `paymentRow`, `billingFact`, `eurRates`, `payingNow`,
- `billingGroupOf`, `arrTotals`, `arrSnapshot`, `accountDay`; Plan 3 `carlosPlatformCostUSD`, `costBasisLabel`,
- `costBasisHint`, `s.cfg.CostScope`.
+ `billingGroupOf`, `arrTotals`, `arrSnapshot`, `accountDay`,
+ `moneyInputs`, `moneyReady`; 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 approved "no rate yet"; not `ok` → not `OK`,
- `Hint` from `costBasisHint`.
+ → not `OK`, `Hint` the rates reason; not `ok` → not `OK`, `Hint` from
+ `costBasisHint`.
+ - `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`.
+ - **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
+ }
+ // 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
+ ```
+ 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`.
- `type moneyMonth struct { Month string /* "2006-01" */; Subscriptions,
- OnceOff, Refunds, Tax, Fees, Net int64 /* euro cents */; EURKnown bool;
- Platform platformCost; Cash int64; CashShown bool }`.
+ OnceOff, Refunds, Tax, Fees, Net int64 /* euro cents */; Currencies
+ []string /* settled currencies seen */; Platform platformCost }`.
- `func moneyByMonth(rows []paymentRow, months []string, r eurRates, platform map[string]platformCost) []moneyMonth`
- — per row, in euros from `Settled`/`SettledTax`/`Fee` and
- `SettledCurrency`: subscription and once-off rows add `Settled −
- SettledTax` to their column; refunds and reversals add `Settled −
- SettledTax` to `Refunds` (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`. `CashShown` only with `Platform.OK` and `EURKnown`;
- `Cash = Net − Platform.Cents`. A row whose currency has no rate makes
- `EURKnown` false.
+ — sums only; whether a sum may be shown is the gate's. Per row, in
+ euros from `Settled`/`SettledTax`/`Fee` and `SettledCurrency`:
+ subscription and once-off rows add `Settled − SettledTax` to their
+ column; refunds and reversals add `Settled − SettledTax` to `Refunds`
+ (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; Profit int64; ProfitShown bool }`.
- - `func earnedSoFar(arr arrTotals, m moneyMonth, now time.Time) earnedView`
- — `MRR = round(arr.EUR / 12 × day-of-month / days-in-month)`, marked
- incomplete unless `arr.Complete()`; `Profit = MRR + OnceOff + Refunds −
- Platform.Cents`, shown only with `Platform.OK && arr.Complete() &&
- m.EURKnown`.
- - `type monthEarning struct { Recurring int64 /* euro cents */; Known,
- Partial bool }`
- - `func accountEarnings(month string, days []accountDay, snaps []arrSnapshot, firstDay string) (by map[int64]monthEarning, covered bool)`
- — pure. `covered` is false when `firstDay` is `""` or after the
- month's last day: every account's earnings are unknown. Otherwise, for
- each day of the month on or after `firstDay`, the rows of that day's
- snapshot (or, for a day with none, of the latest earlier snapshot day)
- add `AnnualEUR / 365` (summed exactly, rounded once at the end) to each
- `Paying` account's `Recurring`; a used row with `!EURKnown` or `Annual
- == -1` makes that account `Known false`; days before `firstDay` make
- every account `Partial`. An account with no rows in a covered month
- earned 0 recurring (`Known true`).
+ 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`.
+ - `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.
- `type accountMoney struct { Fact billingFact; Group billingGroup;
- Earns, Costs, Margin int64 /* euro cents, the month */; CostKnown,
- EURKnown bool; NearUsed, NearLimit int64; NearCap capID }`.
- - `accountMoney` gains `EarnsKnown, EarnsPartial bool`.
- - `func accountMoneyRows(facts []billingFact, exemptID int64, earned map[int64]monthEarning, covered bool, monthRows []paymentRow, costUSD map[string]float64, near map[int64]capState, r eurRates) []accountMoney`
+ 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` =
- its `earned[id].Recurring` plus that month's once-off less refunds,
- each `Settled − SettledTax`; `EarnsKnown` = `covered` and the
- account's `Known` and every once-off row converted; `EarnsPartial`
- from `Partial`; `Margin` unknown whenever `Earns` or `Costs` is; `Costs` = `costUSD[sqid]` in euros (`CostKnown`
- false when `costUSD` is nil; an account absent from a non-nil map
- costs 0); `Margin = Earns − Costs`; `NearCap`, `NearUsed`, `NearLimit`
- from `near` (zero when absent). `monthRows` is the last complete
- month's payments, so every per-account figure is that month's.
+ `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.
- Decision recorded: the earned view subtracts refunds, matching the
per-account rule (spec §4.6 per-account says "less refunds").
- [ ] **Step 1: Write the failing tests**
- `TestEURText` (0, 2400, 120000, −18800); `TestMinorText`.
+ - `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.
- `TestMoneyByMonth`: a 2800 usd first payment settled 2610 eur fee 106,
a 504-tax eur once-off, a refund, a fee row of −45 in one month →
- exact columns; an empty month → zeros; `CashShown` false with a
- platform cost that is not `OK`, true with one that is.
- - `TestEarnedSoFar`: ARR 2400 on 9 Nov → MRR `round(200 × 9 / 30) = 60`;
- `TestEarnedHiddenWithoutBasis`; `TestEarnedHiddenWithPartialRates`
- (rates hold usd but not gbp, a gbp paying account: `arr.EURKnown`
- false → profit hidden though `Platform.OK`; a month holding a gbp
- payment → `EURKnown` false, cash hidden).
+ exact columns; an empty month → zeros.
- `TestMoneyByMonthRefundTaxExclusive`: a 12000 eur charge with 2000 tax,
fully refunded with refund tax -2000 → `OnceOff 10000`, `Refunds
-10000`, `Tax 0`, `Net` = −fees.
- - `TestAccountEarningsNovemberSignup`: October fully covered by
- snapshots without account A, A first paid 7 Nov → A's October
- recurring 0, `Known`.
- - `TestAccountEarningsNovemberTermination`: October snapshots carry B
- paying eur 3650 every day, B ended on 3 Nov (today's fact not paying)
- → B's October recurring `31 × 3650 / 365 = 310`.
- - `TestAccountEarningsBeforeHistory`: first snapshot 9 Nov → October not
- `covered`; November partial; a day missing in a covered month carries
- the previous day forward.
- - `TestAccountMoneyRows`: October recurring 200 from `earned`, an
- October once-off 1000 (tax 0) and cost 1.10 usd at 1.10 → `Earns
- 1200`, `Costs 100`, `Margin 1100`; not `covered` → `EarnsKnown false`
- and margin unknown; `costUSD` nil → `CostKnown false`; a `near` row
- fills `NearCap`.
+ - `TestEarnedSoFar`: ARR 2400 on 9 Nov → MRR `round(200 × 9 / 30) = 60`.
+ - `TestAccountEarningsOctober`: complete snapshots for every October day,
+ account A `InARR` with `AnnualEUR 120000` (€1,200) each day →
+ `by[A] == 10000` (€100.00).
+ - `TestAccountEarningsNovemberSignup`: October covered without account
+ B, B first paid 7 Nov → `by[B] == 0`.
+ - `TestAccountEarningsNovemberTermination`: October covered with C
+ `InARR` €1,200 every day, C ended 3 Nov (today's fact not paying) →
+ `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`.
- `TestPlatformCostEUR` (bills seeded as Plan 3's tests seed them): a
- 110 usd bill under `CostScope{AccountCarlosOnly: true}` at usd 1.10 →
- `OK`, `Cents 10000`, `Label` C2; the zero scope → not `OK`, `Hint` C4;
- no bill → not `OK`, `Hint` C6; no usd rate → not `OK`, `Hint` "no rate
- yet".
-- [ ] **Step 2: Run** `go test ./internal/console -run 'TestEURText|TestMinorText|TestMoneyByMonth|TestEarned|TestAccountEarnings|TestAccountMoneyRows|TestPlatformCostEUR' -count=1` → FAIL.
+ 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, and the platform cost seam`.
+- [ ] **Step 5: Commit** `console: billing page money, the money gate helper, platform cost`.
### Task 4: The overview
@@ -405,67 +448,85 @@ Every later task takes its strings from this record through
- `func (s *Store) NearestCaps() (map[int64]capState, error)` — per
account, the `plan_cap_state` row with the highest `used / cap_limit`
among `cap_limit > 0`.
- - `type opBillingInput struct { Now time.Time; Rev billingRevenue; Facts
+ - `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 */; LastMonth string; LastRows []paymentRow /* last
- complete month, Kind "" */; MonthsRows []paymentRow /* the six
- months, Kind "all": fee rows included */; Snaps []arrSnapshot /* the
- last 90 days */; Earned map[int64]monthEarning; Covered bool; FirstDay
- string; Recent []paymentRow /* 5 */; CostUSD
- map[string]float64; Platform map[string]platformCost; Funnel [3]int;
- Near map[int64]capState }`
+ 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 }`
- Row types the later tasks reuse: `type opBillingAccountRow struct {
Href, Name, Plan, PlanNote string; Apps int; Earns, Costs, Margin,
Renews, Joined string; Status opPill }` (`PlanNote` the packs and seats
line, or "paying since" on the overview); `type opBillingPaymentRow
- struct { Href /* "" when not a link */, When, Account, What, Charged,
- Net, Fee string; Status opPill }`; `type opBillingReasonRow struct {
- Href, Label string; Count int; Cost, Biggest string }`. Money cells are
- already formatted (`eurText`, `minorText`, or the approved "unknown" /
- "no rate yet").
+ struct { Href /* "" when not a link */, When, Account, What string;
+ Charged, Net, Fee opMoneyFigure; Status opPill }`; `type
+ opBillingReasonRow struct { Href, Label string; Count int; Cost
+ opMoneyFigure; Biggest string }`. In the account row, `Earns`, `Costs`
+ and `Margin` are `opMoneyFigure`s too. Every money cell is an
+ `opMoneyFigure` from `opMoney`; templates print `.Text`, and `.Why`
+ beside it when not shown.
+ - `opBillingView.Figures []opMoneyFigure`: every figure the builder made,
+ 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`: ARR (EUR; delta = now − `MonthStart.EUR`, shown
- only when both are `Complete()`; note = each currency in
- `ByCurrency`, `minorText`, joined, plus the rate note, plus the
- incomplete note when `!Complete()`), MRR (`EUR / 12`, the same
- incomplete marking), Received this month (`Months[0].Net`),
- Paying accounts (`Paying of Accounts (pct)`, change vs
- `MonthStart.Paying`), Needs attention (`Attention`).
+ 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 bar per snapshot day, `N` the euro ARR,
- scaled as `dashBars` scales; the `co-bars` markup and screen-reader
- table of the Dashboard's new-people chart, with an "incomplete"
- column; a note counting the days that are not `Complete()`. With no
- snapshot yet, `op_empty` with the approved line.
+ []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.
2. `Paying []opBillingAccountRow`: the 5 most recent `FirstPaid` among
- paying accounts, with plan, packs and seats, earns, costs
- (estimate), margin, renews (`PeriodEnd`), status (Payment failing
- for `past_due`, Cancels at renewal, else Paid).
- 3. `Earned earnedView` beside `Funnel` (signed up, made an app, active
- last 30 days, paying).
- 4. `Months []moneyMonth`, each linking to
+ 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).
+ 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`.
5. `Recent`: when, account, what (reason word, plan label for
- subscription rows, detail for domain rows), amount (`minorText`),
- status.
+ subscription rows, detail for domain rows), amount (`minorText`,
+ `needRevenue`), status.
6. `Weeks []dashBar`: `dashBars` over 12 `DayCount`s, one per week
ending today, counting `FirstPaid`.
7. `Reasons []opBillingReasonRow`: Free, Sponsored, House, Ours with
- count, cost to run (last month, estimate) and the costliest account;
- then Shared and idle (`Platform[LastMonth] − Σ all accounts' costs`)
- only with `Platform[LastMonth].OK`. Rows link to `/fleet/billing/accounts?tab=<group>`.
+ 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
+ `/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.
+ `billingusage.go:193` maps them) and `capAmount` for used and limit
+ (usage, not money: shown as is).
- `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` and `FirstSnapshotDay` for `accountEarnings` over the
- last complete month, `LoadEconomics(ctx, "last")` (failure → logged,
- `CostUSD` nil, costs show "unknown"); renders `ops_billing`.
+ `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`.
- `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
@@ -475,30 +536,42 @@ Every later task takes its strings from this record through
- [ ] **Step 1: Write the failing tests**
- `TestBuildOpBillingView`: one eur paying account (2400, first paid 7
- Nov), 37 others across groups, a rate, a CARLOS-only bill (account scope) → tile values
- and notes as approved, `Paying` one row with status Paid, `Weeks` with
- 1 in the last bar, `Reasons` four rows plus Shared and idle.
- - `TestOverviewHidesCostWithoutBasis`: a whole-account bill under the zero scope → no AWS bill line,
- no profit, no cash column values, no Shared and idle, Plan 3's C4
- hint present.
+ Nov), 37 others across groups, every gate input good, an `account`
+ 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`.
+ - `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
+ holding D shows paying-list earns and margins with the history reason.
- `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 snapshot days, the middle one with
- `amounts_known 0` → three bars, the note counts one incomplete day; no
+ - `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.
- - `TestOverviewUnknownAmount`: a paying account with `Annual -1` → the
- ARR and MRR tiles carry the incomplete note; the delta is not shown.
- - `TestOverviewNoRate`: no rates → converted tiles show "no rate yet";
- the per-currency note is present.
- - `TestOverviewEmpty`: no payments, no paying accounts, no Economics →
- empty states, `0 of N (0%)`, six €0.00 months.
+ - `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
first, and the "All paying accounts" link.
- `TestOverviewRowsAreLinks`: rendered HTML: each list row has
`co-rowlink` and a first `a.rst-nm` with the documented href.
- `TestBillingFunnel`, `TestNearestCaps` (store).
-- [ ] **Step 2: Run** `go test ./internal/console -run 'TestBuildOpBillingView|TestOverview|TestBillingFunnel|TestNearestCaps' -count=1` → FAIL.
+- [ ] **Step 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`.
@@ -522,12 +595,19 @@ Every later task takes its strings from this record through
Prev, Next string; TestMode bool; RateNote string; MonthName string }`
- `func buildOpBillingAccounts(rows []accountMoney, group billingGroup, sort string, page int, q url.Values) opBillingAccountsView`
— 50 per page; sorts descending except `joined` (newest first) and
- `limit` (highest ratio first, accounts with no cap row last); unknown
- earns, costs or margins sort last; ties by account id. Columns: account, plan, apps, earns, costs (estimate),
- margin, joined. An unknown `tab` or `sort` falls back to the default.
+ `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
+ `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),
`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.
@@ -554,12 +634,17 @@ 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. Reads `Payments` with `Kind ""` (no fee rows).
+ 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).
- 50 per page, newest first.
- [ ] **Step 1: Write the failing tests**: `TestBillingPaymentsFilters`
(month, each kind, both), `TestBillingPaymentsPages`,
- `TestPaymentsUnmatchedAndDeleted`, `TestBillingPaymentsBadQuery`.
+ `TestPaymentsUnmatchedAndDeleted`, `TestBillingPaymentsBadQuery`,
+ `TestBillingPaymentsGated` (stale reconcile → money cells not
+ available, rows still listed).
- [ ] **Step 2: Run** `go test ./internal/console -run 'TestBillingPayments|TestPaymentsUnmatched' -count=1` → FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run** the same → PASS.
@@ -577,20 +662,26 @@ 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`
- (or "no rate yet"; with the incomplete marking unless `Complete()`), the test-mode word when `TestMode`, `Href:
+ 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:
"/fleet/billing"`. `handleDashboard` appends it to `d.Stats` only when
`s.billing != nil`; a `billingRevenueNow` error is logged and the tile
left out.
- [ ] **Step 1: Write the failing tests**: `TestDashboardTileOnlyWithBilling`
(off → five stats, no `/fleet/billing` link; on → six, the last links
- to Billing with the approved note), `TestOpStatLinks` (an `opStat` with
- `Href` renders as one link; without, unchanged markup).
+ to Billing with the approved note; a stale reconcile → the
+ not-available text), `TestOpStatLinks` (an `opStat` with `Href` renders
+ as one link; without, unchanged markup).
- [ ] **Step 2: Run** `go test ./internal/console -run 'TestDashboardTile|TestOpStat|TestDashboard' -count=1` → FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run** the same → PASS.
- [ ] **Step 5: Commit** `console: paying accounts tile on the dashboard`.
+- [ ] **Step 6: The landing gate** (AGENTS.md "Build & test"), once, on
+ the branch tip: `go build ./...` and `make test` → both clean. Fix
+ anything they find in its own commit before the branch is described and
+ merged.
---