Schema 7 adds signals (hypothesis, how to spot it, angle, status, utm slug), funnel_events (stage, channel, subject, campaign, source, deduped by external ID) and outside_campaigns. Prospects -> Signals is the scorecard: each signal's funnel from found to paid, people once per stage, with revenue and outside spend, by period and channel. Each signal's page shows its funnel by channel, its campaigns and its latest steps. Prospects carry a signal (filter, change, "found" recorded) and outcomes can be recorded by hand. Settings -> Lead sources holds origami.chat and explee.com API keys. Every 6 hours (or Import now) Supermarket reads their campaigns, numbers and spend, contacted people, replies and hot leads, read-only: interested people and repliers become prospects, unsubscribes are suppressed, and each campaign is assigned to a signal. The explee.com client follows its OpenAPI schema; origami.chat's responses are undocumented, so its client reads fields loosely and its Test shows the real response. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
441 lines
15 KiB
Go
441 lines
15 KiB
Go
// Package web is Supermarket's local web interface.
|
|
package web
|
|
|
|
import (
|
|
"embed"
|
|
"fmt"
|
|
"html/template"
|
|
"io/fs"
|
|
"log/slog"
|
|
"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/secrets"
|
|
"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
|
|
}
|
|
|
|
// 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/{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 /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 /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; 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,
|
|
// 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,
|
|
"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
|
|
}
|
|
|
|
// 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", "Audit your websites and open fixes as pull requests on your Hugo repositories.", ""},
|
|
{"metrics", "Metrics", "Phase 4", "Pipeline influence, CAC, CLV and NRR from Stripe, EspoCRM and Plausible.", ""},
|
|
{"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()
|
|
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.",
|
|
"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.",
|
|
"rules-refreshed": "Rules refreshed.",
|
|
"imported": "Imported.",
|
|
"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 != "" {
|
|
sep := "?"
|
|
if strings.Contains(path, "?") {
|
|
sep = "&"
|
|
}
|
|
path += sep + "msg=" + url.QueryEscape(msg)
|
|
}
|
|
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")
|
|
}
|
|
}
|