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:
@@ -58,3 +58,21 @@ func TestEnginesPage(t *testing.T) {
|
||||
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/test", s.emailTest)
|
||||
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/check", s.seoCheckPage)
|
||||
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"},
|
||||
{"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"},
|
||||
{"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.", ""},
|
||||
}
|
||||
|
||||
|
||||
@@ -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",
|
||||
"/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
|
||||
"/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"} {
|
||||
rec := do(h, http.MethodGet, path, nil, nil)
|
||||
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",
|
||||
"In Plausible, your account settings → API Keys → New API key, of the Stats API kind.", ""}
|
||||
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"
|
||||
|
||||
Reference in New Issue
Block a user