console: the billing page shows current usage beside packs and plan cards, from the plan-limits pass's stored measurements (no new requests); stale periods show as unknown; copy approved by Paul
Squashed from billing-usage into main.
9 files changed,
+671
−20
docs/superpowers/reviews/CODEX-REVIEW-BRIEF-billing-usage.md+29 −0internal/console/billingpage.go+29 −9internal/console/billingpage_copy.go+14 −0internal/console/billingpage_test.go+8 −1internal/console/billingsync_test.go+8 −1internal/console/billingusage.go+197 −0internal/console/billingusage_test.go+338 −0internal/console/templates/billing.html+21 −7internal/console/templates/layout.html+27 −2
CI passed — run details
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-billing-usage.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-billing-usage.md| new file mode 100644 |
| index 000000000..80f6aa5b8 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-billing-usage.md |
| @@ -0,0 +1,29 @@ |
| +# Review brief: branch billing-usage, round 1 of 3 |
| + |
| +Repo carlos/platform, branch `billing-usage`, the commit that adds this brief (named in your prompt). |
| +Under review: the diff `origin/main...HEAD`: the console billing page shows the account's current usage beside the pack rows and plan cards, read from the plan-limits pass's stored measurements (`plan_cap_state`), with a "Usage as of" line. Copy approved by Paul on 2026-10-30. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- The design and the approved copy. |
| +- Rule: no new S3, provider or bucket request on a page view (Paul's S3-cost rule). |
| + |
| +## What to check |
| + |
| +1. No new external request on a page view; the only addition is console-database reads. A failing or missing measurement never shows as zero; a stale period (email per UTC day, bandwidth and awake hours per UTC month) shows as unknown. |
| +2. Used vs limit is compared against the right limit: the account's effective limit today (packs and team seats included) for pack rows, each plan's own limit on plan cards; near (>= 80%) and over thresholds are right, including limit zero/unlimited. |
| +3. Members see usage read-only with no forms; nothing leaks another account's rows (the account id comes from the authorised page's account). |
| +4. Existing invariants: currency/prices guard, action order, CSRF on POST forms, success-screen behaviour, billing lints. |
| +5. Contrast of the near/over emphasis in both themes; 390 px layout. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3 with file:line, failure scenario and fix. End with exactly one verdict: **READY**, **READY AFTER FIXES**, or **NOT READY**. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites. |
diff --git a/internal/console/billingpage.go b/internal/console/billingpage.go| index b035c7df6..4357f028e 100644 |
| --- a/internal/console/billingpage.go |
| +++ b/internal/console/billingpage.go |
| @@ -50,6 +50,9 @@ type billingPageInput struct { |
| Problems []string // open problem reasons |
| Retiring, Ready, Owner bool |
| Now time.Time |
| + // Caps is the plan-limits pass's rows for the account (plan_cap_state), |
| + // the usage the page shows (billingusage.go). |
| + Caps []capState |
| } |
| // billingPageState is the page's decision: a billingCopy notice key ("" for |
| @@ -200,9 +203,12 @@ type billingView struct { |
| // it gives the account today. |
| Plan string |
| Facts []string |
| - Includes []string |
| + Includes []billingInclude |
| limits *plans.Limits // the limits Includes lists, nil for none |
| Offers billingOffers |
| + // Usage is the account's use as the plan-limits pass last measured it, |
| + // nil when it has measured nothing this period (addUsage). |
| + Usage *billingUsageView |
| // Success is the screen that replaces the page after a completed |
| // purchase, nil for none (billingSuccessFor). |
| Success *billingSuccess |
| @@ -262,7 +268,15 @@ type billingPlanOption struct { |
| Prices, Totals []billingPrice |
| // Includes is a few of the plan's limits for this account today |
| // (planIncludes). |
| - Includes []string |
| + Includes []billingInclude |
| +} |
| + |
| +// billingInclude is one limit a plan card or the summary lists, and on a |
| +// plan card's apps and instances the account's use beside it (addUsage). |
| +type billingInclude struct { |
| + Text string |
| + Use *billingUse |
| + running bool // the apps and instances line |
| } |
| type billingPackInput struct { |
| @@ -270,6 +284,7 @@ type billingPackInput struct { |
| Label, Adds string // the pack as the page names it, and what one adds |
| Prices []billingPrice // the purchase form's, one per currency it can submit |
| Max, Value int |
| + Use *billingUse // the account's use of the limit the pack raises (addUsage) |
| } |
| type billingCurrencyOption struct { |
| @@ -308,6 +323,9 @@ func (s *Server) billingPageInputFor(acct *Account, role string, now time.Time) |
| if in.Retiring, err = s.store.BillingRetiring(acct.ID, now); err != nil { |
| return in, err |
| } |
| + if in.Caps, err = s.store.CapStates(acct.ID); err != nil { |
| + return in, err |
| + } |
| return in, nil |
| } |
| @@ -448,6 +466,7 @@ func (s *Server) billingViewFor(r *http.Request, in billingPageInput, st billing |
| if v.Offers.Change && b != nil { |
| v.Change = billingChange(cat, book, plan, packs, b.Currency) |
| } |
| + addUsage(v, cat, in.Caps, members, in.Now) |
| if v.Offers.StartOver && in.Intent != nil { |
| ci := in.Intent |
| v.StartOver = []billingField{{"plan", ci.Plan}, {"currency", ci.Currency}} |
| @@ -702,22 +721,23 @@ func billingDate(t time.Time) string { return t.UTC().Format("2 January 2006") } |
| // words `carlos accounts plan` uses: apps and instances, sleeps after, |
| // disk per app, custom domains, and the member cap of a plan that has one |
| // (maxMembers, 0 for none). A limit of 0 is left out. |
| -func planIncludes(l plans.Limits, maxMembers int) []string { |
| - var out []string |
| +func planIncludes(l plans.Limits, maxMembers int) []billingInclude { |
| + var out []billingInclude |
| + add := func(text string) { out = append(out, billingInclude{Text: text}) } |
| if l.RunningThings > 0 { |
| - out = append(out, fmt.Sprintf(billingCopy["limit.running"], billingCount(int64(l.RunningThings)))) |
| + out = append(out, billingInclude{Text: fmt.Sprintf(billingCopy["limit.running"], billingCount(int64(l.RunningThings))), running: true}) |
| } |
| if l.IdleSeconds > 0 { |
| - out = append(out, fmt.Sprintf(billingCopy["limit.idle"], billingDuration(l.IdleSeconds))) |
| + add(fmt.Sprintf(billingCopy["limit.idle"], billingDuration(l.IdleSeconds))) |
| } |
| if l.DiskBytes > 0 { |
| - out = append(out, fmt.Sprintf(billingCopy["limit.disk"], billingBytes(l.DiskBytes))) |
| + add(fmt.Sprintf(billingCopy["limit.disk"], billingBytes(l.DiskBytes))) |
| } |
| if l.CustomDomains { |
| - out = append(out, billingCopy["limit.domains"]) |
| + add(billingCopy["limit.domains"]) |
| } |
| if maxMembers > 0 { |
| - out = append(out, fmt.Sprintf(billingCopy["limit.members"], maxMembers)) |
| + add(fmt.Sprintf(billingCopy["limit.members"], maxMembers)) |
| } |
| return out |
| } |
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go| index be796d5f0..9594d9d13 100644 |
| --- a/internal/console/billingpage_copy.go |
| +++ b/internal/console/billingpage_copy.go |
| @@ -163,4 +163,18 @@ var billingCopy = map[string]string{ |
| "done.packs.title": "Your packs are ready", |
| "done.packs.lede": "Your packs are ready to use on %s.", |
| "done.packs.flash": "Your packs are ready to use.", |
| + |
| + // The account's usage beside the packs and plan cards, from the |
| + // plan-limits pass (2026-10-29). copy approved by Paul 2026-10-30. |
| + "usage.of": "%s of %s used", |
| + "usage.of_today": "%s of %s used today", |
| + "usage.of_month": "%s of %s used this month", |
| + "usage.unknown": "Usage not known yet", |
| + "usage.disk": "Up to %s per app", |
| + "usage.you_use": "You use %s", |
| + "usage.as_of": "Usage as of %s", |
| + "usage.label.running": "Apps and instances", |
| + "usage.label.storage": "Object storage", |
| + "usage.label.email": "Email", |
| + "usage.label.bandwidth": "Bandwidth", |
| } |
diff --git a/internal/console/billingpage_test.go b/internal/console/billingpage_test.go| index 71aa259c5..cd4008699 100644 |
| --- a/internal/console/billingpage_test.go |
| +++ b/internal/console/billingpage_test.go |
| @@ -137,7 +137,14 @@ type billingPageFixture struct { |
| func newBillingPageFixture(t *testing.T) *billingPageFixture { |
| t.Helper() |
| - bf := newBillingFixture(t) |
| + return newBillingPageFixtureWith(t, consoleFixtureOptions{WithKey: true}) |
| +} |
| + |
| +// newBillingPageFixtureWith is newBillingPageFixture over the console |
| +// fixture o describes. |
| +func newBillingPageFixtureWith(t *testing.T, o consoleFixtureOptions) *billingPageFixture { |
| + t.Helper() |
| + bf := newBillingFixtureWith(t, o) |
| bf.srv.billing.ready.Store(true) |
| bf.setUser("owner" + bf.acct.Sqid + "@example.com") |
| c := newBrowser(t) |
diff --git a/internal/console/billingsync_test.go b/internal/console/billingsync_test.go| index a52b1f45f..2c7b1017d 100644 |
| --- a/internal/console/billingsync_test.go |
| +++ b/internal/console/billingsync_test.go |
| @@ -260,7 +260,14 @@ func testPersonalSub(id, customer, sqid, status string, packs map[string]int64) |
| // account bound to customer cus_1. |
| func newBillingFixture(t *testing.T) *billingFixture { |
| t.Helper() |
| - fx := newConsoleFixture(t) |
| + return newBillingFixtureWith(t, consoleFixtureOptions{WithKey: true}) |
| +} |
| + |
| +// newBillingFixtureWith is newBillingFixture over the console fixture o |
| +// describes. |
| +func newBillingFixtureWith(t *testing.T, o consoleFixtureOptions) *billingFixture { |
| + t.Helper() |
| + fx := newConsoleFixtureWith(t, o) |
| fake := enableBilling(t, fx.srv) |
| acct := planAccount(t, fx, 501) |
| if err := fx.st.SetBillingCustomer(acct.ID, "cus_1", billingNow); err != nil { |
diff --git a/internal/console/billingusage.go b/internal/console/billingusage.go| new file mode 100644 |
| index 000000000..4f3f7a949 |
| --- /dev/null |
| +++ b/internal/console/billingusage.go |
| @@ -0,0 +1,197 @@ |
| +package console |
| + |
| +import ( |
| + "fmt" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/plans" |
| +) |
| + |
| +// The billing page's usage (2026-10-29): an owner deciding on packs or an |
| +// upgrade sees what the account uses beside each limit. The figures are |
| +// the plan-limits pass's (plangracepass.go): every hour it measures every |
| +// cap the account's limits offer and stores one plan_cap_state row per |
| +// cap, at every level. The page reads those rows from the console |
| +// database and nothing else: a page view measures nothing and makes no |
| +// bucket or provider request. |
| +// |
| +// A row counts only in its own period: an email row from an earlier UTC |
| +// day, or a bandwidth row from an earlier UTC month, is not this period's |
| +// use, so it shows as not known, never as its old figure or as zero. |
| +// Disk is a per-app limit nothing measures centrally: its limit alone. |
| + |
| +// usageCaps are the caps the page shows, in order: the ones a pack raises. |
| +var usageCaps = []capID{capRunningThings, capStorage, capEmail, capBandwidth} |
| + |
| +// billingUse is a use beside a limit as the page shows it. Level is "" |
| +// below 80% of the limit, "warn" from 80% up to it, "over" past it. |
| +type billingUse struct { |
| + Text, Level string |
| +} |
| + |
| +// billingUsageRow is one line of the summary's usage list. |
| +type billingUsageRow struct { |
| + Label string |
| + Use *billingUse |
| +} |
| + |
| +// billingUsageView is the account's usage on the page. AsOf is the "Usage |
| +// as of" line, at the oldest measurement shown. Rows is the summary's |
| +// list, set only when no pack row carries the usage (a member, or a page |
| +// with no packs to change). |
| +type billingUsageView struct { |
| + AsOf string |
| + Rows []billingUsageRow |
| +} |
| + |
| +// accountUsage is the account's use per cap, from rows measured in their |
| +// cap's current period, and the oldest such measurement. Nothing current |
| +// is (nil, zero). |
| +func accountUsage(rows []capState, now time.Time) (map[capID]int64, time.Time) { |
| + var used map[capID]int64 |
| + var oldest time.Time |
| + for _, st := range rows { |
| + shown := false |
| + for _, c := range usageCaps { |
| + shown = shown || st.Cap == c |
| + } |
| + if !shown || st.Period != capPeriod(st.Cap, now) || st.UpdatedAt.IsZero() { |
| + continue |
| + } |
| + if used == nil { |
| + used = map[capID]int64{} |
| + } |
| + used[st.Cap] = st.Used |
| + if oldest.IsZero() || st.UpdatedAt.Before(oldest) { |
| + oldest = st.UpdatedAt |
| + } |
| + } |
| + return used, oldest |
| +} |
| + |
| +// capLimit is l's limit for c, 0 for none. |
| +func capLimit(l plans.Limits, c capID) int64 { |
| + switch c { |
| + case capRunningThings: |
| + return int64(l.RunningThings) |
| + case capStorage: |
| + return l.StorageBytes |
| + case capEmail: |
| + return int64(l.EmailPerDay) |
| + case capBandwidth: |
| + return l.BandwidthBytesMonth |
| + } |
| + return 0 |
| +} |
| + |
| +// capAmount is an amount of c as the page writes it: a count or a size. |
| +func capAmount(c capID, n int64) string { |
| + if c == capStorage || c == capBandwidth { |
| + return billingBytes(n) |
| + } |
| + return billingCount(n) |
| +} |
| + |
| +// useLevel is the emphasis for used against limit: levelOf's, at the limit |
| +// shown (which may be a pack or plan away from the one the pass measured |
| +// against). |
| +func useLevel(c capID, used, limit int64) string { |
| + switch l := levelOf(c, used, limit); { |
| + case l.over(): |
| + return "over" |
| + case l == levelWarn: |
| + return "warn" |
| + } |
| + return "" |
| +} |
| + |
| +// useOfLimit is "12 of 35 used" for c against limit, "today" or "this |
| +// month" for a cap counted per UTC day or month; not known when the pass |
| +// has no current row; nil when there is no limit to show it beside. |
| +func useOfLimit(used map[capID]int64, c capID, limit int64) *billingUse { |
| + if limit <= 0 { |
| + return nil |
| + } |
| + n, ok := used[c] |
| + if !ok { |
| + return &billingUse{Text: billingCopy["usage.unknown"]} |
| + } |
| + key := "usage.of" |
| + switch c { |
| + case capEmail: |
| + key = "usage.of_today" |
| + case capBandwidth: |
| + key = "usage.of_month" |
| + } |
| + return &billingUse{Text: fmt.Sprintf(billingCopy[key], capAmount(c, n), capAmount(c, limit)), Level: useLevel(c, n, limit)} |
| +} |
| + |
| +// packUse is a pack row's use: of the limit the pack raises, at the |
| +// account's limits today, or disk's limit alone; nil when the pack raises |
| +// nothing the page measures. |
| +func packUse(used map[capID]int64, adds, limits plans.Limits) *billingUse { |
| + for _, c := range usageCaps { |
| + if capLimit(adds, c) > 0 { |
| + return useOfLimit(used, c, capLimit(limits, c)) |
| + } |
| + } |
| + if adds.DiskBytes > 0 && limits.DiskBytes > 0 { |
| + return &billingUse{Text: fmt.Sprintf(billingCopy["usage.disk"], billingBytes(limits.DiskBytes))} |
| + } |
| + return nil |
| +} |
| + |
| +// addUsage puts the account's usage on v: each pack row's, beside each |
| +// plan card's apps and instances, and the as-of line; in the summary when |
| +// no pack row carries it. Nothing measured this period leaves v as it was. |
| +func addUsage(v *billingView, cat *plans.Catalog, rows []capState, members int, now time.Time) { |
| + used, oldest := accountUsage(rows, now) |
| + if used == nil || v.limits == nil { |
| + return |
| + } |
| + u := &billingUsageView{AsOf: fmt.Sprintf(billingCopy["usage.as_of"], oldest.UTC().Format("2006-01-02 15:04 UTC"))} |
| + inPacks := false |
| + packs := func(ps []billingPackInput) { |
| + for i := range ps { |
| + if ps[i].Use = packUse(used, cat.Packs[ps[i].Name].Adds, *v.limits); ps[i].Use != nil { |
| + inPacks = true |
| + } |
| + } |
| + } |
| + if v.Buy != nil { |
| + packs(v.Buy.Packs) |
| + if n, ok := used[capRunningThings]; ok { |
| + for i := range v.Buy.Plans { |
| + opt := &v.Buy.Plans[i] |
| + l, err := cat.Effective(opt.Name, nil, nil, members) |
| + if err != nil || l.RunningThings <= 0 { |
| + continue |
| + } |
| + for j := range opt.Includes { |
| + if opt.Includes[j].running { |
| + opt.Includes[j].Use = &billingUse{Text: fmt.Sprintf(billingCopy["usage.you_use"], billingCount(n)), |
| + Level: useLevel(capRunningThings, n, int64(l.RunningThings))} |
| + } |
| + } |
| + } |
| + } |
| + } |
| + if v.Change != nil { |
| + packs(v.Change.Packs) |
| + } |
| + if !inPacks { |
| + // No pack row carries it (a member, or no packs to change): the |
| + // summary lists it instead. |
| + labels := map[capID]string{capRunningThings: "usage.label.running", capStorage: "usage.label.storage", |
| + capEmail: "usage.label.email", capBandwidth: "usage.label.bandwidth"} |
| + for _, c := range usageCaps { |
| + if use := useOfLimit(used, c, capLimit(*v.limits, c)); use != nil { |
| + u.Rows = append(u.Rows, billingUsageRow{Label: billingCopy[labels[c]], Use: use}) |
| + } |
| + } |
| + if len(u.Rows) == 0 { |
| + return |
| + } |
| + } |
| + v.Usage = u |
| +} |
diff --git a/internal/console/billingusage_test.go b/internal/console/billingusage_test.go| new file mode 100644 |
| index 000000000..80b63f05e |
| --- /dev/null |
| +++ b/internal/console/billingusage_test.go |
| @@ -0,0 +1,338 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// The billing page's usage (2026-10-29): what the plan-limits pass last |
| +// stored in plan_cap_state, beside the packs, the plan cards and, where no |
| +// pack row carries it, in the summary. Read from the console database |
| +// only; a page view measures nothing. |
| + |
| +const gib = int64(1) << 30 |
| + |
| +// putCapRows stores the plan-limits pass's rows for the fixture's account. |
| +func putCapRows(t *testing.T, pf *billingPageFixture, rows ...capState) { |
| + t.Helper() |
| + for _, st := range rows { |
| + st.AccountID = pf.acct.ID |
| + if st.Level == "" { |
| + st.Level = levelOK |
| + } |
| + if err := pf.st.PutCapState(st); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +// usageRow is a row for c measured at `at`, in at's period. |
| +func usageRow(c capID, used int64, at time.Time) capState { |
| + return capState{Cap: c, Period: capPeriod(c, at), Used: used, UpdatedAt: at} |
| +} |
| + |
| +// changeRow is the paid view's pack row for name. |
| +func changeRow(t *testing.T, body, name string) string { |
| + t.Helper() |
| + m := regexp.MustCompile(`(?s)<tr data-pack="` + name + `">(.*?)</tr>`).FindStringSubmatch(body) |
| + if m == nil { |
| + t.Fatalf("no pack row %q:\n%s", name, body) |
| + } |
| + return m[1] |
| +} |
| + |
| +// useSpan is the usage element a row or card carries, "" for none. |
| +var useSpan = regexp.MustCompile(`<(?:span|dd) class="[^"]*\buse\b[^"]*">[^<]*</(?:span|dd)>`) |
| + |
| +func useOf(t *testing.T, markup string) string { |
| + t.Helper() |
| + return useSpan.FindString(markup) |
| +} |
| + |
| +func usageAsOf(at time.Time) string { |
| + return fmt.Sprintf(billingCopy["usage.as_of"], at.UTC().Format("2006-01-02 15:04 UTC")) |
| +} |
| + |
| +// TestBillingPageUsageFromCapRows: a paid Personal account with packs sees, |
| +// on each pack row, its use of the limit that pack raises, from the pass's |
| +// rows: low plain, 80% and up warned, past the limit over; disk the limit |
| +// alone; and one "as of" line, the oldest measurement shown. |
| +func TestBillingPageUsageFromCapRows(t *testing.T) { |
| + pf := newBillingPageFixture(t) |
| + pf.payFor(t, "personal", map[string]int{"apps": 2, "email": 1}, nil) |
| + now := time.Now().UTC() |
| + older := now.Add(-50 * time.Minute) |
| + bandwidth := usageRow(capBandwidth, 60*gib, older) // 60 GB of 50 GB: over |
| + bandwidth.Period = capPeriod(capBandwidth, now) // measured this month, an earlier pass |
| + putCapRows(t, pf, |
| + usageRow(capRunningThings, 12, now), // 12 of 35: low |
| + usageRow(capEmail, 1700, now), // 1,700 of 2,000: 85%, near |
| + bandwidth, |
| + usageRow(capStorage, 3*gib, now), // 3 GB of 25 GB: low |
| + usageRow(capAwakeHours, 10, now), // no pack raises it |
| + ) |
| + _, body := pf.page(t, "") |
| + |
| + for _, c := range []struct { |
| + pack, text, class string |
| + }{ |
| + {"apps", fmt.Sprintf(billingCopy["usage.of"], "12", "35"), "use"}, |
| + {"email", fmt.Sprintf(billingCopy["usage.of_today"], "1,700", "2,000"), "use use-warn"}, |
| + {"bandwidth", fmt.Sprintf(billingCopy["usage.of_month"], "60 GB", "50 GB"), "use use-over"}, |
| + {"storage", fmt.Sprintf(billingCopy["usage.of"], "3 GB", "25 GB"), "use"}, |
| + } { |
| + got := useOf(t, changeRow(t, body, c.pack)) |
| + want := `<span class="small ` + c.class + `">` + esc(c.text) + `</span>` |
| + if got != want { |
| + t.Errorf("pack %s: usage %q, want %q", c.pack, got, want) |
| + } |
| + } |
| + // Disk per app is not measured centrally: its limit alone. |
| + disk := changeRow(t, body, "disk") |
| + if got, want := useOf(t, disk), `<span class="small use">`+esc(fmt.Sprintf(billingCopy["usage.disk"], "10 GB"))+`</span>`; got != want { |
| + t.Errorf("disk: usage %q, want %q", got, want) |
| + } |
| + if strings.Contains(disk, esc(" used")) { |
| + t.Errorf("disk shows a use it has no measure of:\n%s", disk) |
| + } |
| + // One "as of" line, at the oldest row shown. |
| + if n := strings.Count(body, esc(usageAsOf(older))); n != 1 { |
| + t.Errorf("want one %q, got %d", usageAsOf(older), n) |
| + } |
| + if strings.Contains(body, esc(usageAsOf(now))) { |
| + t.Error("the as-of line names the newest row, not the oldest") |
| + } |
| + // Pack rows carry it, so the summary does not repeat it. |
| + if strings.Contains(body, `class="billing-usage"`) { |
| + t.Error("the summary repeats the usage the pack rows show") |
| + } |
| +} |
| + |
| +// TestBillingPageUsageStalePeriodUnknown: a row from an earlier UTC day |
| +// (email) or month (bandwidth) is not this period's use: it shows as not |
| +// known, never as its old figure or as zero. A cap with no row is not |
| +// known either. |
| +func TestBillingPageUsageStalePeriodUnknown(t *testing.T) { |
| + pf := newBillingPageFixture(t) |
| + pf.payFor(t, "personal", map[string]int{}, nil) |
| + now := time.Now().UTC() |
| + lastMonth := time.Date(now.Year(), now.Month(), 1, 12, 0, 0, 0, time.UTC).AddDate(0, -1, 0) |
| + yesterday := now.AddDate(0, 0, -1) |
| + putCapRows(t, pf, |
| + usageRow(capRunningThings, 4, now), |
| + usageRow(capEmail, 999, yesterday), |
| + usageRow(capBandwidth, 70*gib, lastMonth), |
| + ) |
| + _, body := pf.page(t, "") |
| + unknown := `<span class="small use">` + esc(billingCopy["usage.unknown"]) + `</span>` |
| + for _, pack := range []string{"email", "bandwidth", "storage"} { |
| + row := changeRow(t, body, pack) |
| + if got := useOf(t, row); got != unknown { |
| + t.Errorf("%s: usage %q, want %q", pack, got, unknown) |
| + } |
| + if strings.Contains(row, "999") || strings.Contains(row, "70 GB") || strings.Contains(row, esc(fmt.Sprintf(billingCopy["usage.of_today"], "0", "1,000"))) { |
| + t.Errorf("%s: a stale row shows as a figure:\n%s", pack, row) |
| + } |
| + } |
| + if got, want := useOf(t, changeRow(t, body, "apps")), `<span class="small use">`+esc(fmt.Sprintf(billingCopy["usage.of"], "4", "25"))+`</span>`; got != want { |
| + t.Errorf("apps: usage %q, want %q", got, want) |
| + } |
| + // The as-of line names only what is shown: the fresh row. |
| + if !strings.Contains(body, esc(usageAsOf(now))) || strings.Contains(body, esc(usageAsOf(lastMonth))) || strings.Contains(body, esc(usageAsOf(yesterday))) { |
| + t.Errorf("as-of line wrong:\n%s", body) |
| + } |
| + |
| + // Every row stale: nothing is known, so the page shows no usage at all. |
| + pf2 := newBillingPageFixture(t) |
| + pf2.payFor(t, "personal", map[string]int{}, nil) |
| + putCapRows(t, pf2, usageRow(capEmail, 5, yesterday)) |
| + _, body = pf2.page(t, "") |
| + if useOf(t, body) != "" || strings.Contains(body, esc(fmt.Sprintf(billingCopy["usage.as_of"], ""))) { |
| + t.Errorf("only stale rows: want no usage:\n%s", body) |
| + } |
| +} |
| + |
| +// TestBillingPageUsageNoRowsNoUsage: before the pass has measured anything |
| +// the page is as it was: no usage, no as-of line. |
| +func TestBillingPageUsageNoRowsNoUsage(t *testing.T) { |
| + pf := newBillingPageFixture(t) |
| + pf.payFor(t, "personal", map[string]int{"apps": 1}, nil) |
| + _, body := pf.page(t, "") |
| + if useOf(t, body) != "" || strings.Contains(body, `class="small usage-asof"`) { |
| + t.Errorf("no rows: want no usage:\n%s", body) |
| + } |
| +} |
| + |
| +// TestBillingPageUsageBuyView: a free account choosing a plan sees its use |
| +// against the free plan's limits on the pack rows, and beside each plan |
| +// card's apps and instances, at that plan's limit: near Personal's 25 at |
| +// 22, and plain against a larger plan's. |
| +func TestBillingPageUsageBuyView(t *testing.T) { |
| + pf := newBillingPageFixture(t) |
| + now := time.Now().UTC() |
| + putCapRows(t, pf, usageRow(capRunningThings, 22, now), usageRow(capEmail, 10, now)) |
| + _, body := pf.page(t, "") |
| + form := htmlForm(body, `<form class="buy"`) |
| + if form == "" { |
| + t.Fatalf("no purchase form:\n%s", body) |
| + } |
| + // Pack rows: against the account's limits today (free: 3, 50 a day). |
| + if got, want := useOf(t, changeRow(t, form, "apps")), `<span class="small use use-over">`+esc(fmt.Sprintf(billingCopy["usage.of"], "22", "3"))+`</span>`; got != want { |
| + t.Errorf("apps: usage %q, want %q", got, want) |
| + } |
| + if got, want := useOf(t, changeRow(t, form, "email")), `<span class="small use">`+esc(fmt.Sprintf(billingCopy["usage.of_today"], "10", "50"))+`</span>`; got != want { |
| + t.Errorf("email: usage %q, want %q", got, want) |
| + } |
| + // Plan cards: beside the plan's own apps and instances. |
| + cards := regexp.MustCompile(`(?s)<div class="plan-card">(.*?)</ul>`).FindAllStringSubmatch(form, -1) |
| + if len(cards) == 0 { |
| + t.Fatalf("no plan cards:\n%s", form) |
| + } |
| + youUse := esc(fmt.Sprintf(billingCopy["usage.you_use"], "22")) |
| + seen := map[string]string{} |
| + for _, c := range cards { |
| + name := regexp.MustCompile(`data-plan="([^"]+)"`).FindStringSubmatch(c[1])[1] |
| + seen[name] = useOf(t, c[1]) |
| + } |
| + if got, want := seen["personal"], `<span class="small use use-warn">`+youUse+`</span>`; got != want { |
| + t.Errorf("personal card: usage %q, want %q", got, want) |
| + } |
| + for name, got := range seen { |
| + if name == "personal" { |
| + continue |
| + } |
| + if got != `<span class="small use">`+youUse+`</span>` { |
| + t.Errorf("%s card: usage %q, want plain %q", name, got, youUse) |
| + } |
| + } |
| + if n := strings.Count(body, `class="small usage-asof"`); n != 1 { |
| + t.Errorf("want one as-of line, got %d", n) |
| + } |
| + // The usage spans never read as prices to the currency rules. |
| + assertBuyFormPriced(t, pf, body, 1) |
| +} |
| + |
| +// TestBillingPageUsageMember: a member sees the account's usage, in the |
| +// summary since no pack row is theirs, with no form to change anything. |
| +func TestBillingPageUsageMember(t *testing.T) { |
| + pf := newBillingPageFixture(t) |
| + pf.payFor(t, "personal", map[string]int{"apps": 2}, nil) |
| + now := time.Now().UTC() |
| + putCapRows(t, pf, usageRow(capRunningThings, 34, now), usageRow(capStorage, 30*gib, now)) |
| + if err := pf.st.AddMember(pf.acct.ID, "member@example.com", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + member, _ := signInAs(t, pf.consoleFixture, "member@example.com", "code-billing-usage-member") |
| + _, _, body := get(t, member, pf.ts.URL+pf.billingPath("")) |
| + i := strings.Index(body, `class="billing-usage"`) |
| + if i < 0 { |
| + t.Fatalf("a member sees no usage:\n%s", body) |
| + } |
| + strip := body[i:] |
| + strip = strip[:strings.Index(strip, "</dl>")] |
| + for _, want := range []string{ |
| + esc(billingCopy["usage.label.running"]), |
| + `<dd class="use use-warn">` + esc(fmt.Sprintf(billingCopy["usage.of"], "34", "35")) + `</dd>`, |
| + esc(billingCopy["usage.label.storage"]), |
| + `<dd class="use use-over">` + esc(fmt.Sprintf(billingCopy["usage.of"], "30 GB", "25 GB")) + `</dd>`, |
| + esc(billingCopy["usage.label.email"]), |
| + `<dd class="use">` + esc(billingCopy["usage.unknown"]) + `</dd>`, |
| + } { |
| + if !strings.Contains(strip, want) { |
| + t.Errorf("member's usage is missing %q:\n%s", want, strip) |
| + } |
| + } |
| + if !strings.Contains(body, esc(usageAsOf(now))) { |
| + t.Errorf("member's page has no as-of line:\n%s", body) |
| + } |
| + for _, refused := range []string{`/billing/change"`, `/billing/checkout"`, `/billing/renewal"`, `name="pack"`, `name="quantity"`, `type="number"`} { |
| + if strings.Contains(body, refused) { |
| + t.Errorf("a member's billing page carries %q", refused) |
| + } |
| + } |
| +} |
| + |
| +// billingReadCounter counts every deployment-store request once armed. |
| +type billingReadCounter struct { |
| + release.Store |
| + armed atomic.Bool |
| + mu sync.Mutex |
| + calls []string |
| +} |
| + |
| +func (c *billingReadCounter) note(op, key string) { |
| + if c.armed.Load() { |
| + c.mu.Lock() |
| + c.calls = append(c.calls, op+" "+key) |
| + c.mu.Unlock() |
| + } |
| +} |
| + |
| +func (c *billingReadCounter) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + c.note("get", key) |
| + return c.Store.Get(ctx, key) |
| +} |
| + |
| +func (c *billingReadCounter) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + c.note("put", key) |
| + return c.Store.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +func (c *billingReadCounter) List(ctx context.Context, prefix string) ([]string, error) { |
| + c.note("list", prefix) |
| + return c.Store.List(ctx, prefix) |
| +} |
| + |
| +func (c *billingReadCounter) ListDirs(ctx context.Context, prefix string) ([]string, error) { |
| + c.note("listdirs", prefix) |
| + return c.Store.ListDirs(ctx, prefix) |
| +} |
| + |
| +func (c *billingReadCounter) Delete(ctx context.Context, key string) error { |
| + c.note("delete", key) |
| + return c.Store.Delete(ctx, key) |
| +} |
| + |
| +// TestBillingPageUsageMakesNoRequests: a page view showing usage makes no |
| +// provider request and no deployment-store request: the figures are the |
| +// pass's rows, never a fresh measure. |
| +func TestBillingPageUsageMakesNoRequests(t *testing.T) { |
| + counter := &billingReadCounter{} |
| + pf := newBillingPageFixtureWith(t, consoleFixtureOptions{WithKey: true, WrapReleases: func(s release.Store) release.Store { |
| + counter.Store = s |
| + return counter |
| + }}) |
| + pf.payFor(t, "personal", map[string]int{"apps": 2, "storage": 1}, nil) |
| + now := time.Now().UTC() |
| + putCapRows(t, pf, usageRow(capRunningThings, 30, now), usageRow(capStorage, 80*gib, now), |
| + usageRow(capEmail, 3, now), usageRow(capBandwidth, gib, now)) |
| + pf.fake.Lock() |
| + pf.fake.CallsBy = map[string]int{} |
| + pf.fake.Unlock() |
| + counter.armed.Store(true) |
| + _, body := pf.page(t, "") |
| + counter.armed.Store(false) |
| + if useOf(t, body) == "" { |
| + t.Fatalf("the page shows no usage:\n%s", body) |
| + } |
| + pf.fake.Lock() |
| + for k, n := range pf.fake.CallsBy { |
| + if n != 0 { |
| + t.Errorf("the billing page made %d %s provider requests, want none", n, k) |
| + } |
| + } |
| + pf.fake.Unlock() |
| + counter.mu.Lock() |
| + defer counter.mu.Unlock() |
| + if len(counter.calls) != 0 { |
| + t.Errorf("the billing page made %d deployment-store requests, want none: %v", len(counter.calls), counter.calls) |
| + } |
| +} |
diff --git a/internal/console/templates/billing.html b/internal/console/templates/billing.html| index bc195aff5..06a195640 100644 |
| --- a/internal/console/templates/billing.html |
| +++ b/internal/console/templates/billing.html |
| @@ -19,9 +19,17 @@ |
| </ul>{{end}} |
| </div> |
| {{if .Includes}}<ul class="billing-includes"> |
| - {{range .Includes}}<li>{{icon "check"}}<span>{{.}}</span></li> |
| + {{range .Includes}}<li>{{icon "check"}}<span>{{.Text}}</span></li> |
| {{end}} |
| </ul>{{end}} |
| + {{/* The usage, here only when no pack row carries it (billingusage.go). */}} |
| + {{with .Usage}}{{if .Rows}}<div class="billing-usage"> |
| + <dl> |
| + {{range .Rows}}<div><dt>{{.Label}}</dt><dd class="use{{if .Use.Level}} use-{{.Use.Level}}{{end}}">{{.Use.Text}}</dd></div> |
| + {{end}} |
| + </dl> |
| + <p class="small usage-asof">{{.AsOf}}</p> |
| + </div>{{end}}{{end}} |
| </section> |
| {{/* The offered actions, in decideBillingPage's order. */}} |
| {{range .Actions}} |
| @@ -76,17 +84,20 @@ |
| {{end}}</span> |
| </p> |
| {{if .Includes}}<ul class="plan-incl" id="plan-{{.Name}}-incl"> |
| - {{range .Includes}}<li>{{icon "check"}}<span>{{.}}</span></li> |
| + {{range .Includes}}<li>{{icon "check"}}<span>{{.Text}}</span>{{with .Use}}<span class="small use{{if .Level}} use-{{.Level}}{{end}}">{{.Text}}</span>{{end}}</li> |
| {{end}} |
| </ul>{{end}} |
| </div> |
| {{end}}</fieldset> |
| - {{if .Packs}}<h3 id="packs-title">{{billingText "packs.title"}}</h3> |
| + {{if .Packs}}<div class="packs-head"> |
| + <h3 id="packs-title">{{billingText "packs.title"}}</h3> |
| + {{with $.Billing.Usage}}{{if not .Rows}}<p class="small usage-asof">{{.AsOf}}</p>{{end}}{{end}} |
| + </div> |
| <p class="small">{{billingText "packs.lede"}}</p> |
| <div class="tablewrap"> |
| <table class="packs" aria-labelledby="packs-title"> |
| {{range .Packs}}<tr data-pack="{{.Name}}"> |
| - <td><label for="pack-{{.Name}}">{{.Label}}</label>{{if .Adds}}<span class="small" id="pack-{{.Name}}-adds">{{.Adds}}</span>{{end}}</td> |
| + <td><label for="pack-{{.Name}}">{{.Label}}</label>{{if .Adds}}<span class="small" id="pack-{{.Name}}-adds">{{.Adds}}</span>{{end}}{{with .Use}}<span class="small use{{if .Level}} use-{{.Level}}{{end}}">{{.Text}}</span>{{end}}</td> |
| <td><input type="number" id="pack-{{.Name}}" name="pack_{{.Name}}" min="0" max="{{.Max}}" step="1" value="{{.Value}}" inputmode="numeric" data-select{{if .Adds}} aria-describedby="pack-{{.Name}}-adds"{{end}}></td> |
| <td>{{range .Prices}}<span class="small price price-{{.Code}}" data-currency="{{.Code}}">{{.Text}}</span> |
| {{end}}</td> |
| @@ -100,11 +111,14 @@ |
| </form> |
| {{end}}{{end}} |
| {{if eq . "change"}}{{with $.Billing.Change}} |
| -{{if .Packs}}<h2 id="packs-title">{{billingText "packs.title"}}</h2> |
| +{{if .Packs}}<div class="sectionhead packs-head"> |
| + <h2 id="packs-title">{{billingText "packs.title"}}</h2> |
| + {{with $.Billing.Usage}}{{if not .Rows}}<p class="small usage-asof">{{.AsOf}}</p>{{end}}{{end}} |
| +</div> |
| <div class="tablewrap"> |
| <table class="packs packs-change" aria-labelledby="packs-title"> |
| - {{range .Packs}}<tr> |
| - <td><label for="change-{{.Name}}">{{.Label}}</label>{{if .Adds}}<span class="small" id="change-{{.Name}}-adds">{{.Adds}}</span>{{end}}</td> |
| + {{range .Packs}}<tr data-pack="{{.Name}}"> |
| + <td><label for="change-{{.Name}}">{{.Label}}</label>{{if .Adds}}<span class="small" id="change-{{.Name}}-adds">{{.Adds}}</span>{{end}}{{with .Use}}<span class="small use{{if .Level}} use-{{.Level}}{{end}}">{{.Text}}</span>{{end}}</td> |
| <td class="small">{{.Price}}</td> |
| <td><form method="post" action="{{$.Base}}/billing/change"> |
| <input type="hidden" name="csrf" value="{{$.CSRF}}"> |
diff --git a/internal/console/templates/layout.html b/internal/console/templates/layout.html| index 904ca0731..db74d4435 100644 |
| --- a/internal/console/templates/layout.html |
| +++ b/internal/console/templates/layout.html |
| @@ -653,8 +653,9 @@ |
| .plan-card:has(input:checked) .plan-incl { border-top-color: var(--accent-soft); } |
| /* Packs: one row each, the name and what one adds, a quantity, a price. |
| The quantity box is wide enough for its maximum and steps by one. */ |
| - .buy h3 { margin: 0 0 0.2rem; } |
| - .buy h3 + .small { margin: 0 0 0.75rem; } |
| + .buy h3 { margin: 0; } |
| + .buy .packs-head { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 0.2rem 1rem; margin: 0 0 0.2rem; } |
| + .buy .packs-head + .small { margin: 0 0 0.75rem; } |
| table.packs { margin: 0; } |
| .packs tr:first-child td { border-top: 1px solid var(--rule); } |
| .packs td { padding: 0.75rem 1.25rem 0.75rem 0; vertical-align: middle; } |
| @@ -673,6 +674,30 @@ |
| } |
| .packs input[type=number]:hover { border-color: var(--ink); } |
| .packs input[type=number]:focus-visible { border-color: var(--accent); outline: 2px solid var(--accent); outline-offset: 1px; } |
| + /* Usage beside a limit (billingusage.go), as the plan-limits pass last |
| + measured it: quiet figures in the muted ink. From 80% of the limit the |
| + figure takes the ink and a warn dot; past it, the bad ink and a bad |
| + dot. The weight and the dot carry it as well as the colour. */ |
| + .use { font-variant-numeric: tabular-nums; } |
| + .use-warn, .use-over { font-weight: 600; } |
| + .use-warn { color: var(--ink); } |
| + .use-over { color: var(--bad); } |
| + .use-warn::before, .use-over::before { |
| + content: ""; display: inline-block; width: 0.45rem; height: 0.45rem; margin: 0 0.4rem 0.1em 0; |
| + border-radius: 50%; background: var(--warn); vertical-align: middle; |
| + } |
| + .use-over::before { background: var(--bad); } |
| + .packs td:first-child .use { margin-top: 0.15rem; } |
| + .plan-incl .use { margin-left: auto; padding-left: 0.5rem; white-space: nowrap; } |
| + .usage-asof { margin: 0; } |
| + .packs-head .usage-asof { font-size: 0.82rem; } |
| + /* The summary's usage, when no pack row carries it: a row of figures |
| + under the plan, its as-of line beneath. */ |
| + .billing-usage { flex: 1 1 100%; padding: 0.9rem 0 0; border-top: 1px solid var(--rule); } |
| + .billing-usage dl { display: flex; flex-wrap: wrap; gap: 0.6rem 2.75rem; margin: 0 0 0.6rem; } |
| + .billing-usage dt { font-size: 0.82rem; color: var(--muted); } |
| + .billing-usage dd { margin: 0; font-size: 0.95rem; } |
| + .billing-usage .usage-asof { font-size: 0.82rem; } |
| /* Analytics (app_analytics.html, and the Overview's traffic card). The |
| chart is the page's one loud element; everything around it stays in |