Phase 4 part 6: the dashboard, CSV exports and an open metrics page
The MRR page adds churn, CLV, CAC and CLV:CAC. Eight tables download as CSV (MRR, NRR and revenue cohorts, CAC by month and channel, spend, products, customers). Metrics → Publish builds an open metrics page from chosen totals only (never a customer) and opens a pull request that adds or updates it on the site, checked with a Hugo build. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,249 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// Exports are the tables that can be downloaded as CSV, by name.
|
||||
var Exports = []struct{ Name, Title string }{
|
||||
{"mrr", "MRR month by month"},
|
||||
{"nrr-cohorts", "NRR by cohort"},
|
||||
{"cohort-revenue", "Revenue by cohort"},
|
||||
{"cac", "CAC by month"},
|
||||
{"cac-channels", "CAC by channel (12 months)"},
|
||||
{"spend", "Spend log"},
|
||||
{"products", "Products and margins"},
|
||||
{"customers", "Customers: MRR and CRM match"},
|
||||
}
|
||||
|
||||
func dollars(cents float64) string { return strconv.FormatFloat(cents/100, 'f', 2, 64) }
|
||||
|
||||
func pct(f float64) string {
|
||||
if f < 0 {
|
||||
return ""
|
||||
}
|
||||
return strconv.FormatFloat(f, 'f', 1, 64)
|
||||
}
|
||||
|
||||
// Export writes one table as CSV, amounts in dollars.
|
||||
func Export(w io.Writer, d *db.DB, name string, now time.Time) error {
|
||||
model, err := Build(d, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cw := csv.NewWriter(w)
|
||||
defer cw.Flush()
|
||||
write := func(rows ...[]string) error {
|
||||
for _, r := range rows {
|
||||
if err := cw.Write(r); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
switch name {
|
||||
case "mrr":
|
||||
write([]string{"month", "partial", "mrr", "customers", "arpa", "new", "new_customers", "expansion", "contraction", "churn",
|
||||
"churned_customers", "reactivation", "net_new", "nrr_pct", "nrr_12m_pct"})
|
||||
for _, m := range model.Months {
|
||||
if err := write([]string{m.Month, strconv.FormatBool(m.Partial), dollars(m.MRR), strconv.Itoa(m.Customers), dollars(m.ARPA()),
|
||||
dollars(m.New), strconv.Itoa(m.NewCount), dollars(m.Expansion), dollars(m.Contraction), dollars(m.Churn),
|
||||
strconv.Itoa(m.ChurnCount), dollars(m.Reactivation), dollars(m.NetNew()), pct(m.NRR), pct(m.NRR12)}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "nrr-cohorts":
|
||||
head := []string{"first_paid", "customers", "starting_mrr"}
|
||||
for k := 0; k <= 24; k++ {
|
||||
head = append(head, fmt.Sprintf("month_%d_pct", k))
|
||||
}
|
||||
write(head)
|
||||
for _, c := range model.Cohorts(1000, 24) {
|
||||
row := []string{c.Month, strconv.Itoa(c.Customers), dollars(c.Start)}
|
||||
for _, r := range c.Retained {
|
||||
row = append(row, pct(r))
|
||||
}
|
||||
if err := write(row); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "cohort-revenue":
|
||||
cs, err := RevenueByCohort(d, model, 1000, 24, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
head := []string{"first_paid", "customers"}
|
||||
for k := 0; k <= 24; k++ {
|
||||
head = append(head, fmt.Sprintf("month_%d_revenue_per_customer", k))
|
||||
}
|
||||
write(head)
|
||||
for _, c := range cs {
|
||||
row := []string{c.Month, strconv.Itoa(c.Customers)}
|
||||
for _, v := range c.PerCustomer {
|
||||
if v.Known {
|
||||
row = append(row, dollars(v.V))
|
||||
} else {
|
||||
row = append(row, "")
|
||||
}
|
||||
}
|
||||
if err := write(row); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "cac", "cac-channels":
|
||||
names, err := CustomerNames(d)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c, err := BuildCAC(d, model, names)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
amount := func(f float64) string {
|
||||
if f < 0 {
|
||||
return ""
|
||||
}
|
||||
return dollars(f)
|
||||
}
|
||||
if name == "cac" {
|
||||
write([]string{"month", "spend", "new_customers", "cac", "cac_3_months"})
|
||||
months := slices.Clone(c.Months)
|
||||
slices.Reverse(months)
|
||||
for _, m := range months {
|
||||
if err := write([]string{m.Month, dollars(float64(m.Spend)), strconv.Itoa(m.New), amount(m.CAC), amount(m.Trailing3)}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
write([]string{"channel", "spend", "new_customers", "cac"})
|
||||
for _, ch := range c.Channels {
|
||||
if err := write([]string{ChannelName(ch.Channel), dollars(float64(ch.Spend)), strconv.Itoa(ch.New), amount(ch.CAC)}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "spend":
|
||||
log, err := SpendLog(d, 100000)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
write([]string{"month", "channel", "amount", "note", "source"})
|
||||
for _, s := range log {
|
||||
if err := write([]string{s.Month, s.Channel, dollars(float64(s.AmountCents)), s.Note, s.Source}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "products":
|
||||
ps, err := Products(d, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
write([]string{"product_id", "name", "billed_12_months", "invoices", "margin_pct", "own_margin"})
|
||||
for _, p := range ps {
|
||||
if err := write([]string{p.ID, p.Name, dollars(float64(p.Revenue)), strconv.Itoa(p.Invoices), pct(p.Margin), strconv.FormatBool(p.Own)}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "customers":
|
||||
ms, err := Matches(d, model)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
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],
|
||||
m.Account.ID, m.Account.Name, m.How}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("no table %q", name)
|
||||
}
|
||||
return cw.Error()
|
||||
}
|
||||
|
||||
// PublicParts are what an open metrics page can show; nothing about any
|
||||
// one customer is ever published.
|
||||
var PublicParts = []struct{ ID, Label string }{
|
||||
{"mrr", "MRR and ARR"},
|
||||
{"customers", "Paying customers and the average per customer"},
|
||||
{"growth", "Growth over 12 months"},
|
||||
{"nrr", "Net revenue retention (12 months)"},
|
||||
{"churn", "Monthly customer churn"},
|
||||
{"table", "A month-by-month table (MRR, customers, net change), last 12 months"},
|
||||
}
|
||||
|
||||
// PublicPage is the Markdown body of an open metrics page: totals only.
|
||||
func PublicPage(m *Model, clv *CLV, parts map[string]bool, now time.Time) string {
|
||||
months := m.Months
|
||||
if len(months) > 0 && months[len(months)-1].Partial {
|
||||
months = months[:len(months)-1]
|
||||
}
|
||||
if len(months) == 0 {
|
||||
return ""
|
||||
}
|
||||
last := months[len(months)-1]
|
||||
money := func(cents float64) string {
|
||||
s := strconv.FormatFloat(cents/100, 'f', 0, 64)
|
||||
for i := len(s) - 3; i > 0; i -= 3 {
|
||||
s = s[:i] + "," + s[i:]
|
||||
}
|
||||
return "$" + s
|
||||
}
|
||||
var b []string
|
||||
b = append(b, fmt.Sprintf("Our numbers at the end of %s, straight from our billing.", monthName(last.Month)), "")
|
||||
if parts["mrr"] {
|
||||
b = append(b, fmt.Sprintf("- **Monthly recurring revenue:** %s (%s a year)", money(last.MRR), money(12*last.MRR)))
|
||||
}
|
||||
if parts["customers"] {
|
||||
b = append(b, fmt.Sprintf("- **Paying customers:** %d, at %s a month on average", last.Customers, money(last.ARPA())))
|
||||
}
|
||||
if parts["growth"] && len(months) > 12 {
|
||||
if base := months[len(months)-13].MRR; base > 0 {
|
||||
b = append(b, fmt.Sprintf("- **Growth over 12 months:** %+.0f%%", 100*(last.MRR-base)/base))
|
||||
}
|
||||
}
|
||||
if parts["nrr"] && last.NRR12 >= 0 {
|
||||
b = append(b, fmt.Sprintf("- **Net revenue retention, 12 months:** %.0f%% (what customers of a year ago pay now)", last.NRR12))
|
||||
}
|
||||
if parts["churn"] && clv != nil && clv.ChurnMonths > 0 {
|
||||
b = append(b, fmt.Sprintf("- **Monthly customer churn:** %.1f%%, averaged over %d months", clv.Churn, clv.ChurnMonths))
|
||||
}
|
||||
if parts["table"] {
|
||||
b = append(b, "", "| Month | MRR | Customers | Net change |", "|---|---:|---:|---:|")
|
||||
from := max(0, len(months)-12)
|
||||
for i := len(months) - 1; i >= from; i-- {
|
||||
mo := months[i]
|
||||
sign := ""
|
||||
if mo.NetNew() > 0 {
|
||||
sign = "+"
|
||||
}
|
||||
b = append(b, fmt.Sprintf("| %s | %s | %d | %s%s |", monthName(mo.Month), money(mo.MRR), mo.Customers, sign, money(mo.NetNew())))
|
||||
}
|
||||
}
|
||||
b = append(b, "", fmt.Sprintf("*Updated %s. MRR counts recurring billing after discounts; trials, one-off charges and unpaid invoices don't count.*", now.Format("2 January 2006")))
|
||||
return joinLines(b)
|
||||
}
|
||||
|
||||
func monthName(ym string) string {
|
||||
t, err := time.Parse("2006-01", ym)
|
||||
if err != nil {
|
||||
return ym
|
||||
}
|
||||
return t.Format("January 2006")
|
||||
}
|
||||
|
||||
func joinLines(lines []string) string {
|
||||
out := ""
|
||||
for _, l := range lines {
|
||||
out += l + "\n"
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestExportsAndPublicPage(t *testing.T) {
|
||||
d := openDB(t)
|
||||
now := time.Date(2027, 2, 15, 0, 0, 0, 0, time.UTC)
|
||||
addLines(t, d, monthly("cus_a", 10000, "2026-01", "2027-03")...)
|
||||
addLines(t, d, monthly("cus_b", 5000, "2026-06", "2027-03")...)
|
||||
d.Exec(`INSERT INTO stripe_objects (kind, id, customer, data) VALUES ('customer', 'cus_a', 'cus_a', '{"name":"Secret Co","email":"ceo@secret.example"}')`)
|
||||
d.Exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, data) VALUES ('invoice', 'pa', 'cus_a', 'paid', 'usd', '{"amount_paid":10000}')`)
|
||||
AddSpend(d, Spend{Month: "2026-06", Channel: "linkedin", AmountCents: 50000}, now)
|
||||
for _, e := range Exports {
|
||||
var buf bytes.Buffer
|
||||
if err := Export(&buf, d, e.Name, now); err != nil {
|
||||
t.Errorf("%s: %v", e.Name, err)
|
||||
continue
|
||||
}
|
||||
rows, err := csv.NewReader(&buf).ReadAll()
|
||||
if err != nil || len(rows) < 2 {
|
||||
t.Errorf("%s: %d rows %v", e.Name, len(rows), err)
|
||||
}
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
Export(&buf, d, "mrr", now)
|
||||
if !strings.Contains(buf.String(), "2026-06,false,150.00,2,75.00,50.00,1,") {
|
||||
t.Errorf("mrr csv:\n%s", buf.String())
|
||||
}
|
||||
buf.Reset()
|
||||
Export(&buf, d, "customers", now)
|
||||
if !strings.Contains(buf.String(), "cus_a,Secret Co,ceo@secret.example,100.00,2026-01") {
|
||||
t.Errorf("customers csv:\n%s", buf.String())
|
||||
}
|
||||
if err := Export(&buf, d, "nope", now); err == nil {
|
||||
t.Error("an unknown table exported")
|
||||
}
|
||||
|
||||
m, _ := Build(d, now)
|
||||
clv, _ := BuildCLV(d, m, now)
|
||||
page := PublicPage(m, clv, map[string]bool{"mrr": true, "customers": true, "growth": true, "nrr": true, "churn": true, "table": true}, now)
|
||||
for _, want := range []string{"end of January 2027", "**Monthly recurring revenue:** $150 ($1,800 a year)", "**Paying customers:** 2",
|
||||
"**Growth over 12 months:** +50%", "| January 2027 | $150 | 2 |", "| June 2026 | $150 | 2 | +$50 |"} {
|
||||
if !strings.Contains(page, want) {
|
||||
t.Errorf("page lacks %q:\n%s", want, page)
|
||||
}
|
||||
}
|
||||
for _, never := range []string{"Secret", "secret.example", "cus_"} {
|
||||
if strings.Contains(page, never) {
|
||||
t.Errorf("the public page names a customer: %q", never)
|
||||
}
|
||||
}
|
||||
if p := PublicPage(m, clv, map[string]bool{"mrr": true}, now); strings.Contains(p, "|") || strings.Contains(p, "customers") {
|
||||
t.Errorf("unchosen parts shown:\n%s", p)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user