console: billing overview shows native amounts and pins its routes
Fix round 1 of Task 4 (Astra review of 706f8ae3). - Every converted total on the overview shows its amounts in their own currencies, built in the same opMoney format function (opBillingMoney, opMoneyFigure.Native); totals in euros only show none. ARR points carry their own snapshot's rates day. platformCost keeps its dollars (USD). - NearestCaps takes now and skips rows outside the cap's current period; its contract is in its doc comment. - The three billing routes are pinned in the claim route census.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+303
−51
internal/console/opbilling.go+2 −1internal/console/opbilling_money.go+7 −2internal/console/opbilling_money_test.go+2 −2internal/console/opbilling_overview.go+171 −34internal/console/opbilling_store.go+10 −5internal/console/opbilling_store_test.go+22 −2internal/console/opbilling_test.go+82 −2internal/console/templates/ops_billing.html+4 −3internal/console/testdata/claim-routes.txt+3 −0
diff --git a/internal/console/opbilling.go b/internal/console/opbilling.go| index b7655e391..d153d7c4f 100644 |
| --- a/internal/console/opbilling.go |
| +++ b/internal/console/opbilling.go |
| @@ -110,6 +110,7 @@ func (s *Server) opBillingInputs(ctx context.Context, now time.Time) (opBillingI |
| if err != nil { |
| return opBillingInput{}, err |
| } |
| + in.Payments = all |
| 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 { |
| @@ -144,7 +145,7 @@ func (s *Server) opBillingInputs(ctx context.Context, now time.Time) (opBillingI |
| return opBillingInput{}, err |
| } |
| in.Funnel = [3]int{signed, withApp, active} |
| - if in.Near, err = s.store.NearestCaps(); err != nil { |
| + if in.Near, err = s.store.NearestCaps(now); err != nil { |
| return opBillingInput{}, err |
| } |
| return in, nil |
diff --git a/internal/console/opbilling_money.go b/internal/console/opbilling_money.go| index 5ba763faa..751a21b9f 100644 |
| --- a/internal/console/opbilling_money.go |
| +++ b/internal/console/opbilling_money.go |
| @@ -31,6 +31,7 @@ func econComplete(v *EconomicsView, err error) bool { |
| // platformCost is one month's platform cost as the Billing pages may show it. |
| type platformCost struct { |
| Cents int64 // euro cents; meaningful only when OK and the usd rate converted it |
| + USD int64 // the dollars it converts, in cents; meaningful only when OK |
| Basis string // as carlosPlatformCostUSD returns it |
| Label string // costBasisLabel(Basis, ""): shown beside a figure |
| Hint string // costBasisHint(s.cfg.CostScope, Basis, month), or the |
| @@ -51,7 +52,7 @@ func (s *Server) platformCostEUR(ctx context.Context, month string, r eurRates) |
| pc.Hint = costBasisHint(s.cfg.CostScope, basis, month) |
| return pc |
| } |
| - pc.OK = true |
| + pc.OK, pc.USD = true, int64(math.Round(usd*100)) |
| if cents, converted := r.eurCents(int64(math.Round(usd*100)), "usd"); converted { |
| pc.Cents = cents |
| } else { |
| @@ -69,7 +70,11 @@ const moneyWhyHistory = "history" |
| type opMoneyFigure struct { |
| moneyFigure // Name, Use, Shown, Why (the code) |
| Text string // the formatted figure, or the not-available text |
| - Reason string // the reason's text when !Shown |
| + // Native is a converted total's amounts in their own currencies |
| + // ("$28.00, €24.00"), set by opBillingMoney inside its format |
| + // function; "" when the figure converted nothing or is refused. |
| + Native string |
| + Reason string // the reason's text when !Shown |
| } |
| // opMoney asks moneyReady(in, u) and calls format only when ready. |
diff --git a/internal/console/opbilling_money_test.go b/internal/console/opbilling_money_test.go| index a41b0efe1..49483f7e4 100644 |
| --- a/internal/console/opbilling_money_test.go |
| +++ b/internal/console/opbilling_money_test.go |
| @@ -439,10 +439,10 @@ func TestPlatformCostEUR(t *testing.T) { |
| want platformCost |
| }{ |
| {name: "account bill", bill: ptrBill(bill("account", economics.SourceCostExplorer, 110)), rates: r, |
| - want: platformCost{Cents: 10000, Basis: economics.BasisAccount, Label: c1, OK: true}}, |
| + want: platformCost{Cents: 10000, USD: 11000, Basis: economics.BasisAccount, Label: c1, OK: true}}, |
| {name: "account bill, no usd rate", bill: ptrBill(bill("account", economics.SourceCostExplorer, 110)), |
| rates: eurRates{Day: "2026-11-06", PerEUR: map[string]float64{"gbp": 0.87}}, |
| - want: platformCost{Basis: economics.BasisAccount, Label: c1, Hint: billCopyWhyRates, OK: true}}, |
| + want: platformCost{USD: 11000, Basis: economics.BasisAccount, Label: c1, Hint: billCopyWhyRates, OK: true}}, |
| {name: "unstated bill zero scope", bill: ptrBill(bill("", economics.SourceCostExplorer, 110)), rates: r, |
| want: platformCost{Basis: economics.BasisUnstated, Label: costLabelOther, Hint: c3}}, |
| {name: "manual whole bill account scope", bill: ptrBill(bill("whole", economics.SourceManual, 110)), |
diff --git a/internal/console/opbilling_overview.go b/internal/console/opbilling_overview.go| index 9f96055e5..dc7838d73 100644 |
| --- a/internal/console/opbilling_overview.go |
| +++ b/internal/console/opbilling_overview.go |
| @@ -42,6 +42,9 @@ type opBillingInput struct { |
| ExemptID int64 |
| Rates eurRates |
| Months []moneyMonth // 6, newest first, from the Kind "all" read |
| + // Payments is that read itself: the money table's amounts in their |
| + // own currencies come from it (opBillingNatives). |
| + Payments []paymentRow |
| // LastMonth is the last complete month ("2006-01"); LastRows its |
| // payments (Kind "": no fee rows). |
| LastMonth string |
| @@ -92,6 +95,9 @@ type opBillingARRDay struct { |
| H int |
| Known bool |
| Value opMoneyFigure |
| + // RateNote is BDP-4 with the day's own rates day, when its ARR |
| + // converted another currency. |
| + RateNote string |
| } |
| // opBillingLine is one line of the earned panel; Note sits beside the |
| @@ -313,6 +319,106 @@ func usdCents(r eurRates, usd float64) int64 { |
| return settledEUR(r, int64(math.Round(usd*100)), "usd") |
| } |
| +// nativeAmounts is money in its own currencies: minor units by lower-case |
| +// currency. |
| +type nativeAmounts map[string]int64 |
| + |
| +// plus is a + b, currency by currency; minus is a − b. |
| +func (a nativeAmounts) plus(b nativeAmounts) nativeAmounts { |
| + out := nativeAmounts{} |
| + for c, v := range a { |
| + out[c] += v |
| + } |
| + for c, v := range b { |
| + out[c] += v |
| + } |
| + return out |
| +} |
| + |
| +func (a nativeAmounts) minus(b nativeAmounts) nativeAmounts { |
| + neg := nativeAmounts{} |
| + for c, v := range b { |
| + neg[c] = -v |
| + } |
| + return a.plus(neg) |
| +} |
| + |
| +// nativeText is a converted total's breakdown: each currency with a |
| +// non-zero amount, sorted, written by minor (minorText, passed in so it is |
| +// only ever called from inside an opMoney format function); "" when |
| +// nothing but euros is in it, since nothing was converted. |
| +func nativeText(n nativeAmounts, minor func(int64, string) string) string { |
| + var parts []string |
| + converted := false |
| + for _, c := range slices.Sorted(maps.Keys(n)) { |
| + if n[c] == 0 { |
| + continue |
| + } |
| + converted = converted || c != "eur" |
| + parts = append(parts, minor(n[c], c)) |
| + } |
| + if !converted { |
| + return "" |
| + } |
| + return strings.Join(parts, ", ") |
| +} |
| + |
| +// opBillingMoney is a euro total through opMoney with its breakdown in |
| +// native currencies (Native) built in the same format function. |
| +func opBillingMoney(figs *[]opMoneyFigure, name string, in moneyInputs, u moneyUse, platform map[string]platformCost, cents int64, native nativeAmounts) opMoneyFigure { |
| + var nat string |
| + f := opMoney(figs, name, in, u, platform, func() string { |
| + nat = nativeText(native, minorText) |
| + return eurText(cents) |
| + }) |
| + f.Native = nat |
| + return f |
| +} |
| + |
| +// monthNatives is a month of the money table in settled currencies, by |
| +// column, summed as moneyByMonth sums the euros. |
| +type monthNatives struct { |
| + Subscriptions, OnceOff, Refunds, Tax, Fees, Net nativeAmounts |
| +} |
| + |
| +// opBillingNatives is each of months' columns in settled currencies from |
| +// rows (Kind "all"), by month. |
| +func opBillingNatives(rows []paymentRow, months []string) map[string]monthNatives { |
| + out := map[string]monthNatives{} |
| + for _, m := range months { |
| + out[m] = monthNatives{nativeAmounts{}, nativeAmounts{}, nativeAmounts{}, nativeAmounts{}, nativeAmounts{}, nativeAmounts{}} |
| + } |
| + for _, p := range rows { |
| + m, ok := out[p.At.UTC().Format("2006-01")] |
| + if !ok { |
| + continue |
| + } |
| + c := strings.ToLower(p.SettledCurrency) |
| + revenue := p.Settled - p.SettledTax |
| + switch p.Kind { |
| + case billing.PaymentSubscription: |
| + m.Subscriptions[c] += revenue |
| + case billing.PaymentOnceOff: |
| + m.OnceOff[c] += revenue |
| + case billing.PaymentRefund: |
| + m.Refunds[c] += revenue |
| + case billing.PaymentFee: |
| + m.Fees[c] -= p.Settled |
| + } |
| + m.Tax[c] += p.SettledTax |
| + m.Fees[c] += p.Fee |
| + } |
| + for _, m := range out { |
| + for c, v := range m.Subscriptions.plus(m.OnceOff).plus(m.Refunds).minus(m.Fees) { |
| + m.Net[c] = v |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// usdNative is usd cents as native amounts. |
| +func usdNative(cents int64) nativeAmounts { return nativeAmounts{"usd": cents} } |
| + |
| // 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 { |
| @@ -328,8 +434,14 @@ func buildOpBillingView(in opBillingInput) *opBillingView { |
| } |
| arrCur := slices.Sorted(maps.Keys(in.Rev.ByCurrency)) |
| arrUse := opBillingUse(inFacts|inPayments|inAmounts, arrCur, "") |
| + var monthNames []string |
| + for _, m := range in.Months { |
| + monthNames = append(monthNames, m.Month) |
| + } |
| + natives := opBillingNatives(in.Payments, append(monthNames, month)) |
| + thisNative := natives[thisMonth.Month] |
| - v.Tiles = opBillingTiles(figs, in, thisMonth, arrCur, arrUse) |
| + v.Tiles = opBillingTiles(figs, in, thisMonth, thisNative, arrCur, arrUse) |
| opBillingARRChart(v, in) |
| rows := accountMoneyRows(in.Facts, in.ExemptID, in.Earned, in.LastRows, in.CostUSD, in.Near, in.Rates) |
| @@ -339,13 +451,20 @@ func buildOpBillingView(in opBillingInput) *opBillingView { |
| 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) }) |
| + mrrNative := nativeAmounts{} |
| + dim := int64(daysInMonthOf(in.Now)) |
| + for c, annual := range in.Rev.ByCurrency { |
| + mrrNative[c] = divRound(annual*int64(in.Now.UTC().Day()), 12*dim) |
| + } |
| + awsNative := usdNative(e.Platform.USD) |
| + recurring := opBillingMoney(figs, "earned.recurring", in.Gate, arrUse, in.Platform, e.MRR, mrrNative) |
| + onceOff := opBillingMoney(figs, "earned.onceoff", in.Gate, mUse, in.Platform, e.OnceOff, thisNative.OnceOff) |
| + refunds := opBillingMoney(figs, "earned.refunds", in.Gate, mUse, in.Platform, e.Refunds, thisNative.Refunds) |
| + aws := opBillingMoney(figs, "earned.aws", in.Gate, opBillingPlatformUse(month), in.Platform, e.Platform.Cents, awsNative) |
| 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()) }) |
| + profit := opBillingMoney(figs, "earned.profit", in.Gate, profitUse, in.Platform, e.Profit(), |
| + mrrNative.plus(thisNative.OnceOff).plus(thisNative.Refunds).minus(awsNative)) |
| awsLine := opBillingLine{Label: billCopyEarnedAWS, Value: aws} |
| if aws.Shown { |
| awsLine.Note = e.Platform.Label |
| @@ -379,7 +498,7 @@ func buildOpBillingView(in opBillingInput) *opBillingView { |
| step(billCopyFunnelPaying, in.Rev.Paying, &payingFig), |
| } |
| - opBillingMonths(v, in) |
| + opBillingMonths(v, in, natives) |
| opBillingRecent(v, in) |
| opBillingWeekly(v, in) |
| opBillingReasons(v, in, rows) |
| @@ -389,7 +508,7 @@ func buildOpBillingView(in opBillingInput) *opBillingView { |
| // 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 { |
| +func opBillingTiles(figs *[]opMoneyFigure, in opBillingInput, thisMonth moneyMonth, thisNative monthNatives, arrCur []string, arrUse moneyUse) []opStat { |
| rev := in.Rev |
| rateNote := fmt.Sprintf(billCopyRateNote, opBillingRateDay(in.Rates.Day)) |
| withRate := func(note string, currencies []string) string { |
| @@ -443,9 +562,20 @@ func opBillingTiles(figs *[]opMoneyFigure, in opBillingInput, thisMonth moneyMon |
| } |
| } |
| - 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) }) |
| + // A converted total's note carries its own amounts and the rate day. |
| + withNative := func(note string, f opMoneyFigure) string { |
| + if f.Native == "" { |
| + return note |
| + } |
| + return note + " (" + f.Native + "), " + rateNote |
| + } |
| + mrrNative := nativeAmounts{} |
| + for c, annual := range rev.ByCurrency { |
| + mrrNative[c] = divRound(annual, 12) |
| + } |
| + mrr := opBillingMoney(figs, "tile.mrr", in.Gate, arrUse, in.Platform, divRound(rev.EUR, 12), mrrNative) |
| + received := opBillingMoney(figs, "tile.received", in.Gate, opBillingUse(inPayments, thisMonth.Currencies, ""), in.Platform, |
| + thisMonth.Net, thisNative.Net) |
| var payingNote string |
| paying := opMoney(figs, "tile.paying", in.Gate, payingUse, in.Platform, func() string { |
| @@ -469,8 +599,8 @@ func opBillingTiles(figs *[]opMoneyFigure, in opBillingInput, thisMonth moneyMon |
| func() string { return opNumber(rev.Attention) }) |
| return []opStat{ |
| arrTile, |
| - stat(billCopyTileMRR, mrr, withRate(billCopyMRRNote, arrCur)), |
| - stat(billCopyTileReceived, received, withRate(billCopyReceivedNote, thisMonth.Currencies)), |
| + stat(billCopyTileMRR, mrr, withNative(billCopyMRRNote, mrr)), |
| + stat(billCopyTileReceived, received, withNative(billCopyReceivedNote, received)), |
| payingTile, |
| stat(billCopyTileAttention, attention, billCopyAttentionNote), |
| } |
| @@ -503,7 +633,10 @@ func opBillingARRChart(v *opBillingView, in opBillingInput) { |
| 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) }) |
| + pt.Value = opBillingMoney(&v.Figures, "arr."+day, in.Gate, moneyUse{}, in.Platform, s.EUR, nativeAmounts(s.ARR)) |
| + if pt.Value.Native != "" { |
| + pt.RateNote = fmt.Sprintf(billCopyRateNote, opBillingRateDay(s.RateDay)) |
| + } |
| top = max(top, s.EUR) |
| } else { |
| gaps++ |
| @@ -604,12 +737,13 @@ func opBillingAccountStatus(f billingFact) opPill { |
| // 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) { |
| +func opBillingMonths(v *opBillingView, in opBillingInput, natives map[string]monthNatives) { |
| 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) }) |
| + n := natives[m.Month] |
| + fig := func(col string, cents int64, native nativeAmounts) opMoneyFigure { |
| + return opBillingMoney(&v.Figures, "month."+m.Month+"."+col, in.Gate, use, in.Platform, cents, native) |
| } |
| label := opBillingMonthLabel(m.Month, in.Now) |
| if i == 0 { |
| @@ -617,18 +751,19 @@ func opBillingMonths(v *opBillingView, in opBillingInput) { |
| } |
| 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) }) |
| + Subscriptions: fig("subscriptions", m.Subscriptions, n.Subscriptions), |
| + OnceOff: fig("onceoff", m.OnceOff, n.OnceOff), |
| + Refunds: fig("refunds", m.Refunds, n.Refunds), |
| + Tax: fig("tax", m.Tax, n.Tax), |
| + Fees: fig("fees", m.Fees, n.Fees), |
| + Net: fig("net", m.Net, n.Net), |
| + } |
| + aws := usdNative(m.Platform.USD) |
| + row.AWS = opBillingMoney(&v.Figures, "month."+m.Month+".aws", in.Gate, opBillingPlatformUse(m.Month), in.Platform, |
| + m.Platform.Cents, aws) |
| 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) }) |
| + row.Cash = opBillingMoney(&v.Figures, "month."+m.Month+".cash", in.Gate, cashUse, in.Platform, |
| + m.Net-m.Platform.Cents, n.Net.minus(aws)) |
| if row.AWS.Shown && m.Platform.Label != "" && !slices.Contains(v.MonthNotes, m.Platform.Label) { |
| v.MonthNotes = append(v.MonthNotes, m.Platform.Label) |
| } |
| @@ -750,7 +885,7 @@ func opBillingReasons(v *opBillingView, in opBillingInput, rows []accountMoney) |
| 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 cents, usd, top int64 |
| var biggest string |
| for _, a := range rows { |
| if a.Group != g.Group { |
| @@ -762,26 +897,28 @@ func opBillingReasons(v *opBillingView, in opBillingInput, rows []accountMoney) |
| } |
| c := usdCents(in.Rates, a.CostUSD) |
| cents += c |
| + usd += int64(math.Round(a.CostUSD * 100)) |
| 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) }) |
| + row.Cost = opBillingMoney(&v.Figures, "reason."+string(g.Group)+".cost", in.Gate, opBillingCostUse, in.Platform, |
| + cents, usdNative(usd)) |
| if row.Cost.Shown { |
| row.Biggest = biggest |
| } |
| v.Reasons = append(v.Reasons, row) |
| } |
| - var all int64 |
| + var all, allUSD int64 |
| for _, sqid := range slices.Sorted(maps.Keys(in.CostUSD)) { |
| all += usdCents(in.Rates, in.CostUSD[sqid]) |
| + allUSD += int64(math.Round(in.CostUSD[sqid] * 100)) |
| } |
| 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) })}) |
| + Cost: opBillingMoney(&v.Figures, "reason.shared.cost", in.Gate, sharedUse, in.Platform, |
| + platform.Cents-all, usdNative(platform.USD-allUSD))}) |
| v.ReasonWhys = opBillingWhys(v.Figures[start:]) |
| } |
diff --git a/internal/console/opbilling_store.go b/internal/console/opbilling_store.go| index 465423afe..b9293fae8 100644 |
| --- a/internal/console/opbilling_store.go |
| +++ b/internal/console/opbilling_store.go |
| @@ -31,11 +31,13 @@ func (s *Store) BillingFunnel(now time.Time) (signedUp, withApp, active30 int, e |
| 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) { |
| +// NearestCaps is, per account, the cap closest to its limit at now. The |
| +// contract: only the five labelled caps (usageCaps, the caps the usage |
| +// summary names and that have approved labels); only rows of the current |
| +// period (Period == capPeriod(cap, now), as the usage summary counts them); |
| +// among rows with cap_limit > 0, the highest used / cap_limit; ties go to |
| +// the cap first in usageCaps. An account with no such row is absent. |
| +func (s *Store) NearestCaps(now time.Time) (map[int64]capState, error) { |
| caps := make([]string, len(usageCaps)) |
| args := make([]any, len(usageCaps)) |
| for i, c := range usageCaps { |
| @@ -59,6 +61,9 @@ func (s *Store) NearestCaps() (map[int64]capState, error) { |
| return nil, err |
| } |
| st.UpdatedAt = timeOrZero(updated) |
| + if st.Period != capPeriod(st.Cap, now) { |
| + continue |
| + } |
| cur, ok := out[st.AccountID] |
| if !ok || capNearer(st, cur, rank) { |
| out[st.AccountID] = st |
diff --git a/internal/console/opbilling_store_test.go b/internal/console/opbilling_store_test.go| index 1561d36ed..978d847e9 100644 |
| --- a/internal/console/opbilling_store_test.go |
| +++ b/internal/console/opbilling_store_test.go |
| @@ -99,7 +99,8 @@ func TestNearestCaps(t *testing.T) { |
| 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 { |
| + if err := st.PutCapState(capState{AccountID: account, Cap: c, Period: capPeriod(c, now), Level: levelOK, |
| + Used: used, Limit: limit, UpdatedAt: now}); err != nil { |
| t.Fatal(err) |
| } |
| } |
| @@ -114,7 +115,13 @@ func TestNearestCaps(t *testing.T) { |
| put(ids["nac"], capEmail, 5, 10) |
| put(ids["nac"], capRunningThings, 1, 2) |
| - got, err := st.NearestCaps() |
| + // naa: last month's bandwidth row, over its limit, is a stale period |
| + // and does not count; nor does yesterday's email row. |
| + if err := st.PutCapState(capState{AccountID: ids["naa"], Cap: capEmail, Period: "2026-11-08", Level: levelOver, |
| + Used: 50, Limit: 10, UpdatedAt: now.Add(-24 * time.Hour)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := st.NearestCaps(now) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -132,4 +139,17 @@ func TestNearestCaps(t *testing.T) { |
| if s := got[ids["naa"]]; s.Used != 8_000_000_000 || s.Limit != 10_000_000_000 { |
| t.Errorf("naa = %+v", s) |
| } |
| + // A month later every row above is a past period but running things |
| + // and storage, which have none. |
| + later, err := st.NearestCaps(now.AddDate(0, 1, 0)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + pick = map[int64]capID{} |
| + for id, s := range later { |
| + pick[id] = s.Cap |
| + } |
| + if want := map[int64]capID{ids["naa"]: capRunningThings, ids["nab"]: capStorage, ids["nac"]: capRunningThings}; !reflect.DeepEqual(pick, want) { |
| + t.Errorf("a month later: nearest = %v, want %v", pick, want) |
| + } |
| } |
diff --git a/internal/console/opbilling_test.go b/internal/console/opbilling_test.go| index 3e87fe0ab..1e0001053 100644 |
| --- a/internal/console/opbilling_test.go |
| +++ b/internal/console/opbilling_test.go |
| @@ -127,7 +127,8 @@ func (w overviewWorld) input(in moneyInputs) opBillingInput { |
| gate := in |
| gate.PlatformOK = map[string]bool{} |
| for _, m := range overviewMonths { |
| - pc := platformCost{Basis: "account", Label: costLabelAccount, OK: true} |
| + // The bill is in dollars: w.platform euro cents at 1.12. |
| + pc := platformCost{Basis: "account", Label: costLabelAccount, OK: true, USD: w.platform * 112 / 100} |
| if cents, ok := r.eurCents(w.platform, "eur"); ok { |
| pc.Cents = cents |
| } |
| @@ -162,7 +163,7 @@ func (w overviewWorld) input(in moneyInputs) opBillingInput { |
| 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, |
| + Months: moneyByMonth(w.payments, overviewMonths, r, platform), Payments: w.payments, 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, |
| } |
| @@ -371,6 +372,18 @@ func overviewMixed() overviewWorld { |
| } |
| return 2400 |
| }) |
| + // Each day's ARR in its own currencies, converted at that day's rates: |
| + // 3 November's at 2 November's. |
| + for i := range w.snaps { |
| + s := &w.snaps[i] |
| + s.ARR, s.RateDay = map[string]int64{"eur": 2400}, "2026-11-02" |
| + if s.Day >= "2026-11-03" { |
| + s.ARR["usd"] = 2800 |
| + } |
| + if s.Day >= "2026-11-06" { |
| + s.RateDay = "2026-11-06" |
| + } |
| + } |
| 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}) |
| @@ -742,3 +755,70 @@ func TestOverviewMoneyIncludesFeeRows(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// TestOverviewNativeAmounts: every converted total shows its amounts in |
| +// their own currencies beside it, built in the same format function; a |
| +// total that converted nothing shows none; per-account cells show none; |
| +// ARR points carry their own day's rates. |
| +func TestOverviewNativeAmounts(t *testing.T) { |
| + v := buildOpBillingView(overviewMixed().input(overviewGood())) |
| + rate := fmt.Sprintf(billCopyRateNote, "6 Nov 2026") |
| + for _, tc := range []struct { |
| + name, got, want string |
| + }{ |
| + {"ARR note", v.Tiles[0].Note, fmt.Sprintf(billCopyARRNote, "€24.00, $28.00") + ", " + rate}, |
| + {"MRR note", v.Tiles[1].Note, billCopyMRRNote + " (€2.00, $2.33), " + rate}, |
| + {"received note", v.Tiles[2].Note, billCopyReceivedNote + " (−€0.45, $26.90), " + rate}, |
| + {"earned recurring", v.Earned[0].Value.Native, "€0.60, $0.70"}, |
| + {"earned aws", v.Earned[3].Value.Native, "$560.00"}, |
| + {"earned profit", v.Earned[4].Value.Native, "€0.60, −$559.30"}, |
| + {"November subscriptions", v.Months[0].Subscriptions.Native, "$28.00"}, |
| + {"November net", v.Months[0].Net.Native, "−€0.45, $26.90"}, |
| + {"November cash", v.Months[0].Cash.Native, "−€0.45, −$533.10"}, |
| + {"October once-off", v.Months[1].OnceOff.Native, "£10.00"}, |
| + {"October tax", v.Months[1].Tax.Native, "£2.00"}, |
| + {"September subscriptions (eur only)", v.Months[2].Subscriptions.Native, ""}, |
| + {"September net (eur only)", v.Months[2].Net.Native, ""}, |
| + {"free cost", v.Reasons[0].Cost.Native, "$1.12"}, |
| + {"shared and idle", v.Reasons[4].Cost.Native, "$542.64"}, |
| + {"paying costs (per account)", v.Paying[0].Costs.Native, ""}, |
| + {"limits cost (per account)", v.NearLimits[0].Cost.Native, ""}, |
| + } { |
| + if tc.got != tc.want { |
| + t.Errorf("%s = %q, want %q", tc.name, tc.got, tc.want) |
| + } |
| + } |
| + points := map[string]opBillingARRDay{} |
| + for _, d := range v.ARR { |
| + points[d.Day.Format(snapshotDayFormat)] = d |
| + } |
| + if p := points["2026-11-03"]; p.Value.Native != "€24.00, $28.00" || p.RateNote != fmt.Sprintf(billCopyRateNote, "2 Nov 2026") { |
| + t.Errorf("3 November: %q, %q", p.Value.Native, p.RateNote) |
| + } |
| + if p := points["2026-10-15"]; p.Value.Native != "" || p.RateNote != "" { |
| + t.Errorf("15 October (eur only): %q, %q", p.Value.Native, p.RateNote) |
| + } |
| + |
| + fx := newConsoleFixture(t) |
| + enableBilling(t, fx.srv) |
| + body := html.UnescapeString(renderOverview(t, fx, v)) |
| + for _, want := range []string{ |
| + "<td>3 Nov</td><td>€49.00 (€24.00, $28.00), estimated at ECB rates of 2 Nov 2026</td>", |
| + "<td>15 Oct</td><td>€24.00</td>", |
| + } { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("page lacks %q", want) |
| + } |
| + } |
| + for _, f := range []opMoneyFigure{v.Months[1].OnceOff, v.Months[0].Net, v.Reasons[4].Cost, v.Earned[3].Value} { |
| + if want := f.Text + "<small co-sub>" + f.Native + "</small>"; !strings.Contains(body, want) { |
| + t.Errorf("page lacks %q", want) |
| + } |
| + } |
| + if want := v.Months[2].Subscriptions.Text + "</span>"; !strings.Contains(body, "<span co-num>"+want) { |
| + t.Errorf("September's eur subscriptions carry a breakdown") |
| + } |
| + if !strings.Contains(body, v.Tiles[1].Note) || !strings.Contains(body, v.Tiles[2].Note) { |
| + t.Error("tile notes missing from the page") |
| + } |
| +} |
diff --git a/internal/console/templates/ops_billing.html b/internal/console/templates/ops_billing.html| index 93e04670d..e2a095305 100644 |
| --- a/internal/console/templates/ops_billing.html |
| +++ b/internal/console/templates/ops_billing.html |
| @@ -24,7 +24,7 @@ |
| <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> |
| + <tr><td>{{.Day.Format "2 Jan"}}</td><td>{{.Value.Text}}{{with .Value.Native}} ({{.}}){{end}}{{with .RateNote}}, {{.}}{{end}}</td></tr> |
| {{- end}} |
| </table> |
| </div> |
| @@ -138,10 +138,11 @@ |
| {{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 |
| +{{/* op_bill_fig is one money cell: the figure (with its amounts in their |
| + own currencies under it when it converted any), 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}} |
| +{{define "op_bill_fig"}}{{if .Shown}}<span co-num>{{.Text}}{{with .Native}}<small co-sub>{{.}}</small>{{end}}</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}} |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 810a77601..333f6d525 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -7,6 +7,9 @@ route /fleet/alerts/connectors/{id}/test |
| route /fleet/alerts/rules/{rule} |
| route /fleet/architecture |
| route /fleet/architecture/refresh |
| +route /fleet/billing |
| +route /fleet/billing/accounts |
| +route /fleet/billing/payments |
| route /fleet/economics/bill |
| route /fleet/economics/scenarios |
| route /fleet/economics/tier |