Phase 4 part 5: CLV and revenue by cohort
CLV = ARPA × revenue-weighted gross margin ÷ customer churn averaged over up to 12 complete months, with lifetime and CLV:CAC (CAC over its own 12-month window). Revenue by cohort from money that came in: paid invoices less refunds and post-payment credits not refunded, cumulative per customer, with a gross profit view; months not reached are told apart from negative amounts. Metrics → CLV and cohorts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1142,6 +1142,29 @@ into `main`.
|
|||||||
weighted by each product's share of the revenue.
|
weighted by each product's share of the revenue.
|
||||||
- Each signup cohort's actual cumulative revenue, net of refunds and
|
- Each signup cohort's actual cumulative revenue, net of refunds and
|
||||||
credit notes.
|
credit notes.
|
||||||
|
- **Built 2026-11-22** (no schema change):
|
||||||
|
- **`BuildCLV`** measures on the last complete month:
|
||||||
|
- ARPA;
|
||||||
|
- the margin, weighted by each product's 12-month billings;
|
||||||
|
- customer churn, as customers lost ÷ customers at the start,
|
||||||
|
summed over up to the last 12 complete months;
|
||||||
|
- lifetime = 1 ÷ churn;
|
||||||
|
- CLV = ARPA × margin × lifetime;
|
||||||
|
- CAC = spend ÷ new customers over its own 12-month window (churn
|
||||||
|
needs the month before, so its window starts a month later);
|
||||||
|
- CLV:CAC.
|
||||||
|
- **`RevenueByCohort`** uses money that actually came in: paid
|
||||||
|
invoices' `amount_paid` at `paid_at`, minus refunds that
|
||||||
|
succeeded, minus post-payment credit notes less any part refunded
|
||||||
|
(pre-payment notes already lowered the amount paid). It's counted
|
||||||
|
by the month it happened, cumulative per customer, for each first
|
||||||
|
paid month, with a gross profit view.
|
||||||
|
- Cells mark months not reached yet separately from the amount,
|
||||||
|
because revenue can be negative when refunds exceed payments.
|
||||||
|
- The page is Metrics → CLV and cohorts. On the live account, CLV
|
||||||
|
is about $1,161 of gross profit per customer: $94 a month, 60%
|
||||||
|
margin, 4.9% monthly churn, a 20.6-month lifetime. CAC waits for
|
||||||
|
spend to be logged.
|
||||||
6. **The dashboard.**
|
6. **The dashboard.**
|
||||||
- MRR over time with its movements, NRR, CAC, CLV and CLV:CAC.
|
- MRR over time with its movements, NRR, CAC, CLV and CLV:CAC.
|
||||||
- CSV export of every table.
|
- CSV export of every table.
|
||||||
|
|||||||
@@ -151,6 +151,8 @@ Edit the brief and answer those questions ("not tested" is a fine answer), then
|
|||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
|
*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.
|
||||||
|
|
||||||
*Customers and the CRM* (under Metrics) matches each Stripe customer to its EspoCRM Account, in this order:
|
*Customers and the CRM* (under Metrics) matches each Stripe customer to its EspoCRM Account, in this order:
|
||||||
- a stored ID, either side;
|
- a stored ID, either side;
|
||||||
- the email, on the Account or one of its Contacts;
|
- the email, on the Account or one of its Contacts;
|
||||||
|
|||||||
@@ -444,6 +444,18 @@ Throughout, also notice:
|
|||||||
- [ ] By channel: a customer who first replied to an outreach email counts
|
- [ ] By channel: a customer who first replied to an outreach email counts
|
||||||
under Email; customers with no step before paying count as unknown.
|
under Email; customers with no step before paying count as unknown.
|
||||||
|
|
||||||
|
### CLV and cohorts
|
||||||
|
|
||||||
|
- [ ] Metrics → CLV and cohorts shows CLV with what it rests on: average
|
||||||
|
per customer, gross margin (it changes when you set product
|
||||||
|
margins), monthly churn and lifetime. Check: CLV = average × margin ×
|
||||||
|
lifetime.
|
||||||
|
- [ ] With spend logged, CAC over 12 months and CLV:CAC appear.
|
||||||
|
- [ ] Revenue by cohort: pick one customer who started alone in a month and
|
||||||
|
compare the row with what they paid in Stripe, less refunds. A
|
||||||
|
cohort whose refunds exceed its payments shows a negative amount.
|
||||||
|
- [ ] *Gross profit* shows the same table after margin.
|
||||||
|
|
||||||
### Customers and the CRM
|
### Customers and the CRM
|
||||||
|
|
||||||
- [ ] Before Hermes has copied the CRM, Metrics → Customers and the CRM says
|
- [ ] Before Hermes has copied the CRM, Metrics → Customers and the CRM says
|
||||||
|
|||||||
@@ -0,0 +1,242 @@
|
|||||||
|
package metrics
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"supermarket/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CLV is customer lifetime value, and what it rests on. Amounts are in
|
||||||
|
// cents.
|
||||||
|
type CLV struct {
|
||||||
|
Month string // the last complete month it's measured on
|
||||||
|
ARPA float64 // MRR per paying customer
|
||||||
|
Margin float64 // percent, weighted by each product's revenue
|
||||||
|
Churn float64 // percent of customers lost a month, averaged over 12 months
|
||||||
|
ChurnMonths int // how many months the average covers
|
||||||
|
Lifetime float64 // months: 1 ÷ churn
|
||||||
|
Value float64 // ARPA × margin ÷ churn; -1 when churn is 0
|
||||||
|
CAC float64 // over the same 12 months; -1 without spend or new customers
|
||||||
|
Ratio float64 // CLV ÷ CAC; -1 when either is unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildCLV works CLV out from the MRR model, the margins and the spend log:
|
||||||
|
// the last complete month's ARPA, the revenue-weighted margin of the last
|
||||||
|
// 12 months, and the customer churn rate averaged over the last 12 complete
|
||||||
|
// months (customers lost ÷ customers at the start).
|
||||||
|
func BuildCLV(d *db.DB, m *Model, now time.Time) (*CLV, error) {
|
||||||
|
months := m.Months
|
||||||
|
if len(months) > 0 && months[len(months)-1].Partial {
|
||||||
|
months = months[:len(months)-1]
|
||||||
|
}
|
||||||
|
if len(months) < 2 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
last := months[len(months)-1]
|
||||||
|
c := &CLV{Month: last.Month, ARPA: last.ARPA(), Value: -1, CAC: -1, Ratio: -1}
|
||||||
|
products, err := Products(d, now)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rev := map[string]int64{}
|
||||||
|
for _, p := range products {
|
||||||
|
rev[p.ID] = p.Revenue
|
||||||
|
}
|
||||||
|
c.Margin = WeightedMargin(LoadMargins(d), rev)
|
||||||
|
var lost, base int
|
||||||
|
// Churn needs the month before, so it starts a month later than CAC.
|
||||||
|
for i := max(1, len(months)-12); i < len(months); i++ {
|
||||||
|
base += months[i-1].Customers
|
||||||
|
lost += months[i].ChurnCount
|
||||||
|
c.ChurnMonths++
|
||||||
|
}
|
||||||
|
from, newCount := max(0, len(months)-12), 0
|
||||||
|
for i := from; i < len(months); i++ {
|
||||||
|
newCount += months[i].NewCount
|
||||||
|
}
|
||||||
|
if base > 0 {
|
||||||
|
c.Churn = 100 * float64(lost) / float64(base)
|
||||||
|
}
|
||||||
|
if c.Churn > 0 {
|
||||||
|
c.Lifetime = 100 / c.Churn
|
||||||
|
c.Value = c.ARPA * c.Margin / 100 * c.Lifetime
|
||||||
|
}
|
||||||
|
var spend int64
|
||||||
|
if err := d.QueryRow(`SELECT coalesce(sum(amount_cents), 0) FROM spend WHERE month BETWEEN ? AND ?`,
|
||||||
|
months[from].Month, last.Month).Scan(&spend); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if spend > 0 && newCount > 0 {
|
||||||
|
c.CAC = float64(spend) / float64(newCount)
|
||||||
|
if c.Value > 0 {
|
||||||
|
c.Ratio = c.Value / c.CAC
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Revenue by cohort ---
|
||||||
|
|
||||||
|
// revenueEvent is money in (or out) for a customer at a time.
|
||||||
|
type revenueEvent struct {
|
||||||
|
customer string
|
||||||
|
at int64
|
||||||
|
cents int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// cashFlows are each customer's payments, net of refunds and of credit
|
||||||
|
// notes that gave money back without a refund: paid invoices' amount paid
|
||||||
|
// when paid, refunds that went through when made, and post-payment credit
|
||||||
|
// notes (less any part refunded, which is counted as a refund) when issued.
|
||||||
|
// Pre-payment credit notes already lowered the amount paid.
|
||||||
|
func cashFlows(d *db.DB, currency string) ([]revenueEvent, error) {
|
||||||
|
var out []revenueEvent
|
||||||
|
rows, err := d.Query(`SELECT customer, coalesce(json_extract(data, '$.status_transitions.paid_at'), created),
|
||||||
|
coalesce(json_extract(data, '$.amount_paid'), 0) FROM stripe_objects
|
||||||
|
WHERE kind = 'invoice' AND status = 'paid' AND currency = ? AND customer != ''`, currency)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for rows.Next() {
|
||||||
|
var e revenueEvent
|
||||||
|
if err := rows.Scan(&e.customer, &e.at, &e.cents); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if e.cents != 0 {
|
||||||
|
out = append(out, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
rows, err = d.Query(`SELECT customer, created, amount FROM stripe_objects
|
||||||
|
WHERE kind = 'refund' AND status = 'succeeded' AND currency = ? AND customer != ''`, currency)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for rows.Next() {
|
||||||
|
var e revenueEvent
|
||||||
|
if err := rows.Scan(&e.customer, &e.at, &e.cents); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
e.cents = -e.cents
|
||||||
|
out = append(out, e)
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
rows, err = d.Query(`SELECT customer, created, data FROM stripe_objects
|
||||||
|
WHERE kind = 'credit_note' AND status = 'issued' AND currency = ? AND customer != ''`, currency)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for rows.Next() {
|
||||||
|
var cust, raw string
|
||||||
|
var at int64
|
||||||
|
if err := rows.Scan(&cust, &at, &raw); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var cn struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
PostPaymentAmount int64 `json:"post_payment_amount"`
|
||||||
|
Refunds []struct {
|
||||||
|
AmountRefunded int64 `json:"amount_refunded"`
|
||||||
|
} `json:"refunds"`
|
||||||
|
RefundAmount int64 `json:"refund_amount"` // older API versions
|
||||||
|
Refund any `json:"refund"`
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal([]byte(raw), &cn)
|
||||||
|
credit := cn.PostPaymentAmount
|
||||||
|
for _, r := range cn.Refunds {
|
||||||
|
credit -= r.AmountRefunded
|
||||||
|
}
|
||||||
|
if cn.Refund != nil && len(cn.Refunds) == 0 {
|
||||||
|
credit = 0 // an older note tied to a refund: counted there
|
||||||
|
}
|
||||||
|
if credit > 0 {
|
||||||
|
out = append(out, revenueEvent{customer: cust, at: at, cents: -credit})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cell is one cohort month's figure; Known is false for months not
|
||||||
|
// reached yet. (Revenue can be negative, when refunds exceed payments.)
|
||||||
|
type Cell struct {
|
||||||
|
V float64
|
||||||
|
Known bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// CohortRevenue is what a signup cohort has paid: cumulative revenue per
|
||||||
|
// customer, k months after their first paid month.
|
||||||
|
type CohortRevenue struct {
|
||||||
|
Month string
|
||||||
|
Customers int
|
||||||
|
PerCustomer []Cell // cents, cumulative, for months 0, 1, 2…
|
||||||
|
Margin []Cell // the same, after gross margin
|
||||||
|
}
|
||||||
|
|
||||||
|
// RevenueByCohort follows the last n signup cohorts for up to span months:
|
||||||
|
// the money they paid, net of refunds and credits, cumulative and per
|
||||||
|
// customer, with the margin-weighted gross profit beside it.
|
||||||
|
func RevenueByCohort(d *db.DB, m *Model, n, span int, now time.Time) ([]CohortRevenue, error) {
|
||||||
|
flows, err := cashFlows(d, m.Currency)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
products, err := Products(d, now)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rev := map[string]int64{}
|
||||||
|
for _, p := range products {
|
||||||
|
rev[p.ID] = p.Revenue
|
||||||
|
}
|
||||||
|
margin := WeightedMargin(LoadMargins(d), rev) / 100
|
||||||
|
idx := map[string]int{}
|
||||||
|
for i, mo := range m.Months {
|
||||||
|
idx[mo.Month] = i
|
||||||
|
}
|
||||||
|
// Each customer's payments, by month index.
|
||||||
|
paid := map[string]map[int]int64{}
|
||||||
|
for _, f := range flows {
|
||||||
|
mon := time.Unix(f.at, 0).UTC().Format("2006-01")
|
||||||
|
i, ok := idx[mon]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if paid[f.customer] == nil {
|
||||||
|
paid[f.customer] = map[int]int64{}
|
||||||
|
}
|
||||||
|
paid[f.customer][i] += f.cents
|
||||||
|
}
|
||||||
|
members := map[string][]string{}
|
||||||
|
for c, first := range m.First {
|
||||||
|
members[first] = append(members[first], c)
|
||||||
|
}
|
||||||
|
var out []CohortRevenue
|
||||||
|
for i := len(m.Months) - 1; i >= 0 && len(out) < n; i-- {
|
||||||
|
cs := members[m.Months[i].Month]
|
||||||
|
if len(cs) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
co := CohortRevenue{Month: m.Months[i].Month, Customers: len(cs)}
|
||||||
|
var cum float64
|
||||||
|
for k := 0; k <= span; k++ {
|
||||||
|
if i+k >= len(m.Months) {
|
||||||
|
co.PerCustomer = append(co.PerCustomer, Cell{})
|
||||||
|
co.Margin = append(co.Margin, Cell{})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, c := range cs {
|
||||||
|
cum += float64(paid[c][i+k])
|
||||||
|
}
|
||||||
|
per := cum / float64(len(cs))
|
||||||
|
co.PerCustomer = append(co.PerCustomer, Cell{per, true})
|
||||||
|
co.Margin = append(co.Margin, Cell{per * margin, true})
|
||||||
|
}
|
||||||
|
out = append(out, co)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package metrics
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCLV(t *testing.T) {
|
||||||
|
d := openDB(t)
|
||||||
|
now := time.Date(2026, 7, 15, 0, 0, 0, 0, time.UTC)
|
||||||
|
// Ten customers at $100 from January; one leaves at the end of March,
|
||||||
|
// one at the end of May. Products: all "prod_core", at a 50% margin.
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
to := "2026-08"
|
||||||
|
switch i {
|
||||||
|
case 0:
|
||||||
|
to = "2026-03"
|
||||||
|
case 1:
|
||||||
|
to = "2026-05"
|
||||||
|
}
|
||||||
|
addLines(t, d, monthly(fmt.Sprintf("cus_%d", i), 10000, "2026-01", to)...)
|
||||||
|
}
|
||||||
|
d.Exec(`UPDATE stripe_invoice_lines SET product = 'prod_core'`)
|
||||||
|
SaveMargins(d, Margins{Default: 60, ByProduct: map[string]float64{"prod_core": 50}})
|
||||||
|
AddSpend(d, Spend{Month: "2026-01", Channel: "general", AmountCents: 300000}, now)
|
||||||
|
m, _ := Build(d, now)
|
||||||
|
c, err := BuildCLV(d, m, now)
|
||||||
|
if err != nil || c == nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Complete months: Jan–Jun. Churn: 2 lost over 5 month-starts of
|
||||||
|
// 10+10+9+9+8 customers = 2/46.
|
||||||
|
if c.Month != "2026-06" || c.ARPA != 10000 || c.Margin != 50 || c.ChurnMonths != 5 || !near(c.Churn*46, 200) {
|
||||||
|
t.Fatalf("clv: %+v", c)
|
||||||
|
}
|
||||||
|
// CLV = $100 × 50% × 23 months = $1,150; CAC = $3,000 ÷ 10 = $300.
|
||||||
|
if !near(c.Value, 115000) || !near(c.CAC, 30000) || c.Ratio < 3.83 || c.Ratio > 3.84 {
|
||||||
|
t.Errorf("value: %+v", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRevenueByCohort(t *testing.T) {
|
||||||
|
d := openDB(t)
|
||||||
|
now := time.Date(2026, 4, 15, 0, 0, 0, 0, time.UTC)
|
||||||
|
addLines(t, d, monthly("cus_a", 10000, "2026-01", "2026-05")...)
|
||||||
|
addLines(t, d, monthly("cus_b", 10000, "2026-01", "2026-05")...)
|
||||||
|
at := func(s string) int64 { return day(s) }
|
||||||
|
for _, inv := range []struct {
|
||||||
|
id, cust string
|
||||||
|
paid int64
|
||||||
|
when string
|
||||||
|
}{
|
||||||
|
{"p1", "cus_a", 10000, "2026-01-10"}, {"p2", "cus_a", 10000, "2026-02-10"}, {"p3", "cus_b", 10000, "2026-01-10"},
|
||||||
|
{"p4", "cus_b", 10000, "2026-02-10"}, {"p5", "cus_b", 10000, "2026-03-10"},
|
||||||
|
} {
|
||||||
|
d.Exec(`INSERT INTO stripe_objects (kind, id, customer, created, status, currency, data) VALUES ('invoice', ?, ?, ?, 'paid', 'usd', ?)`,
|
||||||
|
inv.id, inv.cust, at(inv.when), fmt.Sprintf(`{"amount_paid":%d,"status_transitions":{"paid_at":%d}}`, inv.paid, at(inv.when)))
|
||||||
|
}
|
||||||
|
// cus_b gets $40 back in February; a $20 post-payment credit in March,
|
||||||
|
// $5 of it refunded (counted as a refund); and a pre-payment note,
|
||||||
|
// which the amount paid already reflects.
|
||||||
|
d.Exec(`INSERT INTO stripe_objects (kind, id, customer, created, status, currency, amount, data) VALUES
|
||||||
|
('refund', 'r1', 'cus_b', ?, 'succeeded', 'usd', 4000, '{}'),
|
||||||
|
('refund', 'r2', 'cus_b', ?, 'canceled', 'usd', 9999, '{}'),
|
||||||
|
('credit_note', 'cn1', 'cus_b', ?, 'issued', 'usd', 2000, '{"type":"post_payment","post_payment_amount":2000,"refunds":[{"amount_refunded":500}]}'),
|
||||||
|
('credit_note', 'cn2', 'cus_a', ?, 'issued', 'usd', 3000, '{"type":"pre_payment","pre_payment_amount":3000,"post_payment_amount":0}')`,
|
||||||
|
at("2026-02-20"), at("2026-02-21"), at("2026-03-20"), at("2026-02-01"))
|
||||||
|
m, _ := Build(d, now)
|
||||||
|
cos, err := RevenueByCohort(d, m, 5, 4, now)
|
||||||
|
if err != nil || len(cos) != 1 {
|
||||||
|
t.Fatalf("cohorts: %+v %v", cos, err)
|
||||||
|
}
|
||||||
|
co := cos[0]
|
||||||
|
// Two customers, cumulative: Jan $200 → $100 each; Feb +$200 −$40 =
|
||||||
|
// $360 → $180; Mar +$100 −$15 = $445 → $222.50; Apr nothing → same.
|
||||||
|
want := []float64{10000, 18000, 22250, 22250}
|
||||||
|
for i, w := range want {
|
||||||
|
if c := co.PerCustomer[i]; !c.Known || !near(c.V, w) {
|
||||||
|
t.Errorf("month %d: %+v, want %.0f", i, c, w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if co.PerCustomer[4].Known {
|
||||||
|
t.Error("a month not reached yet is known")
|
||||||
|
}
|
||||||
|
if !near(co.Margin[1].V, 18000*0.6) {
|
||||||
|
t.Errorf("gross profit: %v", co.Margin[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNegativeCohortRevenueShows(t *testing.T) {
|
||||||
|
d := openDB(t)
|
||||||
|
now := time.Date(2026, 3, 15, 0, 0, 0, 0, time.UTC)
|
||||||
|
addLines(t, d, monthly("cus_r", 10000, "2026-01", "2026-02")...)
|
||||||
|
d.Exec(`INSERT INTO stripe_objects (kind, id, customer, created, status, currency, data) VALUES ('invoice', 'pr', 'cus_r', ?, 'paid', 'usd', '{"amount_paid":10000}')`, day("2026-01-10"))
|
||||||
|
d.Exec(`INSERT INTO stripe_objects (kind, id, customer, created, status, currency, amount, data) VALUES ('refund', 'rr', 'cus_r', ?, 'succeeded', 'usd', 15000, '{}')`, day("2026-02-01"))
|
||||||
|
m, _ := Build(d, now)
|
||||||
|
cos, _ := RevenueByCohort(d, m, 5, 2, now)
|
||||||
|
if len(cos) != 1 || !cos[0].PerCustomer[1].Known || cos[0].PerCustomer[1].V != -5000 {
|
||||||
|
t.Errorf("negative revenue: %+v", cos)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -400,3 +400,28 @@ func (s *Server) metricsSpendDelete(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
redirect(w, r, "/metrics/spend", "deleted")
|
redirect(w, r, "/metrics/spend", "deleted")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- CLV and cohorts ---
|
||||||
|
|
||||||
|
func (s *Server) metricsCLV(w http.ResponseWriter, r *http.Request) {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
cohorts, err := metrics.RevenueByCohort(s.DB, model, 18, 12, now)
|
||||||
|
if err != nil {
|
||||||
|
s.serverError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.render(w, r, "metrics-clv", page{Title: "CLV and cohorts", Nav: "metrics/clv", Data: map[string]any{
|
||||||
|
"CLV": clv, "Cohorts": cohorts, "Span": make([]int, 13), "Profit": r.URL.Query().Get("view") == "profit",
|
||||||
|
"Currency": model.Currency,
|
||||||
|
}})
|
||||||
|
}
|
||||||
|
|||||||
@@ -168,6 +168,7 @@ func (s *Server) Handler() (http.Handler, error) {
|
|||||||
mux.HandleFunc("GET /metrics/month/{month}", s.metricsMonth)
|
mux.HandleFunc("GET /metrics/month/{month}", s.metricsMonth)
|
||||||
mux.HandleFunc("GET /metrics/customers", s.metricsCustomers)
|
mux.HandleFunc("GET /metrics/customers", s.metricsCustomers)
|
||||||
mux.HandleFunc("GET /metrics/spend", s.metricsSpend)
|
mux.HandleFunc("GET /metrics/spend", s.metricsSpend)
|
||||||
|
mux.HandleFunc("GET /metrics/clv", s.metricsCLV)
|
||||||
mux.HandleFunc("POST /metrics/spend", s.metricsSpendAdd)
|
mux.HandleFunc("POST /metrics/spend", s.metricsSpendAdd)
|
||||||
mux.HandleFunc("POST /metrics/spend/{id}/delete", s.metricsSpendDelete)
|
mux.HandleFunc("POST /metrics/spend/{id}/delete", s.metricsSpendDelete)
|
||||||
mux.HandleFunc("POST /metrics/customers/{id}", s.metricsCustomerMatch)
|
mux.HandleFunc("POST /metrics/customers/{id}", s.metricsCustomerMatch)
|
||||||
@@ -326,6 +327,7 @@ func (s *Server) loadTemplates() error {
|
|||||||
return strconv.FormatFloat(f, 'f', 0, 64) + "%"
|
return strconv.FormatFloat(f, 'f', 0, 64) + "%"
|
||||||
},
|
},
|
||||||
"spendChannel": metrics.ChannelName,
|
"spendChannel": metrics.ChannelName,
|
||||||
|
"dec1f": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) },
|
||||||
"cents": func(f float64) string {
|
"cents": func(f float64) string {
|
||||||
if f < 0 {
|
if f < 0 {
|
||||||
return "·"
|
return "·"
|
||||||
|
|||||||
@@ -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",
|
"/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", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
|
||||||
"/content/scheduled", "/content/published",
|
"/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",
|
"/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",
|
||||||
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
|
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
|
||||||
rec := do(h, http.MethodGet, path, nil, nil)
|
rec := do(h, http.MethodGet, path, nil, nil)
|
||||||
if rec.Code != http.StatusOK {
|
if rec.Code != http.StatusOK {
|
||||||
|
|||||||
@@ -54,6 +54,7 @@
|
|||||||
<div class="subnav">
|
<div class="subnav">
|
||||||
<a href="/metrics" {{if eq $nav "metrics/overview"}}aria-current="page"{{end}}>MRR and NRR</a>
|
<a href="/metrics" {{if eq $nav "metrics/overview"}}aria-current="page"{{end}}>MRR and NRR</a>
|
||||||
<a href="/metrics/spend" {{if eq $nav "metrics/spend"}}aria-current="page"{{end}}>Spend and CAC</a>
|
<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/customers" {{if eq $nav "metrics/customers"}}aria-current="page"{{end}}>Customers and the CRM</a>
|
||||||
</div>
|
</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
{{define "content"}}{{with .Data}}{{$d := .}}
|
||||||
|
<div class="heading"><h1>CLV and cohorts</h1></div>
|
||||||
|
<p class="lede">What a customer is worth over their life with you, and what each signup cohort has actually paid. CLV is a projection from today's numbers; the cohort table is money that came in, net of refunds and credits.</p>
|
||||||
|
|
||||||
|
{{with .CLV}}
|
||||||
|
<section class="card">
|
||||||
|
<h2>Customer lifetime value <span class="muted small">measured on {{.Month}}</span></h2>
|
||||||
|
<div class="funnel">
|
||||||
|
<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, 12 months</span><strong>{{cents .CAC}}</strong></div>
|
||||||
|
<div class="step"><span class="label">CLV : CAC</span><strong>{{if ge .Ratio 0.0}}{{dec1f .Ratio}} : 1{{else}}·{{end}}</strong><span class="rate">3 : 1 or more is healthy</span></div>
|
||||||
|
<div class="step"><span class="label">Average per customer</span><strong>{{usd .ARPA}}</strong><span class="rate">a month</span></div>
|
||||||
|
<div class="step"><span class="label">Gross margin</span><strong>{{dec1f .Margin}}%</strong><span class="rate">weighted by product</span></div>
|
||||||
|
<div class="step"><span class="label">Churn</span><strong>{{dec1f .Churn}}%</strong><span class="rate">of customers a month, {{.ChurnMonths}}-month average</span></div>
|
||||||
|
<div class="step"><span class="label">Lifetime</span><strong>{{if .Lifetime}}{{dec1f .Lifetime}}{{else}}·{{end}}</strong><span class="rate">months, on average</span></div>
|
||||||
|
</div>
|
||||||
|
<p class="small muted">CLV = average MRR per customer × gross margin ÷ monthly churn. The margin weighs each product's margin (set on <a href="/metrics#margins">MRR and NRR</a>) by what it billed over 12 months. CAC is the spend logged over the same 12 months ÷ the new customers in them{{if lt .CAC 0.0}}: <a href="/metrics/spend">log your spend</a> to see it{{end}}.</p>
|
||||||
|
</section>
|
||||||
|
{{else}}
|
||||||
|
<section class="card empty"><p>CLV needs at least two complete months of billing from Stripe.</p></section>
|
||||||
|
{{end}}
|
||||||
|
|
||||||
|
{{if .Cohorts}}
|
||||||
|
<h2>Revenue by cohort</h2>
|
||||||
|
<p class="help">Customers by the month they first paid, and what they've paid since, per customer, cumulative: invoices paid, less refunds and credits. Month 0 is the month they first paid.</p>
|
||||||
|
<nav class="tabs">
|
||||||
|
<a href="/metrics/clv" {{if not .Profit}}aria-current="page"{{end}}>Revenue</a>
|
||||||
|
<a href="/metrics/clv?view=profit" {{if .Profit}}aria-current="page"{{end}}>Gross profit</a>
|
||||||
|
</nav>
|
||||||
|
<div class="table-wrap"><table class="list compact cohorts">
|
||||||
|
<thead><tr><th>First paid</th><th class="num">Customers</th>{{range $i, $_ := .Span}}<th class="num">{{$i}}</th>{{end}}</tr></thead>
|
||||||
|
<tbody>{{range .Cohorts}}<tr><td>{{.Month}}</td><td class="num">{{.Customers}}</td>
|
||||||
|
{{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>
|
||||||
|
{{end}}
|
||||||
|
{{end}}{{end}}
|
||||||
Reference in New Issue
Block a user