carlos / platform Public

console: billing money figures, the gate helper, full Economics reads

Plan 2 Task 3. opMoney is the one way a Billing page shows money: it asks
Plan 1's gate and formats only when ready, otherwise "Not available yet"
with the approved reason (BDP-8 to BDP-12, Plan 3's hint for platform,
BDP-13 for a month the stored days do not cover). eurText and minorText
are called only inside its format functions (a go/ast test holds it).

platformCostEUR reads Plan 3's CARLOS-only cost and converts it at the
usd rate. moneyByMonth, earnedSoFar, accountEarnings, accountMoneyRows
and accountFigures are the sums and per-account figures the pages build
on; revenue is Settled - SettledTax everywhere, refunds included.

sweepUsage now counts metrics and edge day objects that exist but fail to
read or parse (usageSweep.ReadFailures, carried on EconomicsView), and
econComplete refuses a view with any, so a day covered by one good object
no longer hides another box's failed read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 81e51d2fb4882d0eeb70668c80ad5f1c6b58e6e9 parent 9db00e8
5 files changed, +978 −2
  • internal/console/economicspass.go +22 −2
  • internal/console/economicspass_test.go +68 −0
  • internal/console/economicsview.go +5 −0
  • internal/console/opbilling_money.go +419 −0
  • internal/console/opbilling_money_test.go +464 −0

CI failed — run details

diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go
index 0108dd95c..0f2699b1f 100644
--- a/internal/console/economicspass.go
+++ b/internal/console/economicspass.go
@@ -339,6 +339,14 @@ type usageSweep struct {
// defaults to false for it, matching the honesty rule: a caller must
// show "unmetered", never a zero that reads as "confirmed no egress".
EgressMetered map[string]bool
+ // ReadFailures counts the metrics and edge day objects in [from, to]
+ // that exist but could not be used: a Get that failed with anything
+ // but os.ErrNotExist (an over-cap object included), or a body that
+ // does not parse. An absent object is not a failure. A day can be
+ // covered by one box's good object while another box's failed, so
+ // CoveredDays alone cannot say a sweep read everything; a sweep with
+ // ReadFailures above 0 is not a complete read.
+ ReadFailures int
}
// sweepUsage reads every UTC day in [from, to] (both truncated to midnight,
@@ -433,12 +441,18 @@ func (s *Server) sweepUsage(ctx context.Context, st release.Store, from, to time
box := strings.TrimSuffix(strings.TrimPrefix(boxPrefix, metricsBoxesPrefix), "/")
raw, _, gerr := st.Get(ctx, metrics.DayKey(box, date))
if gerr != nil {
- continue // missing = skip, uncovered by this box
+ // Missing = skip, uncovered by this box. Any other
+ // failure skips it too, but is counted.
+ if !errors.Is(gerr, os.ErrNotExist) {
+ sweep.ReadFailures++
+ }
+ continue
}
var roll metrics.DayRollup
if jerr := json.Unmarshal(raw, &roll); jerr != nil {
log.Printf("console: sweep usage: parse %s: %v", metrics.DayKey(box, date), jerr)
jobFailed(ctx, fmt.Errorf("sweep usage: parse %s: %w", metrics.DayKey(box, date), jerr))
+ sweep.ReadFailures++
continue
}
covered = true
@@ -497,12 +511,18 @@ func (s *Server) sweepUsage(ctx context.Context, st release.Store, from, to time
box := strings.TrimSuffix(strings.TrimPrefix(boxPrefix, usage.EdgeBoxesPrefix), "/")
raw, _, gerr := st.Get(ctx, usage.EdgeDayKey(box, date))
if gerr != nil {
- continue // missing = skip, uncovered by this box
+ // Missing = skip, uncovered by this box; any other
+ // failure is counted.
+ if !errors.Is(gerr, os.ErrNotExist) {
+ sweep.ReadFailures++
+ }
+ continue
}
var ed usage.EdgeDay
if jerr := json.Unmarshal(raw, &ed); jerr != nil {
log.Printf("console: sweep usage: parse %s: %v", usage.EdgeDayKey(box, date), jerr)
jobFailed(ctx, fmt.Errorf("sweep usage: parse %s: %w", usage.EdgeDayKey(box, date), jerr))
+ sweep.ReadFailures++
continue
}
covered = true
diff --git a/internal/console/economicspass_test.go b/internal/console/economicspass_test.go
index 7d768eacf..0bae88f6f 100644
--- a/internal/console/economicspass_test.go
+++ b/internal/console/economicspass_test.go
@@ -743,3 +743,71 @@ func TestEconomicsTierDoor(t *testing.T) {
t.Fatalf("account tier after operator POST = %q, want %q", got, want)
}
}
+
+// failDayStore fails one key's Get with an injected error; every other
+// read goes to the store below.
+type failDayStore struct {
+ release.Store
+ key string
+}
+
+func (f failDayStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if key == f.key {
+ return nil, "", errors.New("injected read failure")
+ }
+ return f.Store.Get(ctx, key)
+}
+
+// TestSweepUsageCountsReadFailures: a metrics day that exists but cannot
+// be read is counted, even though the same day's edge object covers the
+// day; an absent metrics day is not a failure. Through LoadEconomics the
+// view carries the count and econComplete refuses it.
+func TestSweepUsageCountsReadFailures(t *testing.T) {
+ now := time.Now().UTC()
+ today := now.Truncate(24 * time.Hour)
+ date := usage.DayOf(today)
+ failing := metrics.DayKey("box1", date)
+ fx := newConsoleFixtureWith(t, consoleFixtureOptions{WrapReleases: func(st release.Store) release.Store {
+ return failDayStore{Store: st, key: failing}
+ }})
+ ctx := context.Background()
+
+ roll := metrics.DayRollup{V: 1, Box: "box1", Date: date, Hours: map[string]metrics.HourAgg{}}
+ putStoreJSON(t, fx.rel, failing, roll)
+ putStoreJSON(t, fx.rel, usage.EdgeDayKey("box1", date), usage.EdgeDay{
+ V: 1, Box: "box1", Date: date,
+ Hours: map[string]map[string]usage.EdgeRow{"09": {
+ "a.bab.oncarlos.test": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9},
+ }},
+ })
+ // box2 is listed (it wrote a day before the period) but has no day in
+ // the period: absent, not a failure.
+ before := usage.DayOf(today.AddDate(0, 0, -40))
+ putStoreJSON(t, fx.rel, metrics.DayKey("box2", before), metrics.DayRollup{V: 1, Box: "box2", Date: before, Hours: map[string]metrics.HourAgg{}})
+
+ attrib, _, err := fx.srv.loadAttributionForEconomics()
+ if err != nil {
+ t.Fatal(err)
+ }
+ sweep, err := fx.srv.sweepUsage(ctx, fx.srv.cfg.Releases, today, today, attrib)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if sweep.CoveredDays != sweep.PeriodDays || sweep.PeriodDays != 1 {
+ t.Errorf("covered %d of %d days, want 1 of 1 (the edge object covers the day)", sweep.CoveredDays, sweep.PeriodDays)
+ }
+ if sweep.ReadFailures != 1 {
+ t.Errorf("ReadFailures = %d, want 1 (box1's metrics day; box2's absent day is not a failure)", sweep.ReadFailures)
+ }
+
+ view, err := fx.srv.LoadEconomics(ctx, "mtd")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if view.ReadFailures != 1 {
+ t.Errorf("view.ReadFailures = %d, want 1", view.ReadFailures)
+ }
+ if econComplete(view, nil) {
+ t.Error("econComplete = true for a view with a read failure")
+ }
+}
diff --git a/internal/console/economicsview.go b/internal/console/economicsview.go
index 14a17fa22..ede31a168 100644
--- a/internal/console/economicsview.go
+++ b/internal/console/economicsview.go
@@ -62,6 +62,10 @@ type EconomicsView struct {
Boxes []BoxEconomics
Bills []economics.Bill // this month + previous, if present
CoveredDays, PeriodDays int
+ // ReadFailures is the sweep's count of usage day objects that exist
+ // but could not be read or parsed (usageSweep.ReadFailures). A view
+ // with any is not a complete read, however many days it covers.
+ ReadFailures int
// DaysInMonth is the CURRENT real calendar month's length (statementsPass's
// own daysInMonth derivation: time.Date(y, mo+1, 0, ...).Day()) —
// deliberately NOT PeriodDays, which on "mtd" is only the number of days
@@ -703,6 +707,7 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom
Bills: bills,
CoveredDays: sweep.CoveredDays,
PeriodDays: sweep.PeriodDays,
+ ReadFailures: sweep.ReadFailures,
DaysInMonth: daysInMonth,
DataJSON: template.JS(raw),
Tiers: tiers,
diff --git a/internal/console/opbilling_money.go b/internal/console/opbilling_money.go
new file mode 100644
index 000000000..5ba763faa
--- /dev/null
+++ b/internal/console/opbilling_money.go
@@ -0,0 +1,419 @@
+package console
+
+import (
+ "context"
+ "fmt"
+ "maps"
+ "math"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+)
+
+// The money behind the Billing pages (billing dashboard plan 2, Task 3):
+// the one way a page shows a money figure (opMoney, through Plan 1's gate),
+// the formatters it alone calls, the platform cost as the pages may show
+// it, and the sums the pages are built from. The sums here never decide
+// whether they may be shown; the gate does.
+
+// econComplete is whether an Economics read can stand behind a cost: it
+// read without error, with no degraded sweep, no fallback scenario, no
+// usage day it failed to read, and every day of its period covered. It is
+// moneyInputs.EconomicsComplete.
+func econComplete(v *EconomicsView, err error) bool {
+ return err == nil && v != nil && v.Warning == "" && v.ScenarioWarning == "" &&
+ v.ReadFailures == 0 && v.CoveredDays == v.PeriodDays
+}
+
+// platformCost is one month's platform cost as the Billing pages may show it.
+type platformCost struct {
+ Cents int64 // euro cents; meaningful only when OK and the usd rate converted it
+ 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 rates reason when the dollars would not convert
+ // OK: a CARLOS-only figure exists (carlosPlatformCostUSD's ok). Its
+ // dollars may still lack a rate: Cents is then 0, and every figure
+ // using it declares inRates for usd, so the gate refuses it.
+ OK bool
+}
+
+// platformCostEUR is the month's ("2006-01") platform cost: Plan 3's
+// carlosPlatformCostUSD, converted with r (eurCents of round(usd × 100),
+// "usd"). Every page reads platform cost through this function only.
+func (s *Server) platformCostEUR(ctx context.Context, month string, r eurRates) platformCost {
+ usd, basis, ok := s.carlosPlatformCostUSD(ctx, month)
+ pc := platformCost{Basis: basis, Label: costBasisLabel(basis, "")}
+ if !ok {
+ pc.Hint = costBasisHint(s.cfg.CostScope, basis, month)
+ return pc
+ }
+ pc.OK = true
+ if cents, converted := r.eurCents(int64(math.Round(usd*100)), "usd"); converted {
+ pc.Cents = cents
+ } else {
+ pc.Hint = billCopyWhyRates
+ }
+ return pc
+}
+
+// moneyWhyHistory is the reason a past month's per-account figure is
+// refused when its stored days do not cover the month (accountEarnings).
+// It is decided by the history, not by moneyReady.
+const moneyWhyHistory = "history"
+
+// opMoneyFigure is one money figure as a page shows it.
+type opMoneyFigure struct {
+ moneyFigure // Name, Use, Shown, Why (the code)
+ Text string // the formatted figure, or the not-available text
+ Reason string // the reason's text when !Shown
+}
+
+// opMoney asks moneyReady(in, u) and calls format only when ready.
+// A refused figure's Reason is the approved text for its Why, or
+// platform[u.Month].Hint for moneyWhyPlatform. Every call is appended
+// to *figs.
+func opMoney(figs *[]opMoneyFigure, name string, in moneyInputs, u moneyUse, platform map[string]platformCost, format func() string) opMoneyFigure {
+ ok, why := moneyReady(in, u)
+ f := opMoneyFigure{moneyFigure: moneyFigure{Name: name, Use: u, Shown: ok, Why: why}}
+ if ok {
+ f.Text = format()
+ } else {
+ f.Text = billCopyNotAvailable
+ f.Reason = moneyReasonText(why, u.Month, platform)
+ }
+ *figs = append(*figs, f)
+ return f
+}
+
+// opMoneyHistoryRefused records a figure refused because month is not
+// covered by complete stored days, whatever the gate says. No formatter
+// runs.
+func opMoneyHistoryRefused(figs *[]opMoneyFigure, name string, u moneyUse, month string) opMoneyFigure {
+ f := opMoneyFigure{
+ moneyFigure: moneyFigure{Name: name, Use: u, Why: moneyWhyHistory},
+ Text: billCopyNotAvailable,
+ Reason: moneyReasonText(moneyWhyHistory, month, nil),
+ }
+ *figs = append(*figs, f)
+ return f
+}
+
+// moneyReasonText is the approved text for a refusal code: BDP-8 to BDP-12
+// for the gate's inputs (in moneyWhy* order), Plan 3's hint for the
+// month's platform cost, BDP-13 for a month the history does not cover.
+func moneyReasonText(why, month string, platform map[string]platformCost) string {
+ switch why {
+ case moneyWhyFacts:
+ return billCopyWhyFacts
+ case moneyWhyPayments:
+ return billCopyWhyPayments
+ case moneyWhyRates:
+ return billCopyWhyRates
+ case moneyWhyAmounts:
+ return billCopyWhyAmounts
+ case moneyWhyEconomics:
+ return billCopyWhyEconomics
+ case moneyWhyPlatform:
+ return platform[month].Hint
+ case moneyWhyHistory:
+ return fmt.Sprintf(billCopyWhyHistory, billingMonthName(month))
+ }
+ return ""
+}
+
+// billingMonthName is a "2006-01" month as the pages name it: "October
+// 2026". Anything else is returned as it is.
+func billingMonthName(month string) string {
+ t, err := time.Parse("2006-01", month)
+ if err != nil {
+ return month
+ }
+ return t.Format("January 2006")
+}
+
+// lastCompleteMonth is the calendar month (UTC) before now's, "2006-01".
+func lastCompleteMonth(now time.Time) string {
+ utc := now.UTC()
+ return time.Date(utc.Year(), utc.Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -1, 0).Format("2006-01")
+}
+
+// eurText is euro cents as the pages show them: €24.00, €1,200.00,
+// −€188.00 (U+2212, as dashDelta). Called only inside opMoney's format
+// functions; never a template func.
+func eurText(cents int64) string { return moneyText(cents, "€", "") }
+
+// minorText is an amount in a currency's minor units: $28.00, £22.00,
+// €24.00, any other currency as 28.00 XYZ. Called only inside opMoney's
+// format functions; never a template func.
+func minorText(minor int64, currency string) string {
+ switch c := strings.ToLower(currency); c {
+ case "usd":
+ return moneyText(minor, "$", "")
+ case "gbp":
+ return moneyText(minor, "£", "")
+ case "eur":
+ return moneyText(minor, "€", "")
+ default:
+ return moneyText(minor, "", " "+strings.ToUpper(c))
+ }
+}
+
+// moneyText is minor units with two decimals, thousands with commas, a
+// U+2212 minus before the symbol.
+func moneyText(minor int64, symbol, suffix string) string {
+ sign, u := "", uint64(minor)
+ if minor < 0 {
+ sign, u = "−", -uint64(minor)
+ }
+ whole := strconv.FormatUint(u/100, 10)
+ for i := len(whole) - 3; i > 0; i -= 3 {
+ whole = whole[:i] + "," + whole[i:]
+ }
+ return fmt.Sprintf("%s%s%s.%02d%s", sign, symbol, whole, u%100, suffix)
+}
+
+// divRound is n / d rounded half away from zero; d > 0.
+func divRound(n, d int64) int64 {
+ q, r := n/d, n%d
+ if r < 0 {
+ r = -r
+ }
+ if 2*r >= d {
+ if n < 0 {
+ q--
+ } else {
+ q++
+ }
+ }
+ return q
+}
+
+// daysInMonthOf is the length of t's calendar month (UTC).
+func daysInMonthOf(t time.Time) int {
+ t = t.UTC()
+ return time.Date(t.Year(), t.Month()+1, 0, 0, 0, 0, 0, time.UTC).Day()
+}
+
+// settledEUR is a settled amount in euro cents; 0 when its currency has no
+// rate (a figure using it declares the currency, and the gate refuses it).
+func settledEUR(r eurRates, minor int64, currency string) int64 {
+ cents, _ := r.eurCents(minor, strings.ToLower(currency))
+ return cents
+}
+
+// moneyMonth is one month of the money record, in euro cents.
+type moneyMonth struct {
+ Month string // "2006-01"
+ Subscriptions, OnceOff, Refunds, Tax, Fees, Net int64 // euro cents
+ Currencies []string
+ Platform platformCost
+}
+
+// moneyByMonth sums rows (Kind "all": fee rows included) into each of
+// months, in months' order; a row in no listed month is left out. Sums
+// only; whether a sum may be shown is the gate's. Each row counts in euros
+// from what settled: subscriptions and once-offs add Settled − SettledTax
+// to their column, refunds and reversals theirs to Refunds (signed, so tax
+// never counts as revenue); every row's SettledTax goes to Tax and its Fee
+// to Fees, and a fee row's −Settled to Fees too. Net is revenue after
+// refunds and fees, before tax. Currencies are the settled currencies seen.
+func moneyByMonth(rows []paymentRow, months []string, r eurRates, platform map[string]platformCost) []moneyMonth {
+ out := make([]moneyMonth, len(months))
+ at := map[string]int{}
+ seen := make([]map[string]bool, len(months))
+ for i, m := range months {
+ out[i] = moneyMonth{Month: m, Platform: platform[m]}
+ at[m] = i
+ seen[i] = map[string]bool{}
+ }
+ for _, p := range rows {
+ i, ok := at[p.At.UTC().Format("2006-01")]
+ if !ok {
+ continue
+ }
+ m := &out[i]
+ cur := strings.ToLower(p.SettledCurrency)
+ seen[i][cur] = true
+ revenue := settledEUR(r, p.Settled-p.SettledTax, cur)
+ switch p.Kind {
+ case billing.PaymentSubscription:
+ m.Subscriptions += revenue
+ case billing.PaymentOnceOff:
+ m.OnceOff += revenue
+ case billing.PaymentRefund:
+ m.Refunds += revenue
+ case billing.PaymentFee:
+ m.Fees += settledEUR(r, -p.Settled, cur)
+ }
+ m.Tax += settledEUR(r, p.SettledTax, cur)
+ m.Fees += settledEUR(r, p.Fee, cur)
+ }
+ for i := range out {
+ m := &out[i]
+ m.Net = m.Subscriptions + m.OnceOff + m.Refunds - m.Fees
+ if len(seen[i]) > 0 {
+ m.Currencies = slices.Sorted(maps.Keys(seen[i]))
+ }
+ }
+ return out
+}
+
+// earnedView is the steady view of a month so far: ARR spread over the
+// year and counted to today, that month's once-offs and refunds, and the
+// platform cost.
+type earnedView struct {
+ Month string
+ MRR, OnceOff, Refunds int64
+ Platform platformCost
+}
+
+// Profit is MRR + OnceOff + Refunds − the platform cost. Refunds are
+// negative, so they come off (spec §4.6 per-account: "less refunds").
+func (e earnedView) Profit() int64 { return e.MRR + e.OnceOff + e.Refunds - e.Platform.Cents }
+
+// earnedSoFar is m's earned view on now: MRR = round(ARR ÷ 12 ×
+// day-of-month ÷ days-in-month), rounded once.
+func earnedSoFar(arr arrTotals, m moneyMonth, now time.Time) earnedView {
+ dim := int64(daysInMonthOf(now))
+ return earnedView{
+ Month: m.Month,
+ MRR: divRound(arr.EUR*int64(now.UTC().Day()), 12*dim),
+ OnceOff: m.OnceOff,
+ Refunds: m.Refunds,
+ Platform: m.Platform,
+ }
+}
+
+// accountEarnings is what each account earned in month ("2006-01") from
+// the stored days: ARR ÷ 12, prorated by calendar day. covered is true only
+// when every day of the month has a stored snapshot that is Complete; with
+// no carry-forward, one missing or incomplete day leaves the month not
+// covered and by nil. When covered, each day an account's row is InARR
+// adds AnnualEUR / 12 / days-in-month, summed exactly and rounded once; a
+// cancelling account (not InARR) adds nothing. Pure.
+func accountEarnings(month string, days []accountDay, snaps []arrSnapshot) (by map[int64]int64, covered bool) {
+ start, err := time.Parse("2006-01", month)
+ if err != nil {
+ return nil, false
+ }
+ dim := daysInMonthOf(start)
+ complete := map[string]bool{}
+ for _, s := range snaps {
+ if s.Complete {
+ complete[s.Day] = true
+ }
+ }
+ for d := 0; d < dim; d++ {
+ if !complete[start.AddDate(0, 0, d).Format(snapshotDayFormat)] {
+ return nil, false
+ }
+ }
+ sums := map[int64]int64{}
+ for _, r := range days {
+ if r.InARR && strings.HasPrefix(r.Day, month+"-") {
+ sums[r.AccountID] += r.AnnualEUR
+ }
+ }
+ by = map[int64]int64{}
+ for id, sum := range sums {
+ by[id] = divRound(sum, 12*int64(dim))
+ }
+ return by, true
+}
+
+// accountMoney is one account's raw money parts for a month: the page
+// builds the figures from it (accountFigures).
+type accountMoney struct {
+ Fact billingFact
+ Group billingGroup
+ Recurring int64 // euro cents, accountEarnings
+ // OnceOff is that month's once-off less refunds, Settled − SettledTax,
+ // in euro cents.
+ OnceOff int64
+ OnceOffCurrencies []string // the settled currencies OnceOff converts
+ CostUSD float64 // Economics' estimate
+ HasCost bool // Economics has a row for the account
+ NearUsed int64
+ NearLimit int64
+ NearCap capID
+}
+
+// accountMoneyRows is every fact's money parts, in facts' order: its group,
+// what it earned (earned, by account id), its once-off less refunds from
+// monthRows (the month's payments, Kind "": no fee rows; unmatched rows
+// left out), its Economics cost (costUSD, by sqid) and its nearest cap.
+func accountMoneyRows(facts []billingFact, exemptID int64, earned map[int64]int64, monthRows []paymentRow, costUSD map[string]float64, near map[int64]capState, r eurRates) []accountMoney {
+ onceOff := map[int64]int64{}
+ currencies := map[int64]map[string]bool{}
+ for _, p := range monthRows {
+ if p.AccountID == 0 || (p.Kind != billing.PaymentOnceOff && p.Kind != billing.PaymentRefund) {
+ continue
+ }
+ cur := strings.ToLower(p.SettledCurrency)
+ onceOff[p.AccountID] += settledEUR(r, p.Settled-p.SettledTax, cur)
+ if currencies[p.AccountID] == nil {
+ currencies[p.AccountID] = map[string]bool{}
+ }
+ currencies[p.AccountID][cur] = true
+ }
+ out := make([]accountMoney, 0, len(facts))
+ for _, f := range facts {
+ a := accountMoney{
+ Fact: f,
+ Group: billingGroupOf(f, exemptID),
+ Recurring: earned[f.AccountID],
+ OnceOff: onceOff[f.AccountID],
+ }
+ if cs := currencies[f.AccountID]; len(cs) > 0 {
+ a.OnceOffCurrencies = slices.Sorted(maps.Keys(cs))
+ }
+ a.CostUSD, a.HasCost = costUSD[f.Sqid]
+ if st, ok := near[f.AccountID]; ok {
+ a.NearUsed, a.NearLimit, a.NearCap = st.Used, st.Limit, st.Cap
+ }
+ out = append(out, a)
+ }
+ return out
+}
+
+// accountFigures are an account's earns, costs and margin for the last
+// complete month before in.Now, the figures the overview and the accounts
+// page both show. Earns (recurring plus once-off) declares inPayments and
+// the once-off currencies' rates; costs (Economics' estimate, in usd)
+// declare inEconomics and the usd rate; margin declares both. When the
+// stored days do not cover the month (covered false), earns and margin are
+// refused with the history reason whatever the gate. r is in.Rates. Names
+// are prefix + ".earns", ".costs", ".margin".
+func accountFigures(figs *[]opMoneyFigure, a accountMoney, covered bool, in moneyInputs, r eurRates, prefix string) (earns, costs, margin opMoneyFigure) {
+ month := lastCompleteMonth(in.Now)
+ earnsUse := moneyUse{Inputs: inPayments | ratesUse(a.OnceOffCurrencies...), Currencies: a.OnceOffCurrencies}
+ costsUse := moneyUse{Inputs: inEconomics | inRates, Currencies: []string{"usd"}}
+ union := slices.Clone(a.OnceOffCurrencies)
+ if !slices.Contains(union, "usd") {
+ union = append(union, "usd")
+ }
+ slices.Sort(union)
+ marginUse := moneyUse{Inputs: earnsUse.Inputs | costsUse.Inputs, Currencies: union}
+
+ earned := a.Recurring + a.OnceOff
+ var cost int64
+ if a.HasCost {
+ cost = settledEUR(r, int64(math.Round(a.CostUSD*100)), "usd")
+ }
+ if covered {
+ earns = opMoney(figs, prefix+".earns", in, earnsUse, nil, func() string { return eurText(earned) })
+ } else {
+ earns = opMoneyHistoryRefused(figs, prefix+".earns", earnsUse, month)
+ }
+ costs = opMoney(figs, prefix+".costs", in, costsUse, nil, func() string { return eurText(cost) })
+ if covered {
+ margin = opMoney(figs, prefix+".margin", in, marginUse, nil, func() string { return eurText(earned - cost) })
+ } else {
+ margin = opMoneyHistoryRefused(figs, prefix+".margin", marginUse, month)
+ }
+ return earns, costs, margin
+}
diff --git a/internal/console/opbilling_money_test.go b/internal/console/opbilling_money_test.go
new file mode 100644
index 000000000..a41b0efe1
--- /dev/null
+++ b/internal/console/opbilling_money_test.go
@@ -0,0 +1,464 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/economics"
+)
+
+func TestEconComplete(t *testing.T) {
+ good := func() *EconomicsView { return &EconomicsView{CoveredDays: 31, PeriodDays: 31} }
+ if !econComplete(good(), nil) {
+ t.Fatal("a complete view is not complete")
+ }
+ for name, v := range map[string]func(v *EconomicsView){
+ "warning": func(v *EconomicsView) { v.Warning = "no registry" },
+ "scenario warning": func(v *EconomicsView) { v.ScenarioWarning = "bad scenario" },
+ "read failure": func(v *EconomicsView) { v.ReadFailures = 1 },
+ "uncovered day": func(v *EconomicsView) { v.CoveredDays = 30 },
+ } {
+ g := good()
+ v(g)
+ if econComplete(g, nil) {
+ t.Errorf("%s: complete", name)
+ }
+ }
+ if econComplete(good(), errors.New("sweep failed")) {
+ t.Error("an error: complete")
+ }
+ if econComplete(nil, nil) {
+ t.Error("no view: complete")
+ }
+}
+
+func TestEURText(t *testing.T) {
+ for _, tc := range []struct {
+ cents int64
+ want string
+ }{
+ {0, "€0.00"},
+ {2400, "€24.00"},
+ {120000, "€1,200.00"},
+ {-18800, "−€188.00"},
+ {5, "€0.05"},
+ {-45, "−€0.45"},
+ {123456789, "€1,234,567.89"},
+ } {
+ if got := eurText(tc.cents); got != tc.want {
+ t.Errorf("eurText(%d) = %q, want %q", tc.cents, got, tc.want)
+ }
+ }
+}
+
+func TestMinorText(t *testing.T) {
+ for _, tc := range []struct {
+ minor int64
+ currency string
+ want string
+ }{
+ {2800, "usd", "$28.00"},
+ {2200, "gbp", "£22.00"},
+ {2400, "eur", "€24.00"},
+ {2800, "chf", "28.00 CHF"},
+ {-2800, "usd", "−$28.00"},
+ {-2800, "chf", "−28.00 CHF"},
+ {123456, "usd", "$1,234.56"},
+ {2800, "USD", "$28.00"},
+ } {
+ if got := minorText(tc.minor, tc.currency); got != tc.want {
+ t.Errorf("minorText(%d, %q) = %q, want %q", tc.minor, tc.currency, got, tc.want)
+ }
+ }
+}
+
+func TestOpMoneyRefusesAndRecords(t *testing.T) {
+ now := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)
+ platform := map[string]platformCost{"2026-10": {Hint: "the October hint"}}
+ var figs []opMoneyFigure
+ calls := 0
+ format := func() string { calls++; return "€1.00" }
+
+ f := opMoney(&figs, "ready", goodMoneyInputs(now), moneyUse{Inputs: inPayments}, platform, format)
+ if !f.Shown || f.Text != "€1.00" || f.Reason != "" || f.Why != "" || calls != 1 {
+ t.Errorf("ready: %+v, %d calls", f, calls)
+ }
+
+ broken := goodMoneyInputs(now)
+ broken.Reconciled = now.Add(-3 * time.Hour)
+ f = opMoney(&figs, "declared", broken, moneyUse{Inputs: inPayments}, platform, format)
+ if f.Shown || calls != 1 || f.Text != billCopyNotAvailable || f.Why != moneyWhyPayments || f.Reason != billCopyWhyPayments {
+ t.Errorf("declared input broken: %+v, %d calls", f, calls)
+ }
+
+ f = opMoney(&figs, "undeclared", broken, moneyUse{Inputs: inFacts}, platform, format)
+ if !f.Shown || f.Text != "€1.00" || calls != 2 {
+ t.Errorf("undeclared input broken: %+v", f)
+ }
+
+ noPlatform := goodMoneyInputs(now)
+ noPlatform.PlatformOK = map[string]bool{"2026-10": false}
+ f = opMoney(&figs, "platform", noPlatform, moneyUse{Inputs: inPlatform, Month: "2026-10"}, platform, format)
+ if f.Shown || f.Why != moneyWhyPlatform || f.Reason != "the October hint" || calls != 2 {
+ t.Errorf("platform: %+v", f)
+ }
+
+ // Every reason code has its approved text.
+ for why, want := range map[string]string{
+ moneyWhyFacts: billCopyWhyFacts, moneyWhyPayments: billCopyWhyPayments, moneyWhyRates: billCopyWhyRates,
+ moneyWhyAmounts: billCopyWhyAmounts, moneyWhyEconomics: billCopyWhyEconomics,
+ } {
+ if got := moneyReasonText(why, "", platform); got != want {
+ t.Errorf("reason %s = %q, want %q", why, got, want)
+ }
+ }
+
+ var names []string
+ for _, f := range figs {
+ names = append(names, f.Name)
+ }
+ if want := []string{"ready", "declared", "undeclared", "platform"}; !reflect.DeepEqual(names, want) {
+ t.Errorf("recorded %v, want %v", names, want)
+ }
+}
+
+// TestMoneyFormattersOnlyInsideOpMoney: eurText and minorText are used
+// only inside a function literal passed as opMoney's last argument,
+// anywhere in the package's non-test code, so no money is formatted
+// outside the gate, and no template func map can name them.
+func TestMoneyFormattersOnlyInsideOpMoney(t *testing.T) {
+ paths, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fset := token.NewFileSet()
+ inside := 0
+ for _, path := range paths {
+ if strings.HasSuffix(path, "_test.go") {
+ continue
+ }
+ src, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ file, err := parser.ParseFile(fset, path, src, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var stack []ast.Node
+ ast.Inspect(file, func(n ast.Node) bool {
+ if n == nil {
+ stack = stack[:len(stack)-1]
+ return true
+ }
+ defer func() { stack = append(stack, n) }()
+ id, ok := n.(*ast.Ident)
+ if !ok || (id.Name != "eurText" && id.Name != "minorText") {
+ return true
+ }
+ if fd, ok := stack[len(stack)-1].(*ast.FuncDecl); ok && fd.Name == id {
+ return true // the declaration
+ }
+ if formatArgOfOpMoney(stack) {
+ inside++
+ return true
+ }
+ t.Errorf("%s: %s used outside an opMoney format function", fset.Position(id.Pos()), id.Name)
+ return true
+ })
+ }
+ if inside == 0 {
+ t.Error("found no formatter inside opMoney: the check sees nothing")
+ }
+}
+
+// formatArgOfOpMoney reports whether some function literal on stack is the
+// last argument of a call to opMoney.
+func formatArgOfOpMoney(stack []ast.Node) bool {
+ for i := len(stack) - 1; i > 0; i-- {
+ lit, ok := stack[i].(*ast.FuncLit)
+ if !ok {
+ continue
+ }
+ call, ok := stack[i-1].(*ast.CallExpr)
+ if !ok || len(call.Args) == 0 || call.Args[len(call.Args)-1] != ast.Expr(lit) {
+ continue
+ }
+ if fn, ok := call.Fun.(*ast.Ident); ok && fn.Name == "opMoney" {
+ return true
+ }
+ }
+ return false
+}
+
+// pay is a payment row for the money tests.
+func pay(kind billing.PaymentKind, reason string, at time.Time, settled, settledTax, fee int64, currency string) paymentRow {
+ return paymentRow{Payment: billing.Payment{
+ Movement: fmt.Sprintf("mv_%s_%d_%d", kind, at.Unix(), settled), Kind: kind, Reason: reason,
+ Amount: settled, Tax: settledTax, Currency: currency,
+ Settled: settled, SettledTax: settledTax, Fee: fee, SettledCurrency: currency, At: at,
+ }}
+}
+
+func TestMoneyByMonth(t *testing.T) {
+ oct := func(d int) time.Time { return time.Date(2026, 10, d, 12, 0, 0, 0, time.UTC) }
+ first := pay(billing.PaymentSubscription, billing.ReasonFirst, oct(3), 2610, 0, 106, "eur")
+ first.Amount, first.Currency = 2800, "usd"
+ rows := []paymentRow{
+ first,
+ pay(billing.PaymentOnceOff, billing.ReasonOther, oct(10), 2904, 504, 72, "eur"),
+ pay(billing.PaymentRefund, billing.ReasonOther, oct(12), -1452, -252, 0, "eur"),
+ pay(billing.PaymentFee, billing.ReasonOther, oct(20), -45, 0, 0, "eur"),
+ // September: a usd-settled once-off at usd 1.12.
+ pay(billing.PaymentOnceOff, billing.ReasonOther, time.Date(2026, 9, 5, 0, 0, 0, 0, time.UTC), 1120, 0, 0, "usd"),
+ // Outside the months asked for.
+ pay(billing.PaymentOnceOff, billing.ReasonOther, time.Date(2026, 8, 5, 0, 0, 0, 0, time.UTC), 999, 0, 0, "eur"),
+ }
+ r := eurRates{Day: "2026-11-06", PerEUR: map[string]float64{"usd": 1.12}}
+ platform := map[string]platformCost{"2026-10": {Cents: 5000, OK: true, Label: "x"}}
+ got := moneyByMonth(rows, []string{"2026-11", "2026-10", "2026-09"}, r, platform)
+ want := []moneyMonth{
+ {Month: "2026-11"},
+ {Month: "2026-10", Subscriptions: 2610, OnceOff: 2400, Refunds: -1200, Tax: 252, Fees: 223,
+ Net: 2610 + 2400 - 1200 - 223, Currencies: []string{"eur"}, Platform: platform["2026-10"]},
+ {Month: "2026-09", OnceOff: 1000, Net: 1000, Currencies: []string{"usd"}},
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("moneyByMonth:\n got %+v\nwant %+v", got, want)
+ }
+}
+
+func TestMoneyByMonthRefundTaxExclusive(t *testing.T) {
+ at := time.Date(2026, 10, 4, 0, 0, 0, 0, time.UTC)
+ rows := []paymentRow{
+ pay(billing.PaymentOnceOff, billing.ReasonOther, at, 12000, 2000, 380, "eur"),
+ pay(billing.PaymentRefund, billing.ReasonOther, at.Add(time.Hour), -12000, -2000, 0, "eur"),
+ }
+ got := moneyByMonth(rows, []string{"2026-10"}, eurRates{}, nil)[0]
+ if got.OnceOff != 10000 || got.Refunds != -10000 || got.Tax != 0 || got.Fees != 380 || got.Net != -380 {
+ t.Errorf("fully refunded charge: %+v", got)
+ }
+}
+
+func TestEarnedSoFar(t *testing.T) {
+ now := time.Date(2026, 11, 9, 15, 0, 0, 0, time.UTC)
+ m := moneyMonth{Month: "2026-11", OnceOff: 500, Refunds: -100, Platform: platformCost{Cents: 300, OK: true}}
+ e := earnedSoFar(arrTotals{EUR: 2400}, m, now)
+ if e.Month != "2026-11" || e.MRR != 60 || e.OnceOff != 500 || e.Refunds != -100 || e.Platform.Cents != 300 {
+ t.Errorf("earnedSoFar = %+v", e)
+ }
+ if p := e.Profit(); p != 60+500-100-300 {
+ t.Errorf("profit = %d", p)
+ }
+}
+
+// octoberSnaps is a complete snapshot for every day of October 2026.
+func octoberSnaps() []arrSnapshot {
+ var out []arrSnapshot
+ for d := 1; d <= 31; d++ {
+ out = append(out, arrSnapshot{Day: fmt.Sprintf("2026-10-%02d", d), Complete: true})
+ }
+ return out
+}
+
+// octoberRows is one account's row for every day of October.
+func octoberRows(account, annualEUR int64, paying, in bool) []accountDay {
+ var out []accountDay
+ for d := 1; d <= 31; d++ {
+ out = append(out, accountDay{Day: fmt.Sprintf("2026-10-%02d", d), AccountID: account,
+ Annual: annualEUR, Currency: "eur", AnnualEUR: annualEUR, Paying: paying, InARR: in})
+ }
+ return out
+}
+
+func TestAccountEarningsOctober(t *testing.T) {
+ by, covered := accountEarnings("2026-10", octoberRows(1, 120000, true, true), octoberSnaps())
+ if !covered || by[1] != 10000 {
+ t.Errorf("by = %v, covered %v; want account 1 at 10000", by, covered)
+ }
+}
+
+func TestAccountEarningsNovemberSignup(t *testing.T) {
+ // B (2) first paid on 7 Nov: October's rows do not hold it.
+ days := octoberRows(1, 120000, true, true)
+ days = append(days, accountDay{Day: "2026-11-07", AccountID: 2, AnnualEUR: 120000, Paying: true, InARR: true})
+ snaps := append(octoberSnaps(), arrSnapshot{Day: "2026-11-07", Complete: true})
+ by, covered := accountEarnings("2026-10", days, snaps)
+ if !covered || by[2] != 0 || by[1] != 10000 {
+ t.Errorf("by = %v, covered %v", by, covered)
+ }
+}
+
+func TestAccountEarningsNovemberTermination(t *testing.T) {
+ // C (3) ended on 3 Nov: October still earned in full.
+ by, covered := accountEarnings("2026-10", octoberRows(3, 120000, true, true), octoberSnaps())
+ if !covered || by[3] != 10000 {
+ t.Errorf("by = %v, covered %v", by, covered)
+ }
+}
+
+func TestAccountEarningsCancelling(t *testing.T) {
+ by, covered := accountEarnings("2026-10", octoberRows(4, 120000, true, false), octoberSnaps())
+ if !covered || by[4] != 0 {
+ t.Errorf("by = %v, covered %v", by, covered)
+ }
+}
+
+func TestAccountEarningsPartialMonthRoundsOnce(t *testing.T) {
+ // 10 days at €1,000 a year: 100000 × 10 / (12 × 31) = 2688.17 → 2688,
+ // where rounding each day (268.8 → 269) would give 2690.
+ var days []accountDay
+ for d := 1; d <= 10; d++ {
+ days = append(days, accountDay{Day: fmt.Sprintf("2026-10-%02d", d), AccountID: 5, AnnualEUR: 100000, Paying: true, InARR: true})
+ }
+ by, covered := accountEarnings("2026-10", days, octoberSnaps())
+ if !covered || by[5] != 2688 {
+ t.Errorf("by = %v, covered %v", by, covered)
+ }
+}
+
+func TestAccountEarningsNotCovered(t *testing.T) {
+ first := []arrSnapshot{{Day: "2026-11-09", Complete: true}}
+ days := []accountDay{{Day: "2026-11-09", AccountID: 1, AnnualEUR: 120000, Paying: true, InARR: true}}
+ for _, month := range []string{"2026-10", "2026-11"} {
+ if by, covered := accountEarnings(month, days, first); covered || by != nil {
+ t.Errorf("%s with the first snapshot on 9 Nov: by %v, covered %v", month, by, covered)
+ }
+ }
+ incomplete := octoberSnaps()
+ incomplete[14].Complete = false
+ if by, covered := accountEarnings("2026-10", octoberRows(1, 120000, true, true), incomplete); covered || by != nil {
+ t.Errorf("one incomplete day: by %v, covered %v", by, covered)
+ }
+ missing := octoberSnaps()
+ missing = append(missing[:14], missing[15:]...)
+ if by, covered := accountEarnings("2026-10", octoberRows(1, 120000, true, true), missing); covered || by != nil {
+ t.Errorf("one missing day: by %v, covered %v", by, covered)
+ }
+}
+
+// accountFiguresWorld is a paying usd account with an October once-off in
+// gbp and an Economics cost.
+func accountFiguresWorld(t *testing.T) accountMoney {
+ t.Helper()
+ facts := []billingFact{{AccountID: 7, Sqid: "acc7", Name: "shop", Subscription: "sub_1", Billable: true,
+ Paid: true, Currency: "usd", Annual: 24000}}
+ gbp := pay(billing.PaymentOnceOff, billing.ReasonDomain, time.Date(2026, 10, 12, 0, 0, 0, 0, time.UTC), 1200, 200, 50, "gbp")
+ gbp.AccountID = 7
+ r := goodMoneyInputs(time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)).Rates
+ rows := accountMoneyRows(facts, 1, map[int64]int64{7: 1786}, []paymentRow{gbp},
+ map[string]float64{"acc7": 3.36}, nil, r)
+ if len(rows) != 1 {
+ t.Fatalf("rows = %+v", rows)
+ }
+ a := rows[0]
+ // 1000 gbp pence at 0.87 per euro is 1149 cents.
+ if a.Group != groupPaying || a.Recurring != 1786 || a.OnceOff != 1149 ||
+ !reflect.DeepEqual(a.OnceOffCurrencies, []string{"gbp"}) || !a.HasCost || a.CostUSD != 3.36 {
+ t.Fatalf("account money = %+v", a)
+ }
+ return a
+}
+
+func TestAccountFiguresGateInvariant(t *testing.T) {
+ now := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)
+ a := accountFiguresWorld(t)
+ checkGateInvariant(t, goodMoneyInputs(now), func(in moneyInputs) []moneyFigure {
+ var figs []opMoneyFigure
+ accountFigures(&figs, a, true, in, in.Rates, "acc7")
+ var out []moneyFigure
+ for _, f := range figs {
+ out = append(out, f.moneyFigure)
+ }
+ return out
+ })
+
+ var figs []opMoneyFigure
+ earns, costs, margin := accountFigures(&figs, a, true, goodMoneyInputs(now), goodMoneyInputs(now).Rates, "acc7")
+ // 3.36 usd at 1.12 is 300 cents.
+ if earns.Text != "€29.35" || costs.Text != "€3.00" || margin.Text != "€26.35" {
+ t.Errorf("figures: %q %q %q", earns.Text, costs.Text, margin.Text)
+ }
+ if len(figs) != 3 {
+ t.Errorf("recorded %d figures, want 3", len(figs))
+ }
+
+ // Not covered: earns and margin carry the history reason whatever the
+ // gate; costs do not depend on the history.
+ history := fmt.Sprintf(billCopyWhyHistory, "October 2026")
+ for _, in := range []moneyInputs{goodMoneyInputs(now), func() moneyInputs {
+ in := goodMoneyInputs(now)
+ in.Reconciled = time.Time{}
+ return in
+ }()} {
+ figs = nil
+ earns, costs, margin = accountFigures(&figs, a, false, in, in.Rates, "acc7")
+ for _, f := range []opMoneyFigure{earns, margin} {
+ if f.Shown || f.Why != moneyWhyHistory || f.Reason != history || f.Text != billCopyNotAvailable {
+ t.Errorf("not covered: %+v", f)
+ }
+ }
+ if !costs.Shown {
+ t.Errorf("not covered: costs refused: %+v", costs)
+ }
+ if len(figs) != 3 {
+ t.Errorf("not covered: recorded %d figures, want 3", len(figs))
+ }
+ }
+}
+
+func TestPlatformCostEUR(t *testing.T) {
+ const month = "2026-10"
+ r := eurRates{Day: "2026-11-06", PerEUR: map[string]float64{"usd": 1.10}}
+ bill := func(basis, source string, usd float64) economics.Bill {
+ return economics.Bill{Schema: 1, Month: month, TotalUSD: usd,
+ Services: map[string]float64{"AmazonEC2": usd}, Source: source, Basis: basis}
+ }
+ const (
+ c1 = "AWS, whole account: CARLOS only"
+ c3 = "This bill covers the whole AWS account, which may hold more than CARLOS. If the account runs only CARLOS, set CONSOLE_COST_ACCOUNT_CARLOS_ONLY=true on the console."
+ c4 = "No AWS bill on file for 2026-10 yet."
+ c7 = "This bill was entered as covering the whole AWS account, CARLOS and other things, so it does not count as CARLOS cost."
+ )
+ for _, tc := range []struct {
+ name string
+ bill *economics.Bill
+ scope CostScope
+ rates eurRates
+ want platformCost
+ }{
+ {name: "account bill", bill: ptrBill(bill("account", economics.SourceCostExplorer, 110)), rates: r,
+ want: platformCost{Cents: 10000, Basis: economics.BasisAccount, Label: c1, OK: true}},
+ {name: "account bill, no usd rate", bill: ptrBill(bill("account", economics.SourceCostExplorer, 110)),
+ rates: eurRates{Day: "2026-11-06", PerEUR: map[string]float64{"gbp": 0.87}},
+ want: platformCost{Basis: economics.BasisAccount, Label: c1, Hint: billCopyWhyRates, OK: true}},
+ {name: "unstated bill zero scope", bill: ptrBill(bill("", economics.SourceCostExplorer, 110)), rates: r,
+ want: platformCost{Basis: economics.BasisUnstated, Label: costLabelOther, Hint: c3}},
+ {name: "manual whole bill account scope", bill: ptrBill(bill("whole", economics.SourceManual, 110)),
+ scope: CostScope{AccountCarlosOnly: true}, rates: r,
+ want: platformCost{Basis: economics.BasisWhole, Label: costLabelOther, Hint: c7}},
+ {name: "no bill", rates: r, want: platformCost{Basis: costBasisMissing, Label: costLabelOther, Hint: c4}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.CostScope = tc.scope
+ if tc.bill != nil {
+ putStoreJSON(t, fx.rel, economics.BillKey(month), *tc.bill)
+ }
+ if got := fx.srv.platformCostEUR(context.Background(), month, tc.rates); got != tc.want {
+ t.Errorf("platformCostEUR = %+v, want %+v", got, tc.want)
+ }
+ })
+ }
+}