console: billing pages final review fixes
- Not paying, by reason: each group's count goes through opMoney, declaring the facts and the payments like the tab counts, so a stale read refuses it instead of printing counts. - Zero-decimal currencies: the CLI's list moves to internal/minorunits; eurCents converts whole units and minorText prints none (1,200 JPY). - One per-row conversion (paymentRowEUR): the money table and the payments list net the same euros for the same payment. - econComplete takes the month: a cached "last" view of another month is incomplete, so costs are refused, never wrong. - opBillingMoney sets Native on the inventory copy too. - Test: an operator's POST with billing on draws the missing-route 404.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+299
−88
billing_cli.go+5 −10internal/console/billingrates.go+11 −5internal/console/billingrates_test.go+9 −0internal/console/economicspass_test.go+5 −1internal/console/opbilling.go+17 −13internal/console/opbilling_money.go+69 −35internal/console/opbilling_money_test.go+82 −5internal/console/opbilling_overview.go+14 −8internal/console/opbilling_test.go+56 −10internal/console/templates/ops_billing.html+1 −1internal/minorunits/minorunits.go+19 −0internal/minorunits/minorunits_test.go+11 −0
diff --git a/billing_cli.go b/billing_cli.go| index 89d4194de..639487b91 100644 |
| --- a/billing_cli.go |
| +++ b/billing_cli.go |
| @@ -23,6 +23,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/clireg" |
| + "github.com/carlosframework/platform/internal/minorunits" |
| ) |
| // billingProblemReply mirrors the console door's wire shape. |
| @@ -458,16 +459,9 @@ func printBillingPayments(w io.Writer, list []billingPaymentReply) { |
| // currency; any other prints its code in capitals and a space. |
| var currencySymbols = map[string]string{"eur": "€", "usd": "$", "gbp": "£"} |
| -// zeroDecimalCurrencies are the currencies whose minor unit is the whole |
| -// unit (Stripe's zero-decimal list): 1200 jpy is ¥1,200, not 12.00. |
| -var zeroDecimalCurrencies = map[string]bool{ |
| - "bif": true, "clp": true, "djf": true, "gnf": true, "jpy": true, "kmf": true, "krw": true, "mga": true, |
| - "pyg": true, "rwf": true, "ugx": true, "vnd": true, "vuv": true, "xaf": true, "xof": true, "xpf": true, |
| -} |
| - |
| // formatMinor formats minor units of currency, with a comma between |
| // thousands: two decimals (€2,400.00, -$12.00), or none for a |
| -// zero-decimal currency (JPY 1,200). |
| +// zero-decimal currency (JPY 1,200; minorunits.ZeroDecimal). |
| func formatMinor(minor int64, currency string) string { |
| sign := "" |
| u := uint64(minor) |
| @@ -476,7 +470,8 @@ func formatMinor(minor int64, currency string) string { |
| } |
| cur := strings.ToLower(currency) |
| whole, cents := u, uint64(0) |
| - if !zeroDecimalCurrencies[cur] { |
| + zero := minorunits.ZeroDecimal(cur) |
| + if !zero { |
| whole, cents = u/100, u%100 |
| } |
| digits := strconv.FormatUint(whole, 10) |
| @@ -491,7 +486,7 @@ func formatMinor(minor int64, currency string) string { |
| if !ok { |
| symbol = strings.ToUpper(currency) + " " |
| } |
| - if zeroDecimalCurrencies[cur] { |
| + if zero { |
| return sign + symbol + b.String() |
| } |
| return fmt.Sprintf("%s%s%s.%02d", sign, symbol, b.String(), cents) |
diff --git a/internal/console/billingrates.go b/internal/console/billingrates.go| index 30c0fdcef..c903092d8 100644 |
| --- a/internal/console/billingrates.go |
| +++ b/internal/console/billingrates.go |
| @@ -9,6 +9,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/fxrate" |
| + "github.com/carlosframework/platform/internal/minorunits" |
| ) |
| // billingRatesEvery is how old the newest stored euro rates must be before |
| @@ -25,10 +26,11 @@ type eurRates struct { |
| } |
| // eurCents converts minor units of currency to euro cents: euros are |
| -// themselves, another currency is divided by its rate, rounded. Every |
| -// selling currency has two decimals, so minor units convert to cents |
| -// directly. False when the currency has no rate, or the result is not a |
| -// finite number within int64. |
| +// themselves, another currency is divided by its rate, rounded. A |
| +// two-decimal currency's minor units convert to cents directly; a |
| +// zero-decimal one's (minorunits.ZeroDecimal: 1200 jpy is ¥1,200) are whole |
| +// units, a hundred cents each. False when the currency has no rate, or the |
| +// result is not a finite number within int64. |
| func (r eurRates) eurCents(minor int64, currency string) (int64, bool) { |
| if currency == "eur" { |
| return minor, true |
| @@ -38,7 +40,11 @@ func (r eurRates) eurCents(minor int64, currency string) (int64, bool) { |
| return 0, false |
| } |
| // float64(math.MaxInt64) is 2^63, itself out of range; -2^63 is in. |
| - q := math.Round(float64(minor) / rate) |
| + units := float64(minor) |
| + if minorunits.ZeroDecimal(currency) { |
| + units *= 100 |
| + } |
| + q := math.Round(units / rate) |
| if math.IsNaN(q) || q >= float64(math.MaxInt64) || q < float64(math.MinInt64) { |
| return 0, false |
| } |
diff --git a/internal/console/billingrates_test.go b/internal/console/billingrates_test.go| index b18d261e7..531e269eb 100644 |
| --- a/internal/console/billingrates_test.go |
| +++ b/internal/console/billingrates_test.go |
| @@ -44,6 +44,15 @@ func TestEURCents(t *testing.T) { |
| if got, ok := r.eurCents(2400, "eur"); !ok || got != 2400 { |
| t.Errorf("eurCents(2400, eur) = %d, %v; want 2400, true", got, ok) |
| } |
| + // A zero-decimal currency's minor unit is its whole unit: ¥1,200 at |
| + // 160 per euro is €7.50, and a refund converts the same way. |
| + r.PerEUR["jpy"] = 160 |
| + if got, ok := r.eurCents(1200, "jpy"); !ok || got != 750 { |
| + t.Errorf("eurCents(1200, jpy) = %d, %v; want 750, true", got, ok) |
| + } |
| + if got, ok := r.eurCents(-400, "jpy"); !ok || got != -250 { |
| + t.Errorf("eurCents(-400, jpy) = %d, %v; want -250, true", got, ok) |
| + } |
| if got, ok := r.eurCents(2400, "chf"); ok { |
| t.Errorf("eurCents(2400, chf) = %d, true; want false", got) |
| } |
diff --git a/internal/console/economicspass_test.go b/internal/console/economicspass_test.go| index 0bae88f6f..1be094233 100644 |
| --- a/internal/console/economicspass_test.go |
| +++ b/internal/console/economicspass_test.go |
| @@ -807,7 +807,11 @@ func TestSweepUsageCountsReadFailures(t *testing.T) { |
| if view.ReadFailures != 1 { |
| t.Errorf("view.ReadFailures = %d, want 1", view.ReadFailures) |
| } |
| - if econComplete(view, nil) { |
| + // Read as the billing pages' "last" view of its month, so only the |
| + // read failure can make it incomplete. |
| + last := *view |
| + last.Period = "last" |
| + if econComplete(&last, nil, lastCompleteMonth(last.GeneratedAt)) { |
| t.Error("econComplete = true for a view with a read failure") |
| } |
| } |
diff --git a/internal/console/opbilling.go b/internal/console/opbilling.go| index 8989e950e..4132f6dcb 100644 |
| --- a/internal/console/opbilling.go |
| +++ b/internal/console/opbilling.go |
| @@ -357,7 +357,8 @@ func opBillingPaymentsHref(q url.Values, month, kind string, n int) string { |
| // month or an unknown kind is all. Each row's words are the overview's |
| // (opBillingPaymentRowOf); charged is what the customer was charged, in |
| // its own currency, and declares the payments only; net (Settled − |
| -// SettledTax − Fee, refunds and reversals alike) and fee are in euros and |
| +// SettledTax − Fee, refunds and reversals alike) and fee are in euros as |
| +// paymentRowEUR converts them (as the overview's money table does), and |
| // declare the payments and, for a currency other than euros, its rate. |
| // The month filter offers this month and the eleven before it, and the |
| // chosen month when older. Pure. |
| @@ -415,8 +416,9 @@ func buildOpBillingPayments(rows []paymentRow, facts []billingFact, total int, i |
| row := opBillingPaymentRowOf(p, byID) |
| row.Charged = opMoney(&v.Figures, name+".charged", in, moneyUse{Inputs: inPayments}, nil, |
| func() string { return minorText(p.Amount, p.Currency) }) |
| - row.Net = opBillingPaymentEUR(&v.Figures, name+".net", in, euros, r, p.Settled-p.SettledTax-p.Fee, cur) |
| - row.Fee = opBillingPaymentEUR(&v.Figures, name+".fee", in, euros, r, p.Fee, cur) |
| + e := paymentRowEUR(r, p) |
| + row.Net = opBillingPaymentEUR(&v.Figures, name+".net", in, euros, e.Net(), p.Settled-p.SettledTax-p.Fee, cur) |
| + row.Fee = opBillingPaymentEUR(&v.Figures, name+".fee", in, euros, e.Fee, p.Fee, cur) |
| converted = converted || cur != "eur" |
| v.Rows = append(v.Rows, row) |
| } |
| @@ -427,18 +429,19 @@ func buildOpBillingPayments(rows []paymentRow, facts []billingFact, total int, i |
| return v |
| } |
| -// opBillingPaymentEUR is one payment's settled amount (minor units of |
| -// currency, lower case) in euros through opMoney. A currency other than |
| -// eur carries the amount as recorded in Native, built in the same format |
| -// function and set on both the returned figure and its copy in *figs; an |
| -// eur amount converted nothing and has none. |
| -func opBillingPaymentEUR(figs *[]opMoneyFigure, name string, in moneyInputs, u moneyUse, r eurRates, minor int64, currency string) opMoneyFigure { |
| +// opBillingPaymentEUR is one payment's settled amount through opMoney: |
| +// cents as paymentRowEUR converted it, minor the same amount as it settled |
| +// (minor units of currency, lower case). A currency other than eur carries |
| +// minor in Native, built in the same format function and set on both the |
| +// returned figure and its copy in *figs; an eur amount converted nothing |
| +// and has none. |
| +func opBillingPaymentEUR(figs *[]opMoneyFigure, name string, in moneyInputs, u moneyUse, cents, minor int64, currency string) opMoneyFigure { |
| var nat string |
| f := opMoney(figs, name, in, u, nil, func() string { |
| if currency != "eur" { |
| nat = minorText(minor, currency) |
| } |
| - return eurText(settledEUR(r, minor, currency)) |
| + return eurText(cents) |
| }) |
| f.Native = nat |
| (*figs)[len(*figs)-1].Native = nat |
| @@ -541,8 +544,9 @@ func (s *Server) opBillingInputs(ctx context.Context, now time.Time) (opBillingI |
| // "": 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. |
| +// econComplete decides whether costs show, and only a view of |
| +// in.LastMonth can) 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 { |
| @@ -571,7 +575,7 @@ func (s *Server) opBillingAccountInputs(ctx context.Context, now, snapsFrom time |
| if econErr != nil { |
| log.Printf("console: billing: economics: %v", econErr) |
| } |
| - in.Gate.EconomicsComplete = econComplete(econ, econErr) |
| + in.Gate.EconomicsComplete = econComplete(econ, econErr, in.LastMonth) |
| in.CostUSD = map[string]float64{} |
| if econ != nil { |
| for _, a := range econ.Accounts { |
diff --git a/internal/console/opbilling_money.go b/internal/console/opbilling_money.go| index 1e5335238..b63175188 100644 |
| --- a/internal/console/opbilling_money.go |
| +++ b/internal/console/opbilling_money.go |
| @@ -11,6 +11,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/minorunits" |
| ) |
| // The money behind the Billing pages (billing dashboard plan 2, Task 3): |
| @@ -19,13 +20,15 @@ import ( |
| // it, and the sums the pages are built from. The sums here never decide |
| // whether they may be shown; the gate does. |
| -// econComplete is whether an Economics read can stand behind a cost: it |
| -// read without error, with no degraded sweep, no fallback scenario, no |
| -// usage day it failed to read, and every day of its period covered. It is |
| -// moneyInputs.EconomicsComplete. |
| -func econComplete(v *EconomicsView, err error) bool { |
| - return err == nil && v != nil && v.Warning == "" && v.ScenarioWarning == "" && |
| - v.ReadFailures == 0 && v.CoveredDays == v.PeriodDays |
| +// econComplete is whether an Economics read can stand behind a cost for |
| +// month ("2006-01"): it read without error, is a "last" view of that month |
| +// (built in the month after it: a cached view from before the month turned |
| +// is the month before, so incomplete rather than wrong), with no degraded |
| +// sweep, no fallback scenario, no usage day it failed to read, and every |
| +// day of its period covered. It is moneyInputs.EconomicsComplete. |
| +func econComplete(v *EconomicsView, err error, month string) bool { |
| + return err == nil && v != nil && v.Period == "last" && lastCompleteMonth(v.GeneratedAt) == month && |
| + v.Warning == "" && v.ScenarioWarning == "" && v.ReadFailures == 0 && v.CoveredDays == v.PeriodDays |
| } |
| // platformCost is one month's platform cost as the Billing pages may show it. |
| @@ -149,36 +152,44 @@ func lastCompleteMonth(now time.Time) string { |
| // eurText is euro cents as the pages show them: €24.00, €1,200.00, |
| // −€188.00 (U+2212, as dashDelta). Called only inside opMoney's format |
| // functions; never a template func. |
| -func eurText(cents int64) string { return moneyText(cents, "€", "") } |
| +func eurText(cents int64) string { return moneyText(cents, "€", "", false) } |
| // minorText is an amount in a currency's minor units: $28.00, £22.00, |
| -// €24.00, any other currency as 28.00 XYZ. Called only inside opMoney's |
| -// format functions; never a template func. |
| +// €24.00, any other currency as 28.00 XYZ, and a zero-decimal currency |
| +// (minorunits.ZeroDecimal) in whole units, 1,200 JPY. Called only inside |
| +// opMoney's format functions; never a template func. |
| func minorText(minor int64, currency string) string { |
| switch c := strings.ToLower(currency); c { |
| case "usd": |
| - return moneyText(minor, "$", "") |
| + return moneyText(minor, "$", "", false) |
| case "gbp": |
| - return moneyText(minor, "£", "") |
| + return moneyText(minor, "£", "", false) |
| case "eur": |
| - return moneyText(minor, "€", "") |
| + return moneyText(minor, "€", "", false) |
| default: |
| - return moneyText(minor, "", " "+strings.ToUpper(c)) |
| + return moneyText(minor, "", " "+strings.ToUpper(c), minorunits.ZeroDecimal(c)) |
| } |
| } |
| -// moneyText is minor units with two decimals, thousands with commas, a |
| -// U+2212 minus before the symbol. |
| -func moneyText(minor int64, symbol, suffix string) string { |
| +// moneyText is minor units with two decimals (whole units, none, when |
| +// zeroDecimal), thousands with commas, a U+2212 minus before the symbol. |
| +func moneyText(minor int64, symbol, suffix string, zeroDecimal bool) string { |
| sign, u := "", uint64(minor) |
| if minor < 0 { |
| sign, u = "−", -uint64(minor) |
| } |
| - whole := strconv.FormatUint(u/100, 10) |
| + units, cents := u/100, u%100 |
| + if zeroDecimal { |
| + units = u |
| + } |
| + whole := strconv.FormatUint(units, 10) |
| for i := len(whole) - 3; i > 0; i -= 3 { |
| whole = whole[:i] + "," + whole[i:] |
| } |
| - return fmt.Sprintf("%s%s%s.%02d%s", sign, symbol, whole, u%100, suffix) |
| + if zeroDecimal { |
| + return sign + symbol + whole + suffix |
| + } |
| + return fmt.Sprintf("%s%s%s.%02d%s", sign, symbol, whole, cents, suffix) |
| } |
| // divRound is n / d rounded half away from zero; d > 0. |
| @@ -210,6 +221,31 @@ func settledEUR(r eurRates, minor int64, currency string) int64 { |
| return cents |
| } |
| +// rowEUR is one payment row in euro cents, each part converted once at r |
| +// from what settled: Revenue is Settled − SettledTax (a fee row has none), |
| +// Tax is SettledTax, Fee is Fee (and a fee row's −Settled). Net is |
| +// Revenue − Fee, in euros. The overview's money table and the payments |
| +// list both convert through paymentRowEUR, so the same payment nets the |
| +// same euros on both pages. |
| +type rowEUR struct{ Revenue, Tax, Fee int64 } |
| + |
| +// Net is the row's revenue after fees, before tax, in euro cents. |
| +func (e rowEUR) Net() int64 { return e.Revenue - e.Fee } |
| + |
| +// paymentRowEUR is p's rowEUR at r; a part whose currency has no rate is 0 |
| +// (a figure using it declares the currency, and the gate refuses it). |
| +func paymentRowEUR(r eurRates, p paymentRow) rowEUR { |
| + cur := strings.ToLower(p.SettledCurrency) |
| + e := rowEUR{Tax: settledEUR(r, p.SettledTax, cur)} |
| + if p.Kind == billing.PaymentFee { |
| + e.Fee = settledEUR(r, p.Fee-p.Settled, cur) |
| + return e |
| + } |
| + e.Revenue = settledEUR(r, p.Settled-p.SettledTax, cur) |
| + e.Fee = settledEUR(r, p.Fee, cur) |
| + return e |
| +} |
| + |
| // moneyMonth is one month of the money record, in euro cents. |
| type moneyMonth struct { |
| Month string // "2006-01" |
| @@ -221,11 +257,12 @@ type moneyMonth struct { |
| // moneyByMonth sums rows (Kind "all": fee rows included) into each of |
| // months, in months' order; a row in no listed month is left out. Sums |
| // only; whether a sum may be shown is the gate's. Each row counts in euros |
| -// from what settled: subscriptions and once-offs add Settled − SettledTax |
| -// to their column, refunds and reversals theirs to Refunds (signed, so tax |
| -// never counts as revenue); every row's SettledTax goes to Tax and its Fee |
| -// to Fees, and a fee row's −Settled to Fees too. Net is revenue after |
| -// refunds and fees, before tax. Currencies are the settled currencies seen. |
| +// as paymentRowEUR converts it: subscriptions and once-offs add Revenue |
| +// (Settled − SettledTax) to their column, refunds and reversals theirs to |
| +// Refunds (signed, so tax never counts as revenue); every row's Tax goes |
| +// to Tax and its Fee (a fee row's −Settled included) to Fees. Net is |
| +// revenue after refunds and fees, before tax: the sum of the rows' Net. |
| +// Currencies are the settled currencies seen. |
| func moneyByMonth(rows []paymentRow, months []string, r eurRates, platform map[string]platformCost) []moneyMonth { |
| out := make([]moneyMonth, len(months)) |
| at := map[string]int{} |
| @@ -241,21 +278,18 @@ func moneyByMonth(rows []paymentRow, months []string, r eurRates, platform map[s |
| continue |
| } |
| m := &out[i] |
| - cur := strings.ToLower(p.SettledCurrency) |
| - seen[i][cur] = true |
| - revenue := settledEUR(r, p.Settled-p.SettledTax, cur) |
| + seen[i][strings.ToLower(p.SettledCurrency)] = true |
| + e := paymentRowEUR(r, p) |
| switch p.Kind { |
| case billing.PaymentSubscription: |
| - m.Subscriptions += revenue |
| + m.Subscriptions += e.Revenue |
| case billing.PaymentOnceOff: |
| - m.OnceOff += revenue |
| + m.OnceOff += e.Revenue |
| case billing.PaymentRefund: |
| - m.Refunds += revenue |
| - case billing.PaymentFee: |
| - m.Fees += settledEUR(r, -p.Settled, cur) |
| + m.Refunds += e.Revenue |
| } |
| - m.Tax += settledEUR(r, p.SettledTax, cur) |
| - m.Fees += settledEUR(r, p.Fee, cur) |
| + m.Tax += e.Tax |
| + m.Fees += e.Fee |
| } |
| for i := range out { |
| m := &out[i] |
| @@ -359,7 +393,7 @@ func accountMoneyRows(facts []billingFact, exemptID int64, earned map[int64]int6 |
| continue |
| } |
| cur := strings.ToLower(p.SettledCurrency) |
| - onceOff[p.AccountID] += settledEUR(r, p.Settled-p.SettledTax, cur) |
| + onceOff[p.AccountID] += paymentRowEUR(r, p).Revenue |
| if currencies[p.AccountID] == nil { |
| currencies[p.AccountID] = map[string]bool{} |
| } |
diff --git a/internal/console/opbilling_money_test.go b/internal/console/opbilling_money_test.go| index 49483f7e4..08033b7f6 100644 |
| --- a/internal/console/opbilling_money_test.go |
| +++ b/internal/console/opbilling_money_test.go |
| @@ -7,6 +7,7 @@ import ( |
| "go/ast" |
| "go/parser" |
| "go/token" |
| + "net/url" |
| "os" |
| "path/filepath" |
| "reflect" |
| @@ -19,8 +20,12 @@ import ( |
| ) |
| func TestEconComplete(t *testing.T) { |
| - good := func() *EconomicsView { return &EconomicsView{CoveredDays: 31, PeriodDays: 31} } |
| - if !econComplete(good(), nil) { |
| + // A "last" view built on 3 November covers October. |
| + built := time.Date(2026, 11, 3, 9, 0, 0, 0, time.UTC) |
| + good := func() *EconomicsView { |
| + return &EconomicsView{Period: "last", GeneratedAt: built, CoveredDays: 31, PeriodDays: 31} |
| + } |
| + if !econComplete(good(), nil, "2026-10") { |
| t.Fatal("a complete view is not complete") |
| } |
| for name, v := range map[string]func(v *EconomicsView){ |
| @@ -28,17 +33,24 @@ func TestEconComplete(t *testing.T) { |
| "scenario warning": func(v *EconomicsView) { v.ScenarioWarning = "bad scenario" }, |
| "read failure": func(v *EconomicsView) { v.ReadFailures = 1 }, |
| "uncovered day": func(v *EconomicsView) { v.CoveredDays = 30 }, |
| + // A cached "last" view from before the month turned is the month |
| + // before: not the month asked for, so not complete. |
| + "previous month": func(v *EconomicsView) { v.GeneratedAt = time.Date(2026, 10, 31, 23, 59, 0, 0, time.UTC) }, |
| + "not last": func(v *EconomicsView) { v.Period = "mtd" }, |
| } { |
| g := good() |
| v(g) |
| - if econComplete(g, nil) { |
| + if econComplete(g, nil, "2026-10") { |
| t.Errorf("%s: complete", name) |
| } |
| } |
| - if econComplete(good(), errors.New("sweep failed")) { |
| + if econComplete(good(), nil, "2026-11") { |
| + t.Error("October's view for November: complete") |
| + } |
| + if econComplete(good(), errors.New("sweep failed"), "2026-10") { |
| t.Error("an error: complete") |
| } |
| - if econComplete(nil, nil) { |
| + if econComplete(nil, nil, "2026-10") { |
| t.Error("no view: complete") |
| } |
| } |
| @@ -76,6 +88,10 @@ func TestMinorText(t *testing.T) { |
| {-2800, "chf", "−28.00 CHF"}, |
| {123456, "usd", "$1,234.56"}, |
| {2800, "USD", "$28.00"}, |
| + // Zero-decimal currencies: the minor unit is the whole unit. |
| + {1200, "jpy", "1,200 JPY"}, |
| + {-1200, "JPY", "−1,200 JPY"}, |
| + {5, "krw", "5 KRW"}, |
| } { |
| if got := minorText(tc.minor, tc.currency); got != tc.want { |
| t.Errorf("minorText(%d, %q) = %q, want %q", tc.minor, tc.currency, got, tc.want) |
| @@ -251,6 +267,67 @@ func TestMoneyByMonthRefundTaxExclusive(t *testing.T) { |
| } |
| } |
| +// TestMoneyByMonthZeroDecimal: a yen-settled charge and its refund |
| +// convert at the yen's scale: ¥1,200 at 160 per euro is €7.50, not €0.08. |
| +func TestMoneyByMonthZeroDecimal(t *testing.T) { |
| + at := time.Date(2026, 10, 4, 0, 0, 0, 0, time.UTC) |
| + rows := []paymentRow{ |
| + pay(billing.PaymentOnceOff, billing.ReasonOther, at, 1200, 0, 48, "jpy"), |
| + pay(billing.PaymentRefund, billing.ReasonOther, at.Add(time.Hour), -400, 0, 0, "jpy"), |
| + } |
| + r := eurRates{Day: "2026-11-06", PerEUR: map[string]float64{"jpy": 160}} |
| + got := moneyByMonth(rows, []string{"2026-10"}, r, nil)[0] |
| + if got.OnceOff != 750 || got.Refunds != -250 || got.Fees != 30 || got.Net != 750-250-30 { |
| + t.Errorf("yen month: %+v", got) |
| + } |
| +} |
| + |
| +// TestPaymentRowEURAgreesAcrossPages: the overview's money table and the |
| +// payments list convert a row the same way, so the same payment nets the |
| +// same euros on both. $1.00 settled with $0.03 of fees at 1.12: revenue |
| +// €0.89, fee €0.03, net €0.86 on both pages (converting the $0.97 net |
| +// once would give €0.87). |
| +func TestPaymentRowEURAgreesAcrossPages(t *testing.T) { |
| + p := pay(billing.PaymentOnceOff, billing.ReasonOther, time.Date(2026, 11, 5, 10, 0, 0, 0, time.UTC), 100, 0, 3, "usd") |
| + p.AccountID = 2 |
| + in := goodMoneyInputs(time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)) |
| + in.Rates = eurRates{Day: "2026-11-06", FetchedAt: in.Rates.FetchedAt, PerEUR: map[string]float64{"usd": 1.12}} |
| + m := moneyByMonth([]paymentRow{p}, []string{"2026-11"}, in.Rates, nil)[0] |
| + if m.OnceOff != 89 || m.Fees != 3 || m.Net != 86 { |
| + t.Fatalf("overview month: %+v", m) |
| + } |
| + v := buildOpBillingPayments([]paymentRow{p}, nil, 1, in, in.Rates, "", "", 1, url.Values{}) |
| + if len(v.Rows) != 1 { |
| + t.Fatalf("%d payment rows", len(v.Rows)) |
| + } |
| + if got := v.Rows[0]; got.Net.Text != eurText(m.Net) || got.Fee.Text != eurText(m.Fees) { |
| + t.Errorf("payments row net %q fee %q; overview net %s fee %s", got.Net.Text, got.Fee.Text, eurText(m.Net), eurText(m.Fees)) |
| + } |
| + // A yen row agrees too, and shows its native amounts at the yen's scale. |
| + y := pay(billing.PaymentOnceOff, billing.ReasonOther, time.Date(2026, 11, 6, 10, 0, 0, 0, time.UTC), 1200, 0, 48, "jpy") |
| + y.Amount = 1200 |
| + in.Rates.PerEUR["jpy"] = 160 |
| + ym := moneyByMonth([]paymentRow{y}, []string{"2026-11"}, in.Rates, nil)[0] |
| + yv := buildOpBillingPayments([]paymentRow{y}, nil, 1, in, in.Rates, "", "", 1, url.Values{}) |
| + row := yv.Rows[0] |
| + if row.Charged.Text != "1,200 JPY" || row.Net.Text != eurText(ym.Net) || row.Net.Text != "€7.20" || |
| + row.Fee.Text != "€0.30" || row.Net.Native != "1,152 JPY" || row.Fee.Native != "48 JPY" { |
| + t.Errorf("yen row: charged %q net %q (%q) fee %q (%q); overview net %s", |
| + row.Charged.Text, row.Net.Text, row.Net.Native, row.Fee.Text, row.Fee.Native, eurText(ym.Net)) |
| + } |
| +} |
| + |
| +// TestOpBillingMoneyInventoryNative: the inventory copy of a converted |
| +// total carries its native breakdown, as the returned figure does. |
| +func TestOpBillingMoneyInventoryNative(t *testing.T) { |
| + in := goodMoneyInputs(time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)) |
| + var figs []opMoneyFigure |
| + f := opBillingMoney(&figs, "x", in, moneyUse{Inputs: inPayments}, nil, 2500, nativeAmounts{"usd": 2800}) |
| + if f.Native != "$28.00" || len(figs) != 1 || figs[0].Native != f.Native { |
| + t.Errorf("returned native %q, inventory %+v", f.Native, figs) |
| + } |
| +} |
| + |
| func TestEarnedSoFar(t *testing.T) { |
| now := time.Date(2026, 11, 9, 15, 0, 0, 0, time.UTC) |
| m := moneyMonth{Month: "2026-11", OnceOff: 500, Refunds: -100, Platform: platformCost{Cents: 300, OK: true}} |
diff --git a/internal/console/opbilling_overview.go b/internal/console/opbilling_overview.go| index 8052e6b14..7bb3b7f57 100644 |
| --- a/internal/console/opbilling_overview.go |
| +++ b/internal/console/opbilling_overview.go |
| @@ -83,11 +83,11 @@ type opBillingPaymentRow struct { |
| } |
| // opBillingReasonRow is one row of not paying, by reason. Shared and idle |
| -// has no Href and no count. |
| +// has no Href and no count. Count is gated like the paying tile: the |
| +// groups come from the facts and the payments. |
| type opBillingReasonRow struct { |
| Href, Label string |
| - Count int |
| - Cost opMoneyFigure |
| + Count, Cost opMoneyFigure |
| Biggest string |
| } |
| @@ -367,7 +367,8 @@ func nativeText(n nativeAmounts, minor func(int64, string) string) string { |
| } |
| // opBillingMoney is a euro total through opMoney with its breakdown in |
| -// native currencies (Native) built in the same format function. |
| +// native currencies (Native) built in the same format function and set on |
| +// both the returned figure and its copy in *figs. |
| 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 { |
| @@ -375,6 +376,7 @@ func opBillingMoney(figs *[]opMoneyFigure, name string, in moneyInputs, u moneyU |
| return eurText(cents) |
| }) |
| f.Native = nat |
| + (*figs)[len(*figs)-1].Native = nat |
| return f |
| } |
| @@ -892,9 +894,10 @@ var opBillingReasonGroups = []struct { |
| {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. |
| +// opBillingReasons is not paying, by reason: each group's count (the facts |
| +// and the payments, as the accounts page's tab counts), 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)) |
| @@ -902,11 +905,12 @@ func opBillingReasons(v *opBillingView, in opBillingInput, rows []accountMoney) |
| row := opBillingReasonRow{Href: "/fleet/billing/accounts?tab=" + string(g.Group), Label: g.Label} |
| var cents, usd, top int64 |
| var biggest string |
| + count := 0 |
| for _, a := range rows { |
| if a.Group != g.Group { |
| continue |
| } |
| - row.Count++ |
| + count++ |
| if !a.HasCost { |
| continue |
| } |
| @@ -917,6 +921,8 @@ func opBillingReasons(v *opBillingView, in opBillingInput, rows []accountMoney) |
| top, biggest = c, a.Fact.Name |
| } |
| } |
| + row.Count = opMoney(&v.Figures, "reason."+string(g.Group)+".count", in.Gate, moneyUse{Inputs: inFacts | inPayments}, in.Platform, |
| + func() string { return opNumber(count) }) |
| row.Cost = opBillingMoney(&v.Figures, "reason."+string(g.Group)+".cost", in.Gate, opBillingCostUse, in.Platform, |
| cents, usdNative(usd)) |
| if row.Cost.Shown { |
diff --git a/internal/console/opbilling_test.go b/internal/console/opbilling_test.go| index d9c1e0c59..1bf25d04c 100644 |
| --- a/internal/console/opbilling_test.go |
| +++ b/internal/console/opbilling_test.go |
| @@ -65,6 +65,24 @@ func TestBillingRoutesOperatorOnly(t *testing.T) { |
| assertBillingRoutesMissing(t, fx, newBrowser(t), "signed out, billing on") |
| } |
| +// TestBillingRoutesPostHiddenForOperator: an operator's POST on a billing |
| +// console draws exactly the missing-route 404, never a 405 that would show |
| +// the route exists. |
| +func TestBillingRoutesPostHiddenForOperator(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + enableBilling(t, fx.srv) |
| + c := signInOperator(t, fx) |
| + ghostStatus, ghost := missingRoute(t, fx, c) |
| + for _, r := range opBillingRoutes { |
| + if st, _, _ := get(t, c, fx.ts.URL+r.Path); st != http.StatusOK { |
| + t.Fatalf("sanity: GET %s = %d, want 200", r.Path, st) |
| + } |
| + if st, _, body := postForm(t, c, fx.ts.URL+r.Path, url.Values{}); st != ghostStatus || body != ghost { |
| + t.Errorf("POST %s operator, billing on = %d %q, want the missing-route 404", r.Path, st, body) |
| + } |
| + } |
| +} |
| + |
| func TestBillingRoutesRender(t *testing.T) { |
| fx := newConsoleFixture(t) |
| enableBilling(t, fx.srv) |
| @@ -277,22 +295,21 @@ func TestBuildOpBillingView(t *testing.T) { |
| } |
| } |
| type reason struct { |
| - Label string |
| - Count int |
| - Cost, Bigger string |
| + Label string |
| + Count, Cost, Bigger string |
| } |
| var reasons []reason |
| for _, r := range v.Reasons { |
| - reasons = append(reasons, reason{r.Label, r.Count, r.Cost.Text, r.Biggest}) |
| + reasons = append(reasons, reason{r.Label, r.Count.Text, 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", ""}, |
| + {billCopyReasonFree, "25", "€25.00", "free15"}, |
| + {billCopyReasonSponsored, "10", "€10.00", "free3"}, |
| + {billCopyReasonHouse, "2", "€2.00", "free13"}, |
| + {billCopyReasonOurs, "1", "€10.00", "ops"}, |
| + {billCopyReasonShared, "", "€141.00", ""}, |
| } |
| if !reflect.DeepEqual(reasons, wantReasons) { |
| t.Errorf("reasons:\n got %+v\nwant %+v", reasons, wantReasons) |
| @@ -414,7 +431,8 @@ func overviewFigureNames() []string { |
| } |
| } |
| 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", |
| + "reason.free.count", "reason.free.cost", "reason.sponsored.count", "reason.sponsored.cost", |
| + "reason.house.count", "reason.house.cost", "reason.ours.count", "reason.ours.cost", "reason.shared.cost", |
| "limits.accf.cost") |
| return names |
| } |
| @@ -438,6 +456,34 @@ func TestOverviewGateInvariant(t *testing.T) { |
| }) |
| } |
| +// TestOverviewReasonCountsGated: the reasons table's counts come from the |
| +// facts and the payments, as the paying tile's do, so a stale facts read |
| +// refuses them with the same reason instead of printing counts beside a |
| +// tile that says not available yet. |
| +func TestOverviewReasonCountsGated(t *testing.T) { |
| + w := overviewMixed() |
| + stale := overviewGood() |
| + stale.StaleFacts = 1 |
| + v := buildOpBillingView(w.input(stale)) |
| + for _, r := range v.Reasons[:4] { |
| + if want := (moneyUse{Inputs: inFacts | inPayments}); !reflect.DeepEqual(r.Count.Use, want) { |
| + t.Errorf("%s count declares %+v, want %+v", r.Label, r.Count.Use, want) |
| + } |
| + if r.Count.Shown || r.Count.Text != billCopyNotAvailable || r.Count.Reason != billCopyWhyFacts { |
| + t.Errorf("%s count with stale facts = %+v; want refused", r.Label, r.Count) |
| + } |
| + } |
| + if !slices.Contains(v.ReasonWhys, billCopyWhyFacts) { |
| + t.Errorf("reason whys %q lack the facts reason", v.ReasonWhys) |
| + } |
| + body := renderOverview(t, newConsoleFixture(t), v) |
| + want := `<a class="rst-nm" href="/fleet/billing/accounts?tab=free">` + html.EscapeString(billCopyReasonFree) + |
| + `</a><span co-num co-na title="` + html.EscapeString(billCopyWhyFacts) + `">` + html.EscapeString(billCopyNotAvailable) + `</span>` |
| + if !strings.Contains(body, want) { |
| + t.Errorf("free reason row does not read not available; want %q", want) |
| + } |
| +} |
| + |
| // 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 { |
diff --git a/internal/console/templates/ops_billing.html b/internal/console/templates/ops_billing.html| index e2a095305..457660586 100644 |
| --- a/internal/console/templates/ops_billing.html |
| +++ b/internal/console/templates/ops_billing.html |
| @@ -111,7 +111,7 @@ |
| <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> |
| + {{if .Href}}<div rst-lrow co-rowlink><a class="rst-nm" href="{{.Href}}">{{.Label}}</a>{{template "op_bill_fig" .Count}}{{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> |
diff --git a/internal/minorunits/minorunits.go b/internal/minorunits/minorunits.go| new file mode 100644 |
| index 000000000..4d5a64538 |
| --- /dev/null |
| +++ b/internal/minorunits/minorunits.go |
| @@ -0,0 +1,19 @@ |
| +// Package minorunits is how many decimals a currency's amounts carry, |
| +// shared by the CLI and the console: Stripe counts most currencies in |
| +// hundredths and a few in whole units. It imports nothing of the |
| +// platform's, so the CLI can use it without reaching anything else. |
| +package minorunits |
| + |
| +import "strings" |
| + |
| +// zeroDecimalCurrencies are the currencies whose minor unit is the whole |
| +// unit (Stripe's zero-decimal list): 1200 jpy is ¥1,200, not 12.00. |
| +var zeroDecimalCurrencies = map[string]bool{ |
| + "bif": true, "clp": true, "djf": true, "gnf": true, "jpy": true, "kmf": true, "krw": true, "mga": true, |
| + "pyg": true, "rwf": true, "ugx": true, "vnd": true, "vuv": true, "xaf": true, "xof": true, "xpf": true, |
| +} |
| + |
| +// ZeroDecimal reports whether currency (any case) counts its amounts in |
| +// whole units: its minor unit is the unit itself, so an amount of 1200 is |
| +// 1,200, not 12.00. Every other currency has two decimals. |
| +func ZeroDecimal(currency string) bool { return zeroDecimalCurrencies[strings.ToLower(currency)] } |
diff --git a/internal/minorunits/minorunits_test.go b/internal/minorunits/minorunits_test.go| new file mode 100644 |
| index 000000000..79d10471e |
| --- /dev/null |
| +++ b/internal/minorunits/minorunits_test.go |
| @@ -0,0 +1,11 @@ |
| +package minorunits |
| + |
| +import "testing" |
| + |
| +func TestZeroDecimal(t *testing.T) { |
| + for c, want := range map[string]bool{"jpy": true, "JPY": true, "krw": true, "usd": false, "eur": false, "gbp": false, "chf": false, "": false} { |
| + if got := ZeroDecimal(c); got != want { |
| + t.Errorf("ZeroDecimal(%q) = %v, want %v", c, got, want) |
| + } |
| + } |
| +} |