carlos / platform Public

console: the billing overview

Billing dashboard Plan 2, Task 4: /fleet/billing in the approved mockup's
order. Tiles (ARR, MRR, received this month, paying accounts, needs
attention), ARR by day from the stored snapshots, the five newest paying
accounts with last month's earns, costs and margin, earned this month
beside the sign-up funnel, money received by month, recent payments, new
paying accounts by week, not paying by reason with Shared and idle, and
the free accounts closest to a limit.

- buildOpBillingView is pure over opBillingInput; every money figure goes
  through opMoney with the gate in Gate, and Figures lists them all.
- Store.BillingFunnel and Store.NearestCaps (opbilling_store.go).
- Whole rows are links (co-rowlink); new co-cols sets with phone rules.
- usageCapLabels shared by the usage summary and the limits list.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 706f8ae3fccfb4b9520b1e7153f33ab2f49f4b73 parent 81e51d2
8 files changed, +1,964 −15
  • internal/console/billingusage.go +6 −3
  • internal/console/opbilling.go +85 −10
  • internal/console/opbilling_overview.go +823 −0
  • internal/console/opbilling_store.go +83 −0
  • internal/console/opbilling_store_test.go +135 −0
  • internal/console/opbilling_test.go +655 −0
  • internal/console/static/ops.css +40 −0
  • internal/console/templates/ops_billing.html +137 −2
