Phase 14, parts 5 and 6: seats, and moving down to Free

Seats: inviting past the seats paid for offers the owner to add one
(Stripe prorates it); admins are told to ask the owner; Free has two.
Moving down: past the plan's seats, the owner and one other (the owner's
pick, or the first to join) edit and the rest read; storage is measured
hourly, and past the plan's, photo uploads and the SEO crawl stop.
Nothing is deleted. TEST.md section 18.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 13:34:22 -07:00
co-authored by Claude Opus 5.5
parent aa0408fb14
commit 6d3eb18b5e
16 changed files with 573 additions and 6 deletions
+34
View File
@@ -58,6 +58,12 @@ tools over MCP, approvals, limits and visibility, and the JSON API. Schema
with a Postgres schema per team (decided 2026-11-26); schema 42. Next is with a Postgres schema per team (decided 2026-11-26); schema 42. Next is
Phase 14 (billing), or Phase 12 once the Core's `idproviders.yml` is in. Phase 14 (billing), or Phase 12 once the Core's `idproviders.yml` is in.
**Everything through Phase 13, and Phase 12, is merged and pushed**
(2026-11-26). **Phase 14 (billing) is built** on branch `phase14` (Stripe,
multi-tenant only, off without `SUPERMARKET_STRIPE_KEY`); schema 44. Then
the user tests each edition by hand with TEST.md: local, server with the
Core, multi-tenant.
**Phase 12 (signing in with the Core, OIDC) is built** on branch **Phase 12 (signing in with the Core, OIDC) is built** on branch
`phase12`, which starts from `phase13` (2026-11-26), with the Core's `phase12`, which starts from `phase13` (2026-11-26), with the Core's
`idproviders.yml` as the guide. Not yet tried against a real Authelia. Phase 12 still needs who adds Supermarket's client to `idproviders.yml` as the guide. Not yet tried against a real Authelia. Phase 12 still needs who adds Supermarket's client to
@@ -3286,6 +3292,34 @@ Checkout; both are off until set.
only, before it's deleted again. Paying (`invoice.paid`) clears it all. only, before it's deleted again. Paying (`invoice.paid`) clears it all.
- Each step goes in the team's audit log. - Each step goes in the team's audit log.
**Part 5 built 2026-11-26.**
- Inviting someone (or adding someone from another team, or turning
someone back on) checks the seats. The trial has no limit (Checkout
counts the people). Free has two: past that, *subscribe*. Paid has the
seats paid for: the owner is offered *Add a seat for them*, which sets
the subscription's quantity one higher (Stripe prorates it) and then
invites; an admin is told to ask the owner. Turning someone back on
doesn't buy a seat: turn someone else off, or add seats in Stripe's
billing page. Fewer seats are set there too.
**Part 6 built 2026-11-26.**
- A team with more people than its plan's seats (moving down to Free,
which has two): the owner and one other keep editing, the one the owner
picks under Settings → Billing, or else whoever joined first. The rest
keep their accounts and read what they could (an admin reads every
module, as a member), and are told why when they try to change
something. No one is removed.
- Storage: the hourly billing turn measures each team's files and its
schema's tables (`storage_used`). Past the plan's, a photo upload says
the storage is full and the SEO crawl waits; nothing is deleted.
Exports still work (a team on its way out can always take its data).
A crawl's pages are kept in the team's tables, so the crawl waiting
covers them; previews (and site clones) are Sites, which Free has only
to read, so none are made.
- TEST.md: section 18, on the multi-tenant pass with Stripe's test mode.
Phase 14 is built.
#### Order #### Order
``` ```
+46 -1
View File
@@ -19,7 +19,7 @@ are run first on the local edition, on this computer. Then:
|---|---|---| |---|---|---|
| **Local** | `install.sh` / `./update.sh`, at <http://localhost:8470> | 1–13, 14 (local part), 15 | | **Local** | `install.sh` / `./update.sh`, at <http://localhost:8470> | 1–13, 14 (local part), 15 |
| **Server, with the Core** | `./install-server.sh` on a server (or a test machine, with Caddy's own CA), its Core's domain entered under Settings → Core & Hermes | 14, 15 (agents on a server), 16, and a quick run through 2–10 as a member with only some modules | | **Server, with the Core** | `./install-server.sh` on a server (or a test machine, with Caddy's own CA), its Core's domain entered under Settings → Core & Hermes | 14, 15 (agents on a server), 16, and a quick run through 2–10 as a member with only some modules |
| **Multi-tenant** | `compose.multi.yaml` with a Postgres and a Garage bucket (`multi.env`), `SUPERMARKET_PLATFORM_ADMINS` set | 17, and 16 for a team's Core sign-in | | **Multi-tenant** | `compose.multi.yaml` with a Postgres and a Garage bucket (`multi.env`), `SUPERMARKET_PLATFORM_ADMINS` set | 17, 18 (with Stripe's test mode), and 16 for a team's Core sign-in |
On the server and multi-tenant passes, sign in as different people (an On the server and multi-tenant passes, sign in as different people (an
owner, an admin, a member with one module) in separate browser profiles or owner, an admin, a member with one module) in separate browser profiles or
@@ -953,3 +953,48 @@ Hermes:
- [ ] Restart one copy: people stay signed in, and the others carry on - [ ] Restart one copy: people stay signed in, and the others carry on
the background work. the background work.
## 18. Billing (Phase 14)
Multi-tenant only, with Stripe in **test mode**: `SUPERMARKET_STRIPE_KEY`
(`sk_test_…`), `SUPERMARKET_STRIPE_PRICE` (a monthly per-person price),
and `SUPERMARKET_STRIPE_WEBHOOK_SECRET` from `stripe listen --forward-to
https://<domain>/billing/stripe` (or a webhook endpoint in the dashboard
with `checkout.session.completed`, `customer.subscription.*`,
`invoice.paid` and `invoice.payment_failed`). Pay with Stripe's test card
4242 4242 4242 4242. Some steps need time to pass: set the dates in the
`billing` table, then wait for the hourly turn (or restart a copy).
- [ ] Without the Stripe key, a team has everything and there's no
Settings → Billing.
- [ ] A new team is on a 14-day trial of Paid: Settings → Billing says so,
with people, agents, storage and the crawl against the plan's.
Admins see the plan without the buttons.
- [ ] *Subscribe with Stripe* (the owner) goes to Checkout with the
people as the quantity; paying brings you back, and the page soon
shows *Active*, the seats paid for, and the next invoice.
- [ ] *Open Stripe's billing page* opens the Customer Portal; cancelling
there ends the subscription at the period's end, and the page
follows.
- [ ] Each change shows in Activity ("billing changed"). Sending the same
event again (`stripe events resend`) changes nothing.
- [ ] A trial that ends without a subscription drops to Free, and the
owner gets an email. Prospects, Metrics and Sites can be read, not
changed ("The Free plan doesn't include…"); their jobs stop. One
agent, ten Market entries, a 500-page weekly crawl.
- [ ] A failed payment (test card 4000 0000 0000 0341, then a renewal):
a banner on every page (*Pay now* for the owner), and an email.
14 days on: read-only, agents refused, an email. 53 days: everyone
warned. 60: the team closes as being deleted, everyone emailed;
the owner's *Undo* gives a week more to pay.
- [ ] Paying the overdue invoice clears the banner and read-only.
- [ ] Seats: inviting past the seats paid for offers the owner *Add a seat
for them* (Stripe's next invoice shows the proration); an admin is
told to ask the owner. On Free, past two people: *subscribe*.
- [ ] Moving down to Free with more than two people: the owner and one
other edit (the first to join, until the owner chooses under
Settings → Billing); the rest read, and are told why. No one is
removed.
- [ ] Storage: Settings → Billing shows what the team stores (within the
hour). Past the plan's (set `storage_used` high to try it), a photo
upload says the storage is full and the SEO crawl waits. Exports
still work.
+9
View File
@@ -221,3 +221,12 @@ func (t *Teams) Close() {
delete(t.open, id) delete(t.open, id)
} }
} }
// Size is how many bytes a team's schema takes: its tables, their indexes
// and what's stored beside them.
func (t *Teams) Size(id int64) (int64, error) {
var n sql.NullInt64
err := t.platform.SQL.QueryRow(`SELECT sum(pg_total_relation_size(c.oid)) FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = $1 AND c.relkind IN ('r', 'm')`, t.Schema(id)).Scan(&n)
return n.Int64, err
}
+5 -4
View File
@@ -432,12 +432,13 @@ func HasOwner(d *db.DB, team int64) (bool, error) {
type TeamUser struct { type TeamUser struct {
*User *User
Membership Membership
Joined time.Time // when they joined the team
} }
// Members are the team's users, people first, then by name. // Members are the team's users, people first, then by name.
func Members(d *db.DB, team int64) ([]TeamUser, error) { func Members(d *db.DB, team int64) ([]TeamUser, error) {
cols := strings.ReplaceAll("u."+userCols, ", ", ", u.") cols := strings.ReplaceAll("u."+userCols, ", ", ", u.")
rows, err := d.Query(`SELECT `+cols+`, m.role, m.modules FROM users u JOIN memberships m ON m.user_id = u.id rows, err := d.Query(`SELECT `+cols+`, m.role, m.modules, m.created_at FROM users u JOIN memberships m ON m.user_id = u.id
WHERE m.team_id = ? ORDER BY u.kind DESC, u.name COLLATE NOCASE, u.email`, team) WHERE m.team_id = ? ORDER BY u.kind DESC, u.name COLLATE NOCASE, u.email`, team)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -445,14 +446,14 @@ func Members(d *db.DB, team int64) ([]TeamUser, error) {
defer rows.Close() defer rows.Close()
var out []TeamUser var out []TeamUser
for rows.Next() { for rows.Next() {
var role, modules string var role, modules, joined string
u, err := scanUser(rowWith{rows, []any{&role, &modules}}) u, err := scanUser(rowWith{rows, []any{&role, &modules, &joined}})
if err != nil { if err != nil {
return nil, err return nil, err
} }
m := Membership{Team: team, User: u.ID, Role: Role(role), Modules: map[string]Access{}} m := Membership{Team: team, User: u.ID, Role: Role(role), Modules: map[string]Access{}}
_ = json.Unmarshal([]byte(modules), &m.Modules) _ = json.Unmarshal([]byte(modules), &m.Modules)
out = append(out, TeamUser{User: u, Membership: m}) out = append(out, TeamUser{User: u, Membership: m, Joined: parseTS(joined)})
} }
return out, rows.Err() return out, rows.Err()
} }
+10
View File
@@ -183,6 +183,16 @@ func (s *Server) allow(area string, next http.Handler) http.Handler {
return return
} }
if !v.can(area, write) { if !v.can(area, write) {
if write && v.OverSeats {
msg := "The team has more people than its plan has seats, so you can read, not change. The team's owner chooses who keeps editing, under Settings → Billing."
if ts, err := s.teamServer(r); err == nil {
if _, plan := ts.kept(); plan != nil {
msg = fmt.Sprintf("The %s plan has %d people, and the team has more, so you can read, not change. The team's owner chooses who keeps editing, under Settings → Billing, or moves up a plan.", plan.Name, plan.Seats)
}
}
http.Error(w, msg, http.StatusForbidden)
return
}
// A module the team's plan has only to read: say so. // 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 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 ts, err := s.teamServer(r); err == nil {
+1 -1
View File
@@ -180,7 +180,7 @@ var actionLabels = map[string]string{
"key-made": "made a new key for", "key-revoked": "revoked a key of", "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", "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:", "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:", "billing-checkout": "went to subscribe:", "billing": "billing changed:", "trial-ended": "the trial ended:", "lapse-due": "a payment failed:", "lapse-read-only": "made read-only:", "lapse-warned": "warned of deletion:", "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:", "billing-seat": "added a seat:", "billing-kept": "chose who keeps editing:", "billing": "billing changed:", "trial-ended": "the trial ended:", "lapse-due": "a payment failed:", "lapse-read-only": "made read-only:", "lapse-warned": "warned of deletion:", "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", "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", "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",
} }
+6
View File
@@ -31,6 +31,9 @@ type viewer struct {
Platform bool // runs the multi-tenant platform (SUPERMARKET_PLATFORM_ADMINS) Platform bool // runs the multi-tenant platform (SUPERMARKET_PLATFORM_ADMINS)
Viewing bool // a platform admin viewing a team, read-only Viewing bool // a platform admin viewing a team, read-only
ReadOnly bool // the team's subscription has lapsed: nothing may change ReadOnly bool // the team's subscription has lapsed: nothing may change
// More people than the plan's seats, and not one kept: they read, and
// change nothing.
OverSeats bool
} }
// localOwner is the local edition's one user. // localOwner is the local edition's one user.
@@ -172,6 +175,9 @@ func (s *Server) lookupSession(r *http.Request) (*viewer, error) {
if ts, err := s.forTeam(sess.Team); err == nil { if ts, err := s.forTeam(sess.Team); err == nil {
plan, ro := ts.teamPlan() plan, ro := ts.teamPlan()
v.Member, v.ReadOnly = planned(m, plan, ro), ro v.Member, v.ReadOnly = planned(m, plan, ro), ro
if kept, _ := ts.kept(); kept != nil && !kept[u.ID] {
v.Member, v.OverSeats = viewOnly(v.Member), true
}
} }
} }
return v, nil return v, nil
+54
View File
@@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"strconv"
"time" "time"
"supermarket/internal/appmail" "supermarket/internal/appmail"
@@ -44,6 +45,10 @@ type billingData struct {
InvoiceErr string InvoiceErr string
Yearly bool Yearly bool
Problem string Problem string
// More people than the plan's seats: who keeps editing (the owner
// picks one), and the others the owner could pick.
Kept map[int64]bool
Others []users.TeamUser
} }
// people counts the team's people (not agents), invited ones too. // people counts the team's people (not agents), invited ones too.
@@ -88,6 +93,14 @@ func (s *Server) renderBilling(w http.ResponseWriter, r *http.Request, problem s
} }
d.StorageOf = plan.StorageBytes(seats, a.StorageBlocks) d.StorageOf = plan.StorageBytes(seats, a.StorageBlocks)
d.Yearly = d.Paid.PriceYear != "" d.Yearly = d.Paid.PriceYear != ""
if d.Kept, _ = s.kept(); d.Kept != nil {
list, _ := users.Members(s.platform(), s.team())
for _, m := range list {
if m.Kind == users.Person && m.Status != users.Disabled && m.Role != users.Owner {
d.Others = append(d.Others, m)
}
}
}
if d.Owner && a.Customer != "" && a.Subscription != "" { if d.Owner && a.Customer != "" && a.Subscription != "" {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
d.Invoice, err = s.billingStripe().Upcoming(ctx, a.Customer) d.Invoice, err = s.billingStripe().Upcoming(ctx, a.Customer)
@@ -283,6 +296,12 @@ func (s *Server) billingTurn(ctx context.Context, now time.Time) {
s.Log.Error("billing: saving", "team", a.Team, "err", err) s.Log.Error("billing: saving", "team", a.Team, "err", err)
} }
} }
if used, err := ts.measureStorage(ctx); err != nil {
s.Log.Warn("billing: measuring storage", "team", a.Team, "err", err)
} else if used != a.StorageUsed {
a.StorageUsed = used
save()
}
owner := ts.ownerOf() owner := ts.ownerOf()
switch { switch {
case a.Status == billing.Trialing && a.Subscription == "" && !now.Before(a.TrialEnds): case a.Status == billing.Trialing && a.Subscription == "" && !now.Before(a.TrialEnds):
@@ -379,3 +398,38 @@ func (s *Server) lapseUndone(team int64, now time.Time) {
s.Log.Error("billing: saving", "team", team, "err", err) s.Log.Error("billing: saving", "team", team, "err", err)
} }
} }
// billingKeep is the owner choosing who keeps editing when the team has
// more people than its plan's seats.
func (s *Server) billingKeep(w http.ResponseWriter, r *http.Request) {
v := s.owner(w, r)
if v == nil || !s.billingOn() {
if v != nil {
http.NotFound(w, r)
}
return
}
id, _ := strconv.ParseInt(r.PostFormValue("user"), 10, 64)
m, err := users.MembershipOf(s.platform(), s.team(), id)
if err != nil || m.Role == users.Owner {
s.renderBilling(w, r, "Choose someone in the team.")
return
}
u, err := users.ByID(s.platform(), id)
if err != nil || u.Kind != users.Person {
s.renderBilling(w, r, "Choose someone in the team.")
return
}
a, err := billing.Get(s.platform(), s.team())
if err != nil {
s.serverError(w, err)
return
}
a.KeptMember = id
if err := billing.Save(s.platform(), a, time.Now()); err != nil {
s.serverError(w, err)
return
}
s.audit(r, "billing-kept", u.Email, "keeps editing")
redirect(w, r, "/settings/billing", "saved")
}
+103
View File
@@ -0,0 +1,103 @@
package web
import (
"context"
"net/http"
"net/url"
"strings"
"testing"
"time"
"supermarket/internal/billing"
"supermarket/internal/users"
)
// Moving down to Free: the people past its two read, and storage past its
// gigabyte keeps nothing new. Nothing's deleted.
func TestMovingDownToFree(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
person := func(email string, role users.Role, mods map[string]users.Access, joined time.Time) (*users.User, *http.Cookie) {
p := &users.User{Email: email, Name: strings.Split(email, "@")[0], Status: users.Active}
if err := users.Create(s.platform(), p, joined); err != nil {
t.Fatal(err)
}
if err := users.Join(s.platform(), team, p.ID, role, mods, joined); err != nil {
t.Fatal(err)
}
token, _, _ := users.StartSessionIn(s.platform(), p.ID, team, "", "", time.Now())
return p, &http.Cookie{Name: sessionCookie, Value: token}
}
ada, ac := person("ada@acme.example", users.Admin, nil, time.Now().Add(time.Hour))
bo, bc := person("bo@acme.example", users.Member, map[string]users.Access{"content": users.Edit}, time.Now().Add(2*time.Hour))
write := func(c *http.Cookie) *http.Response {
return as(h, c, http.MethodPost, "/content/999/fetch", nil).Result()
}
// On the trial, everyone edits.
if r := write(bc); r.StatusCode == http.StatusForbidden {
t.Fatal("Bo can't edit on the trial")
}
// Free: the owner and the first to join edit; Bo reads.
setAccount(t, s, team, func(a *billing.Account) { a.Status = billing.Free })
if r := write(ac); r.StatusCode == http.StatusForbidden {
t.Error("Ada can't edit")
}
rec := as(h, bc, http.MethodPost, "/content/999/fetch", nil)
if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "Free plan has 2 people") {
t.Errorf("Bo: %d %s", rec.Code, rec.Body)
}
if rec := as(h, bc, http.MethodGet, "/content", nil); rec.Code != http.StatusOK {
t.Errorf("Bo can't read: %d", rec.Code)
}
// The owner keeps Bo instead: Ada reads, as a member, everything.
rec = as(h, c, http.MethodGet, "/settings/billing", nil)
if !strings.Contains(rec.Body.String(), "Who keeps editing") {
t.Errorf("billing page: %s", rec.Body)
}
if rec := as(h, c, http.MethodPost, "/settings/billing/keep", url.Values{"user": {itoa64(bo.ID)}}); rec.Code != http.StatusSeeOther {
t.Fatalf("keep: %d %s", rec.Code, rec.Body)
}
if r := write(bc); r.StatusCode == http.StatusForbidden {
t.Error("Bo still can't edit")
}
if r := write(ac); r.StatusCode != http.StatusForbidden {
t.Error("Ada still edits")
}
if rec := as(h, ac, http.MethodPost, "/settings/users", url.Values{"email": {"x@acme.example"}, "name": {"X"}}); rec.Code != http.StatusForbidden {
t.Errorf("Ada still invites: %d", rec.Code)
}
if rec := as(h, ac, http.MethodGet, "/content", nil); rec.Code != http.StatusOK {
t.Errorf("Ada can't read: %d", rec.Code)
}
if rec := as(h, ac, http.MethodPost, "/settings/billing/keep", url.Values{"user": {itoa64(ada.ID)}}); rec.Code != http.StatusForbidden {
t.Errorf("Ada chose: %d", rec.Code)
}
if n, _ := users.Members(s.platform(), team); len(n) < 3 {
t.Error("someone was removed")
}
// Storage: measured each hour; past the plan's, nothing new is kept.
ts, _ := s.forTeam(team)
ts.Files.Put(context.Background(), "exports/x.tar.gz", strings.NewReader("12345"), 5)
s.billingTurn(context.Background(), time.Now())
a, _ := billing.Get(s.platform(), team)
if a.StorageUsed < 5 {
t.Errorf("measured %d", a.StorageUsed)
}
if ts.storageFull() != nil || !ts.jobAllowed("seo") {
t.Error("full already")
}
setAccount(t, s, team, func(a *billing.Account) { a.StorageUsed = 2 << 30 })
if err := ts.storageFull(); err == nil || !strings.Contains(err.Error(), "storage is full") {
t.Errorf("full: %v", err)
}
if ts.jobAllowed("seo") {
t.Error("the crawl runs with the storage full")
}
}
+4
View File
@@ -37,6 +37,10 @@ func (s *Server) accountPhoto(w http.ResponseWriter, r *http.Request) {
} }
key := "" key := ""
if r.URL.Query().Get("remove") == "" { if r.URL.Query().Get("remove") == "" {
if err := s.storageFull(); err != nil {
fail(sentence(err.Error()) + ".")
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxPhoto+64<<10) r.Body = http.MaxBytesReader(w, r.Body, maxPhoto+64<<10)
f, _, err := r.FormFile("photo") f, _, err := r.FormFile("photo")
if err != nil { if err != nil {
+193
View File
@@ -1,8 +1,11 @@
package web package web
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"net/http"
"sort"
"time" "time"
"supermarket/internal/billing" "supermarket/internal/billing"
@@ -69,6 +72,9 @@ func (s *Server) jobAllowed(name string) bool {
return name == "accounts" return name == "accounts"
} }
m, ok := jobModule[name] m, ok := jobModule[name]
if name == "seo" && s.storageFull() != nil {
return false // a crawl keeps its pages
}
return !ok || plan.Includes(m) return !ok || plan.Includes(m)
} }
@@ -115,3 +121,190 @@ func (s *Server) crawlLimits() (int, time.Duration) {
} }
return plan.CrawlPages, plan.CrawlInterval() return plan.CrawlPages, plan.CrawlInterval()
} }
// seatRoom says why the team has no room for another person ("" if it
// has), and whether a seat could be bought for them: a subscription paid
// per person, not lapsed. On the trial there's no limit: Checkout counts
// the people.
func (s *Server) seatRoom() (problem string, canAdd bool, a *billing.Account) {
if !s.billingOn() || s.team() == 0 {
return "", false, nil
}
a, err := billing.Get(s.platform(), s.team())
if err != nil {
return "", false, nil
}
plan, ro := a.Effective(s.Plans, time.Now())
people, _ := s.people()
seats := plan.Seats
if seats == 0 {
if a.Subscription == "" || a.Seats == 0 {
return "", false, a
}
seats = a.Seats
}
if people < seats {
return "", false, a
}
if plan.Seats != 0 {
return fmt.Sprintf("The %s plan has %d people, and the team has them all. To invite more, subscribe under Settings → Billing.", plan.Name, plan.Seats), false, a
}
return fmt.Sprintf("All %d seats paid for are taken.", seats), !ro, a
}
// addSeat pays for one more person: Stripe charges for the rest of the
// period now (prorated).
func (s *Server) addSeat(ctx context.Context, a *billing.Account) error {
people, _ := s.people()
n := a.Seats
if people > n {
n = people
}
n++
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
if err := s.billingStripe().SetQuantity(ctx, a.Subscription, n); err != nil {
return err
}
a.Seats = n
return billing.Save(s.platform(), a, time.Now())
}
// seatCheck is the invite's and turning-on's look at the seats: "" to go
// ahead (a seat added first if the owner said so), or what to say, and
// whether to offer the owner a seat (only where the form can take it).
func (s *Server) seatCheck(r *http.Request, v *viewer, offerable bool) (problem string, offer bool) {
problem, canAdd, a := s.seatRoom()
if problem == "" {
return "", false
}
owner := v.Member.Role == users.Owner && !v.Viewing
switch {
case canAdd && owner && !offerable:
return problem + " Turn someone else off first, or add seats on Stripe's billing page (Settings → Billing).", false
case canAdd && owner && r.PostFormValue("add_seat") == "1":
if err := s.addSeat(r.Context(), a); err != nil {
return "Stripe didn't add the seat: " + err.Error() + ".", true
}
s.audit(r, "billing-seat", "", fmt.Sprintf("%d seats", a.Seats))
return "", false
case canAdd && owner:
return problem + " Add one: Stripe charges for it from today, for the rest of the period.", true
case canAdd:
return problem + " Ask the team's owner to add one.", false
case !owner:
return problem + " Ask the team's owner.", false
}
return problem, false
}
// kept says who keeps their access when a team has more people than its
// plan's seats (after moving down to Free): the owner, the one the owner
// chose (billing.kept_member), then whoever joined first. The rest can
// read, not change. nil: everyone keeps theirs.
func (s *Server) kept() (map[int64]bool, *billing.Plan) {
if !s.billingOn() || s.team() == 0 {
return nil, nil
}
a, err := billing.Get(s.platform(), s.team())
if err != nil {
return nil, nil
}
plan, _ := a.Effective(s.Plans, time.Now())
if plan.Seats == 0 {
return nil, plan
}
list, err := users.Members(s.platform(), s.team())
if err != nil {
return nil, plan
}
var people []users.TeamUser
for _, m := range list {
if m.Kind == users.Person && m.Status != users.Disabled {
people = append(people, m)
}
}
if len(people) <= plan.Seats {
return nil, plan
}
rank := func(m users.TeamUser) int {
switch {
case m.Role == users.Owner:
return 0
case m.ID == a.KeptMember:
return 1
}
return 2
}
sort.SliceStable(people, func(i, j int) bool {
if ri, rj := rank(people[i]), rank(people[j]); ri != rj {
return ri < rj
}
return people[i].Joined.Before(people[j].Joined)
})
out := map[int64]bool{}
for _, m := range people[:plan.Seats] {
out[m.ID] = true
}
return out, plan
}
// viewOnly makes a membership read-only: an admin reads every module, a
// member theirs, and neither changes anything.
func viewOnly(m users.Membership) users.Membership {
if m.Admin() {
m.Modules = map[string]users.Access{}
for _, g := range grants() {
m.Modules[g.ID] = users.View
}
m.Role = users.Member
}
m.Cap = map[string]users.Access{}
for id := range m.Modules {
m.Cap[id] = users.View
}
return m
}
// storageFull says why the team can't store another file, or nil.
func (s *Server) storageFull() error {
if !s.billingOn() || s.team() == 0 {
return nil
}
a, err := billing.Get(s.platform(), s.team())
if err != nil {
return nil
}
plan, _ := a.Effective(s.Plans, time.Now())
seats := a.Seats
if seats == 0 {
seats, _ = s.people()
}
if limit := plan.StorageBytes(seats, a.StorageBlocks); limit > 0 && a.StorageUsed >= limit {
return fmt.Errorf("the team's storage is full (%s of the %s plan's %s): nothing's deleted, but nothing new is kept until there's room, or the owner moves up a plan or adds storage",
humanBytes(a.StorageUsed), plan.Name, humanBytes(limit))
}
return nil
}
// measureStorage notes how much a team stores: its files and its tables.
func (s *Server) measureStorage(ctx context.Context) (int64, error) {
var n int64
if s.Files != nil {
list, err := s.Files.List(ctx, "")
if err != nil {
return 0, err
}
for _, f := range list {
n += f.Size
}
}
if s.Teams != nil {
size, err := s.Teams.Size(s.team())
if err != nil {
return 0, err
}
n += size
}
return n, nil
}
+86
View File
@@ -0,0 +1,86 @@
package web
import (
"net/http"
"net/url"
"strings"
"testing"
"time"
"supermarket/internal/billing"
"supermarket/internal/users"
)
func TestSeats(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
invite := func(c *http.Cookie, email string, more url.Values) (int, string) {
form := url.Values{"email": {email}, "name": {"X"}, "role": {"admin"}}
for k, v := range more {
form[k] = v
}
rec := as(h, c, http.MethodPost, "/settings/users", form)
return rec.Code, rec.Body.String()
}
// The trial has no limit.
for _, e := range []string{"a@acme.example", "b@acme.example"} {
if code, body := invite(c, e, nil); code != http.StatusSeeOther {
t.Fatalf("trial invite %s: %d %s", e, code, body)
}
}
// Free: two people, and the team has three already.
setAccount(t, s, team, func(a *billing.Account) { a.Status = billing.Free })
if code, body := invite(c, "c@acme.example", nil); code != http.StatusUnprocessableEntity || !strings.Contains(body, "Free plan has 2 people") {
t.Errorf("free invite: %d", code)
}
// Paid for four: one more fits, then the owner's asked to add a seat.
setAccount(t, s, team, func(a *billing.Account) {
a.Status, a.Plan, a.Subscription, a.Seats = billing.Active, "paid", "sub_1", 4
})
if code, body := invite(c, "c@acme.example", nil); code != http.StatusSeeOther {
t.Fatalf("fourth: %d %s", code, body)
}
code, body := invite(c, "d@acme.example", nil)
if code != http.StatusUnprocessableEntity || !strings.Contains(body, "All 4 seats") || !strings.Contains(body, `name="add_seat"`) {
t.Errorf("fifth: %d %s", code, body)
}
if code, body := invite(c, "d@acme.example", url.Values{"add_seat": {"1"}}); code != http.StatusSeeOther {
t.Fatalf("with a seat: %d %s", code, body)
}
if f.qty != "5" {
t.Errorf("Stripe's quantity %q", f.qty)
}
if a, _ := billing.Get(s.platform(), team); a.Seats != 5 {
t.Errorf("seats %d", a.Seats)
}
// An admin is told to ask the owner, and can't add one.
admin := &users.User{Email: "e@acme.example", Name: "E", Status: users.Active}
users.Create(s.platform(), admin, time.Now())
users.Join(s.platform(), team, admin.ID, users.Admin, nil, time.Now())
setAccount(t, s, team, func(a *billing.Account) { a.Seats = 6 })
token, _, _ := users.StartSessionIn(s.platform(), admin.ID, team, "", "", time.Now())
ac := &http.Cookie{Name: sessionCookie, Value: token}
code, body = invite(ac, "f@acme.example", url.Values{"add_seat": {"1"}})
if code != http.StatusUnprocessableEntity || !strings.Contains(body, "Ask the team&#39;s owner") || strings.Contains(body, `name="add_seat"`) {
t.Errorf("admin: %d %s", code, body)
}
if f.qty != "5" {
t.Error("an admin added a seat")
}
// Turning someone back on needs a seat too.
b, _ := users.ByEmail(s.platform(), "b@acme.example")
as(h, c, http.MethodPost, "/settings/users/"+itoa64(b.ID)+"/disable", nil)
invite(c, "g@acme.example", nil)
if rec := as(h, c, http.MethodPost, "/settings/users/"+itoa64(b.ID)+"/enable", nil); rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "Turn someone else off") {
t.Errorf("enable: %d", rec.Code)
}
}
+1
View File
@@ -349,6 +349,7 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /settings/billing", (*Server).billingPage) mux.HandleFunc("GET /settings/billing", (*Server).billingPage)
mux.HandleFunc("POST /settings/billing/checkout", (*Server).billingCheckout) mux.HandleFunc("POST /settings/billing/checkout", (*Server).billingCheckout)
mux.HandleFunc("POST /settings/billing/portal", (*Server).billingPortal) mux.HandleFunc("POST /settings/billing/portal", (*Server).billingPortal)
mux.HandleFunc("POST /settings/billing/keep", (*Server).billingKeep)
mux.HandleFunc("GET /settings/data", (*Server).dataPage) mux.HandleFunc("GET /settings/data", (*Server).dataPage)
mux.HandleFunc("POST /settings/data/export", (*Server).dataExport) mux.HandleFunc("POST /settings/data/export", (*Server).dataExport)
mux.HandleFunc("GET /settings/data/exports/{name}", (*Server).dataDownload) mux.HandleFunc("GET /settings/data/exports/{name}", (*Server).dataDownload)
+11
View File
@@ -13,6 +13,17 @@
{{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}} {{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> </dl>
</section> </section>
{{if .Kept}}
<section class="card">
<h3>Who keeps editing</h3>
<p>The {{.Plan.Name}} plan has {{.Plan.Seats}} people, and the team has {{.People}}. Everyone keeps their account and can read; only {{.Plan.Seats}} change things.{{if not .Owner}} The team's owner chooses who.{{end}} Nothing is deleted.</p>
<ul>{{range .Others}}<li>{{.Name}} &lt;{{.Email}}&gt;: {{if index $.Data.Kept .ID}}<strong>edits</strong>{{else}}<span class="muted">reads</span>{{end}}</li>{{end}}</ul>
{{if .Owner}}<form method="post" action="/settings/billing/keep" class="inline">
<label>Keeps editing, with you <select name="user">{{range .Others}}<option value="{{.ID}}"{{if index $.Data.Kept .ID}} selected{{end}}>{{.Name}}</option>{{end}}</select></label>
<button type="submit" class="secondary">Save</button>
</form>{{end}}
</section>
{{end}}
{{if .Owner}} {{if .Owner}}
{{if ne .Account.Status "active"}} {{if ne .Account.Status "active"}}
<form class="card" method="post" action="/settings/billing/checkout"> <form class="card" method="post" action="/settings/billing/checkout">
+1
View File
@@ -24,6 +24,7 @@
<label>Name <input name="name" value="{{.Form.Name}}" required></label> <label>Name <input name="name" value="{{.Form.Name}}" required></label>
</div> </div>
{{template "access-fields" (dict "Role" .Form.Role "Modules" .Form.Modules "Grants" .Grants)}} {{template "access-fields" (dict "Role" .Form.Role "Modules" .Form.Modules "Grants" .Grants)}}
{{if .Form.SeatOffer}}<label class="check"><input type="checkbox" name="add_seat" value="1" required> Add a seat for them</label>{{end}}
<p class="help">They get an email with a link that works once, for 7 days, to choose a password and fill in their profile.</p> <p class="help">They get an email with a link that works once, for 7 days, to choose a password and fill in their profile.</p>
<button type="submit">Send the invitation</button> <button type="submit">Send the invitation</button>
</form> </form>
+9
View File
@@ -166,6 +166,7 @@ type inviteForm struct {
Role users.Role Role users.Role
Modules map[string]users.Access Modules map[string]users.Access
Problem string Problem string
SeatOffer bool // the owner may add a seat for them
} }
func (s *Server) usersPage(w http.ResponseWriter, r *http.Request) { func (s *Server) usersPage(w http.ResponseWriter, r *http.Request) {
@@ -229,6 +230,7 @@ func (s *Server) userInvite(w http.ResponseWriter, r *http.Request) {
// to this one, with the account they have. // to this one, with the account they have.
if _, err := users.MembershipOf(s.platform(), s.team(), old.ID); err == nil || !s.multi() || old.Kind != users.Person { if _, err := users.MembershipOf(s.platform(), s.team(), old.ID); err == nil || !s.multi() || old.Kind != users.Person {
f.Problem = "Someone has that email address already: they're in the list below." f.Problem = "Someone has that email address already: they're in the list below."
} else if f.Problem, f.SeatOffer = s.seatCheck(r, v, true); f.Problem != "" {
} else { } else {
if err := s.addExisting(v, old, role, mods, time.Now()); err != nil { if err := s.addExisting(v, old, role, mods, time.Now()); err != nil {
s.serverError(w, err) s.serverError(w, err)
@@ -243,6 +245,9 @@ func (s *Server) userInvite(w http.ResponseWriter, r *http.Request) {
return return
} }
} }
if f.Problem == "" {
f.Problem, f.SeatOffer = s.seatCheck(r, v, true)
}
if f.Problem != "" { if f.Problem != "" {
s.renderUsers(w, r, v, f, http.StatusUnprocessableEntity) s.renderUsers(w, r, v, f, http.StatusUnprocessableEntity)
return return
@@ -432,6 +437,10 @@ func (s *Server) userAction(w http.ResponseWriter, r *http.Request) {
return return
} }
case "enable": case "enable":
if problem, _ := s.seatCheck(r, v, false); problem != "" {
s.renderUser(w, r, v, u, m, problem, http.StatusUnprocessableEntity)
return
}
status := users.Active status := users.Active
if !u.HasPassword { if !u.HasPassword {
status = users.Invited // never joined: invite them again status = users.Invited // never joined: invite them again