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>
256 lines
10 KiB
Go
256 lines
10 KiB
Go
package web
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"supermarket/internal/billing"
|
|
"supermarket/internal/users"
|
|
)
|
|
|
|
// newBilled is the multi-tenant edition with billing on.
|
|
func newBilled(t *testing.T) (*Server, http.Handler) {
|
|
t.Helper()
|
|
s, h := newMultiEdition(t)
|
|
p, err := billing.Load("", "price_month", "price_year", "price_block")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
s.Plans = p
|
|
return s, h
|
|
}
|
|
|
|
// signUp makes a team through the sign-up page (so it gets its trial).
|
|
func signUp(t *testing.T, h http.Handler, email, company, site string) *http.Cookie {
|
|
t.Helper()
|
|
rec := postForm(h, "/signup", url.Values{"email": {email}, "password": {"a long enough one"}, "company": {company}, "website": {site}})
|
|
c := cookieOf(rec, sessionCookie)
|
|
if rec.Code != http.StatusSeeOther || c == nil {
|
|
t.Fatalf("sign up: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
return c
|
|
}
|
|
|
|
// setAccount changes a team's billing, as Stripe's events would.
|
|
func setAccount(t *testing.T, s *Server, team int64, fn func(a *billing.Account)) {
|
|
t.Helper()
|
|
a, err := billing.Get(s.platform(), team)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
fn(a)
|
|
if err := billing.Save(s.platform(), a, time.Now()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func TestPlansLimitTeams(t *testing.T) {
|
|
s, h := newBilled(t)
|
|
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
|
|
ts, _ := s.forTeam(team)
|
|
|
|
// A new team's trial: Paid, everything.
|
|
a, _ := billing.Get(s.platform(), team)
|
|
if a.Status != billing.Trialing || a.TrialEnds.Before(time.Now().Add(13*24*time.Hour)) {
|
|
t.Fatalf("trial %+v", a)
|
|
}
|
|
if rec := as(h, c, http.MethodPost, "/prospects/new", url.Values{"company_name": {"Lead Co"}, "website": {"https://lead.example"}}); rec.Code == http.StatusForbidden {
|
|
t.Error("Prospects closed on the trial")
|
|
}
|
|
if !ts.jobAllowed("outreach") {
|
|
t.Error("outreach job held on the trial")
|
|
}
|
|
if n, every := ts.crawlLimits(); n != 10000 || every != 24*time.Hour {
|
|
t.Errorf("trial crawl %d %v", n, every)
|
|
}
|
|
|
|
// The trial over, without a subscription: Free.
|
|
setAccount(t, s, team, func(a *billing.Account) { a.TrialEnds = time.Now().Add(-time.Hour) })
|
|
if rec := as(h, c, http.MethodPost, "/prospects/new", url.Values{"company_name": {"Other"}, "website": {"https://other.example"}}); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "Free plan") {
|
|
t.Errorf("Prospects on Free: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
if rec := as(h, c, http.MethodGet, "/prospects", nil); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Lead Co") {
|
|
t.Errorf("Prospects' data on Free: %d", rec.Code)
|
|
}
|
|
if ts.jobAllowed("outreach") || !ts.jobAllowed("seo") {
|
|
t.Error("jobs on Free")
|
|
}
|
|
if n, every := ts.crawlLimits(); n != 500 || every != 7*24*time.Hour {
|
|
t.Errorf("free crawl %d %v", n, every)
|
|
}
|
|
// One agent on Free.
|
|
if rec := as(h, c, http.MethodPost, "/settings/agents", url.Values{"name": {"One"}, "scope:seo": {"read"}}); rec.Code != http.StatusOK {
|
|
t.Fatalf("first agent: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
if rec := as(h, c, http.MethodPost, "/settings/agents", url.Values{"name": {"Two"}, "scope:seo": {"read"}}); rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "1 agents") {
|
|
t.Errorf("second agent on Free: %d", rec.Code)
|
|
}
|
|
// Ten Market entries on Free.
|
|
for i := 0; i < 10; i++ {
|
|
if rec := as(h, c, http.MethodPost, "/market/save", url.Values{"name": {"Entry " + strconv.Itoa(i)}, "relationship": {"partner"}, "description": {"x"}}); rec.Code != http.StatusSeeOther {
|
|
t.Fatalf("entry %d: %d", i, rec.Code)
|
|
}
|
|
}
|
|
if rec := as(h, c, http.MethodPost, "/market/save", url.Values{"name": {"Eleven"}, "relationship": {"partner"}, "description": {"x"}}); rec.Code == http.StatusSeeOther {
|
|
t.Error("an eleventh entry on Free")
|
|
}
|
|
|
|
// Paid and active: everything again.
|
|
setAccount(t, s, team, func(a *billing.Account) { a.Status = billing.Active })
|
|
if rec := as(h, c, http.MethodPost, "/market/save", url.Values{"name": {"Eleven"}, "relationship": {"partner"}, "description": {"x"}}); rec.Code != http.StatusSeeOther {
|
|
t.Errorf("Paid: %d", rec.Code)
|
|
}
|
|
|
|
// Past due for 15 days: read-only, for people and agents.
|
|
setAccount(t, s, team, func(a *billing.Account) {
|
|
a.Status, a.PastDueSince = billing.PastDue, time.Now().Add(-15*24*time.Hour)
|
|
})
|
|
rec := as(h, c, http.MethodPost, "/market/save", url.Values{"name": {"Twelve"}, "relationship": {"partner"}, "description": {"x"}})
|
|
if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "lapsed") {
|
|
t.Errorf("lapsed: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
if rec := as(h, c, http.MethodGet, "/market", nil); rec.Code != http.StatusOK {
|
|
t.Errorf("lapsed, reading: %d", rec.Code)
|
|
}
|
|
_, key := newAgentIn(t, ts, "Late", map[string]users.Access{"market": users.View})
|
|
if code, _ := mcpTools(h, key); code != http.StatusForbidden {
|
|
t.Errorf("agent of a lapsed team: %d", code)
|
|
}
|
|
if ts.jobAllowed("seo") || !ts.jobAllowed("accounts") {
|
|
t.Error("jobs of a lapsed team")
|
|
}
|
|
}
|
|
|
|
func TestNoBillingNoLimits(t *testing.T) {
|
|
s, h := newMultiEdition(t)
|
|
c := signUp(t, h, "olu@acme.example", "Acme", "acme.example")
|
|
if rec := as(h, c, http.MethodPost, "/prospects/new", url.Values{"company_name": {"Lead"}, "website": {"https://lead.example"}}); rec.Code == http.StatusForbidden {
|
|
t.Error("limited without billing")
|
|
}
|
|
if a, _ := billing.Get(s.platform(), 1); a.Status != billing.Free || a.Customer != "" {
|
|
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
|
|
}
|