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:
2026-11-22 13:28:50 -07:00
co-authored by Claude Opus 5.5
parent 23f765159f
commit 152c14b580
18 changed files with 637 additions and 5 deletions
+33
View File
@@ -160,3 +160,36 @@ func TestSpendPage(t *testing.T) {
t.Error("the entry wasn't deleted")
}
}
func TestExportAndPublishPages(t *testing.T) {
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: "https://us.example"}}})
s.DB.Exec(`INSERT INTO stripe_objects (kind, id, currency, data) VALUES ('invoice', 'in_0', 'usd', '{}')`)
start := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -2, 0)
for i := 0; i < 3; i++ {
ps := start.AddDate(0, i, 0)
s.DB.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, customer, status, currency, amount, period_start, period_end, interval, interval_count, recurring)
VALUES (?, ?, 'cus_a', 'paid', 'usd', 9900, ?, ?, 'month', 1, 1)`, fmt.Sprint("in_", i), fmt.Sprint("il_", i), ps.Unix(), ps.AddDate(0, 1, 0).Unix())
}
rec := do(h, http.MethodGet, "/metrics/export/mrr.csv", nil, nil)
if rec.Header().Get("Content-Type") != "text/csv; charset=utf-8" || !strings.Contains(rec.Header().Get("Content-Disposition"), "supermarket-mrr-") ||
!strings.HasPrefix(rec.Body.String(), "month,partial,mrr") {
t.Errorf("export: %v %s", rec.Header(), rec.Body)
}
if rec := do(h, http.MethodGet, "/metrics/export/secrets.csv", nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("unknown export: %d", rec.Code)
}
if body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String(); !strings.Contains(body, "/metrics/export/mrr.csv") {
t.Error("no download link on Metrics")
}
postForm(h, "/metrics/publish", url.Values{"site": {"0"}, "path": {"/numbers/"}, "title": {"Our numbers"}, "part": {"mrr", "table"}, "do": {"save"}})
body := do(h, http.MethodGet, "/metrics/publish", nil, nil).Body.String()
for _, want := range []string{`value="/numbers/"`, "Monthly recurring revenue:** $99", "| Month | MRR |"} {
if !strings.Contains(body, want) {
t.Errorf("publish page lacks %q", want)
}
}
if rec := postForm(h, "/metrics/publish", url.Values{"site": {"0"}, "path": {""}, "title": {"x"}}); !strings.Contains(rec.Body.String(), "an address and a title") {
t.Error("an empty address was accepted")
}
}
+128
View File
@@ -32,6 +32,11 @@ func (s *Server) renderMetrics(w http.ResponseWriter, r *http.Request, errMsg st
s.serverError(w, err)
return
}
clv, err := metrics.BuildCLV(s.DB, model, time.Now())
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "metrics", page{Title: "Metrics", Nav: "metrics/overview", Error: errMsg, Data: map[string]any{
"Stripe": s.stripe() != nil,
"Last": metrics.LastSync(s.DB),
@@ -39,6 +44,7 @@ func (s *Server) renderMetrics(w http.ResponseWriter, r *http.Request, errMsg st
"Products": products,
"Margins": metrics.LoadMargins(s.DB),
"Model": model,
"CLV": clv,
"Now": model.Last(),
"Recent": model.Recent(13),
"Bars": bars(model, 24),
@@ -425,3 +431,125 @@ func (s *Server) metricsCLV(w http.ResponseWriter, r *http.Request) {
"Currency": model.Currency,
}})
}
// --- CSV export and the open metrics page ---
func (s *Server) metricsExport(w http.ResponseWriter, r *http.Request) {
name := strings.TrimSuffix(r.PathValue("name"), ".csv")
known := false
for _, e := range metrics.Exports {
known = known || e.Name == name
}
if !known {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
w.Header().Set("Content-Disposition", `attachment; filename="supermarket-`+name+`-`+time.Now().Format("2006-01-02")+`.csv"`)
if err := metrics.Export(w, s.DB, name, time.Now()); err != nil {
s.Log.Error("metrics: export", "table", name, "err", err)
}
}
// publishOptions are the open metrics page's settings.
type publishOptions struct {
Site int `json:"site"`
Path string `json:"path"`
Title string `json:"title"`
Parts map[string]bool `json:"parts"`
PRURL string `json:"pr_url"`
PRAt time.Time `json:"pr_at"`
}
const publishKey = "metrics:publish"
func (s *Server) publishOptions() publishOptions {
o := publishOptions{Path: "/metrics/", Title: "Open metrics", Parts: map[string]bool{"mrr": true, "customers": true, "growth": true, "nrr": true}}
_, _ = s.DB.GetJSON(publishKey, &o)
return o
}
func (s *Server) metricsPublishPage(w http.ResponseWriter, r *http.Request) {
s.renderPublish(w, r, s.publishOptions(), "")
}
func (s *Server) renderPublish(w http.ResponseWriter, r *http.Request, o publishOptions, errMsg string) {
now := time.Now()
model, err := metrics.Build(s.DB, now)
if err != nil {
s.serverError(w, err)
return
}
clv, err := metrics.BuildCLV(s.DB, model, now)
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "metrics-publish", page{Title: "Publish metrics", Nav: "metrics/publish", Error: errMsg, Data: map[string]any{
"O": o, "Parts": metrics.PublicParts, "Sites": s.seoSites(), "Gitea": s.gitea() != nil,
"Preview": metrics.PublicPage(model, clv, o.Parts, now),
}})
}
// metricsPublish saves the page's settings, and with "pr" opens the pull
// request.
func (s *Server) metricsPublish(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
o := s.publishOptions()
o.Site, _ = strconv.Atoi(r.PostFormValue("site"))
o.Path = strings.TrimSpace(r.PostFormValue("path"))
o.Title = strings.TrimSpace(r.PostFormValue("title"))
o.Parts = map[string]bool{}
for _, p := range r.PostForm["part"] {
o.Parts[p] = true
}
if o.Path == "" || o.Title == "" {
s.renderPublish(w, r, o, "Give the page an address and a title.")
return
}
if r.PostFormValue("do") == "pr" {
var site *seoSite
for _, st := range s.seoSites() {
if st.Index == o.Site {
site = &st
}
}
if site == nil {
s.renderPublish(w, r, o, "Choose a website.")
return
}
now := time.Now()
model, err := metrics.Build(s.DB, now)
if err != nil {
s.serverError(w, err)
return
}
clv, _ := metrics.BuildCLV(s.DB, model, now)
body := metrics.PublicPage(model, clv, o.Parts, now)
if body == "" {
s.renderPublish(w, r, o, "There's no complete month of billing to publish yet.")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
defer cancel()
pr, _, err := s.applier(*site).PublishPage(ctx, o.Path, o.Title, "Our revenue numbers, straight from our billing.", body,
"Proposed by Supermarket: the open metrics page, with totals only (nothing about any one customer).")
if err != nil {
s.renderPublish(w, r, o, "Couldn't open the pull request: "+err.Error())
return
}
o.PRURL, o.PRAt = pr.HTMLURL, now
}
if err := s.DB.PutJSON(publishKey, o); err != nil {
s.serverError(w, err)
return
}
msg := "saved"
if r.PostFormValue("do") == "pr" {
msg = "setup-opened"
}
redirect(w, r, "/metrics/publish", msg)
}
+3
View File
@@ -169,6 +169,9 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /metrics/customers", s.metricsCustomers)
mux.HandleFunc("GET /metrics/spend", s.metricsSpend)
mux.HandleFunc("GET /metrics/clv", s.metricsCLV)
mux.HandleFunc("GET /metrics/export/{name}", s.metricsExport)
mux.HandleFunc("GET /metrics/publish", s.metricsPublishPage)
mux.HandleFunc("POST /metrics/publish", s.metricsPublish)
mux.HandleFunc("POST /metrics/spend", s.metricsSpendAdd)
mux.HandleFunc("POST /metrics/spend/{id}/delete", s.metricsSpendDelete)
mux.HandleFunc("POST /metrics/customers/{id}", s.metricsCustomerMatch)
+1 -1
View File
@@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) {
"/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz",
"/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
"/content/scheduled", "/content/published",
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit",
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish",
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
rec := do(h, http.MethodGet, path, nil, nil)
if rec.Code != http.StatusOK {
+1
View File
@@ -56,6 +56,7 @@
<a href="/metrics/spend" {{if eq $nav "metrics/spend"}}aria-current="page"{{end}}>Spend and CAC</a>
<a href="/metrics/clv" {{if eq $nav "metrics/clv"}}aria-current="page"{{end}}>CLV and cohorts</a>
<a href="/metrics/customers" {{if eq $nav "metrics/customers"}}aria-current="page"{{end}}>Customers and the CRM</a>
<a href="/metrics/publish" {{if eq $nav "metrics/publish"}}aria-current="page"{{end}}>Publish</a>
</div>
{{end}}
{{if eq .ID "prospects"}}
+1
View File
@@ -33,5 +33,6 @@
{{if $d.Profit}}{{range .Margin}}<td class="num">{{if .Known}}{{usd .V}}{{end}}</td>{{end}}{{else}}{{range .PerCustomer}}<td class="num">{{if .Known}}{{usd .V}}{{end}}</td>{{end}}{{end}}
</tr>{{end}}</tbody>
</table></div>
<p class="small"><a href="/metrics/export/cohort-revenue.csv">Download as CSV</a> (every cohort, 24 months)</p>
{{end}}
{{end}}{{end}}
@@ -19,6 +19,7 @@
</div>
</section>
<p class="small"><a href="/metrics/export/customers.csv">Download every customer as CSV</a></p>
<nav class="tabs">
<a href="/metrics/customers" {{if eq .Show ""}}aria-current="page"{{end}}>To fix</a>
<a href="/metrics/customers?show=paying" {{if eq .Show "paying"}}aria-current="page"{{end}}>Paying now</a>
@@ -0,0 +1,23 @@
{{define "content"}}{{with .Data}}{{$o := .O}}
<div class="heading"><h1>Publish your metrics</h1></div>
<p class="lede">An "open metrics" page on your website: your revenue numbers, straight from billing, for customers and investors who like seeing a company's real numbers. Only totals are published, never anything about any one customer. It goes to the site as a pull request, like the SEO changes; merging publishes it. Open it again whenever you want the numbers updated.</p>
<form method="post" action="/metrics/publish" class="card">
<div class="cols">
<label>Website <select name="site">{{range .Sites}}<option value="{{.Index}}" {{if eq .Index $o.Site}}selected{{end}}>{{.URL}}</option>{{end}}</select></label>
<label>Address on the site <input name="path" value="{{$o.Path}}"></label>
</div>
<label>Title <input name="title" value="{{$o.Title}}"></label>
<fieldset><legend>What to show</legend>
{{range .Parts}}<label class="check"><input type="checkbox" name="part" value="{{.ID}}" {{if index $o.Parts .ID}}checked{{end}}> {{.Label}}</label>{{end}}
</fieldset>
<div class="actions">
<button type="submit" class="secondary" name="do" value="save">Save and preview</button>
<button type="submit" name="do" value="pr" data-busy="Opening…" {{if not .Gitea}}disabled title="Save a Gitea token under Settings → Search engines"{{end}}>Open a pull request</button>
</div>
{{with $o.PRURL}}<p class="small">Last opened {{ago $o.PRAt}}: <a href="{{.}}" target="_blank" rel="noopener noreferrer">the pull request ↗</a></p>{{end}}
</form>
<h2>Preview</h2>
{{if .Preview}}<pre class="sample">{{.Preview}}</pre>{{else}}<p class="help">There's no complete month of billing to publish yet.</p>{{end}}
{{end}}{{end}}
+3 -3
View File
@@ -9,7 +9,7 @@
<tbody>{{range .Months}}<tr><td>{{.Month}}</td><td class="num">{{if .Spend}}{{money .Spend}}{{else}}<span class="muted">·</span>{{end}}</td><td class="num">{{.New}}</td>
<td class="num">{{if .Spend}}{{cents .CAC}}{{else}}<span class="muted">no spend logged</span>{{end}}</td><td class="num">{{cents .Trailing3}}</td></tr>{{end}}</tbody>
</table></div>
<p class="help">One month's CAC swings with a handful of customers; the three-month figure is steadier.</p>
<p class="help">One month's CAC swings with a handful of customers; the three-month figure is steadier. <a href="/metrics/export/cac.csv">Download as CSV</a></p>
</section>
{{with .CAC.Channels}}
@@ -19,7 +19,7 @@
<thead><tr><th>Channel</th><th class="num">Spend</th><th class="num">New customers</th><th class="num">CAC</th></tr></thead>
<tbody>{{range .}}<tr><td>{{spendChannel .Channel}}</td><td class="num">{{money .Spend}}</td><td class="num">{{.New}}</td><td class="num">{{cents .CAC}}</td></tr>{{end}}</tbody>
</table>
<p class="help">{{if $d.CAC.Unknown}}{{$d.CAC.Unknown}} new customers had no step in the funnel before paying, so their channel is unknown. {{end}}General spend counts in the monthly CAC, not in any one channel's.</p>
<p class="help">{{if $d.CAC.Unknown}}{{$d.CAC.Unknown}} new customers had no step in the funnel before paying, so their channel is unknown. {{end}}General spend counts in the monthly CAC, not in any one channel's. <a href="/metrics/export/cac-channels.csv">Download as CSV</a></p>
</section>
{{end}}
@@ -42,7 +42,7 @@
</form>
{{if .Log}}
<h2>The log</h2>
<h2>The log <a class="small" href="/metrics/export/spend.csv">Download as CSV</a></h2>
<table class="list compact">
<thead><tr><th>Month</th><th>Channel</th><th class="num">Amount</th><th>Note</th><th>From</th><th></th></tr></thead>
<tbody>{{range .Log}}<tr><td>{{.Month}}</td><td>{{spendChannel .Channel}}</td><td class="num">{{money .AmountCents}}</td><td class="small">{{.Note}}</td><td class="small muted">{{.Source}}</td>
+11 -1
View File
@@ -27,6 +27,14 @@
<div class="step"><span class="label">NRR, this month</span><strong>{{pct .NRR}}</strong><span class="rate">of last month's MRR kept</span></div>
<div class="step"><span class="label">NRR, 12 months</span><strong>{{pct .NRR12}}</strong><span class="rate">what customers of a year ago pay now</span></div>
</div>
{{with $d.CLV}}
<div class="funnel">
<div class="step"><span class="label">Churn</span><strong>{{dec1f .Churn}}%</strong><span class="rate">of customers a month</span></div>
<div class="step"><span class="label">CLV</span><strong>{{cents .Value}}</strong><span class="rate">gross profit per customer</span></div>
<div class="step"><span class="label">CAC</span><strong>{{cents .CAC}}</strong><span class="rate">{{if lt .CAC 0.0}}<a href="/metrics/spend">log spend</a>{{else}}12 months{{end}}</span></div>
<div class="step"><span class="label">CLV : CAC</span><strong>{{if ge .Ratio 0.0}}{{dec1f .Ratio}} : 1{{else}}·{{end}}</strong></div>
</div>
{{end}}
{{with $d.Bars}}
<svg class="chart" viewBox="0 0 600 170" role="img" aria-label="MRR by month">
{{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}}
@@ -50,6 +58,7 @@
<td class="num">{{if .Reactivation}}{{usd .Reactivation}}{{else}}<span class="muted">·</span>{{end}}</td>
</tr>{{end}}</tbody>
</table></div>
<p class="small"><a href="/metrics/export/mrr.csv">Download as CSV</a> (every month)</p>
{{if $d.Cohorts}}
<h2>Cohorts</h2>
@@ -58,6 +67,7 @@
<thead><tr><th>First paid</th><th class="num">Customers</th><th class="num">Starting MRR</th>{{range $i, $_ := $d.Span}}<th class="num">{{$i}}</th>{{end}}</tr></thead>
<tbody>{{range $d.Cohorts}}<tr><td>{{.Month}}</td><td class="num">{{.Customers}}</td><td class="num">{{usd .Start}}</td>{{range .Retained}}<td class="num">{{if ge . 0.0}}{{pct .}}{{end}}</td>{{end}}</tr>{{end}}</tbody>
</table></div>
<p class="small"><a href="/metrics/export/nrr-cohorts.csv">Download as CSV</a> (every cohort, 24 months)</p>
{{end}}
<form method="post" action="/metrics/start" class="row small">
@@ -98,7 +108,7 @@
<td class="num">{{if .ID}}<input name="margin:{{.ID}}" value="{{if .Own}}{{.Margin}}{{end}}" placeholder="{{$m.Default}}" inputmode="decimal" size="5"> %{{else}}<span class="muted">default</span>{{end}}</td>
</tr>{{end}}</tbody>
</table>
<div class="actions"><button type="submit">Save margins</button></div>
<div class="actions"><button type="submit">Save margins</button> <a class="small" href="/metrics/export/products.csv">Download as CSV</a></div>
</form>
{{end}}
{{end}}{{end}}