Metrics: total spend from Stripe's charges, as Stripe counts it

Customers who paid without an invoice (one-off Checkout payments) were
missed, and the Stripe card counted every customer record, deleted ones
too. The sync now reads charges (and follows their events); a customer's
total spend is their successful charges, captured less refunded. A
database synced before reads everything once (sync state version 2).
Until charges are in, paid invoices less refunds stand in.

The Stripe card's Customers now counts those who spent more than $0, "of
N in Stripe", and a Payments count is added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 12:35:00 -07:00
co-authored by Claude Opus 5.5
parent 6f2fbdf63a
commit 739f85fde1
7 changed files with 103 additions and 23 deletions
+2 -1
View File
@@ -227,7 +227,8 @@ var EventTypes = []string{
"customer.created", "customer.updated", "customer.deleted", "customer.created", "customer.updated", "customer.deleted",
"invoice.created", "invoice.finalized", "invoice.updated", "invoice.paid", "invoice.voided", "invoice.marked_uncollectible", "invoice.created", "invoice.finalized", "invoice.updated", "invoice.paid", "invoice.voided", "invoice.marked_uncollectible",
"credit_note.created", "credit_note.updated", "credit_note.voided", "credit_note.created", "credit_note.updated", "credit_note.voided",
"refund.created", "refund.updated", "charge.refunded", "refund.created", "refund.updated",
"charge.succeeded", "charge.captured", "charge.updated", "charge.refunded", "charge.failed",
} }
// Event is one change, with the object as it was after it. // Event is one change, with the object as it was after it.
+24 -11
View File
@@ -169,7 +169,7 @@ func Matches(d *db.DB, model *Model) ([]Match, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
paying, err := spenders(d) paying, err := Spenders(d)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -307,17 +307,27 @@ func MatchSummary(ms []Match) map[string]int {
return out return out
} }
// spenders are the customers whose total spend is above $0: what their // Spenders are the customers whose total spend is above $0, as Stripe's
// paid invoices charged (amount_paid, so $0 and fully discounted invoices // dashboard counts it: their successful payments (charges), less what was
// count as nothing), less what was refunded. Customers who only had a // refunded. Customers who only had a trial, or have only unpaid invoices,
// trial, or have only open invoices, aren't customers yet. // aren't customers yet. Until the charges are synced, paid invoices
func spenders(d *db.DB) (map[string]bool, error) { // (amount_paid) less refunds stand in.
func Spenders(d *db.DB) (map[string]bool, error) {
var charges int
if err := d.QueryRow(`SELECT count(*) FROM stripe_objects WHERE kind = ?`, KindCharge).Scan(&charges); err != nil {
return nil, err
}
type row struct { type row struct {
kind, customer, data string kind, customer, data string
amount int64 amount int64
} }
rows, err := d.Query(`SELECT kind, customer, amount, data FROM stripe_objects q := `SELECT kind, customer, amount, '' FROM stripe_objects
WHERE customer != '' AND ((kind = 'invoice' AND status = 'paid') OR (kind = 'refund' AND status IN ('succeeded', 'pending')))`) WHERE kind = 'charge' AND status = 'succeeded' AND customer != ''`
if charges == 0 {
q = `SELECT kind, customer, amount, data FROM stripe_objects
WHERE customer != '' AND ((kind = 'invoice' AND status = 'paid') OR (kind = 'refund' AND status IN ('succeeded', 'pending')))`
}
rows, err := d.Query(q)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -336,16 +346,19 @@ func spenders(d *db.DB) (map[string]bool, error) {
} }
spend := map[string]int64{} spend := map[string]int64{}
for _, r := range all { for _, r := range all {
if r.kind == KindRefund { switch r.kind {
case KindCharge:
spend[r.customer] += r.amount // captured, less refunded
case KindRefund:
spend[r.customer] -= r.amount spend[r.customer] -= r.amount
continue case KindInvoice:
}
var inv struct { var inv struct {
AmountPaid int64 `json:"amount_paid"` AmountPaid int64 `json:"amount_paid"`
} }
_ = json.Unmarshal([]byte(r.data), &inv) _ = json.Unmarshal([]byte(r.data), &inv)
spend[r.customer] += inv.AmountPaid spend[r.customer] += inv.AmountPaid
} }
}
out := map[string]bool{} out := map[string]bool{}
for c, v := range spend { for c, v := range spend {
if v > 0 { if v > 0 {
+23 -5
View File
@@ -21,6 +21,7 @@ const (
KindInvoice = "invoice" KindInvoice = "invoice"
KindCreditNote = "credit_note" KindCreditNote = "credit_note"
KindRefund = "refund" KindRefund = "refund"
KindCharge = "charge" // a payment: what total spend is counted from
KindProduct = "product" KindProduct = "product"
) )
@@ -31,8 +32,13 @@ const eventsKept = 29 * 24 * time.Hour
type syncState struct { type syncState struct {
Backfilled time.Time `json:"backfilled"` Backfilled time.Time `json:"backfilled"`
LastEvent int64 `json:"last_event"` // created time of the last event applied LastEvent int64 `json:"last_event"` // created time of the last event applied
Version int `json:"version"` // syncVersion when last backfilled
} }
// syncVersion goes up when a backfill reads a new kind of object (2:
// charges), so the next sync reads everything once.
const syncVersion = 2
const stateKey = "metrics:stripe-state" const stateKey = "metrics:stripe-state"
// SyncResult is what a sync did. // SyncResult is what a sync did.
@@ -78,7 +84,7 @@ func sync(ctx context.Context, d *db.DB, c *stripe.Client, now time.Time, forceF
if _, err := d.GetJSON(stateKey, &st); err != nil { if _, err := d.GetJSON(stateKey, &st); err != nil {
return err return err
} }
if forceFull || st.LastEvent == 0 || now.Sub(time.Unix(st.LastEvent, 0)) > eventsKept { if forceFull || st.LastEvent == 0 || st.Version < syncVersion || now.Sub(time.Unix(st.LastEvent, 0)) > eventsKept {
res.Full = true res.Full = true
// Events from the moment the backfill starts are applied next time, // Events from the moment the backfill starts are applied next time,
// so nothing falls between the two. // so nothing falls between the two.
@@ -91,6 +97,7 @@ func sync(ctx context.Context, d *db.DB, c *stripe.Client, now time.Time, forceF
{KindInvoice, "/v1/invoices", nil}, {KindInvoice, "/v1/invoices", nil},
{KindCreditNote, "/v1/credit_notes", nil}, {KindCreditNote, "/v1/credit_notes", nil},
{KindRefund, "/v1/refunds", url.Values{"expand[]": {"data.charge"}}}, {KindRefund, "/v1/refunds", url.Values{"expand[]": {"data.charge"}}},
{KindCharge, "/v1/charges", nil},
{KindProduct, "/v1/products", nil}, {KindProduct, "/v1/products", nil},
} { } {
raws, err := c.ListRaw(ctx, l.path, l.q, 0) raws, err := c.ListRaw(ctx, l.path, l.q, 0)
@@ -110,7 +117,7 @@ func sync(ctx context.Context, d *db.DB, c *stripe.Client, now time.Time, forceF
res.Counts[l.kind]++ res.Counts[l.kind]++
} }
} }
st = syncState{Backfilled: now, LastEvent: start.Unix()} st = syncState{Backfilled: now, LastEvent: start.Unix(), Version: syncVersion}
return d.PutJSON(stateKey, st) return d.PutJSON(stateKey, st)
} }
// Products change rarely and have no events followed: read them all. // Products change rarely and have no events followed: read them all.
@@ -157,7 +164,8 @@ func sync(ctx context.Context, d *db.DB, c *stripe.Client, now time.Time, forceF
obj = full obj = full
} }
case "charge": case "charge":
// charge.refunded: its refunds are what matter. kind = KindCharge
// charge.refunded: its refunds matter too.
for _, r := range head.Refunds.Data { for _, r := range head.Refunds.Data {
var rh struct { var rh struct {
ID string `json:"id"` ID string `json:"id"`
@@ -219,6 +227,15 @@ func store(ctx context.Context, d *db.DB, c *stripe.Client, kind string, raw jso
} }
_ = json.Unmarshal(o.Charge, &ch) _ = json.Unmarshal(o.Charge, &ch)
customer = stripe.IDOf(ch.Customer) customer = stripe.IDOf(ch.Customer)
case KindCharge:
// What the customer was charged and kept paying: captured, less
// refunded.
var ch struct {
AmountCaptured int64 `json:"amount_captured"`
AmountRefunded int64 `json:"amount_refunded"`
}
_ = json.Unmarshal(raw, &ch)
amount = ch.AmountCaptured - ch.AmountRefunded
case KindInvoice: case KindInvoice:
if o.Status == "draft" { if o.Status == "draft" {
return nil // not billed yet return nil // not billed yet
@@ -290,9 +307,10 @@ func currencies(d *db.DB) ([]string, error) {
return out, rows.Err() return out, rows.Err()
} }
// Counts are how many objects of each kind are stored. // Counts are how many objects of each kind are stored (deleted customers
// left out).
func Counts(d *db.DB) (map[string]int, error) { func Counts(d *db.DB) (map[string]int, error) {
rows, err := d.Query(`SELECT kind, count(*) FROM stripe_objects GROUP BY kind`) rows, err := d.Query(`SELECT kind, count(*) FROM stripe_objects WHERE status != 'deleted' GROUP BY kind`)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+41
View File
@@ -57,6 +57,12 @@ func fakeStripe(t *testing.T, events *string) *httptest.Server {
t.Errorf("refunds without their charge: %s", r.URL) t.Errorf("refunds without their charge: %s", r.URL)
} }
fmt.Fprint(w, `{"data":[{"id":"re_1","object":"refund","amount":2000,"currency":"usd","created":1760200000,"status":"succeeded","charge":{"id":"ch_1","customer":"cus_a"}}],"has_more":false}`) fmt.Fprint(w, `{"data":[{"id":"re_1","object":"refund","amount":2000,"currency":"usd","created":1760200000,"status":"succeeded","charge":{"id":"ch_1","customer":"cus_a"}}],"has_more":false}`)
case "/v1/charges":
fmt.Fprint(w, `{"data":[
{"id":"ch_1","object":"charge","customer":"cus_a","created":1760000000,"status":"succeeded","currency":"usd","amount":4500,"amount_captured":4500,"amount_refunded":2000},
{"id":"ch_3","object":"charge","customer":"cus_c","created":1760000000,"status":"succeeded","currency":"usd","amount":1000,"amount_captured":1000,"amount_refunded":0},
{"id":"ch_4","object":"charge","customer":"cus_d","created":1760000000,"status":"succeeded","currency":"usd","amount":800,"amount_captured":800,"amount_refunded":800},
{"id":"ch_5","object":"charge","customer":"cus_e","created":1760000000,"status":"failed","currency":"usd","amount":900,"amount_captured":0,"amount_refunded":0}],"has_more":false}`)
case "/v1/refunds/re_2": case "/v1/refunds/re_2":
fmt.Fprint(w, `{"id":"re_2","object":"refund","amount":300,"currency":"usd","created":1762000000,"status":"succeeded","charge":{"id":"ch_2","customer":"cus_b"}}`) fmt.Fprint(w, `{"id":"re_2","object":"refund","amount":300,"currency":"usd","created":1762000000,"status":"succeeded","charge":{"id":"ch_2","customer":"cus_b"}}`)
case "/v1/products": case "/v1/products":
@@ -113,6 +119,19 @@ func TestSync(t *testing.T) {
if sub != "sub_2" || cust != "cus_b" || !recurring { if sub != "sub_2" || cust != "cus_b" || !recurring {
t.Errorf("new line: %q %q %v", sub, cust, recurring) t.Errorf("new line: %q %q %v", sub, cust, recurring)
} }
// Total spend comes from the charges: cus_c paid without an invoice;
// cus_d was refunded in full; cus_e's payment failed; cus_b only has an
// open invoice.
sp, err := Spenders(d)
if err != nil {
t.Fatal(err)
}
if len(sp) != 2 || !sp["cus_a"] || !sp["cus_c"] {
t.Errorf("spenders: %v", sp)
}
if counts[KindCharge] != 4 {
t.Errorf("charges: %v", counts)
}
var refundCustomer string var refundCustomer string
d.QueryRow(`SELECT customer FROM stripe_objects WHERE kind = 'refund' AND id = 're_1'`).Scan(&refundCustomer) d.QueryRow(`SELECT customer FROM stripe_objects WHERE kind = 'refund' AND id = 're_1'`).Scan(&refundCustomer)
if refundCustomer != "cus_a" { if refundCustomer != "cus_a" {
@@ -163,3 +182,25 @@ func TestSync(t *testing.T) {
t.Errorf("without products: %+v %v", res, err) t.Errorf("without products: %+v %v", res, err)
} }
} }
// A database synced before charges were read gets one full read, then
// goes back to events.
func TestSyncReadsChargesOnce(t *testing.T) {
d := openDB(t)
events := `{"data":[],"has_more":false}`
srv := fakeStripe(t, &events)
defer srv.Close()
c := stripe.New("rk_test").WithBase(srv.URL)
now := time.Unix(1762100000, 0)
if err := d.PutJSON(stateKey, syncState{Backfilled: now.Add(-time.Hour), LastEvent: now.Add(-time.Hour).Unix()}); err != nil {
t.Fatal(err)
}
res, err := Sync(context.Background(), d, c, now, false)
if err != nil || !res.Full || res.Counts[KindCharge] != 4 {
t.Fatalf("first sync: %+v %v", res, err)
}
res, err = Sync(context.Background(), d, c, now.Add(time.Hour), false)
if err != nil || res.Full {
t.Fatalf("second sync: %+v %v", res, err)
}
}
+6
View File
@@ -37,10 +37,16 @@ func (s *Server) renderMetrics(w http.ResponseWriter, r *http.Request, errMsg st
s.serverError(w, err) s.serverError(w, err)
return return
} }
spenders, err := metrics.Spenders(s.DB)
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "metrics", page{Title: "Metrics", Nav: "metrics/overview", Error: errMsg, Data: map[string]any{ s.render(w, r, "metrics", page{Title: "Metrics", Nav: "metrics/overview", Error: errMsg, Data: map[string]any{
"Stripe": s.stripe() != nil, "Stripe": s.stripe() != nil,
"Last": metrics.LastSync(s.DB), "Last": metrics.LastSync(s.DB),
"Counts": counts, "Counts": counts,
"Spenders": len(spenders),
"Products": products, "Products": products,
"Margins": metrics.LoadMargins(s.DB), "Margins": metrics.LoadMargins(s.DB),
"Model": model, "Model": model,
@@ -1,6 +1,6 @@
{{define "content"}}{{with .Data}}{{$d := .}} {{define "content"}}{{with .Data}}{{$d := .}}
<div class="heading"><h1>Customers and the CRM</h1></div> <div class="heading"><h1>Customers and the CRM</h1></div>
<p class="lede">Each Stripe customer who has spent more than $0 (paid invoices, less refunds; trials and unpaid invoices don't count), matched to its EspoCRM Account: first by a stored ID (a Stripe customer ID in the Account, or an EspoCRM ID in Stripe's metadata), then by email (the Account's, or one of its Contacts'), then by the email's domain (free mail like Gmail doesn't count). Fix what it gets wrong; your choice is kept. Pipeline influence and per-account numbers build on this.</p> <p class="lede">Each Stripe customer who has spent more than $0 (their payments, less refunds, as Stripe counts total spend; trials and unpaid invoices don't count), matched to its EspoCRM Account: first by a stored ID (a Stripe customer ID in the Account, or an EspoCRM ID in Stripe's metadata), then by email (the Account's, or one of its Contacts'), then by the email's domain (free mail like Gmail doesn't count). Fix what it gets wrong; your choice is kept. Pipeline influence and per-account numbers build on this.</p>
<section class="card"> <section class="card">
{{if not .CRMCount}} {{if not .CRMCount}}
+2 -1
View File
@@ -85,7 +85,8 @@
<p class="small {{if .Error}}error-text{{else}}muted{{end}}">Synced {{ago .At}}{{if .Full}} (everything read){{else}} ({{.Events}} changes since the last sync){{end}}{{with .Error}}: {{.}}{{end}}.{{with .Currency}} Currencies: {{range $i, $c := .}}{{if $i}}, {{end}}{{$c}}{{end}}.{{end}}</p> <p class="small {{if .Error}}error-text{{else}}muted{{end}}">Synced {{ago .At}}{{if .Full}} (everything read){{else}} ({{.Events}} changes since the last sync){{end}}{{with .Error}}: {{.}}{{end}}.{{with .Currency}} Currencies: {{range $i, $c := .}}{{if $i}}, {{end}}{{$c}}{{end}}.{{end}}</p>
{{else}}<p class="help">Not synced yet: the first sync reads all your Stripe history, which can take a few minutes.</p>{{end}} {{else}}<p class="help">Not synced yet: the first sync reads all your Stripe history, which can take a few minutes.</p>{{end}}
<div class="funnel"> <div class="funnel">
<div class="step"><span class="label">Customers</span><strong>{{num (or (index .Counts "customer") 0)}}</strong></div> <div class="step"><span class="label">Customers</span><strong>{{num .Spenders}}</strong><span class="rate">spent more than $0, of {{num (or (index .Counts "customer") 0)}} in Stripe</span></div>
<div class="step"><span class="label">Payments</span><strong>{{num (or (index .Counts "charge") 0)}}</strong></div>
<div class="step"><span class="label">Invoices</span><strong>{{num (or (index .Counts "invoice") 0)}}</strong></div> <div class="step"><span class="label">Invoices</span><strong>{{num (or (index .Counts "invoice") 0)}}</strong></div>
<div class="step"><span class="label">Credit notes</span><strong>{{num (or (index .Counts "credit_note") 0)}}</strong></div> <div class="step"><span class="label">Credit notes</span><strong>{{num (or (index .Counts "credit_note") 0)}}</strong></div>
<div class="step"><span class="label">Refunds</span><strong>{{num (or (index .Counts "refund") 0)}}</strong></div> <div class="step"><span class="label">Refunds</span><strong>{{num (or (index .Counts "refund") 0)}}</strong></div>