From 6d3eb18b5eb0eb6d40eea510e45f6a63e8ef8f07 Mon Sep 17 00:00:00 2001 From: David Young Date: Wed, 25 Nov 2026 13:34:22 -0700 Subject: [PATCH] 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 --- PLAN.md | 34 +++++ TEST.md | 47 ++++++- internal/db/teams.go | 9 ++ internal/users/users.go | 9 +- internal/web/access.go | 10 ++ internal/web/activity.go | 2 +- internal/web/auth.go | 6 + internal/web/billing.go | 54 ++++++++ internal/web/downgrade_test.go | 103 +++++++++++++++ internal/web/photo.go | 4 + internal/web/plans.go | 193 ++++++++++++++++++++++++++++ internal/web/seats_test.go | 86 +++++++++++++ internal/web/server.go | 1 + internal/web/templates/billing.html | 11 ++ internal/web/templates/users.html | 1 + internal/web/users.go | 9 ++ 16 files changed, 573 insertions(+), 6 deletions(-) create mode 100644 internal/web/downgrade_test.go create mode 100644 internal/web/seats_test.go diff --git a/PLAN.md b/PLAN.md index e91b59e..eca5e95 100644 --- a/PLAN.md +++ b/PLAN.md @@ -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 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 `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 @@ -3286,6 +3292,34 @@ Checkout; both are off until set. only, before it's deleted again. Paying (`invoice.paid`) clears it all. - 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 ``` diff --git a/TEST.md b/TEST.md index d1c4063..7672172 100644 --- a/TEST.md +++ b/TEST.md @@ -19,7 +19,7 @@ are run first on the local edition, on this computer. Then: |---|---|---| | **Local** | `install.sh` / `./update.sh`, at | 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 | -| **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 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 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:///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. diff --git a/internal/db/teams.go b/internal/db/teams.go index ae2d3d8..bd40fd6 100644 --- a/internal/db/teams.go +++ b/internal/db/teams.go @@ -221,3 +221,12 @@ func (t *Teams) Close() { 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 +} diff --git a/internal/users/users.go b/internal/users/users.go index 0dc3ea2..ad2f162 100644 --- a/internal/users/users.go +++ b/internal/users/users.go @@ -432,12 +432,13 @@ func HasOwner(d *db.DB, team int64) (bool, error) { type TeamUser struct { *User Membership + Joined time.Time // when they joined the team } // Members are the team's users, people first, then by name. func Members(d *db.DB, team int64) ([]TeamUser, error) { 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) if err != nil { return nil, err @@ -445,14 +446,14 @@ func Members(d *db.DB, team int64) ([]TeamUser, error) { defer rows.Close() var out []TeamUser for rows.Next() { - var role, modules string - u, err := scanUser(rowWith{rows, []any{&role, &modules}}) + var role, modules, joined string + u, err := scanUser(rowWith{rows, []any{&role, &modules, &joined}}) if err != nil { return nil, err } m := Membership{Team: team, User: u.ID, Role: Role(role), Modules: map[string]Access{}} _ = 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() } diff --git a/internal/web/access.go b/internal/web/access.go index b642fe0..4d99723 100644 --- a/internal/web/access.go +++ b/internal/web/access.go @@ -183,6 +183,16 @@ func (s *Server) allow(area string, next http.Handler) http.Handler { return } 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. 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 { diff --git a/internal/web/activity.go b/internal/web/activity.go index 1efaac3..a5463dc 100644 --- a/internal/web/activity.go +++ b/internal/web/activity.go @@ -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:", "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", "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", } diff --git a/internal/web/auth.go b/internal/web/auth.go index c195388..038365d 100644 --- a/internal/web/auth.go +++ b/internal/web/auth.go @@ -31,6 +31,9 @@ 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 + // 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. @@ -172,6 +175,9 @@ func (s *Server) lookupSession(r *http.Request) (*viewer, error) { if ts, err := s.forTeam(sess.Team); err == nil { plan, ro := ts.teamPlan() 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 diff --git a/internal/web/billing.go b/internal/web/billing.go index 0580e9d..36423ca 100644 --- a/internal/web/billing.go +++ b/internal/web/billing.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "net/http" + "strconv" "time" "supermarket/internal/appmail" @@ -44,6 +45,10 @@ type billingData struct { InvoiceErr string Yearly bool 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. @@ -88,6 +93,14 @@ func (s *Server) renderBilling(w http.ResponseWriter, r *http.Request, problem s } d.StorageOf = plan.StorageBytes(seats, a.StorageBlocks) 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 != "" { ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) 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) } } + 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() switch { 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) } } + +// 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") +} diff --git a/internal/web/downgrade_test.go b/internal/web/downgrade_test.go new file mode 100644 index 0000000..5248f63 --- /dev/null +++ b/internal/web/downgrade_test.go @@ -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") + } +} diff --git a/internal/web/photo.go b/internal/web/photo.go index cd7a4b3..f0fc001 100644 --- a/internal/web/photo.go +++ b/internal/web/photo.go @@ -37,6 +37,10 @@ func (s *Server) accountPhoto(w http.ResponseWriter, r *http.Request) { } key := "" 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) f, _, err := r.FormFile("photo") if err != nil { diff --git a/internal/web/plans.go b/internal/web/plans.go index f269dd8..ea59228 100644 --- a/internal/web/plans.go +++ b/internal/web/plans.go @@ -1,8 +1,11 @@ package web import ( + "context" "errors" "fmt" + "net/http" + "sort" "time" "supermarket/internal/billing" @@ -69,6 +72,9 @@ func (s *Server) jobAllowed(name string) bool { return name == "accounts" } m, ok := jobModule[name] + if name == "seo" && s.storageFull() != nil { + return false // a crawl keeps its pages + } return !ok || plan.Includes(m) } @@ -115,3 +121,190 @@ func (s *Server) crawlLimits() (int, time.Duration) { } 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 +} diff --git a/internal/web/seats_test.go b/internal/web/seats_test.go new file mode 100644 index 0000000..817f3a6 --- /dev/null +++ b/internal/web/seats_test.go @@ -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'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) + } +} diff --git a/internal/web/server.go b/internal/web/server.go index fd44b18..0f37f46 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -349,6 +349,7 @@ func (s *Server) Handler() (http.Handler, error) { 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("POST /settings/billing/keep", (*Server).billingKeep) mux.HandleFunc("GET /settings/data", (*Server).dataPage) mux.HandleFunc("POST /settings/data/export", (*Server).dataExport) mux.HandleFunc("GET /settings/data/exports/{name}", (*Server).dataDownload) diff --git a/internal/web/templates/billing.html b/internal/web/templates/billing.html index 9ab58a2..4d6f1e0 100644 --- a/internal/web/templates/billing.html +++ b/internal/web/templates/billing.html @@ -13,6 +13,17 @@ {{if .Owner}}{{with .Invoice}}
Next invoice
{{money .AmountDue}} {{.Currency}}, {{.Date.Local.Format "2 Jan 2006"}}
{{end}}{{with .InvoiceErr}}
Next invoice
{{.}}
{{end}}{{end}} +{{if .Kept}} +
+

