Files
supermarket/internal/web/server.go
T
davidandClaude Opus 5.5 c36f786ae9 Fixes from the first round of TEST.md
SEO: a domain property (sc-domain:) covers every subdomain, so the shop,
Gitea and forum were counted as the website. What ranks, the morning
check, the Monday report, keywords, change candidates and the audit's
traffic now read only the website's own host (with or without www).
The report keeps pages worth a proposal apart from "Waiting for your
yes", explains only moves past the thresholds, and says "places up/down".

Also:
- Feed summaries drop the posts' scripts and styles.
- Spend you log can't be negative.
- Test and check buttons can't be clicked twice while they run.
- Previews show the site's web fonts and icon sprites.
- Backups are read without leaving -wal/-shm files; deleting one removes
  them, and leftovers are swept at start.
- The Overview's setup flags a CRM that Hermes can't reach.
- Import now says what came in; adding a prospect that exists says so;
  prospects can be deleted.
- Signal tags and brief addresses keep accented letters (Ü → u).
- Page errors start with a capital; clearer messages for bad uploads,
  CRM retry and cancel, keywords, and the finished audit.
- The module you're in stays unfolded in the sidebar.
- A picked keyword can be unpicked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 06:31:42 -07:00

673 lines
26 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"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/core"
"supermarket/internal/db"
"supermarket/internal/legacy"
"supermarket/internal/metrics"
"supermarket/internal/oauth"
"supermarket/internal/prospects"
"supermarket/internal/secrets"
"supermarket/internal/seo"
"supermarket/internal/signals"
"supermarket/internal/sites"
)
//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
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
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 /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("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/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/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
}
// 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,
"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"
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.", "/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 from your website's own sections, preview them, and publish them as pull requests on Gitea.", "/sites"},
}
// 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 = flashText(r.URL.Query())
}
p.Error = sentence(p.Error)
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.",
"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.",
"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")
}
}