diff --git a/internal/console/billingusage.go b/internal/console/billingusage.go
index ccf9cec7a..1c3cd86c5 100644
--- a/internal/console/billingusage.go
+++ b/internal/console/billingusage.go
@@ -23,6 +23,11 @@ import (
// usageCaps are the caps the page shows, in order.
var usageCaps = []capID{capRunningThings, capStorage, capEmail, capBandwidth, capPDF}
+// usageCapLabels is each of usageCaps' label key in billingCopy: the usage
+// summary's rows and the billing overview's nearest limit.
+var usageCapLabels = map[capID]string{capRunningThings: "usage.label.running", capStorage: "usage.label.storage",
+ capEmail: "usage.label.email", capBandwidth: "usage.label.bandwidth", capPDF: "usage.label.pdf"}
+
// billingUse is a use beside a limit as the page shows it. Level is ""
// below 80% of the limit, "warn" from 80% up to it, "over" past it.
type billingUse struct {
@@ -190,15 +195,13 @@ func addUsage(v *billingView, cat *plans.Catalog, rows []capState, members int,
if !inPacks || v.limits.PDFRendersMonth > 0 {
// No pack row carries it (a member, or no packs to change): the
// summary lists it instead.
- labels := map[capID]string{capRunningThings: "usage.label.running", capStorage: "usage.label.storage",
- capEmail: "usage.label.email", capBandwidth: "usage.label.bandwidth", capPDF: "usage.label.pdf"}
for _, c := range usageCaps {
// PDFs have no pack row, so their usage always belongs in the summary.
if inPacks && c != capPDF {
continue
}
if use := useOfLimit(used, c, capLimit(*v.limits, c)); use != nil {
- u.Rows = append(u.Rows, billingUsageRow{Label: billingCopy[labels[c]], Use: use})
+ u.Rows = append(u.Rows, billingUsageRow{Label: billingCopy[usageCapLabels[c]], Use: use})
}
}
if len(u.Rows) == 0 {
diff --git a/internal/console/opbilling.go b/internal/console/opbilling.go
index 01dba271c..b7655e391 100644
--- a/internal/console/opbilling.go
+++ b/internal/console/opbilling.go
@@ -1,8 +1,11 @@
package console
import (
+ "context"
"fmt"
+ "log"
"net/http"
+ "time"
)
// The operator Billing pages (billing dashboard plan 2, spec 2026-11-09
@@ -14,12 +17,6 @@ import (
// exactly as a missing route does, operators included. Every word comes
// from opbilling_copy.go.
-// opBillingView is the overview's data.
-type opBillingView struct {
- Header opHeader
- TestMode bool
-}
-
// opBillingAccountsView is the accounts list's data.
type opBillingAccountsView struct {
Header opHeader
@@ -67,14 +64,92 @@ func (s *Server) handleOpBilling(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- p := s.billingPage(addr, raw, billCopyRail)
- p.OpBilling = &opBillingView{
- Header: opHeader{Title: billCopyRail, Sub: fmt.Sprintf(billCopyOverviewSub, s.brandName())},
- TestMode: s.billingTestMode(),
+ in, err := s.opBillingInputs(r.Context(), s.now())
+ if err != nil {
+ log.Printf("console: billing overview: %v", err)
+ http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
+ return
}
+ p := s.billingPage(addr, raw, billCopyRail)
+ v := buildOpBillingView(in)
+ v.Header = opHeader{Title: billCopyRail, Sub: fmt.Sprintf(billCopyOverviewSub, s.brandName())}
+ v.TestMode = s.billingTestMode()
+ p.OpBilling = v
s.render(w, http.StatusOK, "ops_billing", p)
}
+// opBillingInputs gathers the overview's inputs at now: the revenue and
+// facts, six months of payments with fee rows (the money table and this
+// month) and last month's without (per-account once-offs), 90 days of
+// snapshots and last month's account rows (per-account earnings), the
+// newest payments, last month's Economics read (an error is logged;
+// econComplete decides whether costs show), each month's platform cost,
+// the funnel and the nearest caps. The gate is Rev.Inputs with the cost
+// inputs filled in.
+func (s *Server) opBillingInputs(ctx context.Context, now time.Time) (opBillingInput, error) {
+ rev, facts, err := s.billingRevenueNow(now)
+ if err != nil {
+ return opBillingInput{}, err
+ }
+ in := opBillingInput{Now: now, Rev: rev, Facts: facts, ExemptID: s.store.planExemptID, Rates: rev.Inputs.Rates}
+ utc := now.UTC()
+ monthStart := time.Date(utc.Year(), utc.Month(), 1, 0, 0, 0, 0, time.UTC)
+ months := make([]string, 6)
+ for i := range months {
+ months[i] = monthStart.AddDate(0, -i, 0).Format("2006-01")
+ }
+ in.LastMonth = months[1]
+ in.Gate = rev.Inputs
+ in.Gate.PlatformOK = map[string]bool{}
+ in.Platform = map[string]platformCost{}
+ for _, m := range months {
+ pc := s.platformCostEUR(ctx, m, in.Rates)
+ in.Platform[m], in.Gate.PlatformOK[m] = pc, pc.OK
+ }
+ all, _, err := s.store.Payments(paymentFilter{From: monthStart.AddDate(0, -5, 0), To: now, Kind: "all"})
+ if err != nil {
+ return opBillingInput{}, err
+ }
+ in.Months = moneyByMonth(all, months, in.Rates, in.Platform)
+ lastStart := monthStart.AddDate(0, -1, 0)
+ if in.LastRows, _, err = s.store.Payments(paymentFilter{From: lastStart, To: monthStart}); err != nil {
+ return opBillingInput{}, err
+ }
+ today := opMidnight(now)
+ if in.Snaps, err = s.store.ARRSnapshots(today.AddDate(0, 0, -(opBillingChartDays-1)).Format(snapshotDayFormat),
+ today.Format(snapshotDayFormat)); err != nil {
+ return opBillingInput{}, err
+ }
+ days, err := s.store.AccountDays(lastStart.Format(snapshotDayFormat), monthStart.AddDate(0, 0, -1).Format(snapshotDayFormat))
+ if err != nil {
+ return opBillingInput{}, err
+ }
+ in.Earned, in.Covered = accountEarnings(in.LastMonth, days, in.Snaps)
+ if in.Recent, _, err = s.store.Payments(paymentFilter{Limit: opBillingListMax}); err != nil {
+ return opBillingInput{}, err
+ }
+ econ, econErr := s.LoadEconomics(ctx, "last")
+ if econErr != nil {
+ log.Printf("console: billing overview: economics: %v", econErr)
+ }
+ in.Gate.EconomicsComplete = econComplete(econ, econErr)
+ in.CostUSD = map[string]float64{}
+ if econ != nil {
+ for _, a := range econ.Accounts {
+ in.CostUSD[a.Account] = a.CostUSD
+ }
+ }
+ signed, withApp, active, err := s.store.BillingFunnel(now)
+ if err != nil {
+ return opBillingInput{}, err
+ }
+ in.Funnel = [3]int{signed, withApp, active}
+ if in.Near, err = s.store.NearestCaps(); err != nil {
+ return opBillingInput{}, err
+ }
+ return in, nil
+}
+
// handleOpBillingAccounts is the accounts list.
func (s *Server) handleOpBillingAccounts(w http.ResponseWriter, r *http.Request) {
addr, raw, ok := s.billingPageGate(w, r)
diff --git a/internal/console/opbilling_overview.go b/internal/console/opbilling_overview.go
new file mode 100644
index 000000000..9f96055e5
--- /dev/null
+++ b/internal/console/opbilling_overview.go
@@ -0,0 +1,823 @@
+package console
+
+import (
+ "cmp"
+ "fmt"
+ "maps"
+ "math"
+ "net/url"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+)
+
+// The billing overview (/fleet/billing, spec §5.2), built by one pure
+// function from the inputs handleOpBilling gathers. Every money figure is
+// an opMoneyFigure from opMoney, declaring the inputs it uses; the gate
+// travels in opBillingInput.Gate. Sections follow the approved mockup:
+// tiles, ARR by day, the newest paying accounts, earned this month beside
+// the funnel, money by month, recent payments, new paying accounts by
+// week, not paying by reason, and free accounts closest to their limits.
+
+// opBillingListMax is how many rows a list on the overview shows; each
+// links to its full list.
+const opBillingListMax = 5
+
+// opBillingChartDays is how many days the ARR chart reaches back.
+const opBillingChartDays = 90
+
+// opBillingWeeks is how many weeks the new paying accounts chart shows.
+const opBillingWeeks = 12
+
+// opBillingInput is everything the overview is built from.
+type opBillingInput struct {
+ Now time.Time
+ Rev billingRevenue
+ Gate moneyInputs // Rev.Inputs plus EconomicsComplete and PlatformOK (by month)
+ // Facts and ExemptID are what Rev was totalled from.
+ Facts []billingFact
+ ExemptID int64
+ Rates eurRates
+ Months []moneyMonth // 6, newest first, from the Kind "all" read
+ // LastMonth is the last complete month ("2006-01"); LastRows its
+ // payments (Kind "": no fee rows).
+ LastMonth string
+ LastRows []paymentRow
+ Snaps []arrSnapshot // the last 90 days, oldest first
+ // Earned and Covered are accountEarnings over LastMonth.
+ Earned map[int64]int64
+ Covered bool
+ Recent []paymentRow // the newest 5 (Kind "")
+ CostUSD map[string]float64
+ Platform map[string]platformCost
+ Funnel [3]int // signed up, made an app, active in the last 30 days
+ Near map[int64]capState
+}
+
+// opBillingAccountRow is one account in a billing list. Since is the line
+// under the name ("paying since" on the overview); PlanNote the seats and
+// packs under the plan.
+type opBillingAccountRow struct {
+ Href, Name, Since, Plan, PlanNote string
+ Apps int
+ Earns, Costs, Margin opMoneyFigure
+ Renews, Joined string
+ Status opPill
+}
+
+// opBillingPaymentRow is one payment in a billing list. Href is "" when
+// the account cell is not a link (unmatched, or the account deleted).
+type opBillingPaymentRow struct {
+ Href, When, Account, What string
+ Charged, Net, Fee opMoneyFigure
+ Status opPill
+}
+
+// opBillingReasonRow is one row of not paying, by reason. Shared and idle
+// has no Href and no count.
+type opBillingReasonRow struct {
+ Href, Label string
+ Count int
+ Cost opMoneyFigure
+ Biggest string
+}
+
+// opBillingARRDay is one day of the ARR chart. A day with no complete
+// stored snapshot is not Known: no bar, and not available in the table.
+type opBillingARRDay struct {
+ Day time.Time
+ H int
+ Known bool
+ Value opMoneyFigure
+}
+
+// opBillingLine is one line of the earned panel; Note sits beside the
+// figure (the AWS bill's basis label).
+type opBillingLine struct {
+ Label string
+ Value opMoneyFigure
+ Note string
+ Total bool
+}
+
+// opBillingFunnelRow is one step of the funnel: a count and its share of
+// sign-ups as a meter. Paying is a figure; the reason shows when refused.
+type opBillingFunnelRow struct {
+ Label string
+ Meter opMeter
+ Shown bool
+ Reason string
+}
+
+// opBillingMonthRow is one month of the money table.
+type opBillingMonthRow struct {
+ Href, Label string
+ Subscriptions, OnceOff, Refunds, Tax, Fees, Net, AWS opMoneyFigure
+ Cash opMoneyFigure
+}
+
+// opBillingLimitRow is one free account close to a limit.
+type opBillingLimitRow struct {
+ Href, Name, Limit, Used string
+ Cost opMoneyFigure
+}
+
+// opBillingView is the overview's data. Each list's Whys are the reasons
+// its refused figures give, once each, shown under it.
+type opBillingView struct {
+ Header opHeader
+ TestMode bool
+ RateLine string
+
+ Tiles []opStat
+
+ ARR []opBillingARRDay
+ ARRFrom string
+ ARRGaps string
+
+ PayingList opMoneyFigure
+ Paying []opBillingAccountRow
+ PayingNote string
+ HistoryNote string
+ PayingWhys []string
+
+ EarnedHeading string
+ Earned []opBillingLine
+ EarnedWhys []string
+ Funnel []opBillingFunnelRow
+
+ Months []opBillingMonthRow
+ MonthNotes []string
+ MonthWhys []string
+
+ Recent []opBillingPaymentRow
+ RecentWhys []string
+
+ WeeksFig opMoneyFigure
+ Weeks []dashBar
+
+ CostHeading string
+ Reasons []opBillingReasonRow
+ ReasonWhys []string
+
+ NearLimits []opBillingLimitRow
+ LimitWhys []string
+
+ // Figures is every figure the builder made, in order.
+ Figures []opMoneyFigure
+}
+
+// opBillingWords are the overview's fixed words, every one an approved
+// row of opbilling_copy.go; the template reads them as .W.
+type opBillingWords struct {
+ ARRChart, Today, ARRCaption, ARRDay, ARREUR, ARREmpty string
+ PayingHeading, AllPaying, ColAccount, ColPlan, ColEarns, ColCosts string
+ Estimate, ColMargin, ColRenews, ColStatus, PayingEmpty string
+ FunnelHeading, EarnedNote string
+ MoneyHeading, ColMonth, ColSubscriptions, OnceOff, Refunds, ColTax string
+ ColFees, ColNet, ColAWS, ColCash, MoneyNote string
+ RecentHeading, AllPayments, ColWhen, ColWhat, ColAmount, PaymentsEmpty string
+ WeeklyHeading, ThisWeek, WeeklyCaption, WeeklyWeek, WeeklyCount string
+ ReasonsHeading, AllAccounts, ColWhy, Accounts, ColCostliest, ReasonNote string
+ LimitsHeading, AllFree, ColNearest, ColUsed, LimitsNote, LimitsEmpty string
+ NotAvailable string
+}
+
+var opBillingOverviewWords = opBillingWords{
+ ARRChart: billCopyARRChart, Today: billCopyChartToday, ARRCaption: billCopyARRTableCaption,
+ ARRDay: billCopyARRTableDay, ARREUR: billCopyARRTableEUR, ARREmpty: billCopyARRChartEmpty,
+ PayingHeading: billCopyTilePaying, AllPaying: billCopyAllPaying, ColAccount: billCopyColAccount,
+ ColPlan: billCopyColPlan, ColEarns: billCopyColEarns, ColCosts: billCopyColCosts,
+ Estimate: billCopyEstimate, ColMargin: billCopyColMargin, ColRenews: billCopyColRenews,
+ ColStatus: billCopyColStatus, PayingEmpty: billCopyPayingEmpty,
+ FunnelHeading: billCopyFunnelHeading, EarnedNote: billCopyEarnedNote,
+ MoneyHeading: billCopyMoneyHeading, ColMonth: billCopyColMonth, ColSubscriptions: billCopyColSubscriptions,
+ OnceOff: billCopyOnceOff, Refunds: billCopyRefunds, ColTax: billCopyColTax, ColFees: billCopyColFees,
+ ColNet: billCopyColNet, ColAWS: billCopyColAWS, ColCash: billCopyColCash, MoneyNote: billCopyMoneyNote,
+ RecentHeading: billCopyRecentHeading, AllPayments: billCopyAllPayments, ColWhen: billCopyColWhen,
+ ColWhat: billCopyColWhat, ColAmount: billCopyColAmount, PaymentsEmpty: billCopyPaymentsEmpty,
+ WeeklyHeading: billCopyWeeklyHeading, ThisWeek: billCopyChartThisWeek, WeeklyCaption: billCopyWeeklyTableCaption,
+ WeeklyWeek: billCopyWeeklyTableWeek, WeeklyCount: billCopyWeeklyTableCount,
+ ReasonsHeading: billCopyReasonsHeading, AllAccounts: billCopyAllAccounts, ColWhy: billCopyColWhy,
+ Accounts: billCopyAccounts, ColCostliest: billCopyColCostliest, ReasonNote: billCopyReasonsNote,
+ LimitsHeading: billCopyLimitsHeading, AllFree: billCopyAllFree, ColNearest: billCopyColNearestLimit,
+ ColUsed: billCopyColUsed, LimitsNote: billCopyLimitsNote, LimitsEmpty: billCopyLimitsEmpty,
+ NotAvailable: billCopyNotAvailable,
+}
+
+// W is the overview's fixed words.
+func (*opBillingView) W() opBillingWords { return opBillingOverviewWords }
+
+// opBillingAccountHref is an account's page on the operator pages: the
+// activity view narrowed to it, as People and accounts links it.
+func opBillingAccountHref(sqid string) string {
+ return "/fleet/activity?account=" + url.QueryEscape(sqid)
+}
+
+// opBillingDate is a day as the billing lists write it: 7 Nov 2026.
+func opBillingDate(t time.Time) string {
+ if t.IsZero() {
+ return ""
+ }
+ return t.UTC().Format("2 Jan 2006")
+}
+
+// opBillingRateDay is a rates day ("2006-01-02") as the rate note writes
+// it; anything else as it is.
+func opBillingRateDay(day string) string {
+ t, err := time.Parse(snapshotDayFormat, day)
+ if err != nil {
+ return day
+ }
+ return opBillingDate(t)
+}
+
+// opBillingMonthLabel is a month ("2006-01") as the overview names it:
+// "October" in now's year, "December 2025" in another.
+func opBillingMonthLabel(month string, now time.Time) string {
+ t, err := time.Parse("2006-01", month)
+ if err != nil {
+ return month
+ }
+ if t.Year() == now.UTC().Year() {
+ return t.Format("January")
+ }
+ return t.Format("January 2006")
+}
+
+// opBillingPercent is n of total as a percentage with at most one
+// decimal: 2.6%, 0%, 100%. No total is 0%.
+func opBillingPercent(n, total int) string {
+ if total <= 0 {
+ return "0%"
+ }
+ p := math.Round(float64(n)*1000/float64(total)) / 10
+ return strconv.FormatFloat(p, 'f', -1, 64) + "%"
+}
+
+// opBillingCountDelta is a change in a count over the month, in BDP-20 to
+// BDP-22, and its tone (a rise positive, anything else neutral).
+func opBillingCountDelta(d int) (string, string) {
+ switch {
+ case d > 0:
+ return fmt.Sprintf(billCopyDeltaUp, opNumber(d)), "positive"
+ case d < 0:
+ return fmt.Sprintf(billCopyDeltaDown, opNumber(-d)), "neutral"
+ }
+ return billCopyDeltaNone, "neutral"
+}
+
+// opBillingCurrencies is the union of lists, sorted, each once.
+func opBillingCurrencies(lists ...[]string) []string {
+ seen := map[string]bool{}
+ for _, l := range lists {
+ for _, c := range l {
+ seen[c] = true
+ }
+ }
+ return slices.Sorted(maps.Keys(seen))
+}
+
+// opBillingUse is base plus the rates for currencies, when any is not eur.
+func opBillingUse(base moneyInput, currencies []string, month string) moneyUse {
+ return moneyUse{Inputs: base | ratesUse(currencies...), Currencies: currencies, Month: month}
+}
+
+// opBillingCostUse is a cost estimated from Economics: inEconomics and the
+// usd rate.
+var opBillingCostUse = moneyUse{Inputs: inEconomics | inRates, Currencies: []string{"usd"}}
+
+// opBillingPlatformUse is month's platform cost: inPlatform and the usd
+// rate.
+func opBillingPlatformUse(month string) moneyUse {
+ return moneyUse{Inputs: inPlatform | inRates, Currencies: []string{"usd"}, Month: month}
+}
+
+// opBillingWhys is the reasons of figs not shown, once each, in order.
+func opBillingWhys(figs []opMoneyFigure) []string {
+ var out []string
+ for _, f := range figs {
+ if !f.Shown && f.Reason != "" && !slices.Contains(out, f.Reason) {
+ out = append(out, f.Reason)
+ }
+ }
+ return out
+}
+
+// usdCents is Economics' usd estimate in euro cents at r; 0 with no usd
+// rate (every figure using it declares the usd rate).
+func usdCents(r eurRates, usd float64) int64 {
+ return settledEUR(r, int64(math.Round(usd*100)), "usd")
+}
+
+// buildOpBillingView builds the overview from in. Pure: the same input
+// gives the same view, and every figure goes through opMoney with in.Gate.
+func buildOpBillingView(in opBillingInput) *opBillingView {
+ v := &opBillingView{TestMode: in.Rev.TestMode}
+ if in.Rates.Day != "" {
+ v.RateLine = fmt.Sprintf(billCopyRateNoteLine, opBillingRateDay(in.Rates.Day))
+ }
+ figs := &v.Figures
+ month := in.Now.UTC().Format("2006-01")
+ thisMonth := moneyMonth{Month: month, Platform: in.Platform[month]}
+ if len(in.Months) > 0 {
+ thisMonth = in.Months[0]
+ }
+ arrCur := slices.Sorted(maps.Keys(in.Rev.ByCurrency))
+ arrUse := opBillingUse(inFacts|inPayments|inAmounts, arrCur, "")
+
+ v.Tiles = opBillingTiles(figs, in, thisMonth, arrCur, arrUse)
+ opBillingARRChart(v, in)
+
+ rows := accountMoneyRows(in.Facts, in.ExemptID, in.Earned, in.LastRows, in.CostUSD, in.Near, in.Rates)
+ opBillingPayingList(v, in, rows)
+
+ start := len(*figs)
+ e := earnedSoFar(in.Rev.arrTotals, thisMonth, in.Now)
+ mUse := opBillingUse(inPayments, thisMonth.Currencies, "")
+ v.EarnedHeading = fmt.Sprintf(billCopyEarnedHeading, opBillingMonthLabel(month, in.Now))
+ recurring := opMoney(figs, "earned.recurring", in.Gate, arrUse, in.Platform, func() string { return eurText(e.MRR) })
+ onceOff := opMoney(figs, "earned.onceoff", in.Gate, mUse, in.Platform, func() string { return eurText(e.OnceOff) })
+ refunds := opMoney(figs, "earned.refunds", in.Gate, mUse, in.Platform, func() string { return eurText(e.Refunds) })
+ aws := opMoney(figs, "earned.aws", in.Gate, opBillingPlatformUse(month), in.Platform, func() string { return eurText(e.Platform.Cents) })
+ profitUse := opBillingUse(arrUse.Inputs|mUse.Inputs|inPlatform|inRates,
+ opBillingCurrencies(arrCur, thisMonth.Currencies, []string{"usd"}), month)
+ profit := opMoney(figs, "earned.profit", in.Gate, profitUse, in.Platform, func() string { return eurText(e.Profit()) })
+ awsLine := opBillingLine{Label: billCopyEarnedAWS, Value: aws}
+ if aws.Shown {
+ awsLine.Note = e.Platform.Label
+ }
+ v.Earned = []opBillingLine{
+ {Label: billCopyEarnedRecurring, Value: recurring},
+ {Label: billCopyOnceOff, Value: onceOff},
+ {Label: billCopyRefunds, Value: refunds},
+ awsLine,
+ {Label: billCopyEarnedProfit, Value: profit, Total: true},
+ }
+ v.EarnedWhys = opBillingWhys((*figs)[start:])
+
+ payingFig := opMoney(figs, "funnel.paying", in.Gate, moneyUse{Inputs: inFacts | inPayments}, in.Platform,
+ func() string { return opNumber(in.Rev.Paying) })
+ signed := in.Funnel[0]
+ step := func(label string, n int, f *opMoneyFigure) opBillingFunnelRow {
+ r := opBillingFunnelRow{Label: label, Shown: true, Meter: opMeter{Text: opNumber(n)}}
+ if signed > 0 {
+ r.Meter.Percent = n * 100 / signed
+ }
+ if f != nil && !f.Shown {
+ r = opBillingFunnelRow{Label: label, Meter: opMeter{Text: f.Text}, Reason: f.Reason}
+ }
+ return r
+ }
+ v.Funnel = []opBillingFunnelRow{
+ step(billCopyFunnelSignedUp, in.Funnel[0], nil),
+ step(billCopyFunnelMadeApp, in.Funnel[1], nil),
+ step(billCopyFunnelActive, in.Funnel[2], nil),
+ step(billCopyFunnelPaying, in.Rev.Paying, &payingFig),
+ }
+
+ opBillingMonths(v, in)
+ opBillingRecent(v, in)
+ opBillingWeekly(v, in)
+ opBillingReasons(v, in, rows)
+ opBillingNearLimits(v, in, rows)
+ return v
+}
+
+// opBillingTiles is the band: ARR (with its change this month), MRR,
+// received this month, paying accounts (with theirs) and needs attention.
+func opBillingTiles(figs *[]opMoneyFigure, in opBillingInput, thisMonth moneyMonth, arrCur []string, arrUse moneyUse) []opStat {
+ rev := in.Rev
+ rateNote := fmt.Sprintf(billCopyRateNote, opBillingRateDay(in.Rates.Day))
+ withRate := func(note string, currencies []string) string {
+ if ratesUse(currencies...) != 0 {
+ return note + ", " + rateNote
+ }
+ return note
+ }
+ stat := func(label string, f opMoneyFigure, note string) opStat {
+ s := opStat{Label: label, Value: f.Text, Note: note}
+ if !f.Shown {
+ s.Note = f.Reason
+ }
+ return s
+ }
+
+ monthStart := rev.MonthStart
+ if monthStart != nil && !monthStart.Complete {
+ monthStart = nil
+ }
+ payingUse := moneyUse{Inputs: inFacts | inPayments}
+
+ var arrNote string
+ arr := opMoney(figs, "tile.arr", in.Gate, arrUse, in.Platform, func() string {
+ parts := []string{}
+ for _, c := range arrCur {
+ parts = append(parts, minorText(rev.ByCurrency[c], c))
+ }
+ if len(parts) == 0 {
+ parts = append(parts, eurText(0))
+ }
+ arrNote = withRate(fmt.Sprintf(billCopyARRNote, strings.Join(parts, ", ")), arrCur)
+ return eurText(rev.EUR)
+ })
+ arrTile := stat(billCopyTileARR, arr, arrNote)
+ arrTile.Lead = true
+ if monthStart != nil {
+ tone := "neutral"
+ d := opMoney(figs, "tile.arr.delta", in.Gate, arrUse, in.Platform, func() string {
+ switch diff := rev.EUR - monthStart.EUR; {
+ case diff > 0:
+ tone = "positive"
+ return fmt.Sprintf(billCopyDeltaUp, eurText(diff))
+ case diff < 0:
+ return fmt.Sprintf(billCopyDeltaDown, eurText(-diff))
+ }
+ return billCopyDeltaNone
+ })
+ if d.Shown {
+ arrTile.Delta, arrTile.Tone = d.Text, tone
+ }
+ }
+
+ mrr := opMoney(figs, "tile.mrr", in.Gate, arrUse, in.Platform, func() string { return eurText(divRound(rev.EUR, 12)) })
+ received := opMoney(figs, "tile.received", in.Gate, opBillingUse(inPayments, thisMonth.Currencies, ""), in.Platform,
+ func() string { return eurText(thisMonth.Net) })
+
+ var payingNote string
+ paying := opMoney(figs, "tile.paying", in.Gate, payingUse, in.Platform, func() string {
+ payingNote = fmt.Sprintf(billCopyPayingNote, opNumber(rev.Paying), opNumber(rev.Accounts), opBillingPercent(rev.Paying, rev.Accounts))
+ return opNumber(rev.Paying)
+ })
+ payingTile := stat(billCopyTilePaying, paying, payingNote)
+ if monthStart != nil {
+ var tone string
+ d := opMoney(figs, "tile.paying.delta", in.Gate, payingUse, in.Platform, func() string {
+ var text string
+ text, tone = opBillingCountDelta(rev.Paying - monthStart.Paying)
+ return text
+ })
+ if d.Shown {
+ payingTile.Delta, payingTile.Tone = d.Text, tone
+ }
+ }
+
+ attention := opMoney(figs, "tile.attention", in.Gate, payingUse, in.Platform,
+ func() string { return opNumber(rev.Attention) })
+ return []opStat{
+ arrTile,
+ stat(billCopyTileMRR, mrr, withRate(billCopyMRRNote, arrCur)),
+ stat(billCopyTileReceived, received, withRate(billCopyReceivedNote, thisMonth.Currencies)),
+ payingTile,
+ stat(billCopyTileAttention, attention, billCopyAttentionNote),
+ }
+}
+
+// opBillingARRChart is ARR by day: one slot per day from the first stored
+// snapshot (at most opBillingChartDays back) to today. A day's point shows
+// only when its stored snapshot is Complete; it declares no live input,
+// since the day's own completeness decided it. Any other day has no bar.
+func opBillingARRChart(v *opBillingView, in opBillingInput) {
+ if len(in.Snaps) == 0 {
+ return
+ }
+ today := opMidnight(in.Now)
+ byDay := map[string]arrSnapshot{}
+ first := today
+ for _, s := range in.Snaps {
+ byDay[s.Day] = s
+ if d, err := time.Parse(snapshotDayFormat, s.Day); err == nil && d.Before(first) {
+ first = d
+ }
+ }
+ if earliest := today.AddDate(0, 0, -(opBillingChartDays - 1)); first.Before(earliest) {
+ first = earliest
+ }
+ var top int64
+ gaps := 0
+ for d := first; !d.After(today); d = d.AddDate(0, 0, 1) {
+ day := d.Format(snapshotDayFormat)
+ pt := opBillingARRDay{Day: d, Value: opMoneyFigure{Text: billCopyNotAvailable}}
+ if s, ok := byDay[day]; ok && s.Complete {
+ pt.Known = true
+ pt.Value = opMoney(&v.Figures, "arr."+day, in.Gate, moneyUse{}, in.Platform, func() string { return eurText(s.EUR) })
+ top = max(top, s.EUR)
+ } else {
+ gaps++
+ }
+ v.ARR = append(v.ARR, pt)
+ }
+ for i := range v.ARR {
+ pt := &v.ARR[i]
+ if !pt.Known || top <= 0 {
+ continue
+ }
+ if eur := byDay[pt.Day.Format(snapshotDayFormat)].EUR; eur > 0 {
+ pt.H = max(int(math.Round(20*float64(eur)/float64(top))), 1)
+ }
+ }
+ v.ARRFrom = v.ARR[0].Day.Format("2 Jan")
+ switch {
+ case gaps == 1:
+ v.ARRGaps = billCopyARRGapOne
+ case gaps > 1:
+ v.ARRGaps = fmt.Sprintf(billCopyARRGapMany, opNumber(gaps))
+ }
+}
+
+// opBillingPayingList is the newest paying accounts, by first payment,
+// with the last complete month's earns, costs and margin. The list itself
+// declares the facts and the payments: refused, the reason stands in for
+// the rows.
+func opBillingPayingList(v *opBillingView, in opBillingInput, rows []accountMoney) {
+ start := len(v.Figures)
+ v.PayingList = opMoney(&v.Figures, "paying.list", in.Gate, moneyUse{Inputs: inFacts | inPayments}, in.Platform,
+ func() string { return "" })
+ var paying []accountMoney
+ for _, a := range rows {
+ if a.Group == groupPaying {
+ paying = append(paying, a)
+ }
+ }
+ slices.SortStableFunc(paying, func(a, b accountMoney) int {
+ if c := b.Fact.FirstPaid.Compare(a.Fact.FirstPaid); c != 0 {
+ return c
+ }
+ return cmp.Compare(a.Fact.AccountID, b.Fact.AccountID)
+ })
+ if len(paying) > opBillingListMax {
+ paying = paying[:opBillingListMax]
+ }
+ for _, a := range paying {
+ f := a.Fact
+ earns, costs, margin := accountFigures(&v.Figures, a, in.Covered, in.Gate, in.Rates, "paying."+f.Sqid)
+ row := opBillingAccountRow{
+ Href: opBillingAccountHref(f.Sqid), Name: f.Name, Plan: planLabel(f.Plan), PlanNote: opBillingPlanNote(f),
+ Apps: f.Apps, Earns: earns, Costs: costs, Margin: margin,
+ Renews: opBillingDate(f.PeriodEnd), Joined: opBillingDate(f.Created), Status: opBillingAccountStatus(f),
+ }
+ if !f.FirstPaid.IsZero() {
+ row.Since = fmt.Sprintf(billCopyPayingSince, opBillingDate(f.FirstPaid))
+ }
+ v.Paying = append(v.Paying, row)
+ }
+ v.PayingNote = fmt.Sprintf(billCopyPayingListNote, opBillingMonthLabel(in.LastMonth, in.Now))
+ if len(in.Snaps) == 0 || in.Snaps[0].Day > in.LastMonth+"-01" {
+ v.HistoryNote = billCopyHistoryShort
+ }
+ v.PayingWhys = opBillingWhys(v.Figures[start:])
+}
+
+// opBillingPlanNote is an account's seats and packs: "2 seats, 3 packs";
+// "" with neither.
+func opBillingPlanNote(f billingFact) string {
+ var parts []string
+ if f.Seats > 0 {
+ parts = append(parts, fmt.Sprintf(billCopySeats, opNumber(f.Seats)))
+ }
+ packs := 0
+ for _, n := range f.Packs {
+ packs += max(n, 0)
+ }
+ if packs > 0 {
+ parts = append(parts, fmt.Sprintf(billCopyPacks, opNumber(packs)))
+ }
+ return strings.Join(parts, ", ")
+}
+
+// opBillingAccountStatus is a paying account's status: its renewal failing,
+// cancelling at renewal, or paid.
+func opBillingAccountStatus(f billingFact) opPill {
+ switch {
+ case f.RenewalFailing:
+ return opPill{Label: billCopyStatusFailing, Tone: "negative"}
+ case f.CancelAtPeriodEnd:
+ return opPill{Label: billCopyStatusCancels, Tone: "warning"}
+ }
+ return opPill{Label: billCopyStatusPaid, Tone: "positive"}
+}
+
+// opBillingMonths is the money table: each month's revenue columns, tax,
+// fees and net (the payments and that month's settled currencies), its
+// AWS bill (the platform cost and the usd rate) and cash after costs (all
+// of them).
+func opBillingMonths(v *opBillingView, in opBillingInput) {
+ start := len(v.Figures)
+ for i, m := range in.Months {
+ use := opBillingUse(inPayments, m.Currencies, "")
+ fig := func(col string, cents int64) opMoneyFigure {
+ return opMoney(&v.Figures, "month."+m.Month+"."+col, in.Gate, use, in.Platform, func() string { return eurText(cents) })
+ }
+ label := opBillingMonthLabel(m.Month, in.Now)
+ if i == 0 {
+ label = fmt.Sprintf(billCopyMonthSoFar, label)
+ }
+ row := opBillingMonthRow{
+ Href: "/fleet/billing/payments?month=" + m.Month, Label: label,
+ Subscriptions: fig("subscriptions", m.Subscriptions),
+ OnceOff: fig("onceoff", m.OnceOff),
+ Refunds: fig("refunds", m.Refunds),
+ Tax: fig("tax", m.Tax),
+ Fees: fig("fees", m.Fees),
+ Net: fig("net", m.Net),
+ }
+ row.AWS = opMoney(&v.Figures, "month."+m.Month+".aws", in.Gate, opBillingPlatformUse(m.Month), in.Platform,
+ func() string { return eurText(m.Platform.Cents) })
+ cashUse := opBillingUse(inPayments|inPlatform|inRates, opBillingCurrencies(m.Currencies, []string{"usd"}), m.Month)
+ row.Cash = opMoney(&v.Figures, "month."+m.Month+".cash", in.Gate, cashUse, in.Platform,
+ func() string { return eurText(m.Net - m.Platform.Cents) })
+ if row.AWS.Shown && m.Platform.Label != "" && !slices.Contains(v.MonthNotes, m.Platform.Label) {
+ v.MonthNotes = append(v.MonthNotes, m.Platform.Label)
+ }
+ v.Months = append(v.Months, row)
+ }
+ v.MonthWhys = opBillingWhys(v.Figures[start:])
+}
+
+// opBillingRecent is the newest payments: when, the account, what it was
+// and the amount as charged (the payments only: no conversion).
+func opBillingRecent(v *opBillingView, in opBillingInput) {
+ start := len(v.Figures)
+ facts := map[int64]billingFact{}
+ for _, f := range in.Facts {
+ facts[f.AccountID] = f
+ }
+ for i, p := range in.Recent {
+ if i == opBillingListMax {
+ break
+ }
+ row := opBillingPaymentRowOf(p, facts)
+ row.Charged = opMoney(&v.Figures, fmt.Sprintf("recent.%d.charged", i+1), in.Gate, moneyUse{Inputs: inPayments}, in.Platform,
+ func() string { return minorText(p.Amount, p.Currency) })
+ v.Recent = append(v.Recent, row)
+ }
+ v.RecentWhys = opBillingWhys(v.Figures[start:])
+}
+
+// opBillingPaymentRowOf is a payment's words: when, its account (a link to
+// a live account; Unmatched or Deleted account, not links, otherwise),
+// what it was and its status. The money cells are the caller's.
+func opBillingPaymentRowOf(p paymentRow, facts map[int64]billingFact) opBillingPaymentRow {
+ row := opBillingPaymentRow{When: opBillingDate(p.At), What: opBillingPaymentWhat(p, facts[p.AccountID])}
+ f, live := facts[p.AccountID]
+ switch {
+ case p.AccountID == 0:
+ row.Account = billCopyStatusUnmatched
+ case !live:
+ row.Account = billCopyDeletedAccount
+ default:
+ row.Account, row.Href = f.Name, opBillingAccountHref(f.Sqid)
+ }
+ row.Status = opPill{Label: billCopyStatusPaid, Tone: "positive"}
+ if p.Kind == billing.PaymentRefund && p.Settled < 0 {
+ row.Status = opPill{Label: billCopyStatusRefunded, Tone: "neutral"}
+ }
+ return row
+}
+
+// opBillingPaymentWhat is what a payment was: a refund, a reversed refund,
+// a returned payment, a domain and its name, a subscription's plan and
+// reason (Personal, first year), or a once-off.
+func opBillingPaymentWhat(p paymentRow, f billingFact) string {
+ switch {
+ case p.Reason == billing.ReasonReversed:
+ return billCopyWhatReversed
+ case p.Reason == billing.ReasonPaymentFailed:
+ return billCopyWhatReturned
+ case p.Kind == billing.PaymentRefund:
+ return billCopyWhatRefund
+ case p.Reason == billing.ReasonDomain:
+ if p.Detail == "" {
+ return billCopyWhatDomain
+ }
+ return billCopyWhatDomain + ", " + p.Detail
+ case p.Kind == billing.PaymentSubscription:
+ word := map[string]string{billing.ReasonFirst: billCopyWhatFirst, billing.ReasonRenewal: billCopyWhatRenewal,
+ billing.ReasonChange: billCopyWhatChange}[p.Reason]
+ plan := planLabel(f.Plan)
+ switch {
+ case plan == "":
+ return word
+ case word == "":
+ return plan
+ }
+ return plan + ", " + word
+ }
+ return billCopyWhatOnceOff
+}
+
+// opBillingWeekly is new paying accounts by week: twelve weeks, the last
+// ending today, each counting the accounts whose first subscription
+// payment fell in it. The chart declares the facts and the payments.
+func opBillingWeekly(v *opBillingView, in opBillingInput) {
+ v.WeeksFig = opMoney(&v.Figures, "weeks", in.Gate, moneyUse{Inputs: inFacts | inPayments}, in.Platform,
+ func() string { return "" })
+ tomorrow := opMidnight(in.Now).AddDate(0, 0, 1)
+ first := tomorrow.AddDate(0, 0, -7*opBillingWeeks)
+ days := make([]DayCount, opBillingWeeks)
+ for i := range days {
+ days[i].Day = first.AddDate(0, 0, 7*i)
+ }
+ for _, f := range in.Facts {
+ if !f.Paid || f.AccountID == in.ExemptID || f.FirstPaid.Before(first) || !f.FirstPaid.Before(tomorrow) {
+ continue
+ }
+ days[int(f.FirstPaid.Sub(first)/(7*24*time.Hour))].N++
+ }
+ v.Weeks = dashBars(days)
+}
+
+// opBillingReasonGroups are the not-paying groups, in the table's order,
+// with their labels.
+var opBillingReasonGroups = []struct {
+ Group billingGroup
+ Label string
+}{
+ {groupFree, billCopyReasonFree},
+ {groupSponsored, billCopyReasonSponsored},
+ {groupHouse, billCopyReasonHouse},
+ {groupOurs, billCopyReasonOurs},
+}
+
+// opBillingReasons is not paying, by reason: each group's count, what it
+// cost to run last month (Economics' estimate) and its costliest account,
+// then Shared and idle, the platform cost less every account's estimate.
+func opBillingReasons(v *opBillingView, in opBillingInput, rows []accountMoney) {
+ start := len(v.Figures)
+ v.CostHeading = fmt.Sprintf(billCopyColCostToRun, opBillingMonthLabel(in.LastMonth, in.Now))
+ for _, g := range opBillingReasonGroups {
+ row := opBillingReasonRow{Href: "/fleet/billing/accounts?tab=" + string(g.Group), Label: g.Label}
+ var cents, top int64
+ var biggest string
+ for _, a := range rows {
+ if a.Group != g.Group {
+ continue
+ }
+ row.Count++
+ if !a.HasCost {
+ continue
+ }
+ c := usdCents(in.Rates, a.CostUSD)
+ cents += c
+ if c > top {
+ top, biggest = c, a.Fact.Name
+ }
+ }
+ row.Cost = opMoney(&v.Figures, "reason."+string(g.Group)+".cost", in.Gate, opBillingCostUse, in.Platform,
+ func() string { return eurText(cents) })
+ if row.Cost.Shown {
+ row.Biggest = biggest
+ }
+ v.Reasons = append(v.Reasons, row)
+ }
+ var all int64
+ for _, sqid := range slices.Sorted(maps.Keys(in.CostUSD)) {
+ all += usdCents(in.Rates, in.CostUSD[sqid])
+ }
+ platform := in.Platform[in.LastMonth]
+ sharedUse := moneyUse{Inputs: inEconomics | inPlatform | inRates, Currencies: []string{"usd"}, Month: in.LastMonth}
+ v.Reasons = append(v.Reasons, opBillingReasonRow{Label: billCopyReasonShared,
+ Cost: opMoney(&v.Figures, "reason.shared.cost", in.Gate, sharedUse, in.Platform,
+ func() string { return eurText(platform.Cents - all) })})
+ v.ReasonWhys = opBillingWhys(v.Figures[start:])
+}
+
+// opBillingNearLimits is the free accounts closest to a limit: highest
+// used / limit first, ties by account, with the cap, its use and the
+// account's cost to run last month.
+func opBillingNearLimits(v *opBillingView, in opBillingInput, rows []accountMoney) {
+ start := len(v.Figures)
+ var near []accountMoney
+ for _, a := range rows {
+ if a.Group == groupFree && a.NearLimit > 0 {
+ near = append(near, a)
+ }
+ }
+ ratio := func(a accountMoney) float64 { return float64(a.NearUsed) / float64(a.NearLimit) }
+ slices.SortStableFunc(near, func(a, b accountMoney) int {
+ if c := cmp.Compare(ratio(b), ratio(a)); c != 0 {
+ return c
+ }
+ return cmp.Compare(a.Fact.AccountID, b.Fact.AccountID)
+ })
+ if len(near) > opBillingListMax {
+ near = near[:opBillingListMax]
+ }
+ for _, a := range near {
+ cents := int64(0)
+ if a.HasCost {
+ cents = usdCents(in.Rates, a.CostUSD)
+ }
+ v.NearLimits = append(v.NearLimits, opBillingLimitRow{
+ Href: opBillingAccountHref(a.Fact.Sqid), Name: a.Fact.Name,
+ Limit: billingCopy[usageCapLabels[a.NearCap]],
+ Used: fmt.Sprintf(billCopyUsedOf, capAmount(a.NearCap, a.NearUsed), capAmount(a.NearCap, a.NearLimit)),
+ Cost: opMoney(&v.Figures, "limits."+a.Fact.Sqid+".cost", in.Gate, opBillingCostUse, in.Platform,
+ func() string { return eurText(cents) }),
+ })
+ }
+ v.LimitWhys = opBillingWhys(v.Figures[start:])
+}
diff --git a/internal/console/opbilling_store.go b/internal/console/opbilling_store.go
new file mode 100644
index 000000000..465423afe
--- /dev/null
+++ b/internal/console/opbilling_store.go
@@ -0,0 +1,83 @@
+package console
+
+import (
+ "strings"
+ "time"
+)
+
+// The billing overview's two reads beyond Plan 1's records (billing
+// dashboard plan 2, Task 4): the sign-up funnel and each account's nearest
+// cap.
+
+// opSQLBillingFunnel counts live accounts, those with a live app, and those
+// active in the window: a member seen (users.last_seen) or signed in
+// (sessions.created_at) since ?1, or a deploy (an audit row of
+// deployActions) on the account since ?1.
+const opSQLBillingFunnel = `SELECT COUNT(*),
+ COALESCE(SUM(EXISTS(SELECT 1 FROM apps p WHERE p.account_id = a.id AND p.deleted_at = 0)), 0),
+ COALESCE(SUM(
+ EXISTS(SELECT 1 FROM memberships m JOIN users u ON u.address = m.address WHERE m.account_id = a.id AND u.last_seen >= ?1)
+ OR EXISTS(SELECT 1 FROM memberships m JOIN sessions s ON s.address = m.address WHERE m.account_id = a.id AND s.created_at >= ?1)
+ OR EXISTS(SELECT 1 FROM audit d WHERE d.account_id = a.id AND d.created_at >= ?1 AND d.action IN (?2, ?3))
+ ), 0)
+FROM accounts a WHERE a.deleted_at = 0`
+
+// BillingFunnel is the overview's sign-up funnel at now: live accounts,
+// those with a live app, and those active in the last 30 days (a member
+// seen or signed in, or a deploy on the account).
+func (s *Store) BillingFunnel(now time.Time) (signedUp, withApp, active30 int, err error) {
+ since := now.Add(-30 * 24 * time.Hour).Unix()
+ err = s.db.QueryRow(opSQLBillingFunnel, since, deployActions[0], deployActions[1]).Scan(&signedUp, &withApp, &active30)
+ return signedUp, withApp, active30, err
+}
+
+// NearestCaps is, per account, the plan_cap_state row with the highest
+// used / cap_limit among rows with a limit, for the caps the usage summary
+// names (usageCaps, each with a label). Ties go to the cap first in
+// usageCaps.
+func (s *Store) NearestCaps() (map[int64]capState, error) {
+ caps := make([]string, len(usageCaps))
+ args := make([]any, len(usageCaps))
+ for i, c := range usageCaps {
+ caps[i], args[i] = "?", string(c)
+ }
+ rows, err := s.db.Query(`SELECT account_id, cap, period, level, used, cap_limit, updated_at FROM plan_cap_state
+ WHERE cap_limit > 0 AND cap IN (`+strings.Join(caps, ", ")+`)`, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ rank := map[capID]int{}
+ for i, c := range usageCaps {
+ rank[c] = i
+ }
+ out := map[int64]capState{}
+ for rows.Next() {
+ var st capState
+ var updated int64
+ if err := rows.Scan(&st.AccountID, &st.Cap, &st.Period, &st.Level, &st.Used, &st.Limit, &updated); err != nil {
+ return nil, err
+ }
+ st.UpdatedAt = timeOrZero(updated)
+ cur, ok := out[st.AccountID]
+ if !ok || capNearer(st, cur, rank) {
+ out[st.AccountID] = st
+ }
+ }
+ return out, rows.Err()
+}
+
+// capNearer is whether a is closer to its limit than b: a higher used /
+// limit, then the cap earlier in rank. Both limits are positive; the
+// ratios are compared as floats, since a byte count times a byte limit
+// overflows int64.
+func capNearer(a, b capState, rank map[capID]int) bool {
+ x, y := capRatio(a), capRatio(b)
+ if x != y {
+ return x > y
+ }
+ return rank[a.Cap] < rank[b.Cap]
+}
+
+// capRatio is st's used / limit; its limit is positive.
+func capRatio(st capState) float64 { return float64(st.Used) / float64(st.Limit) }
diff --git a/internal/console/opbilling_store_test.go b/internal/console/opbilling_store_test.go
new file mode 100644
index 000000000..1561d36ed
--- /dev/null
+++ b/internal/console/opbilling_store_test.go
@@ -0,0 +1,135 @@
+package console
+
+import (
+ "reflect"
+ "testing"
+ "time"
+)
+
+func TestBillingFunnel(t *testing.T) {
+ st, ids := planStore(t, "faa", "fab", "fac", "fad", "fae", "faf", "fag")
+ now := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)
+ old := now.Add(-40 * 24 * time.Hour)
+ recent := now.Add(-2 * 24 * time.Hour)
+ // faa: an app, its owner seen recently.
+ if _, err := st.CreateAppIn(ids["faa"], "shop", "faa@example.com", old); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.EnsureUser("faa@example.com", old); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.TouchLastSeen("faa@example.com", recent); err != nil {
+ t.Fatal(err)
+ }
+ // fab: an app, its owner seen long ago, but signed in recently.
+ if _, err := st.CreateAppIn(ids["fab"], "blog", "fab@example.com", old); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.EnsureUser("fab@example.com", old); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.TouchLastSeen("fab@example.com", old); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.CreateSession("fab@example.com", "", recent); err != nil {
+ t.Fatal(err)
+ }
+ // fac: an app and a recent deploy, nobody seen.
+ if _, err := st.CreateAppIn(ids["fac"], "docs", "fac@example.com", old); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.RecordEvent(ids["fac"], "docs", "fac@example.com", "promote", "", recent); err != nil {
+ t.Fatal(err)
+ }
+ // fad: a deleted app only, an old deploy and a recent non-deploy event.
+ if _, err := st.CreateAppIn(ids["fad"], "gone", "fad@example.com", old); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.db.Exec(`UPDATE apps SET deleted_at = ? WHERE app = 'gone'`, old.Unix()); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.RecordEvent(ids["fad"], "gone", "fad@example.com", "rollback", "", old); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.RecordEvent(ids["fad"], "gone", "fad@example.com", "env.set", "", recent); err != nil {
+ t.Fatal(err)
+ }
+ // fae: a member (not the owner) seen recently.
+ if _, err := st.db.Exec(`INSERT INTO memberships (account_id, address, role, added_at) VALUES (?, 'm@example.com', 'member', ?)`,
+ ids["fae"], old.Unix()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.EnsureUser("m@example.com", old); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.TouchLastSeen("m@example.com", recent); err != nil {
+ t.Fatal(err)
+ }
+ // faf: deleted, with an app and a recent visit; counts nowhere.
+ if _, err := st.CreateAppIn(ids["faf"], "dead", "faf@example.com", old); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.EnsureUser("faf@example.com", old); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.TouchLastSeen("faf@example.com", recent); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.ReapAccount(ids["faf"], now); err != nil {
+ t.Fatal(err)
+ }
+ // fag: nothing at all.
+
+ signed, apps, active, err := st.BillingFunnel(now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if signed != 6 || apps != 3 || active != 4 {
+ t.Errorf("funnel = %d, %d, %d; want 6 live, 3 with a live app, 4 active (faa, fab, fac, fae)", signed, apps, active)
+ }
+
+ empty, _ := planStore(t)
+ if s, a, n, err := empty.BillingFunnel(now); err != nil || s != 0 || a != 0 || n != 0 {
+ t.Errorf("empty store: %d, %d, %d, %v", s, a, n, err)
+ }
+}
+
+func TestNearestCaps(t *testing.T) {
+ st, ids := planStore(t, "naa", "nab", "nac")
+ now := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)
+ put := func(account int64, c capID, used, limit int64) {
+ t.Helper()
+ if err := st.PutCapState(capState{AccountID: account, Cap: c, Level: levelOK, Used: used, Limit: limit, UpdatedAt: now}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // naa: bandwidth at 8 of 10 GB (0.8) is nearer than running at 2 of 3.
+ put(ids["naa"], capRunningThings, 2, 3)
+ put(ids["naa"], capBandwidth, 8_000_000_000, 10_000_000_000)
+ // nab: a lapse-only cap and a cap with no limit are not candidates.
+ put(ids["nab"], capSidecars, 9, 1)
+ put(ids["nab"], capEmail, 99, 0)
+ put(ids["nab"], capStorage, 1, 4)
+ // nac: a tie goes to the cap first in usageCaps.
+ put(ids["nac"], capEmail, 5, 10)
+ put(ids["nac"], capRunningThings, 1, 2)
+
+ got, err := st.NearestCaps()
+ if err != nil {
+ t.Fatal(err)
+ }
+ pick := map[int64]capID{}
+ for id, s := range got {
+ pick[id] = s.Cap
+ if s.AccountID != id {
+ t.Errorf("row for %d carries account %d", id, s.AccountID)
+ }
+ }
+ want := map[int64]capID{ids["naa"]: capBandwidth, ids["nab"]: capStorage, ids["nac"]: capRunningThings}
+ if !reflect.DeepEqual(pick, want) {
+ t.Errorf("nearest = %v, want %v", pick, want)
+ }
+ if s := got[ids["naa"]]; s.Used != 8_000_000_000 || s.Limit != 10_000_000_000 {
+ t.Errorf("naa = %+v", s)
+ }
+}
diff --git a/internal/console/opbilling_test.go b/internal/console/opbilling_test.go
index c53faf04d..3e87fe0ab 100644
--- a/internal/console/opbilling_test.go
+++ b/internal/console/opbilling_test.go
@@ -1,12 +1,20 @@
package console
import (
+ "context"
"fmt"
"html"
"net/http"
+ "net/http/httptest"
"net/url"
+ "reflect"
+ "slices"
"strings"
"testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/fxrate"
)
// opBillingRoutes is the three billing pages and the <h1> each carries.
@@ -87,3 +95,650 @@ func TestBillingRoutesRender(t *testing.T) {
}
}
}
+
+// overviewNow is the overview tests' clock: Monday 9 November 2026, noon.
+var overviewNow = time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)
+
+// overviewMonths is the six months the overview's money table shows on
+// overviewNow, newest first.
+var overviewMonths = []string{"2026-11", "2026-10", "2026-09", "2026-08", "2026-07", "2026-06"}
+
+// overviewWorld is an overview input with every gate input complete: the
+// facts, the payments of the last six months (Kind "all"), the stored
+// snapshots and account rows, Economics' costs and the funnel. The rest is
+// derived as handleOpBilling derives it.
+type overviewWorld struct {
+ facts []billingFact
+ exempt int64
+ payments []paymentRow
+ snaps []arrSnapshot
+ days []accountDay
+ costUSD map[string]float64
+ near map[int64]capState
+ funnel [3]int
+ platform int64 // each month's platform cost, euro cents
+}
+
+// input builds the overview's input from w with the gate in.
+func (w overviewWorld) input(in moneyInputs) opBillingInput {
+ r := in.Rates
+ exempt := w.exempt
+ platform := map[string]platformCost{}
+ gate := in
+ gate.PlatformOK = map[string]bool{}
+ for _, m := range overviewMonths {
+ pc := platformCost{Basis: "account", Label: costLabelAccount, OK: true}
+ if cents, ok := r.eurCents(w.platform, "eur"); ok {
+ pc.Cents = cents
+ }
+ if _, ok := r.eurCents(0, "usd"); !ok {
+ pc.Cents, pc.Hint = 0, billCopyWhyRates
+ }
+ platform[m] = pc
+ gate.PlatformOK[m] = in.PlatformOK[m]
+ }
+ rev := billingRevenue{arrTotals: arrOf(w.facts, exempt, r), Groups: map[billingGroup]int{}, Accounts: len(w.facts), Inputs: gate}
+ for _, f := range w.facts {
+ rev.Groups[billingGroupOf(f, exempt)]++
+ }
+ for i := range w.snaps {
+ if strings.HasPrefix(w.snaps[i].Day, "2026-11-") {
+ rev.MonthStart = &w.snaps[i]
+ break
+ }
+ }
+ var last, recent []paymentRow
+ for _, p := range w.payments {
+ if p.Kind == billing.PaymentFee {
+ continue
+ }
+ if len(recent) < opBillingListMax {
+ recent = append(recent, p)
+ }
+ if p.At.Format("2006-01") == "2026-10" {
+ last = append(last, p)
+ }
+ }
+ earned, covered := accountEarnings("2026-10", w.days, w.snaps)
+ return opBillingInput{
+ Now: in.Now, Rev: rev, Gate: gate, Facts: w.facts, ExemptID: exempt, Rates: r,
+ Months: moneyByMonth(w.payments, overviewMonths, r, platform), LastMonth: "2026-10", LastRows: last,
+ Snaps: w.snaps, Earned: earned, Covered: covered, Recent: recent, CostUSD: w.costUSD,
+ Platform: platform, Funnel: w.funnel, Near: w.near,
+ }
+}
+
+// overviewGood is every gate input complete on overviewNow, with each of
+// the six months' platform cost.
+func overviewGood() moneyInputs {
+ in := goodMoneyInputs(overviewNow)
+ in.PlatformOK = map[string]bool{}
+ for _, m := range overviewMonths {
+ in.PlatformOK[m] = true
+ }
+ return in
+}
+
+// overviewSnaps is a complete snapshot for every day from 1 October to
+// overviewNow's day, ARR eur from (a day) on.
+func overviewSnaps(eur func(day string) int64) []arrSnapshot {
+ var out []arrSnapshot
+ for d := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC); !d.After(overviewNow); d = d.AddDate(0, 0, 1) {
+ day := d.Format(snapshotDayFormat)
+ out = append(out, arrSnapshot{Day: day, EUR: eur(day), Complete: true})
+ }
+ return out
+}
+
+// payingFactAt is a paying account first paid at paid.
+func payingFactAt(id int64, sqid, currency string, annual int64, paid time.Time) billingFact {
+ f := payingFact(id, currency, annual)
+ f.Sqid, f.Name, f.Plan, f.Subscribed, f.FactsReadAt = sqid, sqid+"-shop", "personal", true, overviewNow.Add(-time.Hour)
+ f.FirstPaid, f.PeriodEnd = paid, paid.AddDate(1, 0, 0)
+ f.Created = paid.AddDate(0, -1, 0)
+ return f
+}
+
+// overviewOneEUR is the approved example: one eur account paying 2400 a
+// year since 7 November, the ops account and 37 others not paying.
+func overviewOneEUR() overviewWorld {
+ w := overviewWorld{exempt: 1, costUSD: map[string]float64{}, platform: 19000, funnel: [3]int{39, 30, 25}}
+ w.facts = append(w.facts, billingFact{AccountID: 1, Sqid: "ops", Name: "ops"})
+ paid := time.Date(2026, 11, 7, 10, 0, 0, 0, time.UTC)
+ w.facts = append(w.facts, payingFactAt(2, "acca", "eur", 2400, paid))
+ for i := int64(3); i < 40; i++ {
+ f := billingFact{AccountID: i, Sqid: fmt.Sprintf("acc%d", i), Name: fmt.Sprintf("free%d", i), Plan: "free"}
+ switch {
+ case i < 13:
+ f.Sponsored = true
+ case i < 15:
+ f.House = true
+ }
+ w.facts = append(w.facts, f)
+ w.costUSD[f.Sqid] = 1.12
+ }
+ w.costUSD["acca"], w.costUSD["ops"] = 2.24, 11.2
+ first := pay(billing.PaymentSubscription, billing.ReasonFirst, paid, 2400, 0, 100, "eur")
+ first.AccountID, first.Subscription = 2, "sub_2"
+ w.payments = []paymentRow{first}
+ w.snaps = overviewSnaps(func(day string) int64 {
+ if day >= "2026-11-07" {
+ return 2400
+ }
+ return 0
+ })
+ w.near = map[int64]capState{20: {AccountID: 20, Cap: capRunningThings, Used: 3, Limit: 3}}
+ return w
+}
+
+func TestBuildOpBillingView(t *testing.T) {
+ v := buildOpBillingView(overviewOneEUR().input(overviewGood()))
+ type tile struct{ Label, Value, Delta, Note string }
+ var tiles []tile
+ for _, s := range v.Tiles {
+ tiles = append(tiles, tile{s.Label, s.Value, s.Delta, s.Note})
+ }
+ want := []tile{
+ {billCopyTileARR, "€24.00", "+€24.00 this month", "€24.00 before tax"},
+ {billCopyTileMRR, "€2.00", "", billCopyMRRNote},
+ {billCopyTileReceived, "€23.00", "", billCopyReceivedNote},
+ {billCopyTilePaying, "1", "+1 this month", "1 of 39 (2.6%)"},
+ {billCopyTileAttention, "0", "", billCopyAttentionNote},
+ }
+ if !reflect.DeepEqual(tiles, want) {
+ t.Errorf("tiles:\n got %+v\nwant %+v", tiles, want)
+ }
+ if v.RateLine != fmt.Sprintf(billCopyRateNoteLine, "6 Nov 2026") {
+ t.Errorf("rate line = %q", v.RateLine)
+ }
+ if !v.PayingList.Shown || len(v.Paying) != 1 {
+ t.Fatalf("paying list: %+v, %d rows", v.PayingList, len(v.Paying))
+ }
+ p := v.Paying[0]
+ if p.Status.Label != billCopyStatusPaid || p.Href != "/fleet/activity?account=acca" || p.Plan != "Personal" ||
+ p.Since != "paying since 7 Nov 2026" || p.Renews != "7 Nov 2027" {
+ t.Errorf("paying row = %+v", p)
+ }
+ // 2.24 usd at 1.12 is €2.00; nothing earned in October.
+ if p.Earns.Text != "€0.00" || p.Costs.Text != "€2.00" || p.Margin.Text != "−€2.00" {
+ t.Errorf("paying figures: %q %q %q", p.Earns.Text, p.Costs.Text, p.Margin.Text)
+ }
+ if n := len(v.Weeks); n != opBillingWeeks || v.Weeks[n-1].N != 1 {
+ t.Errorf("weeks = %+v; want 12, 1 in the last", v.Weeks)
+ }
+ for _, w := range v.Weeks[:len(v.Weeks)-1] {
+ if w.N != 0 {
+ t.Errorf("week %s = %d, want 0", w.Day.Format("2 Jan"), w.N)
+ }
+ }
+ type reason struct {
+ Label string
+ Count int
+ Cost, Bigger string
+ }
+ var reasons []reason
+ for _, r := range v.Reasons {
+ reasons = append(reasons, reason{r.Label, r.Count, r.Cost.Text, r.Biggest})
+ }
+ // 37 others at €1.00 each: 10 sponsored, 2 house, 25 free; ours €10.00.
+ // Shared and idle: €190.00 less €49.00.
+ wantReasons := []reason{
+ {billCopyReasonFree, 25, "€25.00", "free15"},
+ {billCopyReasonSponsored, 10, "€10.00", "free3"},
+ {billCopyReasonHouse, 2, "€2.00", "free13"},
+ {billCopyReasonOurs, 1, "€10.00", "ops"},
+ {billCopyReasonShared, 0, "€141.00", ""},
+ }
+ if !reflect.DeepEqual(reasons, wantReasons) {
+ t.Errorf("reasons:\n got %+v\nwant %+v", reasons, wantReasons)
+ }
+ if v.Reasons[0].Href != "/fleet/billing/accounts?tab=free" || v.Reasons[4].Href != "" {
+ t.Errorf("reason links: %q, %q", v.Reasons[0].Href, v.Reasons[4].Href)
+ }
+ if len(v.NearLimits) != 1 || v.NearLimits[0].Name != "free20" || v.NearLimits[0].Used != "3 of 3" ||
+ v.NearLimits[0].Limit != billingCopy["usage.label.running"] || v.NearLimits[0].Cost.Text != "€1.00" {
+ t.Errorf("near limits = %+v", v.NearLimits)
+ }
+ if len(v.Months) != 6 || v.Months[0].Label != "November so far" || v.Months[0].Subscriptions.Text != "€24.00" ||
+ v.Months[0].Fees.Text != "€1.00" || v.Months[0].Net.Text != "€23.00" || v.Months[0].AWS.Text != "€190.00" ||
+ v.Months[0].Cash.Text != "−€167.00" || v.Months[1].Label != "October" ||
+ v.Months[0].Href != "/fleet/billing/payments?month=2026-11" {
+ t.Errorf("months[0] = %+v", v.Months[0])
+ }
+ var earned []string
+ for _, l := range v.Earned {
+ earned = append(earned, l.Label+" "+l.Value.Text)
+ }
+ // MRR so far: 2400 × 9 / (12 × 30) = 60 cents.
+ wantEarned := []string{billCopyEarnedRecurring + " €0.60", billCopyOnceOff + " €0.00", billCopyRefunds + " €0.00",
+ billCopyEarnedAWS + " €190.00", billCopyEarnedProfit + " −€189.40"}
+ if !reflect.DeepEqual(earned, wantEarned) || v.Earned[3].Note != costLabelAccount {
+ t.Errorf("earned = %q (aws note %q)", earned, v.Earned[3].Note)
+ }
+ if v.EarnedHeading != "November so far, earned" {
+ t.Errorf("earned heading = %q", v.EarnedHeading)
+ }
+ var funnel []string
+ for _, f := range v.Funnel {
+ funnel = append(funnel, fmt.Sprintf("%s %s %d", f.Label, f.Meter.Text, f.Meter.Percent))
+ }
+ if want := []string{"Signed up 39 100", "Made an app 30 76", "Active, last 30 days 25 64", "Paying 1 2"}; !reflect.DeepEqual(funnel, want) {
+ t.Errorf("funnel = %q", funnel)
+ }
+ if len(v.Recent) != 1 || v.Recent[0].What != "Personal, first year" || v.Recent[0].Charged.Text != "€24.00" ||
+ v.Recent[0].Account != "acca-shop" || v.Recent[0].Status.Label != billCopyStatusPaid {
+ t.Errorf("recent = %+v", v.Recent)
+ }
+ if v.ARRGaps != "" || len(v.ARR) != 40 || v.ARR[len(v.ARR)-1].H != 20 || v.ARR[0].H != 0 {
+ t.Errorf("ARR chart: %d days, gaps %q", len(v.ARR), v.ARRGaps)
+ }
+ for _, f := range v.Figures {
+ if !f.Shown {
+ t.Errorf("every input good: %s refused (%s)", f.Name, f.Why)
+ }
+ }
+}
+
+// overviewMixed is the invariant's world: an eur and a usd paying
+// account, a gbp once-off last month, an eur subscription in September, a
+// cost for every account, a free account near a limit, and complete
+// snapshots from 1 October.
+func overviewMixed() overviewWorld {
+ w := overviewWorld{exempt: 1, platform: 50000, funnel: [3]int{6, 4, 3}}
+ sepPaid := time.Date(2026, 9, 15, 0, 0, 0, 0, time.UTC)
+ novPaid := time.Date(2026, 11, 3, 0, 0, 0, 0, time.UTC)
+ w.facts = []billingFact{
+ {AccountID: 1, Sqid: "ops", Name: "ops"},
+ payingFactAt(2, "acca", "eur", 2400, sepPaid),
+ payingFactAt(3, "accb", "usd", 2800, novPaid),
+ {AccountID: 4, Sqid: "accf", Name: "free", Plan: "free"},
+ {AccountID: 5, Sqid: "accs", Name: "sponsored", Sponsored: true},
+ {AccountID: 6, Sqid: "acch", Name: "house", House: true},
+ }
+ w.costUSD = map[string]float64{"ops": 5.6, "acca": 2.24, "accb": 3.36, "accf": 1.12, "accs": 4.48, "acch": 0.56}
+ first := pay(billing.PaymentSubscription, billing.ReasonFirst, sepPaid, 2400, 0, 100, "eur")
+ first.AccountID = 2
+ once := pay(billing.PaymentOnceOff, billing.ReasonDomain, time.Date(2026, 10, 12, 0, 0, 0, 0, time.UTC), 1200, 200, 50, "gbp")
+ once.AccountID, once.Detail = 2, "shop.example.com"
+ usd := pay(billing.PaymentSubscription, billing.ReasonFirst, novPaid, 2800, 0, 110, "usd")
+ usd.AccountID = 3
+ fee := pay(billing.PaymentFee, billing.ReasonOther, time.Date(2026, 11, 4, 0, 0, 0, 0, time.UTC), -45, 0, 0, "eur")
+ w.payments = []paymentRow{fee, usd, once, first} // newest first, as Payments lists them
+ slices.SortStableFunc(w.payments, func(a, b paymentRow) int { return b.At.Compare(a.At) })
+ w.snaps = overviewSnaps(func(day string) int64 {
+ if day >= "2026-11-03" {
+ return 2400 + 2500
+ }
+ return 2400
+ })
+ for d := 1; d <= 31; d++ {
+ w.days = append(w.days, accountDay{Day: fmt.Sprintf("2026-10-%02d", d), AccountID: 2, Annual: 2400, Currency: "eur",
+ AnnualEUR: 2400, Paying: true, InARR: true})
+ }
+ w.near = map[int64]capState{4: {AccountID: 4, Cap: capBandwidth, Used: 8_000_000_000, Limit: 10_000_000_000}}
+ return w
+}
+
+// overviewFigureNames is the pinned inventory of what the mixed world's
+// overview shows: every money figure (and gated count) the page has.
+func overviewFigureNames() []string {
+ names := []string{"tile.arr", "tile.arr.delta", "tile.mrr", "tile.received", "tile.paying", "tile.paying.delta", "tile.attention"}
+ for d := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC); !d.After(overviewNow); d = d.AddDate(0, 0, 1) {
+ names = append(names, "arr."+d.Format(snapshotDayFormat))
+ }
+ names = append(names, "paying.list")
+ for _, sqid := range []string{"accb", "acca"} {
+ names = append(names, "paying."+sqid+".earns", "paying."+sqid+".costs", "paying."+sqid+".margin")
+ }
+ names = append(names, "earned.recurring", "earned.onceoff", "earned.refunds", "earned.aws", "earned.profit", "funnel.paying")
+ for _, m := range overviewMonths {
+ for _, col := range []string{"subscriptions", "onceoff", "refunds", "tax", "fees", "net", "aws", "cash"} {
+ names = append(names, "month."+m+"."+col)
+ }
+ }
+ names = append(names, "recent.1.charged", "recent.2.charged", "recent.3.charged", "weeks",
+ "reason.free.cost", "reason.sponsored.cost", "reason.house.cost", "reason.ours.cost", "reason.shared.cost",
+ "limits.accf.cost")
+ return names
+}
+
+func TestOverviewGateInvariant(t *testing.T) {
+ w := overviewMixed()
+ v := buildOpBillingView(w.input(overviewGood()))
+ var got []string
+ for _, f := range v.Figures {
+ got = append(got, f.Name)
+ }
+ if want := overviewFigureNames(); !reflect.DeepEqual(got, want) {
+ t.Errorf("figures:\n got %q\nwant %q", got, want)
+ }
+ checkGateInvariant(t, overviewGood(), func(in moneyInputs) []moneyFigure {
+ var out []moneyFigure
+ for _, f := range buildOpBillingView(w.input(in)).Figures {
+ out = append(out, f.moneyFigure)
+ }
+ return out
+ })
+}
+
+// overviewCostFigure is whether name is a figure built from a usd cost:
+// Economics' estimates, the platform cost, or anything summing either.
+func overviewCostFigure(name string) bool {
+ for _, s := range []string{".costs", ".margin", ".aws", ".cash", "earned.profit", ".cost"} {
+ if strings.HasSuffix(name, s) {
+ return true
+ }
+ }
+ return false
+}
+
+func TestOverviewCostsNeedUSD(t *testing.T) {
+ w := overviewMixed()
+ noUSD := overviewGood()
+ noUSD.Rates.PerEUR = map[string]float64{"gbp": 0.87}
+ stale := overviewGood()
+ stale.Rates.FetchedAt = overviewNow.Add(-27 * time.Hour)
+ for name, in := range map[string]moneyInputs{"no usd rate": noUSD, "rates 27 h old": stale} {
+ v := buildOpBillingView(w.input(in))
+ costs := 0
+ for _, f := range v.Figures {
+ if !overviewCostFigure(f.Name) {
+ continue
+ }
+ costs++
+ if f.Shown || f.Why != moneyWhyRates || f.Reason != billCopyWhyRates {
+ t.Errorf("%s: %s = %+v; want refused for the rates", name, f.Name, f)
+ }
+ }
+ if costs != 4+6*2+2+5+1 { // paying costs and margins, months' aws and cash, earned aws and profit, reasons, limits
+ t.Errorf("%s: %d cost figures", name, costs)
+ }
+ // September's eur subscription and the recorded charges still show.
+ for _, f := range []opMoneyFigure{v.Months[2].Subscriptions, v.Months[2].Net, v.Recent[0].Charged, v.Recent[1].Charged} {
+ if !f.Shown {
+ t.Errorf("%s: %s refused (%s)", name, f.Name, f.Why)
+ }
+ }
+ if v.Months[2].Subscriptions.Text != "€24.00" {
+ t.Errorf("%s: September subscriptions = %q", name, v.Months[2].Subscriptions.Text)
+ }
+ }
+}
+
+func TestOverviewARRChart(t *testing.T) {
+ now := time.Date(2026, 11, 4, 9, 0, 0, 0, time.UTC)
+ in := opBillingInput{Now: now, Gate: goodMoneyInputs(now), Snaps: []arrSnapshot{
+ {Day: "2026-11-01", EUR: 2400, Complete: true},
+ {Day: "2026-11-02", EUR: 2400, Complete: false, Why: moneyWhyPayments},
+ {Day: "2026-11-04", EUR: 1200, Complete: true},
+ }}
+ v := buildOpBillingView(in)
+ var shape []string
+ for _, d := range v.ARR {
+ shape = append(shape, fmt.Sprintf("%s %v %d %s", d.Day.Format("2 Jan"), d.Known, d.H, d.Value.Text))
+ }
+ want := []string{"1 Nov true 20 €24.00", "2 Nov false 0 " + billCopyNotAvailable, "3 Nov false 0 " + billCopyNotAvailable, "4 Nov true 10 €12.00"}
+ if !reflect.DeepEqual(shape, want) {
+ t.Errorf("chart = %q, want %q", shape, want)
+ }
+ if v.ARRGaps != fmt.Sprintf(billCopyARRGapMany, "2") || v.ARRFrom != "1 Nov" {
+ t.Errorf("gaps %q, from %q", v.ARRGaps, v.ARRFrom)
+ }
+ in.Snaps = in.Snaps[:1]
+ in.Now = time.Date(2026, 11, 2, 9, 0, 0, 0, time.UTC)
+ if v := buildOpBillingView(in); v.ARRGaps != billCopyARRGapOne {
+ t.Errorf("one gap: %q", v.ARRGaps)
+ }
+ in.Snaps = nil
+ if v := buildOpBillingView(in); v.ARR != nil || v.ARRGaps != "" {
+ t.Errorf("no snapshots: %+v, %q", v.ARR, v.ARRGaps)
+ }
+ // A snapshot older than 90 days starts the chart 90 days back.
+ in.Snaps = []arrSnapshot{{Day: "2026-01-01", EUR: 100, Complete: true}}
+ if v := buildOpBillingView(in); len(v.ARR) != opBillingChartDays {
+ t.Errorf("old first snapshot: %d days", len(v.ARR))
+ }
+}
+
+// renderOverview is v rendered as the overview page.
+func renderOverview(t *testing.T, fx *consoleFixture, v *opBillingView) string {
+ t.Helper()
+ rec := httptest.NewRecorder()
+ p := fx.srv.billingPage("paul@keymail.dev", "", billCopyRail)
+ p.OpBilling = v
+ fx.srv.render(rec, http.StatusOK, "ops_billing", p)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("render = %d: %s", rec.Code, rec.Body.String())
+ }
+ return rec.Body.String()
+}
+
+func TestOverviewEmpty(t *testing.T) {
+ w := overviewWorld{exempt: 1, funnel: [3]int{3, 0, 0}}
+ w.facts = []billingFact{{AccountID: 1, Sqid: "ops", Name: "ops"}, {AccountID: 2, Sqid: "a2", Name: "a2"}, {AccountID: 3, Sqid: "a3", Name: "a3"}}
+ v := buildOpBillingView(w.input(overviewGood()))
+ if v.Tiles[0].Value != "€0.00" || v.Tiles[0].Note != "€0.00 before tax" || v.Tiles[3].Value != "0" || v.Tiles[3].Note != "0 of 3 (0%)" {
+ t.Errorf("tiles = %+v", v.Tiles)
+ }
+ if len(v.Paying) != 0 || len(v.Recent) != 0 || len(v.NearLimits) != 0 || v.ARR != nil {
+ t.Errorf("lists not empty: %d paying, %d recent, %d near, %d ARR days", len(v.Paying), len(v.Recent), len(v.NearLimits), len(v.ARR))
+ }
+ if len(v.Months) != 6 {
+ t.Fatalf("%d months", len(v.Months))
+ }
+ for _, m := range v.Months {
+ for _, f := range []opMoneyFigure{m.Subscriptions, m.OnceOff, m.Refunds, m.Tax, m.Fees, m.Net} {
+ if f.Text != "€0.00" {
+ t.Errorf("%s = %q, want €0.00", f.Name, f.Text)
+ }
+ }
+ }
+ for _, wk := range v.Weeks {
+ if wk.N != 0 || wk.H != 0 {
+ t.Errorf("week %+v", wk)
+ }
+ }
+ for _, f := range v.Funnel {
+ if f.Meter.Percent < 0 || f.Meter.Percent > 100 {
+ t.Errorf("funnel %+v", f)
+ }
+ }
+ fx := newConsoleFixture(t)
+ enableBilling(t, fx.srv)
+ body := renderOverview(t, fx, v)
+ for _, s := range []string{billCopyPayingEmpty, billCopyPaymentsEmpty, billCopyARRChartEmpty, billCopyLimitsEmpty} {
+ if !strings.Contains(body, html.EscapeString(s)) {
+ t.Errorf("empty page lacks %q", s)
+ }
+ }
+}
+
+func TestOverviewCapsAtFive(t *testing.T) {
+ w := overviewWorld{exempt: 1}
+ w.facts = []billingFact{{AccountID: 1, Sqid: "ops", Name: "ops"}}
+ for i := int64(2); i <= 8; i++ {
+ w.facts = append(w.facts, payingFactAt(i, fmt.Sprintf("acc%d", i), "eur", 2400, time.Date(2026, 10, int(i), 0, 0, 0, 0, time.UTC)))
+ }
+ v := buildOpBillingView(w.input(overviewGood()))
+ var got []string
+ for _, r := range v.Paying {
+ got = append(got, r.Href)
+ }
+ want := []string{"/fleet/activity?account=acc8", "/fleet/activity?account=acc7", "/fleet/activity?account=acc6",
+ "/fleet/activity?account=acc5", "/fleet/activity?account=acc4"}
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("paying rows = %q, want %q", got, want)
+ }
+ fx := newConsoleFixture(t)
+ enableBilling(t, fx.srv)
+ body := renderOverview(t, fx, v)
+ if !strings.Contains(body, `href="/fleet/billing/accounts?tab=paying">`+billCopyAllPaying+`</a>`) {
+ t.Error("no link to all paying accounts")
+ }
+}
+
+// overviewRowLinks is each co-rowlink row's first rst-nm link, in order.
+func overviewRowLinks(body string) []string {
+ var out []string
+ chunks := strings.Split(body, "<div rst-lrow co-rowlink>")
+ for _, c := range chunks[1:] {
+ row, _, _ := strings.Cut(c, "</div>")
+ _, after, ok := strings.Cut(row, `<a class="rst-nm" href="`)
+ if !ok {
+ out = append(out, "")
+ continue
+ }
+ href, _, _ := strings.Cut(after, `"`)
+ out = append(out, html.UnescapeString(href))
+ }
+ return out
+}
+
+func TestOverviewRowsAreLinks(t *testing.T) {
+ w := overviewMixed()
+ // An unmatched and a deleted account's payment: listed, not links.
+ unmatched := pay(billing.PaymentOnceOff, billing.ReasonOther, time.Date(2026, 11, 8, 0, 0, 0, 0, time.UTC), 500, 0, 0, "eur")
+ deleted := pay(billing.PaymentRefund, billing.ReasonOther, time.Date(2026, 11, 7, 0, 0, 0, 0, time.UTC), -500, 0, 0, "eur")
+ deleted.AccountID = 99
+ w.payments = append([]paymentRow{unmatched, deleted}, w.payments...)
+ v := buildOpBillingView(w.input(overviewGood()))
+ var want []string
+ for _, r := range v.Paying {
+ want = append(want, r.Href)
+ }
+ for _, m := range overviewMonths {
+ want = append(want, "/fleet/billing/payments?month="+m)
+ }
+ for _, r := range v.Recent {
+ if r.Href != "" {
+ want = append(want, r.Href)
+ }
+ }
+ for _, g := range []string{"free", "sponsored", "house", "ours"} {
+ want = append(want, "/fleet/billing/accounts?tab="+g)
+ }
+ want = append(want, "/fleet/activity?account=accf")
+ if v.Recent[0].Href != "" || v.Recent[0].Account != billCopyStatusUnmatched ||
+ v.Recent[1].Href != "" || v.Recent[1].Account != billCopyDeletedAccount || v.Recent[1].Status.Label != billCopyStatusRefunded {
+ t.Errorf("unmatched and deleted rows: %+v, %+v", v.Recent[0], v.Recent[1])
+ }
+ fx := newConsoleFixture(t)
+ enableBilling(t, fx.srv)
+ body := renderOverview(t, fx, v)
+ if got := overviewRowLinks(body); !reflect.DeepEqual(got, want) {
+ t.Errorf("row links:\n got %q\nwant %q", got, want)
+ }
+ if strings.Count(body, "<div rst-lrow>") < 3 {
+ t.Error("the unmatched, deleted and shared rows are not plain rows")
+ }
+}
+
+// overviewFixture is a billing console on overviewNow with current rates,
+// a fresh reconcile and one eur account paying 2400 a year since 20
+// September, its facts read ten minutes ago.
+func overviewFixture(t *testing.T) (*consoleFixture, *Account) {
+ t.Helper()
+ fx := newConsoleFixture(t)
+ enableBilling(t, fx.srv)
+ fx.srv.opNow = func() time.Time { return overviewNow }
+ if err := fx.st.PutEURRates(fxrate.Rates{Day: "2026-11-06", PerEUR: map[string]float64{"usd": 1.12}}, overviewNow.Add(-time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.SetPaymentsReconciled(overviewNow.Add(-30 * time.Minute)); err != nil {
+ t.Fatal(err)
+ }
+ acct := planAccount(t, fx, 601)
+ if err := fx.st.SetBillingCustomer(acct.ID, "cus_9", overviewNow); err != nil {
+ t.Fatal(err)
+ }
+ b, err := fx.st.BillingAccount(acct.ID)
+ if err != nil || b == nil {
+ t.Fatalf("billing row: %+v, %v", b, err)
+ }
+ b.Subscription, b.ProviderStatus, b.State, b.Currency, b.Billable, b.Live = "sub_9", "active", billing.StatePaid, "eur", true, true
+ b.Annual, b.FactsReadAt, b.PeriodEnd = 2400, overviewNow.Add(-10*time.Minute), time.Date(2027, 9, 20, 0, 0, 0, 0, time.UTC)
+ if err := fx.st.PutBillingState(*b); err != nil {
+ t.Fatal(err)
+ }
+ charge := testCharge("mv_9", "ch_9")
+ charge.Customer, charge.Subscription, charge.Reason = "cus_9", "sub_9", billing.ReasonFirst
+ charge.Amount, charge.Tax, charge.Settled, charge.SettledTax, charge.Fee = 2400, 0, 2400, 0, 100
+ charge.At = time.Date(2026, 9, 20, 0, 0, 0, 0, time.UTC)
+ recordPayment(t, fx.st, charge)
+ return fx, acct
+}
+
+func TestOverviewAfterMidnightFailure(t *testing.T) {
+ fx, acct := overviewFixture(t)
+ // D (31 October) was stored incomplete, D+1 and every other day
+ // complete; the reconcile is fresh now.
+ for d := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC); !d.After(overviewNow); d = d.AddDate(0, 0, 1) {
+ day := d.Format(snapshotDayFormat)
+ snap := arrSnapshot{Day: day, ARR: map[string]int64{"eur": 2400}, EUR: 2400, RateDay: "2026-11-06", Paying: 1, Complete: true}
+ if day == "2026-10-31" {
+ snap.Complete, snap.Why = false, moneyWhyPayments
+ }
+ rows := []accountDay{{Day: day, AccountID: acct.ID, Annual: 2400, Currency: "eur", AnnualEUR: 2400, Paying: true, InARR: true}}
+ if err := fx.st.PutDailySnapshot(snap, rows, day, d); err != nil {
+ t.Fatal(err)
+ }
+ }
+ in, err := fx.srv.opBillingInputs(context.Background(), overviewNow)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if in.Covered {
+ t.Error("October covered with 31 October incomplete")
+ }
+ v := buildOpBillingView(in)
+ for _, s := range v.Tiles[:2] {
+ if s.Value == billCopyNotAvailable {
+ t.Errorf("tile %s refused: %s", s.Label, s.Note)
+ }
+ }
+ if v.Tiles[0].Value != "€24.00" {
+ t.Errorf("ARR = %q", v.Tiles[0].Value)
+ }
+ for _, d := range v.ARR {
+ if d.Day.Format(snapshotDayFormat) == "2026-10-31" && (d.Known || d.H != 0) {
+ t.Errorf("31 October: %+v", d)
+ }
+ }
+ if v.ARRGaps != billCopyARRGapOne {
+ t.Errorf("gaps = %q", v.ARRGaps)
+ }
+ if len(v.Paying) != 1 {
+ t.Fatalf("paying = %+v", v.Paying)
+ }
+ history := fmt.Sprintf(billCopyWhyHistory, "October 2026")
+ for _, f := range []opMoneyFigure{v.Paying[0].Earns, v.Paying[0].Margin} {
+ if f.Shown || f.Why != moneyWhyHistory || f.Reason != history {
+ t.Errorf("%s = %+v; want the history reason", f.Name, f)
+ }
+ }
+ c := signInOperator(t, fx)
+ status, _, body := get(t, c, fx.ts.URL+"/fleet/billing")
+ if status != http.StatusOK || !strings.Contains(body, html.EscapeString(billCopyARRGapOne)) ||
+ !strings.Contains(body, html.EscapeString(history)) {
+ t.Errorf("page = %d; gap note or history reason missing", status)
+ }
+}
+
+func TestOverviewMoneyIncludesFeeRows(t *testing.T) {
+ fx, _ := overviewFixture(t)
+ recordPayment(t, fx.st, billing.Payment{Movement: "mv_fee", Kind: billing.PaymentFee, Reason: billing.ReasonOther,
+ Amount: -45, Currency: "eur", Settled: -45, SettledCurrency: "eur", At: time.Date(2026, 11, 4, 0, 0, 0, 0, time.UTC)})
+ in, err := fx.srv.opBillingInputs(context.Background(), overviewNow)
+ if err != nil {
+ t.Fatal(err)
+ }
+ v := buildOpBillingView(in)
+ if m := v.Months[0]; m.Fees.Text != "€0.45" || m.Net.Text != "−€0.45" {
+ t.Errorf("November: fees %q, net %q", m.Fees.Text, m.Net.Text)
+ }
+ for _, r := range v.Recent {
+ if r.Charged.Text == "−€0.45" {
+ t.Error("the fee row is listed in recent payments")
+ }
+ }
+}
diff --git a/internal/console/static/ops.css b/internal/console/static/ops.css
index 5c02b4144..208103f6c 100644
--- a/internal/console/static/ops.css
+++ b/internal/console/static/ops.css
@@ -244,3 +244,43 @@
[co-archbox] h4 { font-size: var(--rst-fs-base); }
[co-archbox] p { margin-block: var(--rst-sp-1) 0; }
[co-fact] + [co-fact]::before { color: var(--rst-text-faint); content: " · "; }
+
+/* The billing overview (ops_billing.html). Its lists are Rastrillo rows,
+ one column set each; money cells line up on the right in tabular
+ figures. A refused figure (co-na) reads quieter, its reason in its
+ title and listed under the section. */
+[co-cols="billpaying"] { --rst-cols: minmax(10rem, 2fr) minmax(6rem, 1fr) 6.5rem 7.5rem 6.5rem 6.5rem 9.5rem; }
+[co-cols="billmonths"] { --rst-cols: minmax(6.5rem, 1.3fr) repeat(8, minmax(0, 1fr)); }
+[co-cols="billpayments"] { --rst-cols: 6.5rem minmax(8rem, 1.3fr) minmax(9rem, 2fr) 6.5rem 6.5rem; }
+[co-cols="billreasons"] { --rst-cols: minmax(10rem, 2fr) 5.5rem 10rem minmax(8rem, 1.5fr); }
+[co-cols="billlimits"] { --rst-cols: minmax(10rem, 2fr) minmax(8rem, 1.2fr) minmax(7rem, 1fr) 10rem; }
+[co-cols="billearned"] { --rst-cols: minmax(0, 1fr) auto; }
+[co-cols="billfunnel"] { --rst-cols: 10rem minmax(0, 1fr); }
+[co-num] { font-variant-numeric: tabular-nums; text-align: end; white-space: nowrap; }
+[co-na] { color: var(--rst-text-muted); font-size: var(--rst-fs-xs); white-space: normal; }
+[co-sub] { color: var(--rst-text-muted); display: block; font-size: var(--rst-fs-xs); }
+[co-total] { font-weight: 650; }
+[co-statna] { display: contents; }
+[co-statna] [rst-stat-num] { color: var(--rst-text-muted); font-size: var(--rst-fs-lg); }
+[co-cols^="bill"] > [rst-lrow="head"] > * { min-inline-size: 0; white-space: normal; }
+
+/* A billing row that opens a page: the whole row is the link. Its first
+ rst-nm link stretches over the row, so the row has one focus stop. */
+[co-rowlink] { position: relative; }
+[co-rowlink] > a.rst-nm::after { content: ""; inset: 0; position: absolute; }
+[co-rowlink]:hover { background-color: var(--rst-accent-soft); }
+
+/* Earned this month beside the funnel; one above the other on a phone.
+ The ARR chart has up to 90 bars, so they sit closer. */
+[co-billtwo] { display: grid; gap: 1.5rem var(--rst-sp-5); grid-template-columns: repeat(2, minmax(0, 1fr)); margin-block-start: 1.5rem; }
+[co-bars="dense"] { gap: 1px; }
+
+@media (max-width: 800px) {
+ [co-billtwo] { grid-template-columns: minmax(0, 1fr); }
+ [co-cols="billfunnel"] > [rst-lrow] { grid-template-columns: 8.5rem minmax(0, 1fr); }
+ [co-cols="billpaying"] > [rst-lrow] > :is(:nth-child(2), :nth-child(n+4)),
+ [co-cols="billmonths"] > [rst-lrow] > :is(:nth-child(n+2):nth-child(-n+6), :nth-child(n+8)),
+ [co-cols="billpayments"] > [rst-lrow] > :is(:nth-child(1), :nth-child(3), :nth-child(5)),
+ [co-cols="billreasons"] > [rst-lrow] > :is(:nth-child(2), :nth-child(4)),
+ [co-cols="billlimits"] > [rst-lrow] > :is(:nth-child(2), :nth-child(4)) { display: none; }
+}
diff --git a/internal/console/templates/ops_billing.html b/internal/console/templates/ops_billing.html
index f048c3966..93e04670d 100644
--- a/internal/console/templates/ops_billing.html
+++ b/internal/console/templates/ops_billing.html
@@ -1,7 +1,134 @@
-{{/* Billing (/fleet/billing, opbilling.go): the overview. Every word comes
- from opbilling_copy.go through .OpBilling. */}}
+{{/* Billing (/fleet/billing, opbilling.go, opbilling_overview.go): the
+ overview, in the approved mockup's order. Every word comes from
+ opbilling_copy.go through .OpBilling (its fixed words as .W); every
+ money cell is an opMoneyFigure, printed by op_bill_fig. Each list row
+ with a link is co-rowlink: its first rst-nm link covers the row. */}}
{{define "ops_billing"}}{{template "op_top" .}}
{{template "op_billing_head" .OpBilling}}
+{{with .OpBilling}}{{$w := .W}}
+{{with .RateLine}}<p co-note>{{.}}</p>{{end}}
+<div rst-stats rst-card co-billstats>
+ {{- range .Tiles}}
+ {{if eq .Value $w.NotAvailable}}<div co-statna>{{template "op_stat" .}}</div>{{else}}{{template "op_stat" .}}{{end}}
+ {{- end}}
+</div>
+
+<div rst-box-head><h2>{{$w.ARRChart}}</h2></div>
+{{if .ARR}}
+<div rst-card>
+ <div co-bars="dense" aria-hidden="true">
+ {{- range .ARR}}<span co-bar co-h="{{.H}}"></span>{{end}}
+ </div>
+ <div co-bars-axis aria-hidden="true"><span>{{.ARRFrom}}</span><span>{{$w.Today}}</span></div>
+ <table class="rst-sr-only">
+ <caption>{{$w.ARRCaption}}</caption>
+ <tr><th scope="col">{{$w.ARRDay}}</th><th scope="col">{{$w.ARREUR}}</th></tr>
+ {{- range .ARR}}
+ <tr><td>{{.Day.Format "2 Jan"}}</td><td>{{.Value.Text}}</td></tr>
+ {{- end}}
+ </table>
+</div>
+{{with .ARRGaps}}<p co-note>{{.}}</p>{{end}}
+{{else}}{{template "op_empty" (opEmpty "" $w.ARREmpty)}}{{end}}
+
+<div rst-box-head><h2>{{$w.PayingHeading}}</h2><a rst-btn="ghost" href="/fleet/billing/accounts?tab=paying">{{$w.AllPaying}}</a></div>
+{{if not .PayingList.Shown}}{{template "op_empty" (opEmpty "" .PayingList.Reason)}}
+{{else if .Paying}}
+<div rst-card co-cols="billpaying">
+ <div rst-lrow="head"><span>{{$w.ColAccount}}</span><span>{{$w.ColPlan}}</span><span co-num>{{$w.ColEarns}}</span><span co-num>{{$w.ColCosts}} <small>{{$w.Estimate}}</small></span><span co-num>{{$w.ColMargin}}</span><span>{{$w.ColRenews}}</span><span>{{$w.ColStatus}}</span></div>
+ {{- range .Paying}}
+ <div rst-lrow co-rowlink><a class="rst-nm" href="{{.Href}}">{{.Name}}{{with .Since}}<small>{{.}}</small>{{end}}</a><span>{{.Plan}}{{with .PlanNote}}<small co-sub>{{.}}</small>{{end}}</span>{{template "op_bill_fig" .Earns}}{{template "op_bill_fig" .Costs}}{{template "op_bill_fig" .Margin}}<span class="rst-cell-mut">{{.Renews}}</span><span>{{template "op_status" .Status}}</span></div>
+ {{- end}}
+</div>
+<p co-note>{{.PayingNote}}</p>
+{{with .HistoryNote}}<p co-note>{{.}}</p>{{end}}
+{{template "op_bill_whys" .PayingWhys}}
+{{else}}{{template "op_empty" (opEmpty "" $w.PayingEmpty)}}{{end}}
+
+<div co-billtwo>
+ <section>
+ <div rst-box-head><h2>{{.EarnedHeading}}</h2></div>
+ <div rst-card co-cols="billearned">
+ {{- range .Earned}}
+ <div rst-lrow{{if .Total}} co-total{{end}}><span>{{.Label}}{{with .Note}}<small co-sub>{{.}}</small>{{end}}</span>{{template "op_bill_fig" .Value}}</div>
+ {{- end}}
+ </div>
+ <p co-note>{{$w.EarnedNote}}</p>
+ {{template "op_bill_whys" .EarnedWhys}}
+ </section>
+ <section>
+ <div rst-box-head><h2>{{$w.FunnelHeading}}</h2></div>
+ <div rst-card co-cols="billfunnel">
+ {{- range .Funnel}}
+ <div rst-lrow><span>{{.Label}}</span>{{if .Shown}}{{template "op_meter" .Meter}}{{else}}<span class="rst-cell-mut" title="{{.Reason}}">{{.Meter.Text}}</span>{{end}}</div>
+ {{- end}}
+ </div>
+ {{range .Funnel}}{{if not .Shown}}<p co-note>{{.Reason}}</p>{{end}}{{end}}
+ </section>
+</div>
+
+<div rst-box-head><h2>{{$w.MoneyHeading}}</h2></div>
+<div rst-card co-cols="billmonths">
+ <div rst-lrow="head"><span>{{$w.ColMonth}}</span><span co-num>{{$w.ColSubscriptions}}</span><span co-num>{{$w.OnceOff}}</span><span co-num>{{$w.Refunds}}</span><span co-num>{{$w.ColTax}}</span><span co-num>{{$w.ColFees}}</span><span co-num>{{$w.ColNet}}</span><span co-num>{{$w.ColAWS}}</span><span co-num>{{$w.ColCash}}</span></div>
+ {{- range .Months}}
+ <div rst-lrow co-rowlink><a class="rst-nm" href="{{.Href}}">{{.Label}}</a>{{template "op_bill_fig" .Subscriptions}}{{template "op_bill_fig" .OnceOff}}{{template "op_bill_fig" .Refunds}}{{template "op_bill_fig" .Tax}}{{template "op_bill_fig" .Fees}}{{template "op_bill_fig" .Net}}{{template "op_bill_fig" .AWS}}{{template "op_bill_fig" .Cash}}</div>
+ {{- end}}
+</div>
+<p co-note>{{$w.MoneyNote}}</p>
+{{range .MonthNotes}}<p co-note>{{.}}</p>{{end}}
+{{template "op_bill_whys" .MonthWhys}}
+
+<div rst-box-head><h2>{{$w.RecentHeading}}</h2><a rst-btn="ghost" href="/fleet/billing/payments">{{$w.AllPayments}}</a></div>
+{{if .Recent}}
+<div rst-card co-cols="billpayments">
+ <div rst-lrow="head"><span>{{$w.ColWhen}}</span><span>{{$w.ColAccount}}</span><span>{{$w.ColWhat}}</span><span co-num>{{$w.ColAmount}}</span><span>{{$w.ColStatus}}</span></div>
+ {{- range .Recent}}
+ {{if .Href}}<div rst-lrow co-rowlink>{{else}}<div rst-lrow>{{end}}<span class="rst-cell-mut">{{.When}}</span>{{if .Href}}<a class="rst-nm" href="{{.Href}}">{{.Account}}</a>{{else}}<span class="rst-cell-mut">{{.Account}}</span>{{end}}<span co-clip title="{{.What}}">{{.What}}</span>{{template "op_bill_fig" .Charged}}<span>{{template "op_status" .Status}}</span></div>
+ {{- end}}
+</div>
+{{template "op_bill_whys" .RecentWhys}}
+{{else}}{{template "op_empty" (opEmpty "" $w.PaymentsEmpty)}}{{end}}
+
+<div rst-box-head><h2>{{$w.WeeklyHeading}}</h2></div>
+{{if not .WeeksFig.Shown}}{{template "op_empty" (opEmpty "" .WeeksFig.Reason)}}
+{{else}}
+<div rst-card>
+ <div co-bars aria-hidden="true">
+ {{- range .Weeks}}<span co-bar co-h="{{.H}}"></span>{{end}}
+ </div>
+ <div co-bars-axis aria-hidden="true"><span>{{(index .Weeks 0).Day.Format "2 Jan"}}</span><span>{{$w.ThisWeek}}</span></div>
+ <table class="rst-sr-only">
+ <caption>{{$w.WeeklyCaption}}</caption>
+ <tr><th scope="col">{{$w.WeeklyWeek}}</th><th scope="col">{{$w.WeeklyCount}}</th></tr>
+ {{- range .Weeks}}
+ <tr><td>{{.Day.Format "2 Jan"}}</td><td>{{.N}}</td></tr>
+ {{- end}}
+ </table>
+</div>
+{{end}}
+
+<div rst-box-head><h2>{{$w.ReasonsHeading}}</h2><a rst-btn="ghost" href="/fleet/billing/accounts">{{$w.AllAccounts}}</a></div>
+<div rst-card co-cols="billreasons">
+ <div rst-lrow="head"><span>{{$w.ColWhy}}</span><span co-num>{{$w.Accounts}}</span><span co-num>{{.CostHeading}} <small>{{$w.Estimate}}</small></span><span>{{$w.ColCostliest}}</span></div>
+ {{- range .Reasons}}
+ {{if .Href}}<div rst-lrow co-rowlink><a class="rst-nm" href="{{.Href}}">{{.Label}}</a><span co-num>{{opnum .Count}}</span>{{else}}<div rst-lrow><span>{{.Label}}</span><span></span>{{end}}{{template "op_bill_fig" .Cost}}<span class="rst-cell-mut">{{.Biggest}}</span></div>
+ {{- end}}
+</div>
+<p co-note>{{$w.ReasonNote}}</p>
+{{template "op_bill_whys" .ReasonWhys}}
+
+<div rst-box-head><h2>{{$w.LimitsHeading}}</h2><a rst-btn="ghost" href="/fleet/billing/accounts?tab=free&amp;sort=limit">{{$w.AllFree}}</a></div>
+{{if .NearLimits}}
+<div rst-card co-cols="billlimits">
+ <div rst-lrow="head"><span>{{$w.ColAccount}}</span><span>{{$w.ColNearest}}</span><span co-num>{{$w.ColUsed}}</span><span co-num>{{.CostHeading}} <small>{{$w.Estimate}}</small></span></div>
+ {{- range .NearLimits}}
+ <div rst-lrow co-rowlink><a class="rst-nm" href="{{.Href}}">{{.Name}}</a><span>{{.Limit}}</span><span co-num>{{.Used}}</span>{{template "op_bill_fig" .Cost}}</div>
+ {{- end}}
+</div>
+<p co-note>{{$w.LimitsNote}}</p>
+{{template "op_bill_whys" .LimitWhys}}
+{{else}}{{template "op_empty" (opEmpty "" $w.LimitsEmpty)}}{{end}}
+{{end}}
{{template "op_bottom" .}}{{end}}
{{/* op_billing_head is every billing page's header: the page header and,
@@ -10,3 +137,11 @@
{{define "op_billing_head"}}{{template "op_page_header" .Header}}
{{if .TestMode}}<div rst-callout rst-tone="info"><span rst-callout-ic aria-hidden="true">{{icon "info"}}</span><div rst-callout-body><p>{{opBillingTestMode}}</p></div></div>
{{end}}{{end}}
+
+{{/* op_bill_fig is one money cell: the figure, or Not available yet with
+ its reason as the cell's title (the reasons are also listed under
+ the section, op_bill_whys). Its data is an opMoneyFigure. */}}
+{{define "op_bill_fig"}}{{if .Shown}}<span co-num>{{.Text}}</span>{{else}}<span co-num co-na title="{{.Reason}}">{{.Text}}</span>{{end}}{{end}}
+
+{{/* op_bill_whys is a section's refusal reasons, one line each. */}}
+{{define "op_bill_whys"}}{{range .}}<p co-note>{{.}}</p>{{end}}{{end}}