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:
@@ -143,6 +143,8 @@ Edit the brief and answer those questions ("not tested" is a fine answer), then
|
|||||||
- **Google:** the sitemaps Search Console has, with their errors.
|
- **Google:** the sitemaps Search Console has, with their errors.
|
||||||
- **Bing:** with a Bing Webmaster API key (Settings → Search engines), Bing's weekly clicks and impressions, its top searches, and its crawl issues.
|
- **Bing:** with a Bing Webmaster API key (Settings → Search engines), Bing's weekly clicks and impressions, its top searches, and its crawl issues.
|
||||||
|
|
||||||
|
**Metrics (Metrics).** With the Stripe key from Settings → Website & sales (give it read access to Customers, Invoices, Credit notes, Charges and Refunds, and Events too), Supermarket reads your whole Stripe history once, then the changes every hour. Under *Gross margin by product*, each product shows what it billed over the last 12 months; give each its margin (what you keep after the cost of delivering it), or leave it at the default, 60%. CLV uses them. MRR, NRR, CAC and CLV are built on this in the next parts.
|
||||||
|
|
||||||
**The end of the funnel (Settings → Website & sales).** When writing posts on Content, choose *For a buying signal*: the posts speak to that situation, and their links carry the signal's campaign tag. Each signal's page lists its posts and gives your websites' addresses tagged with it, for landing pages, the shopping cart or links you share. With a Plausible Stats API key (Plausible on your Core by default), Supermarket reads yesterday's visitors on tagged links once a day and counts them as Visited for the signal, by channel; visits are counted per signal, never per person. With a restricted, read-only Stripe key, it reads new checkouts and paid invoices every hour: a checkout with nothing to pay (a trial or a free plan) counts as Signed up, and money paid as Paid, with the amount. A customer is tied to a signal by the `utm_campaign` your shopping cart saves in the Checkout Session's metadata, or else by their email (a prospect's, or one at a prospect company's domain). Your Core's Cal.com has no API, so bookings are read from Cal.com's booking emails in the outreach mailbox: give Cal.com's sending address under Settings → Email, and each new booking counts as Booked for the person who booked.
|
**The end of the funnel (Settings → Website & sales).** When writing posts on Content, choose *For a buying signal*: the posts speak to that situation, and their links carry the signal's campaign tag. Each signal's page lists its posts and gives your websites' addresses tagged with it, for landing pages, the shopping cart or links you share. With a Plausible Stats API key (Plausible on your Core by default), Supermarket reads yesterday's visitors on tagged links once a day and counts them as Visited for the signal, by channel; visits are counted per signal, never per person. With a restricted, read-only Stripe key, it reads new checkouts and paid invoices every hour: a checkout with nothing to pay (a trial or a free plan) counts as Signed up, and money paid as Paid, with the amount. A customer is tied to a signal by the `utm_campaign` your shopping cart saves in the Checkout Session's metadata, or else by their email (a prospect's, or one at a prospect company's domain). Your Core's Cal.com has no API, so bookings are read from Cal.com's booking emails in the outreach mailbox: give Cal.com's sending address under Settings → Email, and each new booking counts as Booked for the person who booked.
|
||||||
|
|
||||||
**Prospects (Prospects → Review).** Companies and people who may fit your targets wait here for review; for now you add them by hand, and finding them for you comes next. Each keeps where and when it was found. Accepting a company queues an EspoCRM Account, accepting a person queues a Lead at their company, with the source, date and why they fit in the record's description. Before you decide, the page warns about records already in your CRM (as of the last sync). *Set aside* keeps a prospect out of the way; the **suppression list** (Prospects → Suppression list) holds emails and domains that must never be added, and is checked when a prospect is added and again before anything is queued.
|
**Prospects (Prospects → Review).** Companies and people who may fit your targets wait here for review; for now you add them by hand, and finding them for you comes next. Each keeps where and when it was found. Accepting a company queues an EspoCRM Account, accepting a person queues a Lead at their company, with the source, date and why they fit in the record's description. Before you decide, the page warns about records already in your CRM (as of the last sync). *Set aside* keeps a prospect out of the way; the **suppression list** (Prospects → Suppression list) holds emails and domains that must never be added, and is checked when a prospect is added and again before anything is queued.
|
||||||
|
|||||||
@@ -399,19 +399,36 @@ Throughout, also notice:
|
|||||||
- [ ] With a Bing Webmaster API key saved, Bing's weekly numbers, searches
|
- [ ] With a Bing Webmaster API key saved, Bing's weekly numbers, searches
|
||||||
and crawl issues appear.
|
and crawl issues appear.
|
||||||
|
|
||||||
## 8. Search
|
## 8. Metrics
|
||||||
|
|
||||||
|
### Stripe sync
|
||||||
|
|
||||||
|
- [ ] With the Stripe key's read access widened (Customers, Invoices, Credit
|
||||||
|
notes, Charges and Refunds, Events), Metrics → *Sync now* reads your
|
||||||
|
whole history the first time and says so.
|
||||||
|
- [ ] The counts of customers, invoices, credit notes and refunds match
|
||||||
|
Stripe's dashboard (draft invoices aren't counted).
|
||||||
|
- [ ] A later *Sync now* applies only the changes since the last one; a
|
||||||
|
payment or refund made in Stripe shows up within the hour.
|
||||||
|
- [ ] The currencies listed are the ones you bill in.
|
||||||
|
- [ ] *Gross margin by product* lists your Stripe products by name, with
|
||||||
|
what each billed over the last 12 months (compare one with Stripe's
|
||||||
|
reports). Setting a margin and saving keeps it; an empty box shows
|
||||||
|
the default.
|
||||||
|
|
||||||
|
## 9. Search
|
||||||
|
|
||||||
- [ ] Searching for an inventory entry, a fetched item, a post, a prospect
|
- [ ] Searching for an inventory entry, a fetched item, a post, a prospect
|
||||||
(company or person) or a signal finds it, with a link to where it is.
|
(company or person) or a signal finds it, with a link to where it is.
|
||||||
|
|
||||||
## 9. Agents (MCP)
|
## 10. Agents (MCP)
|
||||||
|
|
||||||
- [ ] `supermarket token` prints a token.
|
- [ ] `supermarket token` prints a token.
|
||||||
- [ ] Claude Code (`claude mcp list`) shows Supermarket connected, and can
|
- [ ] Claude Code (`claude mcp list`) shows Supermarket connected, and can
|
||||||
list prospects or the CRM queue through it.
|
list prospects or the CRM queue through it.
|
||||||
- [ ] Hermes uses the Supermarket and Core MCP tools in its CRM job.
|
- [ ] Hermes uses the Supermarket and Core MCP tools in its CRM job.
|
||||||
|
|
||||||
## 10. Data and safety
|
## 11. Data and safety
|
||||||
|
|
||||||
- [ ] `~/.local/share/supermarket/secrets.json` is readable only by you
|
- [ ] `~/.local/share/supermarket/secrets.json` is readable only by you
|
||||||
(`ls -l`), and no key is ever shown in the app after saving.
|
(`ls -l`), and no key is ever shown in the app after saving.
|
||||||
|
|||||||
@@ -161,6 +161,7 @@ func run(log *slog.Logger) error {
|
|||||||
go srv.RunOutreach(ctx)
|
go srv.RunOutreach(ctx)
|
||||||
go srv.RunTracking(ctx)
|
go srv.RunTracking(ctx)
|
||||||
go srv.RunSEO(ctx)
|
go srv.RunSEO(ctx)
|
||||||
|
go srv.RunMetrics(ctx)
|
||||||
// A sync falls due, and a claim times out, without anything being
|
// A sync falls due, and a claim times out, without anything being
|
||||||
// written: refresh the state file each minute.
|
// written: refresh the state file each minute.
|
||||||
go func() {
|
go func() {
|
||||||
|
|||||||
@@ -165,3 +165,217 @@ func (c *Client) Check(ctx context.Context) error {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Raw is an object as Stripe sent it, with its ID and creation time read.
|
||||||
|
type Raw struct {
|
||||||
|
ID string
|
||||||
|
Object string
|
||||||
|
Created int64
|
||||||
|
JSON json.RawMessage
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListRaw reads every page of a list endpoint, newest first as Stripe sends
|
||||||
|
// them, keeping each object whole.
|
||||||
|
func (c *Client) ListRaw(ctx context.Context, path string, q url.Values, max int) ([]Raw, error) {
|
||||||
|
if q == nil {
|
||||||
|
q = url.Values{}
|
||||||
|
}
|
||||||
|
q.Set("limit", "100")
|
||||||
|
var all []Raw
|
||||||
|
for {
|
||||||
|
var page struct {
|
||||||
|
Data []json.RawMessage `json:"data"`
|
||||||
|
HasMore bool `json:"has_more"`
|
||||||
|
}
|
||||||
|
if err := c.get(ctx, path, q, &page); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, d := range page.Data {
|
||||||
|
var head struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Object string `json:"object"`
|
||||||
|
Created int64 `json:"created"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(d, &head); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
all = append(all, Raw{ID: head.ID, Object: head.Object, Created: head.Created, JSON: d})
|
||||||
|
}
|
||||||
|
if !page.HasMore || len(page.Data) == 0 || (max > 0 && len(all) >= max) {
|
||||||
|
return all, nil
|
||||||
|
}
|
||||||
|
q.Set("starting_after", all[len(all)-1].ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// InvoiceLines reads all of an invoice's lines (for invoices whose embedded
|
||||||
|
// list was cut short).
|
||||||
|
func (c *Client) InvoiceLines(ctx context.Context, invoiceID string) ([]json.RawMessage, error) {
|
||||||
|
raws, err := c.ListRaw(ctx, "/v1/invoices/"+url.PathEscape(invoiceID)+"/lines", nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := make([]json.RawMessage, len(raws))
|
||||||
|
for i, r := range raws {
|
||||||
|
out[i] = r.JSON
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// EventTypes are the events the sync follows.
|
||||||
|
var EventTypes = []string{
|
||||||
|
"customer.created", "customer.updated", "customer.deleted",
|
||||||
|
"invoice.created", "invoice.finalized", "invoice.updated", "invoice.paid", "invoice.voided", "invoice.marked_uncollectible",
|
||||||
|
"credit_note.created", "credit_note.updated", "credit_note.voided",
|
||||||
|
"refund.created", "refund.updated", "charge.refunded",
|
||||||
|
}
|
||||||
|
|
||||||
|
// Event is one change, with the object as it was after it.
|
||||||
|
type Event struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Created int64 `json:"created"`
|
||||||
|
Data struct {
|
||||||
|
Object json.RawMessage `json:"object"`
|
||||||
|
} `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Events lists the events of the followed types after a time, oldest first.
|
||||||
|
func (c *Client) Events(ctx context.Context, after time.Time) ([]Event, error) {
|
||||||
|
q := url.Values{"created[gt]": {strconv.FormatInt(after.Unix(), 10)}}
|
||||||
|
for _, t := range EventTypes {
|
||||||
|
q.Add("types[]", t)
|
||||||
|
}
|
||||||
|
raws, err := c.ListRaw(ctx, "/v1/events", q, 0)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := make([]Event, 0, len(raws))
|
||||||
|
for i := len(raws) - 1; i >= 0; i-- {
|
||||||
|
var e Event
|
||||||
|
if err := json.Unmarshal(raws[i].JSON, &e); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, e)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Line is an invoice line, read from either shape Stripe has used: the
|
||||||
|
// older one (price, type, proration on the line) and the 2025 one (pricing,
|
||||||
|
// parent).
|
||||||
|
type Line struct {
|
||||||
|
ID string
|
||||||
|
Amount int64 // after discounts, before tax
|
||||||
|
Currency string
|
||||||
|
PeriodStart int64
|
||||||
|
PeriodEnd int64
|
||||||
|
Subscription string
|
||||||
|
Price string
|
||||||
|
Product string
|
||||||
|
Interval string // day, week, month, year; "" for one-off
|
||||||
|
IntervalCount int
|
||||||
|
Quantity int64
|
||||||
|
Proration bool
|
||||||
|
Recurring bool
|
||||||
|
Description string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseLine reads an invoice line.
|
||||||
|
func ParseLine(raw json.RawMessage) (Line, error) {
|
||||||
|
var l struct {
|
||||||
|
Description string `json:"description"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
Amount int64 `json:"amount"`
|
||||||
|
Currency string `json:"currency"`
|
||||||
|
Period struct {
|
||||||
|
Start int64 `json:"start"`
|
||||||
|
End int64 `json:"end"`
|
||||||
|
} `json:"period"`
|
||||||
|
Quantity int64 `json:"quantity"`
|
||||||
|
Proration bool `json:"proration"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Subscription json.RawMessage `json:"subscription"`
|
||||||
|
Price *struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Product json.RawMessage `json:"product"`
|
||||||
|
Recurring *struct {
|
||||||
|
Interval string `json:"interval"`
|
||||||
|
IntervalCount int `json:"interval_count"`
|
||||||
|
} `json:"recurring"`
|
||||||
|
} `json:"price"`
|
||||||
|
Pricing *struct {
|
||||||
|
PriceDetails *struct {
|
||||||
|
Price json.RawMessage `json:"price"`
|
||||||
|
Product string `json:"product"`
|
||||||
|
} `json:"price_details"`
|
||||||
|
} `json:"pricing"`
|
||||||
|
Parent *struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
SubscriptionItemDetails *struct {
|
||||||
|
Subscription string `json:"subscription"`
|
||||||
|
Proration bool `json:"proration"`
|
||||||
|
} `json:"subscription_item_details"`
|
||||||
|
} `json:"parent"`
|
||||||
|
DiscountAmounts []struct {
|
||||||
|
Amount int64 `json:"amount"`
|
||||||
|
} `json:"discount_amounts"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &l); err != nil {
|
||||||
|
return Line{}, err
|
||||||
|
}
|
||||||
|
out := Line{ID: l.ID, Amount: l.Amount, Currency: l.Currency, PeriodStart: l.Period.Start, PeriodEnd: l.Period.End,
|
||||||
|
Quantity: l.Quantity, Proration: l.Proration, Subscription: idOf(l.Subscription), Description: l.Description}
|
||||||
|
for _, d := range l.DiscountAmounts {
|
||||||
|
out.Amount -= d.Amount
|
||||||
|
}
|
||||||
|
if l.Price != nil {
|
||||||
|
out.Price, out.Product = l.Price.ID, idOf(l.Price.Product)
|
||||||
|
if l.Price.Recurring != nil {
|
||||||
|
out.Interval, out.IntervalCount = l.Price.Recurring.Interval, l.Price.Recurring.IntervalCount
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if l.Pricing != nil && l.Pricing.PriceDetails != nil {
|
||||||
|
out.Price = or(out.Price, idOf(l.Pricing.PriceDetails.Price))
|
||||||
|
out.Product = or(out.Product, l.Pricing.PriceDetails.Product)
|
||||||
|
}
|
||||||
|
if l.Parent != nil && l.Parent.SubscriptionItemDetails != nil {
|
||||||
|
out.Subscription = or(out.Subscription, l.Parent.SubscriptionItemDetails.Subscription)
|
||||||
|
out.Proration = out.Proration || l.Parent.SubscriptionItemDetails.Proration
|
||||||
|
}
|
||||||
|
out.Recurring = l.Type == "subscription" || (l.Parent != nil && l.Parent.Type == "subscription_item_details") || out.Interval != ""
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func or(a, b string) string {
|
||||||
|
if a != "" {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
// idOf reads a field that is an ID string or an expanded object with an id.
|
||||||
|
func idOf(raw json.RawMessage) string {
|
||||||
|
if len(raw) == 0 || string(raw) == "null" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
var s string
|
||||||
|
if json.Unmarshal(raw, &s) == nil {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
var o struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(raw, &o)
|
||||||
|
return o.ID
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRaw reads one object.
|
||||||
|
func (c *Client) GetRaw(ctx context.Context, path string, q url.Values) (json.RawMessage, error) {
|
||||||
|
var out json.RawMessage
|
||||||
|
err := c.get(ctx, path, q, &out)
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// IDOf reads a field that is an ID string or an expanded object with an id.
|
||||||
|
func IDOf(raw json.RawMessage) string { return idOf(raw) }
|
||||||
|
|||||||
@@ -495,6 +495,48 @@ CREATE TABLE seo_briefs (
|
|||||||
live_at TEXT
|
live_at TEXT
|
||||||
);
|
);
|
||||||
CREATE INDEX seo_briefs_by_site ON seo_briefs (site, id);
|
CREATE INDEX seo_briefs_by_site ON seo_briefs (site, id);
|
||||||
|
`,
|
||||||
|
// 18: the full Stripe data for the metrics: every customer, invoice,
|
||||||
|
// credit note and refund as Stripe sent it, and the invoice lines the
|
||||||
|
// MRR model reads.
|
||||||
|
`
|
||||||
|
CREATE TABLE stripe_objects (
|
||||||
|
kind TEXT NOT NULL, -- customer, invoice, credit_note, refund
|
||||||
|
id TEXT NOT NULL,
|
||||||
|
customer TEXT NOT NULL DEFAULT '',
|
||||||
|
created INTEGER NOT NULL DEFAULT 0,
|
||||||
|
status TEXT NOT NULL DEFAULT '',
|
||||||
|
currency TEXT NOT NULL DEFAULT '',
|
||||||
|
amount INTEGER NOT NULL DEFAULT 0, -- invoice: total; credit note: total; refund: amount
|
||||||
|
data TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (kind, id)
|
||||||
|
);
|
||||||
|
CREATE INDEX stripe_objects_by_customer ON stripe_objects (kind, customer);
|
||||||
|
CREATE TABLE stripe_invoice_lines (
|
||||||
|
invoice TEXT NOT NULL,
|
||||||
|
id TEXT NOT NULL,
|
||||||
|
customer TEXT NOT NULL DEFAULT '',
|
||||||
|
status TEXT NOT NULL DEFAULT '', -- the invoice's
|
||||||
|
currency TEXT NOT NULL DEFAULT '',
|
||||||
|
amount INTEGER NOT NULL DEFAULT 0, -- after discounts, before tax
|
||||||
|
period_start INTEGER NOT NULL DEFAULT 0,
|
||||||
|
period_end INTEGER NOT NULL DEFAULT 0,
|
||||||
|
subscription TEXT NOT NULL DEFAULT '',
|
||||||
|
price TEXT NOT NULL DEFAULT '',
|
||||||
|
product TEXT NOT NULL DEFAULT '',
|
||||||
|
interval TEXT NOT NULL DEFAULT '',
|
||||||
|
interval_count INTEGER NOT NULL DEFAULT 0,
|
||||||
|
quantity INTEGER NOT NULL DEFAULT 0,
|
||||||
|
proration INTEGER NOT NULL DEFAULT 0,
|
||||||
|
recurring INTEGER NOT NULL DEFAULT 0,
|
||||||
|
PRIMARY KEY (invoice, id)
|
||||||
|
);
|
||||||
|
CREATE INDEX stripe_invoice_lines_by_customer ON stripe_invoice_lines (customer, period_start);
|
||||||
|
`,
|
||||||
|
// 19: invoice lines' descriptions, which name the product when the key
|
||||||
|
// can't read Products.
|
||||||
|
`
|
||||||
|
ALTER TABLE stripe_invoice_lines ADD COLUMN description TEXT NOT NULL DEFAULT '';
|
||||||
`,
|
`,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -58,3 +58,21 @@ func TestEnginesPage(t *testing.T) {
|
|||||||
t.Error("the ping isn't listed")
|
t.Error("the ping isn't listed")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestMarginsForm(t *testing.T) {
|
||||||
|
s, h := newTestServer(t, nil)
|
||||||
|
s.DB.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, status, currency, amount, period_start, product, description)
|
||||||
|
VALUES ('in_1', 'il_1', 'paid', 'usd', 4900, strftime('%s', 'now'), 'prod_core', '1 × Federated Core (at $49.00 / month)')`)
|
||||||
|
if body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String(); !strings.Contains(body, "Federated Core") || !strings.Contains(body, `placeholder="60"`) {
|
||||||
|
t.Fatal("the margin table isn't shown")
|
||||||
|
}
|
||||||
|
if rec := postForm(h, "/metrics/margins", url.Values{"default": {"55%"}, "margin:prod_core": {"70"}}); rec.Code != http.StatusSeeOther {
|
||||||
|
t.Fatalf("save: %d %s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
if body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String(); !strings.Contains(body, `name="margin:prod_core" value="70"`) || !strings.Contains(body, `name="default" value="55"`) {
|
||||||
|
t.Error("the margins weren't saved")
|
||||||
|
}
|
||||||
|
if rec := postForm(h, "/metrics/margins", url.Values{"default": {"abc"}}); !strings.Contains(rec.Body.String(), "percentage") {
|
||||||
|
t.Error("a bad default was accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
package web
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"supermarket/internal/metrics"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *Server) metricsPage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
s.renderMetrics(w, r, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) renderMetrics(w http.ResponseWriter, r *http.Request, errMsg string) {
|
||||||
|
counts, err := metrics.Counts(s.DB)
|
||||||
|
if err != nil {
|
||||||
|
s.serverError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
products, err := metrics.Products(s.DB, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
s.serverError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.render(w, r, "metrics", page{Title: "Metrics", Nav: "metrics/overview", Error: errMsg, Data: map[string]any{
|
||||||
|
"Stripe": s.stripe() != nil,
|
||||||
|
"Last": metrics.LastSync(s.DB),
|
||||||
|
"Counts": counts,
|
||||||
|
"Products": products,
|
||||||
|
"Margins": metrics.LoadMargins(s.DB),
|
||||||
|
}})
|
||||||
|
}
|
||||||
|
|
||||||
|
// metricsMargins saves the gross margins: the default, and per product (an
|
||||||
|
// empty box uses the default).
|
||||||
|
func (s *Server) metricsMargins(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if err := r.ParseForm(); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
parse := func(v string) (float64, bool, error) {
|
||||||
|
v = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(v), "%"))
|
||||||
|
if v == "" {
|
||||||
|
return 0, false, nil
|
||||||
|
}
|
||||||
|
f, err := strconv.ParseFloat(v, 64)
|
||||||
|
return f, true, err
|
||||||
|
}
|
||||||
|
m := metrics.Margins{ByProduct: map[string]float64{}}
|
||||||
|
def, ok, err := parse(r.PostFormValue("default"))
|
||||||
|
if err != nil || !ok {
|
||||||
|
s.renderMetrics(w, r, "Give the default margin as a percentage.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
m.Default = def
|
||||||
|
for key, vals := range r.PostForm {
|
||||||
|
id, isProduct := strings.CutPrefix(key, "margin:")
|
||||||
|
if !isProduct || len(vals) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
v, set, err := parse(vals[0])
|
||||||
|
if err != nil {
|
||||||
|
s.renderMetrics(w, r, "A margin isn't a number: "+vals[0])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if set {
|
||||||
|
m.ByProduct[id] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := metrics.SaveMargins(s.DB, m); err != nil {
|
||||||
|
s.renderMetrics(w, r, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
redirect(w, r, "/metrics#margins", "saved")
|
||||||
|
}
|
||||||
|
|
||||||
|
// metricsSync syncs Stripe now; "full" reads everything again.
|
||||||
|
func (s *Server) metricsSync(w http.ResponseWriter, r *http.Request) {
|
||||||
|
c := s.stripe()
|
||||||
|
if c == nil {
|
||||||
|
s.renderMetrics(w, r, "Save a Stripe key under Settings → Website & sales first.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
if _, err := metrics.Sync(ctx, s.DB, c, time.Now(), r.PostFormValue("full") == "1"); err != nil {
|
||||||
|
s.renderMetrics(w, r, "Syncing Stripe: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
redirect(w, r, "/metrics", "synced")
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunMetrics syncs Stripe every hour.
|
||||||
|
func (s *Server) RunMetrics(ctx context.Context) {
|
||||||
|
tick := time.NewTicker(10 * time.Minute)
|
||||||
|
defer tick.Stop()
|
||||||
|
for {
|
||||||
|
if c := s.stripe(); c != nil {
|
||||||
|
last := metrics.LastSync(s.DB)
|
||||||
|
if last == nil || time.Since(last.At) >= time.Hour {
|
||||||
|
sctx, cancel := context.WithTimeout(ctx, 30*time.Minute)
|
||||||
|
if _, err := metrics.Sync(sctx, s.DB, c, time.Now(), false); err != nil && !errors.Is(err, context.Canceled) {
|
||||||
|
s.Log.Warn("metrics: Stripe sync", "err", err)
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-tick.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -159,6 +159,9 @@ func (s *Server) Handler() (http.Handler, error) {
|
|||||||
mux.HandleFunc("POST /settings/email", s.emailSave)
|
mux.HandleFunc("POST /settings/email", s.emailSave)
|
||||||
mux.HandleFunc("POST /settings/email/test", s.emailTest)
|
mux.HandleFunc("POST /settings/email/test", s.emailTest)
|
||||||
mux.HandleFunc("POST /settings/email/send-test", s.emailSendTest)
|
mux.HandleFunc("POST /settings/email/send-test", s.emailSendTest)
|
||||||
|
mux.HandleFunc("GET /metrics", s.metricsPage)
|
||||||
|
mux.HandleFunc("POST /metrics/sync", s.metricsSync)
|
||||||
|
mux.HandleFunc("POST /metrics/margins", s.metricsMargins)
|
||||||
mux.HandleFunc("GET /seo", s.seoPage)
|
mux.HandleFunc("GET /seo", s.seoPage)
|
||||||
mux.HandleFunc("GET /seo/check", s.seoCheckPage)
|
mux.HandleFunc("GET /seo/check", s.seoCheckPage)
|
||||||
mux.HandleFunc("GET /seo/engines", s.seoEnginesPage)
|
mux.HandleFunc("GET /seo/engines", s.seoEnginesPage)
|
||||||
@@ -378,7 +381,7 @@ var modules = []module{
|
|||||||
{"content", "Content", "Phase 1", "Draft posts from partner and competitor news and your own products; review and publish to X, LinkedIn and Reddit.", "/content"},
|
{"content", "Content", "Phase 1", "Draft posts from partner and competitor news and your own products; review and publish to X, LinkedIn and Reddit.", "/content"},
|
||||||
{"prospects", "Prospects", "Phase 2", "Test buying signals through the whole funnel, from finding prospects to payment; add the people you approve to EspoCRM through Hermes.", "/signals"},
|
{"prospects", "Prospects", "Phase 2", "Test buying signals through the whole funnel, from finding prospects to payment; add the people you approve to EspoCRM through Hermes.", "/signals"},
|
||||||
{"seo", "SEO", "Phase 3", "Run the weekly SEO loop from Search Console: what ranks, what moved, and the changes waiting for your yes, opened as pull requests on your Hugo repositories.", "/seo"},
|
{"seo", "SEO", "Phase 3", "Run the weekly SEO loop from Search Console: what ranks, what moved, and the changes waiting for your yes, opened as pull requests on your Hugo repositories.", "/seo"},
|
||||||
{"metrics", "Metrics", "Phase 4", "Pipeline influence, CAC, CLV and NRR from Stripe, EspoCRM and Plausible.", ""},
|
{"metrics", "Metrics", "Phase 4", "MRR, NRR, CAC and CLV from Stripe, with pipeline influence from EspoCRM.", "/metrics"},
|
||||||
{"sites", "Sites", "Phase 5", "Build pages and sites from a component library and publish them through Gitea.", ""},
|
{"sites", "Sites", "Phase 5", "Build pages and sites from a component library and publish them through Gitea.", ""},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) {
|
|||||||
"/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz",
|
"/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz",
|
||||||
"/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
|
"/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
|
||||||
"/content/scheduled", "/content/published",
|
"/content/scheduled", "/content/published",
|
||||||
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines",
|
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics",
|
||||||
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
|
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
|
||||||
rec := do(h, http.MethodGet, path, nil, nil)
|
rec := do(h, http.MethodGet, path, nil, nil)
|
||||||
if rec.Code != http.StatusOK {
|
if rec.Code != http.StatusOK {
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
{{define "content"}}{{with .Data}}
|
||||||
|
<div class="heading">
|
||||||
|
<h1>Metrics</h1>
|
||||||
|
{{if .Stripe}}<div class="buttons">
|
||||||
|
<form method="post" action="/metrics/sync" data-busy="Syncing…"><button type="submit" class="secondary">Sync now</button></form>
|
||||||
|
</div>{{end}}
|
||||||
|
</div>
|
||||||
|
<p class="lede">MRR and its movements, NRR, CAC and CLV, computed from your Stripe data: every customer, invoice, credit note and refund. MRR comes from the invoice lines (what each customer was billed, for which period), so past months are exact. Supermarket only reads Stripe.</p>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>Stripe</h2>
|
||||||
|
{{if not .Stripe}}
|
||||||
|
<p class="warn-text">Save a restricted Stripe key under <a href="/settings/tracking#stripe">Settings → Website & sales</a>. For the metrics it needs read access to Customers, Invoices, Credit notes, Charges and Refunds, and Events, on top of Checkout Sessions.</p>
|
||||||
|
{{else}}
|
||||||
|
{{with .Last}}
|
||||||
|
<p class="small {{if .Error}}error-text{{else}}muted{{end}}">Synced {{ago .At}}{{if .Full}} (everything read){{else}} ({{.Events}} changes since the last sync){{end}}{{with .Error}}: {{.}}{{end}}.{{with .Currency}} Currencies: {{range $i, $c := .}}{{if $i}}, {{end}}{{$c}}{{end}}.{{end}}</p>
|
||||||
|
{{else}}<p class="help">Not synced yet: the first sync reads all your Stripe history, which can take a few minutes.</p>{{end}}
|
||||||
|
<div class="funnel">
|
||||||
|
<div class="step"><span class="label">Customers</span><strong>{{num (or (index .Counts "customer") 0)}}</strong></div>
|
||||||
|
<div class="step"><span class="label">Invoices</span><strong>{{num (or (index .Counts "invoice") 0)}}</strong></div>
|
||||||
|
<div class="step"><span class="label">Credit notes</span><strong>{{num (or (index .Counts "credit_note") 0)}}</strong></div>
|
||||||
|
<div class="step"><span class="label">Refunds</span><strong>{{num (or (index .Counts "refund") 0)}}</strong></div>
|
||||||
|
</div>
|
||||||
|
<form method="post" action="/metrics/sync" data-busy="Reading everything…" class="inline"><input type="hidden" name="full" value="1"><button type="submit" class="link small">Read everything again</button></form>
|
||||||
|
{{with .Last}}{{range .Notes}}<p class="small muted">{{.}}</p>{{end}}{{end}}
|
||||||
|
{{end}}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{{if .Products}}{{$m := .Margins}}
|
||||||
|
<form method="post" action="/metrics/margins" class="card" id="margins">
|
||||||
|
<h2>Gross margin by product</h2>
|
||||||
|
<p class="small">What you keep of each dollar a product brings in, after what it costs you to deliver (hosting, licences, support). CLV weighs each customer's revenue by the margin of what they buy. An empty box uses the default.</p>
|
||||||
|
<label>Default <input name="default" value="{{$m.Default}}" inputmode="decimal" size="5"> %</label>
|
||||||
|
<table class="list">
|
||||||
|
<thead><tr><th>Product</th><th class="num">Billed, last 12 months</th><th class="num">Invoices</th><th class="num">Margin</th></tr></thead>
|
||||||
|
<tbody>{{range .Products}}<tr>
|
||||||
|
<td>{{.Name}}{{if and .ID (ne .Name .ID)}} <span class="muted small">{{.ID}}</span>{{end}}</td>
|
||||||
|
<td class="num">{{money .Revenue}}</td><td class="num">{{num .Invoices}}</td>
|
||||||
|
<td class="num">{{if .ID}}<input name="margin:{{.ID}}" value="{{if .Own}}{{.Margin}}{{end}}" placeholder="{{$m.Default}}" inputmode="decimal" size="5"> %{{else}}<span class="muted">default</span>{{end}}</td>
|
||||||
|
</tr>{{end}}</tbody>
|
||||||
|
</table>
|
||||||
|
<div class="actions"><button type="submit">Save margins</button></div>
|
||||||
|
</form>
|
||||||
|
{{end}}
|
||||||
|
{{end}}{{end}}
|
||||||
@@ -19,7 +19,7 @@ var (
|
|||||||
plausibleKey = secretField{"plausible", secrets.PlausibleAPIKey, "Stats API key",
|
plausibleKey = secretField{"plausible", secrets.PlausibleAPIKey, "Stats API key",
|
||||||
"In Plausible, your account settings → API Keys → New API key, of the Stats API kind.", ""}
|
"In Plausible, your account settings → API Keys → New API key, of the Stats API kind.", ""}
|
||||||
stripeKey = secretField{"stripe", secrets.StripeAPIKey, "Restricted key",
|
stripeKey = secretField{"stripe", secrets.StripeAPIKey, "Restricted key",
|
||||||
"In Stripe, Developers → API keys → Create restricted key, with Read access to Checkout Sessions and Invoices and nothing else. It starts rk_live_.", "https://dashboard.stripe.com/apikeys"}
|
"In Stripe, Developers → API keys → Create restricted key, with Read access only, to Checkout Sessions, Invoices, Customers, Credit notes, Charges and Refunds, and Events (the last four for Metrics). It starts rk_live_.", "https://dashboard.stripe.com/apikeys"}
|
||||||
)
|
)
|
||||||
|
|
||||||
const plausibleURLKey = "tracking:plausible-url"
|
const plausibleURLKey = "tracking:plausible-url"
|
||||||
|
|||||||
Reference in New Issue
Block a user