Phase 14, part 2: the owner's Billing page
Settings → Billing shows the team's plan, trial, people, agents, storage and next invoice. The owner subscribes through Stripe Checkout (monthly, or yearly when there's a price) and pays or reads invoices in Stripe's Customer Portal; admins see the plan only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -180,7 +180,7 @@ var actionLabels = map[string]string{
|
||||
"key-made": "made a new key for", "key-revoked": "revoked a key of",
|
||||
"asked-approval": "asked for approval to", "did-on-its-own": "did on its own:", "approved": "approved", "refused": "refused",
|
||||
"allowed-on-its-own": "let an agent act on its own:", "withdrew-on-its-own": "took back what an agent may do on its own:",
|
||||
"signin-settings": "changed how people sign in:", "team-created": "set up the team", "viewed-as": "looked at the team's data:", "team-suspended": "suspended the team", "team-restored": "restored the team",
|
||||
"signin-settings": "changed how people sign in:", "billing-checkout": "went to subscribe:", "team-created": "set up the team", "viewed-as": "looked at the team's data:", "team-suspended": "suspended the team", "team-restored": "restored the team",
|
||||
"domain-released": "released the domain", "exported": "exported", "downloaded-export": "downloaded the export", "team-deleting": "asked to delete the team", "team-undeleted": "undid the team's deletion", "invitations-resent": "sent the invitations again:", "domain-proved": "proved the domain", "agent-paused": "paused the agent", "agent-resumed": "resumed the agent", "agent-limits": "changed the limits of",
|
||||
"wrote-draft": "wrote a draft:", "edited-draft": "edited a draft:", "edited-change": "edited a proposed change to", "market-added": "added to the Market", "market-changed": "changed in the Market",
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/billing"
|
||||
"supermarket/internal/users"
|
||||
)
|
||||
|
||||
// Settings → Billing (the multi-tenant edition, with billing on): the
|
||||
// team's plan, people, storage and next invoice. The owner subscribes
|
||||
// through Stripe Checkout and pays, or reads the invoices, in Stripe's
|
||||
// Customer Portal; admins see the plan, not the payment details.
|
||||
|
||||
// billingStripe is the platform's Stripe account; tests replace it.
|
||||
func (s *Server) billingStripe() *billing.Stripe {
|
||||
st := s.st()
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
if st.stripe == nil && s.Config != nil && s.Config.StripeKey != "" {
|
||||
st.stripe = billing.NewStripe(s.Config.StripeKey)
|
||||
}
|
||||
return st.stripe
|
||||
}
|
||||
|
||||
type billingData struct {
|
||||
Owner bool
|
||||
Account *billing.Account
|
||||
Plan *billing.Plan
|
||||
Paid *billing.Plan
|
||||
ReadOnly bool
|
||||
People int
|
||||
Agents int
|
||||
Storage int64
|
||||
StorageOf int64
|
||||
Invoice *billing.Invoice
|
||||
InvoiceErr string
|
||||
Yearly bool
|
||||
Problem string
|
||||
}
|
||||
|
||||
// people counts the team's people (not agents), invited ones too.
|
||||
func (s *Server) people() (people, agents int) {
|
||||
list, err := users.Members(s.platform(), s.team())
|
||||
if err != nil {
|
||||
return 0, 0
|
||||
}
|
||||
for _, m := range list {
|
||||
switch {
|
||||
case m.Kind == users.Agent && m.Status == users.Active:
|
||||
agents++
|
||||
case m.Kind == users.Person && m.Status != users.Disabled:
|
||||
people++
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Server) billingPage(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderBilling(w, r, "")
|
||||
}
|
||||
|
||||
func (s *Server) renderBilling(w http.ResponseWriter, r *http.Request, problem string) {
|
||||
if !s.billingOn() {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
v := viewerOf(r)
|
||||
a, err := billing.Get(s.platform(), s.team())
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
plan, ro := a.Effective(s.Plans, time.Now())
|
||||
d := billingData{Owner: v.Member.Role == users.Owner && !v.Viewing, Account: a, Plan: plan, ReadOnly: ro,
|
||||
Paid: s.Plans.Get(s.Plans.Paid), Problem: problem, Storage: a.StorageUsed}
|
||||
d.People, d.Agents = s.people()
|
||||
seats := a.Seats
|
||||
if seats == 0 {
|
||||
seats = d.People
|
||||
}
|
||||
d.StorageOf = plan.StorageBytes(seats, a.StorageBlocks)
|
||||
d.Yearly = d.Paid.PriceYear != ""
|
||||
if d.Owner && a.Customer != "" && a.Subscription != "" {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
d.Invoice, err = s.billingStripe().Upcoming(ctx, a.Customer)
|
||||
cancel()
|
||||
if err != nil {
|
||||
d.InvoiceErr = err.Error()
|
||||
}
|
||||
}
|
||||
s.render(w, r, "billing", page{Title: "Billing", Nav: "settings/billing", Data: d})
|
||||
}
|
||||
|
||||
// billingCheckout sends the owner to Stripe Checkout to subscribe.
|
||||
func (s *Server) billingCheckout(w http.ResponseWriter, r *http.Request) {
|
||||
v := s.owner(w, r)
|
||||
if v == nil || !s.billingOn() {
|
||||
if v != nil {
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
a, err := billing.Get(s.platform(), s.team())
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
paid := s.Plans.Get(s.Plans.Paid)
|
||||
price := paid.PriceMonth
|
||||
if r.PostFormValue("interval") == "year" && paid.PriceYear != "" {
|
||||
price = paid.PriceYear
|
||||
}
|
||||
if a.Customer == "" {
|
||||
t, _ := users.GetTeam(s.platform(), s.team())
|
||||
name := ""
|
||||
if t != nil {
|
||||
name = t.Name
|
||||
}
|
||||
if a.Customer, err = s.billingStripe().CreateCustomer(ctx, v.User.Email, name, s.team()); err != nil {
|
||||
s.renderBilling(w, r, sentence(err.Error())+".")
|
||||
return
|
||||
}
|
||||
if a.Plan == "" {
|
||||
a.Plan = s.Plans.Paid
|
||||
}
|
||||
if err := billing.Save(s.platform(), a, time.Now()); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
people, _ := s.people()
|
||||
addr, err := s.billingStripe().CheckoutURL(ctx, billing.Checkout{Customer: a.Customer, Price: price, Quantity: people, Team: s.team(),
|
||||
Success: s.PublicURL + "/settings/billing?msg=subscribed", Cancel: s.PublicURL + "/settings/billing", Tax: s.Plans.Tax})
|
||||
if err != nil {
|
||||
s.renderBilling(w, r, sentence(err.Error())+".")
|
||||
return
|
||||
}
|
||||
s.audit(r, "billing-checkout", paid.Name, fmt.Sprintf("%d people", people))
|
||||
http.Redirect(w, r, addr, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// billingPortal sends the owner to Stripe's Customer Portal.
|
||||
func (s *Server) billingPortal(w http.ResponseWriter, r *http.Request) {
|
||||
v := s.owner(w, r)
|
||||
if v == nil || !s.billingOn() {
|
||||
if v != nil {
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
return
|
||||
}
|
||||
a, err := billing.Get(s.platform(), s.team())
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
if a.Customer == "" {
|
||||
s.renderBilling(w, r, "Subscribe first: there are no payments or invoices yet.")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
addr, err := s.billingStripe().PortalURL(ctx, a.Customer, s.PublicURL+"/settings/billing")
|
||||
if err != nil {
|
||||
s.renderBilling(w, r, sentence(err.Error())+".")
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, addr, http.StatusSeeOther)
|
||||
}
|
||||
@@ -2,9 +2,11 @@ package web
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -138,3 +140,116 @@ func TestNoBillingNoLimits(t *testing.T) {
|
||||
t.Errorf("an account without billing: %+v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeStripe is the platform's Stripe for tests: it records the calls.
|
||||
type fakeStripe struct {
|
||||
srv *httptest.Server
|
||||
mu sync.Mutex
|
||||
calls []string // "POST /checkout/sessions price=…&quantity=…"
|
||||
qty string
|
||||
}
|
||||
|
||||
func newFakeStripe(t *testing.T, s *Server) *fakeStripe {
|
||||
t.Helper()
|
||||
f := &fakeStripe{}
|
||||
f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
f.mu.Lock()
|
||||
f.calls = append(f.calls, r.Method+" "+r.URL.Path+" "+r.Form.Encode())
|
||||
f.mu.Unlock()
|
||||
if u, _, ok := r.BasicAuth(); !ok || u != "sk_test_x" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case r.URL.Path == "/customers":
|
||||
w.Write([]byte(`{"id":"cus_123"}`))
|
||||
case r.URL.Path == "/checkout/sessions":
|
||||
w.Write([]byte(`{"url":"https://checkout.stripe.example/c/1"}`))
|
||||
case r.URL.Path == "/billing_portal/sessions":
|
||||
w.Write([]byte(`{"url":"https://billing.stripe.example/p/1"}`))
|
||||
case r.URL.Path == "/invoices/upcoming":
|
||||
w.Write([]byte(`{"amount_due":4500,"currency":"usd","next_payment_attempt":1800000000}`))
|
||||
case strings.HasPrefix(r.URL.Path, "/subscriptions/"):
|
||||
w.Write([]byte(`{"items":{"data":[{"id":"si_1"}]}}`))
|
||||
case strings.HasPrefix(r.URL.Path, "/subscription_items/"):
|
||||
f.mu.Lock()
|
||||
f.qty = r.PostForm.Get("quantity")
|
||||
f.mu.Unlock()
|
||||
w.Write([]byte(`{}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(f.srv.Close)
|
||||
s.Config.StripeKey = "sk_test_x"
|
||||
st := billing.NewStripe("sk_test_x")
|
||||
st.Base = f.srv.URL
|
||||
s.st().stripe = st
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fakeStripe) last(path string) string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for i := len(f.calls) - 1; i >= 0; i-- {
|
||||
if strings.Contains(f.calls[i], " "+path+" ") {
|
||||
return f.calls[i]
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestBillingPage(t *testing.T) {
|
||||
s, h := newBilled(t)
|
||||
f := newFakeStripe(t, s)
|
||||
c := signUp(t, h, "olu@acme.example", "Acme", "acme.example")
|
||||
u, _ := users.ByEmail(s.platform(), "olu@acme.example")
|
||||
list, _ := users.TeamsOf(s.platform(), u.ID)
|
||||
team := list[0].ID
|
||||
|
||||
body := as(h, c, http.MethodGet, "/settings/billing", nil).Body.String()
|
||||
if !strings.Contains(body, "Trial") || !strings.Contains(body, "$15") || !strings.Contains(body, "Subscribe with Stripe") || !strings.Contains(body, `value="year"`) {
|
||||
t.Errorf("billing page: %s", body)
|
||||
}
|
||||
rec := as(h, c, http.MethodPost, "/settings/billing/checkout", url.Values{"interval": {"year"}})
|
||||
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "https://checkout.stripe.example/c/1" {
|
||||
t.Fatalf("checkout: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
call := f.last("/checkout/sessions")
|
||||
for _, want := range []string{"line_items%5B0%5D%5Bprice%5D=price_year", "line_items%5B0%5D%5Bquantity%5D=1", "customer=cus_123", "client_reference_id=" + strconv.FormatInt(team, 10), "mode=subscription"} {
|
||||
if !strings.Contains(call, want) {
|
||||
t.Errorf("checkout lacks %s: %s", want, call)
|
||||
}
|
||||
}
|
||||
if strings.Contains(call, "automatic_tax") {
|
||||
t.Error("tax without asking for it")
|
||||
}
|
||||
if a, _ := billing.Get(s.platform(), team); a.Customer != "cus_123" {
|
||||
t.Errorf("customer not kept: %+v", a)
|
||||
}
|
||||
// With a subscription: the next invoice, and the portal.
|
||||
setAccount(t, s, team, func(a *billing.Account) { a.Status, a.Subscription = billing.Active, "sub_1" })
|
||||
if body := as(h, c, http.MethodGet, "/settings/billing", nil).Body.String(); !strings.Contains(body, "$45") || strings.Contains(body, "Subscribe with Stripe") {
|
||||
t.Errorf("active: %s", body)
|
||||
}
|
||||
if rec := as(h, c, http.MethodPost, "/settings/billing/portal", url.Values{}); rec.Header().Get("Location") != "https://billing.stripe.example/p/1" {
|
||||
t.Errorf("portal: %d", rec.Code)
|
||||
}
|
||||
// An admin sees the plan, not the payments; a member, nothing.
|
||||
ts, _ := s.forTeam(team)
|
||||
admin := addUserIn(t, s, team, "ada@acme.example", users.Admin)
|
||||
adc := sessionIn(t, s, admin, team)
|
||||
body = as(h, adc, http.MethodGet, "/settings/billing", nil).Body.String()
|
||||
if !strings.Contains(body, "Paid") || strings.Contains(body, "$45") || strings.Contains(body, "Open Stripe") {
|
||||
t.Errorf("admin's view: %s", body)
|
||||
}
|
||||
if rec := as(h, adc, http.MethodPost, "/settings/billing/portal", url.Values{}); rec.Code != http.StatusForbidden {
|
||||
t.Errorf("admin to the portal: %d", rec.Code)
|
||||
}
|
||||
mem := addUserIn(t, s, team, "sam@acme.example", users.Member)
|
||||
if rec := as(h, sessionIn(t, s, mem, team), http.MethodGet, "/settings/billing", nil); rec.Code != http.StatusForbidden {
|
||||
t.Errorf("member: %d", rec.Code)
|
||||
}
|
||||
_ = ts
|
||||
}
|
||||
|
||||
@@ -101,6 +101,8 @@ type state struct {
|
||||
rotation atomic.Uint64 // which team's turn comes first (eachTeam)
|
||||
patterns []string // every route's pattern
|
||||
|
||||
stripe *billing.Stripe // the platform's Stripe account (billing)
|
||||
|
||||
mu sync.Mutex
|
||||
copies map[int64]*Server // each team's Server
|
||||
caches map[int64]*teamCache // each team's tokens and lists kept a while
|
||||
@@ -343,6 +345,9 @@ func (s *Server) Handler() (http.Handler, error) {
|
||||
// Signing in (the server edition).
|
||||
mux.HandleFunc("GET /setup/{token}", (*Server).setupPage)
|
||||
mux.HandleFunc("POST /setup/{token}", (*Server).setupSave)
|
||||
mux.HandleFunc("GET /settings/billing", (*Server).billingPage)
|
||||
mux.HandleFunc("POST /settings/billing/checkout", (*Server).billingCheckout)
|
||||
mux.HandleFunc("POST /settings/billing/portal", (*Server).billingPortal)
|
||||
mux.HandleFunc("GET /settings/data", (*Server).dataPage)
|
||||
mux.HandleFunc("POST /settings/data/export", (*Server).dataExport)
|
||||
mux.HandleFunc("GET /settings/data/exports/{name}", (*Server).dataDownload)
|
||||
@@ -707,6 +712,7 @@ func (s *Server) loadTemplates() error {
|
||||
"xreserve": twitter.URLReserve,
|
||||
// money shows cents as dollars: $1,234 or $12.50.
|
||||
"money": money,
|
||||
"int64": func(n int) int64 { return int64(n) },
|
||||
// usd shows float cents as whole dollars: $9,835.
|
||||
"usd": func(cents float64) string { return money(int64(math.Round(cents/100)) * 100) },
|
||||
"mul12": func(f float64) float64 { return 12 * f },
|
||||
@@ -807,6 +813,7 @@ type page struct {
|
||||
Teams []users.TeamInfo // the viewer\'s teams (multi-tenant), for the switcher
|
||||
TeamID int64 // the team they\'re working in
|
||||
Multi bool // the multi-tenant edition
|
||||
Billing bool // teams are billed (multi-tenant)
|
||||
Viewer *viewer // who's looking
|
||||
}
|
||||
|
||||
@@ -887,7 +894,7 @@ func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, p p
|
||||
p.Approvals = s.waitingFor(p.Viewer)
|
||||
p.Teams, p.TeamID = s.teamsOf(p.Viewer), s.team()
|
||||
}
|
||||
p.Multi = s.multi()
|
||||
p.Multi, p.Billing = s.multi(), s.billingOn()
|
||||
out, err := withCSRF(r, func(b *bytes.Buffer) error { return t.ExecuteTemplate(b, "layout.html", p) })
|
||||
if err != nil {
|
||||
s.Log.Error("render", "page", name, "err", err)
|
||||
@@ -951,6 +958,7 @@ var flashes = map[string]string{
|
||||
"exported": "Exported: %d rows. Download it below.",
|
||||
"undeleted": "The team won't be deleted: it's back as it was.",
|
||||
"secret-made": "The client's secret is made: add the entry below to the Core, then Test.",
|
||||
"subscribed": "Thank you: the subscription starts as soon as Stripe confirms it, in a minute.",
|
||||
"domain-released": "Released: another team can prove the domain now.",
|
||||
"invitations-resent": "Sent %d invitations again.",
|
||||
"view-needs-reason": "Give a reason and how long: it's recorded in the team's own log.",
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
{{define "content"}}{{template "settings-start" .}}{{with .Data}}
|
||||
<h2>Billing</h2>
|
||||
{{with .Problem}}<p class="error" role="alert">{{.}}</p>{{end}}
|
||||
<section class="card">
|
||||
<h3>{{.Plan.Name}}{{if eq .Account.Status "trialing"}} <span class="pill">trial</span>{{else if eq .Account.Status "past_due"}} <span class="pill warn">payment due</span>{{end}}{{if .ReadOnly}} <span class="pill warn">read-only</span>{{end}}</h3>
|
||||
<dl class="facts">
|
||||
{{if eq .Account.Status "trialing"}}<dt>Trial</dt><dd>until {{.Account.TrialEnds.Local.Format "2 Jan 2006"}}; then the Free plan, unless you subscribe</dd>{{end}}
|
||||
{{if eq .Account.Status "past_due"}}<dt>Payment</dt><dd class="error-text">due since {{.Account.PastDueSince.Local.Format "2 Jan 2006"}}: after 14 days the team becomes read-only, after 60 it's deleted</dd>{{end}}
|
||||
<dt>People</dt><dd>{{.People}}{{if .Plan.Seats}} of {{.Plan.Seats}}{{else if .Account.Seats}} · {{.Account.Seats}} paid for{{end}}</dd>
|
||||
<dt>Agents</dt><dd>{{.Agents}} of {{.Plan.Agents}}</dd>
|
||||
<dt>Storage</dt><dd>{{bytes .Storage}} of {{bytes .StorageOf}}</dd>
|
||||
<dt>Crawl</dt><dd>{{.Plan.CrawlPages}} pages, {{.Plan.CrawlEvery}}</dd>
|
||||
{{if .Owner}}{{with .Invoice}}<dt>Next invoice</dt><dd>{{money .AmountDue}} {{.Currency}}, {{.Date.Local.Format "2 Jan 2006"}}</dd>{{end}}{{with .InvoiceErr}}<dt>Next invoice</dt><dd class="muted small">{{.}}</dd>{{end}}{{end}}
|
||||
</dl>
|
||||
</section>
|
||||
{{if .Owner}}
|
||||
{{if ne .Account.Status "active"}}
|
||||
<form class="card" method="post" action="/settings/billing/checkout">
|
||||
<h3>Subscribe to {{.Paid.Name}}</h3>
|
||||
<p>{{money (int64 .Paid.PerSeatCents)}} a person a month, for every module, {{.Paid.Agents}} agents, {{.Paid.StorageGBPerSeat}} GB per person, and a daily SEO crawl of up to {{.Paid.CrawlPages}} pages. Today that's {{.People}} {{if eq .People 1}}person{{else}}people{{end}}.</p>
|
||||
{{if .Yearly}}<label class="check"><input type="radio" name="interval" value="month" checked> Monthly</label>
|
||||
<label class="check"><input type="radio" name="interval" value="year"> Yearly</label>{{end}}
|
||||
<button type="submit">Subscribe with Stripe</button>
|
||||
</form>
|
||||
{{end}}
|
||||
<form class="card" method="post" action="/settings/billing/portal">
|
||||
<h3>Payment and invoices</h3>
|
||||
<p class="help">The card, the billing address, past invoices, and cancelling: on Stripe's page.</p>
|
||||
<button type="submit" class="secondary" {{if not .Account.Customer}}disabled{{end}}>Open Stripe's billing page</button>
|
||||
</form>
|
||||
{{else}}
|
||||
<section class="card"><p class="help">The team's owner manages the subscription and its payments.</p></section>
|
||||
{{end}}
|
||||
{{end}}{{template "settings-end"}}{{end}}
|
||||
@@ -171,6 +171,7 @@
|
||||
<div class="nav-label">Data</div>
|
||||
<a href="/settings/backups" {{if eq .Nav "settings/backups"}}aria-current="page"{{end}}>{{template "icon" "backups"}}Backups</a>
|
||||
<a href="/settings/activity" {{if eq .Nav "settings/activity"}}aria-current="page"{{end}}>{{template "icon" "backups"}}Activity</a>
|
||||
{{if $.Billing}}<a href="/settings/billing" {{if eq $.Nav "settings/billing"}}aria-current="page"{{end}}>{{template "icon" "metrics"}}Billing</a>{{end}}
|
||||
{{with $.Viewer}}{{if and .User (eq (print .Member.Role) "owner")}}<a href="/settings/data" {{if eq $.Nav "settings/data"}}aria-current="page"{{end}}>{{template "icon" "backups"}}Your data</a>{{end}}{{end}}
|
||||
<a href="/settings/about" {{if eq .Nav "settings/about"}}aria-current="page"{{end}}>{{template "icon" "info"}}About</a>
|
||||
{{end}}
|
||||
|
||||
Reference in New Issue
Block a user