Files
supermarket/internal/web/server.go
T
davidandClaude Opus 5.5 5e799c7541 Phase 4 part 2: MRR, its movements, NRR and cohorts
Each customer's MRR at each month's end, from the recurring lines of paid
and open invoices: the amount after discounts over the billing interval,
prorations over their part-period. Moves are new, expansion, contraction,
churn and reactivation (sub-dollar noise ignored); NRR monthly and over
12 months; cohorts by first paid month. A start month, suggested when
most of the business appears at once (billing moved to Stripe), makes
those customers the base. Metrics page with a chart, the month table,
cohorts, and each month's customer moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 12:17:53 -07:00

548 lines
20 KiB
Go

// Package web is Supermarket's local web interface.
package web
import (
"embed"
"fmt"
"html/template"
"io/fs"
"log/slog"
"math"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/core"
"supermarket/internal/db"
"supermarket/internal/legacy"
"supermarket/internal/oauth"
"supermarket/internal/prospects"
"supermarket/internal/secrets"
"supermarket/internal/seo"
"supermarket/internal/signals"
)
//go:embed templates/*.html
var templateFS embed.FS
//go:embed static
var staticFS embed.FS
// Server holds what the handlers need.
type Server struct {
DB *db.DB
Secrets *secrets.Store
Core *core.Core // nil without a Core
DataDir string
PublicURL string // e.g. http://localhost:8470, for OAuth redirect URIs
Version string
MCPToken string
MCPSocket string // the MCP socket's path on the host, for Hermes' config
MCP http.Handler
Log *slog.Logger
// What the legacy import did at startup, or why it failed.
ImportStatus *legacy.Status
ImportErr error
pages map[string]*template.Template
mu sync.Mutex
pending map[string]*oauth.Pending // OAuth flows by state
// Reddit: an app-only token for reading rules before sign-in, and the
// account's recent posts for the warnings.
redditAppToken string
redditAppTokenExp time.Time
redditHist []reddit.Submission
redditHistAt time.Time
// sending lets one email go out at a time, from the queue or Send now.
sending sync.Mutex
}
// Handler builds the routes.
func (s *Server) Handler() (http.Handler, error) {
if err := s.loadTemplates(); err != nil {
return nil, err
}
s.pending = map[string]*oauth.Pending{}
mux := http.NewServeMux()
static, _ := fs.Sub(staticFS, "static")
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServerFS(static)))
// Browsers ask for /favicon.ico whatever the page says.
mux.HandleFunc("GET /favicon.ico", func(w http.ResponseWriter, r *http.Request) {
http.ServeFileFS(w, r, static, "favicon.ico")
})
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "ok") })
if s.MCP != nil {
mux.Handle("/mcp", s.MCP)
}
mux.HandleFunc("GET /{$}", s.dashboard)
mux.HandleFunc("GET /search", s.searchPage)
mux.HandleFunc("GET /inventory", s.inventoryList)
mux.HandleFunc("GET /inventory/new", s.inventoryEdit)
mux.HandleFunc("GET /inventory/{id}", s.inventoryEdit)
mux.HandleFunc("POST /inventory/save", s.inventorySave)
mux.HandleFunc("POST /inventory/fill", s.inventoryFill)
mux.HandleFunc("POST /inventory/{id}/delete", s.inventoryDelete)
mux.HandleFunc("GET /inventory/import", s.inventoryImportPage)
mux.HandleFunc("POST /inventory/import", s.inventoryImport)
mux.HandleFunc("GET /inventory/export", s.inventoryExport)
// Settings: the profile, social accounts, AI, and the Core & Hermes.
mux.HandleFunc("GET /settings", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/settings/profile", http.StatusSeeOther)
})
mux.HandleFunc("GET /settings/profile", s.profilePage)
mux.HandleFunc("POST /settings/profile", s.profileSave)
mux.HandleFunc("POST /settings/profile/draft", s.profileDraft)
mux.HandleFunc("GET /settings/ai", s.aiPage)
mux.HandleFunc("POST /settings/ai", s.aiSave)
mux.HandleFunc("POST /settings/ai/test", s.aiTest)
mux.HandleFunc("GET /settings/ai/models", s.aiModels)
mux.HandleFunc("GET /settings/accounts", s.accountsPage)
mux.HandleFunc("POST /settings/accounts", s.accountsSave)
mux.HandleFunc("POST /auth/{provider}/start", s.oauthStart)
mux.HandleFunc("GET /auth/{provider}/callback", s.oauthCallback)
mux.HandleFunc("GET /content", s.contentIndex)
mux.HandleFunc("GET /content/{id}", s.contentEntry)
mux.HandleFunc("POST /content/{id}/fetch", s.contentFetch)
mux.HandleFunc("POST /content/{id}/items", s.contentItems)
mux.HandleFunc("GET /content/scheduled", s.scheduledPage)
mux.HandleFunc("GET /content/published", s.publishedPage)
mux.HandleFunc("GET /posts", s.inboxPage)
// Posts was called the Inbox, and before that Drafts.
mux.HandleFunc("GET /inbox", func(w http.ResponseWriter, r *http.Request) {
redirect(w, r, "/posts", r.URL.Query().Get("msg"))
})
mux.HandleFunc("GET /drafts", func(w http.ResponseWriter, r *http.Request) {
redirect(w, r, "/posts", r.URL.Query().Get("msg"))
})
mux.HandleFunc("POST /drafts/{id}/{action}", s.draftAction)
mux.HandleFunc("POST /reddit/rules/{name}", s.refreshRules)
mux.HandleFunc("GET /prospects", s.prospectsPage)
mux.HandleFunc("GET /prospects/new", s.prospectForm)
mux.HandleFunc("POST /prospects/new", s.prospectAdd)
mux.HandleFunc("GET /prospects/suppressed", s.suppressedPage)
mux.HandleFunc("POST /prospects/suppressed", s.suppressedAction)
mux.HandleFunc("POST /prospects/verify", s.prospectsVerify)
mux.HandleFunc("POST /prospects/{kind}/{id}/{action}", s.prospectAction)
mux.HandleFunc("GET /signals", s.signalsPage)
mux.HandleFunc("GET /signals/new", s.signalPage)
mux.HandleFunc("POST /signals/new", s.signalSave)
mux.HandleFunc("POST /signals/campaigns", s.signalCampaign)
mux.HandleFunc("POST /lead-sources/{source}/import", s.importSource)
mux.HandleFunc("GET /signals/{id}", s.signalPage)
mux.HandleFunc("POST /signals/{id}", s.signalSave)
mux.HandleFunc("POST /signals/{id}/delete", s.signalDelete)
mux.HandleFunc("POST /signals/{id}/discover/{source}", s.signalDiscover)
mux.HandleFunc("GET /signals/{id}/runs", s.signalRuns)
mux.HandleFunc("POST /funnel/{id}/delete", s.funnelDelete)
mux.HandleFunc("GET /settings/sources", s.sourcesPage)
mux.HandleFunc("POST /settings/sources", s.sourcesSave)
mux.HandleFunc("POST /settings/sources/test/{source}", s.sourcesTest)
mux.HandleFunc("GET /settings/email", s.emailPage)
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("POST /metrics/start", s.metricsStart)
mux.HandleFunc("GET /metrics/month/{month}", s.metricsMonth)
mux.HandleFunc("GET /seo", s.seoPage)
mux.HandleFunc("GET /seo/check", s.seoCheckPage)
mux.HandleFunc("GET /seo/engines", s.seoEnginesPage)
mux.HandleFunc("POST /seo/engines/setup", s.seoEnginesSetup)
mux.HandleFunc("POST /seo/engines/ping", s.seoEnginesPing)
mux.HandleFunc("GET /seo/briefs", s.seoBriefsPage)
mux.HandleFunc("POST /seo/briefs", s.seoBriefNew)
mux.HandleFunc("GET /seo/briefs/{id}", s.seoBriefPage)
mux.HandleFunc("POST /seo/briefs/{id}/{action}", s.seoBriefAction)
mux.HandleFunc("GET /seo/keywords", s.seoKeywordsPage)
mux.HandleFunc("POST /seo/keywords", s.seoKeywordsFind)
mux.HandleFunc("POST /seo/keywords/{id}/{action}", s.seoKeywordAction)
mux.HandleFunc("GET /seo/changes", s.seoChangesPage)
mux.HandleFunc("POST /seo/changes/suggest", s.seoChangesSuggest)
mux.HandleFunc("POST /seo/changes/page", s.seoChangeForPage)
mux.HandleFunc("POST /seo/changes/{id}/{action}", s.seoChangeAction)
mux.HandleFunc("POST /settings/search/test/gitea", s.giteaTest)
mux.HandleFunc("GET /seo/audit", s.seoAuditPage)
mux.HandleFunc("POST /seo/audit", s.seoAuditRun)
mux.HandleFunc("GET /seo/audit/status", s.seoAuditStatus)
mux.HandleFunc("GET /seo/report", s.seoReportPage)
mux.HandleFunc("POST /seo/report", s.seoReportWrite)
mux.HandleFunc("GET /settings/search", s.searchSettingsPage)
mux.HandleFunc("POST /settings/search", s.searchSettingsSave)
mux.HandleFunc("POST /settings/search/sync", s.seoSync)
mux.HandleFunc("GET /settings/tracking", s.trackingPage)
mux.HandleFunc("POST /settings/tracking", s.trackingSave)
mux.HandleFunc("POST /settings/tracking/test/{source}", s.trackingTest)
mux.HandleFunc("POST /settings/tracking/run/{source}", s.trackingRun)
mux.HandleFunc("GET /outreach", s.outreachPage)
mux.HandleFunc("POST /outreach/draft", s.outreachDraft)
mux.HandleFunc("POST /outreach/draft-many", s.outreachDraftMany)
mux.HandleFunc("POST /outreach/check", s.outreachCheck)
mux.HandleFunc("POST /outreach/{id}/{action}", s.outreachAction)
mux.HandleFunc("GET /crm", s.crmPage)
mux.HandleFunc("GET /crm/reach", s.crmReach)
mux.HandleFunc("POST /crm/{action}", s.crmAction)
mux.HandleFunc("POST /crm/{id}/{action}", s.crmAction)
mux.HandleFunc("GET /settings/core", s.corePage)
mux.HandleFunc("GET /settings/core/checks", s.coreChecks)
// Where these pages used to be, for bookmarks.
for old, now := range map[string]string{
"/profile": "/settings/profile", "/core": "/settings/core", "/settings/credentials": "/settings/accounts",
} {
mux.HandleFunc("GET "+old, func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, now, http.StatusMovedPermanently)
})
}
return s.guard(mux), nil
}
// guard protects the app, which has no login because only this machine can
// reach it, from web pages open in the same browser:
// - DNS rebinding: a site whose name resolves to 127.0.0.1 would send its
// own Host header, so only local names are accepted.
// - Cross-site requests: a form on another site could POST here, so a
// browser request that changes something must come from this app's pages.
func (s *Server) guard(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !s.localHost(r.Host) {
http.Error(w, "Supermarket only answers at localhost.", http.StatusMisdirectedRequest)
return
}
if r.Method != http.MethodGet && r.Method != http.MethodHead && r.URL.Path != "/mcp" {
if !sameOrigin(r) {
http.Error(w, "Cross-site request refused.", http.StatusForbidden)
return
}
}
h := w.Header()
h.Set("X-Frame-Options", "DENY")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Referrer-Policy", "same-origin")
h.Set("Content-Security-Policy", "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; form-action 'self' https://twitter.com https://x.com https://www.linkedin.com https://www.reddit.com https://old.reddit.com https://accounts.google.com; frame-ancestors 'none'")
next.ServeHTTP(w, r)
})
}
func (s *Server) localHost(hostport string) bool {
host := hostport
if h, _, err := net.SplitHostPort(hostport); err == nil {
host = h
}
host = strings.Trim(strings.ToLower(host), "[]")
switch host {
case "localhost", "127.0.0.1", "::1":
return true
}
if u, err := url.Parse(s.PublicURL); err == nil && strings.EqualFold(u.Hostname(), host) {
return true
}
return false
}
func sameOrigin(r *http.Request) bool {
if origin := r.Header.Get("Origin"); origin != "" {
u, err := url.Parse(origin)
return err == nil && strings.EqualFold(u.Host, r.Host)
}
switch r.Header.Get("Sec-Fetch-Site") {
case "", "same-origin", "none":
return true // non-browser clients send neither header
}
return false
}
func (s *Server) loadTemplates() error {
funcs := template.FuncMap{
"lines": func(v []string) string { return strings.Join(v, "\n") },
"join": strings.Join,
"ago": ago,
"add": func(a, b int) int { return a + b },
"hasPrefix": strings.HasPrefix,
"sourceLabel": prospects.SourceLabel,
"has": func(list []string, v string) bool {
for _, x := range list {
if x == v {
return true
}
}
return false
},
// dict builds a map from key, value pairs, to pass several values
// to a template.
"dict": func(kv ...any) (map[string]any, error) {
if len(kv)%2 != 0 {
return nil, fmt.Errorf("dict: odd number of arguments")
}
m := make(map[string]any, len(kv)/2)
for i := 0; i < len(kv); i += 2 {
k, ok := kv[i].(string)
if !ok {
return nil, fmt.Errorf("dict: key %v isn't a string", kv[i])
}
m[k] = kv[i+1]
}
return m, nil
},
"xreserve": twitter.URLReserve,
// money shows cents as dollars: $1,234 or $12.50.
"money": money,
// usd shows float cents as whole dollars: $9,835.
"usd": func(cents float64) string { return money(int64(math.Round(cents/100)) * 100) },
"mul12": func(f float64) float64 { return 12 * f },
"sub": func(a, b float64) float64 { return a - b },
"pct": func(f float64) string {
if f < 0 {
return "·"
}
return strconv.FormatFloat(f, 'f', 0, 64) + "%"
},
"num": seo.Thousands,
"cls": func(x100 int) float64 { return float64(x100) / 100 },
"dec1": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) },
"pagePath": pagePath,
"stage": signals.StageLabel,
"channel": signals.ChannelLabel,
"truncate": func(n int, s string) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n-1]) + "…"
},
}
names, err := fs.Glob(templateFS, "templates/*.html")
if err != nil {
return err
}
s.pages = map[string]*template.Template{}
for _, name := range names {
base := strings.TrimSuffix(strings.TrimPrefix(name, "templates/"), ".html")
if base == "layout" {
continue
}
t, err := template.New("layout.html").Funcs(funcs).ParseFS(templateFS, "templates/layout.html", name)
if err != nil {
return fmt.Errorf("template %s: %w", name, err)
}
s.pages[base] = t
}
return nil
}
// page is what every template gets.
type page struct {
Title string
Nav string // which menu item is current: "home", "content/posts", "settings/ai"…
Version string
Flash string
Error string
Data any
Inbox int // drafts waiting for review, shown in the menu
Query string // the search box's text
NewProspects int // companies and people waiting for review, shown in the menu
Drafts int // outreach drafts waiting, shown in the menu
}
// Section is the top bar's first breadcrumb, from Nav.
func (p page) Section() string {
switch {
case p.Nav == "home":
return ""
case strings.HasPrefix(p.Nav, "content"):
return "Content"
case strings.HasPrefix(p.Nav, "prospects"):
return "Prospects"
case strings.HasPrefix(p.Nav, "settings"):
return "Settings"
case p.Nav == "inventory":
return "Inventory"
}
return ""
}
// Modules are the app's modules, in the menu and on the Overview. One
// without a Link isn't built yet.
type module struct {
ID, Name, Phase, Body, Link string
}
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", "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.", ""},
}
// Modules is for the menu.
func (p page) Modules() []module { return modules }
// render writes a full page, or only its "content" block for htmx requests
// that ask for a fragment.
func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, p page) {
t, ok := s.pages[name]
if !ok {
http.Error(w, "no template "+name, http.StatusInternalServerError)
return
}
p.Version = s.Version
p.Inbox = s.inboxCount()
p.NewProspects = s.newProspects()
p.Drafts = s.outreachDrafts()
if p.Flash == "" {
p.Flash = flashes[r.URL.Query().Get("msg")]
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := t.ExecuteTemplate(w, "layout.html", p); err != nil {
s.Log.Error("render", "page", name, "err", err)
}
}
// fragment writes one named template (for htmx swaps).
func (s *Server) fragment(w http.ResponseWriter, page, name string, data any) {
t, ok := s.pages[page]
if !ok {
http.Error(w, "no template "+page, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := t.ExecuteTemplate(w, name, data); err != nil {
s.Log.Error("render fragment", "page", page, "name", name, "err", err)
}
}
// Messages shown after a redirect, by code, so no user text is reflected.
var flashes = map[string]string{
"saved": "Saved.",
"deleted": "Deleted.",
"x-connected": "X is connected.",
"li-connected": "LinkedIn is connected.",
"google-connected": "Search Console is connected. Choose each website's property below, then sync.",
"synced": "Synced from Search Console.",
"report-written": "This week's report is written.",
"setup-opened": "Pull request opened: read it on Gitea, then merge it.",
"pinged": "Sent to IndexNow.",
"brief-written": "Brief written. Read it, answer its questions, then write the page.",
"page-written": "Page drafted. Read it, and confirm or remove every sentence that claims an experience.",
"keywords-found": "Looked for keywords: the candidates are below.",
"top-read": "Read the live top results.",
"proposed": "Proposed: read each one, edit it if you like, then say yes or no.",
"approved": "Approved: Supermarket is making the pull request; it shows here in a minute.",
"declined": "Declined.",
"auditing": "Auditing. It reads up to 300 pages politely, so it takes a few minutes; this page updates when it's done.",
"no-data": "There isn't two weeks of Search Console data yet.",
"reddit-connected": "Reddit is connected.",
"crm-test": "Test Lead queued. Hermes creates it on its next run; or run it now (below).",
"crm-sync": "Sync requested: Hermes copies CRM records on its next run.",
"accepted": "Accepted: queued for the CRM. Hermes adds it on its next run.",
"rejected": "Set aside.",
"reconsidered": "Back in New.",
"suppressed": "Added to the suppression list.",
"unsuppressed": "Taken off the suppression list.",
"prospect-added": "Added. Review it below.",
"outcome": "Outcome recorded.",
"discovering": "Searching. It takes a few minutes; new companies appear in Review, tagged with this signal.",
"rules-refreshed": "Rules refreshed.",
"imported": "Imported.",
"hunter-done": "Hunter.io search done: the result is on the card.",
"verified": "Checked with Hunter.io: the result is on each person.",
"drafted-outreach": "Drafted. Read it, edit it, then queue it to send.",
"queued": "Queued: it goes out in turn, within your sending hours.",
"unqueued": "Back in Drafts.",
"sent": "Sent.",
"marked-sent": "Marked as sent.",
"reply-recorded": "Reply recorded.",
"checked": "Inbox checked: what it found is above.",
"test-sent": "Test email sent: check your inbox.",
"oauth-expired": "That sign-in took too long or was already used. Try again.",
"dismissed": "Dismissed.",
"restored": "Restored.",
"drafted": "Drafts written. Review them below.",
"published": "Published.",
"discarded": "Discarded.",
"scheduled": "Scheduled.",
"posted": "Marked as posted: it's under Content → Published.",
"unscheduled": "Back in Posts: edit it, then publish or schedule it again.",
}
func redirect(w http.ResponseWriter, r *http.Request, path, msg string) {
if msg != "" {
// The message goes in the query, before any #fragment.
base, frag, hasFrag := strings.Cut(path, "#")
sep := "?"
if strings.Contains(base, "?") {
sep = "&"
}
path = base + sep + "msg=" + url.QueryEscape(msg)
if hasFrag {
path += "#" + frag
}
}
http.Redirect(w, r, path, http.StatusSeeOther)
}
func (s *Server) serverError(w http.ResponseWriter, err error) {
s.Log.Error("request failed", "err", err)
http.Error(w, "Something went wrong: "+err.Error(), http.StatusInternalServerError)
}
func money(cents int64) string {
neg := cents < 0
if neg {
cents = -cents
}
whole := strconv.FormatInt(cents/100, 10)
for i := len(whole) - 3; i > 0; i -= 3 {
whole = whole[:i] + "," + whole[i:]
}
out := "$" + whole
if c := cents % 100; c != 0 {
out += fmt.Sprintf(".%02d", c)
}
if neg {
out = "-" + out
}
return out
}
func ago(t time.Time) string {
if t.IsZero() {
return "never"
}
d := time.Since(t)
switch {
case d < time.Minute:
return "just now"
case d < time.Hour:
return fmt.Sprintf("%d min ago", int(d.Minutes()))
case d < 48*time.Hour:
return fmt.Sprintf("%d h ago", int(d.Hours()))
default:
return t.Local().Format("2 Jan 2006")
}
}