| index c3013dd17..3456b5238 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 |
| @@ -5,7 +5,7 @@ |
| **Goal:** On a console with billing on, record every payment, refund and |
| provider fee from the billing provider, store each subscription's yearly |
| amount, sort every account into one group, keep daily euro reference rates |
| -and a daily ARR snapshot, and show the result through `carlos billing |
| +and daily ARR and per-account snapshots, and show the result through `carlos billing |
| revenue` and `carlos billing payments`. |
| |
| **Architecture:** Neutral records and three new read-only `billing.Provider` |
| @@ -39,8 +39,20 @@ and §5; Plan 3 (written separately) covers §4.5. |
| - **Never gate readiness on the new reads.** A restricted key without the |
| new permissions fails the money pass (logged, `jobFailed`), never |
| `Check`, the webhook's other kinds or the subscription sync. |
| -- **Idempotent on the provider id.** `billing_payments.provider_id` is the |
| - primary key; a second record of the same id writes nothing. |
| +- **One row per balance movement, recorded once.** `billing_payments` is |
| + keyed by the provider's balance-movement id (Stripe's balance |
| + transaction): a charge, a refund's debit, a failed refund's reversal and |
| + a provider fee are each their own row; a second record of the same |
| + movement writes nothing. |
| +- **Revenue is tax-exclusive in every direction.** Charges, refunds and |
| + 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. |
| - **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 |
| @@ -50,7 +62,11 @@ and §5; Plan 3 (written separately) covers §4.5. |
| current subscription. `billing_accounts.state` is not used for it. |
| - **ARR** (spec §4.2): yearly amount after discounts, before tax, over paying |
| accounts, excluding any with `cancel_at_period_end` and the exempt |
| - account. `past_due` stays in. |
| + account. `past_due` stays in. ARR history starts at the first real |
| + snapshot; nothing rebuilds earlier days (spec §4.2, amended on this |
| + branch 2026-11-09: "History starts on the day this ships"). |
| +- **Snapshots:** today's (UTC) rows are replaced on every pass until the |
| + day ends; earlier days are frozen. |
| - **Groups** (spec §4.7), first match wins: Ours (`planExempt`), Paying |
| (paying and yearly amount not 0; unknown counts as not 0), House |
| (`billing_house` row), Sponsored (`account_plans.source = 'sponsored'` or |
| @@ -93,17 +109,20 @@ and §5; Plan 3 (written separately) covers §4.5. |
| list fits; the cursor never passes a movement that was not recorded |
| (Task 5 `TestReconcileHalvesWindowOnIncomplete`, |
| `TestReconcileCursorHoldsOnError`). |
| -3. **A refund whose charge was never recorded** (refunded before the |
| - backfill read it, or the webhook lost). The refund is recorded against |
| - the same account, from the charge read the refund triggers (Task 5 |
| +3. **A refund that failed, none of it recorded locally** (the backfill |
| + meets it after the fact). The charge, the refund's debit and its |
| + reversal are each recorded once, so the money nets to the charge (Task 5 |
| + `TestReconcileFailedRefundNeverRecorded`); a refund whose charge was |
| + never recorded lands on the charge's account (Task 5 |
| `TestReconcileRefundOfUnrecordedCharge`). |
| 4. **The ECB is down or answers nonsense.** The last good rates stay; a |
| rate of 0, a negative rate or an empty set is refused, never stored |
| (Task 6 `TestECBRefusesBadRates`, `TestRatesPassKeepsLastGood`). |
| -5. **A house account (100% coupon) and a cancel-at-renewal account.** The |
| - house account has yearly amount 0 and no payment, so it is House, not |
| - Paying; the cancelling account is Paying but outside ARR (Task 1 |
| - `TestAnnualOf`, Task 7 `TestARROf`). |
| +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 |
| + account (100% coupon) is House, and a cancelling one is Paying outside |
| + ARR (Task 1 `TestAnnualOf`, Task 7 `TestARROf`). |
| |
| --- |
| |
| @@ -202,21 +221,23 @@ and §5; Plan 3 (written separately) covers §4.5. |
| - Reasons: `ReasonFirst "first"`, `ReasonRenewal "renewal"`, |
| `ReasonChange "change"`, `ReasonDomain "domain"`, `ReasonOther "other"`, |
| `ReasonReversed "reversed"` (a refund that failed and came back). |
| - - `type Payment struct { ID, Movement string; Kind PaymentKind; Reason |
| - string; Customer, Subscription, PaymentIntent, Charge string; Amount, |
| - Tax int64; Currency string /* as charged, signed: negative for refunds |
| - and fees */; Settled, Fee, SettledTax int64; SettledCurrency string; At |
| - time.Time; LiveMode bool }`. `ID` is the provider id of what was paid |
| - or refunded, or the movement id for a fee or a reversal. |
| + - `type Payment struct { Movement string /* the provider's balance-movement |
| + id: the record's key */; Source string /* the charge or refund it |
| + settles; "" for a fee */; Kind PaymentKind; Reason string; Customer, |
| + Subscription, PaymentIntent, Charge string; Amount, Tax int64; Currency |
| + string /* as charged, signed: negative for refund debits and fees, |
| + positive for reversals */; Settled, Fee, SettledTax int64; |
| + SettledCurrency string; At time.Time; LiveMode bool }`. |
| - `type ChargeRecord struct { Captured bool; Charge Payment; Refunds |
| - []Payment }` (refunds already settled, each `Kind PaymentRefund`). |
| + []Payment }` — `Refunds` holds, per refund, its debit (`Kind refund`, |
| + negative) and, when the refund failed, its reversal (`Kind refund`, |
| + `Reason reversed`, positive, the debit's tax negated), each with its |
| + own `Movement`. |
| - `func SettledShare(part, whole, settled int64) int64` — `round(part × |
| settled / whole)`, 0 when `whole` is 0 (settled tax, and a refund's |
| - tax share). |
| - - `func FeePayment(m Movement, live bool) Payment` and |
| - `func ReversalPayment(m Movement, refunded *Payment, live bool) Payment` |
| - (copy customer, subscription and charge from the refunded row when |
| - known). |
| + tax share; the sign follows `settled`). |
| + - `func FeePayment(m Movement, live bool) Payment` (`Movement m.ID`, |
| + `Source ""`, `Kind fee`, `Settled m.Amount`, `Fee 0`). |
| - `EventPayment EventKind = "payment"`: `Event.Object` is a charge id. |
| - Produces (`billingtest.Fake`): fields `Movements []billing.Movement`, |
| `Charges map[string]billing.ChargeRecord`, `AccountOpened time.Time`, and |
| @@ -229,10 +250,8 @@ and §5; Plan 3 (written separately) covers §4.5. |
| |
| - [ ] **Step 1: Write the failing tests**: `TestSettledShare` (tax 400 of |
| 2800 charged, 2610 settled → 373; whole 0 → 0; negative settled keeps |
| - its sign); `TestFeePaymentAndReversal` (fee movement -45 eur → |
| - `Kind fee, Settled -45, Fee 0, ID == movement id`; reversal copies the |
| - refunded row's customer and charge, `Reason reversed`, positive |
| - `Settled`); `TestFakeMoneyMovementsWindowAndPages` (five movements, a |
| + its sign); `TestFeePayment` (fee movement -45 eur → `Kind fee, Settled |
| + -45, Fee 0, Movement == m.ID, Source ""`); `TestFakeMoneyMovementsWindowAndPages` (five movements, a |
| window holding three returns those three oldest first; `PageSize 1` and |
| eleven movements → `ErrIncomplete`); `TestFakeParsesPaymentEvent`. |
| - [ ] **Step 2: Run** `go test ./internal/billing/... -run 'TestSettledShare|TestFeePayment|TestFakeMoney|TestFakeParsesPayment' -count=1` → FAIL. |
| @@ -268,7 +287,8 @@ and §5; Plan 3 (written separately) covers §4.5. |
| `MovementOther`. |
| - `ChargePayments(ctx context.Context, charge string) (billing.ChargeRecord, error)` |
| — `GET /v1/charges/<id>` with `expand[]` `balance_transaction`, |
| - `invoice`, `refunds`, `refunds.data.balance_transaction`; refunds past |
| + `invoice`, `refunds`, `refunds.data.balance_transaction`, |
| + `refunds.data.failure_balance_transaction`; refunds past |
| the first page through `GET /v1/refunds?charge=<id>` (`listAll`, same |
| expansion). 404 → `billing.ErrNotFound`. `Captured` is |
| `captured && balance_transaction != null`. Kind and reason from the |
| @@ -276,10 +296,15 @@ and §5; Plan 3 (written separately) covers §4.5. |
| `subscription_cycle` → subscription/renewal, `subscription_update` → |
| once-off/change, other or no invoice → once-off/other. `Tax` is the |
| invoice's `tax` (0 without an invoice); `Subscription` the invoice's |
| - subscription; `SettledTax` by `billing.SettledShare`. A refund is |
| - `Kind refund`, `Amount` and `Settled` negative, `Tax` its share of the |
| - charge's tax, refunds without a balance transaction or with status |
| - `failed` or `canceled` left out. |
| + subscription; `SettledTax` by `billing.SettledShare`; `Movement` the |
| + charge's balance transaction, `Source` the charge. Every refund with a |
| + balance transaction gives its debit (`Kind refund`, `Amount` and |
| + `Settled` negative, `Tax` its share of the charge's tax, `Movement` its |
| + balance transaction, `Source` the refund), whatever its status now; a |
| + refund with a `failure_balance_transaction` also gives the reversal |
| + (`Reason reversed`, positive, the debit's tax negated, `Movement` the |
| + failure transaction). A refund with neither (pending without a |
| + movement yet, canceled) gives nothing. |
| - `AccountCreated(ctx context.Context) (time.Time, error)` — `created` |
| of `GET /v1/account`. |
| - `ParseEvent`: `charge.succeeded`, `charge.captured`, `charge.refunded` |
| @@ -301,7 +326,12 @@ and §5; Plan 3 (written separately) covers §4.5. |
| "sub_1"`, `Settled 2610`, `Fee 106`, `SettledCurrency "eur"`. |
| - `TestChargePaymentsTaxAndRefund`: eur charge 2904 with invoice tax 504 |
| and one 2904 refund → charge `Tax 504`, `SettledTax 504`; refund |
| - `Amount -2904`, `Tax -504`, `Kind refund`, `Charge` set. |
| + `Amount -2904`, `Tax -504`, `SettledTax -504`, `Kind refund`, `Charge` |
| + set, `Movement` the refund's balance transaction. |
| + - `TestChargePaymentsFailedRefund`: a refund with status `failed`, a |
| + `balance_transaction` (-2904) and a `failure_balance_transaction` |
| + (+2904) → two refund rows, debit and reversal, distinct `Movement`s, |
| + taxes `-504` and `+504`; they sum to 0. |
| - `TestChargePaymentsUpdateIsOnceOff`: `subscription_update` → |
| once-off/change; a charge with no invoice → once-off/other, `Tax 0`. |
| - `TestChargePaymentsUncaptured`: `captured false` → `Captured false`, |
| @@ -334,7 +364,7 @@ and §5; Plan 3 (written separately) covers §4.5. |
| - Consumes: Task 2 `billing.Payment`. |
| - Produces: |
| - `func (s *Store) migrateBillingMoney() error` creating |
| - `billing_payments (provider_id TEXT PRIMARY KEY, movement_id TEXT NOT |
| + `billing_payments (movement_id TEXT PRIMARY KEY, source_id TEXT NOT |
| NULL, kind TEXT NOT NULL, reason TEXT NOT NULL, account_id INTEGER NOT |
| NULL DEFAULT 0, customer, subscription, payment_intent, charge TEXT NOT |
| NULL DEFAULT '', amount INTEGER NOT NULL, tax INTEGER NOT NULL, |
| @@ -348,48 +378,57 @@ and §5; Plan 3 (written separately) covers §4.5. |
| - `type paymentRow struct { billing.Payment; AccountID int64; Detail |
| string; RecordedAt time.Time }` (`AccountID` 0: unmatched). |
| - `func (s *Store) RecordPayment(p billing.Payment, now time.Time) (bool, error)` |
| - — one transaction: match, then `INSERT ... ON CONFLICT(provider_id) DO |
| - NOTHING`; true when a row was written. Matching, first hit wins: |
| + — one transaction: match, inherit tax, then `INSERT ... ON |
| + CONFLICT(movement_id) DO NOTHING`; true when a row was written. |
| + Matching, first hit wins: |
| 1. `p.PaymentIntent` equals a `domain_purchases.payment_intent` → that |
| purchase's account, `Reason domain`, `Detail` the domain; when |
| `p.Tax == 0`, the purchase's currency is `p.Currency` and `p.Amount |
| > purchase.amount`, `Tax = p.Amount − amount` and `SettledTax` by |
| `billing.SettledShare`; |
| 2. `p.Customer` equals a `billing_accounts.customer` → that account; |
| - 3. `p.Charge` names a recorded row → that row's account (and its |
| - subscription when `p.Subscription` is empty); |
| + 3. `p.Charge` is the `source_id` of a recorded charge row → that |
| + row's account (and its subscription when `p.Subscription` is empty); |
| 4. otherwise 0. |
| - - `func (s *Store) HasPayment(providerID string) (bool, error)` |
| - - `func (s *Store) PaymentByID(providerID string) (*paymentRow, error)` (nil when none) |
| + Then, for a refund or reversal whose `Tax` is 0 when the refunded |
| + charge's row has `Tax ≠ 0` (a domain charge's derived tax among them): |
| + `Tax = SettledShare(charge.Tax, charge.Amount, p.Amount)` and |
| + `SettledTax = SettledShare(Tax, p.Amount, p.Settled)`, so a refund |
| + leaves the same share of tax as its charge carried. |
| + - `func (s *Store) HasPayment(movement string) (bool, error)` |
| - `func (s *Store) RematchPayments() (int, error)` — re-runs rules 1-3 for |
| rows with `account_id = 0`; returns how many matched. |
| - `type paymentFilter struct { From, To time.Time /* zero: open */; Kind |
| - string /* "": every kind but fee; "subscription", "once_off", |
| + string /* "": every kind but fee (the payment lists); "all": every |
| + row, fees included (the money sums); "subscription", "once_off", |
| "refund", "fee", "unmatched" (account 0, fees excluded) */; AccountID |
| int64 /* 0: all */; Offset, Limit int /* Limit 0: no limit */ }` |
| - `func (s *Store) Payments(f paymentFilter) ([]paymentRow, int, error)` |
| - — newest first by `at` then `provider_id`, and the count matching. |
| + — 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`. |
| - Gate rows: `billing_payments` {NonApp: "money received, refunded or |
| - kept as fees, keyed by the provider's id and the account; names no |
| + kept as fees, one row per provider balance movement, with the account; names no |
| app"}, `billing_payment_cursor` {NonApp: "how far the payment |
| reconcile has read; names no app"}. |
| - Account deletion leaves payment rows alone: they are the money record. |
| |
| - [ ] **Step 1: Write the failing tests** |
| - `TestRecordPaymentIdempotent`: the same `billing.Payment` twice → true |
| - then false, one row; a second record with other amounts does not |
| - change the first. |
| + then false, one row; a second record of the same `Movement` with other |
| + amounts does not change the first. |
| - `TestRecordPaymentMatchesCustomer`, `TestRecordPaymentMatchesDomainPurchase` |
| (purchase amount 1500 usd, charge 1800 usd, tax 0 → `Tax 300`, |
| `Reason domain`, `Detail` the domain), `TestRecordPaymentRefundFollowsCharge` |
| (refund with no customer, `Charge` recorded on account A → A), |
| + `TestRecordPaymentDomainRefundInheritsTax` (a 12000 eur domain charge |
| + whose derived tax is 2000, fully refunded with `Tax 0` → refund `Tax |
| + -2000`; charge plus refund `Settled − SettledTax` sums to 0), |
| `TestRecordPaymentUnmatched` (→ 0, listed by `Kind "unmatched"`). |
| - `TestRematchPayments`: unmatched row, then the customer is bound → |
| `RematchPayments` returns 1 and the row has the account. |
| - `TestPaymentsFilter`: month bounds, each kind, `""` leaving out fee |
| - rows, account, offset/limit, total, newest first. |
| + rows, `"all"` including them, account, offset/limit, total, newest first. |
| - `TestPaymentCursorRoundTrip`: none → `ok false`; set, read back. |
| - `TestPaymentsSurviveAccountReap`: `ReapAccount` keeps the rows. |
| - [ ] **Step 2: Run** `go test ./internal/console -run 'TestRecordPayment|TestRematchPayments|TestPaymentsFilter|TestPaymentCursor|TestPaymentsSurvive' -count=1` → FAIL. |
| @@ -419,8 +458,10 @@ 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` (Task 7), each |
| - failure logged and passed to `jobFailed`, none stopping the next. |
| + `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. |
| - `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 − |
| @@ -429,11 +470,11 @@ and §5; Plan 3 (written separately) covers §4.5. |
| `MoneyMovements(from, to)`. On `billing.ErrIncomplete` halve the |
| window and retry the same `from`; below `billingMoneyMinWindow` |
| return the error. Any other error returns it. |
| - 3. For the window's movements, oldest first: charge and refund kinds |
| - whose `Source` is not yet recorded add `Charge` to a set; fee → |
| - `RecordPayment(billing.FeePayment(m, live))`; refund failure → |
| - `RecordPayment(billing.ReversalPayment(m, PaymentByID(m.Source), live))`; |
| - other → logged once per type per run. |
| + 3. For the window's movements not yet recorded (`HasPayment(m.ID)`), |
| + oldest first: charge, refund and refund-failure kinds add `m.Charge` |
| + to a set (the charge read records every movement of that charge); |
| + fee → `RecordPayment(billing.FeePayment(m, live))`; other → logged |
| + once per type per run. |
| 4. `recordCharge` for each charge in the set; the first error returns |
| it, leaving the cursor where it was. |
| 5. `SetPaymentCursor(to)`, `from = to`, window back to |
| @@ -442,7 +483,8 @@ and §5; Plan 3 (written separately) covers §4.5. |
| - `func (s *Server) recordCharge(ctx context.Context, charge string, now time.Time) error` |
| — `ChargePayments`; `billing.ErrNotFound` or `!Captured` → nil; a |
| record whose `LiveMode` is not the console's → logged and skipped, |
| - nil; else `RecordPayment` for the charge and every refund. |
| + nil; else `RecordPayment` for the charge, then every refund row (the |
| + charge first, so refunds can inherit its account and tax). |
| - Webhook: `case billing.EventPayment:` → `recordCharge(s.billingClock(r.Context()), ev.Object, now)`; |
| error → 503 (the provider redelivers); success → 204. Its doc comment |
| gains the case. |
| @@ -463,8 +505,14 @@ and §5; Plan 3 (written separately) covers §4.5. |
| - `TestReconcileRefundOfUnrecordedCharge`: only a refund movement in the |
| window, its charge never recorded → charge and refund recorded, refund |
| on the charge's account. |
| - - `TestReconcileFeesAndReversals`: a fee movement → one fee row; a |
| - refund failure → a reversal row with the refunded row's account. |
| + - `TestReconcileFailedRefundNeverRecorded`: nothing recorded locally; |
| + the window holds the charge, the refund debit and the refund-failure |
| + movements; the fake's charge record carries the failed refund → three |
| + rows (charge, debit, reversal), each keyed by its movement, on the |
| + charge's account; `Settled` sums to the charge's; a second run adds |
| + nothing. |
| + - `TestReconcileFees`: a fee movement → one fee row; a second run adds |
| + nothing. |
| - `TestReconcileSkipsOtherMode`: a charge record with the other |
| `LiveMode` → nothing recorded, no error. |
| - `TestWebhookPaymentEventRecords` (204, row present), |
| @@ -571,28 +619,45 @@ 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 bool; RateDay string; Paying, Attention int }` — `Attention` |
| - counts paying accounts that are `past_due` or cancelling; `EURKnown` |
| - false when a currency in `ByCurrency` has no rate. |
| + 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`. |
| - `func arrOf(facts []billingFact, exemptID int64, r eurRates) arrTotals` |
| - Table `billing_arr_daily (day TEXT PRIMARY KEY, arr TEXT NOT NULL /* |
| JSON currency → minor */, arr_eur INTEGER NOT NULL, eur_known INTEGER |
| - NOT NULL, rate_day TEXT NOT NULL, paying INTEGER NOT NULL, rebuilt |
| - INTEGER NOT NULL DEFAULT 0, written_at INTEGER NOT NULL)`; gate |
| - {NonApp: "daily recurring revenue totals; names no app"}. |
| + 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"}. |
| + - 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"}. |
| - `type arrSnapshot struct { Day string; ARR map[string]int64; EUR int64; |
| - EURKnown bool; RateDay string; Paying int; Rebuilt bool }` |
| - - `func (s *Store) PutARRSnapshot(a arrSnapshot, now time.Time) (bool, error)` (insert or ignore) |
| + EURKnown, AmountsKnown bool; Unknown int; PaymentsCurrent bool; RateDay |
| + string; Paying int }` and `func (a arrSnapshot) Complete() bool` (all |
| + three flags). |
| + - `type accountDay struct { Day string; AccountID int64; Annual int64; |
| + Currency string; AnnualEUR int64; EURKnown, 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 |
| + an error (earlier days are frozen). `a.Day` after `today`: refused. |
| - `func (s *Store) ARRSnapshots(fromDay, toDay string) ([]arrSnapshot, error)` (inclusive, oldest first) |
| - - `func rebuildARR(rows []paymentRow, days []time.Time, r eurRates) []arrSnapshot` |
| - — pure, for each day: per currency, the pre-tax amounts (`Amount − |
| - Tax`) of subscription payments in the 365 days up to that day, less |
| - refunds of those charges; `Paying` the distinct accounts among them; |
| - `Rebuilt true`. |
| - - `func (s *Server) billingSnapshotPass(ctx context.Context, now time.Time) error` |
| - — writes today's (UTC) row once. When the table is empty it first |
| - writes rebuilt rows for the first of each month from the month of the |
| - earliest subscription payment through this month, skipping today. |
| + - `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. |
| - `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 }` |
| @@ -610,18 +675,27 @@ 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`; 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`, `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`. |
| + - `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`. |
| - `TestBillingFactsQuery`: an account per group, a deleted account |
| (absent), apps counted, `FirstPaid` the earliest subscription payment. |
| - - `TestRebuildARR`: one 2400 eur first payment on 7 Oct, a refunded 1000 |
| - usd payment → the 1 Nov point is `{eur:2400}`, `Paying 1`; the 1 Sep |
| - point is empty. |
| - - `TestSnapshotPassOncePerDay`: two passes on one day → one row; the |
| - next day → a second row; first ever pass with old payments → rebuilt |
| - month rows plus today's. |
| -- [ ] **Step 2: Run** `go test ./internal/console -run 'TestPayingNow|TestBillingGroupOf|TestARROf|TestBillingFactsQuery|TestRebuildARR|TestSnapshotPass' -count=1` → FAIL. |
| + - `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. |
| + - `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. |
| - [ ] **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`. |
| @@ -637,7 +711,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 |
| + 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 |
| 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). |
| @@ -677,13 +752,14 @@ and §5; Plan 3 (written separately) covers §4.5. |
| - Consumes: Task 4 `Payments`, Task 7 `billingRevenueNow`, Task 8 copy. |
| - Produces: |
| - `GET /api/cli/billing/revenue` (`billingDoor`): `{"arr":{"eur":2400}, |
| - "arr_eur":2400,"eur_known":true,"rate_day":"2026-11-06","mrr_eur":200, |
| - "paying":1,"accounts":38,"attention":0,"groups":{"paying":1,...}, |
| - "test_mode":false}`; amounts in minor units; `mrr_eur` is `arr_eur / 12` |
| - rounded. |
| + "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/payments?month=YYYY-MM&kind=K` (`billingDoor`; |
| - `kind` as `paymentFilter.Kind`, limit 500): an array of `{"id","at", |
| - "account","kind","reason","detail","amount","tax","currency","settled", |
| + `kind` as `paymentFilter.Kind`, limit 500): an array of `{"movement", |
| + "source","at","account","kind","reason","detail","amount","tax","currency","settled", |
| "fee","settled_currency"}`, newest first; `account` the sqid, "" when |
| unmatched or deleted. A bad month or kind is 400 with the approved text. |
| - `carlos billing revenue` and `carlos billing payments [-month YYYY-MM] |
| @@ -696,13 +772,14 @@ 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 member (not operator) → 404; billing |
| + 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 |
| off → 409 like `problems`. |
| - `TestAPIBillingPayments`: month and kind filters, unmatched shows `""`; |
| `month=2026-13` and `kind=x` → 400. |
| - `TestBillingRevenueCLI` and `TestBillingPaymentsCLI` (beside the |
| - `problems` CLI tests): output lines equal the approved copy; `-kind |
| - once-off` sends `once_off`. |
| + `problems` CLI tests): output lines equal the approved copy, the |
| + unknown-amounts line 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. |