db.DB wraps database/sql for either database. The SQL stays SQLite's: on Postgres each statement's ? become $n and LIKE ignores case as SQLite's does, and the Postgres schema (postgres.sql, schema 29 as a whole) adds SQLite's instr, json_extract and two-argument max/min, and a nocase ICU collation. Needs Postgres 18. LastInsertId became db.Insert (RETURNING id), INSERT OR IGNORE became ON CONFLICT DO NOTHING, upserts qualify their columns, and three queries group by every column they use. SUPERMARKET_TEST_POSTGRES runs the test suite on Postgres, a new schema per test; all tests pass on both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
243 lines
7.2 KiB
Go
243 lines
7.2 KiB
Go
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(CAST(json_extract(data, '$.status_transitions.paid_at') AS BIGINT), created),
|
||
coalesce(CAST(json_extract(data, '$.amount_paid') AS BIGINT), 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
|
||
}
|