carlos / platform Public

console: billing page from neutral facts, with continue, confirm and match-seats actions, and the /upgrade entry (plans 6b)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 219045d562a7791a547b87593729d81275b2fde1 parent e0a7e4a
10 files changed, +1,466 −1
  • internal/console/billingpage.go +631 −0
  • internal/console/billingpage_copy.go +46 −0
  • internal/console/billingpage_test.go +647 −0
  • internal/console/claim_invariant_fixtures_test.go +2 −0
  • internal/console/claim_invariant_probes_read_test.go +3 −0
  • internal/console/server.go +20 −1
  • internal/console/templates/billing.html +101 −0
  • internal/console/templates/billing_pick.html +13 −0
  • internal/console/templates/layout.html +1 −0
  • internal/console/testdata/claim-routes.txt +2 −0
diff --git a/internal/console/billingpage.go b/internal/console/billingpage.go
new file mode 100644
index 000000000..81152200a
--- /dev/null
+++ b/internal/console/billingpage.go
@@ -0,0 +1,631 @@
+package console
+
+import (
+ "cmp"
+ "fmt"
+ "log"
+ "net"
+ "net/http"
+ "net/url"
+ "regexp"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/geoip"
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+// The billing page (plans 6b, Task 8) and the /upgrade entry the public
+// pricing page links to (Call 1). The page is decided from neutral billing
+// facts the console already stores: a view makes no provider request. Its
+// buttons post to the doors Tasks 9 to 12 build.
+
+// problemSeatsUnpaid: a team account with more members than paid seats
+// (Call 11). Declared here (pre-flight Ruling R3); the seat doors open and
+// close it.
+const problemSeatsUnpaid = "seats_unpaid"
+
+// The page's buttons, as decideBillingPage offers them.
+const (
+ offerBuy = "buy"
+ offerChange = "change"
+ offerStop = "stop"
+ offerResume = "resume"
+ offerPortal = "portal"
+ offerConfirm = "confirm"
+ offerContinue = "continue"
+ offerStartOver = "start_over"
+ offerMatchSeats = "match_seats"
+)
+
+// billingPageInput is everything the page decides from.
+type billingPageInput struct {
+ Row *AccountPlanRow
+ Billing *billingAccount
+ Intent *checkoutIntent
+ Op *billingOp // the outstanding operation, nil for none
+ Problems []string // open problem reasons
+ Retiring, Ready, Owner bool
+ Now time.Time
+}
+
+// billingPageState is the page's decision: a billingCopy notice key ("" for
+// none) and the buttons offered, in display order. OwnersOnly is a
+// member's note that an owner would have something to do here.
+type billingPageState struct {
+ Notice string
+ Offered []string
+ OwnersOnly bool
+}
+
+// decideBillingPage is the decision table, first match. Members get the
+// owner's notice and, where an owner would act, notice.owners_only.
+func decideBillingPage(in billingPageInput) billingPageState {
+ notice, offered := decideBillingOwner(in)
+ if in.Owner {
+ return billingPageState{Notice: notice, Offered: offered}
+ }
+ return billingPageState{Notice: notice, OwnersOnly: len(offered) > 0}
+}
+
+func decideBillingOwner(in billingPageInput) (string, []string) {
+ b := in.Billing
+ bound := b != nil && b.Customer != ""
+ live := b != nil && b.Live
+ ifBound := func(keys ...string) []string {
+ if bound {
+ keys = append(keys, offerPortal)
+ }
+ return keys
+ }
+ intent := in.Intent
+ if intent != nil && intentTerminal(intent) {
+ intent = nil
+ }
+ op := in.Op
+ if op != nil && !opOutstanding(op.State) {
+ op = nil
+ }
+ switch {
+ case !in.Ready:
+ return "notice.not_ready", nil
+ case in.Retiring:
+ return "notice.retiring", nil
+ case slices.Contains(in.Problems, problemSeatsUnpaid):
+ return "notice.seats_unpaid", []string{offerPortal}
+ case slices.Contains(in.Problems, problemOperationUnresolved):
+ return "notice.unresolved", []string{offerPortal}
+ case len(in.Problems) > 0:
+ return "notice.problem", ifBound()
+ case in.Row != nil && (in.Row.Source == PlanSourceOperator || in.Row.Source == PlanSourceSponsored):
+ return "notice.operator_plan", nil
+ // A sending row under no hold is one a crash left behind: Confirm now
+ // adopts it as unresolved and finishes it.
+ case op != nil && (op.State == opUnresolved || op.State == opSending):
+ return "notice.confirming", []string{offerConfirm, offerPortal}
+ case (op != nil && op.State == opPending) || (b != nil && b.PendingUpdate):
+ return "notice.pending_payment", []string{offerPortal}
+ case intent != nil && intent.State == intentOpen && !live:
+ return "notice.checkout_open", ifBound(offerContinue, offerStartOver)
+ case intent != nil && intent.State == intentCreating && !live:
+ return "notice.settling", []string{offerConfirm}
+ case !live:
+ return "", []string{offerBuy}
+ case b.State == billing.StatePending:
+ return "notice.settling", nil
+ case b.Collecting:
+ return "notice.collecting", []string{offerPortal}
+ case b.CancelAtPeriodEnd:
+ return "notice.ending", []string{offerResume, offerPortal}
+ case !b.SeatDriftAt.IsZero():
+ return "notice.seat_drift", []string{offerMatchSeats, offerChange, offerStop, offerPortal}
+ default:
+ return "", []string{offerChange, offerStop, offerPortal}
+ }
+}
+
+// OpenBillingProblemReasons is the reasons of the account's open billing
+// problems, each once, sorted.
+func (s *Store) OpenBillingProblemReasons(accountID int64) ([]string, error) {
+ rows, err := s.db.Query(`SELECT DISTINCT reason FROM billing_problems WHERE account_id = ? AND closed_at = 0 ORDER BY reason`, accountID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []string
+ for rows.Next() {
+ var r string
+ if err := rows.Scan(&r); err != nil {
+ return nil, err
+ }
+ out = append(out, r)
+ }
+ return out, rows.Err()
+}
+
+// requestCountry is the ISO 3166-1 alpha-2 country of the request's client
+// address from the console's GeoIP database, "" for none. It only
+// preselects a currency; the buyer can change it.
+func (s *Server) requestCountry(r *http.Request) string {
+ if s.cfg.GeoIPReader == nil {
+ return ""
+ }
+ ip := net.ParseIP(s.clientIP(r))
+ if ip == nil {
+ return ""
+ }
+ a := geoip.FromSnapshot(s.cfg.GeoIPReader.Lookup(ip))
+ if a.State != geoip.StateHit {
+ return ""
+ }
+ return a.Country
+}
+
+// currencyShown is a refused currency value safe to echo back.
+var currencyShown = regexp.MustCompile(`^[a-z0-9]{1,8}$`)
+
+// currencyQuery reads an explicit currency (Call 2). Empty is no choice. A
+// code the book sells, exactly as written, is code. Anything else is
+// refused, never defaulted: shown is the value folded to lower case when
+// that is safe to show, else "".
+func currencyQuery(raw string, book *plans.PriceBook) (code string, refused bool, shown string) {
+ if raw == "" {
+ return "", false, ""
+ }
+ if book != nil {
+ if c, err := book.ChooseCurrency(raw, ""); err == nil {
+ return c, false, ""
+ }
+ }
+ if f := strings.ToLower(raw); currencyShown.MatchString(f) {
+ return "", true, f
+ }
+ return "", true, ""
+}
+
+// ---- the view -------------------------------------------------------------
+
+// billingView is the billing page's body.
+type billingView struct {
+ Notice, OwnersOnly, CurrencyNotice string
+ Facts []string
+ Offers billingOffers
+ Buy *billingBuyView
+ Change *billingChangeView
+ StartOver []billingField // the open intent's own request, for Start over
+}
+
+// billingOffers is decideBillingPage's Offered as the template reads it.
+type billingOffers struct {
+ Buy, Change, Stop, Resume, Portal, Confirm, Continue, StartOver, MatchSeats bool
+}
+
+type billingField struct{ Name, Value string }
+
+// billingBuyView is the first purchase: the paid plans, a quantity per
+// offered pack, and the currency (radios, or the account's fixed one).
+type billingBuyView struct {
+ Plans []billingPlanOption
+ Packs []billingPackInput
+ Currencies []billingCurrencyOption
+ FixedCurrency string
+}
+
+type billingPlanOption struct {
+ Name, Label, Price, Total string
+ Checked bool
+}
+
+type billingPackInput struct {
+ Name, Price string
+ Max, Value int
+}
+
+type billingCurrencyOption struct {
+ Code string
+ Checked bool
+}
+
+// billingChangeView is a paid account's changes: one form per pack, and an
+// upgrade per higher plan (Call 4).
+type billingChangeView struct {
+ Packs []billingPackInput
+ Upgrades []billingPlanOption
+}
+
+// billingPageInputFor reads the stored facts the page decides from.
+func (s *Server) billingPageInputFor(acct *Account, role string, now time.Time) (billingPageInput, error) {
+ in := billingPageInput{Owner: role == RoleOwner, Ready: s.billing.ready.Load(), Now: now}
+ var err error
+ if in.Row, err = s.store.AccountPlan(acct.ID); err != nil {
+ return in, err
+ }
+ if in.Billing, err = s.store.BillingAccount(acct.ID); err != nil {
+ return in, err
+ }
+ if in.Intent, err = s.store.CheckoutIntent(acct.ID); err != nil {
+ return in, err
+ }
+ if in.Billing != nil && in.Billing.Subscription != "" {
+ if in.Op, err = s.store.OutstandingOp(in.Billing.Subscription); err != nil {
+ return in, err
+ }
+ }
+ if in.Problems, err = s.store.OpenBillingProblemReasons(acct.ID); err != nil {
+ return in, err
+ }
+ if in.Retiring, err = s.store.BillingRetiring(acct.ID, now); err != nil {
+ return in, err
+ }
+ return in, nil
+}
+
+// handleBilling is GET /a/{sqid}/billing. Billing off answers the unrouted
+// 404; the account gate answers a non-member with the same 404. Members
+// see the facts and notices, owners also the forms.
+func (s *Server) handleBilling(w http.ResponseWriter, r *http.Request) {
+ if s.billing == nil {
+ http.NotFound(w, r)
+ return
+ }
+ addr, raw, acct, role, ok := s.account(w, r)
+ if !ok {
+ return
+ }
+ // The page reads only what the console stores (the request budget's
+ // 0), so it needs no clock recorder: the forms' handlers install
+ // their own (s.billingClock) when they act.
+ now := time.Now()
+ in, err := s.billingPageInputFor(acct, role, now)
+ if err != nil {
+ log.Printf("console: billing page %s: %v", acct.Sqid, err)
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read billing. Please try again.")
+ return
+ }
+ members, err := s.store.MemberCount(acct.ID)
+ if err != nil {
+ log.Printf("console: billing page %s: members: %v", acct.Sqid, err)
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read billing. Please try again.")
+ return
+ }
+ st := decideBillingPage(in)
+ view := s.billingViewFor(r, in, st, members)
+ p := s.accountPage(w, r, addr, raw, acct, role)
+ p.Title = billingCopy["page.title"]
+ p.ActiveNav = "billing"
+ p.Billing = view
+ s.render(w, http.StatusOK, "billing", p)
+}
+
+func (s *Server) billingViewFor(r *http.Request, in billingPageInput, st billingPageState, members int) *billingView {
+ cat, book := s.cfg.PlanCatalog, s.billing.cfg.Book
+ b := in.Billing
+ v := &billingView{}
+ switch st.Notice {
+ case "":
+ case "notice.ending":
+ v.Notice = fmt.Sprintf(billingCopy[st.Notice], billingDate(b.PeriodEnd))
+ case "notice.seat_drift":
+ v.Notice = fmt.Sprintf(billingCopy[st.Notice], b.Seats, b.SeatDriftMembers)
+ default:
+ v.Notice = billingCopy[st.Notice]
+ }
+ if st.OwnersOnly {
+ v.OwnersOnly = billingCopy["notice.owners_only"]
+ }
+ for _, k := range st.Offered {
+ switch k {
+ case offerBuy:
+ v.Offers.Buy = true
+ case offerChange:
+ v.Offers.Change = true
+ case offerStop:
+ v.Offers.Stop = true
+ case offerResume:
+ v.Offers.Resume = true
+ case offerPortal:
+ v.Offers.Portal = true
+ case offerConfirm:
+ v.Offers.Confirm = true
+ case offerContinue:
+ v.Offers.Continue = true
+ case offerStartOver:
+ v.Offers.StartOver = true
+ case offerMatchSeats:
+ v.Offers.MatchSeats = true
+ }
+ }
+
+ // The facts.
+ plan, packs := cat.DefaultPlan, map[string]int(nil)
+ if in.Row != nil {
+ plan, packs = in.Row.Plan, in.Row.Packs
+ }
+ v.Facts = append(v.Facts, fmt.Sprintf(billingCopy["fact.plan"], planLabel(plan)))
+ if held := heldPacks(packs); len(held) > 0 {
+ var parts []string
+ for _, name := range held {
+ parts = append(parts, fmt.Sprintf("%s %d", name, packs[name]))
+ }
+ v.Facts = append(v.Facts, fmt.Sprintf(billingCopy["fact.packs"], strings.Join(parts, ", ")))
+ }
+ if p, ok := cat.Plans[plan]; ok && p.Team != nil && b != nil {
+ v.Facts = append(v.Facts, fmt.Sprintf(billingCopy["team.members"], members, b.PaidSeats))
+ }
+ if b != nil && b.Currency != "" {
+ v.Facts = append(v.Facts, fmt.Sprintf(billingCopy["fact.currency"], b.Currency))
+ }
+ if b != nil && b.Live && !b.PeriodEnd.IsZero() {
+ switch {
+ case !b.CancelAtPeriodEnd:
+ v.Facts = append(v.Facts, fmt.Sprintf(billingCopy["renews"], billingDate(b.PeriodEnd)))
+ case st.Notice != "notice.ending":
+ v.Facts = append(v.Facts, fmt.Sprintf(billingCopy["notice.ending"], billingDate(b.PeriodEnd)))
+ }
+ }
+
+ if v.Offers.Buy {
+ v.Buy = s.billingBuy(r, book, b, members, &v.CurrencyNotice)
+ }
+ if v.Offers.Change && b != nil {
+ v.Change = billingChange(cat, book, plan, packs, b.Currency)
+ }
+ if v.Offers.StartOver && in.Intent != nil {
+ ci := in.Intent
+ v.StartOver = []billingField{{"plan", ci.Plan}, {"currency", ci.Currency}}
+ for _, name := range heldPacks(ci.Packs) {
+ v.StartOver = append(v.StartOver, billingField{"pack_" + name, fmt.Sprint(ci.Packs[name])})
+ }
+ v.StartOver = append(v.StartOver, billingField{"start_over", "1"})
+ }
+ return v
+}
+
+// billingBuy is the purchase form. The currency: an account's fixed one
+// (Call 3) as text; else an explicit sold code, else the visitor's
+// country's, else the book's default; an explicit code not sold is
+// refused with nothing preselected (Call 2).
+func (s *Server) billingBuy(r *http.Request, book *plans.PriceBook, b *billingAccount, members int, notice *string) *billingBuyView {
+ cat := s.cfg.PlanCatalog
+ buy := &billingBuyView{}
+ raw := r.URL.Query().Get("currency")
+ display, chosen := book.DefaultCurrency, ""
+ if b != nil && b.Currency != "" {
+ buy.FixedCurrency, display = b.Currency, b.Currency
+ if raw != "" && raw != b.Currency {
+ *notice = fmt.Sprintf(billingCopy["currency.fixed"], b.Currency)
+ }
+ } else {
+ code, refused, shown := currencyQuery(raw, book)
+ switch {
+ case refused && shown != "":
+ *notice = fmt.Sprintf(billingCopy["currency.refused"], shown)
+ case refused:
+ *notice = billingCopy["currency.refused_unshown"]
+ case code != "":
+ chosen = code
+ default:
+ if c, err := book.ChooseCurrency("", s.requestCountry(r)); err == nil {
+ chosen = c
+ }
+ }
+ if chosen != "" {
+ display = chosen
+ }
+ for _, c := range book.Currencies {
+ buy.Currencies = append(buy.Currencies, billingCurrencyOption{Code: c, Checked: c == chosen})
+ }
+ }
+
+ want := r.URL.Query().Get("plan")
+ seen := map[string]bool{}
+ for _, name := range paidPlansByTotal(cat, book, display) {
+ p := cat.Plans[name]
+ price, _ := book.PlanPrice(name, display)
+ opt := billingPlanOption{Name: name, Label: planLabel(name), Checked: name == want}
+ if p.Team != nil {
+ opt.Price = fmt.Sprintf(billingCopy["team.price"], plans.FormatMinor(display, price), p.Team.MinMembers)
+ opt.Total = fmt.Sprintf(billingCopy["team.total"], plans.FormatMinor(display, price*int64(p.Team.Billed(members))))
+ } else {
+ opt.Price = fmt.Sprintf(billingCopy["plan.price"], plans.FormatMinor(display, price))
+ }
+ buy.Plans = append(buy.Plans, opt)
+ for _, pk := range p.Packs {
+ if seen[pk] {
+ continue
+ }
+ seen[pk] = true
+ buy.Packs = append(buy.Packs, packInput(cat, book, pk, display, 0))
+ }
+ }
+ return buy
+}
+
+// billingChange is the paid account's pack forms and its upgrades: a plan
+// is offered when its lowest yearly total in the configured book, in the
+// subscription's currency, is higher than the current plan's and it offers
+// every pack held (Call 4). Task 10's door decides again.
+func billingChange(cat *plans.Catalog, book *plans.PriceBook, plan string, packs map[string]int, currency string) *billingChangeView {
+ ch := &billingChangeView{}
+ cur, ok := cat.Plans[plan]
+ if !ok {
+ return ch
+ }
+ if currency == "" {
+ currency = book.DefaultCurrency
+ }
+ for _, pk := range cur.Packs {
+ ch.Packs = append(ch.Packs, packInput(cat, book, pk, currency, packs[pk]))
+ }
+ floor, ok := lowestTotal(cat, book, plan, currency)
+ if !ok {
+ return ch
+ }
+ for _, name := range paidPlansByTotal(cat, book, currency) {
+ total, _ := lowestTotal(cat, book, name, currency)
+ if total <= floor || !offersAll(cat.Plans[name], heldPacks(packs)) {
+ continue
+ }
+ ch.Upgrades = append(ch.Upgrades, billingPlanOption{Name: name, Label: fmt.Sprintf(billingCopy["button.upgrade"], planLabel(name))})
+ }
+ return ch
+}
+
+func packInput(cat *plans.Catalog, book *plans.PriceBook, name, currency string, value int) billingPackInput {
+ in := billingPackInput{Name: name, Max: cat.Packs[name].MaxQuantity, Value: value}
+ if price, ok := book.PackPrice(name, currency); ok {
+ in.Price = fmt.Sprintf(billingCopy["pack.price"], plans.FormatMinor(currency, price))
+ }
+ return in
+}
+
+// lowestTotal is a paid plan's lowest yearly total in currency: its price,
+// times its minimum members on a team plan.
+func lowestTotal(cat *plans.Catalog, book *plans.PriceBook, plan, currency string) (int64, bool) {
+ p, ok := cat.Plans[plan]
+ if !ok || !p.Paid {
+ return 0, false
+ }
+ price, ok := book.PlanPrice(plan, currency)
+ if !ok {
+ return 0, false
+ }
+ if p.Team != nil {
+ price *= int64(p.Team.MinMembers)
+ }
+ return price, true
+}
+
+// paidPlansByTotal is the catalog's paid plans priced in currency, lowest
+// yearly total first, then by name.
+func paidPlansByTotal(cat *plans.Catalog, book *plans.PriceBook, currency string) []string {
+ type priced struct {
+ name string
+ total int64
+ }
+ var ps []priced
+ for name := range cat.Plans {
+ if total, ok := lowestTotal(cat, book, name, currency); ok {
+ ps = append(ps, priced{name, total})
+ }
+ }
+ slices.SortFunc(ps, func(a, b priced) int { return cmp.Or(cmp.Compare(a.total, b.total), cmp.Compare(a.name, b.name)) })
+ out := make([]string, len(ps))
+ for i, p := range ps {
+ out[i] = p.name
+ }
+ return out
+}
+
+func offersAll(p plans.Plan, held []string) bool {
+ for _, pk := range held {
+ if !slices.Contains(p.Packs, pk) {
+ return false
+ }
+ }
+ return true
+}
+
+// heldPacks is the packs with a quantity above 0, sorted.
+func heldPacks(packs map[string]int) []string {
+ var out []string
+ for name, q := range packs {
+ if q > 0 {
+ out = append(out, name)
+ }
+ }
+ slices.Sort(out)
+ return out
+}
+
+// planLabel is a plan name as the page shows it: "community" is
+// "Community".
+func planLabel(name string) string {
+ if name == "" {
+ return ""
+ }
+ return strings.ToUpper(name[:1]) + name[1:]
+}
+
+func billingDate(t time.Time) string { return t.UTC().Format("2 January 2006") }
+
+// ---- /upgrade -------------------------------------------------------------
+
+// upgradeCurrency is a currency value /upgrade keeps as given.
+var upgradeCurrency = regexp.MustCompile(`^[A-Za-z0-9]{1,8}$`)
+
+// upgradeQuery is what /upgrade keeps of its query (Call 1): plan when it is
+// a paid catalog plan; currency as given when it is short and alphanumeric,
+// else "invalid", which the billing page then refuses. Nothing else is
+// carried, so no caller-chosen value reaches a redirect.
+func (s *Server) upgradeQuery(r *http.Request) url.Values {
+ q, kept := r.URL.Query(), url.Values{}
+ if p := q.Get("plan"); p != "" {
+ if pl, ok := s.cfg.PlanCatalog.Plans[p]; ok && pl.Paid {
+ kept.Set("plan", p)
+ }
+ }
+ if c := q.Get("currency"); c != "" {
+ if upgradeCurrency.MatchString(c) {
+ kept.Set("currency", c)
+ } else {
+ kept.Set("currency", "invalid")
+ }
+ }
+ return kept
+}
+
+// withQuery is path, plus "?" and the encoded values when there are any.
+func withQuery(path string, v url.Values) string {
+ if len(v) == 0 {
+ return path
+ }
+ return path + "?" + v.Encode()
+}
+
+// handleUpgrade is GET /upgrade?plan=&currency=, the entry the pricing page
+// links to. Billing off: 404. Signed out: the front door, which signs in
+// or up and returns here through safeNext. Signed in: the billing page of
+// the one account the viewer owns, a picker when they own several (the
+// most recent first), and a note when they own none.
+func (s *Server) handleUpgrade(w http.ResponseWriter, r *http.Request) {
+ if s.billing == nil {
+ http.NotFound(w, r)
+ return
+ }
+ kept := s.upgradeQuery(r)
+ addr, _, ok := s.session(r)
+ if !ok {
+ http.Redirect(w, r, "/?next="+url.QueryEscape(withQuery("/upgrade", kept)), http.StatusSeeOther)
+ return
+ }
+ accts, err := s.store.AccountsFor(addr)
+ if err != nil {
+ log.Printf("console: upgrade for %s: %v", addr, err)
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read your accounts. Please try again.")
+ return
+ }
+ var owned []Account
+ for _, a := range accts {
+ if a.Role == RoleOwner {
+ owned = append(owned, a)
+ }
+ }
+ switch len(owned) {
+ case 0:
+ s.renderMessage(w, r, http.StatusOK, billingCopy["upgrade.not_owner_title"], billingCopy["upgrade.not_owner"])
+ case 1:
+ http.Redirect(w, r, withQuery("/a/"+url.PathEscape(owned[0].Sqid)+"/billing", kept), http.StatusSeeOther)
+ default:
+ slices.SortStableFunc(owned, func(a, b Account) int {
+ return cmp.Or(b.CreatedAt.Compare(a.CreatedAt), cmp.Compare(b.ID, a.ID))
+ })
+ p := s.basePage(r)
+ p.Title = billingCopy["pick.title"]
+ p.BillingPick = owned
+ p.BillingPickQuery = withQuery("", kept)
+ s.render(w, http.StatusOK, "billing_pick", p)
+ }
+}
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go
index 134c23d64..a3b62657c 100644
--- a/internal/console/billingpage_copy.go
+++ b/internal/console/billingpage_copy.go
@@ -16,4 +16,50 @@ var billingCopy = map[string]string{
"change.failed": "We couldn't make that change. Try again in a minute.",
"change.retry": "Your plan just renewed. Try again in a minute.",
"change.clock": "We can't make that change right now. Try again in a few minutes.",
+
+ // The page (Task 8).
+ "page.title": "Billing",
+ "notice.not_ready": "Billing isn't available right now. Try again in a few minutes.",
+ "notice.retiring": "This account is being deleted, so nothing can be bought or changed.",
+ "notice.problem": "We're checking this purchase. Your plan hasn't changed yet, and nothing more will be charged.",
+ "notice.seats_unpaid": "This account has more members than it pays for. Remove members, or ask an operator.",
+ "notice.unresolved": "We couldn't confirm a recent change, and someone is checking it. Nothing more will be charged.",
+ "notice.operator_plan": "An operator set this account's plan, so there's nothing to buy here.",
+ "notice.confirming": "We're confirming a recent change. Nothing more will be charged.",
+ "notice.settling": "We're confirming your payment. This page shows your new plan once it's done.",
+ "notice.pending_payment": "A change is waiting for payment. Pay it from Payment and invoices, or it's dropped after a day.",
+ "notice.checkout_open": "Your payment page is still open.",
+ "notice.collecting": "Your last payment didn't go through. Update your card in Payment and invoices. Your plan stays while we retry.",
+ "notice.ending": "Your plan ends on %s. After that the account moves to the free plan.",
+ "notice.seat_drift": "Your next renewal bills %d seats for %d members.",
+ "notice.owners_only": "Only an owner of this account can change its plan.",
+ "currency.refused": "We don't sell in %q. Choose usd, eur or gbp.",
+ "currency.refused_unshown": "We don't sell in that currency. Choose usd, eur or gbp.",
+ "currency.fixed": "This account pays in %s. To change that, ask an operator.",
+ "buy.title": "Choose a plan",
+ "buy.button": "Continue to payment",
+ "team.price": "%s per member a year, for at least %d members",
+ "team.members": "%d members, paid for %d",
+ "renews": "Renews on %s",
+ "button.confirm": "Confirm now",
+ "button.continue": "Continue to payment",
+ "button.start_over": "Start over",
+ "button.match_seats": "Match seats to members",
+ "button.portal": "Payment and invoices",
+ "upgrade.not_owner_title": "Only owners can upgrade",
+ "upgrade.not_owner": "Only an owner of an account can upgrade it. Create an account of your own to choose a plan.",
+ "pick.title": "Which account?",
+
+ // Task 8's own drafts, beyond the plan's list: labels the page needs.
+ "fact.plan": "Plan: %s",
+ "fact.packs": "Packs: %s",
+ "fact.currency": "Pays in %s",
+ "plan.price": "%s a year",
+ "pack.price": "%s a year each",
+ "team.total": "Today that's %s a year.",
+ "currency.legend": "Currency",
+ "button.change": "Change",
+ "button.upgrade": "Upgrade to %s",
+ "button.stop": "Stop renewal",
+ "button.resume": "Turn renewal back on",
}
diff --git a/internal/console/billingpage_test.go b/internal/console/billingpage_test.go
new file mode 100644
index 000000000..f66e6c3bf
--- /dev/null
+++ b/internal/console/billingpage_test.go
@@ -0,0 +1,647 @@
+package console
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/geo"
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+// ---- the decision table -----------------------------------------------------
+
+func TestDecideBillingPage(t *testing.T) {
+ now := billingNow
+ paid := func(mod func(b *billingAccount)) *billingAccount {
+ b := &billingAccount{Customer: "cus_1", Subscription: "sub_1", State: billing.StatePaid, Live: true, Currency: "usd", PeriodEnd: periodEnd}
+ if mod != nil {
+ mod(b)
+ }
+ return b
+ }
+ free := &billingAccount{Customer: "cus_1"}
+ billingRow := &AccountPlanRow{Plan: "personal", Source: PlanSourceBilling}
+ op := func(state string) *billingOp { return &billingOp{ID: "op_1", State: state} }
+ intent := func(state string) *checkoutIntent { return &checkoutIntent{ID: "ci_1", State: state} }
+
+ cases := []struct {
+ name string
+ in billingPageInput
+ notice string
+ offered []string
+ }{
+ {"not ready", billingPageInput{Billing: paid(nil), Retiring: true}, "notice.not_ready", nil},
+ {"retiring", billingPageInput{Ready: true, Retiring: true, Problems: []string{problemSeatsUnpaid}}, "notice.retiring", nil},
+ {"seats unpaid", billingPageInput{Ready: true, Billing: paid(nil), Problems: []string{problemOperationUnresolved, problemSeatsUnpaid}},
+ "notice.seats_unpaid", []string{"portal"}},
+ {"operation unresolved", billingPageInput{Ready: true, Billing: paid(nil), Problems: []string{problemOperationUnresolved}},
+ "notice.unresolved", []string{"portal"}},
+ {"restore after renewal", billingPageInput{Ready: true, Billing: paid(nil), Problems: []string{problemRestoreAfterRenewal}},
+ "notice.problem", []string{"portal"}},
+ {"another problem, bound", billingPageInput{Ready: true, Billing: free, Problems: []string{problemSecondSubscription}},
+ "notice.problem", []string{"portal"}},
+ {"another problem, unbound", billingPageInput{Ready: true, Problems: []string{problemUnknownCustomer}}, "notice.problem", nil},
+ {"operator row", billingPageInput{Ready: true, Row: &AccountPlanRow{Plan: "business", Source: PlanSourceOperator}, Billing: free,
+ Op: op(opUnresolved)}, "notice.operator_plan", nil},
+ {"sponsored row", billingPageInput{Ready: true, Row: &AccountPlanRow{Plan: "free", Source: PlanSourceSponsored}}, "notice.operator_plan", nil},
+ {"op unresolved", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Op: op(opUnresolved)},
+ "notice.confirming", []string{"confirm", "portal"}},
+ {"op sending", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Op: op(opSending)},
+ "notice.confirming", []string{"confirm", "portal"}},
+ {"op pending", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Op: op(opPending)},
+ "notice.pending_payment", []string{"portal"}},
+ {"pending update", billingPageInput{Ready: true, Row: billingRow, Billing: paid(func(b *billingAccount) { b.PendingUpdate = true })},
+ "notice.pending_payment", []string{"portal"}},
+ {"intent open, bound", billingPageInput{Ready: true, Billing: free, Intent: intent(intentOpen)},
+ "notice.checkout_open", []string{"continue", "start_over", "portal"}},
+ {"intent open, unbound", billingPageInput{Ready: true, Intent: intent(intentOpen)},
+ "notice.checkout_open", []string{"continue", "start_over"}},
+ {"intent creating", billingPageInput{Ready: true, Billing: free, Intent: intent(intentCreating)},
+ "notice.settling", []string{"confirm"}},
+ {"not live", billingPageInput{Ready: true, Billing: free}, "", []string{"buy"}},
+ {"no billing row", billingPageInput{Ready: true}, "", []string{"buy"}},
+ {"intent open but live", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Intent: intent(intentOpen)},
+ "", []string{"change", "stop", "portal"}},
+ {"pending state", billingPageInput{Ready: true, Billing: paid(func(b *billingAccount) { b.State = billing.StatePending })},
+ "notice.settling", nil},
+ {"collecting", billingPageInput{Ready: true, Row: billingRow, Billing: paid(func(b *billingAccount) { b.Collecting = true; b.CancelAtPeriodEnd = true })},
+ "notice.collecting", []string{"portal"}},
+ {"ending", billingPageInput{Ready: true, Row: billingRow, Billing: paid(func(b *billingAccount) { b.CancelAtPeriodEnd = true; b.SeatDriftAt = now })},
+ "notice.ending", []string{"resume", "portal"}},
+ {"seat drift", billingPageInput{Ready: true, Row: billingRow, Billing: paid(func(b *billingAccount) { b.SeatDriftAt = now; b.SeatDriftMembers = 9 })},
+ "notice.seat_drift", []string{"match_seats", "change", "stop", "portal"}},
+ {"paid", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil)}, "", []string{"change", "stop", "portal"}},
+ // Terminal intents are ignored, whatever their state.
+ {"intent completed", billingPageInput{Ready: true, Billing: free, Intent: intent(intentCompleted)}, "", []string{"buy"}},
+ {"intent expired", billingPageInput{Ready: true, Billing: free, Intent: intent(intentExpired)}, "", []string{"buy"}},
+ {"intent abandoned", billingPageInput{Ready: true, Billing: free, Intent: intent(intentAbandoned)}, "", []string{"buy"}},
+ // A settled operation is not outstanding.
+ {"op applied", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Op: op(opApplied)}, "", []string{"change", "stop", "portal"}},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ in := c.in
+ in.Now, in.Owner = now, true
+ got := decideBillingPage(in)
+ if got.Notice != c.notice || !slices.Equal(got.Offered, c.offered) || got.OwnersOnly {
+ t.Fatalf("owner: got %+v, want notice %q offered %v", got, c.notice, c.offered)
+ }
+ in.Owner = false
+ got = decideBillingPage(in)
+ if got.Notice != c.notice || len(got.Offered) != 0 || got.OwnersOnly != (len(c.offered) > 0) {
+ t.Fatalf("member: got %+v, want notice %q, nothing offered, owners only %v", got, c.notice, len(c.offered) > 0)
+ }
+ })
+ }
+ // Every key the plan drafts for the page, and no em dash anywhere.
+ // The plan's notice.past_due is notice.collecting here: "past_due" is a
+ // provider status word (TestConsoleBillingHasNoProviderWords).
+ for _, k := range []string{"page.title", "notice.not_ready", "notice.retiring", "notice.problem", "notice.seats_unpaid",
+ "notice.unresolved", "notice.operator_plan", "notice.confirming", "notice.settling", "notice.pending_payment",
+ "notice.checkout_open", "notice.collecting", "notice.ending", "notice.seat_drift", "notice.owners_only",
+ "currency.refused", "currency.refused_unshown", "currency.fixed", "buy.title", "buy.button", "team.price",
+ "team.members", "renews", "button.confirm", "button.continue", "button.start_over", "button.match_seats",
+ "button.portal", "upgrade.not_owner_title", "upgrade.not_owner", "pick.title"} {
+ if billingCopy[k] == "" {
+ t.Errorf("billingCopy has no %q", k)
+ }
+ }
+ for k, v := range billingCopy {
+ if strings.Contains(v, "\u2014") {
+ t.Errorf("billingCopy[%q] has an em dash", k)
+ }
+ }
+}
+
+// ---- the page --------------------------------------------------------------
+
+// billingPageFixture is a billing fixture whose owner is signed in, with
+// billing ready.
+type billingPageFixture struct {
+ *billingFixture
+ owner *http.Client
+ csrf string
+}
+
+func newBillingPageFixture(t *testing.T) *billingPageFixture {
+ t.Helper()
+ bf := newBillingFixture(t)
+ bf.srv.billing.ready.Store(true)
+ bf.setUser("owner" + bf.acct.Sqid + "@example.com")
+ c := newBrowser(t)
+ signUp(t, bf.consoleFixture, c, "code-billing-page-"+bf.acct.Sqid)
+ return &billingPageFixture{billingFixture: bf, owner: c, csrf: sessionToken(t, bf.consoleFixture, c)}
+}
+
+func (pf *billingPageFixture) billingPath(query string) string {
+ p := "/a/" + pf.acct.Sqid + "/billing"
+ if query != "" {
+ p += "?" + query
+ }
+ return p
+}
+
+// page GETs the billing page as the owner.
+func (pf *billingPageFixture) page(t *testing.T, query string) (int, string) {
+ t.Helper()
+ status, _, body := get(t, pf.owner, pf.ts.URL+pf.billingPath(query))
+ return status, body
+}
+
+// serveAs sends a GET straight to the server from remote, with c's cookies,
+// so the client address is the test's to choose.
+func serveAs(t *testing.T, fx *consoleFixture, c *http.Client, path, remote string) (int, string, string) {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodGet, fx.ts.URL+path, nil)
+ req.RemoteAddr = remote
+ u, _ := url.Parse(fx.ts.URL)
+ if c != nil {
+ for _, ck := range c.Jar.Cookies(u) {
+ req.AddCookie(ck)
+ }
+ }
+ rr := httptest.NewRecorder()
+ fx.srv.ServeHTTP(rr, req)
+ return rr.Code, rr.Header().Get("Location"), rr.Body.String()
+}
+
+// unroutedBody is what an unrouted URL answers.
+func unroutedBody(t *testing.T, fx *consoleFixture, c *http.Client) string {
+ t.Helper()
+ status, _, body := get(t, c, fx.ts.URL+"/no/such/route")
+ if status != http.StatusNotFound {
+ t.Fatalf("unrouted = %d", status)
+ }
+ return body
+}
+
+func TestBillingPageOffAndGate(t *testing.T) {
+ t.Run("billing off", func(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.setUser("paul@keymail.dev")
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-billing-off")
+ status, _, body := get(t, c, fx.ts.URL+"/a/"+fx.sqid+"/billing")
+ if status != http.StatusNotFound || body != unroutedBody(t, fx, c) {
+ t.Fatalf("billing off = %d %q, want the unrouted 404", status, body)
+ }
+ // No nav link either.
+ _, _, home := get(t, c, fx.ts.URL+"/a/"+fx.sqid+"/settings")
+ if strings.Contains(home, `/billing"`) {
+ t.Fatal("billing off: the account nav links billing")
+ }
+ })
+
+ pf := newBillingPageFixture(t)
+ billingURL := pf.ts.URL + pf.billingPath("")
+
+ // Signed out: the front page, as every account page does.
+ if status, loc, _ := get(t, newBrowser(t), billingURL); status != http.StatusFound || loc != "/" {
+ t.Fatalf("signed out = %d -> %q, want 302 -> /", status, loc)
+ }
+
+ // A non-member gets the unrouted 404, byte for byte.
+ stranger, _ := signInAs(t, pf.consoleFixture, "stranger@example.com", "code-billing-stranger")
+ status, _, body := get(t, stranger, billingURL)
+ if status != http.StatusNotFound || body != unroutedBody(t, pf.consoleFixture, stranger) {
+ t.Fatalf("non-member = %d %q, want the unrouted 404", status, body)
+ }
+
+ // A member sees the page and the owners-only note, and no form.
+ 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-member")
+ status, _, body = get(t, member, billingURL)
+ if status != http.StatusOK || !strings.Contains(body, esc(billingCopy["notice.owners_only"])) {
+ t.Fatalf("member = %d, want 200 with the owners-only note:\n%s", status, body)
+ }
+ if strings.Contains(body, `action="/a/`+pf.acct.Sqid+`/billing`) || strings.Contains(body, "/billing/continue") {
+ t.Fatalf("a member was offered a billing form:\n%s", body)
+ }
+ if !strings.Contains(body, `href="/a/`+pf.acct.Sqid+`/billing"`) && !strings.Contains(body, `/billing" aria-current="page"`) {
+ t.Fatalf("no billing nav link:\n%s", body)
+ }
+
+ // The owner of a free account is offered the three paid plans.
+ status, body = pf.page(t, "")
+ if status != http.StatusOK {
+ t.Fatalf("owner = %d", status)
+ }
+ for _, want := range []string{
+ `action="/a/` + pf.acct.Sqid + `/billing/checkout"`, `name="csrf" value="` + pf.csrf + `"`,
+ `name="plan" value="personal"`, `name="plan" value="community"`, `name="plan" value="business"`,
+ esc(billingCopy["buy.title"]), esc(billingCopy["buy.button"]),
+ `name="pack_apps"`, `max="20"`,
+ } {
+ if !strings.Contains(body, want) {
+ t.Errorf("owner page is missing %q", want)
+ }
+ }
+ if strings.Contains(body, `name="plan" value="free"`) {
+ t.Error("the free plan was offered for sale")
+ }
+ if strings.Contains(body, esc(billingCopy["notice.owners_only"])) {
+ t.Error("the owner was told only owners can act")
+ }
+ // Plans in order of their lowest yearly total.
+ if i, j, k := strings.Index(body, `value="personal"`), strings.Index(body, `value="community"`), strings.Index(body, `value="business"`); !(i < j && j < k) {
+ t.Errorf("plans out of order: personal %d, community %d, business %d", i, j, k)
+ }
+ // A preselected plan from the query.
+ _, body = pf.page(t, "plan=community")
+ if !strings.Contains(body, `name="plan" value="community" checked`) {
+ t.Error("?plan=community did not preselect it")
+ }
+
+ // Not ready: the notice, and nothing to buy.
+ pf.srv.billing.ready.Store(false)
+ _, body = pf.page(t, "")
+ if !strings.Contains(body, esc(billingCopy["notice.not_ready"])) || strings.Contains(body, "/billing/checkout") {
+ t.Fatalf("not ready page:\n%s", body)
+ }
+}
+
+func TestBillingPageCurrencyRefusals(t *testing.T) {
+ pf := newBillingPageFixture(t)
+ radio := func(code string) string { return `name="currency" value="` + code + `" checked` }
+
+ // GeoIP: a German address preselects eur.
+ sw := geo.NewSwappable()
+ db, err := geo.OpenMMDB("../geo/testdata/GeoIP2-City-Test.mmdb")
+ if err != nil {
+ t.Fatal(err)
+ }
+ sw.Swap(db)
+ pf.srv.cfg.GeoIPReader = sw
+ if got := pf.srv.requestCountry(httptest.NewRequest(http.MethodGet, "/", nil)); got != "" {
+ t.Fatalf("a loopback client's country = %q, want none", got)
+ }
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ req.RemoteAddr = "[2a02:d180::1]:443"
+ if got := pf.srv.requestCountry(req); got != "DE" {
+ t.Fatalf("requestCountry = %q, want DE", got)
+ }
+ status, _, body := serveAs(t, pf.consoleFixture, pf.owner, pf.billingPath(""), "[2a02:d180::1]:443")
+ if status != http.StatusOK || !strings.Contains(body, radio("eur")) {
+ t.Fatalf("German visitor: %d, want eur preselected:\n%s", status, body)
+ }
+ // No country: the book's default.
+ if _, body := pf.page(t, ""); !strings.Contains(body, radio("usd")) {
+ t.Error("no country: usd not preselected")
+ }
+ // An explicit sold code wins over the country.
+ if _, _, body := serveAs(t, pf.consoleFixture, pf.owner, pf.billingPath("currency=gbp"), "[2a02:d180::1]:443"); !strings.Contains(body, radio("gbp")) {
+ t.Error("?currency=gbp not preselected")
+ }
+
+ _, baseline := pf.page(t, "")
+ for _, c := range []struct{ raw, shown string }{
+ {"jpy", "jpy"}, {"USD", "usd"}, {"usd1", "usd1"}, {"<script>", ""}, {"usdollars", ""}, {"us d", ""},
+ } {
+ _, body := pf.page(t, "currency="+url.QueryEscape(c.raw))
+ want := billingCopy["currency.refused_unshown"]
+ if c.shown != "" {
+ want = fmt.Sprintf(billingCopy["currency.refused"], c.shown)
+ }
+ if !strings.Contains(body, esc(want)) {
+ t.Errorf("currency=%q: missing %q", c.raw, want)
+ }
+ for _, code := range plans.SoldCurrencies {
+ if strings.Contains(body, radio(code)) {
+ t.Errorf("currency=%q: %s was preselected", c.raw, code)
+ }
+ }
+ if strings.Contains(body, "&lt;script") || strings.Count(body, "<script") != strings.Count(baseline, "<script") {
+ t.Errorf("currency=%q: the value reached the page", c.raw)
+ }
+ }
+
+ // currencyQuery itself.
+ book := pf.srv.billing.cfg.Book
+ for _, c := range []struct {
+ raw, code string
+ refused bool
+ shown string
+ }{
+ {"", "", false, ""}, {"eur", "eur", false, ""}, {"EUR", "", true, "eur"}, {"jpy", "", true, "jpy"},
+ {"usd1", "", true, "usd1"}, {"<script>", "", true, ""}, {"abcdefghi", "", true, ""},
+ } {
+ code, refused, shown := currencyQuery(c.raw, book)
+ if code != c.code || refused != c.refused || shown != c.shown {
+ t.Errorf("currencyQuery(%q) = %q %v %q, want %q %v %q", c.raw, code, refused, shown, c.code, c.refused, c.shown)
+ }
+ }
+}
+
+func TestBillingPageFixedCurrency(t *testing.T) {
+ pf := newBillingPageFixture(t)
+ // An earlier subscription, now ended, fixed the account's currency.
+ if err := pf.st.PutBillingState(billingAccount{AccountID: pf.acct.ID, Subscription: "sub_old", State: billing.StateEnded,
+ Currency: "eur", PaidPacks: map[string]int{}}); err != nil {
+ t.Fatal(err)
+ }
+ _, body := pf.page(t, "")
+ if !strings.Contains(body, `type="hidden" name="currency" value="eur"`) || strings.Contains(body, `type="radio" name="currency"`) {
+ t.Fatalf("fixed currency: want a hidden eur and no radios:\n%s", body)
+ }
+ if strings.Contains(body, esc(fmt.Sprintf(billingCopy["currency.fixed"], "eur"))) {
+ t.Error("no explicit currency, yet the fixed notice shows")
+ }
+ if _, body := pf.page(t, "currency=eur"); strings.Contains(body, esc(fmt.Sprintf(billingCopy["currency.fixed"], "eur"))) {
+ t.Error("the fixed currency itself showed the fixed notice")
+ }
+ for _, q := range []string{"usd", "jpy", "<script>"} {
+ _, body := pf.page(t, "currency="+url.QueryEscape(q))
+ if !strings.Contains(body, esc(fmt.Sprintf(billingCopy["currency.fixed"], "eur"))) {
+ t.Errorf("currency=%q on a eur account: no fixed notice", q)
+ }
+ if !strings.Contains(body, `type="hidden" name="currency" value="eur"`) {
+ t.Errorf("currency=%q: the fixed currency is not the one posted", q)
+ }
+ }
+ // Prices show in the fixed currency.
+ if !strings.Contains(body, esc(fmt.Sprintf(billingCopy["plan.price"], plans.FormatMinor("eur", 2400)))) {
+ t.Errorf("personal's eur price is missing:\n%s", body)
+ }
+}
+
+func TestBillingPageTeamTotals(t *testing.T) {
+ pf := newBillingPageFixture(t)
+ add := func(n int) {
+ for i := 0; i < n; i++ {
+ addr := fmt.Sprintf("m%d-%d@example.com", i, time.Now().UnixNano())
+ if err := pf.st.AddMember(pf.acct.ID, addr, RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ total := func(minor int64) string {
+ return esc(fmt.Sprintf(billingCopy["team.total"], plans.FormatMinor("usd", minor)))
+ }
+
+ add(3) // 4 members: billed at 10
+ _, body := pf.page(t, "")
+ for _, want := range []string{
+ total(6000), total(60000),
+ esc(fmt.Sprintf(billingCopy["team.price"], plans.FormatMinor("usd", 600), 10)),
+ esc(fmt.Sprintf(billingCopy["team.price"], plans.FormatMinor("usd", 6000), 10)),
+ esc(fmt.Sprintf(billingCopy["plan.price"], plans.FormatMinor("usd", 2800))),
+ } {
+ if !strings.Contains(body, want) {
+ t.Errorf("4 members: missing %q", want)
+ }
+ }
+ add(8) // 12 members
+ _, body = pf.page(t, "")
+ for _, want := range []string{total(7200), total(72000)} {
+ if !strings.Contains(body, want) {
+ t.Errorf("12 members: missing %q", want)
+ }
+ }
+}
+
+// TestBillingPagePaidFacts: a paid team account shows its plan, packs,
+// members against paid seats, currency and renewal date, and the change,
+// stop and portal forms, each with CSRF.
+func TestBillingPagePaidFacts(t *testing.T) {
+ pf := newBillingPageFixture(t)
+ if _, err := pf.st.SetAccountPlan(pf.acct.ID, "community", map[string]int{"apps": 2}, 12, PlanSourceBilling, nil, "billing", "billing", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := pf.st.PutBillingState(billingAccount{AccountID: pf.acct.ID, Subscription: "sub_1", State: billing.StatePaid, Live: true,
+ Currency: "gbp", PeriodEnd: periodEnd, Plan: "community", Seats: 12, PaidSeats: 12, PaidPacks: map[string]int{"apps": 2}}); err != nil {
+ t.Fatal(err)
+ }
+ // A view makes no provider request (the request budget's 0).
+ pf.fake.Lock()
+ pf.fake.CallsBy = map[string]int{}
+ pf.fake.Unlock()
+ defer func() {
+ pf.fake.Lock()
+ defer pf.fake.Unlock()
+ for k, n := range pf.fake.CallsBy {
+ if n != 0 {
+ t.Errorf("the billing page made %d %s requests, want none", n, k)
+ }
+ }
+ }()
+ _, body := pf.page(t, "")
+ base := `action="/a/` + pf.acct.Sqid + `/billing/`
+ for _, want := range []string{
+ esc(fmt.Sprintf(billingCopy["team.members"], 1, 12)),
+ esc(fmt.Sprintf(billingCopy["renews"], periodEnd.UTC().Format("2 January 2006"))),
+ esc(fmt.Sprintf(billingCopy["fact.currency"], "gbp")),
+ base + `change"`, base + `renewal"`, base + `portal"`,
+ `name="pack" value="apps"`, `name="quantity" value="2"`,
+ `name="plan" value="business"`, esc(fmt.Sprintf(billingCopy["button.upgrade"], "Business")),
+ esc(billingCopy["button.stop"]), esc(billingCopy["button.portal"]),
+ } {
+ if !strings.Contains(body, want) {
+ t.Errorf("paid page is missing %q", want)
+ }
+ }
+ if strings.Contains(body, base+`checkout"`) {
+ t.Error("a paid account was offered checkout")
+ }
+ if n, m := strings.Count(body, `method="post" action="/a/`+pf.acct.Sqid+`/billing/`), strings.Count(body, `name="csrf" value="`+pf.csrf+`"`); m < n || n == 0 {
+ t.Errorf("%d billing forms, %d CSRF fields", n, m)
+ }
+
+ // Renewal stopped: the end date, Resume, and no Stop.
+ b, _ := pf.st.BillingAccount(pf.acct.ID)
+ b.CancelAtPeriodEnd = true
+ if err := pf.st.PutBillingState(*b); err != nil {
+ t.Fatal(err)
+ }
+ _, body = pf.page(t, "")
+ if !strings.Contains(body, esc(fmt.Sprintf(billingCopy["notice.ending"], periodEnd.UTC().Format("2 January 2006")))) ||
+ !strings.Contains(body, `name="renewal" value="resume"`) || strings.Contains(body, `name="renewal" value="stop"`) {
+ t.Errorf("ending page:\n%s", body)
+ }
+ b.CancelAtPeriodEnd = false
+
+ // Seat drift adds Match seats and its notice.
+ b.SeatDriftAt, b.SeatDriftMembers = time.Now(), 10
+ if err := pf.st.PutBillingState(*b); err != nil {
+ t.Fatal(err)
+ }
+ _, body = pf.page(t, "")
+ if !strings.Contains(body, esc(fmt.Sprintf(billingCopy["notice.seat_drift"], 12, 10))) || !strings.Contains(body, base+`seats"`) {
+ t.Errorf("seat drift page:\n%s", body)
+ }
+
+ // An unresolved operation offers Confirm now.
+ if err := pf.st.BeginBillingOp(billingOp{ID: "op_page", AccountID: pf.acct.ID, Subscription: "sub_1", Kind: opPack, PeriodEnd: periodEnd,
+ Target: opTarget{Quantities: map[string]int64{"p": 1}}, StartQuantity: knownStart(2), Prepared: billing.Prepared{Kind: billing.PreparedChange, Method: "POST", Path: "/x", Key: "op:op_page"},
+ State: opUnresolved, CreatedAt: time.Now()}); err != nil {
+ t.Fatal(err)
+ }
+ _, body = pf.page(t, "")
+ if !strings.Contains(body, esc(billingCopy["notice.confirming"])) || !strings.Contains(body, base+`confirm"`) {
+ t.Errorf("unresolved op page:\n%s", body)
+ }
+
+ // An open problem wins.
+ if _, err := pf.st.OpenBillingProblem(pf.acct.ID, "sub_1", problemSeatsUnpaid, "", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ _, body = pf.page(t, "")
+ if !strings.Contains(body, esc(billingCopy["notice.seats_unpaid"])) || strings.Contains(body, base+`confirm"`) {
+ t.Errorf("seats unpaid page:\n%s", body)
+ }
+}
+
+// TestBillingPageOpenIntent: an open Checkout offers continue (a GET, so
+// the session token never rides in a URL) and start over (the intent's
+// own request, posted with CSRF).
+func TestBillingPageOpenIntent(t *testing.T) {
+ pf := newBillingPageFixture(t)
+ ci := testIntent(pf.acct.ID, "ci_page")
+ ci.State = intentOpen
+ if err := pf.st.PutCheckoutIntent(ci); err != nil {
+ t.Fatal(err)
+ }
+ _, body := pf.page(t, "")
+ for _, want := range []string{
+ esc(billingCopy["notice.checkout_open"]),
+ `method="get" action="/a/` + pf.acct.Sqid + `/billing/continue"`,
+ `action="/a/` + pf.acct.Sqid + `/billing/checkout"`, `name="start_over" value="1"`,
+ `name="plan" value="community"`, `name="pack_apps" value="2"`, `name="pack_email" value="1"`,
+ } {
+ if !strings.Contains(body, want) {
+ t.Errorf("open intent page is missing %q", want)
+ }
+ }
+ if strings.Contains(body, "continue?csrf") || strings.Contains(body, esc(billingCopy["buy.title"])) {
+ t.Errorf("open intent page:\n%s", body)
+ }
+}
+
+// ---- /upgrade ---------------------------------------------------------------
+
+func TestUpgradeEntry(t *testing.T) {
+ t.Run("billing off", func(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := newBrowser(t)
+ if status, _, body := get(t, c, fx.ts.URL+"/upgrade?plan=personal"); status != http.StatusNotFound || body != unroutedBody(t, fx, c) {
+ t.Fatalf("signed out, billing off = %d", status)
+ }
+ fx.setUser("paul@keymail.dev")
+ signUp(t, fx, c, "code-upgrade-off")
+ if status, _, _ := get(t, c, fx.ts.URL+"/upgrade"); status != http.StatusNotFound {
+ t.Fatalf("signed in, billing off = %d", status)
+ }
+ })
+
+ pf := newBillingPageFixture(t)
+ signedOut := func(query string) string {
+ t.Helper()
+ status, loc, _ := get(t, newBrowser(t), pf.ts.URL+"/upgrade"+query)
+ if status != http.StatusSeeOther {
+ t.Fatalf("signed out %q = %d, want 303", query, status)
+ }
+ return loc
+ }
+ for _, c := range []struct{ query, next string }{
+ {"", "/upgrade"},
+ {"?plan=community&currency=eur", "/upgrade?currency=eur&plan=community"},
+ {"?plan=../x", "/upgrade"},
+ {"?plan=free", "/upgrade"},
+ {"?plan=business&currency=" + url.QueryEscape("<script>"), "/upgrade?currency=invalid&plan=business"},
+ {"?currency=USD", "/upgrade?currency=USD"},
+ {"?currency=abcdefghi", "/upgrade?currency=invalid"},
+ // Hostile next variants never reach the redirect.
+ {"?next=" + url.QueryEscape("//evil.example") + "&plan=personal", "/upgrade?plan=personal"},
+ {"?next=" + url.QueryEscape("https://evil.example/"), "/upgrade"},
+ {"?plan=personal%0d%0aLocation:%20https://evil.example", "/upgrade"},
+ {"?plan=" + url.QueryEscape("/\\evil.example"), "/upgrade"},
+ } {
+ loc := signedOut(c.query)
+ if want := "/?next=" + url.QueryEscape(c.next); loc != want {
+ t.Errorf("signed out %q -> %q, want %q", c.query, loc, want)
+ }
+ if safeNext(c.next) != c.next {
+ t.Errorf("next %q is not local", c.next)
+ }
+ }
+ // The front door carries it into its form.
+ _, _, home := get(t, newBrowser(t), pf.ts.URL+signedOut("?plan=community"))
+ if !strings.Contains(home, `name="next" value="`+esc("/upgrade?plan=community")+`"`) {
+ t.Fatalf("the front door dropped next:\n%s", home)
+ }
+
+ // Owner of one: straight to its billing page, the query kept.
+ status, loc, _ := get(t, pf.owner, pf.ts.URL+"/upgrade?plan=community&currency=eur&next=//evil.example")
+ if want := pf.billingPath("currency=eur&plan=community"); status != http.StatusSeeOther || loc != want {
+ t.Fatalf("owner of one = %d -> %q, want 303 -> %q", status, loc, want)
+ }
+ if _, loc, _ := get(t, pf.owner, pf.ts.URL+"/upgrade"); loc != pf.billingPath("") {
+ t.Fatalf("owner of one, no query -> %q", loc)
+ }
+
+ // Owner of two: the picker, the most recent first.
+ second := domains.Sqid(502)
+ if err := pf.st.CreateAccount(502, second, "later", "owner"+pf.acct.Sqid+"@example.com", time.Unix(1_800_000_000, 0)); err != nil {
+ t.Fatal(err)
+ }
+ status, _, body := get(t, pf.owner, pf.ts.URL+"/upgrade?plan=business")
+ if status != http.StatusOK || !strings.Contains(body, esc(billingCopy["pick.title"])) {
+ t.Fatalf("owner of two = %d:\n%s", status, body)
+ }
+ first, later := `href="/a/`+pf.acct.Sqid+`/billing?plan=business"`, `href="/a/`+second+`/billing?plan=business"`
+ if i, j := strings.Index(body, later), strings.Index(body, first); i < 0 || j < 0 || i > j {
+ t.Fatalf("picker order: later at %d, first at %d:\n%s", i, j, body)
+ }
+
+ // A member who owns nothing: the not-owner page.
+ 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-upgrade-member")
+ status, loc, body = get(t, member, pf.ts.URL+"/upgrade?plan=personal")
+ if status != http.StatusOK || loc != "" || !strings.Contains(body, esc(billingCopy["upgrade.not_owner"])) ||
+ !strings.Contains(body, esc(billingCopy["upgrade.not_owner_title"])) {
+ t.Fatalf("owner of none = %d -> %q:\n%s", status, loc, body)
+ }
+}
+
+func TestUpgradeAfterSignupLandsOnBilling(t *testing.T) {
+ bf := newBillingFixture(t)
+ bf.srv.billing.ready.Store(true)
+ c := newBrowser(t)
+ status, loc, _ := get(t, c, bf.ts.URL+"/upgrade?plan=personal&currency=gbp")
+ if status != http.StatusSeeOther || !strings.HasPrefix(loc, "/?next=") {
+ t.Fatalf("signed out = %d -> %q", status, loc)
+ }
+ u, _ := url.Parse(loc)
+ next := u.Query().Get("next")
+
+ // A brand-new person signs up with that next.
+ bf.setUser("newcomer@keymail.dev")
+ status, loc = keymailWalk(t, bf.consoleFixture, c, "?next="+url.QueryEscape(next), "code-upgrade-new")
+ if status != http.StatusSeeOther || loc != next {
+ t.Fatalf("callback = %d -> %q, want 303 -> %q", status, loc, next)
+ }
+ accts, err := bf.st.AccountsFor("newcomer@keymail.dev")
+ if err != nil || len(accts) != 1 || accts[0].Role != RoleOwner {
+ t.Fatalf("accounts = %+v, %v; want the one minted on landing", accts, err)
+ }
+ status, loc, _ = get(t, c, bf.ts.URL+loc)
+ if want := "/a/" + accts[0].Sqid + "/billing?currency=gbp&plan=personal"; status != http.StatusSeeOther || loc != want {
+ t.Fatalf("upgrade after signup = %d -> %q, want %q", status, loc, want)
+ }
+ status, _, body := get(t, c, bf.ts.URL+loc)
+ if status != http.StatusOK || !strings.Contains(body, `name="plan" value="personal" checked`) ||
+ !strings.Contains(body, `name="currency" value="gbp" checked`) {
+ t.Fatalf("billing page = %d:\n%s", status, body)
+ }
+}
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 8d96f803b..e01d7b7df 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -800,6 +800,7 @@ var claimFixtures = map[string]claimFixture{
"route GET /a/{sqid}/apps/{app}/releases": claimRead("renders releases"),
"route GET /a/{sqid}/apps/{app}/settings": claimRead("renders app settings"),
"route GET /a/{sqid}/apps/{app}/settings/{section}": claimRead("renders one app settings section"),
+ "route GET /a/{sqid}/billing": claimRead("renders the billing page (plans 6b) from stored billing facts, the plan row and the member count; no provider request; names no app"),
"route GET /a/{sqid}/fleet": claimRead("renders the account's fleet tab"),
"route GET /a/{sqid}/fleet/byo": claimRead("renders bring-your-own-box instructions"),
"route GET /a/{sqid}/fleets/{fleet}": claimRead("renders one fleet's boxes and placements"),
@@ -884,6 +885,7 @@ var claimFixtures = map[string]claimFixture{
"route GET /healthz": claimRead("answers ok and the build"),
"route GET /invite/{token}": claimRead("shows an invitation; joining is the POST"),
"route GET /settings": claimRead("personal settings: the caller's own tokens"),
+ "route GET /upgrade": claimRead("the pricing page's upgrade entry (plans 6b): redirects to the billing page of the account the caller owns, or the front door; writes nothing"),
"route GET /{$}": claimRead("the front door: redirects or renders sign-in"),
// GET that writes: a replica file download streams versioned objects (reads
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go
index 4d05a078e..ab66cb95f 100644
--- a/internal/console/claim_invariant_probes_read_test.go
+++ b/internal/console/claim_invariant_probes_read_test.go
@@ -144,6 +144,7 @@ var claimReadProbes = map[string]claimProbe{
"route GET /a/{sqid}/apps/{app}/settings": claimPageRead(nil, "/a/bab/apps/titogo/settings", "titogo"),
"route GET /a/{sqid}/apps/{app}/settings/{section}": claimPageRead(nil, "/a/bab/apps/titogo/settings/advanced",
"/apps/titogo/control-plane/set"),
+ "route GET /a/{sqid}/billing": claimPageRead(claimBillingWorld, "/a/bab/billing", "<h1>"+billingCopy["page.title"]+"</h1>"),
"route GET /a/{sqid}/fleet": claimPageRead(claimWorldFleet, "/a/bab/fleet", "pi"),
"route GET /a/{sqid}/fleet/byo": claimPageRead(nil, "/a/bab/fleet/byo", "<h1>Bring your own fleet</h1>"),
"route GET /a/{sqid}/fleets/{fleet}": claimPageRead(claimWorldFleet, "/a/bab/fleets/pi", "<h1>pi</h1>"),
@@ -169,6 +170,8 @@ var claimReadProbes = map[string]claimProbe{
"route GET /apps/{app}": claimRedirectRead("/apps/kass", http.StatusFound, "/a/"),
"route GET /auth/cli/tokens": claimRedirectRead("/auth/cli/tokens", http.StatusSeeOther, "/settings"),
"route GET /{$}": claimRedirectRead("/", http.StatusFound, "/a/"),
+ "route GET /upgrade": {setup: claimBillingWorld, do: claimPageReply("/upgrade?plan=personal"), status: http.StatusSeeOther,
+ loc: "/a/bab/billing?plan=personal"},
// ---- the CLI's reads ----
"route GET /api/cli/apps": claimAPIRead(nil, "/api/cli/apps", `"sqid":"bab"`, `"kass"`),
diff --git a/internal/console/server.go b/internal/console/server.go
index 1f3a7b16b..866a20fcd 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -67,6 +67,8 @@ var tmplFS embed.FS
var templates = template.Must(template.New("").Funcs(template.FuncMap{
"fmtTime": func(t time.Time) string { return t.UTC().Format("2006-01-02 15:04 UTC") },
+ // billingText is a billing page string (billingpage_copy.go).
+ "billingText": func(key string) string { return billingCopy[key] },
// until renders a future horizon the way the cards speak: "~4h", never a
// timestamp โ€” the safety-delay strip's "goes live ~4h" and Task 6's
// summary strip both read it this way.
@@ -1565,6 +1567,9 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
// Plans 6b: an owner's Confirm now finishes a billing operation left
// without a definite outcome (billingops.go). 404 with billing off.
s.registerRoute("POST /a/{sqid}/billing/confirm", s.handleBillingConfirm)
+ // The billing page (billingpage.go): member-readable, its forms the
+ // owner's. 404 with billing off.
+ s.registerRoute("GET /a/{sqid}/billing", s.handleBilling)
// Go 1.22's mux prefers this literal over apps/{app} below โ€” exactly why
// "new" must be a reserved app name (claimApp): an app so named could
// never be viewed.
@@ -1681,6 +1686,10 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
s.registerRoute("GET /invite/{token}", s.handleInvitePage)
s.registerRoute("POST /invite/{token}", s.handleAcceptInvite)
s.registerRoute("GET /accounts/new", s.handleNewAccountForm)
+ // The upgrade entry the public pricing page links to (billingpage.go,
+ // plans 6b Call 1): signed out, the front door with next; signed in,
+ // the billing page of the account the viewer owns. 404 with billing off.
+ s.registerRoute("GET /upgrade", s.handleUpgrade)
s.registerRoute("POST /accounts/new", s.handleNewAccount)
// The pre-accounts URLs, kept as redirects so old links and bookmarks
// still land somewhere sensible rather than 404ing.
@@ -1919,7 +1928,7 @@ type page struct {
AccountReview AccountReview
MismatchCopy MismatchCopy
- ActiveNav string // account nav section this page sits in: "apps" | "fleet" | "team" | "settings"
+ ActiveNav string // account nav section this page sits in: "apps" | "fleet" | "team" | "billing" | "settings"
ActiveTab string // app pages: "overview" | "releases" | "instances" | "activity" | "settings"
AppName string // app pages: the {app} segment, for the tab bar and eyebrow
@@ -1961,6 +1970,15 @@ type page struct {
PlanKeepURL, PlanKeepLink string
// PlanKeep is the keep page's body (plans 4d).
PlanKeep *planKeepView
+ // Billing is the billing page's body (plans 6b, billingpage.go).
+ Billing *billingView
+ // BillingPick is /upgrade's picker: the accounts the viewer owns, the
+ // most recent first; BillingPickQuery the kept query each link carries
+ // ("" or "?..."), built from /upgrade's kept values only.
+ BillingPick []Account
+ BillingPickQuery string
+ // BillingNav shows the account nav's billing link: billing is on.
+ BillingNav bool
// planSeen are the over rows behind PlanNotices when the viewer owns
// the account; render records them as notice once the page is written.
planSeen []capState
@@ -3504,6 +3522,7 @@ func (s *Server) accountPage(w http.ResponseWriter, r *http.Request, addr, raw s
Address: addr, CSRF: raw,
Account: acct, Role: role, Base: "/a/" + url.PathEscape(acct.Sqid),
CanPromote: s.cfg.Key != nil,
+ BillingNav: s.billing != nil,
}
p.Flash, p.FlashErr = s.takeFlash(w, r)
if accts, err := s.store.AccountsFor(addr); err != nil {
diff --git a/internal/console/templates/billing.html b/internal/console/templates/billing.html
new file mode 100644
index 000000000..1c37c14ea
--- /dev/null
+++ b/internal/console/templates/billing.html
@@ -0,0 +1,101 @@
+{{define "billing"}}{{template "top" .}}
+{{if .Flash}}<p class="banner">{{.Flash}}</p>{{end}}
+{{if .FlashErr}}<p class="banner error">{{.FlashErr}}</p>{{end}}
+<div class="pagehead">
+ <p class="eyebrow">Account ยท {{.Account.Name}}</p>
+ <h1>{{billingText "page.title"}}</h1>
+</div>
+{{with .Billing}}
+{{if .Notice}}<p class="banner">{{.Notice}}</p>{{end}}
+{{if .OwnersOnly}}<p class="banner">{{.OwnersOnly}}</p>{{end}}
+{{if .CurrencyNotice}}<p class="banner error">{{.CurrencyNotice}}</p>{{end}}
+<ul>
+ {{range .Facts}}<li>{{.}}</li>
+ {{end}}
+</ul>
+<div class="settings-row">
+ {{if .Offers.Confirm}}<form method="post" action="{{$.Base}}/billing/confirm">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ <button type="submit">{{billingText "button.confirm"}}</button>
+ </form>{{end}}
+ {{if .Offers.Continue}}<form method="get" action="{{$.Base}}/billing/continue">
+ <button type="submit">{{billingText "button.continue"}}</button>
+ </form>{{end}}
+ {{if .Offers.StartOver}}<form method="post" action="{{$.Base}}/billing/checkout">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ {{range .StartOver}}<input type="hidden" name="{{.Name}}" value="{{.Value}}">
+ {{end}}<button class="linkish" type="submit">{{billingText "button.start_over"}}</button>
+ </form>{{end}}
+ {{if .Offers.MatchSeats}}<form method="post" action="{{$.Base}}/billing/seats">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ <button type="submit">{{billingText "button.match_seats"}}</button>
+ </form>{{end}}
+ {{if .Offers.Resume}}<form method="post" action="{{$.Base}}/billing/renewal">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ <input type="hidden" name="renewal" value="resume">
+ <button type="submit">{{billingText "button.resume"}}</button>
+ </form>{{end}}
+ {{if .Offers.Portal}}<form method="post" action="{{$.Base}}/billing/portal">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ <button type="submit">{{billingText "button.portal"}}</button>
+ </form>{{end}}
+</div>
+{{with .Buy}}
+<h2>{{billingText "buy.title"}}</h2>
+<form method="post" action="{{$.Base}}/billing/checkout">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ {{range .Plans}}<p>
+ <label><input type="radio" name="plan" value="{{.Name}}"{{if .Checked}} checked{{end}} required> {{.Label}}</label>
+ <span class="small">{{.Price}}{{if .Total}} {{.Total}}{{end}}</span>
+ </p>
+ {{end}}
+ <div class="tablewrap">
+ <table>
+ {{range .Packs}}<tr>
+ <td><label for="pack-{{.Name}}">{{.Name}}</label></td>
+ <td><input type="number" id="pack-{{.Name}}" name="pack_{{.Name}}" min="0" max="{{.Max}}" step="1" value="{{.Value}}"></td>
+ <td class="small">{{.Price}}</td>
+ </tr>
+ {{end}}
+ </table>
+ </div>
+ {{if .FixedCurrency}}<p>{{.FixedCurrency}}<input type="hidden" name="currency" value="{{.FixedCurrency}}"></p>
+ {{else}}<p>{{billingText "currency.legend"}}:
+ {{range .Currencies}}<label><input type="radio" name="currency" value="{{.Code}}"{{if .Checked}} checked{{end}} required> {{.Code}}</label>
+ {{end}}
+ </p>{{end}}
+ <button type="submit">{{billingText "buy.button"}}</button>
+</form>
+{{end}}
+{{with .Change}}
+<div class="tablewrap">
+<table>
+ {{range .Packs}}<tr>
+ <td><label for="change-{{.Name}}">{{.Name}}</label></td>
+ <td class="small">{{.Price}}</td>
+ <td><form method="post" action="{{$.Base}}/billing/change">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ <input type="hidden" name="pack" value="{{.Name}}">
+ <input type="number" id="change-{{.Name}}" name="quantity" value="{{.Value}}" min="0" max="{{.Max}}" step="1">
+ <button class="linkish" type="submit">{{billingText "button.change"}}</button>
+ </form></td>
+ </tr>
+ {{end}}
+</table>
+</div>
+{{if .Upgrades}}<div class="settings-row">
+ {{range .Upgrades}}<form method="post" action="{{$.Base}}/billing/change">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ <input type="hidden" name="plan" value="{{.Name}}">
+ <button type="submit">{{.Label}}</button>
+ </form>
+ {{end}}
+</div>{{end}}
+{{end}}
+{{if .Offers.Stop}}<form method="post" action="{{$.Base}}/billing/renewal">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ <input type="hidden" name="renewal" value="stop">
+ <button class="linkish danger" type="submit">{{billingText "button.stop"}}</button>
+</form>{{end}}
+{{end}}
+{{template "bottom" .}}{{end}}
diff --git a/internal/console/templates/billing_pick.html b/internal/console/templates/billing_pick.html
new file mode 100644
index 000000000..713dc0ea8
--- /dev/null
+++ b/internal/console/templates/billing_pick.html
@@ -0,0 +1,13 @@
+{{define "billing_pick"}}{{template "top" .}}
+<h1>{{billingText "pick.title"}}</h1>
+<div class="tablewrap">
+<table>
+ {{range .BillingPick}}
+ <tr>
+ <td><a href="/a/{{.Sqid}}/billing{{$.BillingPickQuery}}">{{.Name}}</a></td>
+ <td>{{.CreatedAt.UTC.Format "2 January 2006"}}</td>
+ </tr>
+ {{end}}
+</table>
+</div>
+{{template "bottom" .}}{{end}}
diff --git a/internal/console/templates/layout.html b/internal/console/templates/layout.html
index b9fecac85..892799748 100644
--- a/internal/console/templates/layout.html
+++ b/internal/console/templates/layout.html
@@ -581,6 +581,7 @@
<a href="{{.Nav}}/"{{if eq .ActiveNav "apps"}} aria-current="page"{{end}}>Apps</a>
<a href="{{.Nav}}/fleet"{{if eq .ActiveNav "fleet"}} aria-current="page"{{end}}>Fleet</a>
<a href="{{.Nav}}/team"{{if eq .ActiveNav "team"}} aria-current="page"{{end}}>Team</a>
+ {{if .BillingNav}}<a href="{{.Nav}}/billing"{{if eq .ActiveNav "billing"}} aria-current="page"{{end}}>{{billingText "page.title"}}</a>{{end}}
<a href="{{.Nav}}/settings"{{if eq .ActiveNav "settings"}} aria-current="page"{{end}}>Settings</a>
{{end}}
<a class="addr" href="/settings" title="Your settings">{{.Address}}</a>
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index d227eb6bb..aabff5e3f 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -29,6 +29,7 @@ route GET /a/{sqid}/apps/{app}/pipeline
route GET /a/{sqid}/apps/{app}/releases
route GET /a/{sqid}/apps/{app}/settings
route GET /a/{sqid}/apps/{app}/settings/{section}
+route GET /a/{sqid}/billing
route GET /a/{sqid}/fleet
route GET /a/{sqid}/fleet/byo
route GET /a/{sqid}/fleets/{fleet}
@@ -116,6 +117,7 @@ route GET /fleet/store
route GET /healthz
route GET /invite/{token}
route GET /settings
+route GET /upgrade
route GET /{$}
route PATCH /api/cli/apps/{account}/{app}/instances/{host}
route POST /a/{sqid}/analytics/setting