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
+449
View File
@@ -0,0 +1,449 @@
package metrics
import (
"encoding/json"
"fmt"
"slices"
"time"
"supermarket/internal/db"
)
// line is an invoice line, as the MRR model needs it.
type line struct {
customer string
amount int64
start, end int64
interval string
intervalCount int
proration bool
product string
}
const avgMonthSeconds = 365.25 / 12 * 24 * 3600
// monthly is a line's contribution to MRR, in cents: its amount spread over
// its billing interval, or, for a proration, over the part period it
// covers.
func (l line) monthly() float64 {
if !l.proration {
n := float64(max(l.intervalCount, 1))
switch l.interval {
case "month":
return float64(l.amount) / n
case "year":
return float64(l.amount) / (12 * n)
case "week":
return float64(l.amount) * 52 / 12 / n
case "day":
return float64(l.amount) * 365 / 12 / n
}
}
months := float64(l.end-l.start) / avgMonthSeconds
if months <= 0 {
return 0
}
return float64(l.amount) / months
}
// loadLines reads the recurring lines of billed invoices (paid or open; not
// void, not uncollectible) in the main currency.
func loadLines(d *db.DB, currency string) ([]line, error) {
rows, err := d.Query(`SELECT customer, amount, period_start, period_end, interval, interval_count, proration, product
FROM stripe_invoice_lines WHERE recurring = 1 AND status IN ('paid', 'open') AND currency = ? AND customer != ''
AND period_end > period_start`, currency)
if err != nil {
return nil, err
}
defer rows.Close()
var out []line
for rows.Next() {
var l line
if err := rows.Scan(&l.customer, &l.amount, &l.start, &l.end, &l.interval, &l.intervalCount, &l.proration, &l.product); err != nil {
return nil, err
}
out = append(out, l)
}
return out, rows.Err()
}
// MainCurrency is the currency most invoices are in, or "".
func MainCurrency(d *db.DB) string {
cs, _ := currencies(d)
if len(cs) == 0 {
return ""
}
return cs[0]
}
// Movement kinds.
const (
MoveNew = "new"
MoveExpansion = "expansion"
MoveContraction = "contraction"
MoveChurn = "churn"
MoveReactivation = "reactivation"
)
// Month is one month's MRR and how it moved since the month before. Amounts
// are in cents.
type Month struct {
Month string // YYYY-MM
At time.Time
Partial bool // the current month, measured now
MRR float64
Customers int
New float64
Expansion float64
Contraction float64 // positive: the MRR lost
Churn float64 // positive
Reactivation float64
NewCount, ChurnCount int
NRR float64 // this month: kept MRR of last month's customers ÷ last month's MRR; -1 if none
NRR12 float64 // trailing 12 months: the customers paying 12 months ago, now; -1 if not enough history
// By customer, for the month's detail.
ByCustomer map[string]float64
Moves map[string]string // customer → movement kind
}
// ARPA is the average MRR per paying customer.
func (m Month) ARPA() float64 {
if m.Customers == 0 {
return 0
}
return m.MRR / float64(m.Customers)
}
// NetNew is the month's change in MRR.
func (m Month) NetNew() float64 {
return m.New + m.Expansion + m.Reactivation - m.Contraction - m.Churn
}
// Model is the MRR over time.
type Model struct {
Currency string
Months []Month // oldest first, from Start
First map[string]string // customer → the month they first paid (from Start)
Start string // the first month counted ("" for all)
Suggest *Suggestion // a start month worth considering, when none is set
}
// Suggestion is a month where most of the business appears at once, which
// usually means billing moved to Stripe then: counting from it keeps those
// customers from looking new.
type Suggestion struct {
Month string
Customers int
MRR float64
}
const startKey = "metrics:start"
// StartMonth is the month the metrics count from, or "".
func StartMonth(d *db.DB) string {
var s string
_, _ = d.GetJSON(startKey, &s)
return s
}
// SetStartMonth sets it ("" counts everything).
func SetStartMonth(d *db.DB, month string) error {
if month != "" {
if _, err := time.Parse("2006-01", month); err != nil {
return fmt.Errorf("%q isn't a month (YYYY-MM)", month)
}
}
return d.PutJSON(startKey, month)
}
// mrrAt is each customer's MRR at an instant: the lines whose period
// covers it.
func mrrAt(lines []line, t int64) map[string]float64 {
out := map[string]float64{}
for _, l := range lines {
if l.start <= t && t < l.end {
out[l.customer] += l.monthly()
}
}
for c, v := range out {
if v < 0.5 { // less than a cent: a trial, or credits that cancel out
delete(out, c)
}
}
return out
}
// Build works out MRR month by month, from the first billed month to now
// (the current month measured now, the others at their last second).
func Build(d *db.DB, now time.Time) (*Model, error) {
cur := MainCurrency(d)
m := &Model{Currency: cur, First: map[string]string{}, Start: StartMonth(d)}
if cur == "" {
return m, nil
}
lines, err := loadLines(d, cur)
if err != nil {
return nil, err
}
if len(lines) == 0 {
return m, nil
}
first := lines[0].start
for _, l := range lines {
first = min(first, l.start)
}
now = now.UTC()
month := time.Unix(first, 0).UTC()
month = time.Date(month.Year(), month.Month(), 1, 0, 0, 0, 0, time.UTC)
if s, err := time.Parse("2006-01", m.Start); err == nil && s.After(month) {
month = s
}
startMonth := month.Format("2006-01")
var prev map[string]float64
ever := map[string]bool{}
for !month.After(now) {
next := month.AddDate(0, 1, 0)
at, partial := next.Add(-time.Second), false
if at.After(now) {
at, partial = now, true
}
by := mrrAt(lines, at.Unix())
mo := Month{Month: month.Format("2006-01"), At: at, Partial: partial, ByCustomer: by, Moves: map[string]string{}, NRR: -1, NRR12: -1}
for c, v := range by {
mo.MRR += v
mo.Customers++
p := prev[c]
switch {
case mo.Month == startMonth && m.Start != "":
// Already paying when the count starts: the base, not new.
m.First[c] = mo.Month
case p == 0 && !ever[c]:
mo.New += v
mo.NewCount++
mo.Moves[c] = MoveNew
m.First[c] = mo.Month
case p == 0:
mo.Reactivation += v
mo.Moves[c] = MoveReactivation
case v > p+noise(p):
mo.Expansion += v - p
mo.Moves[c] = MoveExpansion
case v < p-noise(p):
mo.Contraction += p - v
mo.Moves[c] = MoveContraction
}
ever[c] = true
}
for c, p := range prev {
if _, still := by[c]; !still {
mo.Churn += p
mo.ChurnCount++
mo.Moves[c] = MoveChurn
}
}
if prevTotal := sum(prev); prevTotal > 0 {
kept := 0.0
for c := range prev {
kept += by[c] // what last month's customers pay now (0 if they left)
}
mo.NRR = 100 * kept / prevTotal
}
m.Months = append(m.Months, mo)
prev = by
month = next
}
if m.Start == "" {
m.Suggest = suggest(m.Months)
}
// Trailing 12 months: the customers paying 12 months before, now.
for i := 12; i < len(m.Months); i++ {
base := m.Months[i-12].ByCustomer
if total := sum(base); total > 0 {
kept := 0.0
for c := range base {
kept += m.Months[i].ByCustomer[c]
}
m.Months[i].NRR12 = 100 * kept / total
}
}
return m, nil
}
func sum(m map[string]float64) float64 {
t := 0.0
for _, v := range m {
t += v
}
return t
}
// Last is the latest month, or nil.
func (m *Model) Last() *Month {
if len(m.Months) == 0 {
return nil
}
return &m.Months[len(m.Months)-1]
}
// Find is a month by its YYYY-MM, or nil.
func (m *Model) Find(month string) *Month {
for i := range m.Months {
if m.Months[i].Month == month {
return &m.Months[i]
}
}
return nil
}
// Recent are the last n months, newest first.
func (m *Model) Recent(n int) []Month {
out := slices.Clone(m.Months)
slices.Reverse(out)
if len(out) > n {
out = out[:n]
}
return out
}
// Cohort is the customers who first paid in one month, and the share of
// their starting MRR they pay in each month after (net revenue retention by
// cohort).
type Cohort struct {
Month string
Customers int
Start float64 // their MRR in their first month
Retained []float64 // percent of Start, for month 0, 1, 2…; -1 beyond today
}
// Cohorts are the last n signup cohorts, newest first, each followed for up
// to span months.
func (m *Model) Cohorts(n, span int) []Cohort {
idx := map[string]int{}
for i, mo := range m.Months {
idx[mo.Month] = i
}
members := map[string][]string{}
for c, first := range m.First {
members[first] = append(members[first], c)
}
var out []Cohort
for i := len(m.Months) - 1; i >= 0 && len(out) < n; i-- {
mo := m.Months[i]
cs := members[mo.Month]
if len(cs) == 0 {
continue
}
co := Cohort{Month: mo.Month, Customers: len(cs)}
for _, c := range cs {
co.Start += mo.ByCustomer[c]
}
for k := 0; k <= span; k++ {
if i+k >= len(m.Months) || co.Start == 0 {
co.Retained = append(co.Retained, -1)
continue
}
kept := 0.0
for _, c := range cs {
kept += m.Months[i+k].ByCustomer[c]
}
co.Retained = append(co.Retained, 100*kept/co.Start)
}
out = append(out, co)
}
return out
}
// suggest finds a month, after the first, where at least 20 customers and
// most of the MRR appear as new at once.
func suggest(months []Month) *Suggestion {
for i := 1; i < len(months); i++ {
mo := months[i]
if mo.NewCount >= 20 && mo.New >= 0.5*mo.MRR {
return &Suggestion{Month: mo.Month, Customers: mo.NewCount, MRR: mo.New}
}
}
return nil
}
// Customer is a Stripe customer's name and email.
type Customer struct {
ID, Name, Email string
}
// CustomerNames reads the names and emails of the customers stored.
func CustomerNames(d *db.DB) (map[string]Customer, error) {
rows, err := d.Query(`SELECT id, data FROM stripe_objects WHERE kind = ?`, KindCustomer)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]Customer{}
for rows.Next() {
var id, raw string
if err := rows.Scan(&id, &raw); err != nil {
return nil, err
}
var c struct {
Name string `json:"name"`
Email string `json:"email"`
}
_ = json.Unmarshal([]byte(raw), &c)
out[id] = Customer{ID: id, Name: c.Name, Email: c.Email}
}
return out, rows.Err()
}
// Change is one customer's move in a month.
type Change struct {
Customer Customer
Kind string
Before, After float64
}
// Changes are a month's moves, biggest first.
func (m *Model) Changes(month string, names map[string]Customer) []Change {
i := -1
for j := range m.Months {
if m.Months[j].Month == month {
i = j
}
}
if i < 0 {
return nil
}
var prev map[string]float64
if i > 0 {
prev = m.Months[i-1].ByCustomer
}
mo := m.Months[i]
var out []Change
for c, k := range mo.Moves {
cu := names[c]
if cu.ID == "" {
cu.ID = c
}
out = append(out, Change{Customer: cu, Kind: k, Before: prev[c], After: mo.ByCustomer[c]})
}
slices.SortFunc(out, func(a, b Change) int {
da, db := a.After-a.Before, b.After-b.Before
if da < 0 {
da = -da
}
if db < 0 {
db = -db
}
switch {
case da > db:
return -1
case da < db:
return 1
}
return 0
})
return out
}
// noise is the change in a customer's MRR too small to be a real move: a
// dollar, or 1%. Spreading prorations over exact part-months leaves cents
// of difference that aren't an upgrade or a downgrade.
func noise(mrr float64) float64 { return max(100, mrr/100) }
+152
View File
@@ -0,0 +1,152 @@
package metrics
import (
"fmt"
"math"
"testing"
"time"
"supermarket/internal/db"
)
func day(s string) int64 {
t, _ := time.Parse("2006-01-02", s)
return t.Unix()
}
type ln struct {
cust, from, to, interval string
amount int64
proration bool
status string
}
var lineN int
func addLines(t *testing.T, d *db.DB, ls ...ln) {
t.Helper()
for _, l := range ls {
lineN++
status := l.status
if status == "" {
status = "paid"
}
if _, err := d.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, customer, status, currency, amount, period_start, period_end,
interval, interval_count, proration, recurring) VALUES (?, ?, ?, ?, 'usd', ?, ?, ?, ?, 1, ?, 1)`,
fmt.Sprintf("in_%d", lineN), fmt.Sprintf("il_%d", lineN), l.cust, status, l.amount, day(l.from), day(l.to), l.interval, l.proration); err != nil {
t.Fatal(err)
}
}
d.Exec(`INSERT OR IGNORE INTO stripe_objects (kind, id, currency, data) VALUES ('invoice', 'in_x', 'usd', '{}')`)
}
// monthly bills a customer $amount a month on the 10th, from one month to
// another (exclusive).
func monthly(cust string, amount int64, from, to string) []ln {
var out []ln
start, _ := time.Parse("2006-01-02", from+"-10")
end, _ := time.Parse("2006-01-02", to+"-10")
for s := start; s.Before(end); s = s.AddDate(0, 1, 0) {
out = append(out, ln{cust: cust, from: s.Format("2006-01-02"), to: s.AddDate(0, 1, 0).Format("2006-01-02"), interval: "month", amount: amount})
}
return out
}
func near(a, b float64) bool { return math.Abs(a-b) < 1 }
func TestBuild(t *testing.T) {
d := openDB(t)
addLines(t, d, monthly("cus_a", 5000, "2026-01", "2026-07")...) // $50 Jan–Jun
addLines(t, d, monthly("cus_b", 2000, "2026-02", "2026-04")...) // $20 Feb–Mar, then gone
addLines(t, d, monthly("cus_b", 2000, "2026-05", "2026-07")...) // back in May
// cus_c pays $1,200 a year from March: $100 a month.
addLines(t, d, ln{cust: "cus_c", from: "2026-03-15", to: "2027-03-15", interval: "year", amount: 120000})
// cus_a upgrades on 25 April: credit for unused $50 time, charge for $80
// time, to 10 May; then $80 a month.
addLines(t, d,
ln{cust: "cus_a", from: "2026-04-25", to: "2026-05-10", amount: -2500, proration: true},
ln{cust: "cus_a", from: "2026-04-25", to: "2026-05-10", amount: 4000, proration: true})
d.Exec(`UPDATE stripe_invoice_lines SET amount = 8000 WHERE customer = 'cus_a' AND period_start >= ?`, day("2026-05-10"))
// A trial, a void invoice and an uncollectible one count for nothing.
addLines(t, d, ln{cust: "cus_t", from: "2026-03-01", to: "2026-04-01", interval: "month", amount: 0},
ln{cust: "cus_v", from: "2026-03-01", to: "2026-04-01", interval: "month", amount: 9900, status: "void"},
ln{cust: "cus_u", from: "2026-03-01", to: "2026-04-01", interval: "month", amount: 9900, status: "uncollectible"})
m, err := Build(d, time.Date(2026, 6, 20, 12, 0, 0, 0, time.UTC))
if err != nil {
t.Fatal(err)
}
if m.Currency != "usd" || len(m.Months) != 6 || m.Months[0].Month != "2026-01" || !m.Last().Partial {
t.Fatalf("months: %d %+v", len(m.Months), m.Months[0])
}
want := map[string]struct {
mrr float64
cust int
}{
"2026-01": {5000, 1}, "2026-02": {7000, 2}, "2026-03": {17000, 3},
// April: cus_a's proration covers 25 April–10 May: +$15 over half a
// month, about $30 a month on top of $50.
"2026-04": {15000 + 3044, 2}, "2026-05": {20000, 3}, "2026-06": {20000, 3},
}
for _, mo := range m.Months {
w := want[mo.Month]
if !near(mo.MRR, w.mrr) || mo.Customers != w.cust {
t.Errorf("%s: MRR %.0f with %d, want %.0f with %d", mo.Month, mo.MRR, mo.Customers, w.mrr, w.cust)
}
}
apr, may := m.Find("2026-04"), m.Find("2026-05")
if !near(apr.Churn, 2000) || apr.ChurnCount != 1 || apr.Moves["cus_b"] != MoveChurn || apr.Moves["cus_a"] != MoveExpansion {
t.Errorf("april: %+v", apr.Moves)
}
if !near(may.Reactivation, 2000) || may.Moves["cus_b"] != MoveReactivation || may.Moves["cus_a"] != "" { // the upgrade counted in April
t.Errorf("may: %+v %v", may.Moves, may.Reactivation)
}
if mar := m.Find("2026-03"); !near(mar.New, 10000) || mar.NewCount != 1 {
t.Errorf("march new: %+v", mar)
}
// April's NRR: March's customers (a, b, c: $170) pay $180.44 in April.
if !near(apr.NRR*170, 18044) {
t.Errorf("april NRR: %v", apr.NRR)
}
if apr.NRR12 != -1 {
t.Error("NRR over 12 months without a year of data")
}
if n := apr.NetNew(); !near(n, apr.MRR-m.Find("2026-03").MRR) {
t.Errorf("net new %v doesn't add up", n)
}
cos := m.Cohorts(12, 3)
if len(cos) != 3 || cos[0].Month != "2026-03" || cos[2].Month != "2026-01" || cos[2].Retained[0] != 100 || !near(cos[2].Retained[3], 100*(5000+3044)/5000) {
t.Errorf("cohorts: %+v", cos)
}
ch := m.Changes("2026-04", map[string]Customer{"cus_b": {ID: "cus_b", Name: "Bea"}})
if len(ch) != 2 || ch[0].Customer.Name != "" || ch[1].Customer.Name != "Bea" || ch[1].Kind != MoveChurn {
t.Errorf("changes: %+v", ch)
}
}
func TestStartMonthAndSuggestion(t *testing.T) {
d := openDB(t)
addLines(t, d, monthly("cus_old", 1000, "2024-01", "2024-03")...)
for i := 0; i < 25; i++ {
addLines(t, d, monthly(fmt.Sprintf("cus_%d", i), 4000, "2025-01", "2025-04")...)
}
now := time.Date(2025, 3, 20, 0, 0, 0, 0, time.UTC)
m, _ := Build(d, now)
if m.Suggest == nil || m.Suggest.Month != "2025-01" || m.Suggest.Customers != 25 {
t.Fatalf("suggestion: %+v", m.Suggest)
}
if err := SetStartMonth(d, "2025-01"); err != nil {
t.Fatal(err)
}
if err := SetStartMonth(d, "January"); err == nil {
t.Error("a bad month was saved")
}
m, _ = Build(d, now)
jan := m.Months[0]
if jan.Month != "2025-01" || jan.New != 0 || jan.Customers != 25 || m.Suggest != nil {
t.Errorf("counted from January: %+v", jan)
}
if cos := m.Cohorts(5, 2); len(cos) != 1 || cos[0].Customers != 25 {
t.Errorf("the starting base's cohort: %+v", cos)
}
}
+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}}