diff --git a/PLAN.md b/PLAN.md index 7941175..e91b59e 100644 --- a/PLAN.md +++ b/PLAN.md @@ -3272,6 +3272,20 @@ Checkout; both are off until set. - Stripe's dashboard needs the endpoint `https:///billing/stripe` with those events. +**Part 4 built 2026-11-26.** +- An hourly platform job (`platform:billing`, one copy at a time) looks at + every team's account, and emails each step once (`billing.warned`): + - a trial over without a subscription: the Free plan, and the owner told; + - past due: the owner told, and every page shows a banner (the owner's + with *Pay now*); + - 14 days: read-only (part 1), and the owner told; + - 53 days: everyone in the team told it goes in a week; + - 60 days: deleted as in Phase 13, part 8 (30 days to undo), and + everyone told. +- An owner undoing a deletion for not paying has a week more to pay, read + only, before it's deleted again. Paying (`invoice.paid`) clears it all. +- Each step goes in the team's audit log. + #### Order ``` diff --git a/internal/web/activity.go b/internal/web/activity.go index 3a4a6d1..1efaac3 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:", "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": "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/billing.go b/internal/web/billing.go index c62b173..0580e9d 100644 --- a/internal/web/billing.go +++ b/internal/web/billing.go @@ -8,6 +8,7 @@ import ( "net/http" "time" + "supermarket/internal/appmail" "supermarket/internal/audit" "supermarket/internal/billing" "supermarket/internal/users" @@ -245,3 +246,136 @@ func (s *Server) stripeWebhook(w http.ResponseWriter, r *http.Request) { } w.WriteHeader(http.StatusOK) } + +// Lapses: an hourly look at every team's account (the platform's job). +// - a trial ended without a subscription: the Free plan, and the owner told +// - past due: the owner told (and a banner, lapseBanner) +// - past due 14 days: read-only (billing.Effective), and the owner told +// - past due 53 days: everyone told the team goes in a week +// - past due 60 days: deleted as an owner's deletion is (30 days to undo) + +const warnBeforeDelete = 7 * 24 * time.Hour + +func (s *Server) billingTurn(ctx context.Context, now time.Time) { + if !s.billingOn() { + return + } + accts, err := billing.All(s.platform()) + if err != nil { + s.Log.Error("billing: listing accounts", "err", err) + return + } + for _, a := range accts { + t, err := users.GetTeam(s.platform(), a.Team) + if err != nil || t.Status == users.TeamDeleting { + continue + } + ts, err := s.forTeam(a.Team) + if err != nil { + continue + } + note := func(action, detail string) { + ts.record(audit.Entry{Kind: audit.System, Action: action, Target: t.Name, Detail: detail}) + s.Log.Info("billing: "+action, "team", t.ID) + } + save := func() { + if err := billing.Save(s.platform(), a, now); err != nil { + s.Log.Error("billing: saving", "team", a.Team, "err", err) + } + } + owner := ts.ownerOf() + switch { + case a.Status == billing.Trialing && a.Subscription == "" && !now.Before(a.TrialEnds): + a.Status = billing.Free + save() + note("trial-ended", "now on the Free plan") + ts.mailOwner(owner, "Your Supermarket trial has ended", "The trial of "+s.Plans.Get(s.Plans.Paid).Name+" for "+t.Name+ + " has ended, so the team is on the Free plan now: what's outside it stays, to read. To keep everything, subscribe:\n"+s.PublicURL+"/settings/billing") + case a.Status == billing.PastDue && !a.PastDueSince.IsZero(): + late := now.Sub(a.PastDueSince) + switch { + case late >= billing.DeleteAfter && a.Warned != "deleting": + a.Warned = "deleting" + save() + when := now.Add(DeleteAfter) + if err := users.SetTeamStatus(s.platform(), t.ID, users.TeamDeleting, when); err != nil { + s.Log.Error("billing: deleting a lapsed team", "team", t.ID, "err", err) + continue + } + note("team-deleting", "the payment has been due 60 days") + s.tellTeam(t, t.Name+" is being deleted from Supermarket", "The payment for "+t.Name+" has been due for 60 days, so the team is being deleted. Its data goes for good on "+ + when.Format("2 January 2006")+". Until then, its owner can undo it when signing in, then pay under Settings → Billing.") + case late >= billing.DeleteAfter-warnBeforeDelete && late < billing.DeleteAfter && a.Warned != "deleting-soon" && a.Warned != "deleting": + a.Warned = "deleting-soon" + save() + note("lapse-warned", "deleted in a week") + s.tellTeam(t, t.Name+" will be deleted in a week", "The payment for "+t.Name+" has been due since "+a.PastDueSince.Format("2 January")+ + ". Unless it's paid, the team will be deleted in a week. Its owner can pay under Settings → Billing:\n"+s.PublicURL+"/settings/billing") + case late >= billing.ReadOnlyAfter && late < billing.DeleteAfter-warnBeforeDelete && a.Warned != "read-only": + a.Warned = "read-only" + save() + note("lapse-read-only", "the payment has been due 14 days") + ts.mailOwner(owner, t.Name+" is read-only until it's paid", "The payment for "+t.Name+" has been due for 14 days, so the team is read-only: nothing is fetched, sent or published, and agents are refused. Pay under Settings → Billing to carry on:\n"+s.PublicURL+"/settings/billing") + case late < billing.ReadOnlyAfter && a.Warned == "": + a.Warned = "past-due" + save() + note("lapse-due", "a payment failed") + ts.mailOwner(owner, "A payment for "+t.Name+" failed", "Stripe couldn't take the payment for "+t.Name+ + ". Update the card under Settings → Billing within 14 days, or the team becomes read-only:\n"+s.PublicURL+"/settings/billing") + } + } + } +} + +// ownerOf is the team's owner. +func (s *Server) ownerOf() *users.User { + list, err := users.Members(s.platform(), s.team()) + if err != nil { + return nil + } + for _, m := range list { + if m.Role == users.Owner { + return m.User + } + } + return nil +} + +func (s *Server) mailOwner(u *users.User, subject, body string) { + if u == nil { + return + } + s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: subject, Body: "Hello" + nameSuffix(u.Name) + ",\n\n" + body + "\n"}) +} + +// lapseBanner is what every page of a team behind on its payment says. +func (s *Server) lapseBanner() string { + if !s.billingOn() || s.team() == 0 { + return "" + } + a, err := billing.Get(s.platform(), s.team()) + if err != nil || a.Status != billing.PastDue || a.PastDueSince.IsZero() { + return "" + } + if _, ro := a.Effective(s.Plans, time.Now()); ro { + return "The team's payment has been due since " + a.PastDueSince.Local().Format("2 Jan") + ", so it's read-only: nothing is fetched, sent or published. Its owner can pay under Settings → Billing." + } + return "The team's payment is due since " + a.PastDueSince.Local().Format("2 Jan") + ". Its owner can pay under Settings → Billing; after 14 days the team becomes read-only." +} + +// lapseUndone: a team deleted for not paying, brought back by its owner, +// has a week to pay before it's deleted again. +func (s *Server) lapseUndone(team int64, now time.Time) { + if !s.billingOn() { + return + } + a, err := billing.Get(s.platform(), team) + if err != nil || a.Status != billing.PastDue || a.Warned != "deleting" { + return + } + a.PastDueSince = now.Add(-billing.DeleteAfter + warnBeforeDelete) + a.Warned = "read-only" // the next turn warns of the week + if err := billing.Save(s.platform(), a, now); err != nil { + s.Log.Error("billing: saving", "team", team, "err", err) + } +} diff --git a/internal/web/data.go b/internal/web/data.go index 25e222a..7213237 100644 --- a/internal/web/data.go +++ b/internal/web/data.go @@ -228,6 +228,7 @@ func (s *Server) teamUndelete(w http.ResponseWriter, r *http.Request) { s.serverError(w, err) return } + s.lapseUndone(t.ID, time.Now()) ts, err := s.forTeam(t.ID) if err == nil { ts.record(audit.Entry{UserID: v.User.ID, UserName: displayName(v.User), Action: "team-undeleted", Target: t.Name, IP: clientIP(r)}) diff --git a/internal/web/lapse_test.go b/internal/web/lapse_test.go new file mode 100644 index 0000000..88c4db6 --- /dev/null +++ b/internal/web/lapse_test.go @@ -0,0 +1,101 @@ +package web + +import ( + "context" + "net/http" + "strings" + "testing" + "time" + + "supermarket/internal/appmail" + "supermarket/internal/billing" + "supermarket/internal/users" +) + +func TestLapses(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 + ob := s.Mail.(*appmail.Outbox) + now := time.Now() + turn := func(at time.Time) { s.billingTurn(context.Background(), at) } + subject := func(n int) string { + t.Helper() + return waitMail(t, s, "olu@acme.example", n).Subject + } + + // The trial ends without a subscription: Free, and an email. + before := ob.Count() + turn(now) + if a, _ := billing.Get(s.platform(), team); a.Status != billing.Trialing { + t.Fatalf("trial ended early: %+v", a) + } + turn(now.Add(15 * 24 * time.Hour)) + if a, _ := billing.Get(s.platform(), team); a.Status != billing.Free { + t.Errorf("after the trial: %+v", a) + } + if got := subject(before + 1); !strings.Contains(got, "trial has ended") { + t.Errorf("trial mail %q", got) + } + + // A failed payment: an email once, and a banner. + due := now.Add(-time.Hour) + setAccount(t, s, team, func(a *billing.Account) { + a.Status, a.Subscription, a.PastDueSince, a.Warned = billing.PastDue, "sub_1", due, "" + }) + before = ob.Count() + turn(now) + if got := subject(before + 1); !strings.Contains(got, "payment for Acme failed") { + t.Errorf("past-due mail %q", got) + } + turn(now) + time.Sleep(50 * time.Millisecond) + if ob.Count() != before+1 { + t.Error("the past-due mail went twice") + } + if rec := as(h, c, http.MethodGet, "/", nil); !strings.Contains(rec.Body.String(), "payment is due since") || !strings.Contains(rec.Body.String(), "Pay now") { + t.Errorf("no banner: %s", rec.Body) + } + + // 14 days: read-only, and an email. + turn(due.Add(15 * 24 * time.Hour)) + if got := subject(before + 2); !strings.Contains(got, "read-only") { + t.Errorf("read-only mail %q", got) + } + // 53 days: everyone's warned. + turn(due.Add(54 * 24 * time.Hour)) + if got := subject(before + 3); !strings.Contains(got, "deleted in a week") { + t.Errorf("warning mail %q", got) + } + // 60 days: deleting, with 30 days to undo. + turn(due.Add(61 * 24 * time.Hour)) + if got := subject(before + 4); !strings.Contains(got, "being deleted") { + t.Errorf("deleting mail %q", got) + } + tm, _ := users.GetTeam(s.platform(), team) + if tm.Status != users.TeamDeleting { + t.Fatalf("team %+v", tm) + } + if rec := as(h, c, http.MethodGet, "/", nil); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "Undo") { + t.Errorf("closed page: %d", rec.Code) + } + + // The owner undoes it: a week more to pay, warned at the next turn. + if rec := as(h, c, http.MethodPost, "/teams/undelete", nil); rec.Code != http.StatusSeeOther { + t.Fatalf("undelete: %d %s", rec.Code, rec.Body) + } + a, _ := billing.Get(s.platform(), team) + if a.Warned != "read-only" || time.Since(a.PastDueSince) < 52*24*time.Hour { + t.Errorf("after undoing: %+v", a) + } + if rec := as(h, c, http.MethodGet, "/", nil); !strings.Contains(rec.Body.String(), "read-only: nothing is fetched") { + t.Errorf("no read-only banner: %s", rec.Body) + } + n := ob.Count() + turn(time.Now()) + if got := waitMail(t, s, "olu@acme.example", n+1).Subject; !strings.Contains(got, "deleted in a week") { + t.Errorf("after undoing, mail %q", got) + } +} diff --git a/internal/web/server.go b/internal/web/server.go index a65f628..fd44b18 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -815,6 +815,7 @@ type page struct { TeamID int64 // the team they\'re working in Multi bool // the multi-tenant edition Billing bool // teams are billed (multi-tenant) + Lapse string // the team\'s payment is overdue: what the banner says Viewer *viewer // who's looking } @@ -894,6 +895,7 @@ func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, p p if !p.Bare { p.Approvals = s.waitingFor(p.Viewer) p.Teams, p.TeamID = s.teamsOf(p.Viewer), s.team() + p.Lapse = s.lapseBanner() } p.Multi, p.Billing = s.multi(), s.billingOn() out, err := withCSRF(r, func(b *bytes.Buffer) error { return t.ExecuteTemplate(b, "layout.html", p) }) diff --git a/internal/web/signin.go b/internal/web/signin.go index 8a5a4c6..b7ef3ea 100644 --- a/internal/web/signin.go +++ b/internal/web/signin.go @@ -479,6 +479,9 @@ func (s *Server) RunTeams(ctx context.Context) { tick := time.NewTicker(time.Hour) defer tick.Stop() for { + if _, err := s.jobs().Do(ctx, "platform:billing", func(ctx context.Context) { s.billingTurn(ctx, time.Now()) }); err != nil { + s.Log.Warn("billing: taking the lock", "err", err) + } if _, err := s.jobs().Do(ctx, "platform:purge", func(ctx context.Context) { s.purgeTeams(ctx, time.Now()) }); err != nil { s.Log.Warn("teams: taking the lock", "err", err) } diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index fe8aacf..8002fd9 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -128,6 +128,7 @@
{{with .Viewer}}{{if .Viewing}}

Viewing this team as the platform's admin, read-only, until {{.Session.ViewUntil.Local.Format "15:04"}}: {{.Session.ViewReason}}

{{end}}{{end}} + {{with .Lapse}}

{{.}} {{with $.Viewer}}{{if eq (print .Member.Role) "owner"}}Pay now{{end}}{{end}}

{{end}} {{if .Flash}}

{{.Flash}}

{{end}} {{if .Error}}{{end}} {{template "content" .}}