When the earliest recurring invoice Stripe has for a customer is a renewal (billing_reason subscription_cycle), they were a customer already, their first year free or billed elsewhere. That first payment now counts as reactivation (movement "existing"), not new: it stays out of New, the cohorts and CAC, and the month's movements still add up. The customers export gives the month first seen paying as first_paid. A $0 trial signup before the first payment still makes a customer new. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
500 lines
13 KiB
Go
500 lines
13 KiB
Go
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
|
|
invoice 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 paid invoices (not open, void or
|
|
// 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, invoice
|
|
FROM stripe_invoice_lines WHERE recurring = 1 AND status = 'paid' AND currency = ? AND customer != ''
|
|
AND period_end > period_start ORDER BY invoice, id`, currency) // a fixed order: float sums come out the same everywhere
|
|
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, &l.invoice); 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"
|
|
// MoveExisting is a customer whose first payment Stripe shows is a
|
|
// renewal: they were a customer already (their first year free, or
|
|
// billed elsewhere). Counted as reactivation, not as new.
|
|
MoveExisting = "existing"
|
|
)
|
|
|
|
// renewalFirst are the customers whose earliest recurring line is on a
|
|
// renewal invoice (billing_reason subscription_cycle).
|
|
func renewalFirst(d *db.DB, lines []line) (map[string]bool, error) {
|
|
earliest := map[string]line{}
|
|
for _, l := range lines {
|
|
if e, ok := earliest[l.customer]; !ok || l.start < e.start {
|
|
earliest[l.customer] = l
|
|
}
|
|
}
|
|
rows, err := d.Query(`SELECT id, coalesce(json_extract(data, '$.billing_reason'), '') FROM stripe_objects WHERE kind = 'invoice' AND status = 'paid'`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
reason := map[string]string{}
|
|
for rows.Next() {
|
|
var id, r string
|
|
if err := rows.Scan(&id, &r); err != nil {
|
|
rows.Close()
|
|
return nil, err
|
|
}
|
|
reason[id] = r
|
|
}
|
|
rows.Close()
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
out := map[string]bool{}
|
|
for c, l := range earliest {
|
|
if reason[l.invoice] == "subscription_cycle" {
|
|
out[c] = true
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// 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): their cohort
|
|
Existing map[string]string // customer → the month first seen paying, for those already customers then (a renewal): no cohort
|
|
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{}, Existing: 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
|
|
}
|
|
renewal, err := renewalFirst(d, lines)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
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] && renewal[c]:
|
|
// Already a customer before Stripe shows them paying.
|
|
mo.Reactivation += v
|
|
mo.Moves[c] = MoveExisting
|
|
m.Existing[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) }
|