Files
davidandClaude Opus 5.5 739f85fde1 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>
2026-11-30 12:35:00 -07:00

207 lines
9.0 KiB
Go

package metrics
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"supermarket/internal/api/stripe"
"supermarket/internal/db"
)
func openDB(t *testing.T) *db.DB {
t.Helper()
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
return d
}
// An invoice in the older line shape, and one in the 2025 shape with more
// lines than fit in the embedded list.
const (
oldInvoice = `{"id":"in_1","object":"invoice","customer":"cus_a","created":1760000000,"status":"paid","currency":"usd","total":4500,
"lines":{"has_more":false,"data":[{"id":"il_1","amount":5000,"currency":"usd","period":{"start":1760000000,"end":1762678400},
"quantity":5,"proration":false,"type":"subscription","subscription":"sub_1",
"price":{"id":"price_m","product":"prod_x","recurring":{"interval":"month","interval_count":1}},
"discount_amounts":[{"amount":500}]}]}}`
newInvoice = `{"id":"in_2","object":"invoice","customer":"cus_b","created":1761000000,"status":"open","currency":"usd","total":120000,
"lines":{"has_more":true,"data":[]}}`
newLines = `{"data":[{"id":"il_2","object":"line_item","amount":120000,"currency":"usd","period":{"start":1761000000,"end":1792536000},
"pricing":{"price_details":{"price":"price_y","product":"prod_x"}},
"parent":{"type":"subscription_item_details","subscription_item_details":{"subscription":"sub_2","proration":false}}}],"has_more":false}`
)
var noProducts bool
func fakeStripe(t *testing.T, events *string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/v1/customers":
fmt.Fprint(w, `{"data":[{"id":"cus_a","object":"customer","created":1750000000,"email":"a@x.example"},{"id":"cus_b","object":"customer","created":1750000001}],"has_more":false}`)
case "/v1/invoices":
fmt.Fprintf(w, `{"data":[%s,%s,{"id":"in_draft","object":"invoice","customer":"cus_a","status":"draft","lines":{"data":[]}}],"has_more":false}`, oldInvoice, newInvoice)
case "/v1/invoices/in_2/lines":
fmt.Fprint(w, newLines)
case "/v1/credit_notes":
fmt.Fprint(w, `{"data":[{"id":"cn_1","object":"credit_note","customer":"cus_a","created":1760100000,"status":"issued","currency":"usd","total":1000}],"has_more":false}`)
case "/v1/refunds":
if r.URL.Query().Get("expand[]") != "data.charge" {
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":
if noProducts {
w.WriteHeader(http.StatusForbidden)
fmt.Fprint(w, `{"error":{"message":"The provided key does not have the required permissions"}}`)
return
}
fmt.Fprint(w, `{"data":[{"id":"prod_x","object":"product","name":"Federated Core","created":1700000000}],"has_more":false}`)
case "/v1/events":
if len(r.URL.Query()["types[]"]) != len(stripe.EventTypes) {
t.Errorf("event types: %v", r.URL.Query()["types[]"])
}
fmt.Fprint(w, *events)
default:
t.Errorf("unexpected %s", r.URL)
http.NotFound(w, r)
}
}))
}
func TestSync(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)
ctx := context.Background()
now := time.Unix(1762100000, 0)
res, err := Sync(ctx, d, c, now, false)
if err != nil {
t.Fatal(err)
}
if !res.Full || res.Counts[KindCustomer] != 2 || res.Counts[KindInvoice] != 3 || res.Counts[KindRefund] != 1 || strings.Join(res.Currency, ",") != "usd" {
t.Fatalf("backfill: %+v", res)
}
counts, _ := Counts(d)
if counts[KindProduct] != 1 {
t.Errorf("products: %v", counts)
}
if counts[KindInvoice] != 2 {
t.Errorf("a draft invoice was kept: %v", counts)
}
var amount, start, end int64
var interval string
d.QueryRow(`SELECT amount, period_start, period_end, interval FROM stripe_invoice_lines WHERE id = 'il_1'`).Scan(&amount, &start, &end, &interval)
if amount != 4500 || interval != "month" || end-start != 2678400 {
t.Errorf("old line: %d %s %d", amount, interval, end-start)
}
var sub, cust string
var recurring bool
d.QueryRow(`SELECT subscription, customer, recurring FROM stripe_invoice_lines WHERE id = 'il_2'`).Scan(&sub, &cust, &recurring)
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" {
t.Errorf("refund's customer: %q", refundCustomer)
}
// Then events: the open invoice is paid, a customer is deleted, a charge
// is refunded.
paid := strings.Replace(strings.Replace(newInvoice, `"status":"open"`, `"status":"paid"`, 1), `"has_more":true`, `"has_more":false`, 1)
paid = strings.Replace(paid, `"data":[]`, `"data":[{"id":"il_2","amount":120000,"currency":"usd","period":{"start":1761000000,"end":1792536000},"type":"subscription","subscription":"sub_2","price":{"id":"price_y","product":"prod_x","recurring":{"interval":"year","interval_count":1}}}]`, 1)
events = fmt.Sprintf(`{"data":[
{"id":"evt_3","type":"charge.refunded","created":1762300000,"data":{"object":{"id":"ch_2","object":"charge","refunds":{"data":[{"id":"re_2"}]}}}},
{"id":"evt_2","type":"customer.deleted","created":1762200000,"data":{"object":{"id":"cus_a","object":"customer","deleted":true}}},
{"id":"evt_1","type":"invoice.paid","created":1762150000,"data":{"object":%s}}],"has_more":false}`, paid)
res, err = Sync(ctx, d, c, now.Add(time.Hour), false)
if err != nil {
t.Fatal(err)
}
if res.Full || res.Events != 3 {
t.Fatalf("events: %+v", res)
}
var status string
d.QueryRow(`SELECT status FROM stripe_objects WHERE kind = 'invoice' AND id = 'in_2'`).Scan(&status)
d.QueryRow(`SELECT interval FROM stripe_invoice_lines WHERE id = 'il_2'`).Scan(&interval)
if status != "paid" || interval != "year" {
t.Errorf("paid invoice: %q %q", status, interval)
}
d.QueryRow(`SELECT status FROM stripe_objects WHERE kind = 'customer' AND id = 'cus_a'`).Scan(&status)
if status != "deleted" {
t.Errorf("deleted customer: %q", status)
}
if counts, _ := Counts(d); counts[KindRefund] != 2 {
t.Errorf("refund from charge.refunded: %v", counts)
}
// A month later the events are gone: everything is read again.
events = `{"data":[],"has_more":false}`
if res, _ := Sync(ctx, d, c, now.AddDate(0, 0, 40), false); !res.Full {
t.Error("an old watermark didn't trigger a backfill")
}
if LastSync(d) == nil {
t.Error("the result isn't kept")
}
// A key without Products access still syncs, and says so.
noProducts = true
defer func() { noProducts = false }()
res, err = Sync(ctx, d, c, now.AddDate(0, 0, 80), true)
if err != nil || len(res.Notes) != 1 || !strings.Contains(res.Notes[0], "can't read Products") {
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)
}
}