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 INTO stripe_objects (kind, id, currency, data) VALUES ('invoice', 'in_x', 'usd', '{}') ON CONFLICT DO NOTHING`) } // 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, an unpaid (open) invoice, a void one 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_o", from: "2026-03-01", to: "2026-04-01", interval: "month", amount: 9900, status: "open"}, 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) } } // 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) } } }