console: the billing accounts list
/fleet/billing/accounts lists one group at a time (Paying, Free, Sponsored, House, Ours, each tab with its count), sorted by earns, costs, margin, joined or nearness to a limit, 50 to a page. Earns, costs and margin are accountFigures for the last complete month; a sort whose column is refused for any row falls back to joined and says why (BDP-131). Tab counts declare the facts and the payments. Rows open the account's activity view across their whole width. The overview's input gathering is split: opBillingAccountInputs reads what every per-account figure needs, and both pages use it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+679
−41
internal/console/opbilling.go+276 −33internal/console/opbilling_money.go+11 −5internal/console/opbilling_test.go+354 −0internal/console/static/ops.css+9 −1internal/console/templates/ops_billing_accounts.html+29 −2
diff --git a/internal/console/opbilling.go b/internal/console/opbilling.go| index d153d7c4f..1c187c774 100644 |
| --- a/internal/console/opbilling.go |
| +++ b/internal/console/opbilling.go |
| @@ -1,10 +1,14 @@ |
| package console |
| import ( |
| + "cmp" |
| "context" |
| "fmt" |
| "log" |
| "net/http" |
| + "net/url" |
| + "slices" |
| + "strconv" |
| "time" |
| ) |
| @@ -17,10 +21,224 @@ import ( |
| // exactly as a missing route does, operators included. Every word comes |
| // from opbilling_copy.go. |
| -// opBillingAccountsView is the accounts list's data. |
| +// opBillingAccountsView is the accounts list's data: one group's accounts |
| +// (Tabs, each group with its count), sorted (Sort), 50 to a page, with the |
| +// last complete month's earns, costs and margin. Fallback says the list |
| +// sorts by joined because the chosen sort's column is not available; Empty |
| +// stands in for a group with no accounts; Whys are the reasons the page's |
| +// refused figures give, once each. PageLine, Prev and Next are the pager, |
| +// "" on a single page; Prev and Next are "" at either end. |
| type opBillingAccountsView struct { |
| - Header opHeader |
| - TestMode bool |
| + Header opHeader |
| + TestMode bool |
| + RateNote string // BDP-5, when there are rates |
| + MonthName string // the last complete month, as the overview names it |
| + MonthNote string // BDP-117 |
| + Tabs opTabs |
| + Sort opTabs |
| + Fallback string |
| + Rows []opBillingAccountRow |
| + Empty string |
| + Whys []string |
| + PageLine string |
| + Prev string |
| + Next string |
| + // Figures is every figure the builder made, in order: the five |
| + // counts, then the page's rows'. |
| + Figures []opMoneyFigure |
| +} |
| + |
| +// opBillingAccountsWords are the accounts list's fixed words, every one an |
| +// approved row of opbilling_copy.go; the template reads them as .W. |
| +type opBillingAccountsWords struct { |
| + ColAccount, ColPlan, ColApps, ColEarns, ColCosts, Estimate, ColMargin, ColJoined string |
| + SortBy, Prev, Next string |
| +} |
| + |
| +var opBillingAccountsFixed = opBillingAccountsWords{ |
| + ColAccount: billCopyColAccount, ColPlan: billCopyColPlan, ColApps: billCopyColApps, ColEarns: billCopyColEarns, |
| + ColCosts: billCopyColCosts, Estimate: billCopyEstimate, ColMargin: billCopyColMargin, ColJoined: billCopyColJoined, |
| + SortBy: billCopySortBy, Prev: billCopyPagerPrev, Next: billCopyPagerNext, |
| +} |
| + |
| +// W is the accounts list's fixed words. |
| +func (*opBillingAccountsView) W() opBillingAccountsWords { return opBillingAccountsFixed } |
| + |
| +// opBillingAccountsPath is the accounts list's route. |
| +const opBillingAccountsPath = "/fleet/billing/accounts" |
| + |
| +// opBillingAccountsPerPage is how many accounts a page of the list shows. |
| +const opBillingAccountsPerPage = 50 |
| + |
| +// opBillingSortDefault is the accounts list's sort without a known one. |
| +const opBillingSortDefault = "costs" |
| + |
| +// opBillingAccountSorts are the accounts list's sorts: the query value, |
| +// its label, and the money column it sorts by ("" for one that is never |
| +// refused). |
| +var opBillingAccountSorts = []struct{ Key, Label, Column string }{ |
| + {"earns", billCopySortEarnings, "earns"}, |
| + {"costs", billCopySortCosts, "costs"}, |
| + {"margin", billCopySortMargin, "margin"}, |
| + {"joined", billCopySortNewest, ""}, |
| + {"limit", billCopySortLimit, ""}, |
| +} |
| + |
| +// opBillingTabLabels is each group's tab label and its empty line. |
| +var opBillingTabLabels = map[billingGroup][2]string{ |
| + groupPaying: {billCopyFunnelPaying, billCopyPayingEmpty}, |
| + groupFree: {billCopyTabFree, billCopyFreeEmpty}, |
| + groupSponsored: {billCopyTabSponsored, billCopySponsoredEmpty}, |
| + groupHouse: {billCopyTabHouse, billCopyHouseEmpty}, |
| + groupOurs: {billCopyTabOurs, billCopyOursEmpty}, |
| +} |
| + |
| +// opBillingAccountsHref is the list at tab and sort, on page n (page 1 |
| +// carries no page parameter), with q's other parameters kept. |
| +func opBillingAccountsHref(q url.Values, tab billingGroup, sort string, n int) string { |
| + v := url.Values{} |
| + for k, vs := range q { |
| + v[k] = slices.Clone(vs) |
| + } |
| + v.Set("tab", string(tab)) |
| + v.Set("sort", sort) |
| + return opPageHref(opBillingAccountsPath, v, n) |
| +} |
| + |
| +// buildOpBillingAccounts is the accounts list: group's rows sorted by sort, |
| +// page page (1-based, clamped), through the gate in, with r the rates |
| +// (in.Rates). An unknown group or sort falls back to paying and costs. |
| +// Each tab's count declares the facts and the payments (the paying group |
| +// depends on both). Earns, costs and margin are accountFigures for the |
| +// last complete month; when the chosen sort's column is refused for any |
| +// row of the group (the gate, or the month not covered), the list sorts by |
| +// joined and Fallback says so with the first such row's reason. Sorts are |
| +// descending, joined newest first, limit highest used / limit first with |
| +// accounts that have no cap row last; ties by account id. Pure. |
| +func buildOpBillingAccounts(rows []accountMoney, covered bool, in moneyInputs, r eurRates, group billingGroup, sort string, page int, q url.Values) opBillingAccountsView { |
| + if _, ok := opBillingTabLabels[group]; !ok { |
| + group = groupPaying |
| + } |
| + column, known := "", false |
| + for _, s := range opBillingAccountSorts { |
| + if s.Key == sort { |
| + column, known = s.Column, true |
| + } |
| + } |
| + if !known { |
| + return buildOpBillingAccounts(rows, covered, in, r, group, opBillingSortDefault, page, q) |
| + } |
| + month := lastCompleteMonth(in.Now) |
| + v := opBillingAccountsView{ |
| + MonthName: opBillingMonthLabel(month, in.Now), |
| + Empty: opBillingTabLabels[group][1], |
| + } |
| + v.MonthNote = fmt.Sprintf(billCopyAccountsMonthNote, v.MonthName) |
| + if r.Day != "" { |
| + v.RateNote = fmt.Sprintf(billCopyRateNoteLine, opBillingRateDay(r.Day)) |
| + } |
| + |
| + counts := map[billingGroup]int{} |
| + var list []accountMoney |
| + for _, a := range rows { |
| + counts[a.Group]++ |
| + if a.Group == group { |
| + list = append(list, a) |
| + } |
| + } |
| + v.Tabs.Label = billCopyTabsLabel |
| + for _, g := range billingGroupOrder { |
| + n := counts[g] |
| + count := opMoney(&v.Figures, "tab."+string(g)+".count", in, moneyUse{Inputs: inFacts | inPayments}, nil, |
| + func() string { return opNumber(n) }) |
| + label := opBillingTabLabels[g][0] |
| + if count.Shown { |
| + label += " " + count.Text |
| + } |
| + v.Tabs.Items = append(v.Tabs.Items, opTab{Label: label, Href: opBillingAccountsHref(q, g, sort, 1), Current: g == group}) |
| + } |
| + v.Sort.Label = billCopySortBy |
| + for _, s := range opBillingAccountSorts { |
| + v.Sort.Items = append(v.Sort.Items, opTab{Label: s.Label, Href: opBillingAccountsHref(q, group, s.Key, 1), Current: s.Key == sort}) |
| + } |
| + |
| + // The chosen column refused for any row: sort by joined, saying why. |
| + // The links keep the chosen sort. |
| + by := sort |
| + if column != "" { |
| + for _, a := range list { |
| + var scratch []opMoneyFigure |
| + earns, costs, margin := accountFigures(&scratch, a, covered, in, r, "") |
| + f := map[string]opMoneyFigure{"earns": earns, "costs": costs, "margin": margin}[column] |
| + if !f.Shown { |
| + v.Fallback = fmt.Sprintf(billCopySortFallback, f.Reason) |
| + by = "joined" |
| + break |
| + } |
| + } |
| + } |
| + opBillingSortAccounts(list, by, r) |
| + |
| + pages := max((len(list)+opBillingAccountsPerPage-1)/opBillingAccountsPerPage, 1) |
| + page = min(max(page, 1), pages) |
| + if pages > 1 { |
| + v.PageLine = fmt.Sprintf(billCopyPagerPage, opNumber(page), opNumber(pages)) |
| + if page > 1 { |
| + v.Prev = opBillingAccountsHref(q, group, sort, page-1) |
| + } |
| + if page < pages { |
| + v.Next = opBillingAccountsHref(q, group, sort, page+1) |
| + } |
| + } |
| + lo := (page - 1) * opBillingAccountsPerPage |
| + hi := min(lo+opBillingAccountsPerPage, len(list)) |
| + for _, a := range list[lo:hi] { |
| + f := a.Fact |
| + earns, costs, margin := accountFigures(&v.Figures, a, covered, in, r, "accounts."+f.Sqid) |
| + v.Rows = append(v.Rows, opBillingAccountRow{ |
| + Href: opBillingAccountHref(f.Sqid), Name: f.Name, Plan: planLabel(f.Plan), PlanNote: opBillingPlanNote(f), |
| + Apps: f.Apps, Earns: earns, Costs: costs, Margin: margin, Joined: opBillingDate(f.Created), |
| + }) |
| + } |
| + v.Whys = opBillingWhys(v.Figures) |
| + return v |
| +} |
| + |
| +// opBillingSortAccounts sorts list in place by sort: earns, costs or |
| +// margin highest first (euro cents at r); joined newest first; limit the |
| +// highest used / limit first, accounts with no cap row last. Ties by |
| +// account id. |
| +func opBillingSortAccounts(list []accountMoney, sort string, r eurRates) { |
| + key := func(a accountMoney) int64 { |
| + earned, cost := a.amounts(r) |
| + switch sort { |
| + case "earns": |
| + return earned |
| + case "costs": |
| + return cost |
| + case "margin": |
| + return earned - cost |
| + } |
| + return a.Fact.Created.UnixNano() |
| + } |
| + ratio := func(a accountMoney) float64 { |
| + if a.NearLimit <= 0 { |
| + return -1 |
| + } |
| + return float64(a.NearUsed) / float64(a.NearLimit) |
| + } |
| + slices.SortStableFunc(list, func(a, b accountMoney) int { |
| + var c int |
| + if sort == "limit" { |
| + c = cmp.Compare(ratio(b), ratio(a)) |
| + } else { |
| + c = cmp.Compare(key(b), key(a)) |
| + } |
| + if c != 0 { |
| + return c |
| + } |
| + return cmp.Compare(a.Fact.AccountID, b.Fact.AccountID) |
| + }) |
| } |
| // opBillingPaymentsView is the payments list's data. |
| @@ -78,28 +296,23 @@ func (s *Server) handleOpBilling(w http.ResponseWriter, r *http.Request) { |
| 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. |
| +// opBillingInputs gathers the overview's inputs at now: what every |
| +// per-account figure needs (opBillingAccountInputs, with 90 days of |
| +// snapshots for the ARR chart), each month's platform cost, six months of |
| +// payments with fee rows (the money table and this month), the newest |
| +// payments and the funnel. 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) |
| + today := opMidnight(now) |
| + in, err := s.opBillingAccountInputs(ctx, now, today.AddDate(0, 0, -(opBillingChartDays-1))) |
| 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) |
| + monthStart := today.AddDate(0, 0, 1-today.Day()) |
| 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 { |
| @@ -112,13 +325,40 @@ func (s *Server) opBillingInputs(ctx context.Context, now time.Time) (opBillingI |
| } |
| in.Payments = all |
| in.Months = moneyByMonth(all, months, in.Rates, in.Platform) |
| + if in.Recent, _, err = s.store.Payments(paymentFilter{Limit: opBillingListMax}); err != nil { |
| + return opBillingInput{}, err |
| + } |
| + signed, withApp, active, err := s.store.BillingFunnel(now) |
| + if err != nil { |
| + return opBillingInput{}, err |
| + } |
| + in.Funnel = [3]int{signed, withApp, active} |
| + return in, nil |
| +} |
| + |
| +// opBillingAccountInputs gathers, at now, what every per-account figure |
| +// for the last complete month is built from (the overview's paying, reasons |
| +// and limits lists and the accounts page): the revenue and facts, the |
| +// stored snapshots from snapsFrom to today, that month's payments (Kind |
| +// "": no fee rows, for once-offs) and account rows (Earned and Covered |
| +// through accountEarnings, which needs the month's snapshots: snapsFrom is |
| +// at or before its first day), its Economics read (an error is logged; |
| +// econComplete decides whether costs show) and the nearest caps. The gate |
| +// is Rev.Inputs with EconomicsComplete. |
| +func (s *Server) opBillingAccountInputs(ctx context.Context, now, snapsFrom 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, Gate: rev.Inputs} |
| + today := opMidnight(now) |
| + monthStart := today.AddDate(0, 0, 1-today.Day()) |
| lastStart := monthStart.AddDate(0, -1, 0) |
| + in.LastMonth = lastStart.Format("2006-01") |
| 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 { |
| + if in.Snaps, err = s.store.ARRSnapshots(snapsFrom.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)) |
| @@ -126,12 +366,9 @@ func (s *Server) opBillingInputs(ctx context.Context, now time.Time) (opBillingI |
| 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) |
| + log.Printf("console: billing: economics: %v", econErr) |
| } |
| in.Gate.EconomicsComplete = econComplete(econ, econErr) |
| in.CostUSD = map[string]float64{} |
| @@ -140,11 +377,6 @@ func (s *Server) opBillingInputs(ctx context.Context, now time.Time) (opBillingI |
| 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(now); err != nil { |
| return opBillingInput{}, err |
| } |
| @@ -157,11 +389,22 @@ func (s *Server) handleOpBillingAccounts(w http.ResponseWriter, r *http.Request) |
| if !ok { |
| return |
| } |
| - p := s.billingPage(addr, raw, billCopyAccounts) |
| - p.OpBillingAccounts = &opBillingAccountsView{ |
| - Header: opHeader{Title: billCopyAccounts, Sub: billCopyAccountsSub}, |
| - TestMode: s.billingTestMode(), |
| + now := s.now() |
| + today := opMidnight(now) |
| + in, err := s.opBillingAccountInputs(r.Context(), now, today.AddDate(0, -1, 1-today.Day())) |
| + if err != nil { |
| + log.Printf("console: billing accounts: %v", err) |
| + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) |
| + return |
| } |
| + q := r.URL.Query() |
| + page, _ := strconv.Atoi(q.Get("page")) |
| + rows := accountMoneyRows(in.Facts, in.ExemptID, in.Earned, in.LastRows, in.CostUSD, in.Near, in.Rates) |
| + v := buildOpBillingAccounts(rows, in.Covered, in.Gate, in.Rates, billingGroup(q.Get("tab")), q.Get("sort"), page, q) |
| + v.Header = opHeader{Title: billCopyAccounts, Sub: billCopyAccountsSub} |
| + v.TestMode = s.billingTestMode() |
| + p := s.billingPage(addr, raw, billCopyAccounts) |
| + p.OpBillingAccounts = &v |
| s.render(w, http.StatusOK, "ops_billing_accounts", p) |
| } |
diff --git a/internal/console/opbilling_money.go b/internal/console/opbilling_money.go| index 751a21b9f..1e5335238 100644 |
| --- a/internal/console/opbilling_money.go |
| +++ b/internal/console/opbilling_money.go |
| @@ -385,6 +385,16 @@ func accountMoneyRows(facts []billingFact, exemptID int64, earned map[int64]int6 |
| return out |
| } |
| +// amounts are what a earned (recurring plus once-off) and what it cost |
| +// (Economics' estimate, 0 with no row), in euro cents at r: the sums behind |
| +// accountFigures, and what the accounts list sorts by. |
| +func (a accountMoney) amounts(r eurRates) (earned, cost int64) { |
| + if a.HasCost { |
| + cost = settledEUR(r, int64(math.Round(a.CostUSD*100)), "usd") |
| + } |
| + return a.Recurring + a.OnceOff, cost |
| +} |
| + |
| // 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 |
| @@ -404,11 +414,7 @@ func accountFigures(figs *[]opMoneyFigure, a accountMoney, covered bool, in mone |
| 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") |
| - } |
| + earned, cost := a.amounts(r) |
| if covered { |
| earns = opMoney(figs, prefix+".earns", in, earnsUse, nil, func() string { return eurText(earned) }) |
| } else { |
diff --git a/internal/console/opbilling_test.go b/internal/console/opbilling_test.go| index 1e0001053..93346ee06 100644 |
| --- a/internal/console/opbilling_test.go |
| +++ b/internal/console/opbilling_test.go |
| @@ -822,3 +822,357 @@ func TestOverviewNativeAmounts(t *testing.T) { |
| t.Error("tile notes missing from the page") |
| } |
| } |
| + |
| +// accountsRow is one account's money parts for the accounts list tests: |
| +// group g, joined on created, earning onceOff (euro cents, in currency) |
| +// and costing usd dollars (none when usd < 0). |
| +func accountsRow(id int64, g billingGroup, created time.Time, onceOff int64, currency string, usd float64) accountMoney { |
| + sqid := fmt.Sprintf("acc%d", id) |
| + a := accountMoney{ |
| + Fact: billingFact{AccountID: id, Sqid: sqid, Name: sqid + "-shop", Plan: "free", Created: created, Apps: int(id % 4)}, |
| + Group: g, OnceOff: onceOff, |
| + } |
| + if currency != "" { |
| + a.OnceOffCurrencies = []string{currency} |
| + } |
| + if usd >= 0 { |
| + a.CostUSD, a.HasCost = usd, true |
| + } |
| + return a |
| +} |
| + |
| +// accountsDay is a day in October 2026. |
| +func accountsDay(d int) time.Time { return time.Date(2026, 10, d, 9, 0, 0, 0, time.UTC) } |
| + |
| +// accountsWorld is four free accounts with ties in every column, two |
| +// paying, one sponsored and the ops account; no house account. |
| +// |
| +// id earns costs margin joined nearest limit |
| +// 10 500 100 400 1 Oct 1 of 3 |
| +// 11 0 200 -200 5 Oct 3 of 3 |
| +// 12 500 100 400 5 Oct none |
| +// 13 1000 0 1000 1 Sep 2 of 3 (once-off in gbp, no cost row) |
| +func accountsWorld() []accountMoney { |
| + near := func(a accountMoney, used int64) accountMoney { |
| + a.NearUsed, a.NearLimit, a.NearCap = used, 3, capRunningThings |
| + return a |
| + } |
| + return []accountMoney{ |
| + accountsRow(1, groupOurs, accountsDay(1), 0, "", 11.2), |
| + accountsRow(2, groupPaying, accountsDay(2), 0, "", 2.24), |
| + accountsRow(3, groupPaying, accountsDay(3), 0, "", 1.12), |
| + near(accountsRow(10, groupFree, accountsDay(1), 500, "eur", 1.12), 1), |
| + near(accountsRow(11, groupFree, accountsDay(5), 0, "", 2.24), 3), |
| + accountsRow(12, groupFree, accountsDay(5), 500, "eur", 1.12), |
| + near(accountsRow(13, groupFree, time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC), 1000, "gbp", -1), 2), |
| + accountsRow(20, groupSponsored, accountsDay(7), 0, "", 1.12), |
| + } |
| +} |
| + |
| +// accountsIDs is the rows' account names, in order. |
| +func accountsIDs(v opBillingAccountsView) []string { |
| + var out []string |
| + for _, r := range v.Rows { |
| + out = append(out, r.Name) |
| + } |
| + return out |
| +} |
| + |
| +func accountsBuild(rows []accountMoney, covered bool, in moneyInputs, g billingGroup, sort string, page int) opBillingAccountsView { |
| + q := url.Values{"tab": {string(g)}, "sort": {sort}} |
| + return buildOpBillingAccounts(rows, covered, in, in.Rates, g, sort, page, q) |
| +} |
| + |
| +func TestBillingAccountsTabsAndCounts(t *testing.T) { |
| + v := accountsBuild(accountsWorld(), true, overviewGood(), groupFree, "margin", 1) |
| + type tab struct { |
| + Label, Href string |
| + Current bool |
| + } |
| + var got []tab |
| + for _, it := range v.Tabs.Items { |
| + got = append(got, tab{it.Label, it.Href, it.Current}) |
| + } |
| + want := []tab{ |
| + {billCopyFunnelPaying + " 2", "/fleet/billing/accounts?sort=margin&tab=paying", false}, |
| + {billCopyTabFree + " 4", "/fleet/billing/accounts?sort=margin&tab=free", true}, |
| + {billCopyTabSponsored + " 1", "/fleet/billing/accounts?sort=margin&tab=sponsored", false}, |
| + {billCopyTabHouse + " 0", "/fleet/billing/accounts?sort=margin&tab=house", false}, |
| + {billCopyTabOurs + " 1", "/fleet/billing/accounts?sort=margin&tab=ours", false}, |
| + } |
| + if v.Tabs.Label != billCopyTabsLabel || !reflect.DeepEqual(got, want) { |
| + t.Errorf("tabs %q:\n got %+v\nwant %+v", v.Tabs.Label, got, want) |
| + } |
| + if ids := accountsIDs(v); len(ids) != 4 { |
| + t.Errorf("free tab rows = %q, want the four free accounts", ids) |
| + } |
| + var sorts []tab |
| + for _, it := range v.Sort.Items { |
| + sorts = append(sorts, tab{it.Label, it.Href, it.Current}) |
| + } |
| + wantSorts := []tab{ |
| + {billCopySortEarnings, "/fleet/billing/accounts?sort=earns&tab=free", false}, |
| + {billCopySortCosts, "/fleet/billing/accounts?sort=costs&tab=free", false}, |
| + {billCopySortMargin, "/fleet/billing/accounts?sort=margin&tab=free", true}, |
| + {billCopySortNewest, "/fleet/billing/accounts?sort=joined&tab=free", false}, |
| + {billCopySortLimit, "/fleet/billing/accounts?sort=limit&tab=free", false}, |
| + } |
| + if v.Sort.Label != billCopySortBy || !reflect.DeepEqual(sorts, wantSorts) { |
| + t.Errorf("sorts %q:\n got %+v\nwant %+v", v.Sort.Label, sorts, wantSorts) |
| + } |
| + if v.MonthName != "October" || v.MonthNote != fmt.Sprintf(billCopyAccountsMonthNote, "October") { |
| + t.Errorf("month %q, note %q", v.MonthName, v.MonthNote) |
| + } |
| + if v.RateNote != fmt.Sprintf(billCopyRateNoteLine, "6 Nov 2026") { |
| + t.Errorf("rate note %q", v.RateNote) |
| + } |
| + r := v.Rows[0] |
| + if r.Href != "/fleet/activity?account=acc13" || r.Joined != "1 Sep 2026" || r.Plan != planLabel("free") || |
| + r.Earns.Text != "€10.00" || r.Costs.Text != "€0.00" || r.Margin.Text != "€10.00" || r.Costs.Native != "" { |
| + t.Errorf("first row = %+v", r) |
| + } |
| + |
| + // The counts declare the facts and the payments: without either, the |
| + // tabs carry their labels alone and the reason is listed. |
| + stale := overviewGood() |
| + stale.StaleFacts = 1 |
| + v = accountsBuild(accountsWorld(), true, stale, groupFree, "margin", 1) |
| + if l := v.Tabs.Items[0].Label; l != billCopyFunnelPaying { |
| + t.Errorf("stale facts: paying tab = %q, want the label alone", l) |
| + } |
| + if !slices.Contains(v.Whys, billCopyWhyFacts) { |
| + t.Errorf("stale facts: whys %q lack the facts reason", v.Whys) |
| + } |
| + |
| + // Each tab's empty line. |
| + for g, want := range map[billingGroup]string{groupPaying: billCopyPayingEmpty, groupFree: billCopyFreeEmpty, |
| + groupSponsored: billCopySponsoredEmpty, groupHouse: billCopyHouseEmpty, groupOurs: billCopyOursEmpty} { |
| + if v := accountsBuild(nil, true, overviewGood(), g, "costs", 1); v.Empty != want || len(v.Rows) != 0 { |
| + t.Errorf("%s with no rows: empty %q, want %q", g, v.Empty, want) |
| + } |
| + } |
| + if v := accountsBuild(accountsWorld(), true, overviewGood(), groupHouse, "costs", 1); v.Empty != billCopyHouseEmpty { |
| + t.Errorf("house tab: empty %q", v.Empty) |
| + } |
| +} |
| + |
| +func TestBillingAccountsSorts(t *testing.T) { |
| + for _, tc := range []struct { |
| + sort string |
| + want []int64 |
| + }{ |
| + {"earns", []int64{13, 10, 12, 11}}, |
| + {"costs", []int64{11, 10, 12, 13}}, |
| + {"margin", []int64{13, 10, 12, 11}}, |
| + {"joined", []int64{11, 12, 10, 13}}, |
| + {"limit", []int64{11, 13, 10, 12}}, |
| + } { |
| + // The same order whatever order the rows come in. |
| + for _, rev := range []bool{false, true} { |
| + rows := accountsWorld() |
| + if rev { |
| + slices.Reverse(rows) |
| + } |
| + v := accountsBuild(rows, true, overviewGood(), groupFree, tc.sort, 1) |
| + var want []string |
| + for _, id := range tc.want { |
| + want = append(want, fmt.Sprintf("acc%d-shop", id)) |
| + } |
| + if got := accountsIDs(v); !reflect.DeepEqual(got, want) { |
| + t.Errorf("sort %s (reversed %v) = %q, want %q", tc.sort, rev, got, want) |
| + } |
| + if v.Fallback != "" { |
| + t.Errorf("sort %s: fallback %q with every input complete", tc.sort, v.Fallback) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestBillingAccountsGateInvariant(t *testing.T) { |
| + rows := accountsWorld() |
| + for _, sort := range []string{"earns", "costs", "margin", "joined", "limit"} { |
| + checkGateInvariant(t, overviewGood(), func(in moneyInputs) []moneyFigure { |
| + var out []moneyFigure |
| + for _, f := range accountsBuild(rows, true, in, groupFree, sort, 1).Figures { |
| + out = append(out, f.moneyFigure) |
| + } |
| + return out |
| + }) |
| + } |
| + v := accountsBuild(rows, true, overviewGood(), groupFree, "costs", 1) |
| + var names []string |
| + for _, f := range v.Figures { |
| + names = append(names, f.Name) |
| + } |
| + want := []string{"tab.paying.count", "tab.free.count", "tab.sponsored.count", "tab.house.count", "tab.ours.count"} |
| + for _, id := range []int{11, 10, 12, 13} { |
| + p := fmt.Sprintf("accounts.acc%d", id) |
| + want = append(want, p+".earns", p+".costs", p+".margin") |
| + } |
| + if !reflect.DeepEqual(names, want) { |
| + t.Errorf("figures:\n got %q\nwant %q", names, want) |
| + } |
| + |
| + // A sort whose column is refused for any row sorts by joined and |
| + // says why. |
| + joined := []string{"acc11-shop", "acc12-shop", "acc10-shop", "acc13-shop"} |
| + late := overviewGood() |
| + late.Reconciled = late.Now.Add(-3 * time.Hour) |
| + noEcon := overviewGood() |
| + noEcon.EconomicsComplete = false |
| + noGBP := overviewGood() |
| + noGBP.Rates.PerEUR = map[string]float64{"usd": 1.12} |
| + for _, tc := range []struct { |
| + name string |
| + in moneyInputs |
| + covered bool |
| + sort string |
| + why string |
| + }{ |
| + {"earns, reconcile late", late, true, "earns", billCopyWhyPayments}, |
| + {"margin, reconcile late", late, true, "margin", billCopyWhyPayments}, |
| + {"costs, economics incomplete", noEcon, true, "costs", billCopyWhyEconomics}, |
| + {"earns, one row's gbp rate missing", noGBP, true, "earns", billCopyWhyRates}, |
| + {"earns, month not covered", overviewGood(), false, "earns", fmt.Sprintf(billCopyWhyHistory, "October 2026")}, |
| + {"margin, month not covered", overviewGood(), false, "margin", fmt.Sprintf(billCopyWhyHistory, "October 2026")}, |
| + } { |
| + v := accountsBuild(rows, tc.covered, tc.in, groupFree, tc.sort, 1) |
| + if want := fmt.Sprintf(billCopySortFallback, tc.why); v.Fallback != want { |
| + t.Errorf("%s: fallback %q, want %q", tc.name, v.Fallback, want) |
| + } |
| + if got := accountsIDs(v); !reflect.DeepEqual(got, joined) { |
| + t.Errorf("%s: rows %q, want by joined %q", tc.name, got, joined) |
| + } |
| + } |
| + // A column still shown keeps its sort. |
| + if v := accountsBuild(rows, false, overviewGood(), groupFree, "costs", 1); v.Fallback != "" { |
| + t.Errorf("costs with the month not covered: fallback %q", v.Fallback) |
| + } |
| + if v := accountsBuild(rows, true, late, groupFree, "limit", 1); v.Fallback != "" { |
| + t.Errorf("limit with the reconcile late: fallback %q", v.Fallback) |
| + } |
| +} |
| + |
| +func TestBillingAccountsPages(t *testing.T) { |
| + var rows []accountMoney |
| + for i := int64(1); i <= 120; i++ { |
| + rows = append(rows, accountsRow(100+i, groupFree, accountsDay(1), 0, "", float64(i))) |
| + } |
| + rows = append(rows, accountsRow(1, groupOurs, accountsDay(1), 0, "", 1)) |
| + base := "/fleet/billing/accounts?" |
| + for _, tc := range []struct { |
| + page, n int |
| + first, line string |
| + prev, next string |
| + }{ |
| + {1, 50, "acc220-shop", "Page 1 of 3", "", base + "page=2&sort=costs&tab=free"}, |
| + {2, 50, "acc170-shop", "Page 2 of 3", base + "sort=costs&tab=free", base + "page=3&sort=costs&tab=free"}, |
| + {3, 20, "acc120-shop", "Page 3 of 3", base + "page=2&sort=costs&tab=free", ""}, |
| + {9, 20, "acc120-shop", "Page 3 of 3", base + "page=2&sort=costs&tab=free", ""}, |
| + } { |
| + v := accountsBuild(rows, true, overviewGood(), groupFree, "costs", tc.page) |
| + if len(v.Rows) != tc.n || v.Rows[0].Name != tc.first || v.PageLine != tc.line || v.Prev != tc.prev || v.Next != tc.next { |
| + t.Errorf("page %d: %d rows from %s, %q, prev %q, next %q", tc.page, len(v.Rows), v.Rows[0].Name, v.PageLine, v.Prev, v.Next) |
| + } |
| + if got := len(v.Figures); got != 5+3*tc.n { |
| + t.Errorf("page %d: %d figures, want the counts and the page's rows'", tc.page, got) |
| + } |
| + } |
| + if v := accountsBuild(accountsWorld(), true, overviewGood(), groupFree, "costs", 1); v.PageLine != "" || v.Prev != "" || v.Next != "" { |
| + t.Errorf("one page: pager %q %q %q", v.PageLine, v.Prev, v.Next) |
| + } |
| +} |
| + |
| +func TestBillingAccountsBadQuery(t *testing.T) { |
| + q := url.Values{"tab": {"bogus"}, "sort": {"price"}, "page": {"-3"}} |
| + v := buildOpBillingAccounts(accountsWorld(), true, overviewGood(), overviewGood().Rates, "bogus", "price", -3, q) |
| + if !v.Tabs.Items[0].Current || !v.Sort.Items[1].Current { |
| + t.Errorf("bad query: tabs %+v, sorts %+v; want Paying and Costs", v.Tabs.Items, v.Sort.Items) |
| + } |
| + if got := accountsIDs(v); !reflect.DeepEqual(got, []string{"acc2-shop", "acc3-shop"}) { |
| + t.Errorf("bad query rows = %q", got) |
| + } |
| + if v.Tabs.Items[1].Href != "/fleet/billing/accounts?sort=costs&tab=free" { |
| + t.Errorf("free tab href %q", v.Tabs.Items[1].Href) |
| + } |
| +} |
| + |
| +func TestBillingAccountsRender(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + enableBilling(t, fx.srv) |
| + render := func(v opBillingAccountsView) string { |
| + t.Helper() |
| + v.Header = opHeader{Title: billCopyAccounts, Sub: billCopyAccountsSub} |
| + rec := httptest.NewRecorder() |
| + p := fx.srv.billingPage("paul@keymail.dev", "", billCopyAccounts) |
| + p.OpBillingAccounts = &v |
| + fx.srv.render(rec, http.StatusOK, "ops_billing_accounts", p) |
| + if rec.Code != http.StatusOK { |
| + t.Fatalf("render = %d: %s", rec.Code, rec.Body.String()) |
| + } |
| + return html.UnescapeString(rec.Body.String()) |
| + } |
| + late := overviewGood() |
| + late.Reconciled = late.Now.Add(-3 * time.Hour) |
| + v := accountsBuild(accountsWorld(), true, late, groupFree, "earns", 1) |
| + body := render(v) |
| + var want []string |
| + for _, r := range v.Rows { |
| + want = append(want, r.Href) |
| + } |
| + if got := overviewRowLinks(body); !reflect.DeepEqual(got, want) || len(got) != 4 { |
| + t.Errorf("row links:\n got %q\nwant %q", got, want) |
| + } |
| + for _, s := range []string{ |
| + v.Fallback, v.MonthNote, v.RateNote, billCopySortBy, billCopyColApps, billCopyColJoined, billCopyEstimate, |
| + `aria-label="` + billCopyTabsLabel + `"`, ">" + billCopyTabFree + "</a>", "acc13-shop", "1 Sep 2026", |
| + } { |
| + if !strings.Contains(body, s) { |
| + t.Errorf("page lacks %q", s) |
| + } |
| + } |
| + if body := render(accountsBuild(nil, true, overviewGood(), groupSponsored, "costs", 1)); !strings.Contains(body, billCopySponsoredEmpty) { |
| + t.Error("the empty sponsored tab lacks its line") |
| + } |
| + var rows []accountMoney |
| + for i := int64(1); i <= 60; i++ { |
| + rows = append(rows, accountsRow(100+i, groupFree, accountsDay(1), 0, "", float64(i))) |
| + } |
| + body = render(accountsBuild(rows, true, overviewGood(), groupFree, "costs", 1)) |
| + for _, s := range []string{"Page 1 of 2", billCopyPagerNext, `href="/fleet/billing/accounts?page=2&sort=costs&tab=free"`} { |
| + if !strings.Contains(body, s) { |
| + t.Errorf("paged list lacks %q", s) |
| + } |
| + } |
| +} |
| + |
| +// The page reads the store as the overview does: every day of October |
| +// complete, the one paying account earned 2400 / 12 = €2.00 there. |
| +func TestBillingAccountsServed(t *testing.T) { |
| + fx, acct := overviewFixture(t) |
| + 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} |
| + 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) |
| + } |
| + } |
| + c := signInOperator(t, fx) |
| + status, _, body := get(t, c, fx.ts.URL+"/fleet/billing/accounts?sort=earns") |
| + body = html.UnescapeString(body) |
| + if status != http.StatusOK { |
| + t.Fatalf("page = %d", status) |
| + } |
| + for _, s := range []string{ |
| + `<a class="rst-nm" href="/fleet/activity?account=` + acct.Sqid + `">`, "<span co-num>€2.00</span>", |
| + billCopyFunnelPaying + " 1", fmt.Sprintf(billCopyAccountsMonthNote, "October"), |
| + } { |
| + if !strings.Contains(body, s) { |
| + t.Errorf("page lacks %q", s) |
| + } |
| + } |
| + if strings.Contains(body, fmt.Sprintf(billCopySortFallback, "")) { |
| + t.Error("page falls back from earns with October covered") |
| + } |
| +} |
diff --git a/internal/console/static/ops.css b/internal/console/static/ops.css| index 208103f6c..d27bc32b6 100644 |
| --- a/internal/console/static/ops.css |
| +++ b/internal/console/static/ops.css |
| @@ -256,6 +256,7 @@ |
| [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-cols="billaccounts"] { --rst-cols: minmax(10rem, 2fr) minmax(6rem, 1fr) 3.5rem 6.5rem 7.5rem 6.5rem 6.5rem; } |
| [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); } |
| @@ -275,6 +276,12 @@ |
| [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; } |
| +/* The accounts list's group tabs, then its sort choices after Sort by, on |
| + one line when they fit; each wraps under the last on a phone. */ |
| +[co-billbar] { align-items: start; column-gap: var(--rst-sp-5); display: flex; flex-wrap: wrap; justify-content: space-between; } |
| +[co-billsort] { align-items: baseline; color: var(--rst-text-muted); display: flex; flex-wrap: wrap; font-size: var(--rst-fs-sm); gap: var(--rst-sp-2); max-inline-size: 100%; min-inline-size: 0; } |
| +[co-billsort] > [rst-seg-tabs] { min-inline-size: 0; } |
| + |
| @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); } |
| @@ -282,5 +289,6 @@ |
| [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; } |
| + [co-cols="billlimits"] > [rst-lrow] > :is(:nth-child(2), :nth-child(4)), |
| + [co-cols="billaccounts"] > [rst-lrow] > :is(:nth-child(n+2):nth-child(-n+4), :nth-child(n+6)) { display: none; } |
| } |
diff --git a/internal/console/templates/ops_billing_accounts.html b/internal/console/templates/ops_billing_accounts.html| index c2232f674..4b2c92167 100644 |
| --- a/internal/console/templates/ops_billing_accounts.html |
| +++ b/internal/console/templates/ops_billing_accounts.html |
| @@ -1,6 +1,33 @@ |
| {{/* Accounts (/fleet/billing/accounts, opbilling.go): what each account |
| - earns and costs. Every word comes from opbilling_copy.go through |
| - .OpBillingAccounts. */}} |
| + earns and costs, one group at a time, sorted, 50 to a page. Every word |
| + comes from opbilling_copy.go through .OpBillingAccounts (its fixed |
| + words as .W); every money cell is an opMoneyFigure, printed by |
| + op_bill_fig (ops_billing.html). Each row is co-rowlink: its rst-nm |
| + link opens the account and covers the row. */}} |
| {{define "ops_billing_accounts"}}{{template "op_top" .}} |
| {{template "op_billing_head" .OpBillingAccounts}} |
| +{{with .OpBillingAccounts}}{{$w := .W}} |
| +{{with .RateNote}}<p co-note>{{.}}</p>{{end}} |
| +<div co-billbar> |
| + {{template "op_seg_tabs" .Tabs}} |
| + <div co-billsort><span aria-hidden="true">{{$w.SortBy}}</span>{{template "op_seg_tabs" .Sort}}</div> |
| +</div> |
| +{{with .Fallback}}<p co-note>{{.}}</p>{{end}} |
| +{{if .Rows}} |
| +<div rst-card co-cols="billaccounts"> |
| + <div rst-lrow="head"><span>{{$w.ColAccount}}</span><span>{{$w.ColPlan}}</span><span co-num>{{$w.ColApps}}</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.ColJoined}}</span></div> |
| + {{- range .Rows}} |
| + <div rst-lrow co-rowlink><a class="rst-nm" href="{{.Href}}">{{.Name}}</a><span>{{.Plan}}{{with .PlanNote}}<small co-sub>{{.}}</small>{{end}}</span><span co-num>{{opnum .Apps}}</span>{{template "op_bill_fig" .Earns}}{{template "op_bill_fig" .Costs}}{{template "op_bill_fig" .Margin}}<span class="rst-cell-mut">{{.Joined}}</span></div> |
| + {{- end}} |
| +</div> |
| +<p co-note>{{.MonthNote}}</p> |
| +{{template "op_bill_whys" .Whys}} |
| +{{if .PageLine}}<nav rst-pagination aria-label="{{.PageLine}}"> |
| + {{- if .Prev}}<a href="{{.Prev}}">{{$w.Prev}}</a>{{else}}<span rst-pagination-disabled>{{$w.Prev}}</span>{{end}} |
| + <span aria-current="page">{{.PageLine}}</span> |
| + {{- if .Next}}<a href="{{.Next}}">{{$w.Next}}</a>{{else}}<span rst-pagination-disabled>{{$w.Next}}</span>{{end}} |
| +</nav>{{end}} |
| +{{else}}{{template "op_empty" (opEmpty "" .Empty)}} |
| +{{template "op_bill_whys" .Whys}}{{end}} |
| +{{end}} |
| {{template "op_bottom" .}}{{end}} |