diff --git a/internal/metrics/export.go b/internal/metrics/export.go index fc9c3f8..ac04b71 100644 --- a/internal/metrics/export.go +++ b/internal/metrics/export.go @@ -158,7 +158,7 @@ func Export(w io.Writer, d *db.DB, name string, now time.Time) error { } write([]string{"customer_id", "name", "email", "mrr_now", "first_paid", "crm_account_id", "crm_account", "matched_by"}) for _, m := range ms { - if err := write([]string{m.Customer.ID, m.Customer.Name, m.Customer.Email, dollars(m.MRR), model.First[m.Customer.ID], + if err := write([]string{m.Customer.ID, m.Customer.Name, m.Customer.Email, dollars(m.MRR), firstPaid(model, m.Customer.ID), m.Account.ID, m.Account.Name, m.How}); err != nil { return err } @@ -247,3 +247,12 @@ func joinLines(lines []string) string { } return out } + +// firstPaid is the month a customer first paid: their cohort's, or, for one +// who was already a customer, the month first seen paying. +func firstPaid(m *Model, customer string) string { + if f := m.First[customer]; f != "" { + return f + } + return m.Existing[customer] +} diff --git a/internal/metrics/mrr.go b/internal/metrics/mrr.go index 41068a3..3e1ac30 100644 --- a/internal/metrics/mrr.go +++ b/internal/metrics/mrr.go @@ -18,6 +18,7 @@ type line struct { intervalCount int proration bool product string + invoice string } const avgMonthSeconds = 365.25 / 12 * 24 * 3600 @@ -49,7 +50,7 @@ func (l line) monthly() float64 { // 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 + 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 { @@ -59,7 +60,7 @@ func loadLines(d *db.DB, currency string) ([]line, error) { 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 { + 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) @@ -83,8 +84,47 @@ const ( 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 { @@ -123,7 +163,8 @@ func (m Month) NetNew() float64 { type Model struct { Currency string Months []Month // oldest first, from Start - First map[string]string // customer → the month they first paid (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 } @@ -177,7 +218,7 @@ func mrrAt(lines []line, t int64) map[string]float64 { // (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)} + m := &Model{Currency: cur, First: map[string]string{}, Existing: map[string]string{}, Start: StartMonth(d)} if cur == "" { return m, nil } @@ -188,6 +229,10 @@ func Build(d *db.DB, now time.Time) (*Model, error) { 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) @@ -217,6 +262,11 @@ func Build(d *db.DB, now time.Time) (*Model, error) { 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++ diff --git a/internal/metrics/mrr_test.go b/internal/metrics/mrr_test.go index 09b50f2..2a093e8 100644 --- a/internal/metrics/mrr_test.go +++ b/internal/metrics/mrr_test.go @@ -152,3 +152,45 @@ func TestStartMonthAndSuggestion(t *testing.T) { t.Errorf("the starting base's cohort: %+v", cos) } } + +// A customer whose first invoice Stripe shows is a renewal was a customer +// already: their first payment counts as reactivation, not new, and puts +// them in no cohort. One whose first invoice is a signup is new. +func TestRenewalFirstIsExisting(t *testing.T) { + d := openDB(t) + addLines(t, d, monthly("cus_a", 5000, "2026-01", "2026-07")...) + for _, c := range []struct{ cust, invoice, reason string }{ + {"cus_old", "in_old", "subscription_cycle"}, + {"cus_new", "in_new", "subscription_create"}, + } { + 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 (?, ?, ?, 'paid', 'usd', 120000, ?, ?, 'year', 1, 0, 1)`, + c.invoice, "il_"+c.cust, c.cust, day("2026-03-02"), day("2027-03-02")); err != nil { + t.Fatal(err) + } + if _, err := d.Exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, data) VALUES ('invoice', ?, ?, 'paid', 'usd', ?)`, + c.invoice, c.cust, `{"billing_reason":"`+c.reason+`"}`); err != nil { + t.Fatal(err) + } + } + m, err := Build(d, time.Date(2026, 6, 20, 12, 0, 0, 0, time.UTC)) + if err != nil { + t.Fatal(err) + } + mar := m.Find("2026-03") + if mar.NewCount != 1 || !near(mar.New, 10000) || !near(mar.Reactivation, 10000) || + mar.Moves["cus_old"] != MoveExisting || mar.Moves["cus_new"] != MoveNew { + t.Errorf("march: new %d %.0f, reactivation %.0f, moves %v", mar.NewCount, mar.New, mar.Reactivation, mar.Moves) + } + if !near(mar.NetNew(), mar.MRR-m.Find("2026-02").MRR) { + t.Errorf("movements don't add up: %.0f vs %.0f", mar.NetNew(), mar.MRR-m.Find("2026-02").MRR) + } + if _, ok := m.First["cus_old"]; ok || m.Existing["cus_old"] != "2026-03" || m.First["cus_new"] != "2026-03" { + t.Errorf("first %v, existing %v", m.First, m.Existing) + } + for _, co := range m.Cohorts(12, 3) { + if co.Month == "2026-03" && co.Customers != 1 { + t.Errorf("March cohort has %d customers, want only cus_new", co.Customers) + } + } +} diff --git a/internal/web/templates/metrics.html b/internal/web/templates/metrics.html index 9ead580..25f4ca1 100644 --- a/internal/web/templates/metrics.html +++ b/internal/web/templates/metrics.html @@ -40,7 +40,7 @@ {{range .}}{{.Month}}: {{usd .MRR}}{{if .Label}}{{.Month}}{{end}}{{end}} {{end}} -

From the invoice lines of paid invoices (an unpaid one counts once it's paid), 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}}

+

From the invoice lines of paid invoices (an unpaid one counts once it's paid), 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. A customer whose first invoice in Stripe is a renewal was a customer already: that first payment counts as reactivation, not new, and puts them in no cohort.{{with $d.Model.Start}}{{if ne . "all"}} Counted from {{.}}.{{end}}{{end}}

Month by month