Files
supermarket/internal/web/billing.go
T
davidandClaude Opus 5.5 4833f53e0d Phase 14, part 3: Stripe's events
/billing/stripe takes Stripe's webhooks, signatures checked, each event
handled once, and keeps each team's subscription up to date: checkout, its
status, seats and period, failed and paid invoices, cancellation.

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

248 lines
7.1 KiB
Go

package web
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"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)
}