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:
@@ -534,3 +534,20 @@ func BuiltFile(outDir, rel string) (string, error) {
|
||||
raw, err := os.ReadFile(filepath.Join(outDir, rel))
|
||||
return string(raw), err
|
||||
}
|
||||
|
||||
// UpsertPage writes a content file, or, if it exists, replaces its body and
|
||||
// sets the given front matter fields.
|
||||
func (r *Repo) UpsertPage(rel string, fields []Field, body string) error {
|
||||
if !r.Exists(rel) {
|
||||
return r.NewPage(rel, fields, body)
|
||||
}
|
||||
if err := r.ReplaceBody(rel, body); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, f := range fields {
|
||||
if err := r.SetFrontMatter(rel, f.Key, f.Value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/api/gitea"
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/hugorepo"
|
||||
)
|
||||
@@ -265,3 +266,48 @@ func (ap *Applier) setupSite(ctx context.Context, site, key string, st *Setup) e
|
||||
st.PRNumber, st.PRURL, st.Note = pr.Number, pr.HTMLURL, note
|
||||
return nil
|
||||
}
|
||||
|
||||
// PublishPage opens a pull request that adds a page to the site, or
|
||||
// updates it if it's there: used for the open metrics page. The build
|
||||
// checks the page comes out.
|
||||
func (ap *Applier) PublishPage(ctx context.Context, pagePath, title, description, body, why string) (*gitea.Pull, string, error) {
|
||||
wc, full, branch, err := ap.workingCopy(ctx)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
canBuild, note := buildCheck(ctx, wc)
|
||||
pagePath = "/" + strings.Trim(pagePath, "/") + "/"
|
||||
work := "supermarket/page" + strings.TrimSuffix(strings.ReplaceAll(pagePath, "/", "-"), "-")
|
||||
if err := wc.NewBranch(ctx, work); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
file, err := wc.FindContent(pagePath)
|
||||
if err != nil {
|
||||
file = "content" + strings.TrimSuffix(pagePath, "/") + ".md"
|
||||
}
|
||||
fields := []hugorepo.Field{{Key: "title", Value: title}, {Key: "description", Value: description}, {Key: "date", Value: time.Now().Format("2006-01-02")}}
|
||||
if err := wc.UpsertPage(file, fields, body); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if canBuild {
|
||||
out, err := wc.Build(ctx)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("after the change, %w", err)
|
||||
}
|
||||
_, _, err = hugorepo.BuiltHead(out, pagePath)
|
||||
os.RemoveAll(out)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("the site builds, but %w", err)
|
||||
}
|
||||
note = "Checked with a build: the page is at " + pagePath + "."
|
||||
}
|
||||
subject := "Update " + pagePath + ": " + title
|
||||
if err := wc.CommitAndPush(ctx, work, subject); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
pr, err := ap.Gitea.OpenPull(ctx, full, work, branch, subject, why+"\n\n"+note+"\n\nMerging publishes it.")
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return pr, file, nil
|
||||
}
|
||||
|
||||
@@ -111,3 +111,31 @@ func TestSetupSite(t *testing.T) {
|
||||
t.Error("the setup isn't kept")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishPage(t *testing.T) {
|
||||
if hugorepo.HugoVersion(context.Background()) == "" {
|
||||
t.Skip("no hugo")
|
||||
}
|
||||
clone := hugotest.Site(t)
|
||||
n := 0
|
||||
g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/api/v1/repos/o/site":
|
||||
json.NewEncoder(w).Encode(map[string]any{"full_name": "o/site", "default_branch": "main", "clone_url": clone, "permissions": map[string]any{"push": true}})
|
||||
case r.URL.Path == "/api/v1/repos/o/site/pulls":
|
||||
n++
|
||||
json.NewEncoder(w).Encode(map[string]any{"number": n, "html_url": fmt.Sprintf("https://gitea.example/pr/%d", n)})
|
||||
}
|
||||
}))
|
||||
defer g.Close()
|
||||
ap := &Applier{Gitea: gitea.New(g.URL, "tok"), Repo: "o/site", ReposDir: filepath.Join(t.TempDir(), "sites"), Author: "P <p@example.com>"}
|
||||
pr, file, err := ap.PublishPage(context.Background(), "/metrics/", "Open metrics", "Our numbers.", "MRR: $150\n", "why")
|
||||
if err != nil || pr.Number != 1 || file != "content/metrics.md" {
|
||||
t.Fatalf("publish: %+v %q %v", pr, file, err)
|
||||
}
|
||||
repo := strings.TrimPrefix(clone, "file://")
|
||||
out, _ := exec.Command("git", "-C", repo, "show", "supermarket/page-metrics:content/metrics.md").CombinedOutput()
|
||||
if !strings.Contains(string(out), `title: "Open metrics"`) || !strings.Contains(string(out), "MRR: $150") {
|
||||
t.Errorf("page: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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"}}
|
||||
|
||||
@@ -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}}
|
||||
@@ -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>
|
||||
|
||||
@@ -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}}
|
||||
|
||||
Reference in New Issue
Block a user