Who keeps editing

+

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.

+
    {{range .Others}}
  • {{.Name}} <{{.Email}}>: {{if index $.Data.Kept .ID}}edits{{else}}reads{{end}}
  • {{end}}
+ {{if .Owner}}
+ + +
{{end}} +
+{{end}} {{if .Owner}} {{if ne .Account.Status "active"}}
diff --git a/internal/web/templates/users.html b/internal/web/templates/users.html index 0a08bf0..416fbef 100644 --- a/internal/web/templates/users.html +++ b/internal/web/templates/users.html @@ -24,6 +24,7 @@ {{template "access-fields" (dict "Role" .Form.Role "Modules" .Form.Modules "Grants" .Grants)}} + {{if .Form.SeatOffer}}{{end}}

They get an email with a link that works once, for 7 days, to choose a password and fill in their profile.

diff --git a/internal/web/users.go b/internal/web/users.go index f5906cd..dae790b 100644 --- a/internal/web/users.go +++ b/internal/web/users.go @@ -166,6 +166,7 @@ type inviteForm struct { Role users.Role Modules map[string]users.Access Problem string + SeatOffer bool // the owner may add a seat for them } 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. 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." + } else if f.Problem, f.SeatOffer = s.seatCheck(r, v, true); f.Problem != "" { } else { if err := s.addExisting(v, old, role, mods, time.Now()); err != nil { s.serverError(w, err) @@ -243,6 +245,9 @@ func (s *Server) userInvite(w http.ResponseWriter, r *http.Request) { return } } + if f.Problem == "" { + f.Problem, f.SeatOffer = s.seatCheck(r, v, true) + } if f.Problem != "" { s.renderUsers(w, r, v, f, http.StatusUnprocessableEntity) return @@ -432,6 +437,10 @@ func (s *Server) userAction(w http.ResponseWriter, r *http.Request) { return } case "enable": + if problem, _ := s.seatCheck(r, v, false); problem != "" { + s.renderUser(w, r, v, u, m, problem, http.StatusUnprocessableEntity) + return + } status := users.Active if !u.HasPassword { status = users.Invited // never joined: invite them again