carlos / platform Public

console: paying accounts, groups, ARR and its daily snapshot

The money gate (moneyReady: each figure declares its inputs and is
refused with the first incomplete one's reason) and checkGateInvariant;
BillingFacts, the five groups, paying (Billable and a subscription
payment received), ARR by currency and in euros; and the daily snapshot,
billing_arr_daily and billing_account_daily, which the money pass
rewrites for today after the rates. Earlier days are frozen.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 65a589c92656b4cecb2a0feae932c622e7ab091d parent 588dab2
8 files changed, +1,449 −5
  • internal/console/billingmoney.go +156 −0
  • internal/console/billingmoney_test.go +291 −0
  • internal/console/billingmoneypass.go +7 −2
  • internal/console/billingpayments_store.go +6 −2
  • internal/console/billingrevenue.go +430 −0
  • internal/console/billingrevenue_test.go +556 −0
  • internal/console/jobs_test.go +1 −1
  • internal/console/store_gate.go +2 −0
diff --git a/internal/console/billingmoney.go b/internal/console/billingmoney.go
new file mode 100644
index 000000000..f6ff01066
--- /dev/null
+++ b/internal/console/billingmoney.go
@@ -0,0 +1,156 @@
+package console
+
+import (
+ "time"
+)
+
+// The money gate: the one place the billing figures' completeness is
+// decided. Every money figure declares the inputs it uses (moneyUse), and
+// moneyReady shows it only when each of those is complete; otherwise the
+// figure is refused with the reason of the first input not complete. A figure is
+// never shown from partial inputs.
+
+// moneyInput is one input a money figure may use.
+type moneyInput uint8
+
+const (
+ inFacts moneyInput = 1 << iota // every paying account's subscription read is current
+ inPayments // the payment reconcile is current
+ inRates // the rates are current and cover the figure's currencies
+ inAmounts // no paying account's yearly amount is unknown
+ inEconomics // the Economics read is complete
+ inPlatform // the figure's month has a CARLOS-only platform cost
+)
+
+var moneyInputOrder = []moneyInput{inFacts, inPayments, inRates, inAmounts, inEconomics, inPlatform}
+
+// moneyUse is what one figure declares: the inputs it uses, the
+// currencies it converts (for inRates) and its month (for inPlatform).
+type moneyUse struct {
+ Inputs moneyInput
+ Currencies []string
+ Month string
+}
+
+// moneyInputs is the state of every input at Now.
+type moneyInputs struct {
+ Now time.Time
+ Rates eurRates // LatestEURRates, with FetchedAt
+ StaleFacts int // paying, non-exempt accounts whose FactsReadAt is older than billingFactsMaxAge
+ Unknown int // arrTotals.Unknown
+ Reconciled time.Time // PaymentsReconciledAt
+ EconomicsComplete bool // Plan 2 fills; false here
+ PlatformOK map[string]bool // Plan 2 fills, by month; nil here
+}
+
+// How old each input may be and still count as current. An input exactly
+// this old is not current. The rates are fetched every billingRatesEvery
+// (20 h), which keeps them current through weekends, when the ECB's newest
+// day is Friday's.
+const (
+ billingFactsMaxAge = 2 * time.Hour
+ billingReconcileMaxAge = 2 * time.Hour
+ billingRatesMaxAge = 26 * time.Hour
+)
+
+// Reasons, one per input, in moneyInputOrder; each has an approved text
+// (Task 8 here, Plan 2's record on the pages).
+const (
+ moneyWhyFacts = "facts"
+ moneyWhyPayments = "payments"
+ moneyWhyRates = "rates"
+ moneyWhyAmounts = "amounts"
+ moneyWhyEconomics = "economics"
+ moneyWhyPlatform = "platform"
+)
+
+// moneyReady checks only the inputs u declares, in moneyInputOrder; the
+// first one not complete is the reason. A time never set (never
+// reconciled, never fetched) is not complete.
+func moneyReady(in moneyInputs, u moneyUse) (ok bool, why string) {
+ current := func(at time.Time, maxAge time.Duration) bool {
+ return !at.IsZero() && in.Now.Sub(at) < maxAge
+ }
+ for _, input := range moneyInputOrder {
+ if u.Inputs&input == 0 {
+ continue
+ }
+ switch input {
+ case inFacts:
+ if in.StaleFacts != 0 {
+ return false, moneyWhyFacts
+ }
+ case inPayments:
+ if !current(in.Reconciled, billingReconcileMaxAge) {
+ return false, moneyWhyPayments
+ }
+ case inRates:
+ if !current(in.Rates.FetchedAt, billingRatesMaxAge) {
+ return false, moneyWhyRates
+ }
+ for _, c := range u.Currencies {
+ if _, ok := in.Rates.eurCents(0, c); !ok {
+ return false, moneyWhyRates
+ }
+ }
+ case inAmounts:
+ if in.Unknown != 0 {
+ return false, moneyWhyAmounts
+ }
+ case inEconomics:
+ if !in.EconomicsComplete {
+ return false, moneyWhyEconomics
+ }
+ case inPlatform:
+ if !in.PlatformOK[u.Month] {
+ return false, moneyWhyPlatform
+ }
+ }
+ }
+ return true, ""
+}
+
+// ratesUse is inRates when any currency is not eur, else 0: the one way a
+// figure decides whether it declares the rates.
+func ratesUse(currencies ...string) moneyInput {
+ for _, c := range currencies {
+ if c != "eur" {
+ return inRates
+ }
+ }
+ return 0
+}
+
+// moneyFigure is one figure as the gate saw it: what the invariant tests
+// enumerate. Plan 2's opMoneyFigure embeds it.
+type moneyFigure struct {
+ Name string
+ Use moneyUse
+ Shown bool
+ Why string
+}
+
+// moneyInputsFor reads the rates and the reconciled time and counts the
+// paying, non-exempt accounts whose subscription read is stale; Unknown
+// comes from arr. The cost inputs (EconomicsComplete, PlatformOK) stay
+// unset.
+func (s *Server) moneyInputsFor(now time.Time, facts []billingFact, arr arrTotals) (moneyInputs, error) {
+ rates, err := s.store.LatestEURRates()
+ if err != nil {
+ return moneyInputs{}, err
+ }
+ reconciled, err := s.store.PaymentsReconciledAt()
+ if err != nil {
+ return moneyInputs{}, err
+ }
+ in := moneyInputs{Now: now, Rates: rates, Reconciled: reconciled, Unknown: arr.Unknown}
+ for _, f := range facts {
+ if f.AccountID == s.store.planExemptID || !payingNow(f) {
+ continue
+ }
+ if f.FactsReadAt.IsZero() || now.Sub(f.FactsReadAt) >= billingFactsMaxAge {
+ in.StaleFacts++
+ }
+ }
+ return in, nil
+}
diff --git a/internal/console/billingmoney_test.go b/internal/console/billingmoney_test.go
new file mode 100644
index 000000000..106665af3
--- /dev/null
+++ b/internal/console/billingmoney_test.go
@@ -0,0 +1,291 @@
+package console
+
+import (
+ "fmt"
+ "maps"
+ "slices"
+ "testing"
+ "time"
+)
+
+// gateBreak is one way checkGateInvariant makes the inputs incomplete: the
+// input it breaks, how, and the currency it removes (rates only).
+type gateBreak struct {
+ name string
+ input moneyInput
+ currency string // "": the whole input is broken
+ apply func(in *moneyInputs)
+}
+
+// gateBreaks are the inputs checkGateInvariant breaks, one at a time: each
+// input in moneyInputOrder, then the usd rate alone.
+func gateBreaks() []gateBreak {
+ return []gateBreak{
+ {name: "facts", input: inFacts, apply: func(in *moneyInputs) { in.StaleFacts = 1 }},
+ {name: "payments", input: inPayments, apply: func(in *moneyInputs) { in.Reconciled = in.Now.Add(-3 * time.Hour) }},
+ {name: "rates", input: inRates, apply: func(in *moneyInputs) { in.Rates.FetchedAt = in.Now.Add(-27 * time.Hour) }},
+ {name: "amounts", input: inAmounts, apply: func(in *moneyInputs) { in.Unknown = 1 }},
+ {name: "economics", input: inEconomics, apply: func(in *moneyInputs) { in.EconomicsComplete = false }},
+ {name: "platform", input: inPlatform, apply: func(in *moneyInputs) {
+ ok := map[string]bool{}
+ for m := range in.PlatformOK {
+ ok[m] = false
+ }
+ in.PlatformOK = ok
+ }},
+ {name: "usd rate", input: inRates, currency: "usd", apply: func(in *moneyInputs) {
+ r := maps.Clone(in.Rates.PerEUR)
+ delete(r, "usd")
+ in.Rates.PerEUR = r
+ }},
+ }
+}
+
+// moneyWhyOf is the reason moneyReady gives for an input.
+func moneyWhyOf(in moneyInput) string {
+ switch in {
+ case inFacts:
+ return moneyWhyFacts
+ case inPayments:
+ return moneyWhyPayments
+ case inRates:
+ return moneyWhyRates
+ case inAmounts:
+ return moneyWhyAmounts
+ case inEconomics:
+ return moneyWhyEconomics
+ case inPlatform:
+ return moneyWhyPlatform
+ }
+ return fmt.Sprintf("input %d", in)
+}
+
+// checkGateInvariant is the gate's invariant over a page's figures: build
+// with good shows every figure; with one input made incomplete, exactly
+// the figures that declare it are refused, each with that input's reason.
+// good must be complete in every input (PlatformOK true for every month a
+// figure names; a usd rate).
+func checkGateInvariant(t *testing.T, good moneyInputs, build func(in moneyInputs) []moneyFigure) {
+ t.Helper()
+ checkGateInvariantTB(t, good, build)
+}
+
+// checkGateInvariantTB is checkGateInvariant on any testing.TB, so the
+// helper itself can be tested against a recorder. It reports with Errorf
+// only.
+func checkGateInvariantTB(t testing.TB, good moneyInputs, build func(in moneyInputs) []moneyFigure) {
+ t.Helper()
+ base := build(good)
+ if len(base) == 0 {
+ t.Errorf("gate invariant: the build shows no figures")
+ return
+ }
+ for _, f := range base {
+ if !f.Shown {
+ t.Errorf("gate invariant: with every input complete, %s is refused (%q)", f.Name, f.Why)
+ }
+ }
+ for _, b := range gateBreaks() {
+ in := good
+ in.Rates.PerEUR = maps.Clone(good.Rates.PerEUR)
+ in.PlatformOK = maps.Clone(good.PlatformOK)
+ b.apply(&in)
+ got := map[string]moneyFigure{}
+ for _, f := range build(in) {
+ got[f.Name] = f
+ }
+ for _, want := range base {
+ f, ok := got[want.Name]
+ if !ok {
+ t.Errorf("gate invariant: %s broken: %s is missing", b.name, want.Name)
+ continue
+ }
+ declares := want.Use.Inputs&b.input != 0
+ if b.currency != "" {
+ declares = declares && slices.Contains(want.Use.Currencies, b.currency)
+ }
+ switch {
+ case declares && f.Shown:
+ t.Errorf("gate invariant: %s broken: %s declares it and is shown", b.name, want.Name)
+ case !declares && !f.Shown:
+ t.Errorf("gate invariant: %s broken: %s does not declare it and is refused (%q)", b.name, want.Name, f.Why)
+ case declares && f.Why != moneyWhyOf(b.input):
+ t.Errorf("gate invariant: %s broken: %s refused for %q, want %q", b.name, want.Name, f.Why, moneyWhyOf(b.input))
+ }
+ }
+ }
+}
+
+// goodMoneyInputs is complete in every input, for October's platform cost.
+func goodMoneyInputs(now time.Time) moneyInputs {
+ return moneyInputs{
+ Now: now,
+ Rates: eurRates{Day: "2026-11-06", FetchedAt: now.Add(-time.Hour), PerEUR: map[string]float64{"usd": 1.12, "gbp": 0.87}},
+ Reconciled: now.Add(-30 * time.Minute),
+ EconomicsComplete: true,
+ PlatformOK: map[string]bool{"2026-10": true},
+ }
+}
+
+func TestMoneyReady(t *testing.T) {
+ now := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)
+ uses := map[string]moneyUse{
+ "facts": {Inputs: inFacts},
+ "payments": {Inputs: inPayments},
+ "rates usd": {Inputs: inRates, Currencies: []string{"usd"}},
+ "amounts": {Inputs: inAmounts},
+ "economics": {Inputs: inEconomics},
+ "platform": {Inputs: inPlatform, Month: "2026-10"},
+ "arr": {Inputs: inFacts | inPayments | inAmounts | inRates, Currencies: []string{"eur", "usd"}},
+ "arr eur": {Inputs: inFacts | inPayments | inAmounts, Currencies: []string{"eur"}},
+ "margin": {Inputs: inFacts | inPayments | inRates | inEconomics | inPlatform, Currencies: []string{"usd"}, Month: "2026-10"},
+ "nothing": {},
+ }
+ for name, u := range uses {
+ if ok, why := moneyReady(goodMoneyInputs(now), u); !ok || why != "" {
+ t.Errorf("%s with every input complete: %v, %q", name, ok, why)
+ }
+ }
+ // Each input broken alone refuses exactly the uses declaring it.
+ for _, b := range gateBreaks() {
+ in := goodMoneyInputs(now)
+ b.apply(&in)
+ for name, u := range uses {
+ declares := u.Inputs&b.input != 0
+ if b.currency != "" {
+ declares = declares && slices.Contains(u.Currencies, b.currency)
+ }
+ ok, why := moneyReady(in, u)
+ if ok == declares {
+ t.Errorf("%s broken, %s: ok %v, want %v", b.name, name, ok, !declares)
+ }
+ if !ok && why != moneyWhyOf(b.input) {
+ t.Errorf("%s broken, %s: why %q, want %q", b.name, name, why, moneyWhyOf(b.input))
+ }
+ }
+ }
+
+ cases := []struct {
+ name string
+ break_ func(in *moneyInputs)
+ use moneyUse
+ ok bool
+ why string
+ }{
+ {"never reconciled", func(in *moneyInputs) { in.Reconciled = time.Time{} }, moneyUse{Inputs: inPayments}, false, moneyWhyPayments},
+ {"reconciled just inside", func(in *moneyInputs) { in.Reconciled = now.Add(-billingReconcileMaxAge + time.Second) }, moneyUse{Inputs: inPayments}, true, ""},
+ {"reconciled exactly max age ago", func(in *moneyInputs) { in.Reconciled = now.Add(-billingReconcileMaxAge) }, moneyUse{Inputs: inPayments}, false, moneyWhyPayments},
+ {"rates never fetched", func(in *moneyInputs) { in.Rates = eurRates{} }, moneyUse{Inputs: inRates, Currencies: []string{"usd"}}, false, moneyWhyRates},
+ {"rates fetched 25 h ago", func(in *moneyInputs) { in.Rates.FetchedAt = now.Add(-25 * time.Hour) }, moneyUse{Inputs: inRates, Currencies: []string{"usd"}}, true, ""},
+ {"gbp declared, no gbp rate", func(in *moneyInputs) { delete(in.Rates.PerEUR, "gbp") }, moneyUse{Inputs: inRates, Currencies: []string{"usd", "gbp"}}, false, moneyWhyRates},
+ {"chf declared, never published", nil, moneyUse{Inputs: inRates, Currencies: []string{"chf"}}, false, moneyWhyRates},
+ {"eur only, stale rates", func(in *moneyInputs) { in.Rates.FetchedAt = now.Add(-72 * time.Hour) }, moneyUse{Inputs: inFacts | ratesUse("eur"), Currencies: []string{"eur"}}, true, ""},
+ {"eur only, no rates at all", func(in *moneyInputs) { in.Rates = eurRates{} }, moneyUse{Inputs: inPayments | ratesUse("eur", "eur"), Currencies: []string{"eur"}}, true, ""},
+ {"platform reads the use's month", nil, moneyUse{Inputs: inPlatform, Month: "2026-11"}, false, moneyWhyPlatform},
+ {"platform nil map", func(in *moneyInputs) { in.PlatformOK = nil }, moneyUse{Inputs: inPlatform, Month: "2026-10"}, false, moneyWhyPlatform},
+ {"two broken: first in order", func(in *moneyInputs) {
+ in.Unknown = 1
+ in.Reconciled = time.Time{}
+ }, moneyUse{Inputs: inAmounts | inPayments}, false, moneyWhyPayments},
+ {"two broken: facts before everything", func(in *moneyInputs) {
+ in.EconomicsComplete = false
+ in.StaleFacts = 2
+ }, moneyUse{Inputs: inEconomics | inFacts}, false, moneyWhyFacts},
+ {"broken input not declared", func(in *moneyInputs) { in.StaleFacts = 3 }, moneyUse{Inputs: inPayments}, true, ""},
+ }
+ for _, c := range cases {
+ in := goodMoneyInputs(now)
+ if c.break_ != nil {
+ c.break_(&in)
+ }
+ ok, why := moneyReady(in, c.use)
+ if ok != c.ok || why != c.why {
+ t.Errorf("%s: %v, %q; want %v, %q", c.name, ok, why, c.ok, c.why)
+ }
+ }
+}
+
+func TestRatesUse(t *testing.T) {
+ if got := ratesUse(); got != 0 {
+ t.Errorf("no currencies: %v", got)
+ }
+ if got := ratesUse("eur", "eur"); got != 0 {
+ t.Errorf("eur only: %v", got)
+ }
+ if got := ratesUse("eur", "usd"); got != inRates {
+ t.Errorf("eur and usd: %v", got)
+ }
+}
+
+// tbRecorder is a testing.TB that records Errorf instead of failing.
+type tbRecorder struct {
+ testing.TB
+ errs []string
+}
+
+func (r *tbRecorder) Helper() {}
+func (r *tbRecorder) Errorf(format string, args ...any) {
+ r.errs = append(r.errs, fmt.Sprintf(format, args...))
+}
+
+func TestCheckGateInvariantCatchesOverDeclared(t *testing.T) {
+ now := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)
+ good := goodMoneyInputs(now)
+ figure := func(name string, declared moneyUse, checked moneyUse, in moneyInputs) moneyFigure {
+ ok, why := moneyReady(in, checked)
+ return moneyFigure{Name: name, Use: declared, Shown: ok, Why: why}
+ }
+ arr := moneyUse{Inputs: inFacts | inPayments | inAmounts | inRates, Currencies: []string{"usd"}}
+ margin := moneyUse{Inputs: inFacts | inEconomics | inPlatform, Month: "2026-10"}
+
+ // Honest: each figure is checked on what it declares.
+ honest := func(in moneyInputs) []moneyFigure {
+ return []moneyFigure{figure("arr", arr, arr, in), figure("margin", margin, margin, in)}
+ }
+ rec := &tbRecorder{TB: t}
+ checkGateInvariantTB(rec, good, honest)
+ if len(rec.errs) != 0 {
+ t.Fatalf("honest build failed the helper: %v", rec.errs)
+ }
+
+ // Over-checked: refused on payments, which it does not declare.
+ over := func(in moneyInputs) []moneyFigure {
+ checked := margin
+ checked.Inputs |= inPayments
+ return []moneyFigure{figure("arr", arr, arr, in), figure("margin", margin, checked, in)}
+ }
+ rec = &tbRecorder{TB: t}
+ checkGateInvariantTB(rec, good, over)
+ if len(rec.errs) == 0 {
+ t.Fatal("a figure refused on an undeclared input passed the helper")
+ }
+
+ // Under-checked: declares economics but is shown without it.
+ under := func(in moneyInputs) []moneyFigure {
+ checked := margin
+ checked.Inputs &^= inEconomics
+ return []moneyFigure{figure("arr", arr, arr, in), figure("margin", margin, checked, in)}
+ }
+ rec = &tbRecorder{TB: t}
+ checkGateInvariantTB(rec, good, under)
+ if len(rec.errs) == 0 {
+ t.Fatal("a figure shown despite a declared broken input passed the helper")
+ }
+
+ // A wrong reason fails it too.
+ wrongWhy := func(in moneyInputs) []moneyFigure {
+ f := figure("arr", arr, arr, in)
+ if !f.Shown {
+ f.Why = moneyWhyEconomics
+ }
+ return []moneyFigure{f}
+ }
+ rec = &tbRecorder{TB: t}
+ checkGateInvariantTB(rec, good, wrongWhy)
+ if len(rec.errs) == 0 {
+ t.Fatal("a refusal with the wrong reason passed the helper")
+ }
+
+ // And the real helper passes the honest build.
+ checkGateInvariant(t, good, honest)
+}
diff --git a/internal/console/billingmoneypass.go b/internal/console/billingmoneypass.go
index 4b6e0574d..beedc4924 100644
--- a/internal/console/billingmoneypass.go
+++ b/internal/console/billingmoneypass.go
@@ -23,8 +23,9 @@ const (
)
// billingMoneyPass is the money half of the billing worker's round, after
-// the subscription sync. With billing off or not ready it does nothing.
-// Each part's failure is logged and fails the job, and never stops the
+// the subscription sync: the payment reconcile, the euro rates, then
+// today's ARR snapshot from both. With billing off or not ready it does
+// nothing. Each part's failure is logged and fails the job, and never stops the
// next part or the subscription sync (the money reads never gate
// readiness).
func (s *Server) billingMoneyPass(ctx context.Context, now time.Time) {
@@ -40,6 +41,10 @@ func (s *Server) billingMoneyPass(ctx context.Context, now time.Time) {
log.Printf("console: billing money pass: euro rates: %v", err)
jobFailed(ctx, fmt.Errorf("billing money pass: euro rates: %w", err))
}
+ if err := s.billingSnapshotPass(ctx, now); err != nil {
+ log.Printf("console: billing money pass: daily snapshot: %v", err)
+ jobFailed(ctx, fmt.Errorf("billing money pass: daily snapshot: %w", err))
+ }
}
// reconcilePayments records every balance movement from the cursor (less
diff --git a/internal/console/billingpayments_store.go b/internal/console/billingpayments_store.go
index 3bca7f88e..9d8f16bc6 100644
--- a/internal/console/billingpayments_store.go
+++ b/internal/console/billingpayments_store.go
@@ -13,7 +13,8 @@ import (
// migrateBillingMoney adds the billing dashboard's money record: one row
// per provider balance movement, the reconcile's cursor, and the daily
// euro reference rates (billingrates.go). Account deletion leaves payment
-// rows alone: they are the money record.
+// rows alone: they are the money record. The daily ARR snapshot's tables
+// follow (migrateBillingSnapshots, billingrevenue.go).
func (s *Store) migrateBillingMoney() error {
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS billing_payments (
movement_id TEXT PRIMARY KEY,
@@ -52,7 +53,10 @@ CREATE TABLE IF NOT EXISTS billing_eur_rates (
fetched_at INTEGER NOT NULL,
PRIMARY KEY (day, currency)
);`)
- return err
+ if err != nil {
+ return err
+ }
+ return s.migrateBillingSnapshots()
}
// paymentRow is a recorded payment with what the console added: the
diff --git a/internal/console/billingrevenue.go b/internal/console/billingrevenue.go
new file mode 100644
index 000000000..ef7a8e6b2
--- /dev/null
+++ b/internal/console/billingrevenue.go
@@ -0,0 +1,430 @@
+package console
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "maps"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+)
+
+// billingFact is what the billing figures know of one live account: the
+// account, its plan row, its house mark, its billing row and whether its
+// subscription has been paid for.
+type billingFact struct {
+ AccountID int64
+ Sqid, Name string
+ Created time.Time
+ Apps int
+ Plan string
+ Packs map[string]int
+ Seats int
+ PlanSource string
+ Sponsored bool // the plan row's source is sponsored, or it carries sponsored limits
+ House bool // a billing_house row
+ Subscription string
+ ProviderStatus string // for display only; the figures read Billable and RenewalFailing
+ Billable bool // billing.Subscription.Billable, as last read
+ RenewalFailing bool // billing.Subscription.RenewalFailing, as last read
+ Currency string // lower case
+ CancelAtPeriodEnd bool
+ PeriodEnd time.Time
+ Annual int64 // -1 unknown
+ FactsReadAt time.Time
+ // Subscribed is a subscription the sync still reads (state paid or
+ // pending): the daily account rows are kept for these.
+ Subscribed bool
+ // Paid and FirstPaid: a subscription payment for Subscription is
+ // recorded, and the earliest one's time.
+ Paid bool
+ FirstPaid time.Time
+}
+
+// BillingFacts reads every live account, in id order, in one query.
+func (s *Store) BillingFacts() ([]billingFact, error) {
+ rows, err := s.db.Query(`SELECT a.id, a.sqid, a.name, a.created_at,
+ (SELECT COUNT(*) FROM apps WHERE apps.account_id = a.id AND apps.deleted_at = 0),
+ COALESCE(p.plan, ''), COALESCE(p.packs, '{}'), COALESCE(p.seats, 0), COALESCE(p.source, ''), COALESCE(p.sponsored, ''),
+ EXISTS(SELECT 1 FROM billing_house h WHERE h.account_id = a.id),
+ COALESCE(b.subscription, ''), COALESCE(b.provider_status, ''), COALESCE(b.currency, ''),
+ COALESCE(b.cancel_at_period_end, 0), COALESCE(b.period_end, 0), COALESCE(b.annual_amount, -1),
+ COALESCE(b.facts_read_at, 0), COALESCE(b.state, ''), COALESCE(b.billable, 0), COALESCE(b.renewal_failing, 0),
+ (SELECT MIN(bp.at) FROM billing_payments bp WHERE bp.kind = ? AND b.subscription != '' AND bp.subscription = b.subscription)
+ FROM accounts a
+ LEFT JOIN account_plans p ON p.account_id = a.id
+ LEFT JOIN billing_accounts b ON b.account_id = a.id
+ WHERE a.deleted_at = 0 ORDER BY a.id`, string(billing.PaymentSubscription))
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []billingFact
+ for rows.Next() {
+ var f billingFact
+ var created, periodEnd, factsRead int64
+ var packs, sponsored, state string
+ var firstPaid sql.NullInt64
+ if err := rows.Scan(&f.AccountID, &f.Sqid, &f.Name, &created, &f.Apps,
+ &f.Plan, &packs, &f.Seats, &f.PlanSource, &sponsored, &f.House,
+ &f.Subscription, &f.ProviderStatus, &f.Currency,
+ &f.CancelAtPeriodEnd, &periodEnd, &f.Annual, &factsRead, &state, &f.Billable, &f.RenewalFailing, &firstPaid); err != nil {
+ return nil, err
+ }
+ if packs != "" && packs != "{}" {
+ if err := json.Unmarshal([]byte(packs), &f.Packs); err != nil {
+ return nil, fmt.Errorf("account %d packs: %w", f.AccountID, err)
+ }
+ }
+ f.Created = time.Unix(created, 0).UTC()
+ f.PeriodEnd, f.FactsReadAt = timeOrZero(periodEnd), timeOrZero(factsRead)
+ f.Currency = strings.ToLower(f.Currency)
+ f.Sponsored = f.PlanSource == PlanSourceSponsored || sponsored != ""
+ f.Subscribed = f.Subscription != "" && (state == string(billing.StatePaid) || state == string(billing.StatePending))
+ if firstPaid.Valid {
+ f.Paid, f.FirstPaid = true, time.Unix(firstPaid.Int64, 0).UTC()
+ }
+ out = append(out, f)
+ }
+ return out, rows.Err()
+}
+
+// billingGroup is the one group an account falls in (spec §4.7).
+type billingGroup string
+
+const (
+ groupOurs billingGroup = "ours"
+ groupPaying billingGroup = "paying"
+ groupHouse billingGroup = "house"
+ groupSponsored billingGroup = "sponsored"
+ groupFree billingGroup = "free"
+)
+
+// billingGroupOrder is the page's tab order.
+var billingGroupOrder = []billingGroup{groupPaying, groupFree, groupSponsored, groupHouse, groupOurs}
+
+// payingNow is §4.2's paying: the provider counts the subscription as
+// running and charging (Billable, a failing renewal included), and a
+// payment for it has been received. Trials and subscriptions never paid
+// are not paying.
+func payingNow(f billingFact) bool {
+ return f.Paid && f.Subscription != "" && f.Billable
+}
+
+// billingGroupOf decides an account's group, in §4.7's order: the exempt
+// account is ours; paying with a non-zero (or unknown) yearly amount is
+// paying; then a house mark, then a sponsorship; free otherwise.
+func billingGroupOf(f billingFact, exemptID int64) billingGroup {
+ switch {
+ case f.AccountID == exemptID:
+ return groupOurs
+ case payingNow(f) && f.Annual != 0:
+ return groupPaying
+ case f.House:
+ return groupHouse
+ case f.Sponsored:
+ return groupSponsored
+ }
+ return groupFree
+}
+
+// inARR is an account ARR counts: paying, not cancelling, a known
+// non-zero yearly amount, not exempt.
+func inARR(f billingFact, exemptID int64) bool {
+ return f.AccountID != exemptID && payingNow(f) && !f.CancelAtPeriodEnd && f.Annual > 0
+}
+
+// arrTotals is ARR by currency and in euros at RateDay's rates. Paying
+// counts the paying group; Attention its accounts whose renewal is failing or
+// cancelling; Unknown its non-cancelling accounts whose yearly amount is
+// unknown (left out of ByCurrency). EUR is 0 when a currency has no rate.
+type arrTotals struct {
+ ByCurrency map[string]int64
+ EUR int64
+ RateDay string
+ Paying, Attention, Unknown int
+}
+
+// arrOf totals ARR over facts. Each currency's total converts once.
+func arrOf(facts []billingFact, exemptID int64, r eurRates) arrTotals {
+ t := arrTotals{ByCurrency: map[string]int64{}, RateDay: r.Day}
+ for _, f := range facts {
+ if billingGroupOf(f, exemptID) != groupPaying {
+ continue
+ }
+ t.Paying++
+ if f.RenewalFailing || f.CancelAtPeriodEnd {
+ t.Attention++
+ }
+ if !f.CancelAtPeriodEnd && f.Annual == -1 {
+ t.Unknown++
+ }
+ if inARR(f, exemptID) {
+ t.ByCurrency[f.Currency] += f.Annual
+ }
+ }
+ for _, c := range slices.Sorted(maps.Keys(t.ByCurrency)) {
+ cents, ok := r.eurCents(t.ByCurrency[c], c)
+ if !ok {
+ t.EUR = 0
+ break
+ }
+ t.EUR += cents
+ }
+ return t
+}
+
+// migrateBillingSnapshots adds the daily ARR snapshot: one row per day
+// with the totals and whether its inputs were complete, and one row per
+// non-exempt subscribed account per day. Called from migrateBillingMoney.
+func (s *Store) migrateBillingSnapshots() error {
+ _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS billing_arr_daily (
+ day TEXT PRIMARY KEY,
+ arr TEXT NOT NULL,
+ 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
+);
+CREATE TABLE IF NOT EXISTS billing_account_daily (
+ day TEXT NOT NULL,
+ account_id INTEGER NOT NULL,
+ annual INTEGER NOT NULL,
+ currency TEXT NOT NULL,
+ annual_eur INTEGER NOT NULL,
+ paying INTEGER NOT NULL,
+ in_arr INTEGER NOT NULL,
+ PRIMARY KEY (day, account_id)
+);`)
+ return err
+}
+
+// arrSnapshot is one day's ARR row. ARR is in minor units by currency.
+type arrSnapshot struct {
+ Day string
+ ARR map[string]int64
+ EUR int64
+ RateDay string
+ Paying int
+ Complete bool
+ Why string
+}
+
+// accountDay is one account's row of a day. Annual is -1 when unknown;
+// AnnualEUR is 0 when Annual is not positive or has no rate.
+type accountDay struct {
+ Day string
+ AccountID int64
+ Annual int64
+ Currency string
+ AnnualEUR int64
+ Paying, InARR bool
+}
+
+// snapshotDayFormat is a snapshot's day, in UTC.
+const snapshotDayFormat = "2006-01-02"
+
+// PutDailySnapshot writes today's snapshot in one transaction: the ARR row
+// is upserted and every account row of the day replaced. Any other day is
+// refused: earlier days are frozen, later ones not yet begun.
+func (s *Store) PutDailySnapshot(a arrSnapshot, accounts []accountDay, today string, now time.Time) error {
+ if a.Day != today {
+ return fmt.Errorf("billing snapshot: %s is not today (%s)", a.Day, today)
+ }
+ for _, r := range accounts {
+ if r.Day != a.Day {
+ return fmt.Errorf("billing snapshot: account %d row for %s in %s's snapshot", r.AccountID, r.Day, a.Day)
+ }
+ }
+ arr := a.ARR
+ if arr == nil {
+ arr = map[string]int64{}
+ }
+ raw, err := json.Marshal(arr)
+ if err != nil {
+ return err
+ }
+ tx, err := s.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer func() { _ = tx.Rollback() }()
+ if _, err := tx.Exec(`INSERT INTO billing_arr_daily (day, arr, arr_eur, rate_day, paying, complete, why, written_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(day) DO UPDATE SET arr = excluded.arr, arr_eur = excluded.arr_eur, rate_day = excluded.rate_day,
+ paying = excluded.paying, complete = excluded.complete, why = excluded.why, written_at = excluded.written_at`,
+ a.Day, string(raw), a.EUR, a.RateDay, a.Paying, a.Complete, a.Why, now.Unix()); err != nil {
+ return err
+ }
+ if _, err := tx.Exec(`DELETE FROM billing_account_daily WHERE day = ?`, a.Day); err != nil {
+ return err
+ }
+ for _, r := range accounts {
+ if _, err := tx.Exec(`INSERT INTO billing_account_daily (day, account_id, annual, currency, annual_eur, paying, in_arr)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`, r.Day, r.AccountID, r.Annual, r.Currency, r.AnnualEUR, r.Paying, r.InARR); err != nil {
+ return err
+ }
+ }
+ return tx.Commit()
+}
+
+// ARRSnapshots lists the ARR rows from fromDay to toDay inclusive, oldest
+// first.
+func (s *Store) ARRSnapshots(fromDay, toDay string) ([]arrSnapshot, error) {
+ rows, err := s.db.Query(`SELECT day, arr, arr_eur, rate_day, paying, complete, why FROM billing_arr_daily
+ WHERE day >= ? AND day <= ? ORDER BY day`, fromDay, toDay)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []arrSnapshot
+ for rows.Next() {
+ var a arrSnapshot
+ var raw string
+ if err := rows.Scan(&a.Day, &raw, &a.EUR, &a.RateDay, &a.Paying, &a.Complete, &a.Why); err != nil {
+ return nil, err
+ }
+ if err := json.Unmarshal([]byte(raw), &a.ARR); err != nil {
+ return nil, fmt.Errorf("billing snapshot %s: %w", a.Day, err)
+ }
+ out = append(out, a)
+ }
+ return out, rows.Err()
+}
+
+// AccountDays lists the account rows from fromDay to toDay inclusive, by
+// day then account.
+func (s *Store) AccountDays(fromDay, toDay string) ([]accountDay, error) {
+ rows, err := s.db.Query(`SELECT day, account_id, annual, currency, annual_eur, paying, in_arr FROM billing_account_daily
+ WHERE day >= ? AND day <= ? ORDER BY day, account_id`, fromDay, toDay)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []accountDay
+ for rows.Next() {
+ var r accountDay
+ if err := rows.Scan(&r.Day, &r.AccountID, &r.Annual, &r.Currency, &r.AnnualEUR, &r.Paying, &r.InARR); err != nil {
+ return nil, err
+ }
+ out = append(out, r)
+ }
+ return out, rows.Err()
+}
+
+// FirstSnapshotDay is the oldest snapshot's day; "" when none.
+func (s *Store) FirstSnapshotDay() (string, error) {
+ var day sql.NullString
+ if err := s.db.QueryRow(`SELECT MIN(day) FROM billing_arr_daily`).Scan(&day); err != nil {
+ return "", err
+ }
+ return day.String, nil
+}
+
+// billingRevenue is the revenue as of now: ARR, the group counts, the
+// first snapshot this month and the gate's inputs. Plan 2's pages and the
+// billing revenue door read through it.
+type billingRevenue struct {
+ arrTotals
+ Groups map[billingGroup]int
+ Accounts int
+ // MonthStart is the first snapshot on or after the 1st of this month
+ // (UTC); nil when none.
+ MonthStart *arrSnapshot
+ TestMode bool
+ Inputs moneyInputs
+}
+
+var errBillingOff = errors.New("billing is off")
+
+// billingRevenueNow reads the facts, the rates and the reconcile once and
+// totals them. ARR converts at the same rates the gate's inputs hold.
+func (s *Server) billingRevenueNow(now time.Time) (billingRevenue, []billingFact, error) {
+ if s.billing == nil {
+ return billingRevenue{}, nil, errBillingOff
+ }
+ exempt := s.store.planExemptID
+ facts, err := s.store.BillingFacts()
+ if err != nil {
+ return billingRevenue{}, nil, err
+ }
+ // Unknown does not depend on the rates: the inputs read the rates once,
+ // and ARR converts at those.
+ in, err := s.moneyInputsFor(now, facts, arrOf(facts, exempt, eurRates{}))
+ if err != nil {
+ return billingRevenue{}, nil, err
+ }
+ rev := billingRevenue{
+ arrTotals: arrOf(facts, exempt, in.Rates),
+ Groups: map[billingGroup]int{},
+ Accounts: len(facts),
+ TestMode: !s.billing.cfg.LiveMode,
+ Inputs: in,
+ }
+ for _, f := range facts {
+ rev.Groups[billingGroupOf(f, exempt)]++
+ }
+ utc := now.UTC()
+ first := time.Date(utc.Year(), utc.Month(), 1, 0, 0, 0, 0, time.UTC)
+ snaps, err := s.store.ARRSnapshots(first.Format(snapshotDayFormat), utc.Format(snapshotDayFormat))
+ if err != nil {
+ return billingRevenue{}, nil, err
+ }
+ if len(snaps) > 0 {
+ rev.MonthStart = &snaps[0]
+ }
+ return rev, facts, nil
+}
+
+// billingSnapshotPass writes today's (UTC) snapshot: ARR and one row per
+// non-exempt subscribed account, complete only when every input they use
+// is (moneyReady). Every pass rewrites today; the day's last pass 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 {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ rev, facts, err := s.billingRevenueNow(now)
+ if err != nil {
+ return err
+ }
+ exempt := s.store.planExemptID
+ today := now.UTC().Format(snapshotDayFormat)
+ var rows []accountDay
+ seen := map[string]bool{}
+ for c := range rev.ByCurrency {
+ seen[c] = true
+ }
+ for _, f := range facts {
+ if f.AccountID == exempt || !f.Subscribed {
+ continue
+ }
+ r := accountDay{Day: today, AccountID: f.AccountID, Annual: f.Annual, Currency: f.Currency,
+ Paying: payingNow(f), InARR: inARR(f, exempt)}
+ if f.Annual > 0 {
+ // The account rows convert their own currencies too, so the
+ // gate covers them.
+ seen[f.Currency] = true
+ if eur, ok := rev.Inputs.Rates.eurCents(f.Annual, f.Currency); ok {
+ r.AnnualEUR = eur
+ }
+ }
+ rows = append(rows, r)
+ }
+ currencies := slices.Sorted(maps.Keys(seen))
+ ok, why := moneyReady(rev.Inputs, moneyUse{
+ Inputs: inFacts | inPayments | inAmounts | ratesUse(currencies...),
+ Currencies: currencies,
+ })
+ snap := arrSnapshot{Day: today, ARR: rev.ByCurrency, EUR: rev.EUR, RateDay: rev.RateDay,
+ Paying: rev.Paying, Complete: ok, Why: why}
+ return s.store.PutDailySnapshot(snap, rows, today, now)
+}
diff --git a/internal/console/billingrevenue_test.go b/internal/console/billingrevenue_test.go
new file mode 100644
index 000000000..8af46f628
--- /dev/null
+++ b/internal/console/billingrevenue_test.go
@@ -0,0 +1,556 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "maps"
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/fxrate"
+ "github.com/carlosframework/platform/internal/plans"
+ "github.com/carlosframework/platform/internal/usage"
+)
+
+func TestPayingNow(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ billable, paid bool
+ failing bool
+ want bool
+ }{
+ {"running, paid", true, true, false, true},
+ {"renewal failing, paid", true, true, true, true},
+ {"not billable (a trial), paid", false, true, false, false},
+ {"running, no payment", true, false, false, false},
+ {"not billable, never paid", false, false, false, false},
+ } {
+ f := billingFact{Subscription: "sub_1", Billable: c.billable, RenewalFailing: c.failing, Paid: c.paid}
+ if got := payingNow(f); got != c.want {
+ t.Errorf("%s: %v, want %v", c.name, got, c.want)
+ }
+ }
+ // The display status is never read.
+ if payingNow(billingFact{Subscription: "sub_1", ProviderStatus: "running", Paid: true}) {
+ t.Error("a provider status alone made the account paying")
+ }
+}
+
+func TestBillingGroupOf(t *testing.T) {
+ const exempt = OpsAccountID
+ paying := func(annual int64) billingFact {
+ return billingFact{AccountID: 7, Subscription: "sub_1", Billable: true, Paid: true, Annual: annual, Currency: "eur"}
+ }
+ withHouse := paying(0)
+ withHouse.House = true
+ exemptPaying := paying(2400)
+ exemptPaying.AccountID = exempt
+ cases := []struct {
+ name string
+ f billingFact
+ want billingGroup
+ }{
+ {"exempt, even when paying", exemptPaying, groupOurs},
+ {"exempt, nothing else", billingFact{AccountID: exempt}, groupOurs},
+ {"paying 2400", paying(2400), groupPaying},
+ {"paying, amount unknown", paying(-1), groupPaying},
+ {"paying 0 with a house row", withHouse, groupHouse},
+ {"house row, never paid", billingFact{AccountID: 7, House: true}, groupHouse},
+ {"sponsored source", billingFact{AccountID: 7, PlanSource: PlanSourceSponsored, Sponsored: true}, groupSponsored},
+ {"operator source, sponsored limits", billingFact{AccountID: 7, PlanSource: PlanSourceOperator, Sponsored: true}, groupSponsored},
+ {"not billable (a trial)", billingFact{AccountID: 7, Subscription: "sub_1", Paid: true, Annual: 2400}, groupFree},
+ {"paying 0, no house row", paying(0), groupFree},
+ {"default plan", billingFact{AccountID: 7, PlanSource: PlanSourceDefault}, groupFree},
+ }
+ for _, c := range cases {
+ if got := billingGroupOf(c.f, exempt); got != c.want {
+ t.Errorf("%s: %s, want %s", c.name, got, c.want)
+ }
+ }
+ if len(billingGroupOrder) != 5 || billingGroupOrder[0] != groupPaying || billingGroupOrder[4] != groupOurs {
+ t.Errorf("billingGroupOrder = %v", billingGroupOrder)
+ }
+}
+
+// payingFact is an active, paid subscription on account id.
+func payingFact(id int64, currency string, annual int64) billingFact {
+ return billingFact{AccountID: id, Subscription: "sub_" + currency, Billable: true, Paid: true,
+ Currency: currency, Annual: annual}
+}
+
+func TestARROf(t *testing.T) {
+ rates := eurRates{Day: "2026-11-06", FetchedAt: billingNow, PerEUR: map[string]float64{"usd": 1.12}}
+ facts := []billingFact{payingFact(2, "eur", 2400), payingFact(3, "usd", 2800)}
+ got := arrOf(facts, OpsAccountID, rates)
+ want := arrTotals{ByCurrency: map[string]int64{"eur": 2400, "usd": 2800}, EUR: 4900, RateDay: "2026-11-06", Paying: 2}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("arrOf = %+v, want %+v", got, want)
+ }
+
+ cancelling := payingFact(4, "eur", 1200)
+ cancelling.CancelAtPeriodEnd = true
+ pastDue := payingFact(5, "eur", 600)
+ pastDue.RenewalFailing = true
+ exempt := payingFact(OpsAccountID, "eur", 9900)
+ trialing := payingFact(6, "eur", 300)
+ trialing.Billable = false
+ unpaid := payingFact(7, "eur", 300)
+ unpaid.Paid = false
+ got = arrOf(append(facts, cancelling, pastDue, exempt, trialing, unpaid), OpsAccountID, rates)
+ want = arrTotals{ByCurrency: map[string]int64{"eur": 3000, "usd": 2800}, EUR: 5500, RateDay: "2026-11-06", Paying: 4, Attention: 2}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("with cancelling, past_due, exempt, trialing, unpaid: %+v, want %+v", got, want)
+ }
+
+ // A currency with no rate: the euro total is 0 (the gate refuses it).
+ got = arrOf([]billingFact{payingFact(2, "eur", 2400), payingFact(3, "gbp", 1000)}, OpsAccountID, rates)
+ if got.EUR != 0 || got.ByCurrency["gbp"] != 1000 {
+ t.Fatalf("no gbp rate: %+v", got)
+ }
+ if got := arrOf(nil, OpsAccountID, rates); got.EUR != 0 || len(got.ByCurrency) != 0 || got.Paying != 0 {
+ t.Fatalf("no facts: %+v", got)
+ }
+}
+
+func TestARROfUnknownAmount(t *testing.T) {
+ rates := eurRates{Day: "2026-11-06", FetchedAt: billingNow, PerEUR: map[string]float64{"usd": 1.12}}
+ cancellingUnknown := payingFact(4, "eur", -1)
+ cancellingUnknown.CancelAtPeriodEnd = true
+ got := arrOf([]billingFact{payingFact(2, "eur", -1), payingFact(3, "eur", 2400), cancellingUnknown, payingFact(OpsAccountID, "eur", -1)},
+ OpsAccountID, rates)
+ if got.Paying != 3 || got.Unknown != 1 || got.ByCurrency["eur"] != 2400 || got.EUR != 2400 || got.Attention != 1 {
+ t.Fatalf("arrOf = %+v; want Paying 3, Unknown 1, eur 2400", got)
+ }
+}
+
+func TestMoneyInputsFor(t *testing.T) {
+ fx := newConsoleFixture(t)
+ now := billingNow
+ if err := fx.st.PutEURRates(fxrate.Rates{Day: "2026-10-24", PerEUR: map[string]float64{"usd": 1.12}}, now.Add(-time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.SetPaymentsReconciled(now.Add(-10 * time.Minute)); err != nil {
+ t.Fatal(err)
+ }
+ fresh := payingFact(2, "eur", 2400)
+ fresh.FactsReadAt = now.Add(-30 * time.Minute)
+ stale := payingFact(3, "usd", 2800)
+ stale.FactsReadAt = now.Add(-3 * time.Hour)
+ trialing := payingFact(4, "eur", 300)
+ trialing.Billable = false
+ trialing.FactsReadAt = now.Add(-30 * 24 * time.Hour)
+ exempt := payingFact(OpsAccountID, "eur", 900)
+ facts := []billingFact{fresh, stale, trialing, exempt}
+ in, err := fx.srv.moneyInputsFor(now, facts, arrTotals{Unknown: 4})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if in.StaleFacts != 1 || in.Unknown != 4 || !in.Now.Equal(now) {
+ t.Fatalf("inputs = %+v; want StaleFacts 1, Unknown 4", in)
+ }
+ if !in.Reconciled.Equal(now.Add(-10*time.Minute)) || in.Rates.Day != "2026-10-24" || !in.Rates.FetchedAt.Equal(now.Add(-time.Hour)) {
+ t.Fatalf("inputs = %+v; want the stored reconcile and rates", in)
+ }
+ if in.EconomicsComplete || in.PlatformOK != nil {
+ t.Fatalf("cost inputs set: %+v", in)
+ }
+}
+
+func TestBillingFactsQuery(t *testing.T) {
+ st, ids := planStore(t, "bab", "bac", "bad", "bae", "baf")
+ created := time.Unix(1_700_000_000, 0).UTC()
+ if err := st.CreateAccount(OpsAccountID, "shop", "ops", "ops@example.com", created); err != nil {
+ t.Fatal(err)
+ }
+ // bab pays: two subscription payments and a once-off before them.
+ if _, err := st.SetAccountPlan(ids["bab"], "personal", map[string]int{"apps": 2}, 0, PlanSourceBilling, nil, "", "billing", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ for _, app := range []string{"shop", "blog"} {
+ if _, err := st.CreateAppIn(ids["bab"], app, "bab@example.com", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := st.SetBillingCustomer(ids["bab"], "cus_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ b, _ := st.BillingAccount(ids["bab"])
+ b.Subscription, b.ProviderStatus, b.State, b.Currency, b.Billable = "sub_1", "active", billing.StatePaid, "eur", true
+ b.Annual, b.FactsReadAt, b.PeriodEnd, b.CancelAtPeriodEnd = 2400, billingNow, billingNow.Add(300*24*time.Hour), true
+ if err := st.PutBillingState(*b); err != nil {
+ t.Fatal(err)
+ }
+ first := testCharge("mv_first", "ch_first")
+ first.At = billingNow.Add(-60 * 24 * time.Hour)
+ second := testCharge("mv_second", "ch_second")
+ second.At = billingNow.Add(-24 * time.Hour)
+ onceOff := testCharge("mv_once", "ch_once")
+ onceOff.Kind, onceOff.Subscription, onceOff.At = billing.PaymentOnceOff, "", billingNow.Add(-90*24*time.Hour)
+ for _, p := range []billing.Payment{second, first, onceOff} {
+ recordPayment(t, st, p)
+ }
+ // bac is a house account; bad sponsored (launch); bae on its default
+ // plan with an operator's sponsored limits; baf deleted.
+ if err := st.SetBillingHouse(ids["bac"], true, "ops@example.com", "", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.SetAccountPlan(ids["bad"], "personal", nil, 0, PlanSourceSponsored, &plans.Limits{RunningThings: 12}, "", "ops", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.SetAccountPlan(ids["bae"], "free", nil, 0, PlanSourceOperator, &plans.Limits{RunningThings: 3}, "", "ops", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.ReapAccount(ids["baf"], billingNow); err != nil {
+ t.Fatal(err)
+ }
+
+ facts, err := st.BillingFacts()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got []int64
+ byID := map[int64]billingFact{}
+ for _, f := range facts {
+ got = append(got, f.AccountID)
+ byID[f.AccountID] = f
+ }
+ if want := []int64{OpsAccountID, ids["bab"], ids["bac"], ids["bad"], ids["bae"]}; !reflect.DeepEqual(got, want) {
+ t.Fatalf("accounts = %v, want %v (id order, deleted absent)", got, want)
+ }
+ bab := byID[ids["bab"]]
+ want := billingFact{
+ AccountID: ids["bab"], Sqid: "bab", Name: "bab", Created: created, Apps: 2,
+ Plan: "personal", Packs: map[string]int{"apps": 2}, PlanSource: PlanSourceBilling,
+ Subscription: "sub_1", ProviderStatus: "active", Billable: true, Currency: "eur", CancelAtPeriodEnd: true,
+ PeriodEnd: billingNow.Add(300 * 24 * time.Hour), Annual: 2400, FactsReadAt: billingNow,
+ Subscribed: true, Paid: true, FirstPaid: first.At,
+ }
+ if !reflect.DeepEqual(bab, want) {
+ t.Fatalf("bab = %+v\nwant %+v", bab, want)
+ }
+ if f := byID[ids["bac"]]; !f.House || f.Paid || f.Annual != -1 || f.Subscription != "" || f.Apps != 0 {
+ t.Errorf("bac = %+v; want a house account, no subscription, amount unknown", f)
+ }
+ if f := byID[ids["bad"]]; !f.Sponsored || f.PlanSource != PlanSourceSponsored {
+ t.Errorf("bad = %+v; want sponsored", f)
+ }
+ if f := byID[ids["bae"]]; !f.Sponsored || f.PlanSource != PlanSourceOperator {
+ t.Errorf("bae = %+v; want sponsored limits", f)
+ }
+ groups := map[int64]billingGroup{}
+ for _, f := range facts {
+ groups[f.AccountID] = billingGroupOf(f, OpsAccountID)
+ }
+ wantGroups := map[int64]billingGroup{OpsAccountID: groupOurs, ids["bab"]: groupPaying, ids["bac"]: groupHouse,
+ ids["bad"]: groupSponsored, ids["bae"]: groupSponsored}
+ if !maps.Equal(groups, wantGroups) {
+ t.Errorf("groups = %v, want %v", groups, wantGroups)
+ }
+}
+
+// snapFixture is a billing console with one paying usd subscription,
+// sub_1 on the fixture's account at 2400 a year, its first charge waiting
+// on the provider, and usd rates fetched at start.
+type snapFixture struct {
+ *billingFixture
+ swept map[string]bool // days with a storage sweep in place
+}
+
+func newSnapFixture(t *testing.T, start time.Time) *snapFixture {
+ t.Helper()
+ bf := newBillingFixture(t)
+ bf.ready(t)
+ bf.fake.Lock()
+ bf.fake.AccountOpened = start.Add(-48 * time.Hour)
+ bf.fake.Unlock()
+ if err := bf.st.PutEURRates(fxrate.Rates{Day: "2026-10-24", PerEUR: map[string]float64{"usd": 1.12}}, start); err != nil {
+ t.Fatal(err)
+ }
+ sf := &snapFixture{billingFixture: bf, swept: map[string]bool{}}
+ sf.subscribe(t, bf.acct, "cus_1", "sub_1", 2400, start.Add(-time.Hour))
+ return sf
+}
+
+// subscribe binds acct's billing row to sub (pending until the sync reads
+// it), puts an active usd subscription at annual on the provider, and its
+// first charge at paidAt.
+func (sf *snapFixture) subscribe(t *testing.T, acct *Account, customer, sub string, annual int64, paidAt time.Time) {
+ t.Helper()
+ s := testPersonalSub(sub, customer, acct.Sqid, "active", nil)
+ s.Annual, s.AnnualKnown = annual, true
+ sf.put(s)
+ b, err := sf.st.BillingAccount(acct.ID)
+ if err != nil || b == nil {
+ t.Fatalf("billing row %d: %+v, %v", acct.ID, b, err)
+ }
+ b.Subscription, b.State = sub, billing.StatePending
+ if err := sf.st.PutBillingState(*b); err != nil {
+ t.Fatal(err)
+ }
+ m, rec := testChargeRecord("ch_"+sub, paidAt, annual)
+ rec.Charge.Customer, rec.Charge.Subscription = customer, sub
+ sf.seedMovement(m)
+ sf.setCharge(m.Charge, rec)
+}
+
+// setStatus moves sub on the provider to status.
+func (sf *snapFixture) setStatus(sub, status string) {
+ sf.fake.Lock()
+ defer sf.fake.Unlock()
+ s := sf.fake.Subs[sub]
+ s.ProviderStatus, s.State, s.Live = status, billingStateFor(status), billingLiveFor(status)
+ s.Billable, s.RenewalFailing = billingBillableFor(status), status == "past_due"
+}
+
+func (sf *snapFixture) failMoney(err error) {
+ sf.fake.Lock()
+ sf.fake.MoneyErr = err
+ sf.fake.Unlock()
+}
+
+func (sf *snapFixture) failSub(sub string, err error) {
+ sf.fake.Lock()
+ defer sf.fake.Unlock()
+ if err == nil {
+ sf.fake.SubErr = nil
+ return
+ }
+ sf.fake.SubErr = map[string]error{sub: err}
+}
+
+// pass runs the billing worker's round at at, with that day's storage
+// sweep in place so the subscription sync fails nothing of its own.
+func (sf *snapFixture) pass(t *testing.T, at time.Time) {
+ t.Helper()
+ if day := usage.DayOf(at); !sf.swept[day] {
+ sf.swept[day] = true
+ putStoreJSON(t, sf.rel, usage.StorageDayKey(day), usage.StorageDay{V: 1, Date: day, Apps: map[string]usage.AppStorage{}})
+ }
+ if err := sf.srv.billingRound(context.Background(), at); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func arrDay(t *testing.T, s *Store, day string) arrSnapshot {
+ t.Helper()
+ snaps, err := s.ARRSnapshots(day, day)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(snaps) != 1 {
+ t.Fatalf("snapshots for %s = %+v; want one", day, snaps)
+ }
+ return snaps[0]
+}
+
+func accountDays(t *testing.T, s *Store, from, to string) []accountDay {
+ t.Helper()
+ rows, err := s.AccountDays(from, to)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return rows
+}
+
+func TestSnapshotTodayReplaceable(t *testing.T) {
+ day := time.Date(2026, 10, 25, 0, 0, 0, 0, time.UTC)
+ sf := newSnapFixture(t, day.Add(8*time.Hour))
+ second := planAccount(t, sf.consoleFixture, 502)
+ if err := sf.st.SetBillingCustomer(second.ID, "cus_2", day); err != nil {
+ t.Fatal(err)
+ }
+ sf.subscribe(t, second, "cus_2", "sub_2", 1200, day.Add(7*time.Hour))
+
+ sf.pass(t, day.Add(8*time.Hour))
+ if a := arrDay(t, sf.st, "2026-10-25"); !a.Complete || a.Paying != 2 {
+ t.Fatalf("first pass: %+v; want complete, two paying", a)
+ }
+ // The reconcile fails for three hours: today is rewritten incomplete.
+ sf.failMoney(errors.New("permission denied"))
+ sf.pass(t, day.Add(11*time.Hour))
+ a := arrDay(t, sf.st, "2026-10-25")
+ if a.Complete || a.Why != moneyWhyPayments || a.Paying != 2 || a.ARR["usd"] != 3600 {
+ t.Fatalf("stale reconcile: %+v; want incomplete for payments, both paying", a)
+ }
+ if rows := accountDays(t, sf.st, "2026-10-25", "2026-10-25"); len(rows) != 2 {
+ t.Fatalf("account rows = %+v; want two", rows)
+ }
+ // sub_2 ends; the reconcile works again.
+ sf.setStatus("sub_2", "canceled")
+ sf.failMoney(nil)
+ sf.pass(t, day.Add(12*time.Hour))
+ a = arrDay(t, sf.st, "2026-10-25")
+ want := arrSnapshot{Day: "2026-10-25", ARR: map[string]int64{"usd": 2400}, EUR: 2143, RateDay: "2026-10-24", Paying: 1, Complete: true}
+ if !reflect.DeepEqual(a, want) {
+ t.Fatalf("after recovery: %+v, want %+v", a, want)
+ }
+ rows := accountDays(t, sf.st, "2026-10-25", "2026-10-25")
+ wantRows := []accountDay{{Day: "2026-10-25", AccountID: sf.acct.ID, Annual: 2400, Currency: "usd", AnnualEUR: 2143, Paying: true, InARR: true}}
+ if !reflect.DeepEqual(rows, wantRows) {
+ t.Fatalf("account rows = %+v, want %+v", rows, wantRows)
+ }
+}
+
+func TestSnapshotEarlierDaysFrozen(t *testing.T) {
+ day := time.Date(2026, 10, 25, 0, 0, 0, 0, time.UTC)
+ sf := newSnapFixture(t, day.Add(9*time.Hour))
+ sf.pass(t, day.Add(10*time.Hour))
+ before := arrDay(t, sf.st, "2026-10-25")
+ beforeRows := accountDays(t, sf.st, "2026-10-25", "2026-10-25")
+ if !before.Complete || len(beforeRows) != 1 {
+ t.Fatalf("first day: %+v, %+v", before, beforeRows)
+ }
+
+ next := day.Add(24 * time.Hour)
+ err := sf.st.PutDailySnapshot(arrSnapshot{Day: "2026-10-25", ARR: map[string]int64{"usd": 1}, Complete: true},
+ []accountDay{{Day: "2026-10-25", AccountID: sf.acct.ID, Annual: 1, Currency: "usd"}}, "2026-10-26", next)
+ if err == nil {
+ t.Fatal("writing yesterday: nil error, want refused")
+ }
+ if err := sf.st.PutDailySnapshot(arrSnapshot{Day: "2026-10-27", Complete: true}, nil, "2026-10-26", next); err == nil {
+ t.Fatal("writing tomorrow: nil error, want refused")
+ }
+ if a := arrDay(t, sf.st, "2026-10-25"); !reflect.DeepEqual(a, before) {
+ t.Fatalf("yesterday changed: %+v, was %+v", a, before)
+ }
+
+ sf.pass(t, next.Add(10*time.Hour))
+ snaps, err := sf.st.ARRSnapshots("2026-10-01", "2026-10-31")
+ if err != nil || len(snaps) != 2 || snaps[0].Day != "2026-10-25" || snaps[1].Day != "2026-10-26" {
+ t.Fatalf("snapshots = %+v, %v; want two days, oldest first", snaps, err)
+ }
+ if !reflect.DeepEqual(snaps[0], before) {
+ t.Fatalf("first day changed by the next day's pass: %+v, was %+v", snaps[0], before)
+ }
+ if rows := accountDays(t, sf.st, "2026-10-25", "2026-10-25"); !reflect.DeepEqual(rows, beforeRows) {
+ t.Fatalf("first day's rows changed: %+v, were %+v", rows, beforeRows)
+ }
+ if rows := accountDays(t, sf.st, "2026-10-25", "2026-10-26"); len(rows) != 2 || rows[1].Day != "2026-10-26" {
+ t.Fatalf("both days' rows = %+v", rows)
+ }
+}
+
+func TestSnapshotStartsAtFirstPass(t *testing.T) {
+ day := time.Date(2026, 10, 25, 0, 0, 0, 0, time.UTC)
+ sf := newSnapFixture(t, day.Add(9*time.Hour))
+ // Older payments, months before the first pass.
+ m, rec := testChargeRecord("ch_old", day.Add(-90*24*time.Hour), 2400)
+ sf.seedMovement(m)
+ sf.setCharge(m.Charge, rec)
+ sf.fake.Lock()
+ sf.fake.AccountOpened = day.Add(-100 * 24 * time.Hour)
+ sf.fake.Unlock()
+ if d, err := sf.st.FirstSnapshotDay(); err != nil || d != "" {
+ t.Fatalf("before any pass: %q, %v", d, err)
+ }
+ sf.pass(t, day.Add(10*time.Hour))
+ snaps, err := sf.st.ARRSnapshots("2000-01-01", "2100-01-01")
+ if err != nil || len(snaps) != 1 || snaps[0].Day != "2026-10-25" {
+ t.Fatalf("snapshots = %+v, %v; want today only", snaps, err)
+ }
+ if d, err := sf.st.FirstSnapshotDay(); err != nil || d != "2026-10-25" {
+ t.Fatalf("FirstSnapshotDay = %q, %v", d, err)
+ }
+}
+
+func TestSnapshotFailureAcrossMidnight(t *testing.T) {
+ d := time.Date(2026, 10, 25, 0, 0, 0, 0, time.UTC)
+ sf := newSnapFixture(t, d.Add(20*time.Hour))
+ sf.pass(t, d.Add(21*time.Hour))
+ if a := arrDay(t, sf.st, "2026-10-25"); !a.Complete {
+ t.Fatalf("21:00: %+v; want complete", a)
+ }
+ sf.failMoney(errors.New("permission denied"))
+ sf.pass(t, d.Add(22*time.Hour))
+ if a := arrDay(t, sf.st, "2026-10-25"); !a.Complete {
+ t.Fatalf("22:00, reconciled an hour ago: %+v; want complete", a)
+ }
+ sf.pass(t, d.Add(23*time.Hour))
+ if a := arrDay(t, sf.st, "2026-10-25"); a.Complete || a.Why != moneyWhyPayments {
+ t.Fatalf("23:00: %+v; want incomplete for payments", a)
+ }
+ sf.pass(t, d.Add(24*time.Hour+30*time.Minute))
+ if a := arrDay(t, sf.st, "2026-10-26"); a.Complete || a.Why != moneyWhyPayments {
+ t.Fatalf("00:30: %+v; want incomplete for payments", a)
+ }
+ sf.failMoney(nil)
+ sf.pass(t, d.Add(26*time.Hour))
+ if a := arrDay(t, sf.st, "2026-10-26"); !a.Complete || a.Why != "" {
+ t.Fatalf("02:00: %+v; want complete", a)
+ }
+ if a := arrDay(t, sf.st, "2026-10-25"); a.Complete || a.Why != moneyWhyPayments {
+ t.Fatalf("day D after recovery: %+v; want its 23:00 write, incomplete for payments", a)
+ }
+}
+
+func TestSnapshotStaleFacts(t *testing.T) {
+ t0 := time.Date(2026, 10, 25, 8, 0, 0, 0, time.UTC)
+ sf := newSnapFixture(t, t0)
+ today := "2026-10-25"
+ sf.pass(t, t0)
+ if a := arrDay(t, sf.st, today); !a.Complete {
+ t.Fatalf("t0: %+v; want complete", a)
+ }
+ // The subscription reads fail; the payment reconcile works.
+ sf.failSub("sub_1", errors.New("network down"))
+ sf.pass(t, t0.Add(time.Hour))
+ if a := arrDay(t, sf.st, today); !a.Complete {
+ t.Fatalf("t0+1h: %+v; want complete", a)
+ }
+ for _, h := range []time.Duration{2, 3} {
+ sf.pass(t, t0.Add(h*time.Hour))
+ if a := arrDay(t, sf.st, today); a.Complete || a.Why != moneyWhyFacts {
+ t.Fatalf("t0+%dh: %+v; want incomplete for facts", h, a)
+ }
+ }
+ // The reads work again and the reconcile fails instead.
+ sf.failSub("sub_1", nil)
+ sf.failMoney(errors.New("permission denied"))
+ sf.pass(t, t0.Add(4*time.Hour))
+ if a := arrDay(t, sf.st, today); !a.Complete {
+ t.Fatalf("t0+4h: %+v; want complete (reconciled an hour ago)", a)
+ }
+ sf.pass(t, t0.Add(5*time.Hour))
+ if a := arrDay(t, sf.st, today); a.Complete || a.Why != moneyWhyPayments {
+ t.Fatalf("t0+5h: %+v; want incomplete for payments", a)
+ }
+}
+
+func TestBillingRevenueNow(t *testing.T) {
+ d := time.Date(2026, 10, 25, 0, 0, 0, 0, time.UTC)
+ sf := newSnapFixture(t, d.Add(8*time.Hour))
+ if err := sf.st.SetBillingHouse(planAccount(t, sf.consoleFixture, 503).ID, true, "ops@example.com", "", d); err != nil {
+ t.Fatal(err)
+ }
+ sf.pass(t, d.Add(9*time.Hour))
+ rev, facts, err := sf.srv.billingRevenueNow(d.Add(9*time.Hour + 30*time.Minute))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(facts) != rev.Accounts || rev.Paying != 1 || rev.ByCurrency["usd"] != 2400 || rev.EUR != 2143 || !rev.TestMode {
+ t.Fatalf("revenue = %+v", rev)
+ }
+ if rev.Groups[groupPaying] != 1 || rev.Groups[groupHouse] != 1 {
+ t.Fatalf("groups = %v", rev.Groups)
+ }
+ total := 0
+ for _, n := range rev.Groups {
+ total += n
+ }
+ if total != rev.Accounts {
+ t.Fatalf("groups %v do not cover the %d accounts", rev.Groups, rev.Accounts)
+ }
+ if rev.MonthStart == nil || rev.MonthStart.Day != "2026-10-25" {
+ t.Fatalf("MonthStart = %+v; want the first snapshot this month", rev.MonthStart)
+ }
+ if ok, why := moneyReady(rev.Inputs, moneyUse{Inputs: inFacts | inPayments | inAmounts | inRates, Currencies: []string{"usd"}}); !ok {
+ t.Fatalf("inputs %+v refuse ARR: %s", rev.Inputs, why)
+ }
+ // Next month, October's snapshot is not this month's start.
+ rev, _, err = sf.srv.billingRevenueNow(time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC))
+ if err != nil || rev.MonthStart != nil {
+ t.Fatalf("November: MonthStart = %+v, %v; want none", rev.MonthStart, err)
+ }
+}
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go
index 468a0a70a..e9371f10b 100644
--- a/internal/console/jobs_test.go
+++ b/internal/console/jobs_test.go
@@ -51,7 +51,7 @@ var jobPassFuncs = map[string][]string{
"StartPlanGracePass": {"planGracePass", "planGraceAccountLocked", "notifyPlanOwners",
"convergeStoreDeny", "dropStaleLapseItem", "resumeStaleCapPause"},
"StartDomainPurchasePass": {"domainPurchasePass", "advancePurchase", "advancePurchaseStep", "advancePurchaseEffects", "reconcileRegisteringPurchase", "purchaseMutation", "purchaseCheckout", "purchaseCheckoutStep", "registerPurchase", "registeredPurchase", "failPurchase", "purchaseAlert", "purchaseOwnerNotice"},
- "StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer", "transitionAccountPlan", "billingMoneyPass", "reconcilePayments", "recordCharge", "recordChargeMovements", "billingRatesPass"},
+ "StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer", "transitionAccountPlan", "billingMoneyPass", "reconcilePayments", "recordCharge", "recordChargeMovements", "billingRatesPass", "billingSnapshotPass"},
"PublishPlansMarker": {"publishPlansMarkerOnce"},
"StartRunSweep": {"runSweepPass", "sweepExpireQueued", "sweepLostRun", "sweepTerminalRun", "sweepOrphanRuns",
"orphanCandidates", "orphanConfirmed", "orphanRunEnd", "auditRunEnd",
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index 68decd137..b8482c5ee 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -289,6 +289,8 @@ var claimSQLTables = map[string]claimSQLTable{
"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 reconcile has read; names no app"},
"billing_eur_rates": {NonApp: "daily euro reference rates; names no app"},
+ "billing_arr_daily": {NonApp: "daily recurring revenue totals; names no app"},
+ "billing_account_daily": {NonApp: "each account's yearly amount per day; names no app"},
"managed_fleet_delivered_keys": {NonApp: "fleet access key IDs ever delivered to boxes; no app identity"},