Phase 4 part 2: MRR, its movements, NRR and cohorts

Each customer's MRR at each month's end, from the recurring lines of paid
and open invoices: the amount after discounts over the billing interval,
prorations over their part-period. Moves are new, expansion, contraction,
churn and reactivation (sub-dollar noise ignored); NRR monthly and over
12 months; cohorts by first paid month. A start month, suggested when
most of the business appears at once (billing moved to Stripe), makes
those customers the base. Metrics page with a chart, the month table,
cohorts, and each month's customer moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 12:17:53 -07:00
co-authored by Claude Opus 5.5
parent 2c242d8c94
commit 5e799c7541
11 changed files with 860 additions and 2 deletions
+33
View File
@@ -7,6 +7,7 @@ import (
"net/url"
"strings"
"testing"
"time"
"supermarket/internal/profile"
"supermarket/internal/secrets"
@@ -76,3 +77,35 @@ func TestMarginsForm(t *testing.T) {
t.Error("a bad default was accepted")
}
}
func TestMRRPages(t *testing.T) {
s, h := newTestServer(t, nil)
s.DB.Exec(`INSERT INTO stripe_objects (kind, id, currency, data) VALUES ('invoice', 'in_0', 'usd', '{}'),
('customer', 'cus_a', '', '{"id":"cus_a","name":"Acme","email":"a@acme.example"}')`)
now := time.Now().UTC()
for i := 3; i >= 0; i-- {
start := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -i, 0)
s.DB.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, customer, status, currency, amount, period_start, period_end, interval, interval_count, recurring)
VALUES (?, ?, 'cus_a', 'paid', 'usd', 9900, ?, ?, 'month', 1, 1)`, fmt.Sprint("in_", i), fmt.Sprint("il_", i), start.Unix(), start.AddDate(0, 1, 0).Unix())
}
body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String()
for _, want := range []string{"$99", "ARR $1,188", "Month by month", "<svg class=\"chart\"", "Cohorts"} {
if !strings.Contains(body, want) {
t.Errorf("metrics lacks %q", want)
}
}
first := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -3, 0).Format("2006-01")
if body := do(h, http.MethodGet, "/metrics/month/"+first, nil, nil).Body.String(); !strings.Contains(body, "Acme") || !strings.Contains(body, "new") {
t.Errorf("month detail: %s", first)
}
if rec := do(h, http.MethodGet, "/metrics/month/1999-01", nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("unknown month: %d", rec.Code)
}
postForm(h, "/metrics/start", url.Values{"month": {first}})
if body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String(); !strings.Contains(body, "Counted from "+first) {
t.Error("the start month isn't used")
}
if rec := postForm(h, "/metrics/start", url.Values{"month": {"soon"}}); !strings.Contains(rec.Body.String(), "isn&#39;t a month") {
t.Errorf("bad month: %s", rec.Body)
}
}
+78
View File
@@ -26,12 +26,90 @@ func (s *Server) renderMetrics(w http.ResponseWriter, r *http.Request, errMsg st
s.serverError(w, err)
return
}
model, err := metrics.Build(s.DB, time.Now())
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "metrics", page{Title: "Metrics", Nav: "metrics/overview", Error: errMsg, Data: map[string]any{
"Stripe": s.stripe() != nil,
"Last": metrics.LastSync(s.DB),
"Counts": counts,
"Products": products,
"Margins": metrics.LoadMargins(s.DB),
"Model": model,
"Now": model.Last(),
"Recent": model.Recent(13),
"Bars": bars(model, 24),
"Cohorts": model.Cohorts(12, 12),
"Span": make([]int, 13),
}})
}
// bar is one month on the MRR chart.
type bar struct {
Month string
MRR float64
X, W, H float64 // in the SVG's units
Y float64
Label bool
}
// bars lays out the last n months of MRR as an SVG bar chart, 600 by 160.
func bars(m *metrics.Model, n int) []bar {
ms := m.Months
if len(ms) > n {
ms = ms[len(ms)-n:]
}
top := 0.0
for _, mo := range ms {
top = max(top, mo.MRR)
}
if top == 0 || len(ms) == 0 {
return nil
}
w := 600.0 / float64(len(ms))
out := make([]bar, len(ms))
for i, mo := range ms {
h := 140 * mo.MRR / top
out[i] = bar{Month: mo.Month, MRR: mo.MRR, X: float64(i)*w + 1, W: w - 2, H: h, Y: 150 - h, Label: i%3 == 0 || i == len(ms)-1}
}
return out
}
// metricsStart sets the month the metrics count from.
func (s *Server) metricsStart(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := metrics.SetStartMonth(s.DB, strings.TrimSpace(r.PostFormValue("month"))); err != nil {
s.renderMetrics(w, r, err.Error())
return
}
redirect(w, r, "/metrics", "saved")
}
// metricsMonth shows one month's moves, customer by customer.
func (s *Server) metricsMonth(w http.ResponseWriter, r *http.Request) {
model, err := metrics.Build(s.DB, time.Now())
if err != nil {
s.serverError(w, err)
return
}
month := r.PathValue("month")
mo := model.Find(month)
if mo == nil {
http.NotFound(w, r)
return
}
names, err := metrics.CustomerNames(s.DB)
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "metrics-month", page{Title: "MRR in " + month, Nav: "metrics/overview", Data: map[string]any{
"M": mo, "Changes": model.Changes(month, names),
}})
}
+14 -1
View File
@@ -7,6 +7,7 @@ import (
"html/template"
"io/fs"
"log/slog"
"math"
"net"
"net/http"
"net/url"
@@ -162,6 +163,8 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /metrics", s.metricsPage)
mux.HandleFunc("POST /metrics/sync", s.metricsSync)
mux.HandleFunc("POST /metrics/margins", s.metricsMargins)
mux.HandleFunc("POST /metrics/start", s.metricsStart)
mux.HandleFunc("GET /metrics/month/{month}", s.metricsMonth)
mux.HandleFunc("GET /seo", s.seoPage)
mux.HandleFunc("GET /seo/check", s.seoCheckPage)
mux.HandleFunc("GET /seo/engines", s.seoEnginesPage)
@@ -305,7 +308,17 @@ func (s *Server) loadTemplates() error {
},
"xreserve": twitter.URLReserve,
// money shows cents as dollars: $1,234 or $12.50.
"money": money,
"money": money,
// usd shows float cents as whole dollars: $9,835.
"usd": func(cents float64) string { return money(int64(math.Round(cents/100)) * 100) },
"mul12": func(f float64) float64 { return 12 * f },
"sub": func(a, b float64) float64 { return a - b },
"pct": func(f float64) string {
if f < 0 {
return "·"
}
return strconv.FormatFloat(f, 'f', 0, 64) + "%"
},
"num": seo.Thousands,
"cls": func(x100 int) float64 { return float64(x100) / 100 },
"dec1": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) },
+9
View File
@@ -436,3 +436,12 @@ table.runs { margin-top: 0.75rem; }
.checks li, .list td .small, .list td a { overflow-wrap: anywhere; }
textarea.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.9rem; }
/* Metrics */
svg.chart { width: 100%; height: auto; margin: 0.75rem 0 0.25rem; }
svg.chart rect { fill: hsl(var(--primary)); opacity: 0.85; }
svg.chart rect:hover { opacity: 1; }
svg.chart text { font-size: 9px; fill: hsl(var(--muted-foreground)); }
table.cohorts td, table.cohorts th { padding-left: 0.4rem; padding-right: 0.4rem; font-size: 0.85rem; }
.table-wrap { overflow-x: auto; }
table.compact th, table.compact td { white-space: nowrap; padding-left: 0.5rem; padding-right: 0.5rem; font-size: 0.85rem; }
+17
View File
@@ -0,0 +1,17 @@
{{define "content"}}{{with .Data}}{{$m := .M}}
<div class="heading">
<h1>MRR in {{$m.Month}}</h1>
<div class="buttons"><a class="button secondary" href="/metrics">Metrics</a></div>
</div>
<p class="lede">{{usd $m.MRR}} from {{num $m.Customers}} customers{{if $m.Partial}}, so far this month{{end}}. Net change {{usd $m.NetNew}}: new {{usd $m.New}}, expansion {{usd $m.Expansion}}, reactivation {{usd $m.Reactivation}}, contraction −{{usd $m.Contraction}}, churn −{{usd $m.Churn}}.</p>
{{if .Changes}}
<table class="list">
<thead><tr><th>Customer</th><th>Movement</th><th class="num">MRR before</th><th class="num">After</th><th class="num">Change</th></tr></thead>
<tbody>{{range .Changes}}<tr>
<td>{{or .Customer.Name .Customer.Email .Customer.ID}}{{if and .Customer.Name .Customer.Email}} <span class="muted small">{{.Customer.Email}}</span>{{end}}</td>
<td><span class="badge {{if or (eq .Kind "churn") (eq .Kind "contraction")}}failed{{else}}published{{end}}">{{.Kind}}</span></td>
<td class="num">{{usd .Before}}</td><td class="num">{{usd .After}}</td><td class="num">{{usd (sub .After .Before)}}</td>
</tr>{{end}}</tbody>
</table>
{{else}}<p class="help">No customer moved this month.</p>{{end}}
{{end}}{{end}}
+59
View File
@@ -7,6 +7,65 @@
</div>
<p class="lede">MRR and its movements, NRR, CAC and CLV, computed from your Stripe data: every customer, invoice, credit note and refund. MRR comes from the invoice lines (what each customer was billed, for which period), so past months are exact. Supermarket only reads Stripe.</p>
{{with .Now}}{{$d := $.Data}}
{{with $d.Model.Suggest}}
<section class="card">
<p class="warn-text">In {{.Month}}, {{.Customers}} customers ({{usd .MRR}} of MRR) appear in Stripe at once. That usually means billing moved to Stripe then, not that they all signed up that month. Counting from {{.Month}} makes them the starting base instead of new customers.</p>
<div class="row">
<form method="post" action="/metrics/start"><input type="hidden" name="month" value="{{.Month}}"><button type="submit" class="small">Count from {{.Month}}</button></form>
<form method="post" action="/metrics/start"><input type="hidden" name="month" value="all"><button type="submit" class="secondary small">Keep counting everything</button></form>
</div>
</section>
{{end}}
<section class="card">
<h2>MRR {{if .Partial}}<span class="muted small">today</span>{{else}}<span class="muted small">at the end of {{.Month}}</span>{{end}}</h2>
<div class="funnel">
<div class="step"><span class="label">MRR</span><strong>{{usd .MRR}}</strong><span class="rate">ARR {{usd (mul12 .MRR)}}</span></div>
<div class="step"><span class="label">Paying customers</span><strong>{{num .Customers}}</strong></div>
<div class="step"><span class="label">Average per customer</span><strong>{{usd .ARPA}}</strong></div>
<div class="step"><span class="label">NRR, this month</span><strong>{{pct .NRR}}</strong><span class="rate">of last month's MRR kept</span></div>
<div class="step"><span class="label">NRR, 12 months</span><strong>{{pct .NRR12}}</strong><span class="rate">what customers of a year ago pay now</span></div>
</div>
{{with $d.Bars}}
<svg class="chart" viewBox="0 0 600 170" role="img" aria-label="MRR by month">
{{range .}}<rect x="{{.X}}" y="{{.Y}}" width="{{.W}}" height="{{.H}}"><title>{{.Month}}: {{usd .MRR}}</title></rect>{{if .Label}}<text x="{{.X}}" y="166">{{.Month}}</text>{{end}}{{end}}
</svg>
{{end}}
<p class="small muted">From the invoice lines of paid and open invoices, in {{$d.Model.Currency}}: each recurring line's amount after discounts, spread over its billing period. Trials ($0), one-off charges, void and uncollectible invoices don't count.{{with $d.Model.Start}}{{if ne . "all"}} Counted from {{.}}.{{end}}{{end}}</p>
</section>
<h2>Month by month</h2>
<div class="table-wrap"><table class="list compact">
<thead><tr><th>Month</th><th class="num">MRR</th><th class="num">Customers</th><th class="num">Net change</th><th class="num">NRR</th><th class="num">New</th><th class="num">Expansion</th><th class="num">Contraction</th><th class="num">Churn</th><th class="num">Reactivation</th></tr></thead>
<tbody>{{range $d.Recent}}<tr>
<td><a href="/metrics/month/{{.Month}}">{{.Month}}</a>{{if .Partial}} <span class="muted small">so far</span>{{end}}</td>
<td class="num">{{usd .MRR}}</td><td class="num">{{num .Customers}}</td>
<td class="num"><strong>{{usd .NetNew}}</strong></td>
<td class="num">{{pct .NRR}}</td>
<td class="num">{{if .New}}{{usd .New}} <span class="muted small">({{.NewCount}})</span>{{else}}<span class="muted">·</span>{{end}}</td>
<td class="num">{{if .Expansion}}{{usd .Expansion}}{{else}}<span class="muted">·</span>{{end}}</td>
<td class="num">{{if .Contraction}}−{{usd .Contraction}}{{else}}<span class="muted">·</span>{{end}}</td>
<td class="num">{{if .Churn}}−{{usd .Churn}} <span class="muted small">({{.ChurnCount}})</span>{{else}}<span class="muted">·</span>{{end}}</td>
<td class="num">{{if .Reactivation}}{{usd .Reactivation}}{{else}}<span class="muted">·</span>{{end}}</td>
</tr>{{end}}</tbody>
</table></div>
{{if $d.Cohorts}}
<h2>Cohorts</h2>
<p class="help">Customers by the month they first paid, and the share of their first month's MRR they pay each month after: above 100% means they grew.</p>
<div class="table-wrap"><table class="list compact cohorts">
<thead><tr><th>First paid</th><th class="num">Customers</th><th class="num">Starting MRR</th>{{range $i, $_ := $d.Span}}<th class="num">{{$i}}</th>{{end}}</tr></thead>
<tbody>{{range $d.Cohorts}}<tr><td>{{.Month}}</td><td class="num">{{.Customers}}</td><td class="num">{{usd .Start}}</td>{{range .Retained}}<td class="num">{{if ge . 0.0}}{{pct .}}{{end}}</td>{{end}}</tr>{{end}}</tbody>
</table></div>
{{end}}
<form method="post" action="/metrics/start" class="row small">
<label class="small">Count from <input name="month" value="{{with $d.Model.Start}}{{if ne . "all"}}{{.}}{{end}}{{end}}" placeholder="YYYY-MM, empty for everything" size="12"></label>
<button type="submit" class="secondary small">Save</button>
</form>
{{end}}
<section class="card">
<h2>Stripe</h2>
{{if not .Stripe}}