Metrics: a customer whose first invoice is a renewal is an existing one

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>
This commit is contained in:
2026-11-30 12:56:34 -07:00
co-authored by Claude Opus 5.5
parent fab349d166
commit 06b17b9eab
4 changed files with 107 additions and 6 deletions
+10 -1
View File
@@ -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"}) write([]string{"customer_id", "name", "email", "mrr_now", "first_paid", "crm_account_id", "crm_account", "matched_by"})
for _, m := range ms { 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 { m.Account.ID, m.Account.Name, m.How}); err != nil {
return err return err
} }
@@ -247,3 +247,12 @@ func joinLines(lines []string) string {
} }
return out 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]
}
+54 -4
View File
@@ -18,6 +18,7 @@ type line struct {
intervalCount int intervalCount int
proration bool proration bool
product string product string
invoice string
} }
const avgMonthSeconds = 365.25 / 12 * 24 * 3600 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 // loadLines reads the recurring lines of paid invoices (not open, void or
// uncollectible) in the main currency. // uncollectible) in the main currency.
func loadLines(d *db.DB, currency string) ([]line, error) { 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 != '' 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 AND period_end > period_start ORDER BY invoice, id`, currency) // a fixed order: float sums come out the same everywhere
if err != nil { if err != nil {
@@ -59,7 +60,7 @@ func loadLines(d *db.DB, currency string) ([]line, error) {
var out []line var out []line
for rows.Next() { for rows.Next() {
var l line 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 return nil, err
} }
out = append(out, l) out = append(out, l)
@@ -83,8 +84,47 @@ const (
MoveContraction = "contraction" MoveContraction = "contraction"
MoveChurn = "churn" MoveChurn = "churn"
MoveReactivation = "reactivation" 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 // Month is one month's MRR and how it moved since the month before. Amounts
// are in cents. // are in cents.
type Month struct { type Month struct {
@@ -123,7 +163,8 @@ func (m Month) NetNew() float64 {
type Model struct { type Model struct {
Currency string Currency string
Months []Month // oldest first, from Start 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) Start string // the first month counted ("" for all)
Suggest *Suggestion // a start month worth considering, when none is set 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). // (the current month measured now, the others at their last second).
func Build(d *db.DB, now time.Time) (*Model, error) { func Build(d *db.DB, now time.Time) (*Model, error) {
cur := MainCurrency(d) 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 == "" { if cur == "" {
return m, nil return m, nil
} }
@@ -188,6 +229,10 @@ func Build(d *db.DB, now time.Time) (*Model, error) {
if len(lines) == 0 { if len(lines) == 0 {
return m, nil return m, nil
} }
renewal, err := renewalFirst(d, lines)
if err != nil {
return nil, err
}
first := lines[0].start first := lines[0].start
for _, l := range lines { for _, l := range lines {
first = min(first, l.start) 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 != "": case mo.Month == startMonth && m.Start != "":
// Already paying when the count starts: the base, not new. // Already paying when the count starts: the base, not new.
m.First[c] = mo.Month 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]: case p == 0 && !ever[c]:
mo.New += v mo.New += v
mo.NewCount++ mo.NewCount++
+42
View File
@@ -152,3 +152,45 @@ func TestStartMonthAndSuggestion(t *testing.T) {
t.Errorf("the starting base's cohort: %+v", cos) 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)
}
}
}
+1 -1
View File
@@ -40,7 +40,7 @@
{{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}} {{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> </svg>
{{end}} {{end}}
<p class="small muted">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}}</p> <p class="small muted">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}}</p>
</section> </section>
<h2>Month by month</h2> <h2>Month by month</h2>