From 152c14b5805e06495c5b75d07c84f4937b002c72 Mon Sep 17 00:00:00 2001 From: David Young Date: Sun, 22 Nov 2026 13:28:50 -0700 Subject: [PATCH] Phase 4 part 6: the dashboard, CSV exports and an open metrics page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- PLAN.md | 17 ++ README.md | 2 + TEST.md | 12 + internal/hugorepo/repo.go | 17 ++ internal/metrics/export.go | 249 ++++++++++++++++++ internal/metrics/export_test.go | 61 +++++ internal/seo/engines.go | 46 ++++ internal/seo/engines_test.go | 28 ++ internal/web/engines_test.go | 33 +++ internal/web/metrics.go | 128 +++++++++ internal/web/server.go | 3 + internal/web/server_test.go | 2 +- internal/web/templates/layout.html | 1 + internal/web/templates/metrics-clv.html | 1 + internal/web/templates/metrics-customers.html | 1 + internal/web/templates/metrics-publish.html | 23 ++ internal/web/templates/metrics-spend.html | 6 +- internal/web/templates/metrics.html | 12 +- 18 files changed, 637 insertions(+), 5 deletions(-) create mode 100644 internal/metrics/export.go create mode 100644 internal/metrics/export_test.go create mode 100644 internal/web/templates/metrics-publish.html diff --git a/PLAN.md b/PLAN.md index 0dec6ef..4fba511 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1170,6 +1170,23 @@ into `main`. - CSV export of every table. - Optionally published as a page on one of the sites, through a pull request. + - **Built 2026-11-22** (no schema change): + - The MRR and NRR page has a second strip: churn, CLV, CAC and + CLV:CAC. + - `metrics.Export` writes eight tables as CSV, amounts in dollars: + MRR month by month (every month), NRR by cohort and revenue by + cohort (24 months), CAC by month and by channel, the spend log, + products and margins, and customers with their MRR and CRM match. + Each is downloaded at `/metrics/export/.csv`, linked under + its table. + - **Metrics → Publish** builds an open metrics page in Markdown, + with totals only: MRR and ARR, customers and ARPA, 12-month + growth, NRR, churn, and a 12-month table, chosen part by part. + - `seo.Applier.PublishPage` opens a pull request that adds or + updates the page (`hugorepo.UpsertPage`), checked with a Hugo + build. The options and the last pull request are kept. A test + checks that no customer's name, email or ID can appear on the + page. 7. **Pipeline influence**, once the CRM bridge works: the value of open and won EspoCRM opportunities with at least one marketing touch, by channel. diff --git a/README.md b/README.md index 67aedd4..d3ccdad 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,8 @@ MRR is built from the invoice lines (each recurring line's amount after discount *CLV and cohorts* (under Metrics): customer lifetime value, as gross profit per customer. That's the average MRR per customer × the gross margin (weighted by product) ÷ the monthly churn rate averaged over 12 months. It's shown beside CAC as CLV:CAC (3:1 or better is healthy). Below it, each signup cohort's actual cumulative revenue per customer, month by month: what came in, less refunds and credits, with a gross profit view. +Every Metrics table has a *Download as CSV* link. *Publish* (under Metrics) builds an "open metrics" page for your website from the numbers you choose: MRR and ARR, customers, growth, NRR, churn, a monthly table. It shows totals only, never anything about any one customer. *Open a pull request* adds or updates the page on the site's Gitea repository; merging publishes it. + *Customers and the CRM* (under Metrics) matches each Stripe customer to its EspoCRM Account, in this order: - a stored ID, either side; - the email, on the Account or one of its Contacts; diff --git a/TEST.md b/TEST.md index c1d6407..135c047 100644 --- a/TEST.md +++ b/TEST.md @@ -456,6 +456,18 @@ Throughout, also notice: cohort whose refunds exceed its payments shows a negative amount. - [ ] *Gross profit* shows the same table after margin. +### Downloads and publishing + +- [ ] Each Metrics table's *Download as CSV* gives a file that opens in a + spreadsheet, with the same numbers as the page. +- [ ] The MRR and NRR page shows churn, CLV, CAC and CLV:CAC above the + chart. +- [ ] Metrics → Publish: choosing what to show and *Save and preview* + changes the preview; no customer is named anywhere in it. +- [ ] **(real)** *Open a pull request* adds the page (or updates it) on the + site's repository, checked with a build; after merging, it's live at + the address chosen. + ### Customers and the CRM - [ ] Before Hermes has copied the CRM, Metrics → Customers and the CRM says diff --git a/internal/hugorepo/repo.go b/internal/hugorepo/repo.go index 60534bc..f0118ab 100644 --- a/internal/hugorepo/repo.go +++ b/internal/hugorepo/repo.go @@ -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 +} diff --git a/internal/metrics/export.go b/internal/metrics/export.go new file mode 100644 index 0000000..fc9c3f8 --- /dev/null +++ b/internal/metrics/export.go @@ -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 +} diff --git a/internal/metrics/export_test.go b/internal/metrics/export_test.go new file mode 100644 index 0000000..ddde05c --- /dev/null +++ b/internal/metrics/export_test.go @@ -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) + } +} diff --git a/internal/seo/engines.go b/internal/seo/engines.go index dd48ce4..b0cdd4e 100644 --- a/internal/seo/engines.go +++ b/internal/seo/engines.go @@ -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 +} diff --git a/internal/seo/engines_test.go b/internal/seo/engines_test.go index 66a1531..6c9304b 100644 --- a/internal/seo/engines_test.go +++ b/internal/seo/engines_test.go @@ -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 "} + 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) + } +} diff --git a/internal/web/engines_test.go b/internal/web/engines_test.go index 7e4d99a..b61e051 100644 --- a/internal/web/engines_test.go +++ b/internal/web/engines_test.go @@ -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") + } +} diff --git a/internal/web/metrics.go b/internal/web/metrics.go index 22e1887..370f5af 100644 --- a/internal/web/metrics.go +++ b/internal/web/metrics.go @@ -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) +} diff --git a/internal/web/server.go b/internal/web/server.go index e804e2c..14a1ba4 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -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) diff --git a/internal/web/server_test.go b/internal/web/server_test.go index bc177ea..fc9dd66 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -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 { diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index 7f59df6..5898946 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -56,6 +56,7 @@ Spend and CAC CLV and cohorts Customers and the CRM + Publish {{end}} {{if eq .ID "prospects"}} diff --git a/internal/web/templates/metrics-clv.html b/internal/web/templates/metrics-clv.html index 2f0eafc..dd015d9 100644 --- a/internal/web/templates/metrics-clv.html +++ b/internal/web/templates/metrics-clv.html @@ -33,5 +33,6 @@ {{if $d.Profit}}{{range .Margin}}{{if .Known}}{{usd .V}}{{end}}{{end}}{{else}}{{range .PerCustomer}}{{if .Known}}{{usd .V}}{{end}}{{end}}{{end}} {{end}} +

Download as CSV (every cohort, 24 months)

{{end}} {{end}}{{end}} diff --git a/internal/web/templates/metrics-customers.html b/internal/web/templates/metrics-customers.html index 0237c1a..f43d16e 100644 --- a/internal/web/templates/metrics-customers.html +++ b/internal/web/templates/metrics-customers.html @@ -19,6 +19,7 @@ +

Download every customer as CSV