Files
supermarket/internal/web/server.go
T
davidandClaude Opus 5.5 a4dd36f5a4 Phase 10, part 6: Settings → Connections, with who connected each
Admins see every service Supermarket uses, whether it's connected,
failing or not set up, when it was last tested (every Test button now
records its result), and who connected or removed it and when. Keys and
sign-ins saved from the settings pages record the person; refreshed
tokens don't.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:15:43 -07:00

856 lines
33 KiB
Go

// Package web is Supermarket's local web interface.
package web
import (
"bytes"
"context"
"embed"
"fmt"
"html/template"
"io/fs"
"log/slog"
"math"
"net"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"supermarket/internal/config"
"supermarket/internal/jobs"
"supermarket/internal/storage"
"sync"
"sync/atomic"
"time"
"unicode"
"unicode/utf8"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/appmail"
"supermarket/internal/core"
"supermarket/internal/db"
"supermarket/internal/legacy"
"supermarket/internal/metrics"
"supermarket/internal/prospects"
"supermarket/internal/secrets"
"supermarket/internal/seo"
"supermarket/internal/signals"
"supermarket/internal/sites"
"supermarket/internal/tracking"
)
//go:embed templates/*.html
var templateFS embed.FS
//go:embed static
var staticFS embed.FS
// Server holds what the handlers need.
type Server struct {
Config *config.Config // how it's run; nil in tests: the local edition
DB *db.DB
Secrets *secrets.Store
Core *core.Core // nil without a Core
DataDir string
Files storage.Store // exports and uploads: a folder or S3; nil in tests
Jobs *jobs.Runner // this copy of the app, for locks shared with others; made on first use in tests
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
Mail appmail.Sender // the app's own mail (invitations, resets); nil on local
Restart func() // stops the app so Docker starts it again; nil in tests
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
jobsOnce sync.Once
setupDone atomic.Bool // the team has its owner (server edition)
// 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
}
// jobs is this copy of the app, for the locks it shares with the others.
func (s *Server) jobs() *jobs.Runner {
s.jobsOnce.Do(func() {
if s.Jobs == nil {
r, err := jobs.New(s.DB, s.Version, s.Log)
if err != nil {
panic(fmt.Sprintf("jobs: %v", err)) // only without a Runner from main: tests
}
s.Jobs = r
}
})
return s.Jobs
}
// alone says whether no other copy of the app is running: only then is
// work marked "running" really interrupted, and safe to mark so.
func (s *Server) alone() bool {
ok, err := s.jobs().Alone()
if err != nil {
s.Log.Warn("jobs: looking for other copies", "err", err)
return false
}
return ok
}
// jobDo runs one turn of a background job under its lock, job:<name>:
// with several copies of the app, one of them does it.
func (s *Server) jobDo(ctx context.Context, name string, fn func(context.Context)) {
if _, err := s.jobs().Do(ctx, "job:"+name, fn); err != nil {
s.Log.Warn("jobs: taking the lock", "job", name, "err", err)
}
}
// sendLock is held while an email goes out, from the queue or Send now:
// one at a time, across every copy of the app.
const sendLock = "outreach:send"
// Handler builds the routes.
func (s *Server) Handler() (http.Handler, error) {
if err := s.loadTemplates(); err != nil {
return nil, err
}
mux := &routes{s: s, 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)
// Signing in (the server edition).
mux.HandleFunc("GET /setup/{token}", s.setupPage)
mux.HandleFunc("POST /setup/{token}", s.setupSave)
mux.HandleFunc("GET /signin", s.signinPage)
mux.HandleFunc("POST /signin", s.signin)
mux.HandleFunc("POST /signin/code", s.signinCode)
mux.HandleFunc("POST /signout", s.signout)
mux.HandleFunc("GET /forgot", s.forgotPage)
mux.HandleFunc("POST /forgot", s.forgot)
mux.HandleFunc("GET /reset/{token}", s.resetPage)
mux.HandleFunc("POST /reset/{token}", s.reset)
mux.HandleFunc("GET /settings/account", s.accountPage)
mux.HandleFunc("POST /settings/account/profile", s.accountProfile)
mux.HandleFunc("POST /settings/account/password", s.accountPassword)
mux.HandleFunc("POST /settings/account/sessions/end-others", s.accountEndOthers)
mux.HandleFunc("POST /settings/account/sessions/{id}/end", s.accountEndSession)
mux.HandleFunc("GET /settings/account/two-factor", s.twoFactorPage)
mux.HandleFunc("POST /settings/account/two-factor", s.twoFactorOn)
mux.HandleFunc("POST /settings/account/two-factor/off", s.twoFactorOff)
mux.HandleFunc("POST /settings/account/recovery-codes", s.recoveryCodes)
mux.HandleFunc("POST /settings/account/photo", s.accountPhoto)
mux.HandleFunc("GET /users/{id}/photo", s.userPhoto)
mux.HandleFunc("GET /settings/users", s.usersPage)
mux.HandleFunc("POST /settings/users", s.userInvite)
mux.HandleFunc("GET /settings/users/{id}", s.userPage)
mux.HandleFunc("POST /settings/users/{id}/{action}", s.userAction)
mux.HandleFunc("GET /invite/{token}", s.invitePage)
mux.HandleFunc("POST /invite/{token}", s.inviteAccept)
mux.HandleFunc("GET /search", s.searchPage)
mux.HandleFunc("GET /market", s.inventoryList)
mux.HandleFunc("GET /market/new", s.inventoryEdit)
mux.HandleFunc("GET /market/{id}", s.inventoryEdit)
mux.HandleFunc("POST /market/save", s.inventorySave)
mux.HandleFunc("POST /market/fill", s.inventoryFill)
mux.HandleFunc("POST /market/{id}/delete", s.inventoryDelete)
mux.HandleFunc("GET /market/import", s.inventoryImportPage)
mux.HandleFunc("POST /market/import", s.inventoryImport)
mux.HandleFunc("GET /market/export", s.inventoryExport)
// The Market was the Inventory: its old addresses lead to the new ones
// (308 keeps a form's POST a POST).
mux.HandleFunc("/inventory", marketMoved)
mux.HandleFunc("/inventory/", marketMoved)
// Settings: the profile, social accounts, AI, and the Core & Hermes.
mux.HandleFunc("GET /settings", func(w http.ResponseWriter, r *http.Request) {
if !viewerOf(r).Member.Admin() {
http.Redirect(w, r, "/settings/account", http.StatusSeeOther)
return
}
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 /settings/accounts/linkedin-page", s.linkedInPageSave)
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 /metrics/customers", s.metricsCustomers)
mux.HandleFunc("GET /metrics/spend", s.metricsSpend)
mux.HandleFunc("GET /metrics/clv", s.metricsCLV)
mux.HandleFunc("GET /metrics/export/{name}", s.metricsExport)
mux.HandleFunc("GET /metrics/publish", s.metricsPublishPage)
mux.HandleFunc("POST /metrics/publish", s.metricsPublish)
mux.HandleFunc("POST /metrics/spend", s.metricsSpendAdd)
mux.HandleFunc("POST /metrics/spend/{id}/delete", s.metricsSpendDelete)
mux.HandleFunc("POST /metrics/customers/{id}", s.metricsCustomerMatch)
mux.HandleFunc("GET /sites", s.sitesPage)
mux.HandleFunc("POST /sites/sync", s.sitesSync)
mux.HandleFunc("GET /sites/pages", s.sitePagesPage)
mux.HandleFunc("POST /sites/pages", s.sitePageNew)
mux.HandleFunc("GET /sites/pages/{id}", s.sitePagePage)
mux.HandleFunc("POST /sites/pages/{id}/{action}", s.sitePageAction)
mux.HandleFunc("GET /sites/publishing", s.sitesPublishingPage)
mux.HandleFunc("POST /sites/theme/update", s.sitesThemeUpdate)
mux.HandleFunc("GET /sites/new", s.newSitePage)
mux.HandleFunc("POST /sites/new", s.newSiteCreate)
mux.HandleFunc("GET /sites/forms", s.sitesFormsPage)
mux.HandleFunc("POST /sites/forms/{action}", s.sitesFormsAction)
mux.HandleFunc("GET /sites/previews", s.sitesPreviewsPage)
mux.HandleFunc("POST /sites/previews/build", s.sitesPreviewBuild)
mux.HandleFunc("POST /sites/previews/delete", s.sitesPreviewDelete)
mux.HandleFunc("GET /preview/{site}/{slug}/{path...}", s.previewServe)
mux.HandleFunc("GET /preview/{site}/{slug}", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, r.URL.Path+"/", http.StatusMovedPermanently)
})
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("GET /seo/next", s.seoNextPage)
mux.HandleFunc("POST /settings/email/listmonk", s.listmonkSave)
mux.HandleFunc("POST /settings/email/listmonk/test", s.listmonkTest)
mux.HandleFunc("POST /settings/email/listmonk/sync", s.listmonkSync)
mux.HandleFunc("GET /seo/links", s.seoLinksPage)
mux.HandleFunc("POST /seo/links/bing", s.seoLinksBing)
mux.HandleFunc("POST /seo/links/{action}", s.seoLinksAction)
mux.HandleFunc("GET /sites/pages/add", s.sitesAddPage)
mux.HandleFunc("POST /sites/pages/add", s.sitesAdd)
mux.HandleFunc("POST /seo/next/dismiss", s.seoNextDismiss)
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/signups", s.trackingSignups)
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/backups", s.backupsPage)
mux.HandleFunc("POST /settings/backups/{action}", s.backupsAction)
mux.HandleFunc("GET /settings/backups/file/{name}", s.backupDownload)
mux.HandleFunc("POST /settings/backups/upload", s.backupUpload)
mux.HandleFunc("GET /settings/about", s.aboutPage)
mux.HandleFunc("GET /settings/connections", s.connectionsPage)
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)
})
}
if err := mux.err(); err != nil {
return nil, err
}
return s.guard(s.csrf(s.sessions(mux.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
}
// humanBytes is a file size for people: "840 KB", "12.3 MB".
func humanBytes(n int64) string {
switch {
case n >= 1<<30:
return fmt.Sprintf("%.1f GB", float64(n)/(1<<30))
case n >= 1<<20:
return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))
case n >= 1<<10:
return fmt.Sprintf("%d KB", n>>10)
}
return fmt.Sprintf("%d bytes", n)
}
var backticks = regexp.MustCompile("`([^`]+)`")
// ticks shows Markdown's `code` spans as code, the rest as plain text.
func ticks(s string) template.HTML {
return template.HTML(backticks.ReplaceAllString(template.HTMLEscapeString(s), "<code>$1</code>"))
}
func (s *Server) loadTemplates() error {
funcs := template.FuncMap{
"lines": func(v []string) string { return strings.Join(v, "\n") },
"join": strings.Join,
"ago": ago,
"ticks": ticks,
"bytes": humanBytes,
"kindLabel": sites.KindLabel,
"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) + "%"
},
"spendChannel": metrics.ChannelName,
"dec1f": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) },
"cents": func(f float64) string {
if f < 0 {
return "·"
}
return money(int64(math.Round(f)))
},
"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,
"change": seo.Percent,
"inc": func(i int) int { return i + 1 },
// statusesFor are the moves an opportunity can make next.
"statusesFor": func(status string) []string {
switch status {
case "open":
return []string{"asked", "dismissed"}
case "asked":
return []string{"won", "dismissed"}
case "dismissed", "won":
return []string{"open"}
}
return nil
},
"flagOf": func(m map[string]string, page string) string { return m[seo.PathKey(page)] },
"conv": func(m map[string]tracking.PageNumbers, page string) tracking.PageNumbers {
return m[tracking.PathOf(page)]
},
"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
Bare bool // no sidebar: pages before signing in
CSRF string // the form token, for htmx (app.js)
Viewer *viewer // who's looking
}
// 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 "Market"
case strings.HasPrefix(p.Nav, "sites"):
return "Sites"
}
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.", "/posts"},
{"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/check"},
{"sites", "Sites", "Phase 5", "Build pages from your website's own sections, preview them, and publish them as pull requests on Gitea.", "/sites"},
{"metrics", "Metrics", "Phase 4", "MRR, NRR, CAC and CLV from Stripe, with pipeline influence from EspoCRM.", "/metrics"},
}
// Modules is for the menu: the viewer's.
func (p page) Modules() []module { return visibleModules(p.Viewer) }
// visibleModules are the modules a viewer may see.
func visibleModules(v *viewer) []module {
if v == nil {
return modules
}
out := make([]module, 0, len(modules))
for _, m := range modules {
if v.can(m.ID, false) {
out = append(out, m)
}
}
return out
}
// Can is for templates: whether the viewer may see an area.
func (p page) Can(area string) bool { return p.Viewer == nil || p.Viewer.can(area, false) }
// 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
if !p.Bare {
p.Inbox = s.inboxCount()
p.NewProspects = s.newProspects()
p.Drafts = s.outreachDrafts()
}
if p.Flash == "" {
p.Flash = flashText(r.URL.Query())
}
p.Error = sentence(p.Error)
p.CSRF = csrfToken(r)
p.Viewer = viewerOf(r)
out, err := withCSRF(r, func(b *bytes.Buffer) error { return t.ExecuteTemplate(b, "layout.html", p) })
if err != nil {
s.Log.Error("render", "page", name, "err", err)
http.Error(w, "The page couldn't be shown: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(out)
}
// fragment writes one named template (for htmx swaps).
func (s *Server) fragment(w http.ResponseWriter, r *http.Request, page, name string, data any) {
t, ok := s.pages[page]
if !ok {
http.Error(w, "no template "+page, http.StatusInternalServerError)
return
}
out, err := withCSRF(r, func(b *bytes.Buffer) error { return t.ExecuteTemplate(b, name, data) })
if err != nil {
s.Log.Error("render fragment", "page", page, "name", name, "err", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(out)
}
// Messages shown after a redirect, by code, so no user text is reflected.
var flashes = map[string]string{
"saved": "Saved.",
"welcome": "Welcome: you're the owner. Start with the company's profile.",
"signed-out": "Signed out.",
"password-reset": "Your new password is saved: sign in with it.",
"password-changed": "Password changed. You're signed out everywhere else.",
"session-ended": "Signed out there.",
"sessions-ended": "Signed out everywhere else.",
"two-factor-off": "Two-factor sign-in is off.",
"codes-low": "You're running out of recovery codes: make new ones below.",
"invited": "Invitation sent.",
"withdrawn": "Invitation withdrawn.",
"disabled": "The account is turned off, and signed out.",
"enabled": "The account is back on.",
"unlocked": "Unlocked.",
"two-factor-reset": "Two-factor sign-in is reset: they sign in with their password, then can turn it on again.",
"signed-out-user": "Signed out everywhere.",
"removed": "Removed.",
"joined": "Welcome to Supermarket.",
"deleted": "Deleted.",
"x-connected": "X is connected.",
"li-connected": "LinkedIn is connected.",
"site-created": "The site is started: its first commit is on Gitea. Build its first pages below.",
"li-page-connected": "The LinkedIn page app 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.",
"keyword-picked": "Picked. Write its brief when you're ready.",
"keyword-dismissed": "Dismissed: it's under Dismissed if you change your mind.",
"keyword-back": "Back among the candidates.",
"signups-saved": "Saved. The pages' sign-ups were read again with it.",
"next-dismissed": "Hidden for 90 days.",
"link-added": "Added, and checked.",
"links-checked": "Checked %d links.",
"link-forgotten": "Forgotten.",
"partners-read": "Looked at the partners' pages: %d new places to ask for a link.",
"alternatives-read": "Searched: %d new lists that leave you out.",
"optouts-synced": "Synced: %d new on the suppression list.",
"listed": "Added to the mailing list.",
"bing-read": "Read the links from Bing.",
"audited": "The audit is done.",
"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.",
"crm-retried": "Queued again: Hermes tries it on its next run.",
"crm-cancelled": "Taken back: Hermes won't do it.",
"prospect-exists": "Already there: nothing new was added. It's in the list 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.",
"imported-counts": "Imported: %d new steps in the funnel, %d new people to review, %d new on the suppression list.",
"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.",
}
// sentence starts a message with a capital letter: errors from deeper
// down are written in lower case, to be wrapped.
func sentence(msg string) string {
r, n := utf8.DecodeRuneInString(msg)
if n == 0 || !unicode.IsLower(r) {
return msg
}
return string(unicode.ToUpper(r)) + msg[n:]
}
// flashText is the message a redirect asked for (?msg=), from the fixed
// list. A message with %d verbs takes its numbers from n1, n2… (digits
// only), so nothing but a number can be put into it from the address.
func flashText(q url.Values) string {
msg := flashes[q.Get("msg")]
if n := strings.Count(msg, "%d"); n > 0 {
args := make([]any, n)
for i := range args {
v, _ := strconv.Atoi(q.Get("n" + strconv.Itoa(i+1)))
args[i] = v
}
msg = fmt.Sprintf(msg, args...)
}
return msg
}
// redirectCounts redirects with a message that has numbers in it.
func redirectCounts(w http.ResponseWriter, r *http.Request, path, msg string, counts ...int) {
base, frag, hasFrag := strings.Cut(path, "#")
for i, c := range counts {
sep := "?"
if strings.Contains(base, "?") {
sep = "&"
}
base += sep + "n" + strconv.Itoa(i+1) + "=" + strconv.Itoa(c)
}
if hasFrag {
base += "#" + frag
}
redirect(w, r, base, msg)
}
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")
}
}
// marketMoved sends an old /inventory address to its /market one.
func marketMoved(w http.ResponseWriter, r *http.Request) {
u := *r.URL
u.Path = "/market" + strings.TrimPrefix(r.URL.Path, "/inventory")
http.Redirect(w, r, u.RequestURI(), http.StatusPermanentRedirect)
}