diff --git a/PLAN.md b/PLAN.md index 680ed66..b50e9d1 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1118,6 +1118,25 @@ into `main`. explee.com campaigns already report it). - CAC = spend ÷ new paying customers, per month and per channel, with the channel taken from the customer's first funnel touch. + - **Built 2026-11-22** (schema 21: `spend`, `spend_seen`): + - Spend is logged by month and channel: the funnel's channels plus + "general" for overheads. It comes in by hand, or from a pasted CSV + of month,channel,amount,note (all or nothing). + - `SyncOutsideSpend` runs with the hourly metrics. It adds each + origami.chat or explee.com campaign's spend since last seen to the + current month. The first time, a campaign's whole lifetime spend + goes into that month, with a note saying so. On the live account, + that was explee.com's $344.51, in November 2026. + - `BuildCAC`: each month's spend ÷ its new customers (from the MRR + model), plus a trailing three-month figure. With no spend logged, + CAC is unknown, never $0. + - By channel, over 12 months: each new customer's channel is their + first funnel event, matched by email; Stripe's own steps don't + count, and customers with none are "unknown". Phase 2's + `stripe_customers.channel` defaults to "website", so it isn't + used. General spend counts toward monthly CAC, not toward any + channel. + - The page is Metrics → Spend and CAC. 5. **CLV and cohorts.** - CLV = ARPA × gross margin ÷ monthly churn rate, with the margin weighted by each product's share of the revenue. diff --git a/README.md b/README.md index f174e3f..7531462 100644 --- a/README.md +++ b/README.md @@ -149,7 +149,9 @@ Edit the brief and answer those questions ("not tested" is a fine answer), then - each month's movements (new, expansion, contraction, churn, reactivation), with a page per month listing each customer's move; - cohorts by the month customers first paid, with the share of their starting MRR they still pay. -MRR is built from the invoice lines (each recurring line's amount after discounts, spread over its billing period), so past months are exact. *Customers and the CRM* (under Metrics) matches each Stripe customer to its EspoCRM Account, in this order: +MRR is built from the invoice lines (each recurring line's amount after discounts, spread over its billing period), so past months are exact. *Spend and CAC* (under Metrics): log what marketing and sales cost each month, by channel, by hand or by pasting a CSV (`month,channel,amount,note`). origami.chat and explee.com campaign spend comes in on its own. CAC is the month's spend over the customers who first paid that month, with a steadier three-month figure. Over the last 12 months it's also shown per channel, using each new customer's first step in the funnel (a reply, a visit, an outreach email), matched by email. + +*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; - the email's domain (free mail doesn't count). diff --git a/TEST.md b/TEST.md index 45448aa..ae6cfbb 100644 --- a/TEST.md +++ b/TEST.md @@ -430,6 +430,20 @@ Throughout, also notice: starting base, and the suggestion goes away. - [ ] Cohorts start at 100% in their first month. +### Spend and CAC + +- [ ] Metrics → Spend and CAC: origami.chat and explee.com campaign spend + appears in the log on its own (the first time, all of it in the + current month, with a note). +- [ ] *Add* logs an amount for a month and channel; a bad amount or month + is refused. +- [ ] Pasting CSV rows imports them; one bad row imports nothing and names + the row. +- [ ] CAC for a month is its spend over its new customers (as counted on + MRR and NRR); months without spend say so instead of showing $0. +- [ ] By channel: a customer who first replied to an outreach email counts + under Email; customers with no step before paying count as unknown. + ### Customers and the CRM - [ ] Before Hermes has copied the CRM, Metrics → Customers and the CRM says diff --git a/internal/db/db.go b/internal/db/db.go index 4d0c519..17bd0ae 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -546,6 +546,27 @@ CREATE TABLE crm_matches ( espo_id TEXT NOT NULL DEFAULT '', -- the Account; '' means "not in the CRM" set_at TEXT NOT NULL ); +`, + // 21: the spend log, for CAC. + ` +CREATE TABLE spend ( + id INTEGER PRIMARY KEY, + month TEXT NOT NULL, -- YYYY-MM + channel TEXT NOT NULL, -- a funnel channel, or general + amount_cents INTEGER NOT NULL, + note TEXT NOT NULL DEFAULT '', + source TEXT NOT NULL DEFAULT 'manual', -- manual, csv, origami, explee + created_at TEXT NOT NULL +); +CREATE INDEX spend_by_month ON spend (month); +-- What each outside campaign had spent when last seen, so only the +-- difference is added. +CREATE TABLE spend_seen ( + source TEXT NOT NULL, + campaign TEXT NOT NULL, + spend_cents INTEGER NOT NULL, + PRIMARY KEY (source, campaign) +); `, } diff --git a/internal/metrics/spend.go b/internal/metrics/spend.go new file mode 100644 index 0000000..a8ca8f6 --- /dev/null +++ b/internal/metrics/spend.go @@ -0,0 +1,351 @@ +package metrics + +import ( + "encoding/csv" + "errors" + "fmt" + "io" + "math" + "slices" + "strconv" + "strings" + "time" + + "supermarket/internal/db" + "supermarket/internal/signals" +) + +// ChannelGeneral is spend that no one channel owns: tools, people, the +// website's hosting. +const ChannelGeneral = "general" + +// SpendChannels are the channels spend can be logged against. +func SpendChannels() []signals.Stage { + return append(slices.Clone(signals.Channels), signals.Stage{ID: ChannelGeneral, Label: "General (no one channel)"}) +} + +// ChannelName is how a spend channel is shown. +func ChannelName(id string) string { + switch id { + case ChannelGeneral: + return "General" + case "": + return "Unknown" + } + return signals.ChannelLabel(id) +} + +func validChannel(c string) bool { + for _, ch := range SpendChannels() { + if ch.ID == c { + return true + } + } + return false +} + +// Spend is one entry in the log. +type Spend struct { + ID int64 + Month string + Channel string + AmountCents int64 + Note string + Source string +} + +// AddSpend logs an amount for a month and channel. +func AddSpend(d *db.DB, sp Spend, now time.Time) error { + if _, err := time.Parse("2006-01", sp.Month); err != nil { + return fmt.Errorf("%q isn't a month (YYYY-MM)", sp.Month) + } + if !validChannel(sp.Channel) { + return fmt.Errorf("unknown channel %q", sp.Channel) + } + if sp.AmountCents == 0 { + return errors.New("give an amount") + } + if sp.Source == "" { + sp.Source = "manual" + } + _, err := d.Exec(`INSERT INTO spend (month, channel, amount_cents, note, source, created_at) VALUES (?, ?, ?, ?, ?, ?)`, + sp.Month, sp.Channel, sp.AmountCents, strings.TrimSpace(sp.Note), sp.Source, now.UTC().Format(time.RFC3339)) + return err +} + +// DeleteSpend removes an entry. +func DeleteSpend(d *db.DB, id int64) error { + _, err := d.Exec(`DELETE FROM spend WHERE id = ?`, id) + return err +} + +// SpendLog lists the entries, newest month first. +func SpendLog(d *db.DB, limit int) ([]Spend, error) { + rows, err := d.Query(`SELECT id, month, channel, amount_cents, note, source FROM spend ORDER BY month DESC, id DESC LIMIT ?`, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []Spend + for rows.Next() { + var s Spend + if err := rows.Scan(&s.ID, &s.Month, &s.Channel, &s.AmountCents, &s.Note, &s.Source); err != nil { + return nil, err + } + out = append(out, s) + } + return out, rows.Err() +} + +// ParseAmount reads "1,250.50", "$80" or "80" as cents. +func ParseAmount(s string) (int64, error) { + s = strings.NewReplacer("$", "", ",", "", " ", "").Replace(strings.TrimSpace(s)) + f, err := strconv.ParseFloat(s, 64) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, fmt.Errorf("%q isn't an amount", s) + } + return int64(math.Round(f * 100)), nil +} + +// ImportSpendCSV adds rows of month,channel,amount[,note]; a header row is +// skipped. Channels may be given by name ("LinkedIn") or ID ("linkedin"). +// Nothing is added unless every row is good. +func ImportSpendCSV(d *db.DB, r io.Reader, now time.Time) (int, error) { + cr := csv.NewReader(r) + cr.FieldsPerRecord = -1 // the note is optional + cr.TrimLeadingSpace = true + rows, err := cr.ReadAll() + if err != nil { + return 0, err + } + byName := map[string]string{} + for _, c := range SpendChannels() { + byName[strings.ToLower(c.ID)] = c.ID + byName[strings.ToLower(c.Label)] = c.ID + } + byName["general"] = ChannelGeneral + var entries []Spend + for i, row := range rows { + if len(row) < 3 { + return 0, fmt.Errorf("row %d: needs month, channel and amount", i+1) + } + month, ch, amt := strings.TrimSpace(row[0]), strings.ToLower(strings.TrimSpace(row[1])), row[2] + if i == 0 && strings.EqualFold(month, "month") { + continue + } + if t, err := time.Parse("2006-01-02", month); err == nil { + month = t.Format("2006-01") + } + if _, err := time.Parse("2006-01", month); err != nil { + return 0, fmt.Errorf("row %d: %q isn't a month (YYYY-MM)", i+1, month) + } + id, ok := byName[ch] + if !ok { + return 0, fmt.Errorf("row %d: unknown channel %q", i+1, row[1]) + } + cents, err := ParseAmount(amt) + if err != nil { + return 0, fmt.Errorf("row %d: %w", i+1, err) + } + note := "" + if len(row) > 3 { + note = row[3] + } + entries = append(entries, Spend{Month: month, Channel: id, AmountCents: cents, Note: note, Source: "csv"}) + } + for _, e := range entries { + if err := AddSpend(d, e, now); err != nil { + return 0, err + } + } + return len(entries), nil +} + +// SyncOutsideSpend adds what outside campaigns (origami.chat, explee.com) +// have spent since last seen, to the current month and their channel. The +// first time, a campaign's whole spend so far is added, with a note. +func SyncOutsideSpend(d *db.DB, now time.Time) (int, error) { + rows, err := d.Query(`SELECT c.source, c.id, c.name, c.spend_cents, s.spend_cents FROM outside_campaigns c + LEFT JOIN spend_seen s ON s.source = c.source AND s.campaign = c.id WHERE c.spend_cents > 0`) + if err != nil { + return 0, err + } + type seen struct { + source, id, name string + total int64 + before *int64 + } + var all []seen + for rows.Next() { + var s seen + if err := rows.Scan(&s.source, &s.id, &s.name, &s.total, &s.before); err != nil { + rows.Close() + return 0, err + } + all = append(all, s) + } + rows.Close() + added := 0 + month := now.Format("2006-01") + for _, s := range all { + var prev int64 + note := "spent in “" + s.name + "”" + if s.before == nil { + note = "spent in “" + s.name + "” before Supermarket tracked it month by month" + } else { + prev = *s.before + } + if delta := s.total - prev; delta != 0 { + if err := AddSpend(d, Spend{Month: month, Channel: s.source, AmountCents: delta, Note: note, Source: s.source}, now); err != nil { + return added, err + } + added++ + } + if _, err := d.Exec(`INSERT INTO spend_seen (source, campaign, spend_cents) VALUES (?, ?, ?) + ON CONFLICT (source, campaign) DO UPDATE SET spend_cents = excluded.spend_cents`, s.source, s.id, s.total); err != nil { + return added, err + } + } + return added, nil +} + +// --- CAC --- + +// CACMonth is one month's spend, new customers and CAC. +type CACMonth struct { + Month string + Spend int64 // cents + New int + CAC float64 // cents; -1 with no new customers + Trailing3 float64 // three months' spend ÷ three months' new customers; -1 when none +} + +// CACChannel is a channel's spend and new customers over a period. +type CACChannel struct { + Channel string + Spend int64 + New int + CAC float64 // -1 with no new customers +} + +// CAC is spend over new paying customers. +type CAC struct { + Months []CACMonth // newest first + Channels []CACChannel // over the last 12 months + Unknown int // new customers with no known first touch +} + +// firstTouch is each email's first funnel channel, from the events the +// funnel recorded before a payment (Stripe's own steps don't count). +func firstTouch(d *db.DB) (map[string]string, error) { + rows, err := d.Query(`SELECT email, channel FROM funnel_events WHERE email != '' AND source != 'stripe' ORDER BY at`) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]string{} + for rows.Next() { + var e, c string + if err := rows.Scan(&e, &c); err != nil { + return nil, err + } + e = strings.ToLower(e) + if _, ok := out[e]; !ok { + out[e] = c + } + } + return out, rows.Err() +} + +// BuildCAC works out CAC from the spend log and the MRR model's new +// customers, by month and, over the last 12 months, by each new customer's +// first funnel channel. +func BuildCAC(d *db.DB, model *Model, names map[string]Customer) (*CAC, error) { + spend := map[string]int64{} + byChan := map[string]int64{} + rows, err := d.Query(`SELECT month, channel, sum(amount_cents) FROM spend GROUP BY month, channel`) + if err != nil { + return nil, err + } + var last12 map[string]bool + if n := len(model.Months); n > 0 { + last12 = map[string]bool{} + for i := max(0, n-12); i < n; i++ { + last12[model.Months[i].Month] = true + } + } + for rows.Next() { + var m, c string + var a int64 + if err := rows.Scan(&m, &c, &a); err != nil { + rows.Close() + return nil, err + } + spend[m] += a + if last12[m] { + byChan[c] += a + } + } + rows.Close() + touch, err := firstTouch(d) + if err != nil { + return nil, err + } + out := &CAC{} + newByChan := map[string]int{} + ms := model.Months + for i := len(ms) - 1; i >= 0; i-- { + mo := ms[i] + cm := CACMonth{Month: mo.Month, Spend: spend[mo.Month], New: mo.NewCount, CAC: -1, Trailing3: -1} + if cm.New > 0 && cm.Spend != 0 { + cm.CAC = float64(cm.Spend) / float64(cm.New) + } + var s3 int64 + n3 := 0 + for j := i; j > i-3 && j >= 0; j-- { + s3 += spend[ms[j].Month] + n3 += ms[j].NewCount + } + // Without spend logged, CAC is unknown, not zero. + if n3 > 0 && i >= 2 && s3 != 0 { + cm.Trailing3 = float64(s3) / float64(n3) + } + out.Months = append(out.Months, cm) + if last12[mo.Month] { + for c, k := range mo.Moves { + if k != MoveNew { + continue + } + ch := touch[strings.ToLower(names[c].Email)] + if ch == "" { + out.Unknown++ + } + newByChan[ch]++ + } + } + } + keys := map[string]bool{} + for c := range byChan { + keys[c] = true + } + for c := range newByChan { + keys[c] = true + } + for c := range keys { + cc := CACChannel{Channel: c, Spend: byChan[c], New: newByChan[c], CAC: -1} + if cc.New > 0 && c != "" && c != ChannelGeneral { + cc.CAC = float64(cc.Spend) / float64(cc.New) + } + out.Channels = append(out.Channels, cc) + } + slices.SortFunc(out.Channels, func(a, b CACChannel) int { + if a.Spend != b.Spend { + if a.Spend > b.Spend { + return -1 + } + return 1 + } + return b.New - a.New + }) + return out, nil +} diff --git a/internal/metrics/spend_test.go b/internal/metrics/spend_test.go new file mode 100644 index 0000000..af3b831 --- /dev/null +++ b/internal/metrics/spend_test.go @@ -0,0 +1,109 @@ +package metrics + +import ( + "strings" + "testing" + "time" +) + +func TestSpendLog(t *testing.T) { + d := openDB(t) + now := time.Date(2026, 11, 22, 0, 0, 0, 0, time.UTC) + if err := AddSpend(d, Spend{Month: "2026-11", Channel: "linkedin", AmountCents: 32000}, now); err != nil { + t.Fatal(err) + } + for _, bad := range []Spend{{Month: "Nov", Channel: "linkedin", AmountCents: 1}, {Month: "2026-11", Channel: "tv", AmountCents: 1}, {Month: "2026-11", Channel: "email"}} { + if err := AddSpend(d, bad, now); err == nil { + t.Errorf("accepted %+v", bad) + } + } + if c, err := ParseAmount("$1,250.50"); err != nil || c != 125050 { + t.Errorf("amount: %d %v", c, err) + } + // A CSV with a bad row adds nothing. + if _, err := ImportSpendCSV(d, strings.NewReader("month,channel,amount,note\n2026-10,LinkedIn,100,ads\n2026-10,Radio,5\n"), now); err == nil || !strings.Contains(err.Error(), "row 3") { + t.Errorf("bad csv: %v", err) + } + n, err := ImportSpendCSV(d, strings.NewReader("month,channel,amount,note\n2026-10-01,LinkedIn,100,ads\n2026-10,general,\"1,000\",tools\n"), now) + if err != nil || n != 2 { + t.Fatalf("csv: %d %v", n, err) + } + log, _ := SpendLog(d, 10) + if len(log) != 3 || log[0].Month != "2026-11" || log[2].Channel != "linkedin" || log[1].AmountCents != 100000 || log[2].Source != "csv" { + t.Errorf("log: %+v", log) + } + DeleteSpend(d, log[0].ID) + if log, _ := SpendLog(d, 10); len(log) != 2 { + t.Errorf("after delete: %+v", log) + } + + // Outside campaigns: the whole spend the first time, then the difference. + d.Exec(`INSERT INTO outside_campaigns (source, id, name, spend_cents, synced_at) VALUES ('explee', '7', 'Nonprofits', 20000, ''), ('origami', 'x', 'Zero', 0, '')`) + if n, _ := SyncOutsideSpend(d, now); n != 1 { + t.Errorf("first sync: %d", n) + } + d.Exec(`UPDATE outside_campaigns SET spend_cents = 26500 WHERE id = '7'`) + SyncOutsideSpend(d, now.AddDate(0, 1, 0)) + if n, _ := SyncOutsideSpend(d, now.AddDate(0, 1, 0)); n != 0 { + t.Error("synced the same spend twice") + } + var dec int64 + var note string + d.QueryRow(`SELECT amount_cents, note FROM spend WHERE source = 'explee' AND month = '2026-12'`).Scan(&dec, ¬e) + if dec != 6500 || !strings.Contains(note, "Nonprofits") { + t.Errorf("delta: %d %q", dec, note) + } +} + +func TestCAC(t *testing.T) { + d := openDB(t) + now := time.Date(2026, 6, 20, 0, 0, 0, 0, time.UTC) + addLines(t, d, monthly("cus_a", 5000, "2026-03", "2026-07")...) + addLines(t, d, monthly("cus_b", 5000, "2026-04", "2026-07")...) + addLines(t, d, monthly("cus_c", 5000, "2026-04", "2026-07")...) + addLines(t, d, monthly("cus_d", 5000, "2026-06", "2026-07")...) + names := map[string]Customer{"cus_a": {Email: "a@x.example"}, "cus_b": {Email: "b@x.example"}, "cus_c": {Email: "c@x.example"}, "cus_d": {Email: "d@x.example"}} + // b came from an outreach email, c from LinkedIn (first touch wins), d's + // only step is its Stripe payment, which doesn't count. + for _, e := range []struct{ email, channel, source, at string }{ + {"b@x.example", "email", "supermarket", "2026-03-01"}, {"c@x.example", "linkedin", "manual", "2026-02-01"}, + {"c@x.example", "email", "supermarket", "2026-03-01"}, {"d@x.example", "website", "stripe", "2026-06-11"}, + } { + d.Exec(`INSERT INTO funnel_events (stage, channel, email, source, at) VALUES ('contacted', ?, ?, ?, ?)`, e.channel, e.email, e.source, e.at+"T00:00:00Z") + } + for _, s := range []Spend{{Month: "2026-04", Channel: "email", AmountCents: 30000}, {Month: "2026-04", Channel: "general", AmountCents: 10000}, + {Month: "2026-06", Channel: "linkedin", AmountCents: 20000}} { + if err := AddSpend(d, s, now); err != nil { + t.Fatal(err) + } + } + m, _ := Build(d, now) + c, err := BuildCAC(d, m, names) + if err != nil { + t.Fatal(err) + } + got := map[string]CACMonth{} + for _, cm := range c.Months { + got[cm.Month] = cm + } + if apr := got["2026-04"]; apr.New != 2 || apr.Spend != 40000 || apr.CAC != 20000 { + t.Errorf("april: %+v", apr) + } + if may := got["2026-05"]; may.CAC != -1 { + t.Errorf("may has no new customers: %+v", may) + } + // June, three months: $600 over 3 customers (b, c, d; a was in March). + if jun := got["2026-06"]; jun.Trailing3 != 20000 || jun.CAC != 20000 { + t.Errorf("june: %+v", jun) + } + ch := map[string]CACChannel{} + for _, x := range c.Channels { + ch[x.Channel] = x + } + if ch["email"].New != 1 || ch["email"].CAC != 30000 || ch["linkedin"].New != 1 || ch["linkedin"].CAC != 20000 || ch["general"].CAC != -1 { + t.Errorf("channels: %+v", ch) + } + if c.Unknown != 2 || ch[""].New != 2 { + t.Errorf("unknown: %d %+v", c.Unknown, ch[""]) + } +} diff --git a/internal/web/engines_test.go b/internal/web/engines_test.go index 5c62f71..7e4d99a 100644 --- a/internal/web/engines_test.go +++ b/internal/web/engines_test.go @@ -137,3 +137,26 @@ func TestCustomersPage(t *testing.T) { t.Errorf("bad id: %d", rec.Code) } } + +func TestSpendPage(t *testing.T) { + _, h := newTestServer(t, nil) + if rec := postForm(h, "/metrics/spend", url.Values{"month": {"2026-10"}, "channel": {"linkedin"}, "amount": {"$320"}, "note": {"ads"}}); rec.Code != http.StatusSeeOther { + t.Fatalf("add: %d %s", rec.Code, rec.Body) + } + if rec := postForm(h, "/metrics/spend", url.Values{"csv": {"2026-09,general,1000,tools"}}); rec.Code != http.StatusSeeOther { + t.Fatalf("csv: %d %s", rec.Code, rec.Body) + } + body := do(h, http.MethodGet, "/metrics/spend", nil, nil).Body.String() + for _, want := range []string{"$320", "ads", "$1,000", "General"} { + if !strings.Contains(body, want) { + t.Errorf("spend page lacks %q", want) + } + } + if rec := postForm(h, "/metrics/spend", url.Values{"month": {"2026-10"}, "channel": {"linkedin"}, "amount": {"lots"}}); !strings.Contains(rec.Body.String(), "isn't an amount") { + t.Error("a bad amount was accepted") + } + postForm(h, "/metrics/spend/1/delete", nil) + if body := do(h, http.MethodGet, "/metrics/spend", nil, nil).Body.String(); strings.Contains(body, ">ads<") { + t.Error("the entry wasn't deleted") + } +} diff --git a/internal/web/metrics.go b/internal/web/metrics.go index 3b0f3e6..420add2 100644 --- a/internal/web/metrics.go +++ b/internal/web/metrics.go @@ -179,6 +179,9 @@ func (s *Server) RunMetrics(ctx context.Context) { defer tick.Stop() for { if c := s.stripe(); c != nil { + if _, err := metrics.SyncOutsideSpend(s.DB, time.Now()); err != nil { + s.Log.Warn("metrics: outside spend", "err", err) + } last := metrics.LastSync(s.DB) if last == nil || time.Since(last.At) >= time.Hour { sctx, cancel := context.WithTimeout(ctx, 30*time.Minute) @@ -319,3 +322,81 @@ func (s *Server) queueAccount(cust string) error { _, err = crm.Enqueue(s.DB, crm.Action{Key: "stripe-customer:" + cust, Entity: "Account", Fields: fields, Match: match, Origin: "stripe-customer:" + cust}) return err } + +// --- Spend and CAC --- + +func (s *Server) metricsSpend(w http.ResponseWriter, r *http.Request) { + s.renderSpend(w, r, "") +} + +func (s *Server) renderSpend(w http.ResponseWriter, r *http.Request, errMsg string) { + model, err := metrics.Build(s.DB, time.Now()) + if err != nil { + s.serverError(w, err) + return + } + names, err := metrics.CustomerNames(s.DB) + if err != nil { + s.serverError(w, err) + return + } + cac, err := metrics.BuildCAC(s.DB, model, names) + if err != nil { + s.serverError(w, err) + return + } + log, err := metrics.SpendLog(s.DB, 200) + if err != nil { + s.serverError(w, err) + return + } + months := cac.Months + if len(months) > 13 { + months = months[:13] + } + s.render(w, r, "metrics-spend", page{Title: "Spend and CAC", Nav: "metrics/spend", Error: errMsg, Data: map[string]any{ + "CAC": cac, "Months": months, "Log": log, "Channels": metrics.SpendChannels(), "This": time.Now().Format("2006-01"), + }}) +} + +// metricsSpendAdd logs spend, or imports a CSV. +func (s *Server) metricsSpendAdd(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + now := time.Now() + if csvText := strings.TrimSpace(r.PostFormValue("csv")); csvText != "" { + n, err := metrics.ImportSpendCSV(s.DB, strings.NewReader(csvText), now) + if err != nil { + s.renderSpend(w, r, "Nothing imported: "+err.Error()) + return + } + s.Log.Info("metrics: spend imported", "rows", n) + redirect(w, r, "/metrics/spend", "imported") + return + } + cents, err := metrics.ParseAmount(r.PostFormValue("amount")) + if err == nil { + err = metrics.AddSpend(s.DB, metrics.Spend{Month: strings.TrimSpace(r.PostFormValue("month")), Channel: r.PostFormValue("channel"), + AmountCents: cents, Note: r.PostFormValue("note")}, now) + } + if err != nil { + s.renderSpend(w, r, err.Error()) + return + } + redirect(w, r, "/metrics/spend", "saved") +} + +func (s *Server) metricsSpendDelete(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + if err := metrics.DeleteSpend(s.DB, id); err != nil { + s.serverError(w, err) + return + } + redirect(w, r, "/metrics/spend", "deleted") +} diff --git a/internal/web/server.go b/internal/web/server.go index bb2276c..cdd1805 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -21,6 +21,7 @@ import ( "supermarket/internal/core" "supermarket/internal/db" "supermarket/internal/legacy" + "supermarket/internal/metrics" "supermarket/internal/oauth" "supermarket/internal/prospects" "supermarket/internal/secrets" @@ -166,6 +167,9 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("POST /metrics/start", s.metricsStart) mux.HandleFunc("GET /metrics/month/{month}", s.metricsMonth) mux.HandleFunc("GET /metrics/customers", s.metricsCustomers) + mux.HandleFunc("GET /metrics/spend", s.metricsSpend) + mux.HandleFunc("POST /metrics/spend", s.metricsSpendAdd) + mux.HandleFunc("POST /metrics/spend/{id}/delete", s.metricsSpendDelete) mux.HandleFunc("POST /metrics/customers/{id}", s.metricsCustomerMatch) mux.HandleFunc("GET /seo", s.seoPage) mux.HandleFunc("GET /seo/check", s.seoCheckPage) @@ -321,6 +325,13 @@ func (s *Server) loadTemplates() error { } return strconv.FormatFloat(f, 'f', 0, 64) + "%" }, + "spendChannel": metrics.ChannelName, + "cents": func(f float64) string { + if f < 0 { + return "·" + } + return money(int64(math.Round(f))) + }, "num": seo.Thousands, "cls": func(x100 int) float64 { return float64(x100) / 100 }, "dec1": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) }, diff --git a/internal/web/server_test.go b/internal/web/server_test.go index aee7b9b..9116a09 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", + "/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", "/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 498f179..7360966 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -53,6 +53,7 @@ {{if eq .ID "metrics"}}
{{end}} diff --git a/internal/web/templates/metrics-spend.html b/internal/web/templates/metrics-spend.html new file mode 100644 index 0000000..78eaef3 --- /dev/null +++ b/internal/web/templates/metrics-spend.html @@ -0,0 +1,52 @@ +{{define "content"}}{{with .Data}}{{$d := .}} +What it costs to win a paying customer: the month's marketing and sales spend over the customers who first paid that month. Stripe has no spend, so log it here: by hand, from a CSV, or automatically for origami.chat and explee.com campaigns. Channel CAC uses each new customer's first step in the funnel (a reply, a visit, an outreach email…), matched by email.
+ +| Month | Spend | New customers | CAC | CAC, 3 months |
|---|---|---|---|---|
| {{.Month}} | {{if .Spend}}{{money .Spend}}{{else}}·{{end}} | {{.New}} | +{{if .Spend}}{{cents .CAC}}{{else}}no spend logged{{end}} | {{cents .Trailing3}} |
One month's CAC swings with a handful of customers; the three-month figure is steadier.
+| Channel | Spend | New customers | CAC |
|---|---|---|---|
| {{spendChannel .Channel}} | {{money .Spend}} | {{.New}} | {{cents .CAC}} |
{{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.
+| Month | Channel | Amount | Note | From | |
|---|---|---|---|---|---|
| {{.Month}} | {{spendChannel .Channel}} | {{money .AmountCents}} | {{.Note}} | {{.Source}} | +