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:
@@ -169,7 +169,7 @@ func Matches(d *db.DB, model *Model) ([]Match, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
paying, err := spenders(d)
|
||||
paying, err := Spenders(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -307,17 +307,27 @@ func MatchSummary(ms []Match) map[string]int {
|
||||
return out
|
||||
}
|
||||
|
||||
// spenders are the customers whose total spend is above $0: what their
|
||||
// paid invoices charged (amount_paid, so $0 and fully discounted invoices
|
||||
// count as nothing), less what was refunded. Customers who only had a
|
||||
// trial, or have only open invoices, aren't customers yet.
|
||||
func spenders(d *db.DB) (map[string]bool, error) {
|
||||
// Spenders are the customers whose total spend is above $0, as Stripe's
|
||||
// dashboard counts it: their successful payments (charges), less what was
|
||||
// refunded. Customers who only had a trial, or have only unpaid invoices,
|
||||
// aren't customers yet. Until the charges are synced, paid invoices
|
||||
// (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 {
|
||||
kind, customer, data string
|
||||
amount int64
|
||||
}
|
||||
rows, err := d.Query(`SELECT kind, customer, amount, data FROM stripe_objects
|
||||
WHERE customer != '' AND ((kind = 'invoice' AND status = 'paid') OR (kind = 'refund' AND status IN ('succeeded', 'pending')))`)
|
||||
q := `SELECT kind, customer, amount, '' FROM stripe_objects
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
@@ -336,15 +346,18 @@ func spenders(d *db.DB) (map[string]bool, error) {
|
||||
}
|
||||
spend := map[string]int64{}
|
||||
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
|
||||
continue
|
||||
case KindInvoice:
|
||||
var inv struct {
|
||||
AmountPaid int64 `json:"amount_paid"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(r.data), &inv)
|
||||
spend[r.customer] += inv.AmountPaid
|
||||
}
|
||||
var inv struct {
|
||||
AmountPaid int64 `json:"amount_paid"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(r.data), &inv)
|
||||
spend[r.customer] += inv.AmountPaid
|
||||
}
|
||||
out := map[string]bool{}
|
||||
for c, v := range spend {
|
||||
|
||||
@@ -21,6 +21,7 @@ const (
|
||||
KindInvoice = "invoice"
|
||||
KindCreditNote = "credit_note"
|
||||
KindRefund = "refund"
|
||||
KindCharge = "charge" // a payment: what total spend is counted from
|
||||
KindProduct = "product"
|
||||
)
|
||||
|
||||
@@ -31,8 +32,13 @@ const eventsKept = 29 * 24 * time.Hour
|
||||
type syncState struct {
|
||||
Backfilled time.Time `json:"backfilled"`
|
||||
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"
|
||||
|
||||
// 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 {
|
||||
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
|
||||
// Events from the moment the backfill starts are applied next time,
|
||||
// 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},
|
||||
{KindCreditNote, "/v1/credit_notes", nil},
|
||||
{KindRefund, "/v1/refunds", url.Values{"expand[]": {"data.charge"}}},
|
||||
{KindCharge, "/v1/charges", nil},
|
||||
{KindProduct, "/v1/products", nil},
|
||||
} {
|
||||
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]++
|
||||
}
|
||||
}
|
||||
st = syncState{Backfilled: now, LastEvent: start.Unix()}
|
||||
st = syncState{Backfilled: now, LastEvent: start.Unix(), Version: syncVersion}
|
||||
return d.PutJSON(stateKey, st)
|
||||
}
|
||||
// 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
|
||||
}
|
||||
case "charge":
|
||||
// charge.refunded: its refunds are what matter.
|
||||
kind = KindCharge
|
||||
// charge.refunded: its refunds matter too.
|
||||
for _, r := range head.Refunds.Data {
|
||||
var rh struct {
|
||||
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)
|
||||
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:
|
||||
if o.Status == "draft" {
|
||||
return nil // not billed yet
|
||||
@@ -290,9 +307,10 @@ func currencies(d *db.DB) ([]string, error) {
|
||||
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) {
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -57,6 +57,12 @@ func fakeStripe(t *testing.T, events *string) *httptest.Server {
|
||||
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}`)
|
||||
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":
|
||||
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":
|
||||
@@ -113,6 +119,19 @@ func TestSync(t *testing.T) {
|
||||
if sub != "sub_2" || cust != "cus_b" || !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
|
||||
d.QueryRow(`SELECT customer FROM stripe_objects WHERE kind = 'refund' AND id = 're_1'`).Scan(&refundCustomer)
|
||||
if refundCustomer != "cus_a" {
|
||||
@@ -163,3 +182,25 @@ func TestSync(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user