Files
supermarket/internal/web/billing.go
T
davidandClaude Opus 5.5 aa0408fb14 Phase 14, part 4: what happens when it lapses
An hourly platform job: a trial over without a subscription goes to Free;
past due, the owner is told and every page has a banner; at 14 days
read-only; at 53 days everyone is warned; at 60 days the team is deleted
with 30 days to undo. Each email once. Undoing a deletion for not paying
gives a week more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:27:03 -07:00

382 lines
13 KiB
Go

package web
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"supermarket/internal/appmail"
"supermarket/internal/audit"
"supermarket/internal/billing"
"supermarket/internal/users"
)
// Settings → Billing (the multi-tenant edition, with billing on): the
// team's plan, people, storage and next invoice. The owner subscribes
// through Stripe Checkout and pays, or reads the invoices, in Stripe's
// Customer Portal; admins see the plan, not the payment details.
// billingStripe is the platform's Stripe account; tests replace it.
func (s *Server) billingStripe() *billing.Stripe {
st := s.st()
st.mu.Lock()
defer st.mu.Unlock()
if st.stripe == nil && s.Config != nil && s.Config.StripeKey != "" {
st.stripe = billing.NewStripe(s.Config.StripeKey)
}
return st.stripe
}
type billingData struct {
Owner bool
Account *billing.Account
Plan *billing.Plan
Paid *billing.Plan
ReadOnly bool
People int
Agents int
Storage int64
StorageOf int64
Invoice *billing.Invoice
InvoiceErr string
Yearly bool
Problem string
}
// people counts the team's people (not agents), invited ones too.
func (s *Server) people() (people, agents int) {
list, err := users.Members(s.platform(), s.team())
if err != nil {
return 0, 0
}
for _, m := range list {
switch {
case m.Kind == users.Agent && m.Status == users.Active:
agents++
case m.Kind == users.Person && m.Status != users.Disabled:
people++
}
}
return
}
func (s *Server) billingPage(w http.ResponseWriter, r *http.Request) {
s.renderBilling(w, r, "")
}
func (s *Server) renderBilling(w http.ResponseWriter, r *http.Request, problem string) {
if !s.billingOn() {
http.NotFound(w, r)
return
}
v := viewerOf(r)
a, err := billing.Get(s.platform(), s.team())
if err != nil {
s.serverError(w, err)
return
}
plan, ro := a.Effective(s.Plans, time.Now())
d := billingData{Owner: v.Member.Role == users.Owner && !v.Viewing, Account: a, Plan: plan, ReadOnly: ro,
Paid: s.Plans.Get(s.Plans.Paid), Problem: problem, Storage: a.StorageUsed}
d.People, d.Agents = s.people()
seats := a.Seats
if seats == 0 {
seats = d.People
}
d.StorageOf = plan.StorageBytes(seats, a.StorageBlocks)
d.Yearly = d.Paid.PriceYear != ""
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)
cancel()
if err != nil {
d.InvoiceErr = err.Error()
}
}
s.render(w, r, "billing", page{Title: "Billing", Nav: "settings/billing", Data: d})
}
// billingCheckout sends the owner to Stripe Checkout to subscribe.
func (s *Server) billingCheckout(w http.ResponseWriter, r *http.Request) {
v := s.owner(w, r)
if v == nil || !s.billingOn() {
if v != nil {
http.NotFound(w, r)
}
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
a, err := billing.Get(s.platform(), s.team())
if err != nil {
s.serverError(w, err)
return
}
paid := s.Plans.Get(s.Plans.Paid)
price := paid.PriceMonth
if r.PostFormValue("interval") == "year" && paid.PriceYear != "" {
price = paid.PriceYear
}
if a.Customer == "" {
t, _ := users.GetTeam(s.platform(), s.team())
name := ""
if t != nil {
name = t.Name
}
if a.Customer, err = s.billingStripe().CreateCustomer(ctx, v.User.Email, name, s.team()); err != nil {
s.renderBilling(w, r, sentence(err.Error())+".")
return
}
if a.Plan == "" {
a.Plan = s.Plans.Paid
}
if err := billing.Save(s.platform(), a, time.Now()); err != nil {
s.serverError(w, err)
return
}
}
people, _ := s.people()
addr, err := s.billingStripe().CheckoutURL(ctx, billing.Checkout{Customer: a.Customer, Price: price, Quantity: people, Team: s.team(),
Success: s.PublicURL + "/settings/billing?msg=subscribed", Cancel: s.PublicURL + "/settings/billing", Tax: s.Plans.Tax})
if err != nil {
s.renderBilling(w, r, sentence(err.Error())+".")
return
}
s.audit(r, "billing-checkout", paid.Name, fmt.Sprintf("%d people", people))
http.Redirect(w, r, addr, http.StatusSeeOther)
}
// billingPortal sends the owner to Stripe's Customer Portal.
func (s *Server) billingPortal(w http.ResponseWriter, r *http.Request) {
v := s.owner(w, r)
if v == nil || !s.billingOn() {
if v != nil {
http.NotFound(w, r)
}
return
}
a, err := billing.Get(s.platform(), s.team())
if err != nil {
s.serverError(w, err)
return
}
if a.Customer == "" {
s.renderBilling(w, r, "Subscribe first: there are no payments or invoices yet.")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
addr, err := s.billingStripe().PortalURL(ctx, a.Customer, s.PublicURL+"/settings/billing")
if err != nil {
s.renderBilling(w, r, sentence(err.Error())+".")
return
}
http.Redirect(w, r, addr, http.StatusSeeOther)
}
// stripeWebhook takes Stripe's events (POST /billing/stripe), with their
// signatures checked; each is handled once.
func (s *Server) stripeWebhook(w http.ResponseWriter, r *http.Request) {
if !s.billingOn() || s.Config == nil {
http.NotFound(w, r)
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
http.Error(w, "too large", http.StatusRequestEntityTooLarge)
return
}
now := time.Now()
if err := billing.VerifySignature(r.Header.Get("Stripe-Signature"), body, s.Config.StripeWebhookSecret, now); err != nil {
s.Log.Warn("billing: a webhook refused", "err", err, "ip", clientIP(r))
http.Error(w, "bad signature", http.StatusBadRequest)
return
}
var e billing.Event
if err := json.Unmarshal(body, &e); err != nil || e.ID == "" {
http.Error(w, "unreadable event", http.StatusBadRequest)
return
}
var seen int
_ = s.platform().QueryRow(`SELECT count(*) FROM stripe_events WHERE id = ?`, e.ID).Scan(&seen)
if seen > 0 {
w.WriteHeader(http.StatusOK) // already handled
return
}
load := func(team int64, customer string) (*billing.Account, error) {
if customer != "" {
if a, err := billing.ByCustomer(s.platform(), customer); err == nil {
return a, nil
}
}
if team == 0 {
return nil, nil
}
if _, err := users.GetTeam(s.platform(), team); err != nil {
return nil, nil // not one of ours
}
return billing.Get(s.platform(), team)
}
a, change, err := billing.Apply(load, s.Plans, &e, now)
if err != nil {
s.Log.Error("billing: handling an event", "event", e.ID, "type", e.Type, "err", err)
http.Error(w, "couldn't handle it", http.StatusInternalServerError) // Stripe tries again
return
}
if a != nil {
if err := billing.Save(s.platform(), a, now); err != nil {
s.Log.Error("billing: saving", "event", e.ID, "err", err)
http.Error(w, "couldn't save it", http.StatusInternalServerError)
return
}
if ts, err := s.forTeam(a.Team); err == nil {
detail := e.Type
if change.Note != "" {
detail = change.Note
}
ts.record(audit.Entry{Kind: audit.System, Action: "billing", Target: change.Before + " → " + change.After, Detail: detail})
}
s.Log.Info("billing: event", "type", e.Type, "team", a.Team, "status", a.Status)
}
if _, err := billing.SeenEvent(s.platform(), e.ID, e.Type, now); err != nil {
s.Log.Warn("billing: noting an event", "err", err)
}
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)
}
}