Phase 4 part 4: the spend log and CAC
Spend by month and channel (the funnel's channels and general), by hand or from pasted CSV (all or nothing); origami.chat and explee.com campaign spend added hourly as the difference since last seen. CAC per month and over three months, and per channel over 12 months from each new customer's first funnel step; unknown, not $0, without spend. Metrics → Spend and CAC. Schema 21. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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[""])
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user