Phase 4 part 1: the full Stripe sync, and margins per product
Customers, invoices with all their lines (both of Stripe's line shapes), credit notes, refunds (with their customer) and products: a backfill, then the Events API every hour, and a new backfill when events have expired. Metrics page with sync status. Gross margin per product: a default (60%) and overrides, with names from Stripe's products or the invoice lines. Schemas 18 and 19. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,160 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// DefaultMargin is the gross margin used for products without their own,
|
||||
// in percent (the user's figure, 2026-11-22).
|
||||
const DefaultMargin = 60.0
|
||||
|
||||
// Margins are the gross margins, in percent: a default, and per product.
|
||||
type Margins struct {
|
||||
Default float64 `json:"default"`
|
||||
ByProduct map[string]float64 `json:"by_product"`
|
||||
}
|
||||
|
||||
const marginsKey = "metrics:margins"
|
||||
|
||||
// LoadMargins returns the saved margins, or the default for everything.
|
||||
func LoadMargins(d *db.DB) Margins {
|
||||
m := Margins{Default: DefaultMargin, ByProduct: map[string]float64{}}
|
||||
if ok, err := d.GetJSON(marginsKey, &m); err != nil || !ok {
|
||||
return Margins{Default: DefaultMargin, ByProduct: map[string]float64{}}
|
||||
}
|
||||
if m.ByProduct == nil {
|
||||
m.ByProduct = map[string]float64{}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// SaveMargins stores the margins, after checking they're percentages.
|
||||
func SaveMargins(d *db.DB, m Margins) error {
|
||||
if m.Default < 0 || m.Default > 100 {
|
||||
return fmt.Errorf("a margin must be between 0 and 100%%")
|
||||
}
|
||||
for p, v := range m.ByProduct {
|
||||
if v < 0 || v > 100 {
|
||||
return fmt.Errorf("%s's margin must be between 0 and 100%%", p)
|
||||
}
|
||||
}
|
||||
return d.PutJSON(marginsKey, m)
|
||||
}
|
||||
|
||||
// For is a product's margin: its own, or the default.
|
||||
func (m Margins) For(product string) float64 {
|
||||
if v, ok := m.ByProduct[product]; ok {
|
||||
return v
|
||||
}
|
||||
return m.Default
|
||||
}
|
||||
|
||||
// Product is a product with what it brought in.
|
||||
type Product struct {
|
||||
ID string
|
||||
Name string
|
||||
Revenue int64 // the last 12 months' billed amount, after discounts, in cents
|
||||
Invoices int
|
||||
Margin float64
|
||||
Own bool // has its own margin
|
||||
}
|
||||
|
||||
var (
|
||||
quantityPrefix = regexp.MustCompile(`^\d+\s*[×x]\s*`)
|
||||
pricedSuffix = regexp.MustCompile(`\s*\((at|Tier).*\)$`)
|
||||
timeOnPrefix = regexp.MustCompile(`^(Unused|Remaining) time on\s+`)
|
||||
)
|
||||
|
||||
// nameFromLine reads a product's name from an invoice line's description:
|
||||
// "1 × Federated Core (at $49.00 / month)" → "Federated Core".
|
||||
func nameFromLine(desc string) string {
|
||||
desc = timeOnPrefix.ReplaceAllString(strings.TrimSpace(desc), "")
|
||||
desc = quantityPrefix.ReplaceAllString(desc, "")
|
||||
desc = pricedSuffix.ReplaceAllString(desc, "")
|
||||
if i := strings.Index(desc, " after "); i > 0 {
|
||||
desc = desc[:i]
|
||||
}
|
||||
return strings.TrimSpace(desc)
|
||||
}
|
||||
|
||||
// Products lists the products billed, with the last 12 months' revenue and
|
||||
// their margins, biggest first.
|
||||
func Products(d *db.DB, now time.Time) ([]Product, error) {
|
||||
names := map[string]string{}
|
||||
rows, err := d.Query(`SELECT id, data FROM stripe_objects WHERE kind = ?`, KindProduct)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var id, raw string
|
||||
if err := rows.Scan(&id, &raw); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
var p struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(raw), &p)
|
||||
names[id] = p.Name
|
||||
}
|
||||
rows.Close()
|
||||
m := LoadMargins(d) // before the next query: the database has one connection
|
||||
since := now.AddDate(-1, 0, 0).Unix()
|
||||
rows, err = d.Query(`SELECT product, coalesce(sum(CASE WHEN period_start >= ? THEN amount ELSE 0 END), 0), count(DISTINCT invoice),
|
||||
(SELECT description FROM stripe_invoice_lines l2 WHERE l2.product = l.product AND description != '' ORDER BY period_start DESC LIMIT 1)
|
||||
FROM stripe_invoice_lines l WHERE status IN ('paid', 'open') GROUP BY product`, since)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []Product
|
||||
for rows.Next() {
|
||||
var p Product
|
||||
var desc *string
|
||||
if err := rows.Scan(&p.ID, &p.Revenue, &p.Invoices, &desc); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
p.Name = names[p.ID]
|
||||
if p.Name == "" && desc != nil {
|
||||
p.Name = nameFromLine(*desc)
|
||||
}
|
||||
if p.Name == "" {
|
||||
p.Name = or(p.ID, "(no product: one-off charges)")
|
||||
}
|
||||
_, p.Own = m.ByProduct[p.ID]
|
||||
p.Margin = m.For(p.ID)
|
||||
out = append(out, p)
|
||||
}
|
||||
rows.Close()
|
||||
slices.SortStableFunc(out, func(a, b Product) int {
|
||||
switch {
|
||||
case a.Revenue > b.Revenue:
|
||||
return -1
|
||||
case a.Revenue < b.Revenue:
|
||||
return 1
|
||||
}
|
||||
return strings.Compare(a.Name, b.Name)
|
||||
})
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// WeightedMargin is a set of lines' margin, weighted by revenue: what a
|
||||
// customer (or the business) keeps of each dollar.
|
||||
func WeightedMargin(m Margins, revenueByProduct map[string]int64) float64 {
|
||||
var total, kept float64
|
||||
for p, r := range revenueByProduct {
|
||||
total += float64(r)
|
||||
kept += float64(r) * m.For(p)
|
||||
}
|
||||
if total == 0 {
|
||||
return m.Default
|
||||
}
|
||||
return kept / total
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNameFromLine(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"1 × Federated Core (at $49.00 / month)": "Federated Core",
|
||||
"3 x Seats (Tier 1 at $10.00 / month)": "Seats",
|
||||
"Unused time on Federated Core after 12 Nov 2026": "Federated Core",
|
||||
"Remaining time on 2 × Federated Core after 12 Nov 2026": "Federated Core",
|
||||
"Setup fee": "Setup fee",
|
||||
} {
|
||||
if got := nameFromLine(in); got != want {
|
||||
t.Errorf("%q: %q", in, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProductsAndMargins(t *testing.T) {
|
||||
d := openDB(t)
|
||||
now := time.Date(2026, 11, 22, 0, 0, 0, 0, time.UTC)
|
||||
recent, old := now.AddDate(0, -2, 0).Unix(), now.AddDate(-2, 0, 0).Unix()
|
||||
for _, l := range []struct {
|
||||
inv, id, product, desc, status string
|
||||
amount, start int64
|
||||
}{
|
||||
{"in_1", "il_1", "prod_core", "1 × Federated Core (at $49.00 / month)", "paid", 4900, recent},
|
||||
{"in_2", "il_2", "prod_core", "1 × Federated Core (at $49.00 / month)", "paid", 4900, old},
|
||||
{"in_3", "il_3", "prod_ai", "1 × Superbrain (at $20.00 / month)", "open", 2000, recent},
|
||||
{"in_4", "il_4", "prod_ai", "1 × Superbrain (at $20.00 / month)", "void", 2000, recent},
|
||||
{"in_5", "il_5", "", "Setup fee", "paid", 10000, recent},
|
||||
} {
|
||||
d.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, customer, status, currency, amount, period_start, period_end, product, description)
|
||||
VALUES (?, ?, 'cus_a', ?, 'usd', ?, ?, ?, ?, ?)`, l.inv, l.id, l.status, l.amount, l.start, l.start+2592000, l.product, l.desc)
|
||||
}
|
||||
d.Exec(`INSERT INTO stripe_objects (kind, id, data) VALUES ('product', 'prod_ai', '{"id":"prod_ai","name":"Superbrain AI"}')`)
|
||||
|
||||
ps, err := Products(d, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(ps) != 3 || ps[0].ID != "" || ps[0].Revenue != 10000 || ps[1].Name != "Federated Core" || ps[1].Revenue != 4900 || ps[1].Invoices != 2 ||
|
||||
ps[2].Name != "Superbrain AI" || ps[2].Revenue != 2000 || ps[2].Margin != 60 {
|
||||
t.Fatalf("products: %+v", ps)
|
||||
}
|
||||
if err := SaveMargins(d, Margins{Default: 60, ByProduct: map[string]float64{"prod_ai": 30}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SaveMargins(d, Margins{Default: 120}); err == nil {
|
||||
t.Error("saved a margin over 100%")
|
||||
}
|
||||
m := LoadMargins(d)
|
||||
if m.For("prod_ai") != 30 || m.For("prod_core") != 60 {
|
||||
t.Errorf("margins: %+v", m)
|
||||
}
|
||||
// $49 at 60% and $20 at 30%: (29.4 + 6) / 69 = 51.3%.
|
||||
if w := WeightedMargin(m, map[string]int64{"prod_core": 4900, "prod_ai": 2000}); w < 51.3 || w > 51.31 {
|
||||
t.Errorf("weighted: %v", w)
|
||||
}
|
||||
if ps, _ := Products(d, now); !ps[2].Own || ps[2].Margin != 30 {
|
||||
t.Errorf("own margin: %+v", ps[2])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
// 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"
|
||||
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
|
||||
}
|
||||
|
||||
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 || 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"}}},
|
||||
{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()}
|
||||
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":
|
||||
// charge.refunded: its refunds are what matter.
|
||||
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 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.
|
||||
func Counts(d *db.DB) (map[string]int, error) {
|
||||
rows, err := d.Query(`SELECT kind, count(*) FROM stripe_objects 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()
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
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/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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user