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 }