diff --git a/internal/api/stripe/client.go b/internal/api/stripe/client.go index a7889e4..14762d0 100644 --- a/internal/api/stripe/client.go +++ b/internal/api/stripe/client.go @@ -227,7 +227,8 @@ var EventTypes = []string{ "customer.created", "customer.updated", "customer.deleted", "invoice.created", "invoice.finalized", "invoice.updated", "invoice.paid", "invoice.voided", "invoice.marked_uncollectible", "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. diff --git a/internal/metrics/crmmatch.go b/internal/metrics/crmmatch.go index 3c91011..8f53d53 100644 --- a/internal/metrics/crmmatch.go +++ b/internal/metrics/crmmatch.go @@ -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 { diff --git a/internal/metrics/sync.go b/internal/metrics/sync.go index d363570..57df112 100644 --- a/internal/metrics/sync.go +++ b/internal/metrics/sync.go @@ -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 } diff --git a/internal/metrics/sync_test.go b/internal/metrics/sync_test.go index 38ea697..3ac3b58 100644 --- a/internal/metrics/sync_test.go +++ b/internal/metrics/sync_test.go @@ -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) + } +} diff --git a/internal/web/metrics.go b/internal/web/metrics.go index 1133ecb..ff90eee 100644 --- a/internal/web/metrics.go +++ b/internal/web/metrics.go @@ -37,10 +37,16 @@ func (s *Server) renderMetrics(w http.ResponseWriter, r *http.Request, errMsg st s.serverError(w, err) 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{ "Stripe": s.stripe() != nil, "Last": metrics.LastSync(s.DB), "Counts": counts, + "Spenders": len(spenders), "Products": products, "Margins": metrics.LoadMargins(s.DB), "Model": model, diff --git a/internal/web/templates/metrics-customers.html b/internal/web/templates/metrics-customers.html index 28c29b0..bcd5f11 100644 --- a/internal/web/templates/metrics-customers.html +++ b/internal/web/templates/metrics-customers.html @@ -1,6 +1,6 @@ {{define "content"}}{{with .Data}}{{$d := .}}
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.
+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.
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}}
{{else}}Not synced yet: the first sync reads all your Stripe history, which can take a few minutes.
{{end}}