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]) } }