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>
329 lines
9.7 KiB
Go
329 lines
9.7 KiB
Go
// Package metrics turns the company's Stripe data into the numbers a
|
|
// subscription business runs on: MRR and its movements, NRR, CAC, CLV and
|
|
// cohorts. Every number is computed here from the synced data; nothing is
|
|
// estimated.
|
|
package metrics
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/url"
|
|
"time"
|
|
|
|
"supermarket/internal/api/stripe"
|
|
"supermarket/internal/db"
|
|
)
|
|
|
|
// Kinds of Stripe object kept.
|
|
const (
|
|
KindCustomer = "customer"
|
|
KindInvoice = "invoice"
|
|
KindCreditNote = "credit_note"
|
|
KindRefund = "refund"
|
|
KindCharge = "charge" // a payment: what total spend is counted from
|
|
KindProduct = "product"
|
|
)
|
|
|
|
// eventsKept is how long Stripe keeps events; a watermark older than this
|
|
// needs a new backfill.
|
|
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.
|
|
type SyncResult struct {
|
|
At time.Time `json:"at"`
|
|
Full bool `json:"full"` // a backfill, not just events
|
|
Events int `json:"events"` // events applied
|
|
Counts map[string]int `json:"counts"` // objects stored, by kind
|
|
Error string `json:"error,omitempty"`
|
|
Currency []string `json:"currency"` // the currencies seen
|
|
Notes []string `json:"notes,omitempty"`
|
|
}
|
|
|
|
const resultKey = "metrics:stripe-last"
|
|
|
|
// LastSync is the last sync's result, or nil.
|
|
func LastSync(d *db.DB) *SyncResult {
|
|
var r SyncResult
|
|
if ok, _ := d.GetJSON(resultKey, &r); !ok {
|
|
return nil
|
|
}
|
|
return &r
|
|
}
|
|
|
|
// Sync brings the Stripe data up to date: a full backfill the first time
|
|
// (or when the events since the last sync are no longer kept), then the
|
|
// events since the last one.
|
|
func Sync(ctx context.Context, d *db.DB, c *stripe.Client, now time.Time, forceFull bool) (*SyncResult, error) {
|
|
res := &SyncResult{At: now, Counts: map[string]int{}}
|
|
err := sync(ctx, d, c, now, forceFull, res)
|
|
if err != nil {
|
|
res.Error = err.Error()
|
|
}
|
|
res.Currency, _ = currencies(d)
|
|
if perr := d.PutJSON(resultKey, res); perr != nil && err == nil {
|
|
err = perr
|
|
}
|
|
return res, err
|
|
}
|
|
|
|
func sync(ctx context.Context, d *db.DB, c *stripe.Client, now time.Time, forceFull bool, res *SyncResult) error {
|
|
var st syncState
|
|
if _, err := d.GetJSON(stateKey, &st); err != nil {
|
|
return err
|
|
}
|
|
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.
|
|
start := now.Add(-time.Minute)
|
|
for _, l := range []struct {
|
|
kind, path string
|
|
q url.Values
|
|
}{
|
|
{KindCustomer, "/v1/customers", nil},
|
|
{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)
|
|
if err != nil && l.kind == KindProduct {
|
|
// Optional: without Products access, names come from the
|
|
// invoice lines.
|
|
res.Notes = append(res.Notes, "Product names come from invoice lines: the key can't read Products ("+err.Error()+").")
|
|
continue
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("reading %ss: %w", l.kind, err)
|
|
}
|
|
for _, r := range raws {
|
|
if err := store(ctx, d, c, l.kind, r.JSON); err != nil {
|
|
return err
|
|
}
|
|
res.Counts[l.kind]++
|
|
}
|
|
}
|
|
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.
|
|
if raws, err := c.ListRaw(ctx, "/v1/products", nil, 0); err == nil {
|
|
for _, r := range raws {
|
|
if err := store(ctx, d, c, KindProduct, r.JSON); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
events, err := c.Events(ctx, time.Unix(st.LastEvent, 0))
|
|
if err != nil {
|
|
return fmt.Errorf("reading events: %w", err)
|
|
}
|
|
for _, e := range events {
|
|
kind, obj := "", e.Data.Object
|
|
var head struct {
|
|
Object string `json:"object"`
|
|
ID string `json:"id"`
|
|
Refunds struct {
|
|
Data []json.RawMessage `json:"data"`
|
|
} `json:"refunds"`
|
|
}
|
|
_ = json.Unmarshal(obj, &head)
|
|
switch head.Object {
|
|
case "customer":
|
|
kind = KindCustomer
|
|
if e.Type == "customer.deleted" {
|
|
if _, err := d.Exec(`UPDATE stripe_objects SET status = 'deleted' WHERE kind = ? AND id = ?`, KindCustomer, head.ID); err != nil {
|
|
return err
|
|
}
|
|
st.LastEvent = e.Created
|
|
res.Events++
|
|
continue
|
|
}
|
|
case "invoice":
|
|
kind = KindInvoice
|
|
case "credit_note":
|
|
kind = KindCreditNote
|
|
case "refund":
|
|
kind = KindRefund
|
|
// Read it again with its charge, for the customer.
|
|
if full, err := c.GetRaw(ctx, "/v1/refunds/"+url.PathEscape(head.ID), url.Values{"expand[]": {"charge"}}); err == nil {
|
|
obj = full
|
|
}
|
|
case "charge":
|
|
kind = KindCharge
|
|
// charge.refunded: its refunds matter too.
|
|
for _, r := range head.Refunds.Data {
|
|
var rh struct {
|
|
ID string `json:"id"`
|
|
}
|
|
_ = json.Unmarshal(r, &rh)
|
|
full, err := c.GetRaw(ctx, "/v1/refunds/"+url.PathEscape(rh.ID), url.Values{"expand[]": {"charge"}})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := store(ctx, d, c, KindRefund, full); err != nil {
|
|
return err
|
|
}
|
|
res.Counts[KindRefund]++
|
|
}
|
|
}
|
|
if kind != "" {
|
|
if err := store(ctx, d, c, kind, obj); err != nil {
|
|
return err
|
|
}
|
|
res.Counts[kind]++
|
|
}
|
|
st.LastEvent = e.Created
|
|
res.Events++
|
|
}
|
|
return d.PutJSON(stateKey, st)
|
|
}
|
|
|
|
// store keeps one object, and an invoice's lines.
|
|
func store(ctx context.Context, d *db.DB, c *stripe.Client, kind string, raw json.RawMessage) error {
|
|
var o struct {
|
|
ID string `json:"id"`
|
|
Customer json.RawMessage `json:"customer"`
|
|
Created int64 `json:"created"`
|
|
Status string `json:"status"`
|
|
Currency string `json:"currency"`
|
|
Total int64 `json:"total"`
|
|
Amount int64 `json:"amount"`
|
|
Deleted bool `json:"deleted"`
|
|
Charge json.RawMessage `json:"charge"`
|
|
Lines struct {
|
|
Data []json.RawMessage `json:"data"`
|
|
HasMore bool `json:"has_more"`
|
|
} `json:"lines"`
|
|
}
|
|
if err := json.Unmarshal(raw, &o); err != nil {
|
|
return err
|
|
}
|
|
customer, amount := stripe.IDOf(o.Customer), o.Total
|
|
switch kind {
|
|
case KindCustomer:
|
|
customer = o.ID
|
|
if o.Deleted {
|
|
o.Status = "deleted"
|
|
}
|
|
case KindRefund:
|
|
amount = o.Amount
|
|
var ch struct {
|
|
Customer json.RawMessage `json:"customer"`
|
|
}
|
|
_ = 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
|
|
}
|
|
}
|
|
if _, err := d.Exec(`INSERT INTO stripe_objects (kind, id, customer, created, status, currency, amount, data) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT (kind, id) DO UPDATE SET customer = excluded.customer, created = excluded.created, status = excluded.status,
|
|
currency = excluded.currency, amount = excluded.amount, data = excluded.data`,
|
|
kind, o.ID, customer, o.Created, o.Status, o.Currency, amount, string(raw)); err != nil {
|
|
return err
|
|
}
|
|
if kind != KindInvoice {
|
|
return nil
|
|
}
|
|
lines := o.Lines.Data
|
|
if o.Lines.HasMore {
|
|
all, err := c.InvoiceLines(ctx, o.ID)
|
|
if err != nil {
|
|
return fmt.Errorf("reading %s's lines: %w", o.ID, err)
|
|
}
|
|
lines = all
|
|
}
|
|
tx, err := d.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
if _, err := tx.Exec(`DELETE FROM stripe_invoice_lines WHERE invoice = ?`, o.ID); err != nil {
|
|
return err
|
|
}
|
|
for _, raw := range lines {
|
|
l, err := stripe.ParseLine(raw)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := tx.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, customer, status, currency, amount, period_start, period_end,
|
|
subscription, price, product, interval, interval_count, quantity, proration, recurring, description)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, o.ID, l.ID, customer, o.Status, or(l.Currency, o.Currency), l.Amount,
|
|
l.PeriodStart, l.PeriodEnd, l.Subscription, l.Price, l.Product, l.Interval, l.IntervalCount, l.Quantity, l.Proration, l.Recurring,
|
|
l.Description); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
|
|
func or(a, b string) string {
|
|
if a != "" {
|
|
return a
|
|
}
|
|
return b
|
|
}
|
|
|
|
// currencies are the currencies in the invoices, most used first.
|
|
func currencies(d *db.DB) ([]string, error) {
|
|
rows, err := d.Query(`SELECT currency FROM stripe_objects WHERE kind = 'invoice' AND currency != '' GROUP BY currency ORDER BY count(*) DESC`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []string
|
|
for rows.Next() {
|
|
var c string
|
|
if err := rows.Scan(&c); err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, c)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// 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 WHERE status != 'deleted' GROUP BY kind`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := map[string]int{}
|
|
for rows.Next() {
|
|
var k string
|
|
var n int
|
|
if err := rows.Scan(&k, &n); err != nil {
|
|
return nil, err
|
|
}
|
|
out[k] = n
|
|
}
|
|
return out, rows.Err()
|
|
}
|