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. Spend is never // below zero. 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) } if f < 0 { return 0, fmt.Errorf("%q is below zero: log what was spent, as a positive 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 }