internal/jobs keeps named locks as leases in the database (schema 31: locks, instances), taken with one conditional UPDATE on SQLite or Postgres, renewed while the work runs and lapsing if its copy stops. Each background loop's turn, sending an email, audits, discovery runs and imports run under a lock; OAuth sign-ins under way are kept in the database. Copies check in, and work marked running is recovered at start only when no other copy is alive. Settings -> About lists the copies and work under way. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
558 lines
16 KiB
Go
558 lines
16 KiB
Go
package web
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"supermarket/internal/crm"
|
|
"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
|
|
}
|
|
model, err := metrics.Build(s.DB, time.Now())
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
clv, err := metrics.BuildCLV(s.DB, model, 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),
|
|
"Model": model,
|
|
"CLV": clv,
|
|
"Now": model.Last(),
|
|
"Recent": model.Recent(13),
|
|
"Bars": bars(model, 24),
|
|
"Cohorts": model.Cohorts(12, 12),
|
|
"Span": make([]int, 13),
|
|
}})
|
|
}
|
|
|
|
// bar is one month on the MRR chart.
|
|
type bar struct {
|
|
Month string
|
|
MRR float64
|
|
X, W, H float64 // in the SVG's units
|
|
Y float64
|
|
Label bool
|
|
}
|
|
|
|
// bars lays out the last n months of MRR as an SVG bar chart, 600 by 160.
|
|
func bars(m *metrics.Model, n int) []bar {
|
|
ms := m.Months
|
|
if len(ms) > n {
|
|
ms = ms[len(ms)-n:]
|
|
}
|
|
top := 0.0
|
|
for _, mo := range ms {
|
|
top = max(top, mo.MRR)
|
|
}
|
|
if top == 0 || len(ms) == 0 {
|
|
return nil
|
|
}
|
|
w := 600.0 / float64(len(ms))
|
|
out := make([]bar, len(ms))
|
|
for i, mo := range ms {
|
|
h := 140 * mo.MRR / top
|
|
out[i] = bar{Month: mo.Month, MRR: mo.MRR, X: float64(i)*w + 1, W: w - 2, H: h, Y: 150 - h, Label: i%3 == 0 || i == len(ms)-1}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// metricsStart sets the month the metrics count from.
|
|
func (s *Server) metricsStart(w http.ResponseWriter, r *http.Request) {
|
|
if err := r.ParseForm(); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err := metrics.SetStartMonth(s.DB, strings.TrimSpace(r.PostFormValue("month"))); err != nil {
|
|
s.renderMetrics(w, r, err.Error())
|
|
return
|
|
}
|
|
redirect(w, r, "/metrics", "saved")
|
|
}
|
|
|
|
// metricsMonth shows one month's moves, customer by customer.
|
|
func (s *Server) metricsMonth(w http.ResponseWriter, r *http.Request) {
|
|
model, err := metrics.Build(s.DB, time.Now())
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
month := r.PathValue("month")
|
|
mo := model.Find(month)
|
|
if mo == nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
names, err := metrics.CustomerNames(s.DB)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
s.render(w, r, "metrics-month", page{Title: "MRR in " + month, Nav: "metrics/overview", Data: map[string]any{
|
|
"M": mo, "Changes": model.Changes(month, names),
|
|
}})
|
|
}
|
|
|
|
// 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 {
|
|
s.jobDo(ctx, "metrics", func(ctx context.Context) {
|
|
if c := s.stripe(); c != nil {
|
|
if _, err := metrics.SyncOutsideSpend(s.DB, time.Now()); err != nil {
|
|
s.Log.Warn("metrics: outside spend", "err", err)
|
|
}
|
|
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:
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- Stripe customers and CRM Accounts ---
|
|
|
|
func (s *Server) metricsCustomers(w http.ResponseWriter, r *http.Request) {
|
|
s.renderCustomers(w, r, "")
|
|
}
|
|
|
|
func (s *Server) renderCustomers(w http.ResponseWriter, r *http.Request, errMsg string) {
|
|
model, err := metrics.Build(s.DB, time.Now())
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
all, err := metrics.Matches(s.DB, model)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
show := r.URL.Query().Get("show")
|
|
var shown []metrics.Match
|
|
for _, m := range all {
|
|
open := m.How == metrics.MatchNone || m.How == metrics.MatchAmbiguous
|
|
if show == "all" || (show == "" && open) || (show == "paying" && m.MRR > 0) {
|
|
shown = append(shown, m)
|
|
}
|
|
}
|
|
accounts, err := metrics.Accounts(s.DB)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
counts, _ := crm.RecordCounts(s.DB)
|
|
sync, _ := crm.LoadSync(s.DB)
|
|
queued := map[string]bool{}
|
|
if acts, err := crm.List(s.DB, 1000); err == nil {
|
|
for _, a := range acts {
|
|
if strings.HasPrefix(a.Key, "stripe-customer:") && a.Status != "cancelled" {
|
|
queued[strings.TrimPrefix(a.Key, "stripe-customer:")] = true
|
|
}
|
|
}
|
|
}
|
|
s.render(w, r, "metrics-customers", page{Title: "Customers and the CRM", Nav: "metrics/customers", Error: errMsg, Data: map[string]any{
|
|
"Matches": shown, "Total": len(all), "Summary": metrics.MatchSummary(all), "Accounts": accounts,
|
|
"CRMCount": counts["Account"], "Synced": sync.Last, "Show": show, "Queued": queued,
|
|
}})
|
|
}
|
|
|
|
// metricsCustomerMatch handles a customer's buttons: choose an Account, say
|
|
// it isn't in the CRM, go back to automatic, or add it to the CRM.
|
|
func (s *Server) metricsCustomerMatch(w http.ResponseWriter, r *http.Request) {
|
|
if err := r.ParseForm(); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
cust := r.PathValue("id")
|
|
if !strings.HasPrefix(cust, "cus_") {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
now := time.Now()
|
|
var err error
|
|
switch r.PostFormValue("do") {
|
|
case "account":
|
|
acc := strings.TrimSpace(r.PostFormValue("account"))
|
|
// The box takes a name; find its Account.
|
|
if accounts, aerr := metrics.Accounts(s.DB); aerr == nil {
|
|
for _, a := range accounts {
|
|
if strings.EqualFold(a.Name, acc) || a.ID == acc {
|
|
acc = a.ID
|
|
}
|
|
}
|
|
}
|
|
if acc == "" {
|
|
err = errors.New("choose an Account")
|
|
} else {
|
|
err = metrics.SetMatch(s.DB, cust, acc, false, now)
|
|
}
|
|
case "none":
|
|
err = metrics.SetMatch(s.DB, cust, "", false, now)
|
|
case "auto":
|
|
err = metrics.SetMatch(s.DB, cust, "", true, now)
|
|
case "add":
|
|
err = s.queueAccount(cust)
|
|
default:
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
if err != nil {
|
|
s.renderCustomers(w, r, err.Error())
|
|
return
|
|
}
|
|
redirect(w, r, "/metrics/customers?show="+r.PostFormValue("show"), "saved")
|
|
}
|
|
|
|
// queueAccount asks Hermes to add a paying Stripe customer to the CRM as an
|
|
// Account (and remembers the match once it exists).
|
|
func (s *Server) queueAccount(cust string) error {
|
|
names, err := metrics.CustomerNames(s.DB)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c, ok := names[cust]
|
|
if !ok {
|
|
return errors.New("no such customer")
|
|
}
|
|
name := c.Name
|
|
if name == "" {
|
|
name = c.Email
|
|
}
|
|
if name == "" {
|
|
return errors.New("the customer has no name or email to create an Account from")
|
|
}
|
|
fields := map[string]any{"name": name, "description": "Added by Supermarket: a paying Stripe customer (" + cust + ")."}
|
|
match := map[string]string{"name": name}
|
|
if dom := crm.EmailDomain(c.Email); dom != "" && !crm.IsFreeMail(dom) {
|
|
fields["website"] = "https://" + dom
|
|
match = map[string]string{"website": "https://" + dom}
|
|
}
|
|
if c.Email != "" {
|
|
fields["emailAddress"] = c.Email
|
|
}
|
|
_, err = crm.Enqueue(s.DB, crm.Action{Key: "stripe-customer:" + cust, Entity: "Account", Fields: fields, Match: match, Origin: "stripe-customer:" + cust})
|
|
return err
|
|
}
|
|
|
|
// --- Spend and CAC ---
|
|
|
|
func (s *Server) metricsSpend(w http.ResponseWriter, r *http.Request) {
|
|
s.renderSpend(w, r, "")
|
|
}
|
|
|
|
func (s *Server) renderSpend(w http.ResponseWriter, r *http.Request, errMsg string) {
|
|
model, err := metrics.Build(s.DB, time.Now())
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
names, err := metrics.CustomerNames(s.DB)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
cac, err := metrics.BuildCAC(s.DB, model, names)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
log, err := metrics.SpendLog(s.DB, 200)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
months := cac.Months
|
|
if len(months) > 13 {
|
|
months = months[:13]
|
|
}
|
|
s.render(w, r, "metrics-spend", page{Title: "Spend and CAC", Nav: "metrics/spend", Error: errMsg, Data: map[string]any{
|
|
"CAC": cac, "Months": months, "Log": log, "Channels": metrics.SpendChannels(), "This": time.Now().Format("2006-01"),
|
|
}})
|
|
}
|
|
|
|
// metricsSpendAdd logs spend, or imports a CSV.
|
|
func (s *Server) metricsSpendAdd(w http.ResponseWriter, r *http.Request) {
|
|
if err := r.ParseForm(); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
now := time.Now()
|
|
if csvText := strings.TrimSpace(r.PostFormValue("csv")); csvText != "" {
|
|
n, err := metrics.ImportSpendCSV(s.DB, strings.NewReader(csvText), now)
|
|
if err != nil {
|
|
s.renderSpend(w, r, "Nothing imported: "+err.Error())
|
|
return
|
|
}
|
|
s.Log.Info("metrics: spend imported", "rows", n)
|
|
redirect(w, r, "/metrics/spend", "imported")
|
|
return
|
|
}
|
|
cents, err := metrics.ParseAmount(r.PostFormValue("amount"))
|
|
if err == nil {
|
|
err = metrics.AddSpend(s.DB, metrics.Spend{Month: strings.TrimSpace(r.PostFormValue("month")), Channel: r.PostFormValue("channel"),
|
|
AmountCents: cents, Note: r.PostFormValue("note")}, now)
|
|
}
|
|
if err != nil {
|
|
s.renderSpend(w, r, err.Error())
|
|
return
|
|
}
|
|
redirect(w, r, "/metrics/spend", "saved")
|
|
}
|
|
|
|
func (s *Server) metricsSpendDelete(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
|
if err != nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
if err := metrics.DeleteSpend(s.DB, id); err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
redirect(w, r, "/metrics/spend", "deleted")
|
|
}
|
|
|
|
// --- CLV and cohorts ---
|
|
|
|
func (s *Server) metricsCLV(w http.ResponseWriter, r *http.Request) {
|
|
now := time.Now()
|
|
model, err := metrics.Build(s.DB, now)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
clv, err := metrics.BuildCLV(s.DB, model, now)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
cohorts, err := metrics.RevenueByCohort(s.DB, model, 18, 12, now)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
s.render(w, r, "metrics-clv", page{Title: "CLV and cohorts", Nav: "metrics/clv", Data: map[string]any{
|
|
"CLV": clv, "Cohorts": cohorts, "Span": make([]int, 13), "Profit": r.URL.Query().Get("view") == "profit",
|
|
"Currency": model.Currency,
|
|
}})
|
|
}
|
|
|
|
// --- CSV export and the open metrics page ---
|
|
|
|
func (s *Server) metricsExport(w http.ResponseWriter, r *http.Request) {
|
|
name := strings.TrimSuffix(r.PathValue("name"), ".csv")
|
|
known := false
|
|
for _, e := range metrics.Exports {
|
|
known = known || e.Name == name
|
|
}
|
|
if !known {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
|
w.Header().Set("Content-Disposition", `attachment; filename="supermarket-`+name+`-`+time.Now().Format("2006-01-02")+`.csv"`)
|
|
if err := metrics.Export(w, s.DB, name, time.Now()); err != nil {
|
|
s.Log.Error("metrics: export", "table", name, "err", err)
|
|
}
|
|
}
|
|
|
|
// publishOptions are the open metrics page's settings.
|
|
type publishOptions struct {
|
|
Site int `json:"site"`
|
|
Path string `json:"path"`
|
|
Title string `json:"title"`
|
|
Parts map[string]bool `json:"parts"`
|
|
PRURL string `json:"pr_url"`
|
|
PRAt time.Time `json:"pr_at"`
|
|
}
|
|
|
|
const publishKey = "metrics:publish"
|
|
|
|
func (s *Server) publishOptions() publishOptions {
|
|
o := publishOptions{Path: "/metrics/", Title: "Open metrics", Parts: map[string]bool{"mrr": true, "customers": true, "growth": true, "nrr": true}}
|
|
_, _ = s.DB.GetJSON(publishKey, &o)
|
|
return o
|
|
}
|
|
|
|
func (s *Server) metricsPublishPage(w http.ResponseWriter, r *http.Request) {
|
|
s.renderPublish(w, r, s.publishOptions(), "")
|
|
}
|
|
|
|
func (s *Server) renderPublish(w http.ResponseWriter, r *http.Request, o publishOptions, errMsg string) {
|
|
now := time.Now()
|
|
model, err := metrics.Build(s.DB, now)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
clv, err := metrics.BuildCLV(s.DB, model, now)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
s.render(w, r, "metrics-publish", page{Title: "Publish metrics", Nav: "metrics/publish", Error: errMsg, Data: map[string]any{
|
|
"O": o, "Parts": metrics.PublicParts, "Sites": s.seoSites(), "Gitea": s.gitea() != nil,
|
|
"Preview": metrics.PublicPage(model, clv, o.Parts, now),
|
|
}})
|
|
}
|
|
|
|
// metricsPublish saves the page's settings, and with "pr" opens the pull
|
|
// request.
|
|
func (s *Server) metricsPublish(w http.ResponseWriter, r *http.Request) {
|
|
if err := r.ParseForm(); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
o := s.publishOptions()
|
|
o.Site, _ = strconv.Atoi(r.PostFormValue("site"))
|
|
o.Path = strings.TrimSpace(r.PostFormValue("path"))
|
|
o.Title = strings.TrimSpace(r.PostFormValue("title"))
|
|
o.Parts = map[string]bool{}
|
|
for _, p := range r.PostForm["part"] {
|
|
o.Parts[p] = true
|
|
}
|
|
if o.Path == "" || o.Title == "" {
|
|
s.renderPublish(w, r, o, "Give the page an address and a title.")
|
|
return
|
|
}
|
|
if r.PostFormValue("do") == "pr" {
|
|
var site *seoSite
|
|
for _, st := range s.seoSites() {
|
|
if st.Index == o.Site {
|
|
site = &st
|
|
}
|
|
}
|
|
if site == nil {
|
|
s.renderPublish(w, r, o, "Choose a website.")
|
|
return
|
|
}
|
|
now := time.Now()
|
|
model, err := metrics.Build(s.DB, now)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
clv, _ := metrics.BuildCLV(s.DB, model, now)
|
|
body := metrics.PublicPage(model, clv, o.Parts, now)
|
|
if body == "" {
|
|
s.renderPublish(w, r, o, "There's no complete month of billing to publish yet.")
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
|
|
defer cancel()
|
|
pr, _, err := s.applier(*site).PublishPage(ctx, o.Path, o.Title, "Our revenue numbers, straight from our billing.", body,
|
|
"Proposed by Supermarket: the open metrics page, with totals only (nothing about any one customer).")
|
|
if err != nil {
|
|
s.renderPublish(w, r, o, "Couldn't open the pull request: "+err.Error())
|
|
return
|
|
}
|
|
o.PRURL, o.PRAt = pr.HTMLURL, now
|
|
}
|
|
if err := s.DB.PutJSON(publishKey, o); err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
msg := "saved"
|
|
if r.PostFormValue("do") == "pr" {
|
|
msg = "setup-opened"
|
|
}
|
|
redirect(w, r, "/metrics/publish", msg)
|
|
}
|