Phase 14, part 1: plans, each team's account, and their limits
The multi-tenant edition's plans (Free and Paid as decided, or a plans file) and each team's billing account, with a 14-day trial of Paid. A team's plan caps what its people and agents may change: modules outside it stay readable, a lapsed team changes nothing, and agents, Market entries, crawls and background jobs keep to it. Without a Stripe key, no billing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+21
-1
@@ -7,6 +7,8 @@ import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"supermarket/internal/users"
|
||||
)
|
||||
|
||||
// Who may reach what. Every route belongs to an area: a module, Settings
|
||||
@@ -170,7 +172,25 @@ func (s *Server) allow(area string, next http.Handler) http.Handler {
|
||||
s.toSignIn(w, r)
|
||||
return
|
||||
}
|
||||
if !v.can(area, !safeMethod(r.Method)) {
|
||||
write := !safeMethod(r.Method)
|
||||
// A lapsed team changes nothing, but its billing, people's own
|
||||
// accounts, and switching teams.
|
||||
if v.ReadOnly && write && !strings.HasPrefix(r.URL.Path, "/settings/billing") &&
|
||||
!platformPath(r.URL.Path) && !strings.HasPrefix(r.URL.Path, "/teams/") {
|
||||
http.Error(w, sentence(errLapsed.Error())+".", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if !v.can(area, write) {
|
||||
// A module the team's plan has only to read: say so.
|
||||
if write && v.Member.Cap != nil && v.Member.Cap[area] == users.View && v.Member.Can(area, false) {
|
||||
if ts, err := s.teamServer(r); err == nil {
|
||||
if plan, _ := ts.teamPlan(); plan != nil {
|
||||
http.Error(w, fmt.Sprintf("The %s plan doesn't include %s: what's there stays, to read. The team's owner can move up a plan under Settings → Billing.",
|
||||
plan.Name, grantName(area)), http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
s.forbidden(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -56,6 +56,12 @@ func (s *Server) AgentAuth(r *http.Request, key string) (*mcpserver.Caller, erro
|
||||
if err != nil {
|
||||
return nil, users.ErrBadKey
|
||||
}
|
||||
if plan, ro := ts.teamPlan(); plan != nil {
|
||||
if ro {
|
||||
return nil, &mcpserver.Refusal{Status: http.StatusForbidden, Reason: sentence(errLapsed.Error()) + "."}
|
||||
}
|
||||
m = planned(m, plan, ro)
|
||||
}
|
||||
lim, err := users.LimitsOf(ts.DB, u.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -315,6 +321,9 @@ func (s *Server) agentCreate(w http.ResponseWriter, r *http.Request) {
|
||||
f := agentForm{Name: strings.TrimSpace(r.PostFormValue("name")), Description: strings.TrimSpace(r.PostFormValue("description")),
|
||||
Expires: r.PostFormValue("expires"), Scopes: agentScopesFromForm(r)}
|
||||
expires, err := expiryFromForm(r, now)
|
||||
if err == nil {
|
||||
err = s.limitAgents()
|
||||
}
|
||||
switch {
|
||||
case f.Name == "":
|
||||
err = errors.New("give the agent a name")
|
||||
@@ -510,6 +519,10 @@ func (s *Server) agentAction(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
case "enable":
|
||||
if lerr := s.limitAgents(); lerr != nil {
|
||||
s.renderAgent(w, r, u, sentence(lerr.Error())+".", http.StatusUnprocessableEntity)
|
||||
return
|
||||
}
|
||||
if err = users.SetStatus(s.DB, u.ID, users.Active); err == nil {
|
||||
s.audit(r, "enabled", u.Name, "an agent")
|
||||
redirect(w, r, back, "enabled")
|
||||
|
||||
@@ -690,6 +690,11 @@ func (s *Server) marketActTools(srv *mcp.Server, c *mcpserver.Caller) {
|
||||
e.ID, action = old.ID, "changed"
|
||||
}
|
||||
}
|
||||
if action == "added" {
|
||||
if err := s.limitSources(len(list)); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
if err := inventory.Save(s.DB, &e); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ type viewer struct {
|
||||
|
||||
Platform bool // runs the multi-tenant platform (SUPERMARKET_PLATFORM_ADMINS)
|
||||
Viewing bool // a platform admin viewing a team, read-only
|
||||
ReadOnly bool // the team's subscription has lapsed: nothing may change
|
||||
}
|
||||
|
||||
// localOwner is the local edition's one user.
|
||||
@@ -166,7 +167,14 @@ func (s *Server) lookupSession(r *http.Request) (*viewer, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &viewer{User: u, Member: m, Session: sess, Platform: pa}, nil
|
||||
v := &viewer{User: u, Member: m, Session: sess, Platform: pa}
|
||||
if s.billingOn() {
|
||||
if ts, err := s.forTeam(sess.Team); err == nil {
|
||||
plan, ro := ts.teamPlan()
|
||||
v.Member, v.ReadOnly = planned(m, plan, ro), ro
|
||||
}
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// toSignIn sends someone who isn't signed in to the sign-in page, and
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"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)
|
||||
}
|
||||
}
|
||||
@@ -86,7 +86,11 @@ func (s *Server) inventorySave(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
e := entryFromForm(r)
|
||||
if err := inventory.Save(s.DB, e); err != nil {
|
||||
err := s.marketRoom(e)
|
||||
if err == nil {
|
||||
err = inventory.Save(s.DB, e)
|
||||
}
|
||||
if err != nil {
|
||||
title := e.Name
|
||||
if title == "" {
|
||||
title = "New entry"
|
||||
@@ -296,3 +300,20 @@ func (s *Server) subredditCheck(ctx context.Context) inventory.SubredditCheck {
|
||||
return info, nil
|
||||
}
|
||||
}
|
||||
|
||||
// marketRoom says why a new entry can't be added (the plan's limit), or nil.
|
||||
func (s *Server) marketRoom(e *inventory.Entry) error {
|
||||
if e.ID != 0 {
|
||||
return nil
|
||||
}
|
||||
list, err := inventory.List(s.DB, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, x := range list {
|
||||
if strings.EqualFold(x.Name, strings.TrimSpace(e.Name)) {
|
||||
return nil // the same name: Save says so
|
||||
}
|
||||
}
|
||||
return s.limitSources(len(list))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/billing"
|
||||
"supermarket/internal/users"
|
||||
)
|
||||
|
||||
// What a team's plan allows (the multi-tenant edition, with billing on):
|
||||
// its modules (the others keep their data, read-only), its agents, its
|
||||
// sources, how much it crawls; and, when the subscription has lapsed too
|
||||
// long, nothing that changes anything.
|
||||
|
||||
// billingOn says whether teams are billed.
|
||||
func (s *Server) billingOn() bool { return s.multi() && s.Plans != nil }
|
||||
|
||||
// teamPlan is the team's plan now and whether it's read-only; nil when
|
||||
// there's no billing (everything allowed).
|
||||
func (s *Server) teamPlan() (*billing.Plan, bool) {
|
||||
if !s.billingOn() || s.team() == 0 {
|
||||
return nil, false
|
||||
}
|
||||
a, err := billing.Get(s.platform(), s.team())
|
||||
if err != nil {
|
||||
s.Log.Error("billing: reading the team's", "team", s.team(), "err", err)
|
||||
return nil, false
|
||||
}
|
||||
return a.Effective(s.Plans, time.Now())
|
||||
}
|
||||
|
||||
// errLapsed is what's said when a lapsed team tries to change something.
|
||||
var errLapsed = errors.New("the team's subscription has lapsed: its owner can renew it under Settings → Billing. Until then, nothing is fetched, sent or published")
|
||||
|
||||
// planned limits a membership to the plan: modules outside it, and every
|
||||
// module when the team is read-only, can only be viewed. Admins keep
|
||||
// Settings (but changes there are refused while read-only: allow).
|
||||
func planned(m users.Membership, plan *billing.Plan, readOnly bool) users.Membership {
|
||||
if plan == nil {
|
||||
return m
|
||||
}
|
||||
m.Cap = map[string]users.Access{}
|
||||
for _, g := range grants() {
|
||||
if plan.Includes(g.ID) && !readOnly {
|
||||
m.Cap[g.ID] = users.Edit
|
||||
} else {
|
||||
m.Cap[g.ID] = users.View
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// jobModule is the module a background job works for, if any.
|
||||
var jobModule = map[string]string{
|
||||
"scheduler": "content", "outreach": "prospects", "imports": "prospects", "discovery": "prospects",
|
||||
"tracking": "prospects", "seo": "seo", "metrics": "metrics",
|
||||
}
|
||||
|
||||
// jobAllowed says whether a team's background job may run: its module in
|
||||
// the plan, and the team not lapsed.
|
||||
func (s *Server) jobAllowed(name string) bool {
|
||||
plan, ro := s.teamPlan()
|
||||
if plan == nil {
|
||||
return true
|
||||
}
|
||||
if ro {
|
||||
return name == "accounts"
|
||||
}
|
||||
m, ok := jobModule[name]
|
||||
return !ok || plan.Includes(m)
|
||||
}
|
||||
|
||||
// limitAgents says why the team may not have another agent, or nil.
|
||||
func (s *Server) limitAgents() error {
|
||||
plan, ro := s.teamPlan()
|
||||
if plan == nil {
|
||||
return nil
|
||||
}
|
||||
if ro {
|
||||
return errLapsed
|
||||
}
|
||||
list, err := users.Members(s.platform(), s.team())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n := 0
|
||||
for _, m := range list {
|
||||
if m.Kind == users.Agent && m.Status == users.Active {
|
||||
n++
|
||||
}
|
||||
}
|
||||
if plan.Agents > 0 && n >= plan.Agents {
|
||||
return fmt.Errorf("the %s plan has %d agents, and the team has them all: turn one off, or move up a plan", plan.Name, plan.Agents)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// limitSources says why the Market may not take another entry, or nil.
|
||||
func (s *Server) limitSources(existing int) error {
|
||||
plan, _ := s.teamPlan()
|
||||
if plan == nil || plan.Sources == 0 || existing < plan.Sources {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("the %s plan watches %d entries in the Market: remove one, or move up a plan", plan.Name, plan.Sources)
|
||||
}
|
||||
|
||||
// crawlLimits are how many pages an audit reads and how often (0: the
|
||||
// edition's own).
|
||||
func (s *Server) crawlLimits() (int, time.Duration) {
|
||||
plan, _ := s.teamPlan()
|
||||
if plan == nil {
|
||||
return 0, 7 * 24 * time.Hour
|
||||
}
|
||||
return plan.CrawlPages, plan.CrawlInterval()
|
||||
}
|
||||
+5
-2
@@ -617,7 +617,9 @@ func (s *Server) startAudit(site seoSite, speed bool) {
|
||||
defer release()
|
||||
ctx, cancel := context.WithTimeout(lctx, 45*time.Minute)
|
||||
defer cancel()
|
||||
a, err := seo.RunAudit(ctx, s.DB, seo.NewFetcher("Supermarket/"+s.Version+" (SEO audit)"), site.URL, site.Property)
|
||||
f := seo.NewFetcher("Supermarket/" + s.Version + " (SEO audit)")
|
||||
f.MaxPages, _ = s.crawlLimits()
|
||||
a, err := seo.RunAudit(ctx, s.DB, f, site.URL, site.Property)
|
||||
if err == nil && speed {
|
||||
for _, p := range busiest(a, 5) {
|
||||
a.Speed = append(a.Speed, seo.CheckSpeed(ctx, p, s.Secrets.Get(secrets.PageSpeedAPIKey)))
|
||||
@@ -682,8 +684,9 @@ func (s *Server) seoAuditStatus(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// weeklyAudits audits each website once a week.
|
||||
func (s *Server) weeklyAudits(now time.Time) {
|
||||
_, every := s.crawlLimits()
|
||||
for _, site := range s.seoSites() {
|
||||
if site.URL != "" && now.Sub(seo.LastDoneAudit(s.DB, site.URL)) > 7*24*time.Hour {
|
||||
if site.URL != "" && now.Sub(seo.LastDoneAudit(s.DB, site.URL)) > every {
|
||||
if a, _ := seo.LatestAudit(s.DB, site.URL); a != nil && a.Status == "failed" && now.Sub(a.StartedAt) < 24*time.Hour {
|
||||
continue // don't retry a failing site more than daily
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ import (
|
||||
"supermarket/internal/api/reddit"
|
||||
"supermarket/internal/api/twitter"
|
||||
"supermarket/internal/appmail"
|
||||
"supermarket/internal/billing"
|
||||
"supermarket/internal/content"
|
||||
"supermarket/internal/core"
|
||||
"supermarket/internal/db"
|
||||
@@ -81,6 +82,9 @@ type Server struct {
|
||||
// Platform is the database every team shares: people, sessions, keys,
|
||||
// locks. On the local and server editions, DB itself.
|
||||
Platform *db.DB
|
||||
// Plans are the multi-tenant edition's billing; nil: no billing, every
|
||||
// team has everything.
|
||||
Plans *billing.Plans
|
||||
|
||||
testPublisher func(*posting.Account) content.Publisher // tests: posts nowhere
|
||||
|
||||
@@ -244,6 +248,9 @@ func (s *Server) jobDo(ctx context.Context, name string, fn func(context.Context
|
||||
if name == "seo" && !ts.domainProved() {
|
||||
return // nothing crawled or read before the domain is proved
|
||||
}
|
||||
if !ts.jobAllowed(name) {
|
||||
return // its module isn't in the team's plan, or the team has lapsed
|
||||
}
|
||||
if _, err := ts.jobs().Do(ctx, ts.lockName("job:"+name), func(c context.Context) { fn(c, ts) }); err != nil {
|
||||
ts.Log.Warn("jobs: taking the lock", "job", name, "team", ts.team(), "err", err)
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"supermarket/internal/appmail"
|
||||
"supermarket/internal/audit"
|
||||
"supermarket/internal/billing"
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/users"
|
||||
)
|
||||
@@ -182,6 +183,11 @@ func (s *Server) newTeam(owner *users.User, company, domain, site string, now ti
|
||||
if err := users.Join(s.platform(), team.ID, owner.ID, users.Owner, nil, now); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.billingOn() {
|
||||
if err := billing.StartTrial(s.platform(), team.ID, s.Plans, now); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
ts, err := s.forTeam(team.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
Reference in New Issue
Block a user